sqlite3.c 7.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805146806146807146808146809146810146811146812146813146814146815146816146817146818146819146820146821146822146823146824146825146826146827146828146829146830146831146832146833146834146835146836146837146838146839146840146841146842146843146844146845146846146847146848146849146850146851146852146853146854146855146856146857146858146859146860146861146862146863146864146865146866146867146868146869146870146871146872146873146874146875146876146877146878146879146880146881146882146883146884146885146886146887146888146889146890146891146892146893146894146895146896146897146898146899146900146901146902146903146904146905146906146907146908146909146910146911146912146913146914146915146916146917146918146919146920146921146922146923146924146925146926146927146928146929146930146931146932146933146934146935146936146937146938146939146940146941146942146943146944146945146946146947146948146949146950146951146952146953146954146955146956146957146958146959146960146961146962146963146964146965146966146967146968146969146970146971146972146973146974146975146976146977146978146979146980146981146982146983146984146985146986146987146988146989146990146991146992146993146994146995146996146997146998146999147000147001147002147003147004147005147006147007147008147009147010147011147012147013147014147015147016147017147018147019147020147021147022147023147024147025147026147027147028147029147030147031147032147033147034147035147036147037147038147039147040147041147042147043147044147045147046147047147048147049147050147051147052147053147054147055147056147057147058147059147060147061147062147063147064147065147066147067147068147069147070147071147072147073147074147075147076147077147078147079147080147081147082147083147084147085147086147087147088147089147090147091147092147093147094147095147096147097147098147099147100147101147102147103147104147105147106147107147108147109147110147111147112147113147114147115147116147117147118147119147120147121147122147123147124147125147126147127147128147129147130147131147132147133147134147135147136147137147138147139147140147141147142147143147144147145147146147147147148147149147150147151147152147153147154147155147156147157147158147159147160147161147162147163147164147165147166147167147168147169147170147171147172147173147174147175147176147177147178147179147180147181147182147183147184147185147186147187147188147189147190147191147192147193147194147195147196147197147198147199147200147201147202147203147204147205147206147207147208147209147210147211147212147213147214147215147216147217147218147219147220147221147222147223147224147225147226147227147228147229147230147231147232147233147234147235147236147237147238147239147240147241147242147243147244147245147246147247147248147249147250147251147252147253147254147255147256147257147258147259147260147261147262147263147264147265147266147267147268147269147270147271147272147273147274147275147276147277147278147279147280147281147282147283147284147285147286147287147288147289147290147291147292147293147294147295147296147297147298147299147300147301147302147303147304147305147306147307147308147309147310147311147312147313147314147315147316147317147318147319147320147321147322147323147324147325147326147327147328147329147330147331147332147333147334147335147336147337147338147339147340147341147342147343147344147345147346147347147348147349147350147351147352147353147354147355147356147357147358147359147360147361147362147363147364147365147366147367147368147369147370147371147372147373147374147375147376147377147378147379147380147381147382147383147384147385147386147387147388147389147390147391147392147393147394147395147396147397147398147399147400147401147402147403147404147405147406147407147408147409147410147411147412147413147414147415147416147417147418147419147420147421147422147423147424147425147426147427147428147429147430147431147432147433147434147435147436147437147438147439147440147441147442147443147444147445147446147447147448147449147450147451147452147453147454147455147456147457147458147459147460147461147462147463147464147465147466147467147468147469147470147471147472147473147474147475147476147477147478147479147480147481147482147483147484147485147486147487147488147489147490147491147492147493147494147495147496147497147498147499147500147501147502147503147504147505147506147507147508147509147510147511147512147513147514147515147516147517147518147519147520147521147522147523147524147525147526147527147528147529147530147531147532147533147534147535147536147537147538147539147540147541147542147543147544147545147546147547147548147549147550147551147552147553147554147555147556147557147558147559147560147561147562147563147564147565147566147567147568147569147570147571147572147573147574147575147576147577147578147579147580147581147582147583147584147585147586147587147588147589147590147591147592147593147594147595147596147597147598147599147600147601147602147603147604147605147606147607147608147609147610147611147612147613147614147615147616147617147618147619147620147621147622147623147624147625147626147627147628147629147630147631147632147633147634147635147636147637147638147639147640147641147642147643147644147645147646147647147648147649147650147651147652147653147654147655147656147657147658147659147660147661147662147663147664147665147666147667147668147669147670147671147672147673147674147675147676147677147678147679147680147681147682147683147684147685147686147687147688147689147690147691147692147693147694147695147696147697147698147699147700147701147702147703147704147705147706147707147708147709147710147711147712147713147714147715147716147717147718147719147720147721147722147723147724147725147726147727147728147729147730147731147732147733147734147735147736147737147738147739147740147741147742147743147744147745147746147747147748147749147750147751147752147753147754147755147756147757147758147759147760147761147762147763147764147765147766147767147768147769147770147771147772147773147774147775147776147777147778147779147780147781147782147783147784147785147786147787147788147789147790147791147792147793147794147795147796147797147798147799147800147801147802147803147804147805147806147807147808147809147810147811147812147813147814147815147816147817147818147819147820147821147822147823147824147825147826147827147828147829147830147831147832147833147834147835147836147837147838147839147840147841147842147843147844147845147846147847147848147849147850147851147852147853147854147855147856147857147858147859147860147861147862147863147864147865147866147867147868147869147870147871147872147873147874147875147876147877147878147879147880147881147882147883147884147885147886147887147888147889147890147891147892147893147894147895147896147897147898147899147900147901147902147903147904147905147906147907147908147909147910147911147912147913147914147915147916147917147918147919147920147921147922147923147924147925147926147927147928147929147930147931147932147933147934147935147936147937147938147939147940147941147942147943147944147945147946147947147948147949147950147951147952147953147954147955147956147957147958147959147960147961147962147963147964147965147966147967147968147969147970147971147972147973147974147975147976147977147978147979147980147981147982147983147984147985147986147987147988147989147990147991147992147993147994147995147996147997147998147999148000148001148002148003148004148005148006148007148008148009148010148011148012148013148014148015148016148017148018148019148020148021148022148023148024148025148026148027148028148029148030148031148032148033148034148035148036148037148038148039148040148041148042148043148044148045148046148047148048148049148050148051148052148053148054148055148056148057148058148059148060148061148062148063148064148065148066148067148068148069148070148071148072148073148074148075148076148077148078148079148080148081148082148083148084148085148086148087148088148089148090148091148092148093148094148095148096148097148098148099148100148101148102148103148104148105148106148107148108148109148110148111148112148113148114148115148116148117148118148119148120148121148122148123148124148125148126148127148128148129148130148131148132148133148134148135148136148137148138148139148140148141148142148143148144148145148146148147148148148149148150148151148152148153148154148155148156148157148158148159148160148161148162148163148164148165148166148167148168148169148170148171148172148173148174148175148176148177148178148179148180148181148182148183148184148185148186148187148188148189148190148191148192148193148194148195148196148197148198148199148200148201148202148203148204148205148206148207148208148209148210148211148212148213148214148215148216148217148218148219148220148221148222148223148224148225148226148227148228148229148230148231148232148233148234148235148236148237148238148239148240148241148242148243148244148245148246148247148248148249148250148251148252148253148254148255148256148257148258148259148260148261148262148263148264148265148266148267148268148269148270148271148272148273148274148275148276148277148278148279148280148281148282148283148284148285148286148287148288148289148290148291148292148293148294148295148296148297148298148299148300148301148302148303148304148305148306148307148308148309148310148311148312148313148314148315148316148317148318148319148320148321148322148323148324148325148326148327148328148329148330148331148332148333148334148335148336148337148338148339148340148341148342148343148344148345148346148347148348148349148350148351148352148353148354148355148356148357148358148359148360148361148362148363148364148365148366148367148368148369148370148371148372148373148374148375148376148377148378148379148380148381148382148383148384148385148386148387148388148389148390148391148392148393148394148395148396148397148398148399148400148401148402148403148404148405148406148407148408148409148410148411148412148413148414148415148416148417148418148419148420148421148422148423148424148425148426148427148428148429148430148431148432148433148434148435148436148437148438148439148440148441148442148443148444148445148446148447148448148449148450148451148452148453148454148455148456148457148458148459148460148461148462148463148464148465148466148467148468148469148470148471148472148473148474148475148476148477148478148479148480148481148482148483148484148485148486148487148488148489148490148491148492148493148494148495148496148497148498148499148500148501148502148503148504148505148506148507148508148509148510148511148512148513148514148515148516148517148518148519148520148521148522148523148524148525148526148527148528148529148530148531148532148533148534148535148536148537148538148539148540148541148542148543148544148545148546148547148548148549148550148551148552148553148554148555148556148557148558148559148560148561148562148563148564148565148566148567148568148569148570148571148572148573148574148575148576148577148578148579148580148581148582148583148584148585148586148587148588148589148590148591148592148593148594148595148596148597148598148599148600148601148602148603148604148605148606148607148608148609148610148611148612148613148614148615148616148617148618148619148620148621148622148623148624148625148626148627148628148629148630148631148632148633148634148635148636148637148638148639148640148641148642148643148644148645148646148647148648148649148650148651148652148653148654148655148656148657148658148659148660148661148662148663148664148665148666148667148668148669148670148671148672148673148674148675148676148677148678148679148680148681148682148683148684148685148686148687148688148689148690148691148692148693148694148695148696148697148698148699148700148701148702148703148704148705148706148707148708148709148710148711148712148713148714148715148716148717148718148719148720148721148722148723148724148725148726148727148728148729148730148731148732148733148734148735148736148737148738148739148740148741148742148743148744148745148746148747148748148749148750148751148752148753148754148755148756148757148758148759148760148761148762148763148764148765148766148767148768148769148770148771148772148773148774148775148776148777148778148779148780148781148782148783148784148785148786148787148788148789148790148791148792148793148794148795148796148797148798148799148800148801148802148803148804148805148806148807148808148809148810148811148812148813148814148815148816148817148818148819148820148821148822148823148824148825148826148827148828148829148830148831148832148833148834148835148836148837148838148839148840148841148842148843148844148845148846148847148848148849148850148851148852148853148854148855148856148857148858148859148860148861148862148863148864148865148866148867148868148869148870148871148872148873148874148875148876148877148878148879148880148881148882148883148884148885148886148887148888148889148890148891148892148893148894148895148896148897148898148899148900148901148902148903148904148905148906148907148908148909148910148911148912148913148914148915148916148917148918148919148920148921148922148923148924148925148926148927148928148929148930148931148932148933148934148935148936148937148938148939148940148941148942148943148944148945148946148947148948148949148950148951148952148953148954148955148956148957148958148959148960148961148962148963148964148965148966148967148968148969148970148971148972148973148974148975148976148977148978148979148980148981148982148983148984148985148986148987148988148989148990148991148992148993148994148995148996148997148998148999149000149001149002149003149004149005149006149007149008149009149010149011149012149013149014149015149016149017149018149019149020149021149022149023149024149025149026149027149028149029149030149031149032149033149034149035149036149037149038149039149040149041149042149043149044149045149046149047149048149049149050149051149052149053149054149055149056149057149058149059149060149061149062149063149064149065149066149067149068149069149070149071149072149073149074149075149076149077149078149079149080149081149082149083149084149085149086149087149088149089149090149091149092149093149094149095149096149097149098149099149100149101149102149103149104149105149106149107149108149109149110149111149112149113149114149115149116149117149118149119149120149121149122149123149124149125149126149127149128149129149130149131149132149133149134149135149136149137149138149139149140149141149142149143149144149145149146149147149148149149149150149151149152149153149154149155149156149157149158149159149160149161149162149163149164149165149166149167149168149169149170149171149172149173149174149175149176149177149178149179149180149181149182149183149184149185149186149187149188149189149190149191149192149193149194149195149196149197149198149199149200149201149202149203149204149205149206149207149208149209149210149211149212149213149214149215149216149217149218149219149220149221149222149223149224149225149226149227149228149229149230149231149232149233149234149235149236149237149238149239149240149241149242149243149244149245149246149247149248149249149250149251149252149253149254149255149256149257149258149259149260149261149262149263149264149265149266149267149268149269149270149271149272149273149274149275149276149277149278149279149280149281149282149283149284149285149286149287149288149289149290149291149292149293149294149295149296149297149298149299149300149301149302149303149304149305149306149307149308149309149310149311149312149313149314149315149316149317149318149319149320149321149322149323149324149325149326149327149328149329149330149331149332149333149334149335149336149337149338149339149340149341149342149343149344149345149346149347149348149349149350149351149352149353149354149355149356149357149358149359149360149361149362149363149364149365149366149367149368149369149370149371149372149373149374149375149376149377149378149379149380149381149382149383149384149385149386149387149388149389149390149391149392149393149394149395149396149397149398149399149400149401149402149403149404149405149406149407149408149409149410149411149412149413149414149415149416149417149418149419149420149421149422149423149424149425149426149427149428149429149430149431149432149433149434149435149436149437149438149439149440149441149442149443149444149445149446149447149448149449149450149451149452149453149454149455149456149457149458149459149460149461149462149463149464149465149466149467149468149469149470149471149472149473149474149475149476149477149478149479149480149481149482149483149484149485149486149487149488149489149490149491149492149493149494149495149496149497149498149499149500149501149502149503149504149505149506149507149508149509149510149511149512149513149514149515149516149517149518149519149520149521149522149523149524149525149526149527149528149529149530149531149532149533149534149535149536149537149538149539149540149541149542149543149544149545149546149547149548149549149550149551149552149553149554149555149556149557149558149559149560149561149562149563149564149565149566149567149568149569149570149571149572149573149574149575149576149577149578149579149580149581149582149583149584149585149586149587149588149589149590149591149592149593149594149595149596149597149598149599149600149601149602149603149604149605149606149607149608149609149610149611149612149613149614149615149616149617149618149619149620149621149622149623149624149625149626149627149628149629149630149631149632149633149634149635149636149637149638149639149640149641149642149643149644149645149646149647149648149649149650149651149652149653149654149655149656149657149658149659149660149661149662149663149664149665149666149667149668149669149670149671149672149673149674149675149676149677149678149679149680149681149682149683149684149685149686149687149688149689149690149691149692149693149694149695149696149697149698149699149700149701149702149703149704149705149706149707149708149709149710149711149712149713149714149715149716149717149718149719149720149721149722149723149724149725149726149727149728149729149730149731149732149733149734149735149736149737149738149739149740149741149742149743149744149745149746149747149748149749149750149751149752149753149754149755149756149757149758149759149760149761149762149763149764149765149766149767149768149769149770149771149772149773149774149775149776149777149778149779149780149781149782149783149784149785149786149787149788149789149790149791149792149793149794149795149796149797149798149799149800149801149802149803149804149805149806149807149808149809149810149811149812149813149814149815149816149817149818149819149820149821149822149823149824149825149826149827149828149829149830149831149832149833149834149835149836149837149838149839149840149841149842149843149844149845149846149847149848149849149850149851149852149853149854149855149856149857149858149859149860149861149862149863149864149865149866149867149868149869149870149871149872149873149874149875149876149877149878149879149880149881149882149883149884149885149886149887149888149889149890149891149892149893149894149895149896149897149898149899149900149901149902149903149904149905149906149907149908149909149910149911149912149913149914149915149916149917149918149919149920149921149922149923149924149925149926149927149928149929149930149931149932149933149934149935149936149937149938149939149940149941149942149943149944149945149946149947149948149949149950149951149952149953149954149955149956149957149958149959149960149961149962149963149964149965149966149967149968149969149970149971149972149973149974149975149976149977149978149979149980149981149982149983149984149985149986149987149988149989149990149991149992149993149994149995149996149997149998149999150000150001150002150003150004150005150006150007150008150009150010150011150012150013150014150015150016150017150018150019150020150021150022150023150024150025150026150027150028150029150030150031150032150033150034150035150036150037150038150039150040150041150042150043150044150045150046150047150048150049150050150051150052150053150054150055150056150057150058150059150060150061150062150063150064150065150066150067150068150069150070150071150072150073150074150075150076150077150078150079150080150081150082150083150084150085150086150087150088150089150090150091150092150093150094150095150096150097150098150099150100150101150102150103150104150105150106150107150108150109150110150111150112150113150114150115150116150117150118150119150120150121150122150123150124150125150126150127150128150129150130150131150132150133150134150135150136150137150138150139150140150141150142150143150144150145150146150147150148150149150150150151150152150153150154150155150156150157150158150159150160150161150162150163150164150165150166150167150168150169150170150171150172150173150174150175150176150177150178150179150180150181150182150183150184150185150186150187150188150189150190150191150192150193150194150195150196150197150198150199150200150201150202150203150204150205150206150207150208150209150210150211150212150213150214150215150216150217150218150219150220150221150222150223150224150225150226150227150228150229150230150231150232150233150234150235150236150237150238150239150240150241150242150243150244150245150246150247150248150249150250150251150252150253150254150255150256150257150258150259150260150261150262150263150264150265150266150267150268150269150270150271150272150273150274150275150276150277150278150279150280150281150282150283150284150285150286150287150288150289150290150291150292150293150294150295150296150297150298150299150300150301150302150303150304150305150306150307150308150309150310150311150312150313150314150315150316150317150318150319150320150321150322150323150324150325150326150327150328150329150330150331150332150333150334150335150336150337150338150339150340150341150342150343150344150345150346150347150348150349150350150351150352150353150354150355150356150357150358150359150360150361150362150363150364150365150366150367150368150369150370150371150372150373150374150375150376150377150378150379150380150381150382150383150384150385150386150387150388150389150390150391150392150393150394150395150396150397150398150399150400150401150402150403150404150405150406150407150408150409150410150411150412150413150414150415150416150417150418150419150420150421150422150423150424150425150426150427150428150429150430150431150432150433150434150435150436150437150438150439150440150441150442150443150444150445150446150447150448150449150450150451150452150453150454150455150456150457150458150459150460150461150462150463150464150465150466150467150468150469150470150471150472150473150474150475150476150477150478150479150480150481150482150483150484150485150486150487150488150489150490150491150492150493150494150495150496150497150498150499150500150501150502150503150504150505150506150507150508150509150510150511150512150513150514150515150516150517150518150519150520150521150522150523150524150525150526150527150528150529150530150531150532150533150534150535150536150537150538150539150540150541150542150543150544150545150546150547150548150549150550150551150552150553150554150555150556150557150558150559150560150561150562150563150564150565150566150567150568150569150570150571150572150573150574150575150576150577150578150579150580150581150582150583150584150585150586150587150588150589150590150591150592150593150594150595150596150597150598150599150600150601150602150603150604150605150606150607150608150609150610150611150612150613150614150615150616150617150618150619150620150621150622150623150624150625150626150627150628150629150630150631150632150633150634150635150636150637150638150639150640150641150642150643150644150645150646150647150648150649150650150651150652150653150654150655150656150657150658150659150660150661150662150663150664150665150666150667150668150669150670150671150672150673150674150675150676150677150678150679150680150681150682150683150684150685150686150687150688150689150690150691150692150693150694150695150696150697150698150699150700150701150702150703150704150705150706150707150708150709150710150711150712150713150714150715150716150717150718150719150720150721150722150723150724150725150726150727150728150729150730150731150732150733150734150735150736150737150738150739150740150741150742150743150744150745150746150747150748150749150750150751150752150753150754150755150756150757150758150759150760150761150762150763150764150765150766150767150768150769150770150771150772150773150774150775150776150777150778150779150780150781150782150783150784150785150786150787150788150789150790150791150792150793150794150795150796150797150798150799150800150801150802150803150804150805150806150807150808150809150810150811150812150813150814150815150816150817150818150819150820150821150822150823150824150825150826150827150828150829150830150831150832150833150834150835150836150837150838150839150840150841150842150843150844150845150846150847150848150849150850150851150852150853150854150855150856150857150858150859150860150861150862150863150864150865150866150867150868150869150870150871150872150873150874150875150876150877150878150879150880150881150882150883150884150885150886150887150888150889150890150891150892150893150894150895150896150897150898150899150900150901150902150903150904150905150906150907150908150909150910150911150912150913150914150915150916150917150918150919150920150921150922150923150924150925150926150927150928150929150930150931150932150933150934150935150936150937150938150939150940150941150942150943150944150945150946150947150948150949150950150951150952150953150954150955150956150957150958150959150960150961150962150963150964150965150966150967150968150969150970150971150972150973150974150975150976150977150978150979150980150981150982150983150984150985150986150987150988150989150990150991150992150993150994150995150996150997150998150999151000151001151002151003151004151005151006151007151008151009151010151011151012151013151014151015151016151017151018151019151020151021151022151023151024151025151026151027151028151029151030151031151032151033151034151035151036151037151038151039151040151041151042151043151044151045151046151047151048151049151050151051151052151053151054151055151056151057151058151059151060151061151062151063151064151065151066151067151068151069151070151071151072151073151074151075151076151077151078151079151080151081151082151083151084151085151086151087151088151089151090151091151092151093151094151095151096151097151098151099151100151101151102151103151104151105151106151107151108151109151110151111151112151113151114151115151116151117151118151119151120151121151122151123151124151125151126151127151128151129151130151131151132151133151134151135151136151137151138151139151140151141151142151143151144151145151146151147151148151149151150151151151152151153151154151155151156151157151158151159151160151161151162151163151164151165151166151167151168151169151170151171151172151173151174151175151176151177151178151179151180151181151182151183151184151185151186151187151188151189151190151191151192151193151194151195151196151197151198151199151200151201151202151203151204151205151206151207151208151209151210151211151212151213151214151215151216151217151218151219151220151221151222151223151224151225151226151227151228151229151230151231151232151233151234151235151236151237151238151239151240151241151242151243151244151245151246151247151248151249151250151251151252151253151254151255151256151257151258151259151260151261151262151263151264151265151266151267151268151269151270151271151272151273151274151275151276151277151278151279151280151281151282151283151284151285151286151287151288151289151290151291151292151293151294151295151296151297151298151299151300151301151302151303151304151305151306151307151308151309151310151311151312151313151314151315151316151317151318151319151320151321151322151323151324151325151326151327151328151329151330151331151332151333151334151335151336151337151338151339151340151341151342151343151344151345151346151347151348151349151350151351151352151353151354151355151356151357151358151359151360151361151362151363151364151365151366151367151368151369151370151371151372151373151374151375151376151377151378151379151380151381151382151383151384151385151386151387151388151389151390151391151392151393151394151395151396151397151398151399151400151401151402151403151404151405151406151407151408151409151410151411151412151413151414151415151416151417151418151419151420151421151422151423151424151425151426151427151428151429151430151431151432151433151434151435151436151437151438151439151440151441151442151443151444151445151446151447151448151449151450151451151452151453151454151455151456151457151458151459151460151461151462151463151464151465151466151467151468151469151470151471151472151473151474151475151476151477151478151479151480151481151482151483151484151485151486151487151488151489151490151491151492151493151494151495151496151497151498151499151500151501151502151503151504151505151506151507151508151509151510151511151512151513151514151515151516151517151518151519151520151521151522151523151524151525151526151527151528151529151530151531151532151533151534151535151536151537151538151539151540151541151542151543151544151545151546151547151548151549151550151551151552151553151554151555151556151557151558151559151560151561151562151563151564151565151566151567151568151569151570151571151572151573151574151575151576151577151578151579151580151581151582151583151584151585151586151587151588151589151590151591151592151593151594151595151596151597151598151599151600151601151602151603151604151605151606151607151608151609151610151611151612151613151614151615151616151617151618151619151620151621151622151623151624151625151626151627151628151629151630151631151632151633151634151635151636151637151638151639151640151641151642151643151644151645151646151647151648151649151650151651151652151653151654151655151656151657151658151659151660151661151662151663151664151665151666151667151668151669151670151671151672151673151674151675151676151677151678151679151680151681151682151683151684151685151686151687151688151689151690151691151692151693151694151695151696151697151698151699151700151701151702151703151704151705151706151707151708151709151710151711151712151713151714151715151716151717151718151719151720151721151722151723151724151725151726151727151728151729151730151731151732151733151734151735151736151737151738151739151740151741151742151743151744151745151746151747151748151749151750151751151752151753151754151755151756151757151758151759151760151761151762151763151764151765151766151767151768151769151770151771151772151773151774151775151776151777151778151779151780151781151782151783151784151785151786151787151788151789151790151791151792151793151794151795151796151797151798151799151800151801151802151803151804151805151806151807151808151809151810151811151812151813151814151815151816151817151818151819151820151821151822151823151824151825151826151827151828151829151830151831151832151833151834151835151836151837151838151839151840151841151842151843151844151845151846151847151848151849151850151851151852151853151854151855151856151857151858151859151860151861151862151863151864151865151866151867151868151869151870151871151872151873151874151875151876151877151878151879151880151881151882151883151884151885151886151887151888151889151890151891151892151893151894151895151896151897151898151899151900151901151902151903151904151905151906151907151908151909151910151911151912151913151914151915151916151917151918151919151920151921151922151923151924151925151926151927151928151929151930151931151932151933151934151935151936151937151938151939151940151941151942151943151944151945151946151947151948151949151950151951151952151953151954151955151956151957151958151959151960151961151962151963151964151965151966151967151968151969151970151971151972151973151974151975151976151977151978151979151980151981151982151983151984151985151986151987151988151989151990151991151992151993151994151995151996151997151998151999152000152001152002152003152004152005152006152007152008152009152010152011152012152013152014152015152016152017152018152019152020152021152022152023152024152025152026152027152028152029152030152031152032152033152034152035152036152037152038152039152040152041152042152043152044152045152046152047152048152049152050152051152052152053152054152055152056152057152058152059152060152061152062152063152064152065152066152067152068152069152070152071152072152073152074152075152076152077152078152079152080152081152082152083152084152085152086152087152088152089152090152091152092152093152094152095152096152097152098152099152100152101152102152103152104152105152106152107152108152109152110152111152112152113152114152115152116152117152118152119152120152121152122152123152124152125152126152127152128152129152130152131152132152133152134152135152136152137152138152139152140152141152142152143152144152145152146152147152148152149152150152151152152152153152154152155152156152157152158152159152160152161152162152163152164152165152166152167152168152169152170152171152172152173152174152175152176152177152178152179152180152181152182152183152184152185152186152187152188152189152190152191152192152193152194152195152196152197152198152199152200152201152202152203152204152205152206152207152208152209152210152211152212152213152214152215152216152217152218152219152220152221152222152223152224152225152226152227152228152229152230152231152232152233152234152235152236152237152238152239152240152241152242152243152244152245152246152247152248152249152250152251152252152253152254152255152256152257152258152259152260152261152262152263152264152265152266152267152268152269152270152271152272152273152274152275152276152277152278152279152280152281152282152283152284152285152286152287152288152289152290152291152292152293152294152295152296152297152298152299152300152301152302152303152304152305152306152307152308152309152310152311152312152313152314152315152316152317152318152319152320152321152322152323152324152325152326152327152328152329152330152331152332152333152334152335152336152337152338152339152340152341152342152343152344152345152346152347152348152349152350152351152352152353152354152355152356152357152358152359152360152361152362152363152364152365152366152367152368152369152370152371152372152373152374152375152376152377152378152379152380152381152382152383152384152385152386152387152388152389152390152391152392152393152394152395152396152397152398152399152400152401152402152403152404152405152406152407152408152409152410152411152412152413152414152415152416152417152418152419152420152421152422152423152424152425152426152427152428152429152430152431152432152433152434152435152436152437152438152439152440152441152442152443152444152445152446152447152448152449152450152451152452152453152454152455152456152457152458152459152460152461152462152463152464152465152466152467152468152469152470152471152472152473152474152475152476152477152478152479152480152481152482152483152484152485152486152487152488152489152490152491152492152493152494152495152496152497152498152499152500152501152502152503152504152505152506152507152508152509152510152511152512152513152514152515152516152517152518152519152520152521152522152523152524152525152526152527152528152529152530152531152532152533152534152535152536152537152538152539152540152541152542152543152544152545152546152547152548152549152550152551152552152553152554152555152556152557152558152559152560152561152562152563152564152565152566152567152568152569152570152571152572152573152574152575152576152577152578152579152580152581152582152583152584152585152586152587152588152589152590152591152592152593152594152595152596152597152598152599152600152601152602152603152604152605152606152607152608152609152610152611152612152613152614152615152616152617152618152619152620152621152622152623152624152625152626152627152628152629152630152631152632152633152634152635152636152637152638152639152640152641152642152643152644152645152646152647152648152649152650152651152652152653152654152655152656152657152658152659152660152661152662152663152664152665152666152667152668152669152670152671152672152673152674152675152676152677152678152679152680152681152682152683152684152685152686152687152688152689152690152691152692152693152694152695152696152697152698152699152700152701152702152703152704152705152706152707152708152709152710152711152712152713152714152715152716152717152718152719152720152721152722152723152724152725152726152727152728152729152730152731152732152733152734152735152736152737152738152739152740152741152742152743152744152745152746152747152748152749152750152751152752152753152754152755152756152757152758152759152760152761152762152763152764152765152766152767152768152769152770152771152772152773152774152775152776152777152778152779152780152781152782152783152784152785152786152787152788152789152790152791152792152793152794152795152796152797152798152799152800152801152802152803152804152805152806152807152808152809152810152811152812152813152814152815152816152817152818152819152820152821152822152823152824152825152826152827152828152829152830152831152832152833152834152835152836152837152838152839152840152841152842152843152844152845152846152847152848152849152850152851152852152853152854152855152856152857152858152859152860152861152862152863152864152865152866152867152868152869152870152871152872152873152874152875152876152877152878152879152880152881152882152883152884152885152886152887152888152889152890152891152892152893152894152895152896152897152898152899152900152901152902152903152904152905152906152907152908152909152910152911152912152913152914152915152916152917152918152919152920152921152922152923152924152925152926152927152928152929152930152931152932152933152934152935152936152937152938152939152940152941152942152943152944152945152946152947152948152949152950152951152952152953152954152955152956152957152958152959152960152961152962152963152964152965152966152967152968152969152970152971152972152973152974152975152976152977152978152979152980152981152982152983152984152985152986152987152988152989152990152991152992152993152994152995152996152997152998152999153000153001153002153003153004153005153006153007153008153009153010153011153012153013153014153015153016153017153018153019153020153021153022153023153024153025153026153027153028153029153030153031153032153033153034153035153036153037153038153039153040153041153042153043153044153045153046153047153048153049153050153051153052153053153054153055153056153057153058153059153060153061153062153063153064153065153066153067153068153069153070153071153072153073153074153075153076153077153078153079153080153081153082153083153084153085153086153087153088153089153090153091153092153093153094153095153096153097153098153099153100153101153102153103153104153105153106153107153108153109153110153111153112153113153114153115153116153117153118153119153120153121153122153123153124153125153126153127153128153129153130153131153132153133153134153135153136153137153138153139153140153141153142153143153144153145153146153147153148153149153150153151153152153153153154153155153156153157153158153159153160153161153162153163153164153165153166153167153168153169153170153171153172153173153174153175153176153177153178153179153180153181153182153183153184153185153186153187153188153189153190153191153192153193153194153195153196153197153198153199153200153201153202153203153204153205153206153207153208153209153210153211153212153213153214153215153216153217153218153219153220153221153222153223153224153225153226153227153228153229153230153231153232153233153234153235153236153237153238153239153240153241153242153243153244153245153246153247153248153249153250153251153252153253153254153255153256153257153258153259153260153261153262153263153264153265153266153267153268153269153270153271153272153273153274153275153276153277153278153279153280153281153282153283153284153285153286153287153288153289153290153291153292153293153294153295153296153297153298153299153300153301153302153303153304153305153306153307153308153309153310153311153312153313153314153315153316153317153318153319153320153321153322153323153324153325153326153327153328153329153330153331153332153333153334153335153336153337153338153339153340153341153342153343153344153345153346153347153348153349153350153351153352153353153354153355153356153357153358153359153360153361153362153363153364153365153366153367153368153369153370153371153372153373153374153375153376153377153378153379153380153381153382153383153384153385153386153387153388153389153390153391153392153393153394153395153396153397153398153399153400153401153402153403153404153405153406153407153408153409153410153411153412153413153414153415153416153417153418153419153420153421153422153423153424153425153426153427153428153429153430153431153432153433153434153435153436153437153438153439153440153441153442153443153444153445153446153447153448153449153450153451153452153453153454153455153456153457153458153459153460153461153462153463153464153465153466153467153468153469153470153471153472153473153474153475153476153477153478153479153480153481153482153483153484153485153486153487153488153489153490153491153492153493153494153495153496153497153498153499153500153501153502153503153504153505153506153507153508153509153510153511153512153513153514153515153516153517153518153519153520153521153522153523153524153525153526153527153528153529153530153531153532153533153534153535153536153537153538153539153540153541153542153543153544153545153546153547153548153549153550153551153552153553153554153555153556153557153558153559153560153561153562153563153564153565153566153567153568153569153570153571153572153573153574153575153576153577153578153579153580153581153582153583153584153585153586153587153588153589153590153591153592153593153594153595153596153597153598153599153600153601153602153603153604153605153606153607153608153609153610153611153612153613153614153615153616153617153618153619153620153621153622153623153624153625153626153627153628153629153630153631153632153633153634153635153636153637153638153639153640153641153642153643153644153645153646153647153648153649153650153651153652153653153654153655153656153657153658153659153660153661153662153663153664153665153666153667153668153669153670153671153672153673153674153675153676153677153678153679153680153681153682153683153684153685153686153687153688153689153690153691153692153693153694153695153696153697153698153699153700153701153702153703153704153705153706153707153708153709153710153711153712153713153714153715153716153717153718153719153720153721153722153723153724153725153726153727153728153729153730153731153732153733153734153735153736153737153738153739153740153741153742153743153744153745153746153747153748153749153750153751153752153753153754153755153756153757153758153759153760153761153762153763153764153765153766153767153768153769153770153771153772153773153774153775153776153777153778153779153780153781153782153783153784153785153786153787153788153789153790153791153792153793153794153795153796153797153798153799153800153801153802153803153804153805153806153807153808153809153810153811153812153813153814153815153816153817153818153819153820153821153822153823153824153825153826153827153828153829153830153831153832153833153834153835153836153837153838153839153840153841153842153843153844153845153846153847153848153849153850153851153852153853153854153855153856153857153858153859153860153861153862153863153864153865153866153867153868153869153870153871153872153873153874153875153876153877153878153879153880153881153882153883153884153885153886153887153888153889153890153891153892153893153894153895153896153897153898153899153900153901153902153903153904153905153906153907153908153909153910153911153912153913153914153915153916153917153918153919153920153921153922153923153924153925153926153927153928153929153930153931153932153933153934153935153936153937153938153939153940153941153942153943153944153945153946153947153948153949153950153951153952153953153954153955153956153957153958153959153960153961153962153963153964153965153966153967153968153969153970153971153972153973153974153975153976153977153978153979153980153981153982153983153984153985153986153987153988153989153990153991153992153993153994153995153996153997153998153999154000154001154002154003154004154005154006154007154008154009154010154011154012154013154014154015154016154017154018154019154020154021154022154023154024154025154026154027154028154029154030154031154032154033154034154035154036154037154038154039154040154041154042154043154044154045154046154047154048154049154050154051154052154053154054154055154056154057154058154059154060154061154062154063154064154065154066154067154068154069154070154071154072154073154074154075154076154077154078154079154080154081154082154083154084154085154086154087154088154089154090154091154092154093154094154095154096154097154098154099154100154101154102154103154104154105154106154107154108154109154110154111154112154113154114154115154116154117154118154119154120154121154122154123154124154125154126154127154128154129154130154131154132154133154134154135154136154137154138154139154140154141154142154143154144154145154146154147154148154149154150154151154152154153154154154155154156154157154158154159154160154161154162154163154164154165154166154167154168154169154170154171154172154173154174154175154176154177154178154179154180154181154182154183154184154185154186154187154188154189154190154191154192154193154194154195154196154197154198154199154200154201154202154203154204154205154206154207154208154209154210154211154212154213154214154215154216154217154218154219154220154221154222154223154224154225154226154227154228154229154230154231154232154233154234154235154236154237154238154239154240154241154242154243154244154245154246154247154248154249154250154251154252154253154254154255154256154257154258154259154260154261154262154263154264154265154266154267154268154269154270154271154272154273154274154275154276154277154278154279154280154281154282154283154284154285154286154287154288154289154290154291154292154293154294154295154296154297154298154299154300154301154302154303154304154305154306154307154308154309154310154311154312154313154314154315154316154317154318154319154320154321154322154323154324154325154326154327154328154329154330154331154332154333154334154335154336154337154338154339154340154341154342154343154344154345154346154347154348154349154350154351154352154353154354154355154356154357154358154359154360154361154362154363154364154365154366154367154368154369154370154371154372154373154374154375154376154377154378154379154380154381154382154383154384154385154386154387154388154389154390154391154392154393154394154395154396154397154398154399154400154401154402154403154404154405154406154407154408154409154410154411154412154413154414154415154416154417154418154419154420154421154422154423154424154425154426154427154428154429154430154431154432154433154434154435154436154437154438154439154440154441154442154443154444154445154446154447154448154449154450154451154452154453154454154455154456154457154458154459154460154461154462154463154464154465154466154467154468154469154470154471154472154473154474154475154476154477154478154479154480154481154482154483154484154485154486154487154488154489154490154491154492154493154494154495154496154497154498154499154500154501154502154503154504154505154506154507154508154509154510154511154512154513154514154515154516154517154518154519154520154521154522154523154524154525154526154527154528154529154530154531154532154533154534154535154536154537154538154539154540154541154542154543154544154545154546154547154548154549154550154551154552154553154554154555154556154557154558154559154560154561154562154563154564154565154566154567154568154569154570154571154572154573154574154575154576154577154578154579154580154581154582154583154584154585154586154587154588154589154590154591154592154593154594154595154596154597154598154599154600154601154602154603154604154605154606154607154608154609154610154611154612154613154614154615154616154617154618154619154620154621154622154623154624154625154626154627154628154629154630154631154632154633154634154635154636154637154638154639154640154641154642154643154644154645154646154647154648154649154650154651154652154653154654154655154656154657154658154659154660154661154662154663154664154665154666154667154668154669154670154671154672154673154674154675154676154677154678154679154680154681154682154683154684154685154686154687154688154689154690154691154692154693154694154695154696154697154698154699154700154701154702154703154704154705154706154707154708154709154710154711154712154713154714154715154716154717154718154719154720154721154722154723154724154725154726154727154728154729154730154731154732154733154734154735154736154737154738154739154740154741154742154743154744154745154746154747154748154749154750154751154752154753154754154755154756154757154758154759154760154761154762154763154764154765154766154767154768154769154770154771154772154773154774154775154776154777154778154779154780154781154782154783154784154785154786154787154788154789154790154791154792154793154794154795154796154797154798154799154800154801154802154803154804154805154806154807154808154809154810154811154812154813154814154815154816154817154818154819154820154821154822154823154824154825154826154827154828154829154830154831154832154833154834154835154836154837154838154839154840154841154842154843154844154845154846154847154848154849154850154851154852154853154854154855154856154857154858154859154860154861154862154863154864154865154866154867154868154869154870154871154872154873154874154875154876154877154878154879154880154881154882154883154884154885154886154887154888154889154890154891154892154893154894154895154896154897154898154899154900154901154902154903154904154905154906154907154908154909154910154911154912154913154914154915154916154917154918154919154920154921154922154923154924154925154926154927154928154929154930154931154932154933154934154935154936154937154938154939154940154941154942154943154944154945154946154947154948154949154950154951154952154953154954154955154956154957154958154959154960154961154962154963154964154965154966154967154968154969154970154971154972154973154974154975154976154977154978154979154980154981154982154983154984154985154986154987154988154989154990154991154992154993154994154995154996154997154998154999155000155001155002155003155004155005155006155007155008155009155010155011155012155013155014155015155016155017155018155019155020155021155022155023155024155025155026155027155028155029155030155031155032155033155034155035155036155037155038155039155040155041155042155043155044155045155046155047155048155049155050155051155052155053155054155055155056155057155058155059155060155061155062155063155064155065155066155067155068155069155070155071155072155073155074155075155076155077155078155079155080155081155082155083155084155085155086155087155088155089155090155091155092155093155094155095155096155097155098155099155100155101155102155103155104155105155106155107155108155109155110155111155112155113155114155115155116155117155118155119155120155121155122155123155124155125155126155127155128155129155130155131155132155133155134155135155136155137155138155139155140155141155142155143155144155145155146155147155148155149155150155151155152155153155154155155155156155157155158155159155160155161155162155163155164155165155166155167155168155169155170155171155172155173155174155175155176155177155178155179155180155181155182155183155184155185155186155187155188155189155190155191155192155193155194155195155196155197155198155199155200155201155202155203155204155205155206155207155208155209155210155211155212155213155214155215155216155217155218155219155220155221155222155223155224155225155226155227155228155229155230155231155232155233155234155235155236155237155238155239155240155241155242155243155244155245155246155247155248155249155250155251155252155253155254155255155256155257155258155259155260155261155262155263155264155265155266155267155268155269155270155271155272155273155274155275155276155277155278155279155280155281155282155283155284155285155286155287155288155289155290155291155292155293155294155295155296155297155298155299155300155301155302155303155304155305155306155307155308155309155310155311155312155313155314155315155316155317155318155319155320155321155322155323155324155325155326155327155328155329155330155331155332155333155334155335155336155337155338155339155340155341155342155343155344155345155346155347155348155349155350155351155352155353155354155355155356155357155358155359155360155361155362155363155364155365155366155367155368155369155370155371155372155373155374155375155376155377155378155379155380155381155382155383155384155385155386155387155388155389155390155391155392155393155394155395155396155397155398155399155400155401155402155403155404155405155406155407155408155409155410155411155412155413155414155415155416155417155418155419155420155421155422155423155424155425155426155427155428155429155430155431155432155433155434155435155436155437155438155439155440155441155442155443155444155445155446155447155448155449155450155451155452155453155454155455155456155457155458155459155460155461155462155463155464155465155466155467155468155469155470155471155472155473155474155475155476155477155478155479155480155481155482155483155484155485155486155487155488155489155490155491155492155493155494155495155496155497155498155499155500155501155502155503155504155505155506155507155508155509155510155511155512155513155514155515155516155517155518155519155520155521155522155523155524155525155526155527155528155529155530155531155532155533155534155535155536155537155538155539155540155541155542155543155544155545155546155547155548155549155550155551155552155553155554155555155556155557155558155559155560155561155562155563155564155565155566155567155568155569155570155571155572155573155574155575155576155577155578155579155580155581155582155583155584155585155586155587155588155589155590155591155592155593155594155595155596155597155598155599155600155601155602155603155604155605155606155607155608155609155610155611155612155613155614155615155616155617155618155619155620155621155622155623155624155625155626155627155628155629155630155631155632155633155634155635155636155637155638155639155640155641155642155643155644155645155646155647155648155649155650155651155652155653155654155655155656155657155658155659155660155661155662155663155664155665155666155667155668155669155670155671155672155673155674155675155676155677155678155679155680155681155682155683155684155685155686155687155688155689155690155691155692155693155694155695155696155697155698155699155700155701155702155703155704155705155706155707155708155709155710155711155712155713155714155715155716155717155718155719155720155721155722155723155724155725155726155727155728155729155730155731155732155733155734155735155736155737155738155739155740155741155742155743155744155745155746155747155748155749155750155751155752155753155754155755155756155757155758155759155760155761155762155763155764155765155766155767155768155769155770155771155772155773155774155775155776155777155778155779155780155781155782155783155784155785155786155787155788155789155790155791155792155793155794155795155796155797155798155799155800155801155802155803155804155805155806155807155808155809155810155811155812155813155814155815155816155817155818155819155820155821155822155823155824155825155826155827155828155829155830155831155832155833155834155835155836155837155838155839155840155841155842155843155844155845155846155847155848155849155850155851155852155853155854155855155856155857155858155859155860155861155862155863155864155865155866155867155868155869155870155871155872155873155874155875155876155877155878155879155880155881155882155883155884155885155886155887155888155889155890155891155892155893155894155895155896155897155898155899155900155901155902155903155904155905155906155907155908155909155910155911155912155913155914155915155916155917155918155919155920155921155922155923155924155925155926155927155928155929155930155931155932155933155934155935155936155937155938155939155940155941155942155943155944155945155946155947155948155949155950155951155952155953155954155955155956155957155958155959155960155961155962155963155964155965155966155967155968155969155970155971155972155973155974155975155976155977155978155979155980155981155982155983155984155985155986155987155988155989155990155991155992155993155994155995155996155997155998155999156000156001156002156003156004156005156006156007156008156009156010156011156012156013156014156015156016156017156018156019156020156021156022156023156024156025156026156027156028156029156030156031156032156033156034156035156036156037156038156039156040156041156042156043156044156045156046156047156048156049156050156051156052156053156054156055156056156057156058156059156060156061156062156063156064156065156066156067156068156069156070156071156072156073156074156075156076156077156078156079156080156081156082156083156084156085156086156087156088156089156090156091156092156093156094156095156096156097156098156099156100156101156102156103156104156105156106156107156108156109156110156111156112156113156114156115156116156117156118156119156120156121156122156123156124156125156126156127156128156129156130156131156132156133156134156135156136156137156138156139156140156141156142156143156144156145156146156147156148156149156150156151156152156153156154156155156156156157156158156159156160156161156162156163156164156165156166156167156168156169156170156171156172156173156174156175156176156177156178156179156180156181156182156183156184156185156186156187156188156189156190156191156192156193156194156195156196156197156198156199156200156201156202156203156204156205156206156207156208156209156210156211156212156213156214156215156216156217156218156219156220156221156222156223156224156225156226156227156228156229156230156231156232156233156234156235156236156237156238156239156240156241156242156243156244156245156246156247156248156249156250156251156252156253156254156255156256156257156258156259156260156261156262156263156264156265156266156267156268156269156270156271156272156273156274156275156276156277156278156279156280156281156282156283156284156285156286156287156288156289156290156291156292156293156294156295156296156297156298156299156300156301156302156303156304156305156306156307156308156309156310156311156312156313156314156315156316156317156318156319156320156321156322156323156324156325156326156327156328156329156330156331156332156333156334156335156336156337156338156339156340156341156342156343156344156345156346156347156348156349156350156351156352156353156354156355156356156357156358156359156360156361156362156363156364156365156366156367156368156369156370156371156372156373156374156375156376156377156378156379156380156381156382156383156384156385156386156387156388156389156390156391156392156393156394156395156396156397156398156399156400156401156402156403156404156405156406156407156408156409156410156411156412156413156414156415156416156417156418156419156420156421156422156423156424156425156426156427156428156429156430156431156432156433156434156435156436156437156438156439156440156441156442156443156444156445156446156447156448156449156450156451156452156453156454156455156456156457156458156459156460156461156462156463156464156465156466156467156468156469156470156471156472156473156474156475156476156477156478156479156480156481156482156483156484156485156486156487156488156489156490156491156492156493156494156495156496156497156498156499156500156501156502156503156504156505156506156507156508156509156510156511156512156513156514156515156516156517156518156519156520156521156522156523156524156525156526156527156528156529156530156531156532156533156534156535156536156537156538156539156540156541156542156543156544156545156546156547156548156549156550156551156552156553156554156555156556156557156558156559156560156561156562156563156564156565156566156567156568156569156570156571156572156573156574156575156576156577156578156579156580156581156582156583156584156585156586156587156588156589156590156591156592156593156594156595156596156597156598156599156600156601156602156603156604156605156606156607156608156609156610156611156612156613156614156615156616156617156618156619156620156621156622156623156624156625156626156627156628156629156630156631156632156633156634156635156636156637156638156639156640156641156642156643156644156645156646156647156648156649156650156651156652156653156654156655156656156657156658156659156660156661156662156663156664156665156666156667156668156669156670156671156672156673156674156675156676156677156678156679156680156681156682156683156684156685156686156687156688156689156690156691156692156693156694156695156696156697156698156699156700156701156702156703156704156705156706156707156708156709156710156711156712156713156714156715156716156717156718156719156720156721156722156723156724156725156726156727156728156729156730156731156732156733156734156735156736156737156738156739156740156741156742156743156744156745156746156747156748156749156750156751156752156753156754156755156756156757156758156759156760156761156762156763156764156765156766156767156768156769156770156771156772156773156774156775156776156777156778156779156780156781156782156783156784156785156786156787156788156789156790156791156792156793156794156795156796156797156798156799156800156801156802156803156804156805156806156807156808156809156810156811156812156813156814156815156816156817156818156819156820156821156822156823156824156825156826156827156828156829156830156831156832156833156834156835156836156837156838156839156840156841156842156843156844156845156846156847156848156849156850156851156852156853156854156855156856156857156858156859156860156861156862156863156864156865156866156867156868156869156870156871156872156873156874156875156876156877156878156879156880156881156882156883156884156885156886156887156888156889156890156891156892156893156894156895156896156897156898156899156900156901156902156903156904156905156906156907156908156909156910156911156912156913156914156915156916156917156918156919156920156921156922156923156924156925156926156927156928156929156930156931156932156933156934156935156936156937156938156939156940156941156942156943156944156945156946156947156948156949156950156951156952156953156954156955156956156957156958156959156960156961156962156963156964156965156966156967156968156969156970156971156972156973156974156975156976156977156978156979156980156981156982156983156984156985156986156987156988156989156990156991156992156993156994156995156996156997156998156999157000157001157002157003157004157005157006157007157008157009157010157011157012157013157014157015157016157017157018157019157020157021157022157023157024157025157026157027157028157029157030157031157032157033157034157035157036157037157038157039157040157041157042157043157044157045157046157047157048157049157050157051157052157053157054157055157056157057157058157059157060157061157062157063157064157065157066157067157068157069157070157071157072157073157074157075157076157077157078157079157080157081157082157083157084157085157086157087157088157089157090157091157092157093157094157095157096157097157098157099157100157101157102157103157104157105157106157107157108157109157110157111157112157113157114157115157116157117157118157119157120157121157122157123157124157125157126157127157128157129157130157131157132157133157134157135157136157137157138157139157140157141157142157143157144157145157146157147157148157149157150157151157152157153157154157155157156157157157158157159157160157161157162157163157164157165157166157167157168157169157170157171157172157173157174157175157176157177157178157179157180157181157182157183157184157185157186157187157188157189157190157191157192157193157194157195157196157197157198157199157200157201157202157203157204157205157206157207157208157209157210157211157212157213157214157215157216157217157218157219157220157221157222157223157224157225157226157227157228157229157230157231157232157233157234157235157236157237157238157239157240157241157242157243157244157245157246157247157248157249157250157251157252157253157254157255157256157257157258157259157260157261157262157263157264157265157266157267157268157269157270157271157272157273157274157275157276157277157278157279157280157281157282157283157284157285157286157287157288157289157290157291157292157293157294157295157296157297157298157299157300157301157302157303157304157305157306157307157308157309157310157311157312157313157314157315157316157317157318157319157320157321157322157323157324157325157326157327157328157329157330157331157332157333157334157335157336157337157338157339157340157341157342157343157344157345157346157347157348157349157350157351157352157353157354157355157356157357157358157359157360157361157362157363157364157365157366157367157368157369157370157371157372157373157374157375157376157377157378157379157380157381157382157383157384157385157386157387157388157389157390157391157392157393157394157395157396157397157398157399157400157401157402157403157404157405157406157407157408157409157410157411157412157413157414157415157416157417157418157419157420157421157422157423157424157425157426157427157428157429157430157431157432157433157434157435157436157437157438157439157440157441157442157443157444157445157446157447157448157449157450157451157452157453157454157455157456157457157458157459157460157461157462157463157464157465157466157467157468157469157470157471157472157473157474157475157476157477157478157479157480157481157482157483157484157485157486157487157488157489157490157491157492157493157494157495157496157497157498157499157500157501157502157503157504157505157506157507157508157509157510157511157512157513157514157515157516157517157518157519157520157521157522157523157524157525157526157527157528157529157530157531157532157533157534157535157536157537157538157539157540157541157542157543157544157545157546157547157548157549157550157551157552157553157554157555157556157557157558157559157560157561157562157563157564157565157566157567157568157569157570157571157572157573157574157575157576157577157578157579157580157581157582157583157584157585157586157587157588157589157590157591157592157593157594157595157596157597157598157599157600157601157602157603157604157605157606157607157608157609157610157611157612157613157614157615157616157617157618157619157620157621157622157623157624157625157626157627157628157629157630157631157632157633157634157635157636157637157638157639157640157641157642157643157644157645157646157647157648157649157650157651157652157653157654157655157656157657157658157659157660157661157662157663157664157665157666157667157668157669157670157671157672157673157674157675157676157677157678157679157680157681157682157683157684157685157686157687157688157689157690157691157692157693157694157695157696157697157698157699157700157701157702157703157704157705157706157707157708157709157710157711157712157713157714157715157716157717157718157719157720157721157722157723157724157725157726157727157728157729157730157731157732157733157734157735157736157737157738157739157740157741157742157743157744157745157746157747157748157749157750157751157752157753157754157755157756157757157758157759157760157761157762157763157764157765157766157767157768157769157770157771157772157773157774157775157776157777157778157779157780157781157782157783157784157785157786157787157788157789157790157791157792157793157794157795157796157797157798157799157800157801157802157803157804157805157806157807157808157809157810157811157812157813157814157815157816157817157818157819157820157821157822157823157824157825157826157827157828157829157830157831157832157833157834157835157836157837157838157839157840157841157842157843157844157845157846157847157848157849157850157851157852157853157854157855157856157857157858157859157860157861157862157863157864157865157866157867157868157869157870157871157872157873157874157875157876157877157878157879157880157881157882157883157884157885157886157887157888157889157890157891157892157893157894157895157896157897157898157899157900157901157902157903157904157905157906157907157908157909157910157911157912157913157914157915157916157917157918157919157920157921157922157923157924157925157926157927157928157929157930157931157932157933157934157935157936157937157938157939157940157941157942157943157944157945157946157947157948157949157950157951157952157953157954157955157956157957157958157959157960157961157962157963157964157965157966157967157968157969157970157971157972157973157974157975157976157977157978157979157980157981157982157983157984157985157986157987157988157989157990157991157992157993157994157995157996157997157998157999158000158001158002158003158004158005158006158007158008158009158010158011158012158013158014158015158016158017158018158019158020158021158022158023158024158025158026158027158028158029158030158031158032158033158034158035158036158037158038158039158040158041158042158043158044158045158046158047158048158049158050158051158052158053158054158055158056158057158058158059158060158061158062158063158064158065158066158067158068158069158070158071158072158073158074158075158076158077158078158079158080158081158082158083158084158085158086158087158088158089158090158091158092158093158094158095158096158097158098158099158100158101158102158103158104158105158106158107158108158109158110158111158112158113158114158115158116158117158118158119158120158121158122158123158124158125158126158127158128158129158130158131158132158133158134158135158136158137158138158139158140158141158142158143158144158145158146158147158148158149158150158151158152158153158154158155158156158157158158158159158160158161158162158163158164158165158166158167158168158169158170158171158172158173158174158175158176158177158178158179158180158181158182158183158184158185158186158187158188158189158190158191158192158193158194158195158196158197158198158199158200158201158202158203158204158205158206158207158208158209158210158211158212158213158214158215158216158217158218158219158220158221158222158223158224158225158226158227158228158229158230158231158232158233158234158235158236158237158238158239158240158241158242158243158244158245158246158247158248158249158250158251158252158253158254158255158256158257158258158259158260158261158262158263158264158265158266158267158268158269158270158271158272158273158274158275158276158277158278158279158280158281158282158283158284158285158286158287158288158289158290158291158292158293158294158295158296158297158298158299158300158301158302158303158304158305158306158307158308158309158310158311158312158313158314158315158316158317158318158319158320158321158322158323158324158325158326158327158328158329158330158331158332158333158334158335158336158337158338158339158340158341158342158343158344158345158346158347158348158349158350158351158352158353158354158355158356158357158358158359158360158361158362158363158364158365158366158367158368158369158370158371158372158373158374158375158376158377158378158379158380158381158382158383158384158385158386158387158388158389158390158391158392158393158394158395158396158397158398158399158400158401158402158403158404158405158406158407158408158409158410158411158412158413158414158415158416158417158418158419158420158421158422158423158424158425158426158427158428158429158430158431158432158433158434158435158436158437158438158439158440158441158442158443158444158445158446158447158448158449158450158451158452158453158454158455158456158457158458158459158460158461158462158463158464158465158466158467158468158469158470158471158472158473158474158475158476158477158478158479158480158481158482158483158484158485158486158487158488158489158490158491158492158493158494158495158496158497158498158499158500158501158502158503158504158505158506158507158508158509158510158511158512158513158514158515158516158517158518158519158520158521158522158523158524158525158526158527158528158529158530158531158532158533158534158535158536158537158538158539158540158541158542158543158544158545158546158547158548158549158550158551158552158553158554158555158556158557158558158559158560158561158562158563158564158565158566158567158568158569158570158571158572158573158574158575158576158577158578158579158580158581158582158583158584158585158586158587158588158589158590158591158592158593158594158595158596158597158598158599158600158601158602158603158604158605158606158607158608158609158610158611158612158613158614158615158616158617158618158619158620158621158622158623158624158625158626158627158628158629158630158631158632158633158634158635158636158637158638158639158640158641158642158643158644158645158646158647158648158649158650158651158652158653158654158655158656158657158658158659158660158661158662158663158664158665158666158667158668158669158670158671158672158673158674158675158676158677158678158679158680158681158682158683158684158685158686158687158688158689158690158691158692158693158694158695158696158697158698158699158700158701158702158703158704158705158706158707158708158709158710158711158712158713158714158715158716158717158718158719158720158721158722158723158724158725158726158727158728158729158730158731158732158733158734158735158736158737158738158739158740158741158742158743158744158745158746158747158748158749158750158751158752158753158754158755158756158757158758158759158760158761158762158763158764158765158766158767158768158769158770158771158772158773158774158775158776158777158778158779158780158781158782158783158784158785158786158787158788158789158790158791158792158793158794158795158796158797158798158799158800158801158802158803158804158805158806158807158808158809158810158811158812158813158814158815158816158817158818158819158820158821158822158823158824158825158826158827158828158829158830158831158832158833158834158835158836158837158838158839158840158841158842158843158844158845158846158847158848158849158850158851158852158853158854158855158856158857158858158859158860158861158862158863158864158865158866158867158868158869158870158871158872158873158874158875158876158877158878158879158880158881158882158883158884158885158886158887158888158889158890158891158892158893158894158895158896158897158898158899158900158901158902158903158904158905158906158907158908158909158910158911158912158913158914158915158916158917158918158919158920158921158922158923158924158925158926158927158928158929158930158931158932158933158934158935158936158937158938158939158940158941158942158943158944158945158946158947158948158949158950158951158952158953158954158955158956158957158958158959158960158961158962158963158964158965158966158967158968158969158970158971158972158973158974158975158976158977158978158979158980158981158982158983158984158985158986158987158988158989158990158991158992158993158994158995158996158997158998158999159000159001159002159003159004159005159006159007159008159009159010159011159012159013159014159015159016159017159018159019159020159021159022159023159024159025159026159027159028159029159030159031159032159033159034159035159036159037159038159039159040159041159042159043159044159045159046159047159048159049159050159051159052159053159054159055159056159057159058159059159060159061159062159063159064159065159066159067159068159069159070159071159072159073159074159075159076159077159078159079159080159081159082159083159084159085159086159087159088159089159090159091159092159093159094159095159096159097159098159099159100159101159102159103159104159105159106159107159108159109159110159111159112159113159114159115159116159117159118159119159120159121159122159123159124159125159126159127159128159129159130159131159132159133159134159135159136159137159138159139159140159141159142159143159144159145159146159147159148159149159150159151159152159153159154159155159156159157159158159159159160159161159162159163159164159165159166159167159168159169159170159171159172159173159174159175159176159177159178159179159180159181159182159183159184159185159186159187159188159189159190159191159192159193159194159195159196159197159198159199159200159201159202159203159204159205159206159207159208159209159210159211159212159213159214159215159216159217159218159219159220159221159222159223159224159225159226159227159228159229159230159231159232159233159234159235159236159237159238159239159240159241159242159243159244159245159246159247159248159249159250159251159252159253159254159255159256159257159258159259159260159261159262159263159264159265159266159267159268159269159270159271159272159273159274159275159276159277159278159279159280159281159282159283159284159285159286159287159288159289159290159291159292159293159294159295159296159297159298159299159300159301159302159303159304159305159306159307159308159309159310159311159312159313159314159315159316159317159318159319159320159321159322159323159324159325159326159327159328159329159330159331159332159333159334159335159336159337159338159339159340159341159342159343159344159345159346159347159348159349159350159351159352159353159354159355159356159357159358159359159360159361159362159363159364159365159366159367159368159369159370159371159372159373159374159375159376159377159378159379159380159381159382159383159384159385159386159387159388159389159390159391159392159393159394159395159396159397159398159399159400159401159402159403159404159405159406159407159408159409159410159411159412159413159414159415159416159417159418159419159420159421159422159423159424159425159426159427159428159429159430159431159432159433159434159435159436159437159438159439159440159441159442159443159444159445159446159447159448159449159450159451159452159453159454159455159456159457159458159459159460159461159462159463159464159465159466159467159468159469159470159471159472159473159474159475159476159477159478159479159480159481159482159483159484159485159486159487159488159489159490159491159492159493159494159495159496159497159498159499159500159501159502159503159504159505159506159507159508159509159510159511159512159513159514159515159516159517159518159519159520159521159522159523159524159525159526159527159528159529159530159531159532159533159534159535159536159537159538159539159540159541159542159543159544159545159546159547159548159549159550159551159552159553159554159555159556159557159558159559159560159561159562159563159564159565159566159567159568159569159570159571159572159573159574159575159576159577159578159579159580159581159582159583159584159585159586159587159588159589159590159591159592159593159594159595159596159597159598159599159600159601159602159603159604159605159606159607159608159609159610159611159612159613159614159615159616159617159618159619159620159621159622159623159624159625159626159627159628159629159630159631159632159633159634159635159636159637159638159639159640159641159642159643159644159645159646159647159648159649159650159651159652159653159654159655159656159657159658159659159660159661159662159663159664159665159666159667159668159669159670159671159672159673159674159675159676159677159678159679159680159681159682159683159684159685159686159687159688159689159690159691159692159693159694159695159696159697159698159699159700159701159702159703159704159705159706159707159708159709159710159711159712159713159714159715159716159717159718159719159720159721159722159723159724159725159726159727159728159729159730159731159732159733159734159735159736159737159738159739159740159741159742159743159744159745159746159747159748159749159750159751159752159753159754159755159756159757159758159759159760159761159762159763159764159765159766159767159768159769159770159771159772159773159774159775159776159777159778159779159780159781159782159783159784159785159786159787159788159789159790159791159792159793159794159795159796159797159798159799159800159801159802159803159804159805159806159807159808159809159810159811159812159813159814159815159816159817159818159819159820159821159822159823159824159825159826159827159828159829159830159831159832159833159834159835159836159837159838159839159840159841159842159843159844159845159846159847159848159849159850159851159852159853159854159855159856159857159858159859159860159861159862159863159864159865159866159867159868159869159870159871159872159873159874159875159876159877159878159879159880159881159882159883159884159885159886159887159888159889159890159891159892159893159894159895159896159897159898159899159900159901159902159903159904159905159906159907159908159909159910159911159912159913159914159915159916159917159918159919159920159921159922159923159924159925159926159927159928159929159930159931159932159933159934159935159936159937159938159939159940159941159942159943159944159945159946159947159948159949159950159951159952159953159954159955159956159957159958159959159960159961159962159963159964159965159966159967159968159969159970159971159972159973159974159975159976159977159978159979159980159981159982159983159984159985159986159987159988159989159990159991159992159993159994159995159996159997159998159999160000160001160002160003160004160005160006160007160008160009160010160011160012160013160014160015160016160017160018160019160020160021160022160023160024160025160026160027160028160029160030160031160032160033160034160035160036160037160038160039160040160041160042160043160044160045160046160047160048160049160050160051160052160053160054160055160056160057160058160059160060160061160062160063160064160065160066160067160068160069160070160071160072160073160074160075160076160077160078160079160080160081160082160083160084160085160086160087160088160089160090160091160092160093160094160095160096160097160098160099160100160101160102160103160104160105160106160107160108160109160110160111160112160113160114160115160116160117160118160119160120160121160122160123160124160125160126160127160128160129160130160131160132160133160134160135160136160137160138160139160140160141160142160143160144160145160146160147160148160149160150160151160152160153160154160155160156160157160158160159160160160161160162160163160164160165160166160167160168160169160170160171160172160173160174160175160176160177160178160179160180160181160182160183160184160185160186160187160188160189160190160191160192160193160194160195160196160197160198160199160200160201160202160203160204160205160206160207160208160209160210160211160212160213160214160215160216160217160218160219160220160221160222160223160224160225160226160227160228160229160230160231160232160233160234160235160236160237160238160239160240160241160242160243160244160245160246160247160248160249160250160251160252160253160254160255160256160257160258160259160260160261160262160263160264160265160266160267160268160269160270160271160272160273160274160275160276160277160278160279160280160281160282160283160284160285160286160287160288160289160290160291160292160293160294160295160296160297160298160299160300160301160302160303160304160305160306160307160308160309160310160311160312160313160314160315160316160317160318160319160320160321160322160323160324160325160326160327160328160329160330160331160332160333160334160335160336160337160338160339160340160341160342160343160344160345160346160347160348160349160350160351160352160353160354160355160356160357160358160359160360160361160362160363160364160365160366160367160368160369160370160371160372160373160374160375160376160377160378160379160380160381160382160383160384160385160386160387160388160389160390160391160392160393160394160395160396160397160398160399160400160401160402160403160404160405160406160407160408160409160410160411160412160413160414160415160416160417160418160419160420160421160422160423160424160425160426160427160428160429160430160431160432160433160434160435160436160437160438160439160440160441160442160443160444160445160446160447160448160449160450160451160452160453160454160455160456160457160458160459160460160461160462160463160464160465160466160467160468160469160470160471160472160473160474160475160476160477160478160479160480160481160482160483160484160485160486160487160488160489160490160491160492160493160494160495160496160497160498160499160500160501160502160503160504160505160506160507160508160509160510160511160512160513160514160515160516160517160518160519160520160521160522160523160524160525160526160527160528160529160530160531160532160533160534160535160536160537160538160539160540160541160542160543160544160545160546160547160548160549160550160551160552160553160554160555160556160557160558160559160560160561160562160563160564160565160566160567160568160569160570160571160572160573160574160575160576160577160578160579160580160581160582160583160584160585160586160587160588160589160590160591160592160593160594160595160596160597160598160599160600160601160602160603160604160605160606160607160608160609160610160611160612160613160614160615160616160617160618160619160620160621160622160623160624160625160626160627160628160629160630160631160632160633160634160635160636160637160638160639160640160641160642160643160644160645160646160647160648160649160650160651160652160653160654160655160656160657160658160659160660160661160662160663160664160665160666160667160668160669160670160671160672160673160674160675160676160677160678160679160680160681160682160683160684160685160686160687160688160689160690160691160692160693160694160695160696160697160698160699160700160701160702160703160704160705160706160707160708160709160710160711160712160713160714160715160716160717160718160719160720160721160722160723160724160725160726160727160728160729160730160731160732160733160734160735160736160737160738160739160740160741160742160743160744160745160746160747160748160749160750160751160752160753160754160755160756160757160758160759160760160761160762160763160764160765160766160767160768160769160770160771160772160773160774160775160776160777160778160779160780160781160782160783160784160785160786160787160788160789160790160791160792160793160794160795160796160797160798160799160800160801160802160803160804160805160806160807160808160809160810160811160812160813160814160815160816160817160818160819160820160821160822160823160824160825160826160827160828160829160830160831160832160833160834160835160836160837160838160839160840160841160842160843160844160845160846160847160848160849160850160851160852160853160854160855160856160857160858160859160860160861160862160863160864160865160866160867160868160869160870160871160872160873160874160875160876160877160878160879160880160881160882160883160884160885160886160887160888160889160890160891160892160893160894160895160896160897160898160899160900160901160902160903160904160905160906160907160908160909160910160911160912160913160914160915160916160917160918160919160920160921160922160923160924160925160926160927160928160929160930160931160932160933160934160935160936160937160938160939160940160941160942160943160944160945160946160947160948160949160950160951160952160953160954160955160956160957160958160959160960160961160962160963160964160965160966160967160968160969160970160971160972160973160974160975160976160977160978160979160980160981160982160983160984160985160986160987160988160989160990160991160992160993160994160995160996160997160998160999161000161001161002161003161004161005161006161007161008161009161010161011161012161013161014161015161016161017161018161019161020161021161022161023161024161025161026161027161028161029161030161031161032161033161034161035161036161037161038161039161040161041161042161043161044161045161046161047161048161049161050161051161052161053161054161055161056161057161058161059161060161061161062161063161064161065161066161067161068161069161070161071161072161073161074161075161076161077161078161079161080161081161082161083161084161085161086161087161088161089161090161091161092161093161094161095161096161097161098161099161100161101161102161103161104161105161106161107161108161109161110161111161112161113161114161115161116161117161118161119161120161121161122161123161124161125161126161127161128161129161130161131161132161133161134161135161136161137161138161139161140161141161142161143161144161145161146161147161148161149161150161151161152161153161154161155161156161157161158161159161160161161161162161163161164161165161166161167161168161169161170161171161172161173161174161175161176161177161178161179161180161181161182161183161184161185161186161187161188161189161190161191161192161193161194161195161196161197161198161199161200161201161202161203161204161205161206161207161208161209161210161211161212161213161214161215161216161217161218161219161220161221161222161223161224161225161226161227161228161229161230161231161232161233161234161235161236161237161238161239161240161241161242161243161244161245161246161247161248161249161250161251161252161253161254161255161256161257161258161259161260161261161262161263161264161265161266161267161268161269161270161271161272161273161274161275161276161277161278161279161280161281161282161283161284161285161286161287161288161289161290161291161292161293161294161295161296161297161298161299161300161301161302161303161304161305161306161307161308161309161310161311161312161313161314161315161316161317161318161319161320161321161322161323161324161325161326161327161328161329161330161331161332161333161334161335161336161337161338161339161340161341161342161343161344161345161346161347161348161349161350161351161352161353161354161355161356161357161358161359161360161361161362161363161364161365161366161367161368161369161370161371161372161373161374161375161376161377161378161379161380161381161382161383161384161385161386161387161388161389161390161391161392161393161394161395161396161397161398161399161400161401161402161403161404161405161406161407161408161409161410161411161412161413161414161415161416161417161418161419161420161421161422161423161424161425161426161427161428161429161430161431161432161433161434161435161436161437161438161439161440161441161442161443161444161445161446161447161448161449161450161451161452161453161454161455161456161457161458161459161460161461161462161463161464161465161466161467161468161469161470161471161472161473161474161475161476161477161478161479161480161481161482161483161484161485161486161487161488161489161490161491161492161493161494161495161496161497161498161499161500161501161502161503161504161505161506161507161508161509161510161511161512161513161514161515161516161517161518161519161520161521161522161523161524161525161526161527161528161529161530161531161532161533161534161535161536161537161538161539161540161541161542161543161544161545161546161547161548161549161550161551161552161553161554161555161556161557161558161559161560161561161562161563161564161565161566161567161568161569161570161571161572161573161574161575161576161577161578161579161580161581161582161583161584161585161586161587161588161589161590161591161592161593161594161595161596161597161598161599161600161601161602161603161604161605161606161607161608161609161610161611161612161613161614161615161616161617161618161619161620161621161622161623161624161625161626161627161628161629161630161631161632161633161634161635161636161637161638161639161640161641161642161643161644161645161646161647161648161649161650161651161652161653161654161655161656161657161658161659161660161661161662161663161664161665161666161667161668161669161670161671161672161673161674161675161676161677161678161679161680161681161682161683161684161685161686161687161688161689161690161691161692161693161694161695161696161697161698161699161700161701161702161703161704161705161706161707161708161709161710161711161712161713161714161715161716161717161718161719161720161721161722161723161724161725161726161727161728161729161730161731161732161733161734161735161736161737161738161739161740161741161742161743161744161745161746161747161748161749161750161751161752161753161754161755161756161757161758161759161760161761161762161763161764161765161766161767161768161769161770161771161772161773161774161775161776161777161778161779161780161781161782161783161784161785161786161787161788161789161790161791161792161793161794161795161796161797161798161799161800161801161802161803161804161805161806161807161808161809161810161811161812161813161814161815161816161817161818161819161820161821161822161823161824161825161826161827161828161829161830161831161832161833161834161835161836161837161838161839161840161841161842161843161844161845161846161847161848161849161850161851161852161853161854161855161856161857161858161859161860161861161862161863161864161865161866161867161868161869161870161871161872161873161874161875161876161877161878161879161880161881161882161883161884161885161886161887161888161889161890161891161892161893161894161895161896161897161898161899161900161901161902161903161904161905161906161907161908161909161910161911161912161913161914161915161916161917161918161919161920161921161922161923161924161925161926161927161928161929161930161931161932161933161934161935161936161937161938161939161940161941161942161943161944161945161946161947161948161949161950161951161952161953161954161955161956161957161958161959161960161961161962161963161964161965161966161967161968161969161970161971161972161973161974161975161976161977161978161979161980161981161982161983161984161985161986161987161988161989161990161991161992161993161994161995161996161997161998161999162000162001162002162003162004162005162006162007162008162009162010162011162012162013162014162015162016162017162018162019162020162021162022162023162024162025162026162027162028162029162030162031162032162033162034162035162036162037162038162039162040162041162042162043162044162045162046162047162048162049162050162051162052162053162054162055162056162057162058162059162060162061162062162063162064162065162066162067162068162069162070162071162072162073162074162075162076162077162078162079162080162081162082162083162084162085162086162087162088162089162090162091162092162093162094162095162096162097162098162099162100162101162102162103162104162105162106162107162108162109162110162111162112162113162114162115162116162117162118162119162120162121162122162123162124162125162126162127162128162129162130162131162132162133162134162135162136162137162138162139162140162141162142162143162144162145162146162147162148162149162150162151162152162153162154162155162156162157162158162159162160162161162162162163162164162165162166162167162168162169162170162171162172162173162174162175162176162177162178162179162180162181162182162183162184162185162186162187162188162189162190162191162192162193162194162195162196162197162198162199162200162201162202162203162204162205162206162207162208162209162210162211162212162213162214162215162216162217162218162219162220162221162222162223162224162225162226162227162228162229162230162231162232162233162234162235162236162237162238162239162240162241162242162243162244162245162246162247162248162249162250162251162252162253162254162255162256162257162258162259162260162261162262162263162264162265162266162267162268162269162270162271162272162273162274162275162276162277162278162279162280162281162282162283162284162285162286162287162288162289162290162291162292162293162294162295162296162297162298162299162300162301162302162303162304162305162306162307162308162309162310162311162312162313162314162315162316162317162318162319162320162321162322162323162324162325162326162327162328162329162330162331162332162333162334162335162336162337162338162339162340162341162342162343162344162345162346162347162348162349162350162351162352162353162354162355162356162357162358162359162360162361162362162363162364162365162366162367162368162369162370162371162372162373162374162375162376162377162378162379162380162381162382162383162384162385162386162387162388162389162390162391162392162393162394162395162396162397162398162399162400162401162402162403162404162405162406162407162408162409162410162411162412162413162414162415162416162417162418162419162420162421162422162423162424162425162426162427162428162429162430162431162432162433162434162435162436162437162438162439162440162441162442162443162444162445162446162447162448162449162450162451162452162453162454162455162456162457162458162459162460162461162462162463162464162465162466162467162468162469162470162471162472162473162474162475162476162477162478162479162480162481162482162483162484162485162486162487162488162489162490162491162492162493162494162495162496162497162498162499162500162501162502162503162504162505162506162507162508162509162510162511162512162513162514162515162516162517162518162519162520162521162522162523162524162525162526162527162528162529162530162531162532162533162534162535162536162537162538162539162540162541162542162543162544162545162546162547162548162549162550162551162552162553162554162555162556162557162558162559162560162561162562162563162564162565162566162567162568162569162570162571162572162573162574162575162576162577162578162579162580162581162582162583162584162585162586162587162588162589162590162591162592162593162594162595162596162597162598162599162600162601162602162603162604162605162606162607162608162609162610162611162612162613162614162615162616162617162618162619162620162621162622162623162624162625162626162627162628162629162630162631162632162633162634162635162636162637162638162639162640162641162642162643162644162645162646162647162648162649162650162651162652162653162654162655162656162657162658162659162660162661162662162663162664162665162666162667162668162669162670162671162672162673162674162675162676162677162678162679162680162681162682162683162684162685162686162687162688162689162690162691162692162693162694162695162696162697162698162699162700162701162702162703162704162705162706162707162708162709162710162711162712162713162714162715162716162717162718162719162720162721162722162723162724162725162726162727162728162729162730162731162732162733162734162735162736162737162738162739162740162741162742162743162744162745162746162747162748162749162750162751162752162753162754162755162756162757162758162759162760162761162762162763162764162765162766162767162768162769162770162771162772162773162774162775162776162777162778162779162780162781162782162783162784162785162786162787162788162789162790162791162792162793162794162795162796162797162798162799162800162801162802162803162804162805162806162807162808162809162810162811162812162813162814162815162816162817162818162819162820162821162822162823162824162825162826162827162828162829162830162831162832162833162834162835162836162837162838162839162840162841162842162843162844162845162846162847162848162849162850162851162852162853162854162855162856162857162858162859162860162861162862162863162864162865162866162867162868162869162870162871162872162873162874162875162876162877162878162879162880162881162882162883162884162885162886162887162888162889162890162891162892162893162894162895162896162897162898162899162900162901162902162903162904162905162906162907162908162909162910162911162912162913162914162915162916162917162918162919162920162921162922162923162924162925162926162927162928162929162930162931162932162933162934162935162936162937162938162939162940162941162942162943162944162945162946162947162948162949162950162951162952162953162954162955162956162957162958162959162960162961162962162963162964162965162966162967162968162969162970162971162972162973162974162975162976162977162978162979162980162981162982162983162984162985162986162987162988162989162990162991162992162993162994162995162996162997162998162999163000163001163002163003163004163005163006163007163008163009163010163011163012163013163014163015163016163017163018163019163020163021163022163023163024163025163026163027163028163029163030163031163032163033163034163035163036163037163038163039163040163041163042163043163044163045163046163047163048163049163050163051163052163053163054163055163056163057163058163059163060163061163062163063163064163065163066163067163068163069163070163071163072163073163074163075163076163077163078163079163080163081163082163083163084163085163086163087163088163089163090163091163092163093163094163095163096163097163098163099163100163101163102163103163104163105163106163107163108163109163110163111163112163113163114163115163116163117163118163119163120163121163122163123163124163125163126163127163128163129163130163131163132163133163134163135163136163137163138163139163140163141163142163143163144163145163146163147163148163149163150163151163152163153163154163155163156163157163158163159163160163161163162163163163164163165163166163167163168163169163170163171163172163173163174163175163176163177163178163179163180163181163182163183163184163185163186163187163188163189163190163191163192163193163194163195163196163197163198163199163200163201163202163203163204163205163206163207163208163209163210163211163212163213163214163215163216163217163218163219163220163221163222163223163224163225163226163227163228163229163230163231163232163233163234163235163236163237163238163239163240163241163242163243163244163245163246163247163248163249163250163251163252163253163254163255163256163257163258163259163260163261163262163263163264163265163266163267163268163269163270163271163272163273163274163275163276163277163278163279163280163281163282163283163284163285163286163287163288163289163290163291163292163293163294163295163296163297163298163299163300163301163302163303163304163305163306163307163308163309163310163311163312163313163314163315163316163317163318163319163320163321163322163323163324163325163326163327163328163329163330163331163332163333163334163335163336163337163338163339163340163341163342163343163344163345163346163347163348163349163350163351163352163353163354163355163356163357163358163359163360163361163362163363163364163365163366163367163368163369163370163371163372163373163374163375163376163377163378163379163380163381163382163383163384163385163386163387163388163389163390163391163392163393163394163395163396163397163398163399163400163401163402163403163404163405163406163407163408163409163410163411163412163413163414163415163416163417163418163419163420163421163422163423163424163425163426163427163428163429163430163431163432163433163434163435163436163437163438163439163440163441163442163443163444163445163446163447163448163449163450163451163452163453163454163455163456163457163458163459163460163461163462163463163464163465163466163467163468163469163470163471163472163473163474163475163476163477163478163479163480163481163482163483163484163485163486163487163488163489163490163491163492163493163494163495163496163497163498163499163500163501163502163503163504163505163506163507163508163509163510163511163512163513163514163515163516163517163518163519163520163521163522163523163524163525163526163527163528163529163530163531163532163533163534163535163536163537163538163539163540163541163542163543163544163545163546163547163548163549163550163551163552163553163554163555163556163557163558163559163560163561163562163563163564163565163566163567163568163569163570163571163572163573163574163575163576163577163578163579163580163581163582163583163584163585163586163587163588163589163590163591163592163593163594163595163596163597163598163599163600163601163602163603163604163605163606163607163608163609163610163611163612163613163614163615163616163617163618163619163620163621163622163623163624163625163626163627163628163629163630163631163632163633163634163635163636163637163638163639163640163641163642163643163644163645163646163647163648163649163650163651163652163653163654163655163656163657163658163659163660163661163662163663163664163665163666163667163668163669163670163671163672163673163674163675163676163677163678163679163680163681163682163683163684163685163686163687163688163689163690163691163692163693163694163695163696163697163698163699163700163701163702163703163704163705163706163707163708163709163710163711163712163713163714163715163716163717163718163719163720163721163722163723163724163725163726163727163728163729163730163731163732163733163734163735163736163737163738163739163740163741163742163743163744163745163746163747163748163749163750163751163752163753163754163755163756163757163758163759163760163761163762163763163764163765163766163767163768163769163770163771163772163773163774163775163776163777163778163779163780163781163782163783163784163785163786163787163788163789163790163791163792163793163794163795163796163797163798163799163800163801163802163803163804163805163806163807163808163809163810163811163812163813163814163815163816163817163818163819163820163821163822163823163824163825163826163827163828163829163830163831163832163833163834163835163836163837163838163839163840163841163842163843163844163845163846163847163848163849163850163851163852163853163854163855163856163857163858163859163860163861163862163863163864163865163866163867163868163869163870163871163872163873163874163875163876163877163878163879163880163881163882163883163884163885163886163887163888163889163890163891163892163893163894163895163896163897163898163899163900163901163902163903163904163905163906163907163908163909163910163911163912163913163914163915163916163917163918163919163920163921163922163923163924163925163926163927163928163929163930163931163932163933163934163935163936163937163938163939163940163941163942163943163944163945163946163947163948163949163950163951163952163953163954163955163956163957163958163959163960163961163962163963163964163965163966163967163968163969163970163971163972163973163974163975163976163977163978163979163980163981163982163983163984163985163986163987163988163989163990163991163992163993163994163995163996163997163998163999164000164001164002164003164004164005164006164007164008164009164010164011164012164013164014164015164016164017164018164019164020164021164022164023164024164025164026164027164028164029164030164031164032164033164034164035164036164037164038164039164040164041164042164043164044164045164046164047164048164049164050164051164052164053164054164055164056164057164058164059164060164061164062164063164064164065164066164067164068164069164070164071164072164073164074164075164076164077164078164079164080164081164082164083164084164085164086164087164088164089164090164091164092164093164094164095164096164097164098164099164100164101164102164103164104164105164106164107164108164109164110164111164112164113164114164115164116164117164118164119164120164121164122164123164124164125164126164127164128164129164130164131164132164133164134164135164136164137164138164139164140164141164142164143164144164145164146164147164148164149164150164151164152164153164154164155164156164157164158164159164160164161164162164163164164164165164166164167164168164169164170164171164172164173164174164175164176164177164178164179164180164181164182164183164184164185164186164187164188164189164190164191164192164193164194164195164196164197164198164199164200164201164202164203164204164205164206164207164208164209164210164211164212164213164214164215164216164217164218164219164220164221164222164223164224164225164226164227164228164229164230164231164232164233164234164235164236164237164238164239164240164241164242164243164244164245164246164247164248164249164250164251164252164253164254164255164256164257164258164259164260164261164262164263164264164265164266164267164268164269164270164271164272164273164274164275164276164277164278164279164280164281164282164283164284164285164286164287164288164289164290164291164292164293164294164295164296164297164298164299164300164301164302164303164304164305164306164307164308164309164310164311164312164313164314164315164316164317164318164319164320164321164322164323164324164325164326164327164328164329164330164331164332164333164334164335164336164337164338164339164340164341164342164343164344164345164346164347164348164349164350164351164352164353164354164355164356164357164358164359164360164361164362164363164364164365164366164367164368164369164370164371164372164373164374164375164376164377164378164379164380164381164382164383164384164385164386164387164388164389164390164391164392164393164394164395164396164397164398164399164400164401164402164403164404164405164406164407164408164409164410164411164412164413164414164415164416164417164418164419164420164421164422164423164424164425164426164427164428164429164430164431164432164433164434164435164436164437164438164439164440164441164442164443164444164445164446164447164448164449164450164451164452164453164454164455164456164457164458164459164460164461164462164463164464164465164466164467164468164469164470164471164472164473164474164475164476164477164478164479164480164481164482164483164484164485164486164487164488164489164490164491164492164493164494164495164496164497164498164499164500164501164502164503164504164505164506164507164508164509164510164511164512164513164514164515164516164517164518164519164520164521164522164523164524164525164526164527164528164529164530164531164532164533164534164535164536164537164538164539164540164541164542164543164544164545164546164547164548164549164550164551164552164553164554164555164556164557164558164559164560164561164562164563164564164565164566164567164568164569164570164571164572164573164574164575164576164577164578164579164580164581164582164583164584164585164586164587164588164589164590164591164592164593164594164595164596164597164598164599164600164601164602164603164604164605164606164607164608164609164610164611164612164613164614164615164616164617164618164619164620164621164622164623164624164625164626164627164628164629164630164631164632164633164634164635164636164637164638164639164640164641164642164643164644164645164646164647164648164649164650164651164652164653164654164655164656164657164658164659164660164661164662164663164664164665164666164667164668164669164670164671164672164673164674164675164676164677164678164679164680164681164682164683164684164685164686164687164688164689164690164691164692164693164694164695164696164697164698164699164700164701164702164703164704164705164706164707164708164709164710164711164712164713164714164715164716164717164718164719164720164721164722164723164724164725164726164727164728164729164730164731164732164733164734164735164736164737164738164739164740164741164742164743164744164745164746164747164748164749164750164751164752164753164754164755164756164757164758164759164760164761164762164763164764164765164766164767164768164769164770164771164772164773164774164775164776164777164778164779164780164781164782164783164784164785164786164787164788164789164790164791164792164793164794164795164796164797164798164799164800164801164802164803164804164805164806164807164808164809164810164811164812164813164814164815164816164817164818164819164820164821164822164823164824164825164826164827164828164829164830164831164832164833164834164835164836164837164838164839164840164841164842164843164844164845164846164847164848164849164850164851164852164853164854164855164856164857164858164859164860164861164862164863164864164865164866164867164868164869164870164871164872164873164874164875164876164877164878164879164880164881164882164883164884164885164886164887164888164889164890164891164892164893164894164895164896164897164898164899164900164901164902164903164904164905164906164907164908164909164910164911164912164913164914164915164916164917164918164919164920164921164922164923164924164925164926164927164928164929164930164931164932164933164934164935164936164937164938164939164940164941164942164943164944164945164946164947164948164949164950164951164952164953164954164955164956164957164958164959164960164961164962164963164964164965164966164967164968164969164970164971164972164973164974164975164976164977164978164979164980164981164982164983164984164985164986164987164988164989164990164991164992164993164994164995164996164997164998164999165000165001165002165003165004165005165006165007165008165009165010165011165012165013165014165015165016165017165018165019165020165021165022165023165024165025165026165027165028165029165030165031165032165033165034165035165036165037165038165039165040165041165042165043165044165045165046165047165048165049165050165051165052165053165054165055165056165057165058165059165060165061165062165063165064165065165066165067165068165069165070165071165072165073165074165075165076165077165078165079165080165081165082165083165084165085165086165087165088165089165090165091165092165093165094165095165096165097165098165099165100165101165102165103165104165105165106165107165108165109165110165111165112165113165114165115165116165117165118165119165120165121165122165123165124165125165126165127165128165129165130165131165132165133165134165135165136165137165138165139165140165141165142165143165144165145165146165147165148165149165150165151165152165153165154165155165156165157165158165159165160165161165162165163165164165165165166165167165168165169165170165171165172165173165174165175165176165177165178165179165180165181165182165183165184165185165186165187165188165189165190165191165192165193165194165195165196165197165198165199165200165201165202165203165204165205165206165207165208165209165210165211165212165213165214165215165216165217165218165219165220165221165222165223165224165225165226165227165228165229165230165231165232165233165234165235165236165237165238165239165240165241165242165243165244165245165246165247165248165249165250165251165252165253165254165255165256165257165258165259165260165261165262165263165264165265165266165267165268165269165270165271165272165273165274165275165276165277165278165279165280165281165282165283165284165285165286165287165288165289165290165291165292165293165294165295165296165297165298165299165300165301165302165303165304165305165306165307165308165309165310165311165312165313165314165315165316165317165318165319165320165321165322165323165324165325165326165327165328165329165330165331165332165333165334165335165336165337165338165339165340165341165342165343165344165345165346165347165348165349165350165351165352165353165354165355165356165357165358165359165360165361165362165363165364165365165366165367165368165369165370165371165372165373165374165375165376165377165378165379165380165381165382165383165384165385165386165387165388165389165390165391165392165393165394165395165396165397165398165399165400165401165402165403165404165405165406165407165408165409165410165411165412165413165414165415165416165417165418165419165420165421165422165423165424165425165426165427165428165429165430165431165432165433165434165435165436165437165438165439165440165441165442165443165444165445165446165447165448165449165450165451165452165453165454165455165456165457165458165459165460165461165462165463165464165465165466165467165468165469165470165471165472165473165474165475165476165477165478165479165480165481165482165483165484165485165486165487165488165489165490165491165492165493165494165495165496165497165498165499165500165501165502165503165504165505165506165507165508165509165510165511165512165513165514165515165516165517165518165519165520165521165522165523165524165525165526165527165528165529165530165531165532165533165534165535165536165537165538165539165540165541165542165543165544165545165546165547165548165549165550165551165552165553165554165555165556165557165558165559165560165561165562165563165564165565165566165567165568165569165570165571165572165573165574165575165576165577165578165579165580165581165582165583165584165585165586165587165588165589165590165591165592165593165594165595165596165597165598165599165600165601165602165603165604165605165606165607165608165609165610165611165612165613165614165615165616165617165618165619165620165621165622165623165624165625165626165627165628165629165630165631165632165633165634165635165636165637165638165639165640165641165642165643165644165645165646165647165648165649165650165651165652165653165654165655165656165657165658165659165660165661165662165663165664165665165666165667165668165669165670165671165672165673165674165675165676165677165678165679165680165681165682165683165684165685165686165687165688165689165690165691165692165693165694165695165696165697165698165699165700165701165702165703165704165705165706165707165708165709165710165711165712165713165714165715165716165717165718165719165720165721165722165723165724165725165726165727165728165729165730165731165732165733165734165735165736165737165738165739165740165741165742165743165744165745165746165747165748165749165750165751165752165753165754165755165756165757165758165759165760165761165762165763165764165765165766165767165768165769165770165771165772165773165774165775165776165777165778165779165780165781165782165783165784165785165786165787165788165789165790165791165792165793165794165795165796165797165798165799165800165801165802165803165804165805165806165807165808165809165810165811165812165813165814165815165816165817165818165819165820165821165822165823165824165825165826165827165828165829165830165831165832165833165834165835165836165837165838165839165840165841165842165843165844165845165846165847165848165849165850165851165852165853165854165855165856165857165858165859165860165861165862165863165864165865165866165867165868165869165870165871165872165873165874165875165876165877165878165879165880165881165882165883165884165885165886165887165888165889165890165891165892165893165894165895165896165897165898165899165900165901165902165903165904165905165906165907165908165909165910165911165912165913165914165915165916165917165918165919165920165921165922165923165924165925165926165927165928165929165930165931165932165933165934165935165936165937165938165939165940165941165942165943165944165945165946165947165948165949165950165951165952165953165954165955165956165957165958165959165960165961165962165963165964165965165966165967165968165969165970165971165972165973165974165975165976165977165978165979165980165981165982165983165984165985165986165987165988165989165990165991165992165993165994165995165996165997165998165999166000166001166002166003166004166005166006166007166008166009166010166011166012166013166014166015166016166017166018166019166020166021166022166023166024166025166026166027166028166029166030166031166032166033166034166035166036166037166038166039166040166041166042166043166044166045166046166047166048166049166050166051166052166053166054166055166056166057166058166059166060166061166062166063166064166065166066166067166068166069166070166071166072166073166074166075166076166077166078166079166080166081166082166083166084166085166086166087166088166089166090166091166092166093166094166095166096166097166098166099166100166101166102166103166104166105166106166107166108166109166110166111166112166113166114166115166116166117166118166119166120166121166122166123166124166125166126166127166128166129166130166131166132166133166134166135166136166137166138166139166140166141166142166143166144166145166146166147166148166149166150166151166152166153166154166155166156166157166158166159166160166161166162166163166164166165166166166167166168166169166170166171166172166173166174166175166176166177166178166179166180166181166182166183166184166185166186166187166188166189166190166191166192166193166194166195166196166197166198166199166200166201166202166203166204166205166206166207166208166209166210166211166212166213166214166215166216166217166218166219166220166221166222166223166224166225166226166227166228166229166230166231166232166233166234166235166236166237166238166239166240166241166242166243166244166245166246166247166248166249166250166251166252166253166254166255166256166257166258166259166260166261166262166263166264166265166266166267166268166269166270166271166272166273166274166275166276166277166278166279166280166281166282166283166284166285166286166287166288166289166290166291166292166293166294166295166296166297166298166299166300166301166302166303166304166305166306166307166308166309166310166311166312166313166314166315166316166317166318166319166320166321166322166323166324166325166326166327166328166329166330166331166332166333166334166335166336166337166338166339166340166341166342166343166344166345166346166347166348166349166350166351166352166353166354166355166356166357166358166359166360166361166362166363166364166365166366166367166368166369166370166371166372166373166374166375166376166377166378166379166380166381166382166383166384166385166386166387166388166389166390166391166392166393166394166395166396166397166398166399166400166401166402166403166404166405166406166407166408166409166410166411166412166413166414166415166416166417166418166419166420166421166422166423166424166425166426166427166428166429166430166431166432166433166434166435166436166437166438166439166440166441166442166443166444166445166446166447166448166449166450166451166452166453166454166455166456166457166458166459166460166461166462166463166464166465166466166467166468166469166470166471166472166473166474166475166476166477166478166479166480166481166482166483166484166485166486166487166488166489166490166491166492166493166494166495166496166497166498166499166500166501166502166503166504166505166506166507166508166509166510166511166512166513166514166515166516166517166518166519166520166521166522166523166524166525166526166527166528166529166530166531166532166533166534166535166536166537166538166539166540166541166542166543166544166545166546166547166548166549166550166551166552166553166554166555166556166557166558166559166560166561166562166563166564166565166566166567166568166569166570166571166572166573166574166575166576166577166578166579166580166581166582166583166584166585166586166587166588166589166590166591166592166593166594166595166596166597166598166599166600166601166602166603166604166605166606166607166608166609166610166611166612166613166614166615166616166617166618166619166620166621166622166623166624166625166626166627166628166629166630166631166632166633166634166635166636166637166638166639166640166641166642166643166644166645166646166647166648166649166650166651166652166653166654166655166656166657166658166659166660166661166662166663166664166665166666166667166668166669166670166671166672166673166674166675166676166677166678166679166680166681166682166683166684166685166686166687166688166689166690166691166692166693166694166695166696166697166698166699166700166701166702166703166704166705166706166707166708166709166710166711166712166713166714166715166716166717166718166719166720166721166722166723166724166725166726166727166728166729166730166731166732166733166734166735166736166737166738166739166740166741166742166743166744166745166746166747166748166749166750166751166752166753166754166755166756166757166758166759166760166761166762166763166764166765166766166767166768166769166770166771166772166773166774166775166776166777166778166779166780166781166782166783166784166785166786166787166788166789166790166791166792166793166794166795166796166797166798166799166800166801166802166803166804166805166806166807166808166809166810166811166812166813166814166815166816166817166818166819166820166821166822166823166824166825166826166827166828166829166830166831166832166833166834166835166836166837166838166839166840166841166842166843166844166845166846166847166848166849166850166851166852166853166854166855166856166857166858166859166860166861166862166863166864166865166866166867166868166869166870166871166872166873166874166875166876166877166878166879166880166881166882166883166884166885166886166887166888166889166890166891166892166893166894166895166896166897166898166899166900166901166902166903166904166905166906166907166908166909166910166911166912166913166914166915166916166917166918166919166920166921166922166923166924166925166926166927166928166929166930166931166932166933166934166935166936166937166938166939166940166941166942166943166944166945166946166947166948166949166950166951166952166953166954166955166956166957166958166959166960166961166962166963166964166965166966166967166968166969166970166971166972166973166974166975166976166977166978166979166980166981166982166983166984166985166986166987166988166989166990166991166992166993166994166995166996166997166998166999167000167001167002167003167004167005167006167007167008167009167010167011167012167013167014167015167016167017167018167019167020167021167022167023167024167025167026167027167028167029167030167031167032167033167034167035167036167037167038167039167040167041167042167043167044167045167046167047167048167049167050167051167052167053167054167055167056167057167058167059167060167061167062167063167064167065167066167067167068167069167070167071167072167073167074167075167076167077167078167079167080167081167082167083167084167085167086167087167088167089167090167091167092167093167094167095167096167097167098167099167100167101167102167103167104167105167106167107167108167109167110167111167112167113167114167115167116167117167118167119167120167121167122167123167124167125167126167127167128167129167130167131167132167133167134167135167136167137167138167139167140167141167142167143167144167145167146167147167148167149167150167151167152167153167154167155167156167157167158167159167160167161167162167163167164167165167166167167167168167169167170167171167172167173167174167175167176167177167178167179167180167181167182167183167184167185167186167187167188167189167190167191167192167193167194167195167196167197167198167199167200167201167202167203167204167205167206167207167208167209167210167211167212167213167214167215167216167217167218167219167220167221167222167223167224167225167226167227167228167229167230167231167232167233167234167235167236167237167238167239167240167241167242167243167244167245167246167247167248167249167250167251167252167253167254167255167256167257167258167259167260167261167262167263167264167265167266167267167268167269167270167271167272167273167274167275167276167277167278167279167280167281167282167283167284167285167286167287167288167289167290167291167292167293167294167295167296167297167298167299167300167301167302167303167304167305167306167307167308167309167310167311167312167313167314167315167316167317167318167319167320167321167322167323167324167325167326167327167328167329167330167331167332167333167334167335167336167337167338167339167340167341167342167343167344167345167346167347167348167349167350167351167352167353167354167355167356167357167358167359167360167361167362167363167364167365167366167367167368167369167370167371167372167373167374167375167376167377167378167379167380167381167382167383167384167385167386167387167388167389167390167391167392167393167394167395167396167397167398167399167400167401167402167403167404167405167406167407167408167409167410167411167412167413167414167415167416167417167418167419167420167421167422167423167424167425167426167427167428167429167430167431167432167433167434167435167436167437167438167439167440167441167442167443167444167445167446167447167448167449167450167451167452167453167454167455167456167457167458167459167460167461167462167463167464167465167466167467167468167469167470167471167472167473167474167475167476167477167478167479167480167481167482167483167484167485167486167487167488167489167490167491167492167493167494167495167496167497167498167499167500167501167502167503167504167505167506167507167508167509167510167511167512167513167514167515167516167517167518167519167520167521167522167523167524167525167526167527167528167529167530167531167532167533167534167535167536167537167538167539167540167541167542167543167544167545167546167547167548167549167550167551167552167553167554167555167556167557167558167559167560167561167562167563167564167565167566167567167568167569167570167571167572167573167574167575167576167577167578167579167580167581167582167583167584167585167586167587167588167589167590167591167592167593167594167595167596167597167598167599167600167601167602167603167604167605167606167607167608167609167610167611167612167613167614167615167616167617167618167619167620167621167622167623167624167625167626167627167628167629167630167631167632167633167634167635167636167637167638167639167640167641167642167643167644167645167646167647167648167649167650167651167652167653167654167655167656167657167658167659167660167661167662167663167664167665167666167667167668167669167670167671167672167673167674167675167676167677167678167679167680167681167682167683167684167685167686167687167688167689167690167691167692167693167694167695167696167697167698167699167700167701167702167703167704167705167706167707167708167709167710167711167712167713167714167715167716167717167718167719167720167721167722167723167724167725167726167727167728167729167730167731167732167733167734167735167736167737167738167739167740167741167742167743167744167745167746167747167748167749167750167751167752167753167754167755167756167757167758167759167760167761167762167763167764167765167766167767167768167769167770167771167772167773167774167775167776167777167778167779167780167781167782167783167784167785167786167787167788167789167790167791167792167793167794167795167796167797167798167799167800167801167802167803167804167805167806167807167808167809167810167811167812167813167814167815167816167817167818167819167820167821167822167823167824167825167826167827167828167829167830167831167832167833167834167835167836167837167838167839167840167841167842167843167844167845167846167847167848167849167850167851167852167853167854167855167856167857167858167859167860167861167862167863167864167865167866167867167868167869167870167871167872167873167874167875167876167877167878167879167880167881167882167883167884167885167886167887167888167889167890167891167892167893167894167895167896167897167898167899167900167901167902167903167904167905167906167907167908167909167910167911167912167913167914167915167916167917167918167919167920167921167922167923167924167925167926167927167928167929167930167931167932167933167934167935167936167937167938167939167940167941167942167943167944167945167946167947167948167949167950167951167952167953167954167955167956167957167958167959167960167961167962167963167964167965167966167967167968167969167970167971167972167973167974167975167976167977167978167979167980167981167982167983167984167985167986167987167988167989167990167991167992167993167994167995167996167997167998167999168000168001168002168003168004168005168006168007168008168009168010168011168012168013168014168015168016168017168018168019168020168021168022168023168024168025168026168027168028168029168030168031168032168033168034168035168036168037168038168039168040168041168042168043168044168045168046168047168048168049168050168051168052168053168054168055168056168057168058168059168060168061168062168063168064168065168066168067168068168069168070168071168072168073168074168075168076168077168078168079168080168081168082168083168084168085168086168087168088168089168090168091168092168093168094168095168096168097168098168099168100168101168102168103168104168105168106168107168108168109168110168111168112168113168114168115168116168117168118168119168120168121168122168123168124168125168126168127168128168129168130168131168132168133168134168135168136168137168138168139168140168141168142168143168144168145168146168147168148168149168150168151168152168153168154168155168156168157168158168159168160168161168162168163168164168165168166168167168168168169168170168171168172168173168174168175168176168177168178168179168180168181168182168183168184168185168186168187168188168189168190168191168192168193168194168195168196168197168198168199168200168201168202168203168204168205168206168207168208168209168210168211168212168213168214168215168216168217168218168219168220168221168222168223168224168225168226168227168228168229168230168231168232168233168234168235168236168237168238168239168240168241168242168243168244168245168246168247168248168249168250168251168252168253168254168255168256168257168258168259168260168261168262168263168264168265168266168267168268168269168270168271168272168273168274168275168276168277168278168279168280168281168282168283168284168285168286168287168288168289168290168291168292168293168294168295168296168297168298168299168300168301168302168303168304168305168306168307168308168309168310168311168312168313168314168315168316168317168318168319168320168321168322168323168324168325168326168327168328168329168330168331168332168333168334168335168336168337168338168339168340168341168342168343168344168345168346168347168348168349168350168351168352168353168354168355168356168357168358168359168360168361168362168363168364168365168366168367168368168369168370168371168372168373168374168375168376168377168378168379168380168381168382168383168384168385168386168387168388168389168390168391168392168393168394168395168396168397168398168399168400168401168402168403168404168405168406168407168408168409168410168411168412168413168414168415168416168417168418168419168420168421168422168423168424168425168426168427168428168429168430168431168432168433168434168435168436168437168438168439168440168441168442168443168444168445168446168447168448168449168450168451168452168453168454168455168456168457168458168459168460168461168462168463168464168465168466168467168468168469168470168471168472168473168474168475168476168477168478168479168480168481168482168483168484168485168486168487168488168489168490168491168492168493168494168495168496168497168498168499168500168501168502168503168504168505168506168507168508168509168510168511168512168513168514168515168516168517168518168519168520168521168522168523168524168525168526168527168528168529168530168531168532168533168534168535168536168537168538168539168540168541168542168543168544168545168546168547168548168549168550168551168552168553168554168555168556168557168558168559168560168561168562168563168564168565168566168567168568168569168570168571168572168573168574168575168576168577168578168579168580168581168582168583168584168585168586168587168588168589168590168591168592168593168594168595168596168597168598168599168600168601168602168603168604168605168606168607168608168609168610168611168612168613168614168615168616168617168618168619168620168621168622168623168624168625168626168627168628168629168630168631168632168633168634168635168636168637168638168639168640168641168642168643168644168645168646168647168648168649168650168651168652168653168654168655168656168657168658168659168660168661168662168663168664168665168666168667168668168669168670168671168672168673168674168675168676168677168678168679168680168681168682168683168684168685168686168687168688168689168690168691168692168693168694168695168696168697168698168699168700168701168702168703168704168705168706168707168708168709168710168711168712168713168714168715168716168717168718168719168720168721168722168723168724168725168726168727168728168729168730168731168732168733168734168735168736168737168738168739168740168741168742168743168744168745168746168747168748168749168750168751168752168753168754168755168756168757168758168759168760168761168762168763168764168765168766168767168768168769168770168771168772168773168774168775168776168777168778168779168780168781168782168783168784168785168786168787168788168789168790168791168792168793168794168795168796168797168798168799168800168801168802168803168804168805168806168807168808168809168810168811168812168813168814168815168816168817168818168819168820168821168822168823168824168825168826168827168828168829168830168831168832168833168834168835168836168837168838168839168840168841168842168843168844168845168846168847168848168849168850168851168852168853168854168855168856168857168858168859168860168861168862168863168864168865168866168867168868168869168870168871168872168873168874168875168876168877168878168879168880168881168882168883168884168885168886168887168888168889168890168891168892168893168894168895168896168897168898168899168900168901168902168903168904168905168906168907168908168909168910168911168912168913168914168915168916168917168918168919168920168921168922168923168924168925168926168927168928168929168930168931168932168933168934168935168936168937168938168939168940168941168942168943168944168945168946168947168948168949168950168951168952168953168954168955168956168957168958168959168960168961168962168963168964168965168966168967168968168969168970168971168972168973168974168975168976168977168978168979168980168981168982168983168984168985168986168987168988168989168990168991168992168993168994168995168996168997168998168999169000169001169002169003169004169005169006169007169008169009169010169011169012169013169014169015169016169017169018169019169020169021169022169023169024169025169026169027169028169029169030169031169032169033169034169035169036169037169038169039169040169041169042169043169044169045169046169047169048169049169050169051169052169053169054169055169056169057169058169059169060169061169062169063169064169065169066169067169068169069169070169071169072169073169074169075169076169077169078169079169080169081169082169083169084169085169086169087169088169089169090169091169092169093169094169095169096169097169098169099169100169101169102169103169104169105169106169107169108169109169110169111169112169113169114169115169116169117169118169119169120169121169122169123169124169125169126169127169128169129169130169131169132169133169134169135169136169137169138169139169140169141169142169143169144169145169146169147169148169149169150169151169152169153169154169155169156169157169158169159169160169161169162169163169164169165169166169167169168169169169170169171169172169173169174169175169176169177169178169179169180169181169182169183169184169185169186169187169188169189169190169191169192169193169194169195169196169197169198169199169200169201169202169203169204169205169206169207169208169209169210169211169212169213169214169215169216169217169218169219169220169221169222169223169224169225169226169227169228169229169230169231169232169233169234169235169236169237169238169239169240169241169242169243169244169245169246169247169248169249169250169251169252169253169254169255169256169257169258169259169260169261169262169263169264169265169266169267169268169269169270169271169272169273169274169275169276169277169278169279169280169281169282169283169284169285169286169287169288169289169290169291169292169293169294169295169296169297169298169299169300169301169302169303169304169305169306169307169308169309169310169311169312169313169314169315169316169317169318169319169320169321169322169323169324169325169326169327169328169329169330169331169332169333169334169335169336169337169338169339169340169341169342169343169344169345169346169347169348169349169350169351169352169353169354169355169356169357169358169359169360169361169362169363169364169365169366169367169368169369169370169371169372169373169374169375169376169377169378169379169380169381169382169383169384169385169386169387169388169389169390169391169392169393169394169395169396169397169398169399169400169401169402169403169404169405169406169407169408169409169410169411169412169413169414169415169416169417169418169419169420169421169422169423169424169425169426169427169428169429169430169431169432169433169434169435169436169437169438169439169440169441169442169443169444169445169446169447169448169449169450169451169452169453169454169455169456169457169458169459169460169461169462169463169464169465169466169467169468169469169470169471169472169473169474169475169476169477169478169479169480169481169482169483169484169485169486169487169488169489169490169491169492169493169494169495169496169497169498169499169500169501169502169503169504169505169506169507169508169509169510169511169512169513169514169515169516169517169518169519169520169521169522169523169524169525169526169527169528169529169530169531169532169533169534169535169536169537169538169539169540169541169542169543169544169545169546169547169548169549169550169551169552169553169554169555169556169557169558169559169560169561169562169563169564169565169566169567169568169569169570169571169572169573169574169575169576169577169578169579169580169581169582169583169584169585169586169587169588169589169590169591169592169593169594169595169596169597169598169599169600169601169602169603169604169605169606169607169608169609169610169611169612169613169614169615169616169617169618169619169620169621169622169623169624169625169626169627169628169629169630169631169632169633169634169635169636169637169638169639169640169641169642169643169644169645169646169647169648169649169650169651169652169653169654169655169656169657169658169659169660169661169662169663169664169665169666169667169668169669169670169671169672169673169674169675169676169677169678169679169680169681169682169683169684169685169686169687169688169689169690169691169692169693169694169695169696169697169698169699169700169701169702169703169704169705169706169707169708169709169710169711169712169713169714169715169716169717169718169719169720169721169722169723169724169725169726169727169728169729169730169731169732169733169734169735169736169737169738169739169740169741169742169743169744169745169746169747169748169749169750169751169752169753169754169755169756169757169758169759169760169761169762169763169764169765169766169767169768169769169770169771169772169773169774169775169776169777169778169779169780169781169782169783169784169785169786169787169788169789169790169791169792169793169794169795169796169797169798169799169800169801169802169803169804169805169806169807169808169809169810169811169812169813169814169815169816169817169818169819169820169821169822169823169824169825169826169827169828169829169830169831169832169833169834169835169836169837169838169839169840169841169842169843169844169845169846169847169848169849169850169851169852169853169854169855169856169857169858169859169860169861169862169863169864169865169866169867169868169869169870169871169872169873169874169875169876169877169878169879169880169881169882169883169884169885169886169887169888169889169890169891169892169893169894169895169896169897169898169899169900169901169902169903169904169905169906169907169908169909169910169911169912169913169914169915169916169917169918169919169920169921169922169923169924169925169926169927169928169929169930169931169932169933169934169935169936169937169938169939169940169941169942169943169944169945169946169947169948169949169950169951169952169953169954169955169956169957169958169959169960169961169962169963169964169965169966169967169968169969169970169971169972169973169974169975169976169977169978169979169980169981169982169983169984169985169986169987169988169989169990169991169992169993169994169995169996169997169998169999170000170001170002170003170004170005170006170007170008170009170010170011170012170013170014170015170016170017170018170019170020170021170022170023170024170025170026170027170028170029170030170031170032170033170034170035170036170037170038170039170040170041170042170043170044170045170046170047170048170049170050170051170052170053170054170055170056170057170058170059170060170061170062170063170064170065170066170067170068170069170070170071170072170073170074170075170076170077170078170079170080170081170082170083170084170085170086170087170088170089170090170091170092170093170094170095170096170097170098170099170100170101170102170103170104170105170106170107170108170109170110170111170112170113170114170115170116170117170118170119170120170121170122170123170124170125170126170127170128170129170130170131170132170133170134170135170136170137170138170139170140170141170142170143170144170145170146170147170148170149170150170151170152170153170154170155170156170157170158170159170160170161170162170163170164170165170166170167170168170169170170170171170172170173170174170175170176170177170178170179170180170181170182170183170184170185170186170187170188170189170190170191170192170193170194170195170196170197170198170199170200170201170202170203170204170205170206170207170208170209170210170211170212170213170214170215170216170217170218170219170220170221170222170223170224170225170226170227170228170229170230170231170232170233170234170235170236170237170238170239170240170241170242170243170244170245170246170247170248170249170250170251170252170253170254170255170256170257170258170259170260170261170262170263170264170265170266170267170268170269170270170271170272170273170274170275170276170277170278170279170280170281170282170283170284170285170286170287170288170289170290170291170292170293170294170295170296170297170298170299170300170301170302170303170304170305170306170307170308170309170310170311170312170313170314170315170316170317170318170319170320170321170322170323170324170325170326170327170328170329170330170331170332170333170334170335170336170337170338170339170340170341170342170343170344170345170346170347170348170349170350170351170352170353170354170355170356170357170358170359170360170361170362170363170364170365170366170367170368170369170370170371170372170373170374170375170376170377170378170379170380170381170382170383170384170385170386170387170388170389170390170391170392170393170394170395170396170397170398170399170400170401170402170403170404170405170406170407170408170409170410170411170412170413170414170415170416170417170418170419170420170421170422170423170424170425170426170427170428170429170430170431170432170433170434170435170436170437170438170439170440170441170442170443170444170445170446170447170448170449170450170451170452170453170454170455170456170457170458170459170460170461170462170463170464170465170466170467170468170469170470170471170472170473170474170475170476170477170478170479170480170481170482170483170484170485170486170487170488170489170490170491170492170493170494170495170496170497170498170499170500170501170502170503170504170505170506170507170508170509170510170511170512170513170514170515170516170517170518170519170520170521170522170523170524170525170526170527170528170529170530170531170532170533170534170535170536170537170538170539170540170541170542170543170544170545170546170547170548170549170550170551170552170553170554170555170556170557170558170559170560170561170562170563170564170565170566170567170568170569170570170571170572170573170574170575170576170577170578170579170580170581170582170583170584170585170586170587170588170589170590170591170592170593170594170595170596170597170598170599170600170601170602170603170604170605170606170607170608170609170610170611170612170613170614170615170616170617170618170619170620170621170622170623170624170625170626170627170628170629170630170631170632170633170634170635170636170637170638170639170640170641170642170643170644170645170646170647170648170649170650170651170652170653170654170655170656170657170658170659170660170661170662170663170664170665170666170667170668170669170670170671170672170673170674170675170676170677170678170679170680170681170682170683170684170685170686170687170688170689170690170691170692170693170694170695170696170697170698170699170700170701170702170703170704170705170706170707170708170709170710170711170712170713170714170715170716170717170718170719170720170721170722170723170724170725170726170727170728170729170730170731170732170733170734170735170736170737170738170739170740170741170742170743170744170745170746170747170748170749170750170751170752170753170754170755170756170757170758170759170760170761170762170763170764170765170766170767170768170769170770170771170772170773170774170775170776170777170778170779170780170781170782170783170784170785170786170787170788170789170790170791170792170793170794170795170796170797170798170799170800170801170802170803170804170805170806170807170808170809170810170811170812170813170814170815170816170817170818170819170820170821170822170823170824170825170826170827170828170829170830170831170832170833170834170835170836170837170838170839170840170841170842170843170844170845170846170847170848170849170850170851170852170853170854170855170856170857170858170859170860170861170862170863170864170865170866170867170868170869170870170871170872170873170874170875170876170877170878170879170880170881170882170883170884170885170886170887170888170889170890170891170892170893170894170895170896170897170898170899170900170901170902170903170904170905170906170907170908170909170910170911170912170913170914170915170916170917170918170919170920170921170922170923170924170925170926170927170928170929170930170931170932170933170934170935170936170937170938170939170940170941170942170943170944170945170946170947170948170949170950170951170952170953170954170955170956170957170958170959170960170961170962170963170964170965170966170967170968170969170970170971170972170973170974170975170976170977170978170979170980170981170982170983170984170985170986170987170988170989170990170991170992170993170994170995170996170997170998170999171000171001171002171003171004171005171006171007171008171009171010171011171012171013171014171015171016171017171018171019171020171021171022171023171024171025171026171027171028171029171030171031171032171033171034171035171036171037171038171039171040171041171042171043171044171045171046171047171048171049171050171051171052171053171054171055171056171057171058171059171060171061171062171063171064171065171066171067171068171069171070171071171072171073171074171075171076171077171078171079171080171081171082171083171084171085171086171087171088171089171090171091171092171093171094171095171096171097171098171099171100171101171102171103171104171105171106171107171108171109171110171111171112171113171114171115171116171117171118171119171120171121171122171123171124171125171126171127171128171129171130171131171132171133171134171135171136171137171138171139171140171141171142171143171144171145171146171147171148171149171150171151171152171153171154171155171156171157171158171159171160171161171162171163171164171165171166171167171168171169171170171171171172171173171174171175171176171177171178171179171180171181171182171183171184171185171186171187171188171189171190171191171192171193171194171195171196171197171198171199171200171201171202171203171204171205171206171207171208171209171210171211171212171213171214171215171216171217171218171219171220171221171222171223171224171225171226171227171228171229171230171231171232171233171234171235171236171237171238171239171240171241171242171243171244171245171246171247171248171249171250171251171252171253171254171255171256171257171258171259171260171261171262171263171264171265171266171267171268171269171270171271171272171273171274171275171276171277171278171279171280171281171282171283171284171285171286171287171288171289171290171291171292171293171294171295171296171297171298171299171300171301171302171303171304171305171306171307171308171309171310171311171312171313171314171315171316171317171318171319171320171321171322171323171324171325171326171327171328171329171330171331171332171333171334171335171336171337171338171339171340171341171342171343171344171345171346171347171348171349171350171351171352171353171354171355171356171357171358171359171360171361171362171363171364171365171366171367171368171369171370171371171372171373171374171375171376171377171378171379171380171381171382171383171384171385171386171387171388171389171390171391171392171393171394171395171396171397171398171399171400171401171402171403171404171405171406171407171408171409171410171411171412171413171414171415171416171417171418171419171420171421171422171423171424171425171426171427171428171429171430171431171432171433171434171435171436171437171438171439171440171441171442171443171444171445171446171447171448171449171450171451171452171453171454171455171456171457171458171459171460171461171462171463171464171465171466171467171468171469171470171471171472171473171474171475171476171477171478171479171480171481171482171483171484171485171486171487171488171489171490171491171492171493171494171495171496171497171498171499171500171501171502171503171504171505171506171507171508171509171510171511171512171513171514171515171516171517171518171519171520171521171522171523171524171525171526171527171528171529171530171531171532171533171534171535171536171537171538171539171540171541171542171543171544171545171546171547171548171549171550171551171552171553171554171555171556171557171558171559171560171561171562171563171564171565171566171567171568171569171570171571171572171573171574171575171576171577171578171579171580171581171582171583171584171585171586171587171588171589171590171591171592171593171594171595171596171597171598171599171600171601171602171603171604171605171606171607171608171609171610171611171612171613171614171615171616171617171618171619171620171621171622171623171624171625171626171627171628171629171630171631171632171633171634171635171636171637171638171639171640171641171642171643171644171645171646171647171648171649171650171651171652171653171654171655171656171657171658171659171660171661171662171663171664171665171666171667171668171669171670171671171672171673171674171675171676171677171678171679171680171681171682171683171684171685171686171687171688171689171690171691171692171693171694171695171696171697171698171699171700171701171702171703171704171705171706171707171708171709171710171711171712171713171714171715171716171717171718171719171720171721171722171723171724171725171726171727171728171729171730171731171732171733171734171735171736171737171738171739171740171741171742171743171744171745171746171747171748171749171750171751171752171753171754171755171756171757171758171759171760171761171762171763171764171765171766171767171768171769171770171771171772171773171774171775171776171777171778171779171780171781171782171783171784171785171786171787171788171789171790171791171792171793171794171795171796171797171798171799171800171801171802171803171804171805171806171807171808171809171810171811171812171813171814171815171816171817171818171819171820171821171822171823171824171825171826171827171828171829171830171831171832171833171834171835171836171837171838171839171840171841171842171843171844171845171846171847171848171849171850171851171852171853171854171855171856171857171858171859171860171861171862171863171864171865171866171867171868171869171870171871171872171873171874171875171876171877171878171879171880171881171882171883171884171885171886171887171888171889171890171891171892171893171894171895171896171897171898171899171900171901171902171903171904171905171906171907171908171909171910171911171912171913171914171915171916171917171918171919171920171921171922171923171924171925171926171927171928171929171930171931171932171933171934171935171936171937171938171939171940171941171942171943171944171945171946171947171948171949171950171951171952171953171954171955171956171957171958171959171960171961171962171963171964171965171966171967171968171969171970171971171972171973171974171975171976171977171978171979171980171981171982171983171984171985171986171987171988171989171990171991171992171993171994171995171996171997171998171999172000172001172002172003172004172005172006172007172008172009172010172011172012172013172014172015172016172017172018172019172020172021172022172023172024172025172026172027172028172029172030172031172032172033172034172035172036172037172038172039172040172041172042172043172044172045172046172047172048172049172050172051172052172053172054172055172056172057172058172059172060172061172062172063172064172065172066172067172068172069172070172071172072172073172074172075172076172077172078172079172080172081172082172083172084172085172086172087172088172089172090172091172092172093172094172095172096172097172098172099172100172101172102172103172104172105172106172107172108172109172110172111172112172113172114172115172116172117172118172119172120172121172122172123172124172125172126172127172128172129172130172131172132172133172134172135172136172137172138172139172140172141172142172143172144172145172146172147172148172149172150172151172152172153172154172155172156172157172158172159172160172161172162172163172164172165172166172167172168172169172170172171172172172173172174172175172176172177172178172179172180172181172182172183172184172185172186172187172188172189172190172191172192172193172194172195172196172197172198172199172200172201172202172203172204172205172206172207172208172209172210172211172212172213172214172215172216172217172218172219172220172221172222172223172224172225172226172227172228172229172230172231172232172233172234172235172236172237172238172239172240172241172242172243172244172245172246172247172248172249172250172251172252172253172254172255172256172257172258172259172260172261172262172263172264172265172266172267172268172269172270172271172272172273172274172275172276172277172278172279172280172281172282172283172284172285172286172287172288172289172290172291172292172293172294172295172296172297172298172299172300172301172302172303172304172305172306172307172308172309172310172311172312172313172314172315172316172317172318172319172320172321172322172323172324172325172326172327172328172329172330172331172332172333172334172335172336172337172338172339172340172341172342172343172344172345172346172347172348172349172350172351172352172353172354172355172356172357172358172359172360172361172362172363172364172365172366172367172368172369172370172371172372172373172374172375172376172377172378172379172380172381172382172383172384172385172386172387172388172389172390172391172392172393172394172395172396172397172398172399172400172401172402172403172404172405172406172407172408172409172410172411172412172413172414172415172416172417172418172419172420172421172422172423172424172425172426172427172428172429172430172431172432172433172434172435172436172437172438172439172440172441172442172443172444172445172446172447172448172449172450172451172452172453172454172455172456172457172458172459172460172461172462172463172464172465172466172467172468172469172470172471172472172473172474172475172476172477172478172479172480172481172482172483172484172485172486172487172488172489172490172491172492172493172494172495172496172497172498172499172500172501172502172503172504172505172506172507172508172509172510172511172512172513172514172515172516172517172518172519172520172521172522172523172524172525172526172527172528172529172530172531172532172533172534172535172536172537172538172539172540172541172542172543172544172545172546172547172548172549172550172551172552172553172554172555172556172557172558172559172560172561172562172563172564172565172566172567172568172569172570172571172572172573172574172575172576172577172578172579172580172581172582172583172584172585172586172587172588172589172590172591172592172593172594172595172596172597172598172599172600172601172602172603172604172605172606172607172608172609172610172611172612172613172614172615172616172617172618172619172620172621172622172623172624172625172626172627172628172629172630172631172632172633172634172635172636172637172638172639172640172641172642172643172644172645172646172647172648172649172650172651172652172653172654172655172656172657172658172659172660172661172662172663172664172665172666172667172668172669172670172671172672172673172674172675172676172677172678172679172680172681172682172683172684172685172686172687172688172689172690172691172692172693172694172695172696172697172698172699172700172701172702172703172704172705172706172707172708172709172710172711172712172713172714172715172716172717172718172719172720172721172722172723172724172725172726172727172728172729172730172731172732172733172734172735172736172737172738172739172740172741172742172743172744172745172746172747172748172749172750172751172752172753172754172755172756172757172758172759172760172761172762172763172764172765172766172767172768172769172770172771172772172773172774172775172776172777172778172779172780172781172782172783172784172785172786172787172788172789172790172791172792172793172794172795172796172797172798172799172800172801172802172803172804172805172806172807172808172809172810172811172812172813172814172815172816172817172818172819172820172821172822172823172824172825172826172827172828172829172830172831172832172833172834172835172836172837172838172839172840172841172842172843172844172845172846172847172848172849172850172851172852172853172854172855172856172857172858172859172860172861172862172863172864172865172866172867172868172869172870172871172872172873172874172875172876172877172878172879172880172881172882172883172884172885172886172887172888172889172890172891172892172893172894172895172896172897172898172899172900172901172902172903172904172905172906172907172908172909172910172911172912172913172914172915172916172917172918172919172920172921172922172923172924172925172926172927172928172929172930172931172932172933172934172935172936172937172938172939172940172941172942172943172944172945172946172947172948172949172950172951172952172953172954172955172956172957172958172959172960172961172962172963172964172965172966172967172968172969172970172971172972172973172974172975172976172977172978172979172980172981172982172983172984172985172986172987172988172989172990172991172992172993172994172995172996172997172998172999173000173001173002173003173004173005173006173007173008173009173010173011173012173013173014173015173016173017173018173019173020173021173022173023173024173025173026173027173028173029173030173031173032173033173034173035173036173037173038173039173040173041173042173043173044173045173046173047173048173049173050173051173052173053173054173055173056173057173058173059173060173061173062173063173064173065173066173067173068173069173070173071173072173073173074173075173076173077173078173079173080173081173082173083173084173085173086173087173088173089173090173091173092173093173094173095173096173097173098173099173100173101173102173103173104173105173106173107173108173109173110173111173112173113173114173115173116173117173118173119173120173121173122173123173124173125173126173127173128173129173130173131173132173133173134173135173136173137173138173139173140173141173142173143173144173145173146173147173148173149173150173151173152173153173154173155173156173157173158173159173160173161173162173163173164173165173166173167173168173169173170173171173172173173173174173175173176173177173178173179173180173181173182173183173184173185173186173187173188173189173190173191173192173193173194173195173196173197173198173199173200173201173202173203173204173205173206173207173208173209173210173211173212173213173214173215173216173217173218173219173220173221173222173223173224173225173226173227173228173229173230173231173232173233173234173235173236173237173238173239173240173241173242173243173244173245173246173247173248173249173250173251173252173253173254173255173256173257173258173259173260173261173262173263173264173265173266173267173268173269173270173271173272173273173274173275173276173277173278173279173280173281173282173283173284173285173286173287173288173289173290173291173292173293173294173295173296173297173298173299173300173301173302173303173304173305173306173307173308173309173310173311173312173313173314173315173316173317173318173319173320173321173322173323173324173325173326173327173328173329173330173331173332173333173334173335173336173337173338173339173340173341173342173343173344173345173346173347173348173349173350173351173352173353173354173355173356173357173358173359173360173361173362173363173364173365173366173367173368173369173370173371173372173373173374173375173376173377173378173379173380173381173382173383173384173385173386173387173388173389173390173391173392173393173394173395173396173397173398173399173400173401173402173403173404173405173406173407173408173409173410173411173412173413173414173415173416173417173418173419173420173421173422173423173424173425173426173427173428173429173430173431173432173433173434173435173436173437173438173439173440173441173442173443173444173445173446173447173448173449173450173451173452173453173454173455173456173457173458173459173460173461173462173463173464173465173466173467173468173469173470173471173472173473173474173475173476173477173478173479173480173481173482173483173484173485173486173487173488173489173490173491173492173493173494173495173496173497173498173499173500173501173502173503173504173505173506173507173508173509173510173511173512173513173514173515173516173517173518173519173520173521173522173523173524173525173526173527173528173529173530173531173532173533173534173535173536173537173538173539173540173541173542173543173544173545173546173547173548173549173550173551173552173553173554173555173556173557173558173559173560173561173562173563173564173565173566173567173568173569173570173571173572173573173574173575173576173577173578173579173580173581173582173583173584173585173586173587173588173589173590173591173592173593173594173595173596173597173598173599173600173601173602173603173604173605173606173607173608173609173610173611173612173613173614173615173616173617173618173619173620173621173622173623173624173625173626173627173628173629173630173631173632173633173634173635173636173637173638173639173640173641173642173643173644173645173646173647173648173649173650173651173652173653173654173655173656173657173658173659173660173661173662173663173664173665173666173667173668173669173670173671173672173673173674173675173676173677173678173679173680173681173682173683173684173685173686173687173688173689173690173691173692173693173694173695173696173697173698173699173700173701173702173703173704173705173706173707173708173709173710173711173712173713173714173715173716173717173718173719173720173721173722173723173724173725173726173727173728173729173730173731173732173733173734173735173736173737173738173739173740173741173742173743173744173745173746173747173748173749173750173751173752173753173754173755173756173757173758173759173760173761173762173763173764173765173766173767173768173769173770173771173772173773173774173775173776173777173778173779173780173781173782173783173784173785173786173787173788173789173790173791173792173793173794173795173796173797173798173799173800173801173802173803173804173805173806173807173808173809173810173811173812173813173814173815173816173817173818173819173820173821173822173823173824173825173826173827173828173829173830173831173832173833173834173835173836173837173838173839173840173841173842173843173844173845173846173847173848173849173850173851173852173853173854173855173856173857173858173859173860173861173862173863173864173865173866173867173868173869173870173871173872173873173874173875173876173877173878173879173880173881173882173883173884173885173886173887173888173889173890173891173892173893173894173895173896173897173898173899173900173901173902173903173904173905173906173907173908173909173910173911173912173913173914173915173916173917173918173919173920173921173922173923173924173925173926173927173928173929173930173931173932173933173934173935173936173937173938173939173940173941173942173943173944173945173946173947173948173949173950173951173952173953173954173955173956173957173958173959173960173961173962173963173964173965173966173967173968173969173970173971173972173973173974173975173976173977173978173979173980173981173982173983173984173985173986173987173988173989173990173991173992173993173994173995173996173997173998173999174000174001174002174003174004174005174006174007174008174009174010174011174012174013174014174015174016174017174018174019174020174021174022174023174024174025174026174027174028174029174030174031174032174033174034174035174036174037174038174039174040174041174042174043174044174045174046174047174048174049174050174051174052174053174054174055174056174057174058174059174060174061174062174063174064174065174066174067174068174069174070174071174072174073174074174075174076174077174078174079174080174081174082174083174084174085174086174087174088174089174090174091174092174093174094174095174096174097174098174099174100174101174102174103174104174105174106174107174108174109174110174111174112174113174114174115174116174117174118174119174120174121174122174123174124174125174126174127174128174129174130174131174132174133174134174135174136174137174138174139174140174141174142174143174144174145174146174147174148174149174150174151174152174153174154174155174156174157174158174159174160174161174162174163174164174165174166174167174168174169174170174171174172174173174174174175174176174177174178174179174180174181174182174183174184174185174186174187174188174189174190174191174192174193174194174195174196174197174198174199174200174201174202174203174204174205174206174207174208174209174210174211174212174213174214174215174216174217174218174219174220174221174222174223174224174225174226174227174228174229174230174231174232174233174234174235174236174237174238174239174240174241174242174243174244174245174246174247174248174249174250174251174252174253174254174255174256174257174258174259174260174261174262174263174264174265174266174267174268174269174270174271174272174273174274174275174276174277174278174279174280174281174282174283174284174285174286174287174288174289174290174291174292174293174294174295174296174297174298174299174300174301174302174303174304174305174306174307174308174309174310174311174312174313174314174315174316174317174318174319174320174321174322174323174324174325174326174327174328174329174330174331174332174333174334174335174336174337174338174339174340174341174342174343174344174345174346174347174348174349174350174351174352174353174354174355174356174357174358174359174360174361174362174363174364174365174366174367174368174369174370174371174372174373174374174375174376174377174378174379174380174381174382174383174384174385174386174387174388174389174390174391174392174393174394174395174396174397174398174399174400174401174402174403174404174405174406174407174408174409174410174411174412174413174414174415174416174417174418174419174420174421174422174423174424174425174426174427174428174429174430174431174432174433174434174435174436174437174438174439174440174441174442174443174444174445174446174447174448174449174450174451174452174453174454174455174456174457174458174459174460174461174462174463174464174465174466174467174468174469174470174471174472174473174474174475174476174477174478174479174480174481174482174483174484174485174486174487174488174489174490174491174492174493174494174495174496174497174498174499174500174501174502174503174504174505174506174507174508174509174510174511174512174513174514174515174516174517174518174519174520174521174522174523174524174525174526174527174528174529174530174531174532174533174534174535174536174537174538174539174540174541174542174543174544174545174546174547174548174549174550174551174552174553174554174555174556174557174558174559174560174561174562174563174564174565174566174567174568174569174570174571174572174573174574174575174576174577174578174579174580174581174582174583174584174585174586174587174588174589174590174591174592174593174594174595174596174597174598174599174600174601174602174603174604174605174606174607174608174609174610174611174612174613174614174615174616174617174618174619174620174621174622174623174624174625174626174627174628174629174630174631174632174633174634174635174636174637174638174639174640174641174642174643174644174645174646174647174648174649174650174651174652174653174654174655174656174657174658174659174660174661174662174663174664174665174666174667174668174669174670174671174672174673174674174675174676174677174678174679174680174681174682174683174684174685174686174687174688174689174690174691174692174693174694174695174696174697174698174699174700174701174702174703174704174705174706174707174708174709174710174711174712174713174714174715174716174717174718174719174720174721174722174723174724174725174726174727174728174729174730174731174732174733174734174735174736174737174738174739174740174741174742174743174744174745174746174747174748174749174750174751174752174753174754174755174756174757174758174759174760174761174762174763174764174765174766174767174768174769174770174771174772174773174774174775174776174777174778174779174780174781174782174783174784174785174786174787174788174789174790174791174792174793174794174795174796174797174798174799174800174801174802174803174804174805174806174807174808174809174810174811174812174813174814174815174816174817174818174819174820174821174822174823174824174825174826174827174828174829174830174831174832174833174834174835174836174837174838174839174840174841174842174843174844174845174846174847174848174849174850174851174852174853174854174855174856174857174858174859174860174861174862174863174864174865174866174867174868174869174870174871174872174873174874174875174876174877174878174879174880174881174882174883174884174885174886174887174888174889174890174891174892174893174894174895174896174897174898174899174900174901174902174903174904174905174906174907174908174909174910174911174912174913174914174915174916174917174918174919174920174921174922174923174924174925174926174927174928174929174930174931174932174933174934174935174936174937174938174939174940174941174942174943174944174945174946174947174948174949174950174951174952174953174954174955174956174957174958174959174960174961174962174963174964174965174966174967174968174969174970174971174972174973174974174975174976174977174978174979174980174981174982174983174984174985174986174987174988174989174990174991174992174993174994174995174996174997174998174999175000175001175002175003175004175005175006175007175008175009175010175011175012175013175014175015175016175017175018175019175020175021175022175023175024175025175026175027175028175029175030175031175032175033175034175035175036175037175038175039175040175041175042175043175044175045175046175047175048175049175050175051175052175053175054175055175056175057175058175059175060175061175062175063175064175065175066175067175068175069175070175071175072175073175074175075175076175077175078175079175080175081175082175083175084175085175086175087175088175089175090175091175092175093175094175095175096175097175098175099175100175101175102175103175104175105175106175107175108175109175110175111175112175113175114175115175116175117175118175119175120175121175122175123175124175125175126175127175128175129175130175131175132175133175134175135175136175137175138175139175140175141175142175143175144175145175146175147175148175149175150175151175152175153175154175155175156175157175158175159175160175161175162175163175164175165175166175167175168175169175170175171175172175173175174175175175176175177175178175179175180175181175182175183175184175185175186175187175188175189175190175191175192175193175194175195175196175197175198175199175200175201175202175203175204175205175206175207175208175209175210175211175212175213175214175215175216175217175218175219175220175221175222175223175224175225175226175227175228175229175230175231175232175233175234175235175236175237175238175239175240175241175242175243175244175245175246175247175248175249175250175251175252175253175254175255175256175257175258175259175260175261175262175263175264175265175266175267175268175269175270175271175272175273175274175275175276175277175278175279175280175281175282175283175284175285175286175287175288175289175290175291175292175293175294175295175296175297175298175299175300175301175302175303175304175305175306175307175308175309175310175311175312175313175314175315175316175317175318175319175320175321175322175323175324175325175326175327175328175329175330175331175332175333175334175335175336175337175338175339175340175341175342175343175344175345175346175347175348175349175350175351175352175353175354175355175356175357175358175359175360175361175362175363175364175365175366175367175368175369175370175371175372175373175374175375175376175377175378175379175380175381175382175383175384175385175386175387175388175389175390175391175392175393175394175395175396175397175398175399175400175401175402175403175404175405175406175407175408175409175410175411175412175413175414175415175416175417175418175419175420175421175422175423175424175425175426175427175428175429175430175431175432175433175434175435175436175437175438175439175440175441175442175443175444175445175446175447175448175449175450175451175452175453175454175455175456175457175458175459175460175461175462175463175464175465175466175467175468175469175470175471175472175473175474175475175476175477175478175479175480175481175482175483175484175485175486175487175488175489175490175491175492175493175494175495175496175497175498175499175500175501175502175503175504175505175506175507175508175509175510175511175512175513175514175515175516175517175518175519175520175521175522175523175524175525175526175527175528175529175530175531175532175533175534175535175536175537175538175539175540175541175542175543175544175545175546175547175548175549175550175551175552175553175554175555175556175557175558175559175560175561175562175563175564175565175566175567175568175569175570175571175572175573175574175575175576175577175578175579175580175581175582175583175584175585175586175587175588175589175590175591175592175593175594175595175596175597175598175599175600175601175602175603175604175605175606175607175608175609175610175611175612175613175614175615175616175617175618175619175620175621175622175623175624175625175626175627175628175629175630175631175632175633175634175635175636175637175638175639175640175641175642175643175644175645175646175647175648175649175650175651175652175653175654175655175656175657175658175659175660175661175662175663175664175665175666175667175668175669175670175671175672175673175674175675175676175677175678175679175680175681175682175683175684175685175686175687175688175689175690175691175692175693175694175695175696175697175698175699175700175701175702175703175704175705175706175707175708175709175710175711175712175713175714175715175716175717175718175719175720175721175722175723175724175725175726175727175728175729175730175731175732175733175734175735175736175737175738175739175740175741175742175743175744175745175746175747175748175749175750175751175752175753175754175755175756175757175758175759175760175761175762175763175764175765175766175767175768175769175770175771175772175773175774175775175776175777175778175779175780175781175782175783175784175785175786175787175788175789175790175791175792175793175794175795175796175797175798175799175800175801175802175803175804175805175806175807175808175809175810175811175812175813175814175815175816175817175818175819175820175821175822175823175824175825175826175827175828175829175830175831175832175833175834175835175836175837175838175839175840175841175842175843175844175845175846175847175848175849175850175851175852175853175854175855175856175857175858175859175860175861175862175863175864175865175866175867175868175869175870175871175872175873175874175875175876175877175878175879175880175881175882175883175884175885175886175887175888175889175890175891175892175893175894175895175896175897175898175899175900175901175902175903175904175905175906175907175908175909175910175911175912175913175914175915175916175917175918175919175920175921175922175923175924175925175926175927175928175929175930175931175932175933175934175935175936175937175938175939175940175941175942175943175944175945175946175947175948175949175950175951175952175953175954175955175956175957175958175959175960175961175962175963175964175965175966175967175968175969175970175971175972175973175974175975175976175977175978175979175980175981175982175983175984175985175986175987175988175989175990175991175992175993175994175995175996175997175998175999176000176001176002176003176004176005176006176007176008176009176010176011176012176013176014176015176016176017176018176019176020176021176022176023176024176025176026176027176028176029176030176031176032176033176034176035176036176037176038176039176040176041176042176043176044176045176046176047176048176049176050176051176052176053176054176055176056176057176058176059176060176061176062176063176064176065176066176067176068176069176070176071176072176073176074176075176076176077176078176079176080176081176082176083176084176085176086176087176088176089176090176091176092176093176094176095176096176097176098176099176100176101176102176103176104176105176106176107176108176109176110176111176112176113176114176115176116176117176118176119176120176121176122176123176124176125176126176127176128176129176130176131176132176133176134176135176136176137176138176139176140176141176142176143176144176145176146176147176148176149176150176151176152176153176154176155176156176157176158176159176160176161176162176163176164176165176166176167176168176169176170176171176172176173176174176175176176176177176178176179176180176181176182176183176184176185176186176187176188176189176190176191176192176193176194176195176196176197176198176199176200176201176202176203176204176205176206176207176208176209176210176211176212176213176214176215176216176217176218176219176220176221176222176223176224176225176226176227176228176229176230176231176232176233176234176235176236176237176238176239176240176241176242176243176244176245176246176247176248176249176250176251176252176253176254176255176256176257176258176259176260176261176262176263176264176265176266176267176268176269176270176271176272176273176274176275176276176277176278176279176280176281176282176283176284176285176286176287176288176289176290176291176292176293176294176295176296176297176298176299176300176301176302176303176304176305176306176307176308176309176310176311176312176313176314176315176316176317176318176319176320176321176322176323176324176325176326176327176328176329176330176331176332176333176334176335176336176337176338176339176340176341176342176343176344176345176346176347176348176349176350176351176352176353176354176355176356176357176358176359176360176361176362176363176364176365176366176367176368176369176370176371176372176373176374176375176376176377176378176379176380176381176382176383176384176385176386176387176388176389176390176391176392176393176394176395176396176397176398176399176400176401176402176403176404176405176406176407176408176409176410176411176412176413176414176415176416176417176418176419176420176421176422176423176424176425176426176427176428176429176430176431176432176433176434176435176436176437176438176439176440176441176442176443176444176445176446176447176448176449176450176451176452176453176454176455176456176457176458176459176460176461176462176463176464176465176466176467176468176469176470176471176472176473176474176475176476176477176478176479176480176481176482176483176484176485176486176487176488176489176490176491176492176493176494176495176496176497176498176499176500176501176502176503176504176505176506176507176508176509176510176511176512176513176514176515176516176517176518176519176520176521176522176523176524176525176526176527176528176529176530176531176532176533176534176535176536176537176538176539176540176541176542176543176544176545176546176547176548176549176550176551176552176553176554176555176556176557176558176559176560176561176562176563176564176565176566176567176568176569176570176571176572176573176574176575176576176577176578176579176580176581176582176583176584176585176586176587176588176589176590176591176592176593176594176595176596176597176598176599176600176601176602176603176604176605176606176607176608176609176610176611176612176613176614176615176616176617176618176619176620176621176622176623176624176625176626176627176628176629176630176631176632176633176634176635176636176637176638176639176640176641176642176643176644176645176646176647176648176649176650176651176652176653176654176655176656176657176658176659176660176661176662176663176664176665176666176667176668176669176670176671176672176673176674176675176676176677176678176679176680176681176682176683176684176685176686176687176688176689176690176691176692176693176694176695176696176697176698176699176700176701176702176703176704176705176706176707176708176709176710176711176712176713176714176715176716176717176718176719176720176721176722176723176724176725176726176727176728176729176730176731176732176733176734176735176736176737176738176739176740176741176742176743176744176745176746176747176748176749176750176751176752176753176754176755176756176757176758176759176760176761176762176763176764176765176766176767176768176769176770176771176772176773176774176775176776176777176778176779176780176781176782176783176784176785176786176787176788176789176790176791176792176793176794176795176796176797176798176799176800176801176802176803176804176805176806176807176808176809176810176811176812176813176814176815176816176817176818176819176820176821176822176823176824176825176826176827176828176829176830176831176832176833176834176835176836176837176838176839176840176841176842176843176844176845176846176847176848176849176850176851176852176853176854176855176856176857176858176859176860176861176862176863176864176865176866176867176868176869176870176871176872176873176874176875176876176877176878176879176880176881176882176883176884176885176886176887176888176889176890176891176892176893176894176895176896176897176898176899176900176901176902176903176904176905176906176907176908176909176910176911176912176913176914176915176916176917176918176919176920176921176922176923176924176925176926176927176928176929176930176931176932176933176934176935176936176937176938176939176940176941176942176943176944176945176946176947176948176949176950176951176952176953176954176955176956176957176958176959176960176961176962176963176964176965176966176967176968176969176970176971176972176973176974176975176976176977176978176979176980176981176982176983176984176985176986176987176988176989176990176991176992176993176994176995176996176997176998176999177000177001177002177003177004177005177006177007177008177009177010177011177012177013177014177015177016177017177018177019177020177021177022177023177024177025177026177027177028177029177030177031177032177033177034177035177036177037177038177039177040177041177042177043177044177045177046177047177048177049177050177051177052177053177054177055177056177057177058177059177060177061177062177063177064177065177066177067177068177069177070177071177072177073177074177075177076177077177078177079177080177081177082177083177084177085177086177087177088177089177090177091177092177093177094177095177096177097177098177099177100177101177102177103177104177105177106177107177108177109177110177111177112177113177114177115177116177117177118177119177120177121177122177123177124177125177126177127177128177129177130177131177132177133177134177135177136177137177138177139177140177141177142177143177144177145177146177147177148177149177150177151177152177153177154177155177156177157177158177159177160177161177162177163177164177165177166177167177168177169177170177171177172177173177174177175177176177177177178177179177180177181177182177183177184177185177186177187177188177189177190177191177192177193177194177195177196177197177198177199177200177201177202177203177204177205177206177207177208177209177210177211177212177213177214177215177216177217177218177219177220177221177222177223177224177225177226177227177228177229177230177231177232177233177234177235177236177237177238177239177240177241177242177243177244177245177246177247177248177249177250177251177252177253177254177255177256177257177258177259177260177261177262177263177264177265177266177267177268177269177270177271177272177273177274177275177276177277177278177279177280177281177282177283177284177285177286177287177288177289177290177291177292177293177294177295177296177297177298177299177300177301177302177303177304177305177306177307177308177309177310177311177312177313177314177315177316177317177318177319177320177321177322177323177324177325177326177327177328177329177330177331177332177333177334177335177336177337177338177339177340177341177342177343177344177345177346177347177348177349177350177351177352177353177354177355177356177357177358177359177360177361177362177363177364177365177366177367177368177369177370177371177372177373177374177375177376177377177378177379177380177381177382177383177384177385177386177387177388177389177390177391177392177393177394177395177396177397177398177399177400177401177402177403177404177405177406177407177408177409177410177411177412177413177414177415177416177417177418177419177420177421177422177423177424177425177426177427177428177429177430177431177432177433177434177435177436177437177438177439177440177441177442177443177444177445177446177447177448177449177450177451177452177453177454177455177456177457177458177459177460177461177462177463177464177465177466177467177468177469177470177471177472177473177474177475177476177477177478177479177480177481177482177483177484177485177486177487177488177489177490177491177492177493177494177495177496177497177498177499177500177501177502177503177504177505177506177507177508177509177510177511177512177513177514177515177516177517177518177519177520177521177522177523177524177525177526177527177528177529177530177531177532177533177534177535177536177537177538177539177540177541177542177543177544177545177546177547177548177549177550177551177552177553177554177555177556177557177558177559177560177561177562177563177564177565177566177567177568177569177570177571177572177573177574177575177576177577177578177579177580177581177582177583177584177585177586177587177588177589177590177591177592177593177594177595177596177597177598177599177600177601177602177603177604177605177606177607177608177609177610177611177612177613177614177615177616177617177618177619177620177621177622177623177624177625177626177627177628177629177630177631177632177633177634177635177636177637177638177639177640177641177642177643177644177645177646177647177648177649177650177651177652177653177654177655177656177657177658177659177660177661177662177663177664177665177666177667177668177669177670177671177672177673177674177675177676177677177678177679177680177681177682177683177684177685177686177687177688177689177690177691177692177693177694177695177696177697177698177699177700177701177702177703177704177705177706177707177708177709177710177711177712177713177714177715177716177717177718177719177720177721177722177723177724177725177726177727177728177729177730177731177732177733177734177735177736177737177738177739177740177741177742177743177744177745177746177747177748177749177750177751177752177753177754177755177756177757177758177759177760177761177762177763177764177765177766177767177768177769177770177771177772177773177774177775177776177777177778177779177780177781177782177783177784177785177786177787177788177789177790177791177792177793177794177795177796177797177798177799177800177801177802177803177804177805177806177807177808177809177810177811177812177813177814177815177816177817177818177819177820177821177822177823177824177825177826177827177828177829177830177831177832177833177834177835177836177837177838177839177840177841177842177843177844177845177846177847177848177849177850177851177852177853177854177855177856177857177858177859177860177861177862177863177864177865177866177867177868177869177870177871177872177873177874177875177876177877177878177879177880177881177882177883177884177885177886177887177888177889177890177891177892177893177894177895177896177897177898177899177900177901177902177903177904177905177906177907177908177909177910177911177912177913177914177915177916177917177918177919177920177921177922177923177924177925177926177927177928177929177930177931177932177933177934177935177936177937177938177939177940177941177942177943177944177945177946177947177948177949177950177951177952177953177954177955177956177957177958177959177960177961177962177963177964177965177966177967177968177969177970177971177972177973177974177975177976177977177978177979177980177981177982177983177984177985177986177987177988177989177990177991177992177993177994177995177996177997177998177999178000178001178002178003178004178005178006178007178008178009178010178011178012178013178014178015178016178017178018178019178020178021178022178023178024178025178026178027178028178029178030178031178032178033178034178035178036178037178038178039178040178041178042178043178044178045178046178047178048178049178050178051178052178053178054178055178056178057178058178059178060178061178062178063178064178065178066178067178068178069178070178071178072178073178074178075178076178077178078178079178080178081178082178083178084178085178086178087178088178089178090178091178092178093178094178095178096178097178098178099178100178101178102178103178104178105178106178107178108178109178110178111178112178113178114178115178116178117178118178119178120178121178122178123178124178125178126178127178128178129178130178131178132178133178134178135178136178137178138178139178140178141178142178143178144178145178146178147178148178149178150178151178152178153178154178155178156178157178158178159178160178161178162178163178164178165178166178167178168178169178170178171178172178173178174178175178176178177178178178179178180178181178182178183178184178185178186178187178188178189178190178191178192178193178194178195178196178197178198178199178200178201178202178203178204178205178206178207178208178209178210178211178212178213178214178215178216178217178218178219178220178221178222178223178224178225178226178227178228178229178230178231178232178233178234178235178236178237178238178239178240178241178242178243178244178245178246178247178248178249178250178251178252178253178254178255178256178257178258178259178260178261178262178263178264178265178266178267178268178269178270178271178272178273178274178275178276178277178278178279178280178281178282178283178284178285178286178287178288178289178290178291178292178293178294178295178296178297178298178299178300178301178302178303178304178305178306178307178308178309178310178311178312178313178314178315178316178317178318178319178320178321178322178323178324178325178326178327178328178329178330178331178332178333178334178335178336178337178338178339178340178341178342178343178344178345178346178347178348178349178350178351178352178353178354178355178356178357178358178359178360178361178362178363178364178365178366178367178368178369178370178371178372178373178374178375178376178377178378178379178380178381178382178383178384178385178386178387178388178389178390178391178392178393178394178395178396178397178398178399178400178401178402178403178404178405178406178407178408178409178410178411178412178413178414178415178416178417178418178419178420178421178422178423178424178425178426178427178428178429178430178431178432178433178434178435178436178437178438178439178440178441178442178443178444178445178446178447178448178449178450178451178452178453178454178455178456178457178458178459178460178461178462178463178464178465178466178467178468178469178470178471178472178473178474178475178476178477178478178479178480178481178482178483178484178485178486178487178488178489178490178491178492178493178494178495178496178497178498178499178500178501178502178503178504178505178506178507178508178509178510178511178512178513178514178515178516178517178518178519178520178521178522178523178524178525178526178527178528178529178530178531178532178533178534178535178536178537178538178539178540178541178542178543178544178545178546178547178548178549178550178551178552178553178554178555178556178557178558178559178560178561178562178563178564178565178566178567178568178569178570178571178572178573178574178575178576178577178578178579178580178581178582178583178584178585178586178587178588178589178590178591178592178593178594178595178596178597178598178599178600178601178602178603178604178605178606178607178608178609178610178611178612178613178614178615178616178617178618178619178620178621178622178623178624178625178626178627178628178629178630178631178632178633178634178635178636178637178638178639178640178641178642178643178644178645178646178647178648178649178650178651178652178653178654178655178656178657178658178659178660178661178662178663178664178665178666178667178668178669178670178671178672178673178674178675178676178677178678178679178680178681178682178683178684178685178686178687178688178689178690178691178692178693178694178695178696178697178698178699178700178701178702178703178704178705178706178707178708178709178710178711178712178713178714178715178716178717178718178719178720178721178722178723178724178725178726178727178728178729178730178731178732178733178734178735178736178737178738178739178740178741178742178743178744178745178746178747178748178749178750178751178752178753178754178755178756178757178758178759178760178761178762178763178764178765178766178767178768178769178770178771178772178773178774178775178776178777178778178779178780178781178782178783178784178785178786178787178788178789178790178791178792178793178794178795178796178797178798178799178800178801178802178803178804178805178806178807178808178809178810178811178812178813178814178815178816178817178818178819178820178821178822178823178824178825178826178827178828178829178830178831178832178833178834178835178836178837178838178839178840178841178842178843178844178845178846178847178848178849178850178851178852178853178854178855178856178857178858178859178860178861178862178863178864178865178866178867178868178869178870178871178872178873178874178875178876178877178878178879178880178881178882178883178884178885178886178887178888178889178890178891178892178893178894178895178896178897178898178899178900178901178902178903178904178905178906178907178908178909178910178911178912178913178914178915178916178917178918178919178920178921178922178923178924178925178926178927178928178929178930178931178932178933178934178935178936178937178938178939178940178941178942178943178944178945178946178947178948178949178950178951178952178953178954178955178956178957178958178959178960178961178962178963178964178965178966178967178968178969178970178971178972178973178974178975178976178977178978178979178980178981178982178983178984178985178986178987178988178989178990178991178992178993178994178995178996178997178998178999179000179001179002179003179004179005179006179007179008179009179010179011179012179013179014179015179016179017179018179019179020179021179022179023179024179025179026179027179028179029179030179031179032179033179034179035179036179037179038179039179040179041179042179043179044179045179046179047179048179049179050179051179052179053179054179055179056179057179058179059179060179061179062179063179064179065179066179067179068179069179070179071179072179073179074179075179076179077179078179079179080179081179082179083179084179085179086179087179088179089179090179091179092179093179094179095179096179097179098179099179100179101179102179103179104179105179106179107179108179109179110179111179112179113179114179115179116179117179118179119179120179121179122179123179124179125179126179127179128179129179130179131179132179133179134179135179136179137179138179139179140179141179142179143179144179145179146179147179148179149179150179151179152179153179154179155179156179157179158179159179160179161179162179163179164179165179166179167179168179169179170179171179172179173179174179175179176179177179178179179179180179181179182179183179184179185179186179187179188179189179190179191179192179193179194179195179196179197179198179199179200179201179202179203179204179205179206179207179208179209179210179211179212179213179214179215179216179217179218179219179220179221179222179223179224179225179226179227179228179229179230179231179232179233179234179235179236179237179238179239179240179241179242179243179244179245179246179247179248179249179250179251179252179253179254179255179256179257179258179259179260179261179262179263179264179265179266179267179268179269179270179271179272179273179274179275179276179277179278179279179280179281179282179283179284179285179286179287179288179289179290179291179292179293179294179295179296179297179298179299179300179301179302179303179304179305179306179307179308179309179310179311179312179313179314179315179316179317179318179319179320179321179322179323179324179325179326179327179328179329179330179331179332179333179334179335179336179337179338179339179340179341179342179343179344179345179346179347179348179349179350179351179352179353179354179355179356179357179358179359179360179361179362179363179364179365179366179367179368179369179370179371179372179373179374179375179376179377179378179379179380179381179382179383179384179385179386179387179388179389179390179391179392179393179394179395179396179397179398179399179400179401179402179403179404179405179406179407179408179409179410179411179412179413179414179415179416179417179418179419179420179421179422179423179424179425179426179427179428179429179430179431179432179433179434179435179436179437179438179439179440179441179442179443179444179445179446179447179448179449179450179451179452179453179454179455179456179457179458179459179460179461179462179463179464179465179466179467179468179469179470179471179472179473179474179475179476179477179478179479179480179481179482179483179484179485179486179487179488179489179490179491179492179493179494179495179496179497179498179499179500179501179502179503179504179505179506179507179508179509179510179511179512179513179514179515179516179517179518179519179520179521179522179523179524179525179526179527179528179529179530179531179532179533179534179535179536179537179538179539179540179541179542179543179544179545179546179547179548179549179550179551179552179553179554179555179556179557179558179559179560179561179562179563179564179565179566179567179568179569179570179571179572179573179574179575179576179577179578179579179580179581179582179583179584179585179586179587179588179589179590179591179592179593179594179595179596179597179598179599179600179601179602179603179604179605179606179607179608179609179610179611179612179613179614179615179616179617179618179619179620179621179622179623179624179625179626179627179628179629179630179631179632179633179634179635179636179637179638179639179640179641179642179643179644179645179646179647179648179649179650179651179652179653179654179655179656179657179658179659179660179661179662179663179664179665179666179667179668179669179670179671179672179673179674179675179676179677179678179679179680179681179682179683179684179685179686179687179688179689179690179691179692179693179694179695179696179697179698179699179700179701179702179703179704179705179706179707179708179709179710179711179712179713179714179715179716179717179718179719179720179721179722179723179724179725179726179727179728179729179730179731179732179733179734179735179736179737179738179739179740179741179742179743179744179745179746179747179748179749179750179751179752179753179754179755179756179757179758179759179760179761179762179763179764179765179766179767179768179769179770179771179772179773179774179775179776179777179778179779179780179781179782179783179784179785179786179787179788179789179790179791179792179793179794179795179796179797179798179799179800179801179802179803179804179805179806179807179808179809179810179811179812179813179814179815179816179817179818179819179820179821179822179823179824179825179826179827179828179829179830179831179832179833179834179835179836179837179838179839179840179841179842179843179844179845179846179847179848179849179850179851179852179853179854179855179856179857179858179859179860179861179862179863179864179865179866179867179868179869179870179871179872179873179874179875179876179877179878179879179880179881179882179883179884179885179886179887179888179889179890179891179892179893179894179895179896179897179898179899179900179901179902179903179904179905179906179907179908179909179910179911179912179913179914179915179916179917179918179919179920179921179922179923179924179925179926179927179928179929179930179931179932179933179934179935179936179937179938179939179940179941179942179943179944179945179946179947179948179949179950179951179952179953179954179955179956179957179958179959179960179961179962179963179964179965179966179967179968179969179970179971179972179973179974179975179976179977179978179979179980179981179982179983179984179985179986179987179988179989179990179991179992179993179994179995179996179997179998179999180000180001180002180003180004180005180006180007180008180009180010180011180012180013180014180015180016180017180018180019180020180021180022180023180024180025180026180027180028180029180030180031180032180033180034180035180036180037180038180039180040180041180042180043180044180045180046180047180048180049180050180051180052180053180054180055180056180057180058180059180060180061180062180063180064180065180066180067180068180069180070180071180072180073180074180075180076180077180078180079180080180081180082180083180084180085180086180087180088180089180090180091180092180093180094180095180096180097180098180099180100180101180102180103180104180105180106180107180108180109180110180111180112180113180114180115180116180117180118180119180120180121180122180123180124180125180126180127180128180129180130180131180132180133180134180135180136180137180138180139180140180141180142180143180144180145180146180147180148180149180150180151180152180153180154180155180156180157180158180159180160180161180162180163180164180165180166180167180168180169180170180171180172180173180174180175180176180177180178180179180180180181180182180183180184180185180186180187180188180189180190180191180192180193180194180195180196180197180198180199180200180201180202180203180204180205180206180207180208180209180210180211180212180213180214180215180216180217180218180219180220180221180222180223180224180225180226180227180228180229180230180231180232180233180234180235180236180237180238180239180240180241180242180243180244180245180246180247180248180249180250180251180252180253180254180255180256180257180258180259180260180261180262180263180264180265180266180267180268180269180270180271180272180273180274180275180276180277180278180279180280180281180282180283180284180285180286180287180288180289180290180291180292180293180294180295180296180297180298180299180300180301180302180303180304180305180306180307180308180309180310180311180312180313180314180315180316180317180318180319180320180321180322180323180324180325180326180327180328180329180330180331180332180333180334180335180336180337180338180339180340180341180342180343180344180345180346180347180348180349180350180351180352180353180354180355180356180357180358180359180360180361180362180363180364180365180366180367180368180369180370180371180372180373180374180375180376180377180378180379180380180381180382180383180384180385180386180387180388180389180390180391180392180393180394180395180396180397180398180399180400180401180402180403180404180405180406180407180408180409180410180411180412180413180414180415180416180417180418180419180420180421180422180423180424180425180426180427180428180429180430180431180432180433180434180435180436180437180438180439180440180441180442180443180444180445180446180447180448180449180450180451180452180453180454180455180456180457180458180459180460180461180462180463180464180465180466180467180468180469180470180471180472180473180474180475180476180477180478180479180480180481180482180483180484180485180486180487180488180489180490180491180492180493180494180495180496180497180498180499180500180501180502180503180504180505180506180507180508180509180510180511180512180513180514180515180516180517180518180519180520180521180522180523180524180525180526180527180528180529180530180531180532180533180534180535180536180537180538180539180540180541180542180543180544180545180546180547180548180549180550180551180552180553180554180555180556180557180558180559180560180561180562180563180564180565180566180567180568180569180570180571180572180573180574180575180576180577180578180579180580180581180582180583180584180585180586180587180588180589180590180591180592180593180594180595180596180597180598180599180600180601180602180603180604180605180606180607180608180609180610180611180612180613180614180615180616180617180618180619180620180621180622180623180624180625180626180627180628180629180630180631180632180633180634180635180636180637180638180639180640180641180642180643180644180645180646180647180648180649180650180651180652180653180654180655180656180657180658180659180660180661180662180663180664180665180666180667180668180669180670180671180672180673180674180675180676180677180678180679180680180681180682180683180684180685180686180687180688180689180690180691180692180693180694180695180696180697180698180699180700180701180702180703180704180705180706180707180708180709180710180711180712180713180714180715180716180717180718180719180720180721180722180723180724180725180726180727180728180729180730180731180732180733180734180735180736180737180738180739180740180741180742180743180744180745180746180747180748180749180750180751180752180753180754180755180756180757180758180759180760180761180762180763180764180765180766180767180768180769180770180771180772180773180774180775180776180777180778180779180780180781180782180783180784180785180786180787180788180789180790180791180792180793180794180795180796180797180798180799180800180801180802180803180804180805180806180807180808180809180810180811180812180813180814180815180816180817180818180819180820180821180822180823180824180825180826180827180828180829180830180831180832180833180834180835180836180837180838180839180840180841180842180843180844180845180846180847180848180849180850180851180852180853180854180855180856180857180858180859180860180861180862180863180864180865180866180867180868180869180870180871180872180873180874180875180876180877180878180879180880180881180882180883180884180885180886180887180888180889180890180891180892180893180894180895180896180897180898180899180900180901180902180903180904180905180906180907180908180909180910180911180912180913180914180915180916180917180918180919180920180921180922180923180924180925180926180927180928180929180930180931180932180933180934180935180936180937180938180939180940180941180942180943180944180945180946180947180948180949180950180951180952180953180954180955180956180957180958180959180960180961180962180963180964180965180966180967180968180969180970180971180972180973180974180975180976180977180978180979180980180981180982180983180984180985180986180987180988180989180990180991180992180993180994180995180996180997180998180999181000181001181002181003181004181005181006181007181008181009181010181011181012181013181014181015181016181017181018181019181020181021181022181023181024181025181026181027181028181029181030181031181032181033181034181035181036181037181038181039181040181041181042181043181044181045181046181047181048181049181050181051181052181053181054181055181056181057181058181059181060181061181062181063181064181065181066181067181068181069181070181071181072181073181074181075181076181077181078181079181080181081181082181083181084181085181086181087181088181089181090181091181092181093181094181095181096181097181098181099181100181101181102181103181104181105181106181107181108181109181110181111181112181113181114181115181116181117181118181119181120181121181122181123181124181125181126181127181128181129181130181131181132181133181134181135181136181137181138181139181140181141181142181143181144181145181146181147181148181149181150181151181152181153181154181155181156181157181158181159181160181161181162181163181164181165181166181167181168181169181170181171181172181173181174181175181176181177181178181179181180181181181182181183181184181185181186181187181188181189181190181191181192181193181194181195181196181197181198181199181200181201181202181203181204181205181206181207181208181209181210181211181212181213181214181215181216181217181218181219181220181221181222181223181224181225181226181227181228181229181230181231181232181233181234181235181236181237181238181239181240181241181242181243181244181245181246181247181248181249181250181251181252181253181254181255181256181257181258181259181260181261181262181263181264181265181266181267181268181269181270181271181272181273181274181275181276181277181278181279181280181281181282181283181284181285181286181287181288181289181290181291181292181293181294181295181296181297181298181299181300181301181302181303181304181305181306181307181308181309181310181311181312181313181314181315181316181317181318181319181320181321181322181323181324181325181326181327181328181329181330181331181332181333181334181335181336181337181338181339181340181341181342181343181344181345181346181347181348181349181350181351181352181353181354181355181356181357181358181359181360181361181362181363181364181365181366181367181368181369181370181371181372181373181374181375181376181377181378181379181380181381181382181383181384181385181386181387181388181389181390181391181392181393181394181395181396181397181398181399181400181401181402181403181404181405181406181407181408181409181410181411181412181413181414181415181416181417181418181419181420181421181422181423181424181425181426181427181428181429181430181431181432181433181434181435181436181437181438181439181440181441181442181443181444181445181446181447181448181449181450181451181452181453181454181455181456181457181458181459181460181461181462181463181464181465181466181467181468181469181470181471181472181473181474181475181476181477181478181479181480181481181482181483181484181485181486181487181488181489181490181491181492181493181494181495181496181497181498181499181500181501181502181503181504181505181506181507181508181509181510181511181512181513181514181515181516181517181518181519181520181521181522181523181524181525181526181527181528181529181530181531181532181533181534181535181536181537181538181539181540181541181542181543181544181545181546181547181548181549181550181551181552181553181554181555181556181557181558181559181560181561181562181563181564181565181566181567181568181569181570181571181572181573181574181575181576181577181578181579181580181581181582181583181584181585181586181587181588181589181590181591181592181593181594181595181596181597181598181599181600181601181602181603181604181605181606181607181608181609181610181611181612181613181614181615181616181617181618181619181620181621181622181623181624181625181626181627181628181629181630181631181632181633181634181635181636181637181638181639181640181641181642181643181644181645181646181647181648181649181650181651181652181653181654181655181656181657181658181659181660181661181662181663181664181665181666181667181668181669181670181671181672181673181674181675181676181677181678181679181680181681181682181683181684181685181686181687181688181689181690181691181692181693181694181695181696181697181698181699181700181701181702181703181704181705181706181707181708181709181710181711181712181713181714181715181716181717181718181719181720181721181722181723181724181725181726181727181728181729181730181731181732181733181734181735181736181737181738181739181740181741181742181743181744181745181746181747181748181749181750181751181752181753181754181755181756181757181758181759181760181761181762181763181764181765181766181767181768181769181770181771181772181773181774181775181776181777181778181779181780181781181782181783181784181785181786181787181788181789181790181791181792181793181794181795181796181797181798181799181800181801181802181803181804181805181806181807181808181809181810181811181812181813181814181815181816181817181818181819181820181821181822181823181824181825181826181827181828181829181830181831181832181833181834181835181836181837181838181839181840181841181842181843181844181845181846181847181848181849181850181851181852181853181854181855181856181857181858181859181860181861181862181863181864181865181866181867181868181869181870181871181872181873181874181875181876181877181878181879181880181881181882181883181884181885181886181887181888181889181890181891181892181893181894181895181896181897181898181899181900181901181902181903181904181905181906181907181908181909181910181911181912181913181914181915181916181917181918181919181920181921181922181923181924181925181926181927181928181929181930181931181932181933181934181935181936181937181938181939181940181941181942181943181944181945181946181947181948181949181950181951181952181953181954181955181956181957181958181959181960181961181962181963181964181965181966181967181968181969181970181971181972181973181974181975181976181977181978181979181980181981181982181983181984181985181986181987181988181989181990181991181992181993181994181995181996181997181998181999182000182001182002182003182004182005182006182007182008182009182010182011182012182013182014182015182016182017182018182019182020182021182022182023182024182025182026182027182028182029182030182031182032182033182034182035182036182037182038182039182040182041182042182043182044182045182046182047182048182049182050182051182052182053182054182055182056182057182058182059182060182061182062182063182064182065182066182067182068182069182070182071182072182073182074182075182076182077182078182079182080182081182082182083182084182085182086182087182088182089182090182091182092182093182094182095182096182097182098182099182100182101182102182103182104182105182106182107182108182109182110182111182112182113182114182115182116182117182118182119182120182121182122182123182124182125182126182127182128182129182130182131182132182133182134182135182136182137182138182139182140182141182142182143182144182145182146182147182148182149182150182151182152182153182154182155182156182157182158182159182160182161182162182163182164182165182166182167182168182169182170182171182172182173182174182175182176182177182178182179182180182181182182182183182184182185182186182187182188182189182190182191182192182193182194182195182196182197182198182199182200182201182202182203182204182205182206182207182208182209182210182211182212182213182214182215182216182217182218182219182220182221182222182223182224182225182226182227182228182229182230182231182232182233182234182235182236182237182238182239182240182241182242182243182244182245182246182247182248182249182250182251182252182253182254182255182256182257182258182259182260182261182262182263182264182265182266182267182268182269182270182271182272182273182274182275182276182277182278182279182280182281182282182283182284182285182286182287182288182289182290182291182292182293182294182295182296182297182298182299182300182301182302182303182304182305182306182307182308182309182310182311182312182313182314182315182316182317182318182319182320182321182322182323182324182325182326182327182328182329182330182331182332182333182334182335182336182337182338182339182340182341182342182343182344182345182346182347182348182349182350182351182352182353182354182355182356182357182358182359182360182361182362182363182364182365182366182367182368182369182370182371182372182373182374182375182376182377182378182379182380182381182382182383182384182385182386182387182388182389182390182391182392182393182394182395182396182397182398182399182400182401182402182403182404182405182406182407182408182409182410182411182412182413182414182415182416182417182418182419182420182421182422182423182424182425182426182427182428182429182430182431182432182433182434182435182436182437182438182439182440182441182442182443182444182445182446182447182448182449182450182451182452182453182454182455182456182457182458182459182460182461182462182463182464182465182466182467182468182469182470182471182472182473182474182475182476182477182478182479182480182481182482182483182484182485182486182487182488182489182490182491182492182493182494182495182496182497182498182499182500182501182502182503182504182505182506182507182508182509182510182511182512182513182514182515182516182517182518182519182520182521182522182523182524182525182526182527182528182529182530182531182532182533182534182535182536182537182538182539182540182541182542182543182544182545182546182547182548182549182550182551182552182553182554182555182556182557182558182559182560182561182562182563182564182565182566182567182568182569182570182571182572182573182574182575182576182577182578182579182580182581182582182583182584182585182586182587182588182589182590182591182592182593182594182595182596182597182598182599182600182601182602182603182604182605182606182607182608182609182610182611182612182613182614182615182616182617182618182619182620182621182622182623182624182625182626182627182628182629182630182631182632182633182634182635182636182637182638182639182640182641182642182643182644182645182646182647182648182649182650182651182652182653182654182655182656182657182658182659182660182661182662182663182664182665182666182667182668182669182670182671182672182673182674182675182676182677182678182679182680182681182682182683182684182685182686182687182688182689182690182691182692182693182694182695182696182697182698182699182700182701182702182703182704182705182706182707182708182709182710182711182712182713182714182715182716182717182718182719182720182721182722182723182724182725182726182727182728182729182730182731182732182733182734182735182736182737182738182739182740182741182742182743182744182745182746182747182748182749182750182751182752182753182754182755182756182757182758182759182760182761182762182763182764182765182766182767182768182769182770182771182772182773182774182775182776182777182778182779182780182781182782182783182784182785182786182787182788182789182790182791182792182793182794182795182796182797182798182799182800182801182802182803182804182805182806182807182808182809182810182811182812182813182814182815182816182817182818182819182820182821182822182823182824182825182826182827182828182829182830182831182832182833182834182835182836182837182838182839182840182841182842182843182844182845182846182847182848182849182850182851182852182853182854182855182856182857182858182859182860182861182862182863182864182865182866182867182868182869182870182871182872182873182874182875182876182877182878182879182880182881182882182883182884182885182886182887182888182889182890182891182892182893182894182895182896182897182898182899182900182901182902182903182904182905182906182907182908182909182910182911182912182913182914182915182916182917182918182919182920182921182922182923182924182925182926182927182928182929182930182931182932182933182934182935182936182937182938182939182940182941182942182943182944182945182946182947182948182949182950182951182952182953182954182955182956182957182958182959182960182961182962182963182964182965182966182967182968182969182970182971182972182973182974182975182976182977182978182979182980182981182982182983182984182985182986182987182988182989182990182991182992182993182994182995182996182997182998182999183000183001183002183003183004183005183006183007183008183009183010183011183012183013183014183015183016183017183018183019183020183021183022183023183024183025183026183027183028183029183030183031183032183033183034183035183036183037183038183039183040183041183042183043183044183045183046183047183048183049183050183051183052183053183054183055183056183057183058183059183060183061183062183063183064183065183066183067183068183069183070183071183072183073183074183075183076183077183078183079183080183081183082183083183084183085183086183087183088183089183090183091183092183093183094183095183096183097183098183099183100183101183102183103183104183105183106183107183108183109183110183111183112183113183114183115183116183117183118183119183120183121183122183123183124183125183126183127183128183129183130183131183132183133183134183135183136183137183138183139183140183141183142183143183144183145183146183147183148183149183150183151183152183153183154183155183156183157183158183159183160183161183162183163183164183165183166183167183168183169183170183171183172183173183174183175183176183177183178183179183180183181183182183183183184183185183186183187183188183189183190183191183192183193183194183195183196183197183198183199183200183201183202183203183204183205183206183207183208183209183210183211183212183213183214183215183216183217183218183219183220183221183222183223183224183225183226183227183228183229183230183231183232183233183234183235183236183237183238183239183240183241183242183243183244183245183246183247183248183249183250183251183252183253183254183255183256183257183258183259183260183261183262183263183264183265183266183267183268183269183270183271183272183273183274183275183276183277183278183279183280183281183282183283183284183285183286183287183288183289183290183291183292183293183294183295183296183297183298183299183300183301183302183303183304183305183306183307183308183309183310183311183312183313183314183315183316183317183318183319183320183321183322183323183324183325183326183327183328183329183330183331183332183333183334183335183336183337183338183339183340183341183342183343183344183345183346183347183348183349183350183351183352183353183354183355183356183357183358183359183360183361183362183363183364183365183366183367183368183369183370183371183372183373183374183375183376183377183378183379183380183381183382183383183384183385183386183387183388183389183390183391183392183393183394183395183396183397183398183399183400183401183402183403183404183405183406183407183408183409183410183411183412183413183414183415183416183417183418183419183420183421183422183423183424183425183426183427183428183429183430183431183432183433183434183435183436183437183438183439183440183441183442183443183444183445183446183447183448183449183450183451183452183453183454183455183456183457183458183459183460183461183462183463183464183465183466183467183468183469183470183471183472183473183474183475183476183477183478183479183480183481183482183483183484183485183486183487183488183489183490183491183492183493183494183495183496183497183498183499183500183501183502183503183504183505183506183507183508183509183510183511183512183513183514183515183516183517183518183519183520183521183522183523183524183525183526183527183528183529183530183531183532183533183534183535183536183537183538183539183540183541183542183543183544183545183546183547183548183549183550183551183552183553183554183555183556183557183558183559183560183561183562183563183564183565183566183567183568183569183570183571183572183573183574183575183576183577183578183579183580183581183582183583183584183585183586183587183588183589183590183591183592183593183594183595183596183597183598183599183600183601183602183603183604183605183606183607183608183609183610183611183612183613183614183615183616183617183618183619183620183621183622183623183624183625183626183627183628183629183630183631183632183633183634183635183636183637183638183639183640183641183642183643183644183645183646183647183648183649183650183651183652183653183654183655183656183657183658183659183660183661183662183663183664183665183666183667183668183669183670183671183672183673183674183675183676183677183678183679183680183681183682183683183684183685183686183687183688183689183690183691183692183693183694183695183696183697183698183699183700183701183702183703183704183705183706183707183708183709183710183711183712183713183714183715183716183717183718183719183720183721183722183723183724183725183726183727183728183729183730183731183732183733183734183735183736183737183738183739183740183741183742183743183744183745183746183747183748183749183750183751183752183753183754183755183756183757183758183759183760183761183762183763183764183765183766183767183768183769183770183771183772183773183774183775183776183777183778183779183780183781183782183783183784183785183786183787183788183789183790183791183792183793183794183795183796183797183798183799183800183801183802183803183804183805183806183807183808183809183810183811183812183813183814183815183816183817183818183819183820183821183822183823183824183825183826183827183828183829183830183831183832183833183834183835183836183837183838183839183840183841183842183843183844183845183846183847183848183849183850183851183852183853183854183855183856183857183858183859183860183861183862183863183864183865183866183867183868183869183870183871183872183873183874183875183876183877183878183879183880183881183882183883183884183885183886183887183888183889183890183891183892183893183894183895183896183897183898183899183900183901183902183903183904183905183906183907183908183909183910183911183912183913183914183915183916183917183918183919183920183921183922183923183924183925183926183927183928183929183930183931183932183933183934183935183936183937183938183939183940183941183942183943183944183945183946183947183948183949183950183951183952183953183954183955183956183957183958183959183960183961183962183963183964183965183966183967183968183969183970183971183972183973183974183975183976183977183978183979183980183981183982183983183984183985183986183987183988183989183990183991183992183993183994183995183996183997183998183999184000184001184002184003184004184005184006184007184008184009184010184011184012184013184014184015184016184017184018184019184020184021184022184023184024184025184026184027184028184029184030184031184032184033184034184035184036184037184038184039184040184041184042184043184044184045184046184047184048184049184050184051184052184053184054184055184056184057184058184059184060184061184062184063184064184065184066184067184068184069184070184071184072184073184074184075184076184077184078184079184080184081184082184083184084184085184086184087184088184089184090184091184092184093184094184095184096184097184098184099184100184101184102184103184104184105184106184107184108184109184110184111184112184113184114184115184116184117184118184119184120184121184122184123184124184125184126184127184128184129184130184131184132184133184134184135184136184137184138184139184140184141184142184143184144184145184146184147184148184149184150184151184152184153184154184155184156184157184158184159184160184161184162184163184164184165184166184167184168184169184170184171184172184173184174184175184176184177184178184179184180184181184182184183184184184185184186184187184188184189184190184191184192184193184194184195184196184197184198184199184200184201184202184203184204184205184206184207184208184209184210184211184212184213184214184215184216184217184218184219184220184221184222184223184224184225184226184227184228184229184230184231184232184233184234184235184236184237184238184239184240184241184242184243184244184245184246184247184248184249184250184251184252184253184254184255184256184257184258184259184260184261184262184263184264184265184266184267184268184269184270184271184272184273184274184275184276184277184278184279184280184281184282184283184284184285184286184287184288184289184290184291184292184293184294184295184296184297184298184299184300184301184302184303184304184305184306184307184308184309184310184311184312184313184314184315184316184317184318184319184320184321184322184323184324184325184326184327184328184329184330184331184332184333184334184335184336184337184338184339184340184341184342184343184344184345184346184347184348184349184350184351184352184353184354184355184356184357184358184359184360184361184362184363184364184365184366184367184368184369184370184371184372184373184374184375184376184377184378184379184380184381184382184383184384184385184386184387184388184389184390184391184392184393184394184395184396184397184398184399184400184401184402184403184404184405184406184407184408184409184410184411184412184413184414184415184416184417184418184419184420184421184422184423184424184425184426184427184428184429184430184431184432184433184434184435184436184437184438184439184440184441184442184443184444184445184446184447184448184449184450184451184452184453184454184455184456184457184458184459184460184461184462184463184464184465184466184467184468184469184470184471184472184473184474184475184476184477184478184479184480184481184482184483184484184485184486184487184488184489184490184491184492184493184494184495184496184497184498184499184500184501184502184503184504184505184506184507184508184509184510184511184512184513184514184515184516184517184518184519184520184521184522184523184524184525184526184527184528184529184530184531184532184533184534184535184536184537184538184539184540184541184542184543184544184545184546184547184548184549184550184551184552184553184554184555184556184557184558184559184560184561184562184563184564184565184566184567184568184569184570184571184572184573184574184575184576184577184578184579184580184581184582184583184584184585184586184587184588184589184590184591184592184593184594184595184596184597184598184599184600184601184602184603184604184605184606184607184608184609184610184611184612184613184614184615184616184617184618184619184620184621184622184623184624184625184626184627184628184629184630184631184632184633184634184635184636184637184638184639184640184641184642184643184644184645184646184647184648184649184650184651184652184653184654184655184656184657184658184659184660184661184662184663184664184665184666184667184668184669184670184671184672184673184674184675184676184677184678184679184680184681184682184683184684184685184686184687184688184689184690184691184692184693184694184695184696184697184698184699184700184701184702184703184704184705184706184707184708184709184710184711184712184713184714184715184716184717184718184719184720184721184722184723184724184725184726184727184728184729184730184731184732184733184734184735184736184737184738184739184740184741184742184743184744184745184746184747184748184749184750184751184752184753184754184755184756184757184758184759184760184761184762184763184764184765184766184767184768184769184770184771184772184773184774184775184776184777184778184779184780184781184782184783184784184785184786184787184788184789184790184791184792184793184794184795184796184797184798184799184800184801184802184803184804184805184806184807184808184809184810184811184812184813184814184815184816184817184818184819184820184821184822184823184824184825184826184827184828184829184830184831184832184833184834184835184836184837184838184839184840184841184842184843184844184845184846184847184848184849184850184851184852184853184854184855184856184857184858184859184860184861184862184863184864184865184866184867184868184869184870184871184872184873184874184875184876184877184878184879184880184881184882184883184884184885184886184887184888184889184890184891184892184893184894184895184896184897184898184899184900184901184902184903184904184905184906184907184908184909184910184911184912184913184914184915184916184917184918184919184920184921184922184923184924184925184926184927184928184929184930184931184932184933184934184935184936184937184938184939184940184941184942184943184944184945184946184947184948184949184950184951184952184953184954184955184956184957184958184959184960184961184962184963184964184965184966184967184968184969184970184971184972184973184974184975184976184977184978184979184980184981184982184983184984184985184986184987184988184989184990184991184992184993184994184995184996184997184998184999185000185001185002185003185004185005185006185007185008185009185010185011185012185013185014185015185016185017185018185019185020185021185022185023185024185025185026185027185028185029185030185031185032185033185034185035185036185037185038185039185040185041185042185043185044185045185046185047185048185049185050185051185052185053185054185055185056185057185058185059185060185061185062185063185064185065185066185067185068185069185070185071185072185073185074185075185076185077185078185079185080185081185082185083185084185085185086185087185088185089185090185091185092185093185094185095185096185097185098185099185100185101185102185103185104185105185106185107185108185109185110185111185112185113185114185115185116185117185118185119185120185121185122185123185124185125185126185127185128185129185130185131185132185133185134185135185136185137185138185139185140185141185142185143185144185145185146185147185148185149185150185151185152185153185154185155185156185157185158185159185160185161185162185163185164185165185166185167185168185169185170185171185172185173185174185175185176185177185178185179185180185181185182185183185184185185185186185187185188185189185190185191185192185193185194185195185196185197185198185199185200185201185202185203185204185205185206185207185208185209185210185211185212185213185214185215185216185217185218185219185220185221185222185223185224185225185226185227185228185229185230185231185232185233185234185235185236185237185238185239185240185241185242185243185244185245185246185247185248185249185250185251185252185253185254185255185256185257185258185259185260185261185262185263185264185265185266185267185268185269185270185271185272185273185274185275185276185277185278185279185280185281185282185283185284185285185286185287185288185289185290185291185292185293185294185295185296185297185298185299185300185301185302185303185304185305185306185307185308185309185310185311185312185313185314185315185316185317185318185319185320185321185322185323185324185325185326185327185328185329185330185331185332185333185334185335185336185337185338185339185340185341185342185343185344185345185346185347185348185349185350185351185352185353185354185355185356185357185358185359185360185361185362185363185364185365185366185367185368185369185370185371185372185373185374185375185376185377185378185379185380185381185382185383185384185385185386185387185388185389185390185391185392185393185394185395185396185397185398185399185400185401185402185403185404185405185406185407185408185409185410185411185412185413185414185415185416185417185418185419185420185421185422185423185424185425185426185427185428185429185430185431185432185433185434185435185436185437185438185439185440185441185442185443185444185445185446185447185448185449185450185451185452185453185454185455185456185457185458185459185460185461185462185463185464185465185466185467185468185469185470185471185472185473185474185475185476185477185478185479185480185481185482185483185484185485185486185487185488185489185490185491185492185493185494185495185496185497185498185499185500185501185502185503185504185505185506185507185508185509185510185511185512185513185514185515185516185517185518185519185520185521185522185523185524185525185526185527185528185529185530185531185532185533185534185535185536185537185538185539185540185541185542185543185544185545185546185547185548185549185550185551185552185553185554185555185556185557185558185559185560185561185562185563185564185565185566185567185568185569185570185571185572185573185574185575185576185577185578185579185580185581185582185583185584185585185586185587185588185589185590185591185592185593185594185595185596185597185598185599185600185601185602185603185604185605185606185607185608185609185610185611185612185613185614185615185616185617185618185619185620185621185622185623185624185625185626185627185628185629185630185631185632185633185634185635185636185637185638185639185640185641185642185643185644185645185646185647185648185649185650185651185652185653185654185655185656185657185658185659185660185661185662185663185664185665185666185667185668185669185670185671185672185673185674185675185676185677185678185679185680185681185682185683185684185685185686185687185688185689185690185691185692185693185694185695185696185697185698185699185700185701185702185703185704185705185706185707185708185709185710185711185712185713185714185715185716185717185718185719185720185721185722185723185724185725185726185727185728185729185730185731185732185733185734185735185736185737185738185739185740185741185742185743185744185745185746185747185748185749185750185751185752185753185754185755185756185757185758185759185760185761185762185763185764185765185766185767185768185769185770185771185772185773185774185775185776185777185778185779185780185781185782185783185784185785185786185787185788185789185790185791185792185793185794185795185796185797185798185799185800185801185802185803185804185805185806185807185808185809185810185811185812185813185814185815185816185817185818185819185820185821185822185823185824185825185826185827185828185829185830185831185832185833185834185835185836185837185838185839185840185841185842185843185844185845185846185847185848185849185850185851185852185853185854185855185856185857185858185859185860185861185862185863185864185865185866185867185868185869185870185871185872185873185874185875185876185877185878185879185880185881185882185883185884185885185886185887185888185889185890185891185892185893185894185895185896185897185898185899185900185901185902185903185904185905185906185907185908185909185910185911185912185913185914185915185916185917185918185919185920185921185922185923185924185925185926185927185928185929185930185931185932185933185934185935185936185937185938185939185940185941185942185943185944185945185946185947185948185949185950185951185952185953185954185955185956185957185958185959185960185961185962185963185964185965185966185967185968185969185970185971185972185973185974185975185976185977185978185979185980185981185982185983185984185985185986185987185988185989185990185991185992185993185994185995185996185997185998185999186000186001186002186003186004186005186006186007186008186009186010186011186012186013186014186015186016186017186018186019186020186021186022186023186024186025186026186027186028186029186030186031186032186033186034186035186036186037186038186039186040186041186042186043186044186045186046186047186048186049186050186051186052186053186054186055186056186057186058186059186060186061186062186063186064186065186066186067186068186069186070186071186072186073186074186075186076186077186078186079186080186081186082186083186084186085186086186087186088186089186090186091186092186093186094186095186096186097186098186099186100186101186102186103186104186105186106186107186108186109186110186111186112186113186114186115186116186117186118186119186120186121186122186123186124186125186126186127186128186129186130186131186132186133186134186135186136186137186138186139186140186141186142186143186144186145186146186147186148186149186150186151186152186153186154186155186156186157186158186159186160186161186162186163186164186165186166186167186168186169186170186171186172186173186174186175186176186177186178186179186180186181186182186183186184186185186186186187186188186189186190186191186192186193186194186195186196186197186198186199186200186201186202186203186204186205186206186207186208186209186210186211186212186213186214186215186216186217186218186219186220186221186222186223186224186225186226186227186228186229186230186231186232186233186234186235186236186237186238186239186240186241186242186243186244186245186246186247186248186249186250186251186252186253186254186255186256186257186258186259186260186261186262186263186264186265186266186267186268186269186270186271186272186273186274186275186276186277186278186279186280186281186282186283186284186285186286186287186288186289186290186291186292186293186294186295186296186297186298186299186300186301186302186303186304186305186306186307186308186309186310186311186312186313186314186315186316186317186318186319186320186321186322186323186324186325186326186327186328186329186330186331186332186333186334186335186336186337186338186339186340186341186342186343186344186345186346186347186348186349186350186351186352186353186354186355186356186357186358186359186360186361186362186363186364186365186366186367186368186369186370186371186372186373186374186375186376186377186378186379186380186381186382186383186384186385186386186387186388186389186390186391186392186393186394186395186396186397186398186399186400186401186402186403186404186405186406186407186408186409186410186411186412186413186414186415186416186417186418186419186420186421186422186423186424186425186426186427186428186429186430186431186432186433186434186435186436186437186438186439186440186441186442186443186444186445186446186447186448186449186450186451186452186453186454186455186456186457186458186459186460186461186462186463186464186465186466186467186468186469186470186471186472186473186474186475186476186477186478186479186480186481186482186483186484186485186486186487186488186489186490186491186492186493186494186495186496186497186498186499186500186501186502186503186504186505186506186507186508186509186510186511186512186513186514186515186516186517186518186519186520186521186522186523186524186525186526186527186528186529186530186531186532186533186534186535186536186537186538186539186540186541186542186543186544186545186546186547186548186549186550186551186552186553186554186555186556186557186558186559186560186561186562186563186564186565186566186567186568186569186570186571186572186573186574186575186576186577186578186579186580186581186582186583186584186585186586186587186588186589186590186591186592186593186594186595186596186597186598186599186600186601186602186603186604186605186606186607186608186609186610186611186612186613186614186615186616186617186618186619186620186621186622186623186624186625186626186627186628186629186630186631186632186633186634186635186636186637186638186639186640186641186642186643186644186645186646186647186648186649186650186651186652186653186654186655186656186657186658186659186660186661186662186663186664186665186666186667186668186669186670186671186672186673186674186675186676186677186678186679186680186681186682186683186684186685186686186687186688186689186690186691186692186693186694186695186696186697186698186699186700186701186702186703186704186705186706186707186708186709186710186711186712186713186714186715186716186717186718186719186720186721186722186723186724186725186726186727186728186729186730186731186732186733186734186735186736186737186738186739186740186741186742186743186744186745186746186747186748186749186750186751186752186753186754186755186756186757186758186759186760186761186762186763186764186765186766186767186768186769186770186771186772186773186774186775186776186777186778186779186780186781186782186783186784186785186786186787186788186789186790186791186792186793186794186795186796186797186798186799186800186801186802186803186804186805186806186807186808186809186810186811186812186813186814186815186816186817186818186819186820186821186822186823186824186825186826186827186828186829186830186831186832186833186834186835186836186837186838186839186840186841186842186843186844186845186846186847186848186849186850186851186852186853186854186855186856186857186858186859186860186861186862186863186864186865186866186867186868186869186870186871186872186873186874186875186876186877186878186879186880186881186882186883186884186885186886186887186888186889186890186891186892186893186894186895186896186897186898186899186900186901186902186903186904186905186906186907186908186909186910186911186912186913186914186915186916186917186918186919186920186921186922186923186924186925186926186927186928186929186930186931186932186933186934186935186936186937186938186939186940186941186942186943186944186945186946186947186948186949186950186951186952186953186954186955186956186957186958186959186960186961186962186963186964186965186966186967186968186969186970186971186972186973186974186975186976186977186978186979186980186981186982186983186984186985186986186987186988186989186990186991186992186993186994186995186996186997186998186999187000187001187002187003187004187005187006187007187008187009187010187011187012187013187014187015187016187017187018187019187020187021187022187023187024187025187026187027187028187029187030187031187032187033187034187035187036187037187038187039187040187041187042187043187044187045187046187047187048187049187050187051187052187053187054187055187056187057187058187059187060187061187062187063187064187065187066187067187068187069187070187071187072187073187074187075187076187077187078187079187080187081187082187083187084187085187086187087187088187089187090187091187092187093187094187095187096187097187098187099187100187101187102187103187104187105187106187107187108187109187110187111187112187113187114187115187116187117187118187119187120187121187122187123187124187125187126187127187128187129187130187131187132187133187134187135187136187137187138187139187140187141187142187143187144187145187146187147187148187149187150187151187152187153187154187155187156187157187158187159187160187161187162187163187164187165187166187167187168187169187170187171187172187173187174187175187176187177187178187179187180187181187182187183187184187185187186187187187188187189187190187191187192187193187194187195187196187197187198187199187200187201187202187203187204187205187206187207187208187209187210187211187212187213187214187215187216187217187218187219187220187221187222187223187224187225187226187227187228187229187230187231187232187233187234187235187236187237187238187239187240187241187242187243187244187245187246187247187248187249187250187251187252187253187254187255187256187257187258187259187260187261187262187263187264187265187266187267187268187269187270187271187272187273187274187275187276187277187278187279187280187281187282187283187284187285187286187287187288187289187290187291187292187293187294187295187296187297187298187299187300187301187302187303187304187305187306187307187308187309187310187311187312187313187314187315187316187317187318187319187320187321187322187323187324187325187326187327187328187329187330187331187332187333187334187335187336187337187338187339187340187341187342187343187344187345187346187347187348187349187350187351187352187353187354187355187356187357187358187359187360187361187362187363187364187365187366187367187368187369187370187371187372187373187374187375187376187377187378187379187380187381187382187383187384187385187386187387187388187389187390187391187392187393187394187395187396187397187398187399187400187401187402187403187404187405187406187407187408187409187410187411187412187413187414187415187416187417187418187419187420187421187422187423187424187425187426187427187428187429187430187431187432187433187434187435187436187437187438187439187440187441187442187443187444187445187446187447187448187449187450187451187452187453187454187455187456187457187458187459187460187461187462187463187464187465187466187467187468187469187470187471187472187473187474187475187476187477187478187479187480187481187482187483187484187485187486187487187488187489187490187491187492187493187494187495187496187497187498187499187500187501187502187503187504187505187506187507187508187509187510187511187512187513187514187515187516187517187518187519187520187521187522187523187524187525187526187527187528187529187530187531187532187533187534187535187536187537187538187539187540187541187542187543187544187545187546187547187548187549187550187551187552187553187554187555187556187557187558187559187560187561187562187563187564187565187566187567187568187569187570187571187572187573187574187575187576187577187578187579187580187581187582187583187584187585187586187587187588187589187590187591187592187593187594187595187596187597187598187599187600187601187602187603187604187605187606187607187608187609187610187611187612187613187614187615187616187617187618187619187620187621187622187623187624187625187626187627187628187629187630187631187632187633187634187635187636187637187638187639187640187641187642187643187644187645187646187647187648187649187650187651187652187653187654187655187656187657187658187659187660187661187662187663187664187665187666187667187668187669187670187671187672187673187674187675187676187677187678187679187680187681187682187683187684187685187686187687187688187689187690187691187692187693187694187695187696187697187698187699187700187701187702187703187704187705187706187707187708187709187710187711187712187713187714187715187716187717187718187719187720187721187722187723187724187725187726187727187728187729187730187731187732187733187734187735187736187737187738187739187740187741187742187743187744187745187746187747187748187749187750187751187752187753187754187755187756187757187758187759187760187761187762187763187764187765187766187767187768187769187770187771187772187773187774187775187776187777187778187779187780187781187782187783187784187785187786187787187788187789187790187791187792187793187794187795187796187797187798187799187800187801187802187803187804187805187806187807187808187809187810187811187812187813187814187815187816187817187818187819187820187821187822187823187824187825187826187827187828187829187830187831187832187833187834187835187836187837187838187839187840187841187842187843187844187845187846187847187848187849187850187851187852187853187854187855187856187857187858187859187860187861187862187863187864187865187866187867187868187869187870187871187872187873187874187875187876187877187878187879187880187881187882187883187884187885187886187887187888187889187890187891187892187893187894187895187896187897187898187899187900187901187902187903187904187905187906187907187908187909187910187911187912187913187914187915187916187917187918187919187920187921187922187923187924187925187926187927187928187929187930187931187932187933187934187935187936187937187938187939187940187941187942187943187944187945187946187947187948187949187950187951187952187953187954187955187956187957187958187959187960187961187962187963187964187965187966187967187968187969187970187971187972187973187974187975187976187977187978187979187980187981187982187983187984187985187986187987187988187989187990187991187992187993187994187995187996187997187998187999188000188001188002188003188004188005188006188007188008188009188010188011188012188013188014188015188016188017188018188019188020188021188022188023188024188025188026188027188028188029188030188031188032188033188034188035188036188037188038188039188040188041188042188043188044188045188046188047188048188049188050188051188052188053188054188055188056188057188058188059188060188061188062188063188064188065188066188067188068188069188070188071188072188073188074188075188076188077188078188079188080188081188082188083188084188085188086188087188088188089188090188091188092188093188094188095188096188097188098188099188100188101188102188103188104188105188106188107188108188109188110188111188112188113188114188115188116188117188118188119188120188121188122188123188124188125188126188127188128188129188130188131188132188133188134188135188136188137188138188139188140188141188142188143188144188145188146188147188148188149188150188151188152188153188154188155188156188157188158188159188160188161188162188163188164188165188166188167188168188169188170188171188172188173188174188175188176188177188178188179188180188181188182188183188184188185188186188187188188188189188190188191188192188193188194188195188196188197188198188199188200188201188202188203188204188205188206188207188208188209188210188211188212188213188214188215188216188217188218188219188220188221188222188223188224188225188226188227188228188229188230188231188232188233188234188235188236188237188238188239188240188241188242188243188244188245188246188247188248188249188250188251188252188253188254188255188256188257188258188259188260188261188262188263188264188265188266188267188268188269188270188271188272188273188274188275188276188277188278188279188280188281188282188283188284188285188286188287188288188289188290188291188292188293188294188295188296188297188298188299188300188301188302188303188304188305188306188307188308188309188310188311188312188313188314188315188316188317188318188319188320188321188322188323188324188325188326188327188328188329188330188331188332188333188334188335188336188337188338188339188340188341188342188343188344188345188346188347188348188349188350188351188352188353188354188355188356188357188358188359188360188361188362188363188364188365188366188367188368188369188370188371188372188373188374188375188376188377188378188379188380188381188382188383188384188385188386188387188388188389188390188391188392188393188394188395188396188397188398188399188400188401188402188403188404188405188406188407188408188409188410188411188412188413188414188415188416188417188418188419188420188421188422188423188424188425188426188427188428188429188430188431188432188433188434188435188436188437188438188439188440188441188442188443188444188445188446188447188448188449188450188451188452188453188454188455188456188457188458188459188460188461188462188463188464188465188466188467188468188469188470188471188472188473188474188475188476188477188478188479188480188481188482188483188484188485188486188487188488188489188490188491188492188493188494188495188496188497188498188499188500188501188502188503188504188505188506188507188508188509188510188511188512188513188514188515188516188517188518188519188520188521188522188523188524188525188526188527188528188529188530188531188532188533188534188535188536188537188538188539188540188541188542188543188544188545188546188547188548188549188550188551188552188553188554188555188556188557188558188559188560188561188562188563188564188565188566188567188568188569188570188571188572188573188574188575188576188577188578188579188580188581188582188583188584188585188586188587188588188589188590188591188592188593188594188595188596188597188598188599188600188601188602188603188604188605188606188607188608188609188610188611188612188613188614188615188616188617188618188619188620188621188622188623188624188625188626188627188628188629188630188631188632188633188634188635188636188637188638188639188640188641188642188643188644188645188646188647188648188649188650188651188652188653188654188655188656188657188658188659188660188661188662188663188664188665188666188667188668188669188670188671188672188673188674188675188676188677188678188679188680188681188682188683188684188685188686188687188688188689188690188691188692188693188694188695188696188697188698188699188700188701188702188703188704188705188706188707188708188709188710188711188712188713188714188715188716188717188718188719188720188721188722188723188724188725188726188727188728188729188730188731188732188733188734188735188736188737188738188739188740188741188742188743188744188745188746188747188748188749188750188751188752188753188754188755188756188757188758188759188760188761188762188763188764188765188766188767188768188769188770188771188772188773188774188775188776188777188778188779188780188781188782188783188784188785188786188787188788188789188790188791188792188793188794188795188796188797188798188799188800188801188802188803188804188805188806188807188808188809188810188811188812188813188814188815188816188817188818188819188820188821188822188823188824188825188826188827188828188829188830188831188832188833188834188835188836188837188838188839188840188841188842188843188844188845188846188847188848188849188850188851188852188853188854188855188856188857188858188859188860188861188862188863188864188865188866188867188868188869188870188871188872188873188874188875188876188877188878188879188880188881188882188883188884188885188886188887188888188889188890188891188892188893188894188895188896188897188898188899188900188901188902188903188904188905188906188907188908188909188910188911188912188913188914188915188916188917188918188919188920188921188922188923188924188925188926188927188928188929188930188931188932188933188934188935188936188937188938188939188940188941188942188943188944188945188946188947188948188949188950188951188952188953188954188955188956188957188958188959188960188961188962188963188964188965188966188967188968188969188970188971188972188973188974188975188976188977188978188979188980188981188982188983188984188985188986188987188988188989188990188991188992188993188994188995188996188997188998188999189000189001189002189003189004189005189006189007189008189009189010189011189012189013189014189015189016189017189018189019189020189021189022189023189024189025189026189027189028189029189030189031189032189033189034189035189036189037189038189039189040189041189042189043189044189045189046189047189048189049189050189051189052189053189054189055189056189057189058189059189060189061189062189063189064189065189066189067189068189069189070189071189072189073189074189075189076189077189078189079189080189081189082189083189084189085189086189087189088189089189090189091189092189093189094189095189096189097189098189099189100189101189102189103189104189105189106189107189108189109189110189111189112189113189114189115189116189117189118189119189120189121189122189123189124189125189126189127189128189129189130189131189132189133189134189135189136189137189138189139189140189141189142189143189144189145189146189147189148189149189150189151189152189153189154189155189156189157189158189159189160189161189162189163189164189165189166189167189168189169189170189171189172189173189174189175189176189177189178189179189180189181189182189183189184189185189186189187189188189189189190189191189192189193189194189195189196189197189198189199189200189201189202189203189204189205189206189207189208189209189210189211189212189213189214189215189216189217189218189219189220189221189222189223189224189225189226189227189228189229189230189231189232189233189234189235189236189237189238189239189240189241189242189243189244189245189246189247189248189249189250189251189252189253189254189255189256189257189258189259189260189261189262189263189264189265189266189267189268189269189270189271189272189273189274189275189276189277189278189279189280189281189282189283189284189285189286189287189288189289189290189291189292189293189294189295189296189297189298189299189300189301189302189303189304189305189306189307189308189309189310189311189312189313189314189315189316189317189318189319189320189321189322189323189324189325189326189327189328189329189330189331189332189333189334189335189336189337189338189339189340189341189342189343189344189345189346189347189348189349189350189351189352189353189354189355189356189357189358189359189360189361189362189363189364189365189366189367189368189369189370189371189372189373189374189375189376189377189378189379189380189381189382189383189384189385189386189387189388189389189390189391189392189393189394189395189396189397189398189399189400189401189402189403189404189405189406189407189408189409189410189411189412189413189414189415189416189417189418189419189420189421189422189423189424189425189426189427189428189429189430189431189432189433189434189435189436189437189438189439189440189441189442189443189444189445189446189447189448189449189450189451189452189453189454189455189456189457189458189459189460189461189462189463189464189465189466189467189468189469189470189471189472189473189474189475189476189477189478189479189480189481189482189483189484189485189486189487189488189489189490189491189492189493189494189495189496189497189498189499189500189501189502189503189504189505189506189507189508189509189510189511189512189513189514189515189516189517189518189519189520189521189522189523189524189525189526189527189528189529189530189531189532189533189534189535189536189537189538189539189540189541189542189543189544189545189546189547189548189549189550189551189552189553189554189555189556189557189558189559189560189561189562189563189564189565189566189567189568189569189570189571189572189573189574189575189576189577189578189579189580189581189582189583189584189585189586189587189588189589189590189591189592189593189594189595189596189597189598189599189600189601189602189603189604189605189606189607189608189609189610189611189612189613189614189615189616189617189618189619189620189621189622189623189624189625189626189627189628189629189630189631189632189633189634189635189636189637189638189639189640189641189642189643189644189645189646189647189648189649189650189651189652189653189654189655189656189657189658189659189660189661189662189663189664189665189666189667189668189669189670189671189672189673189674189675189676189677189678189679189680189681189682189683189684189685189686189687189688189689189690189691189692189693189694189695189696189697189698189699189700189701189702189703189704189705189706189707189708189709189710189711189712189713189714189715189716189717189718189719189720189721189722189723189724189725189726189727189728189729189730189731189732189733189734189735189736189737189738189739189740189741189742189743189744189745189746189747189748189749189750189751189752189753189754189755189756189757189758189759189760189761189762189763189764189765189766189767189768189769189770189771189772189773189774189775189776189777189778189779189780189781189782189783189784189785189786189787189788189789189790189791189792189793189794189795189796189797189798189799189800189801189802189803189804189805189806189807189808189809189810189811189812189813189814189815189816189817189818189819189820189821189822189823189824189825189826189827189828189829189830189831189832189833189834189835189836189837189838189839189840189841189842189843189844189845189846189847189848189849189850189851189852189853189854189855189856189857189858189859189860189861189862189863189864189865189866189867189868189869189870189871189872189873189874189875189876189877189878189879189880189881189882189883189884189885189886189887189888189889189890189891189892189893189894189895189896189897189898189899189900189901189902189903189904189905189906189907189908189909189910189911189912189913189914189915189916189917189918189919189920189921189922189923189924189925189926189927189928189929189930189931189932189933189934189935189936189937189938189939189940189941189942189943189944189945189946189947189948189949189950189951189952189953189954189955189956189957189958189959189960189961189962189963189964189965189966189967189968189969189970189971189972189973189974189975189976189977189978189979189980189981189982189983189984189985189986189987189988189989189990189991189992189993189994189995189996189997189998189999190000190001190002190003190004190005190006190007190008190009190010190011190012190013190014190015190016190017190018190019190020190021190022190023190024190025190026190027190028190029190030190031190032190033190034190035190036190037190038190039190040190041190042190043190044190045190046190047190048190049190050190051190052190053190054190055190056190057190058190059190060190061190062190063190064190065190066190067190068190069190070190071190072190073190074190075190076190077190078190079190080190081190082190083190084190085190086190087190088190089190090190091190092190093190094190095190096190097190098190099190100190101190102190103190104190105190106190107190108190109190110190111190112190113190114190115190116190117190118190119190120190121190122190123190124190125190126190127190128190129190130190131190132190133190134190135190136190137190138190139190140190141190142190143190144190145190146190147190148190149190150190151190152190153190154190155190156190157190158190159190160190161190162190163190164190165190166190167190168190169190170190171190172190173190174190175190176190177190178190179190180190181190182190183190184190185190186190187190188190189190190190191190192190193190194190195190196190197190198190199190200190201190202190203190204190205190206190207190208190209190210190211190212190213190214190215190216190217190218190219190220190221190222190223190224190225190226190227190228190229190230190231190232190233190234190235190236190237190238190239190240190241190242190243190244190245190246190247190248190249190250190251190252190253190254190255190256190257190258190259190260190261190262190263190264190265190266190267190268190269190270190271190272190273190274190275190276190277190278190279190280190281190282190283190284190285190286190287190288190289190290190291190292190293190294190295190296190297190298190299190300190301190302190303190304190305190306190307190308190309190310190311190312190313190314190315190316190317190318190319190320190321190322190323190324190325190326190327190328190329190330190331190332190333190334190335190336190337190338190339190340190341190342190343190344190345190346190347190348190349190350190351190352190353190354190355190356190357190358190359190360190361190362190363190364190365190366190367190368190369190370190371190372190373190374190375190376190377190378190379190380190381190382190383190384190385190386190387190388190389190390190391190392190393190394190395190396190397190398190399190400190401190402190403190404190405190406190407190408190409190410190411190412190413190414190415190416190417190418190419190420190421190422190423190424190425190426190427190428190429190430190431190432190433190434190435190436190437190438190439190440190441190442190443190444190445190446190447190448190449190450190451190452190453190454190455190456190457190458190459190460190461190462190463190464190465190466190467190468190469190470190471190472190473190474190475190476190477190478190479190480190481190482190483190484190485190486190487190488190489190490190491190492190493190494190495190496190497190498190499190500190501190502190503190504190505190506190507190508190509190510190511190512190513190514190515190516190517190518190519190520190521190522190523190524190525190526190527190528190529190530190531190532190533190534190535190536190537190538190539190540190541190542190543190544190545190546190547190548190549190550190551190552190553190554190555190556190557190558190559190560190561190562190563190564190565190566190567190568190569190570190571190572190573190574190575190576190577190578190579190580190581190582190583190584190585190586190587190588190589190590190591190592190593190594190595190596190597190598190599190600190601190602190603190604190605190606190607190608190609190610190611190612190613190614190615190616190617190618190619190620190621190622190623190624190625190626190627190628190629190630190631190632190633190634190635190636190637190638190639190640190641190642190643190644190645190646190647190648190649190650190651190652190653190654190655190656190657190658190659190660190661190662190663190664190665190666190667190668190669190670190671190672190673190674190675190676190677190678190679190680190681190682190683190684190685190686190687190688190689190690190691190692190693190694190695190696190697190698190699190700190701190702190703190704190705190706190707190708190709190710190711190712190713190714190715190716190717190718190719190720190721190722190723190724190725190726190727190728190729190730190731190732190733190734190735190736190737190738190739190740190741190742190743190744190745190746190747190748190749190750190751190752190753190754190755190756190757190758190759190760190761190762190763190764190765190766190767190768190769190770190771190772190773190774190775190776190777190778190779190780190781190782190783190784190785190786190787190788190789190790190791190792190793190794190795190796190797190798190799190800190801190802190803190804190805190806190807190808190809190810190811190812190813190814190815190816190817190818190819190820190821190822190823190824190825190826190827190828190829190830190831190832190833190834190835190836190837190838190839190840190841190842190843190844190845190846190847190848190849190850190851190852190853190854190855190856190857190858190859190860190861190862190863190864190865190866190867190868190869190870190871190872190873190874190875190876190877190878190879190880190881190882190883190884190885190886190887190888190889190890190891190892190893190894190895190896190897190898190899190900190901190902190903190904190905190906190907190908190909190910190911190912190913190914190915190916190917190918190919190920190921190922190923190924190925190926190927190928190929190930190931190932190933190934190935190936190937190938190939190940190941190942190943190944190945190946190947190948190949190950190951190952190953190954190955190956190957190958190959190960190961190962190963190964190965190966190967190968190969190970190971190972190973190974190975190976190977190978190979190980190981190982190983190984190985190986190987190988190989190990190991190992190993190994190995190996190997190998190999191000191001191002191003191004191005191006191007191008191009191010191011191012191013191014191015191016191017191018191019191020191021191022191023191024191025191026191027191028191029191030191031191032191033191034191035191036191037191038191039191040191041191042191043191044191045191046191047191048191049191050191051191052191053191054191055191056191057191058191059191060191061191062191063191064191065191066191067191068191069191070191071191072191073191074191075191076191077191078191079191080191081191082191083191084191085191086191087191088191089191090191091191092191093191094191095191096191097191098191099191100191101191102191103191104191105191106191107191108191109191110191111191112191113191114191115191116191117191118191119191120191121191122191123191124191125191126191127191128191129191130191131191132191133191134191135191136191137191138191139191140191141191142191143191144191145191146191147191148191149191150191151191152191153191154191155191156191157191158191159191160191161191162191163191164191165191166191167191168191169191170191171191172191173191174191175191176191177191178191179191180191181191182191183191184191185191186191187191188191189191190191191191192191193191194191195191196191197191198191199191200191201191202191203191204191205191206191207191208191209191210191211191212191213191214191215191216191217191218191219191220191221191222191223191224191225191226191227191228191229191230191231191232191233191234191235191236191237191238191239191240191241191242191243191244191245191246191247191248191249191250191251191252191253191254191255191256191257191258191259191260191261191262191263191264191265191266191267191268191269191270191271191272191273191274191275191276191277191278191279191280191281191282191283191284191285191286191287191288191289191290191291191292191293191294191295191296191297191298191299191300191301191302191303191304191305191306191307191308191309191310191311191312191313191314191315191316191317191318191319191320191321191322191323191324191325191326191327191328191329191330191331191332191333191334191335191336191337191338191339191340191341191342191343191344191345191346191347191348191349191350191351191352191353191354191355191356191357191358191359191360191361191362191363191364191365191366191367191368191369191370191371191372191373191374191375191376191377191378191379191380191381191382191383191384191385191386191387191388191389191390191391191392191393191394191395191396191397191398191399191400191401191402191403191404191405191406191407191408191409191410191411191412191413191414191415191416191417191418191419191420191421191422191423191424191425191426191427191428191429191430191431191432191433191434191435191436191437191438191439191440191441191442191443191444191445191446191447191448191449191450191451191452191453191454191455191456191457191458191459191460191461191462191463191464191465191466191467191468191469191470191471191472191473191474191475191476191477191478191479191480191481191482191483191484191485191486191487191488191489191490191491191492191493191494191495191496191497191498191499191500191501191502191503191504191505191506191507191508191509191510191511191512191513191514191515191516191517191518191519191520191521191522191523191524191525191526191527191528191529191530191531191532191533191534191535191536191537191538191539191540191541191542191543191544191545191546191547191548191549191550191551191552191553191554191555191556191557191558191559191560191561191562191563191564191565191566191567191568191569191570191571191572191573191574191575191576191577191578191579191580191581191582191583191584191585191586191587191588191589191590191591191592191593191594191595191596191597191598191599191600191601191602191603191604191605191606191607191608191609191610191611191612191613191614191615191616191617191618191619191620191621191622191623191624191625191626191627191628191629191630191631191632191633191634191635191636191637191638191639191640191641191642191643191644191645191646191647191648191649191650191651191652191653191654191655191656191657191658191659191660191661191662191663191664191665191666191667191668191669191670191671191672191673191674191675191676191677191678191679191680191681191682191683191684191685191686191687191688191689191690191691191692191693191694191695191696191697191698191699191700191701191702191703191704191705191706191707191708191709191710191711191712191713191714191715191716191717191718191719191720191721191722191723191724191725191726191727191728191729191730191731191732191733191734191735191736191737191738191739191740191741191742191743191744191745191746191747191748191749191750191751191752191753191754191755191756191757191758191759191760191761191762191763191764191765191766191767191768191769191770191771191772191773191774191775191776191777191778191779191780191781191782191783191784191785191786191787191788191789191790191791191792191793191794191795191796191797191798191799191800191801191802191803191804191805191806191807191808191809191810191811191812191813191814191815191816191817191818191819191820191821191822191823191824191825191826191827191828191829191830191831191832191833191834191835191836191837191838191839191840191841191842191843191844191845191846191847191848191849191850191851191852191853191854191855191856191857191858191859191860191861191862191863191864191865191866191867191868191869191870191871191872191873191874191875191876191877191878191879191880191881191882191883191884191885191886191887191888191889191890191891191892191893191894191895191896191897191898191899191900191901191902191903191904191905191906191907191908191909191910191911191912191913191914191915191916191917191918191919191920191921191922191923191924191925191926191927191928191929191930191931191932191933191934191935191936191937191938191939191940191941191942191943191944191945191946191947191948191949191950191951191952191953191954191955191956191957191958191959191960191961191962191963191964191965191966191967191968191969191970191971191972191973191974191975191976191977191978191979191980191981191982191983191984191985191986191987191988191989191990191991191992191993191994191995191996191997191998191999192000192001192002192003192004192005192006192007192008192009192010192011192012192013192014192015192016192017192018192019192020192021192022192023192024192025192026192027192028192029192030192031192032192033192034192035192036192037192038192039192040192041192042192043192044192045192046192047192048192049192050192051192052192053192054192055192056192057192058192059192060192061192062192063192064192065192066192067192068192069192070192071192072192073192074192075192076192077192078192079192080192081192082192083192084192085192086192087192088192089192090192091192092192093192094192095192096192097192098192099192100192101192102192103192104192105192106192107192108192109192110192111192112192113192114192115192116192117192118192119192120192121192122192123192124192125192126192127192128192129192130192131192132192133192134192135192136192137192138192139192140192141192142192143192144192145192146192147192148192149192150192151192152192153192154192155192156192157192158192159192160192161192162192163192164192165192166192167192168192169192170192171192172192173192174192175192176192177192178192179192180192181192182192183192184192185192186192187192188192189192190192191192192192193192194192195192196192197192198192199192200192201192202192203192204192205192206192207192208192209192210192211192212192213192214192215192216192217192218192219192220192221192222192223192224192225192226192227192228192229192230192231192232192233192234192235192236192237192238192239192240192241192242192243192244192245192246192247192248192249192250192251192252192253192254192255192256192257192258192259192260192261192262192263192264192265192266192267192268192269192270192271192272192273192274192275192276192277192278192279192280192281192282192283192284192285192286192287192288192289192290192291192292192293192294192295192296192297192298192299192300192301192302192303192304192305192306192307192308192309192310192311192312192313192314192315192316192317192318192319192320192321192322192323192324192325192326192327192328192329192330192331192332192333192334192335192336192337192338192339192340192341192342192343192344192345192346192347192348192349192350192351192352192353192354192355192356192357192358192359192360192361192362192363192364192365192366192367192368192369192370192371192372192373192374192375192376192377192378192379192380192381192382192383192384192385192386192387192388192389192390192391192392192393192394192395192396192397192398192399192400192401192402192403192404192405192406192407192408192409192410192411192412192413192414192415192416192417192418192419192420192421192422192423192424192425192426192427192428192429192430192431192432192433192434192435192436192437192438192439192440192441192442192443192444192445192446192447192448192449192450192451192452192453192454192455192456192457192458192459192460192461192462192463192464192465192466192467192468192469192470192471192472192473192474192475192476192477192478192479192480192481192482192483192484192485192486192487192488192489192490192491192492192493192494192495192496192497192498192499192500192501192502192503192504192505192506192507192508192509192510192511192512192513192514192515192516192517192518192519192520192521192522192523192524192525192526192527192528192529192530192531192532192533192534192535192536192537192538192539192540192541192542192543192544192545192546192547192548192549192550192551192552192553192554192555192556192557192558192559192560192561192562192563192564192565192566192567192568192569192570192571192572192573192574192575192576192577192578192579192580192581192582192583192584192585192586192587192588192589192590192591192592192593192594192595192596192597192598192599192600192601192602192603192604192605192606192607192608192609192610192611192612192613192614192615192616192617192618192619192620192621192622192623192624192625192626192627192628192629192630192631192632192633192634192635192636192637192638192639192640192641192642192643192644192645192646192647192648192649192650192651192652192653192654192655192656192657192658192659192660192661192662192663192664192665192666192667192668192669192670192671192672192673192674192675192676192677192678192679192680192681192682192683192684192685192686192687192688192689192690192691192692192693192694192695192696192697192698192699192700192701192702192703192704192705192706192707192708192709192710192711192712192713192714192715192716192717192718192719192720192721192722192723192724192725192726192727192728192729192730192731192732192733192734192735192736192737192738192739192740192741192742192743192744192745192746192747192748192749192750192751192752192753192754192755192756192757192758192759192760192761192762192763192764192765192766192767192768192769192770192771192772192773192774192775192776192777192778192779192780192781192782192783192784192785192786192787192788192789192790192791192792192793192794192795192796192797192798192799192800192801192802192803192804192805192806192807192808192809192810192811192812192813192814192815192816192817192818192819192820192821192822192823192824192825192826192827192828192829192830192831192832192833192834192835192836192837192838192839192840192841192842192843192844192845192846192847192848192849192850192851192852192853192854192855192856192857192858192859192860192861192862192863192864192865192866192867192868192869192870192871192872192873192874192875192876192877192878192879192880192881192882192883192884192885192886192887192888192889192890192891192892192893192894192895192896192897192898192899192900192901192902192903192904192905192906192907192908192909192910192911192912192913192914192915192916192917192918192919192920192921192922192923192924192925192926192927192928192929192930192931192932192933192934192935192936192937192938192939192940192941192942192943192944192945192946192947192948192949192950192951192952192953192954192955192956192957192958192959192960192961192962192963192964192965192966192967192968192969192970192971192972192973192974192975192976192977192978192979192980192981192982192983192984192985192986192987192988192989192990192991192992192993192994192995192996192997192998192999193000193001193002193003193004193005193006193007193008193009193010193011193012193013193014193015193016193017193018193019193020193021193022193023193024193025193026193027193028193029193030193031193032193033193034193035193036193037193038193039193040193041193042193043193044193045193046193047193048193049193050193051193052193053193054193055193056193057193058193059193060193061193062193063193064193065193066193067193068193069193070193071193072193073193074193075193076193077193078193079193080193081193082193083193084193085193086193087193088193089193090193091193092193093193094193095193096193097193098193099193100193101193102193103193104193105193106193107193108193109193110193111193112193113193114193115193116193117193118193119193120193121193122193123193124193125193126193127193128193129193130193131193132193133193134193135193136193137193138193139193140193141193142193143193144193145193146193147193148193149193150193151193152193153193154193155193156193157193158193159193160193161193162193163193164193165193166193167193168193169193170193171193172193173193174193175193176193177193178193179193180193181193182193183193184193185193186193187193188193189193190193191193192193193193194193195193196193197193198193199193200193201193202193203193204193205193206193207193208193209193210193211193212193213193214193215193216193217193218193219193220193221193222193223193224193225193226193227193228193229193230193231193232193233193234193235193236193237193238193239193240193241193242193243193244193245193246193247193248193249193250193251193252193253193254193255193256193257193258193259193260193261193262193263193264193265193266193267193268193269193270193271193272193273193274193275193276193277193278193279193280193281193282193283193284193285193286193287193288193289193290193291193292193293193294193295193296193297193298193299193300193301193302193303193304193305193306193307193308193309193310193311193312193313193314193315193316193317193318193319193320193321193322193323193324193325193326193327193328193329193330193331193332193333193334193335193336193337193338193339193340193341193342193343193344193345193346193347193348193349193350193351193352193353193354193355193356193357193358193359193360193361193362193363193364193365193366193367193368193369193370193371193372193373193374193375193376193377193378193379193380193381193382193383193384193385193386193387193388193389193390193391193392193393193394193395193396193397193398193399193400193401193402193403193404193405193406193407193408193409193410193411193412193413193414193415193416193417193418193419193420193421193422193423193424193425193426193427193428193429193430193431193432193433193434193435193436193437193438193439193440193441193442193443193444193445193446193447193448193449193450193451193452193453193454193455193456193457193458193459193460193461193462193463193464193465193466193467193468193469193470193471193472193473193474193475193476193477193478193479193480193481193482193483193484193485193486193487193488193489193490193491193492193493193494193495193496193497193498193499193500193501193502193503193504193505193506193507193508193509193510193511193512193513193514193515193516193517193518193519193520193521193522193523193524193525193526193527193528193529193530193531193532193533193534193535193536193537193538193539193540193541193542193543193544193545193546193547193548193549193550193551193552193553193554193555193556193557193558193559193560193561193562193563193564193565193566193567193568193569193570193571193572193573193574193575193576193577193578193579193580193581193582193583193584193585193586193587193588193589193590193591193592193593193594193595193596193597193598193599193600193601193602193603193604193605193606193607193608193609193610193611193612193613193614193615193616193617193618193619193620193621193622193623193624193625193626193627193628193629193630193631193632193633193634193635193636193637193638193639193640193641193642193643193644193645193646193647193648193649193650193651193652193653193654193655193656193657193658193659193660193661193662193663193664193665193666193667193668193669193670193671193672193673193674193675193676193677193678193679193680193681193682193683193684193685193686193687193688193689193690193691193692193693193694193695193696193697193698193699193700193701193702193703193704193705193706193707193708193709193710193711193712193713193714193715193716193717193718193719193720193721193722193723193724193725193726193727193728193729193730193731193732193733193734193735193736193737193738193739193740193741193742193743193744193745193746193747193748193749193750193751193752193753193754193755193756193757193758193759193760193761193762193763193764193765193766193767193768193769193770193771193772193773193774193775193776193777193778193779193780193781193782193783193784193785193786193787193788193789193790193791193792193793193794193795193796193797193798193799193800193801193802193803193804193805193806193807193808193809193810193811193812193813193814193815193816193817193818193819193820193821193822193823193824193825193826193827193828193829193830193831193832193833193834193835193836193837193838193839193840193841193842193843193844193845193846193847193848193849193850193851193852193853193854193855193856193857193858193859193860193861193862193863193864193865193866193867193868193869193870193871193872193873193874193875193876193877193878193879193880193881193882193883193884193885193886193887193888193889193890193891193892193893193894193895193896193897193898193899193900193901193902193903193904193905193906193907193908193909193910193911193912193913193914193915193916193917193918193919193920193921193922193923193924193925193926193927193928193929193930193931193932193933193934193935193936193937193938193939193940193941193942193943193944193945193946193947193948193949193950193951193952193953193954193955193956193957193958193959193960193961193962193963193964193965193966193967193968193969193970193971193972193973193974193975193976193977193978193979193980193981193982193983193984193985193986193987193988193989193990193991193992193993193994193995193996193997193998193999194000194001194002194003194004194005194006194007194008194009194010194011194012194013194014194015194016194017194018194019194020194021194022194023194024194025194026194027194028194029194030194031194032194033194034194035194036194037194038194039194040194041194042194043194044194045194046194047194048194049194050194051194052194053194054194055194056194057194058194059194060194061194062194063194064194065194066194067194068194069194070194071194072194073194074194075194076194077194078194079194080194081194082194083194084194085194086194087194088194089194090194091194092194093194094194095194096194097194098194099194100194101194102194103194104194105194106194107194108194109194110194111194112194113194114194115194116194117194118194119194120194121194122194123194124194125194126194127194128194129194130194131194132194133194134194135194136194137194138194139194140194141194142194143194144194145194146194147194148194149194150194151194152194153194154194155194156194157194158194159194160194161194162194163194164194165194166194167194168194169194170194171194172194173194174194175194176194177194178194179194180194181194182194183194184194185194186194187194188194189194190194191194192194193194194194195194196194197194198194199194200194201194202194203194204194205194206194207194208194209194210194211194212194213194214194215194216194217194218194219194220194221194222194223194224194225194226194227194228194229194230194231194232194233194234194235194236194237194238194239194240194241194242194243194244194245194246194247194248194249194250194251194252194253194254194255194256194257194258194259194260194261194262194263194264194265194266194267194268194269194270194271194272194273194274194275194276194277194278194279194280194281194282194283194284194285194286194287194288194289194290194291194292194293194294194295194296194297194298194299194300194301194302194303194304194305194306194307194308194309194310194311194312194313194314194315194316194317194318194319194320194321194322194323194324194325194326194327194328194329194330194331194332194333194334194335194336194337194338194339194340194341194342194343194344194345194346194347194348194349194350194351194352194353194354194355194356194357194358194359194360194361194362194363194364194365194366194367194368194369194370194371194372194373194374194375194376194377194378194379194380194381194382194383194384194385194386194387194388194389194390194391194392194393194394194395194396194397194398194399194400194401194402194403194404194405194406194407194408194409194410194411194412194413194414194415194416194417194418194419194420194421194422194423194424194425194426194427194428194429194430194431194432194433194434194435194436194437194438194439194440194441194442194443194444194445194446194447194448194449194450194451194452194453194454194455194456194457194458194459194460194461194462194463194464194465194466194467194468194469194470194471194472194473194474194475194476194477194478194479194480194481194482194483194484194485194486194487194488194489194490194491194492194493194494194495194496194497194498194499194500194501194502194503194504194505194506194507194508194509194510194511194512194513194514194515194516194517194518194519194520194521194522194523194524194525194526194527194528194529194530194531194532194533194534194535194536194537194538194539194540194541194542194543194544194545194546194547194548194549194550194551194552194553194554194555194556194557194558194559194560194561194562194563194564194565194566194567194568194569194570194571194572194573194574194575194576194577194578194579194580194581194582194583194584194585194586194587194588194589194590194591194592194593194594194595194596194597194598194599194600194601194602194603194604194605194606194607194608194609194610194611194612194613194614194615194616194617194618194619194620194621194622194623194624194625194626194627194628194629194630194631194632194633194634194635194636194637194638194639194640194641194642194643194644194645194646194647194648194649194650194651194652194653194654194655194656194657194658194659194660194661194662194663194664194665194666194667194668194669194670194671194672194673194674194675194676194677194678194679194680194681194682194683194684194685194686194687194688194689194690194691194692194693194694194695194696194697194698194699194700194701194702194703194704194705194706194707194708194709194710194711194712194713194714194715194716194717194718194719194720194721194722194723194724194725194726194727194728194729194730194731194732194733194734194735194736194737194738194739194740194741194742194743194744194745194746194747194748194749194750194751194752194753194754194755194756194757194758194759194760194761194762194763194764194765194766194767194768194769194770194771194772194773194774194775194776194777194778194779194780194781194782194783194784194785194786194787194788194789194790194791194792194793194794194795194796194797194798194799194800194801194802194803194804194805194806194807194808194809194810194811194812194813194814194815194816194817194818194819194820194821194822194823194824194825194826194827194828194829194830194831194832194833194834194835194836194837194838194839194840194841194842194843194844194845194846194847194848194849194850194851194852194853194854194855194856194857194858194859194860194861194862194863194864194865194866194867194868194869194870194871194872194873194874194875194876194877194878194879194880194881194882194883194884194885194886194887194888194889194890194891194892194893194894194895194896194897194898194899194900194901194902194903194904194905194906194907194908194909194910194911194912194913194914194915194916194917194918194919194920194921194922194923194924194925194926194927194928194929194930194931194932194933194934194935194936194937194938194939194940194941194942194943194944194945194946194947194948194949194950194951194952194953194954194955194956194957194958194959194960194961194962194963194964194965194966194967194968194969194970194971194972194973194974194975194976194977194978194979194980194981194982194983194984194985194986194987194988194989194990194991194992194993194994194995194996194997194998194999195000195001195002195003195004195005195006195007195008195009195010195011195012195013195014195015195016195017195018195019195020195021195022195023195024195025195026195027195028195029195030195031195032195033195034195035195036195037195038195039195040195041195042195043195044195045195046195047195048195049195050195051195052195053195054195055195056195057195058195059195060195061195062195063195064195065195066195067195068195069195070195071195072195073195074195075195076195077195078195079195080195081195082195083195084195085195086195087195088195089195090195091195092195093195094195095195096195097195098195099195100195101195102195103195104195105195106195107195108195109195110195111195112195113195114195115195116195117195118195119195120195121195122195123195124195125195126195127195128195129195130195131195132195133195134195135195136195137195138195139195140195141195142195143195144195145195146195147195148195149195150195151195152195153195154195155195156195157195158195159195160195161195162195163195164195165195166195167195168195169195170195171195172195173195174195175195176195177195178195179195180195181195182195183195184195185195186195187195188195189195190195191195192195193195194195195195196195197195198195199195200195201195202195203195204195205195206195207195208195209195210195211195212195213195214195215195216195217195218195219195220195221195222195223195224195225195226195227195228195229195230195231195232195233195234195235195236195237195238195239195240195241195242195243195244195245195246195247195248195249195250195251195252195253195254195255195256195257195258195259195260195261195262195263195264195265195266195267195268195269195270195271195272195273195274195275195276195277195278195279195280195281195282195283195284195285195286195287195288195289195290195291195292195293195294195295195296195297195298195299195300195301195302195303195304195305195306195307195308195309195310195311195312195313195314195315195316195317195318195319195320195321195322195323195324195325195326195327195328195329195330195331195332195333195334195335195336195337195338195339195340195341195342195343195344195345195346195347195348195349195350195351195352195353195354195355195356195357195358195359195360195361195362195363195364195365195366195367195368195369195370195371195372195373195374195375195376195377195378195379195380195381195382195383195384195385195386195387195388195389195390195391195392195393195394195395195396195397195398195399195400195401195402195403195404195405195406195407195408195409195410195411195412195413195414195415195416195417195418195419195420195421195422195423195424195425195426195427195428195429195430195431195432195433195434195435195436195437195438195439195440195441195442195443195444195445195446195447195448195449195450195451195452195453195454195455195456195457195458195459195460195461195462195463195464195465195466195467195468195469195470195471195472195473195474195475195476195477195478195479195480195481195482195483195484195485195486195487195488195489195490195491195492195493195494195495195496195497195498195499195500195501195502195503195504195505195506195507195508195509195510195511195512195513195514195515195516195517195518195519195520195521195522195523195524195525195526195527195528195529195530195531195532195533195534195535195536195537195538195539195540195541195542195543195544195545195546195547195548195549195550195551195552195553195554195555195556195557195558195559195560195561195562195563195564195565195566195567195568195569195570195571195572195573195574195575195576195577195578195579195580195581195582195583195584195585195586195587195588195589195590195591195592195593195594195595195596195597195598195599195600195601195602195603195604195605195606195607195608195609195610195611195612195613195614195615195616195617195618195619195620195621195622195623195624195625195626195627195628195629195630195631195632195633195634195635195636195637195638195639195640195641195642195643195644195645195646195647195648195649195650195651195652195653195654195655195656195657195658195659195660195661195662195663195664195665195666195667195668195669195670195671195672195673195674195675195676195677195678195679195680195681195682195683195684195685195686195687195688195689195690195691195692195693195694195695195696195697195698195699195700195701195702195703195704195705195706195707195708195709195710195711195712195713195714195715195716195717195718195719195720195721195722195723195724195725195726195727195728195729195730195731195732195733195734195735195736195737195738195739195740195741195742195743195744195745195746195747195748195749195750195751195752195753195754195755195756195757195758195759195760195761195762195763195764195765195766195767195768195769195770195771195772195773195774195775195776195777195778195779195780195781195782195783195784195785195786195787195788195789195790195791195792195793195794195795195796195797195798195799195800195801195802195803195804195805195806195807195808195809195810195811195812195813195814195815195816195817195818195819195820195821195822195823195824195825195826195827195828195829195830195831195832195833195834195835195836195837195838195839195840195841195842195843195844195845195846195847195848195849195850195851195852195853195854195855195856195857195858195859195860195861195862195863195864195865195866195867195868195869195870195871195872195873195874195875195876195877195878195879195880195881195882195883195884195885195886195887195888195889195890195891195892195893195894195895195896195897195898195899195900195901195902195903195904195905195906195907195908195909195910195911195912195913195914195915195916195917195918195919195920195921195922195923195924195925195926195927195928195929195930195931195932195933195934195935195936195937195938195939195940195941195942195943195944195945195946195947195948195949195950195951195952195953195954195955195956195957195958195959195960195961195962195963195964195965195966195967195968195969195970195971195972195973195974195975195976195977195978195979195980195981195982195983195984195985195986195987195988195989195990195991195992195993195994195995195996195997195998195999196000196001196002196003196004196005196006196007196008196009196010196011196012196013196014196015196016196017196018196019196020196021196022196023196024196025196026196027196028196029196030196031196032196033196034196035196036196037196038196039196040196041196042196043196044196045196046196047196048196049196050196051196052196053196054196055196056196057196058196059196060196061196062196063196064196065196066196067196068196069196070196071196072196073196074196075196076196077196078196079196080196081196082196083196084196085196086196087196088196089196090196091196092196093196094196095196096196097196098196099196100196101196102196103196104196105196106196107196108196109196110196111196112196113196114196115196116196117196118196119196120196121196122196123196124196125196126196127196128196129196130196131196132196133196134196135196136196137196138196139196140196141196142196143196144196145196146196147196148196149196150196151196152196153196154196155196156196157196158196159196160196161196162196163196164196165196166196167196168196169196170196171196172196173196174196175196176196177196178196179196180196181196182196183196184196185196186196187196188196189196190196191196192196193196194196195196196196197196198196199196200196201196202196203196204196205196206196207196208196209196210196211196212196213196214196215196216196217196218196219196220196221196222196223196224196225196226196227196228196229196230196231196232196233196234196235196236196237196238196239196240196241196242196243196244196245196246196247196248196249196250196251196252196253196254196255196256196257196258196259196260196261196262196263196264196265196266196267196268196269196270196271196272196273196274196275196276196277196278196279196280196281196282196283196284196285196286196287196288196289196290196291196292196293196294196295196296196297196298196299196300196301196302196303196304196305196306196307196308196309196310196311196312196313196314196315196316196317196318196319196320196321196322196323196324196325196326196327196328196329196330196331196332196333196334196335196336196337196338196339196340196341196342196343196344196345196346196347196348196349196350196351196352196353196354196355196356196357196358196359196360196361196362196363196364196365196366196367196368196369196370196371196372196373196374196375196376196377196378196379196380196381196382196383196384196385196386196387196388196389196390196391196392196393196394196395196396196397196398196399196400196401196402196403196404196405196406196407196408196409196410196411196412196413196414196415196416196417196418196419196420196421196422196423196424196425196426196427196428196429196430196431196432196433196434196435196436196437196438196439196440196441196442196443196444196445196446196447196448196449196450196451196452196453196454196455196456196457196458196459196460196461196462196463196464196465196466196467196468196469196470196471196472196473196474196475196476196477196478196479196480196481196482196483196484196485196486196487196488196489196490196491196492196493196494196495196496196497196498196499196500196501196502196503196504196505196506196507196508196509196510196511196512196513196514196515196516196517196518196519196520196521196522196523196524196525196526196527196528196529196530196531196532196533196534196535196536196537196538196539196540196541196542196543196544196545196546196547196548196549196550196551196552196553196554196555196556196557196558196559196560196561196562196563196564196565196566196567196568196569196570196571196572196573196574196575196576196577196578196579196580196581196582196583196584196585196586196587196588196589196590196591196592196593196594196595196596196597196598196599196600196601196602196603196604196605196606196607196608196609196610196611196612196613196614196615196616196617196618196619196620196621196622196623196624196625196626196627196628196629196630196631196632196633196634196635196636196637196638196639196640196641196642196643196644196645196646196647196648196649196650196651196652196653196654196655196656196657196658196659196660196661196662196663196664196665196666196667196668196669196670196671196672196673196674196675196676196677196678196679196680196681196682196683196684196685196686196687196688196689196690196691196692196693196694196695196696196697196698196699196700196701196702196703196704196705196706196707196708196709196710196711196712196713196714196715196716196717196718196719196720196721196722196723196724196725196726196727196728196729196730196731196732196733196734196735196736196737196738196739196740196741196742196743196744196745196746196747196748196749196750196751196752196753196754196755196756196757196758196759196760196761196762196763196764196765196766196767196768196769196770196771196772196773196774196775196776196777196778196779196780196781196782196783196784196785196786196787196788196789196790196791196792196793196794196795196796196797196798196799196800196801196802196803196804196805196806196807196808196809196810196811196812196813196814196815196816196817196818196819196820196821196822196823196824196825196826196827196828196829196830196831196832196833196834196835196836196837196838196839196840196841196842196843196844196845196846196847196848196849196850196851196852196853196854196855196856196857196858196859196860196861196862196863196864196865196866196867196868196869196870196871196872196873196874196875196876196877196878196879196880196881196882196883196884196885196886196887196888196889196890196891196892196893196894196895196896196897196898196899196900196901196902196903196904196905196906196907196908196909196910196911196912196913196914196915196916196917196918196919196920196921196922196923196924196925196926196927196928196929196930196931196932196933196934196935196936196937196938196939196940196941196942196943196944196945196946196947196948196949196950196951196952196953196954196955196956196957196958196959196960196961196962196963196964196965196966196967196968196969196970196971196972196973196974196975196976196977196978196979196980196981196982196983196984196985196986196987196988196989196990196991196992196993196994196995196996196997196998196999197000197001197002197003197004197005197006197007197008197009197010197011197012197013197014197015197016197017197018197019197020197021197022197023197024197025197026197027197028197029197030197031197032197033197034197035197036197037197038197039197040197041197042197043197044197045197046197047197048197049197050197051197052197053197054197055197056197057197058197059197060197061197062197063197064197065197066197067197068197069197070197071197072197073197074197075197076197077197078197079197080197081197082197083197084197085197086197087197088197089197090197091197092197093197094197095197096197097197098197099197100197101197102197103197104197105197106197107197108197109197110197111197112197113197114197115197116197117197118197119197120197121197122197123197124197125197126197127197128197129197130197131197132197133197134197135197136197137197138197139197140197141197142197143197144197145197146197147197148197149197150197151197152197153197154197155197156197157197158197159197160197161197162197163197164197165197166197167197168197169197170197171197172197173197174197175197176197177197178197179197180197181197182197183197184197185197186197187197188197189197190197191197192197193197194197195197196197197197198197199197200197201197202197203197204197205197206197207197208197209197210197211197212197213197214197215197216197217197218197219197220197221197222197223197224197225197226197227197228197229197230197231197232197233197234197235197236197237197238197239197240197241197242197243197244197245197246197247197248197249197250197251197252197253197254197255197256197257197258197259197260197261197262197263197264197265197266197267197268197269197270197271197272197273197274197275197276197277197278197279197280197281197282197283197284197285197286197287197288197289197290197291197292197293197294197295197296197297197298197299197300197301197302197303197304197305197306197307197308197309197310197311197312197313197314197315197316197317197318197319197320197321197322197323197324197325197326197327197328197329197330197331197332197333197334197335197336197337197338197339197340197341197342197343197344197345197346197347197348197349197350197351197352197353197354197355197356197357197358197359197360197361197362197363197364197365197366197367197368197369197370197371197372197373197374197375197376197377197378197379197380197381197382197383197384197385197386197387197388197389197390197391197392197393197394197395197396197397197398197399197400197401197402197403197404197405197406197407197408197409197410197411197412197413197414197415197416197417197418197419197420197421197422197423197424197425197426197427197428197429197430197431197432197433197434197435197436197437197438197439197440197441197442197443197444197445197446197447197448197449197450197451197452197453197454197455197456197457197458197459197460197461197462197463197464197465197466197467197468197469197470197471197472197473197474197475197476197477197478197479197480197481197482197483197484197485197486197487197488197489197490197491197492197493197494197495197496197497197498197499197500197501197502197503197504197505197506197507197508197509197510197511197512197513197514197515197516197517197518197519197520197521197522197523197524197525197526197527197528197529197530197531197532197533197534197535197536197537197538197539197540197541197542197543197544197545197546197547197548197549197550197551197552197553197554197555197556197557197558197559197560197561197562197563197564197565197566197567197568197569197570197571197572197573197574197575197576197577197578197579197580197581197582197583197584197585197586197587197588197589197590197591197592197593197594197595197596197597197598197599197600197601197602197603197604197605197606197607197608197609197610197611197612197613197614197615197616197617197618197619197620197621197622197623197624197625197626197627197628197629197630197631197632197633197634197635197636197637197638197639197640197641197642197643197644197645197646197647197648197649197650197651197652197653197654197655197656197657197658197659197660197661197662197663197664197665197666197667197668197669197670197671197672197673197674197675197676197677197678197679197680197681197682197683197684197685197686197687197688197689197690197691197692197693197694197695197696197697197698197699197700197701197702197703197704197705197706197707197708197709197710197711197712197713197714197715197716197717197718197719197720197721197722197723197724197725197726197727197728197729197730197731197732197733197734197735197736197737197738197739197740197741197742197743197744197745197746197747197748197749197750197751197752197753197754197755197756197757197758197759197760197761197762197763197764197765197766197767197768197769197770197771197772197773197774197775197776197777197778197779197780197781197782197783197784197785197786197787197788197789197790197791197792197793197794197795197796197797197798197799197800197801197802197803197804197805197806197807197808197809197810197811197812197813197814197815197816197817197818197819197820197821197822197823197824197825197826197827197828197829197830197831197832197833197834197835197836197837197838197839197840197841197842197843197844197845197846197847197848197849197850197851197852197853197854197855197856197857197858197859197860197861197862197863197864197865197866197867197868197869197870197871197872197873197874197875197876197877197878197879197880197881197882197883197884197885197886197887197888197889197890197891197892197893197894197895197896197897197898197899197900197901197902197903197904197905197906197907197908197909197910197911197912197913197914197915197916197917197918197919197920197921197922197923197924197925197926197927197928197929197930197931197932197933197934197935197936197937197938197939197940197941197942197943197944197945197946197947197948197949197950197951197952197953197954197955197956197957197958197959197960197961197962197963197964197965197966197967197968197969197970197971197972197973197974197975197976197977197978197979197980197981197982197983197984197985197986197987197988197989197990197991197992197993197994197995197996197997197998197999198000198001198002198003198004198005198006198007198008198009198010198011198012198013198014198015198016198017198018198019198020198021198022198023198024198025198026198027198028198029198030198031198032198033198034198035198036198037198038198039198040198041198042198043198044198045198046198047198048198049198050198051198052198053198054198055198056198057198058198059198060198061198062198063198064198065198066198067198068198069198070198071198072198073198074198075198076198077198078198079198080198081198082198083198084198085198086198087198088198089198090198091198092198093198094198095198096198097198098198099198100198101198102198103198104198105198106198107198108198109198110198111198112198113198114198115198116198117198118198119198120198121198122198123198124198125198126198127198128198129198130198131198132198133198134198135198136198137198138198139198140198141198142198143198144198145198146198147198148198149198150198151198152198153198154198155198156198157198158198159198160198161198162198163198164198165198166198167198168198169198170198171198172198173198174198175198176198177198178198179198180198181198182198183198184198185198186198187198188198189198190198191198192198193198194198195198196198197198198198199198200198201198202198203198204198205198206198207198208198209198210198211198212198213198214198215198216198217198218198219198220198221198222198223198224198225198226198227198228198229198230198231198232198233198234198235198236198237198238198239198240198241198242198243198244198245198246198247198248198249198250198251198252198253198254198255198256198257198258198259198260198261198262198263198264198265198266198267198268198269198270198271198272198273198274198275198276198277198278198279198280198281198282198283198284198285198286198287198288198289198290198291198292198293198294198295198296198297198298198299198300198301198302198303198304198305198306198307198308198309198310198311198312198313198314198315198316198317198318198319198320198321198322198323198324198325198326198327198328198329198330198331198332198333198334198335198336198337198338198339198340198341198342198343198344198345198346198347198348198349198350198351198352198353198354198355198356198357198358198359198360198361198362198363198364198365198366198367198368198369198370198371198372198373198374198375198376198377198378198379198380198381198382198383198384198385198386198387198388198389198390198391198392198393198394198395198396198397198398198399198400198401198402198403198404198405198406198407198408198409198410198411198412198413198414198415198416198417198418198419198420198421198422198423198424198425198426198427198428198429198430198431198432198433198434198435198436198437198438198439198440198441198442198443198444198445198446198447198448198449198450198451198452198453198454198455198456198457198458198459198460198461198462198463198464198465198466198467198468198469198470198471198472198473198474198475198476198477198478198479198480198481198482198483198484198485198486198487198488198489198490198491198492198493198494198495198496198497198498198499198500198501198502198503198504198505198506198507198508198509198510198511198512198513198514198515198516198517198518198519198520198521198522198523198524198525198526198527198528198529198530198531198532198533198534198535198536198537198538198539198540198541198542198543198544198545198546198547198548198549198550198551198552198553198554198555198556198557198558198559198560198561198562198563198564198565198566198567198568198569198570198571198572198573198574198575198576198577198578198579198580198581198582198583198584198585198586198587198588198589198590198591198592198593198594198595198596198597198598198599198600198601198602198603198604198605198606198607198608198609198610198611198612198613198614198615198616198617198618198619198620198621198622198623198624198625198626198627198628198629198630198631198632198633198634198635198636198637198638198639198640198641198642198643198644198645198646198647198648198649198650198651198652198653198654198655198656198657198658198659198660198661198662198663198664198665198666198667198668198669198670198671198672198673198674198675198676198677198678198679198680198681198682198683198684198685198686198687198688198689198690198691198692198693198694198695198696198697198698198699198700198701198702198703198704198705198706198707198708198709198710198711198712198713198714198715198716198717198718198719198720198721198722198723198724198725198726198727198728198729198730198731198732198733198734198735198736198737198738198739198740198741198742198743198744198745198746198747198748198749198750198751198752198753198754198755198756198757198758198759198760198761198762198763198764198765198766198767198768198769198770198771198772198773198774198775198776198777198778198779198780198781198782198783198784198785198786198787198788198789198790198791198792198793198794198795198796198797198798198799198800198801198802198803198804198805198806198807198808198809198810198811198812198813198814198815198816198817198818198819198820198821198822198823198824198825198826198827198828198829198830198831198832198833198834198835198836198837198838198839198840198841198842198843198844198845198846198847198848198849198850198851198852198853198854198855198856198857198858198859198860198861198862198863198864198865198866198867198868198869198870198871198872198873198874198875198876198877198878198879198880198881198882198883198884198885198886198887198888198889198890198891198892198893198894198895198896198897198898198899198900198901198902198903198904198905198906198907198908198909198910198911198912198913198914198915198916198917198918198919198920198921198922198923198924198925198926198927198928198929198930198931198932198933198934198935198936198937198938198939198940198941198942198943198944198945198946198947198948198949198950198951198952198953198954198955198956198957198958198959198960198961198962198963198964198965198966198967198968198969198970198971198972198973198974198975198976198977198978198979198980198981198982198983198984198985198986198987198988198989198990198991198992198993198994198995198996198997198998198999199000199001199002199003199004199005199006199007199008199009199010199011199012199013199014199015199016199017199018199019199020199021199022199023199024199025199026199027199028199029199030199031199032199033199034199035199036199037199038199039199040199041199042199043199044199045199046199047199048199049199050199051199052199053199054199055199056199057199058199059199060199061199062199063199064199065199066199067199068199069199070199071199072199073199074199075199076199077199078199079199080199081199082199083199084199085199086199087199088199089199090199091199092199093199094199095199096199097199098199099199100199101199102199103199104199105199106199107199108199109199110199111199112199113199114199115199116199117199118199119199120199121199122199123199124199125199126199127199128199129199130199131199132199133199134199135199136199137199138199139199140199141199142199143199144199145199146199147199148199149199150199151199152199153199154199155199156199157199158199159199160199161199162199163199164199165199166199167199168199169199170199171199172199173199174199175199176199177199178199179199180199181199182199183199184199185199186199187199188199189199190199191199192199193199194199195199196199197199198199199199200199201199202199203199204199205199206199207199208199209199210199211199212199213199214199215199216199217199218199219199220199221199222199223199224199225199226199227199228199229199230199231199232199233199234199235199236199237199238199239199240199241199242199243199244199245199246199247199248199249199250199251199252199253199254199255199256199257199258199259199260199261199262199263199264199265199266199267199268199269199270199271199272199273199274199275199276199277199278199279199280199281199282199283199284199285199286199287199288199289199290199291199292199293199294199295199296199297199298199299199300199301199302199303199304199305199306199307199308199309199310199311199312199313199314199315199316199317199318199319199320199321199322199323199324199325199326199327199328199329199330199331199332199333199334199335199336199337199338199339199340199341199342199343199344199345199346199347199348199349199350199351199352199353199354199355199356199357199358199359199360199361199362199363199364199365199366199367199368199369199370199371199372199373199374199375199376199377199378199379199380199381199382199383199384199385199386199387199388199389199390199391199392199393199394199395199396199397199398199399199400199401199402199403199404199405199406199407199408199409199410199411199412199413199414199415199416199417199418199419199420199421199422199423199424199425199426199427199428199429199430199431199432199433199434199435199436199437199438199439199440199441199442199443199444199445199446199447199448199449199450199451199452199453199454199455199456199457199458199459199460199461199462199463199464199465199466199467199468199469199470199471199472199473199474199475199476199477199478199479199480199481199482199483199484199485199486199487199488199489199490199491199492199493199494199495199496199497199498199499199500199501199502199503199504199505199506199507199508199509199510199511199512199513199514199515199516199517199518199519199520199521199522199523199524199525199526199527199528199529199530199531199532199533199534199535199536199537199538199539199540199541199542199543199544199545199546199547199548199549199550199551199552199553199554199555199556199557199558199559199560199561199562199563199564199565199566199567199568199569199570199571199572199573199574199575199576199577199578199579199580199581199582199583199584199585199586199587199588199589199590199591199592199593199594199595199596199597199598199599199600199601199602199603199604199605199606199607199608199609199610199611199612199613199614199615199616199617199618199619199620199621199622199623199624199625199626199627199628199629199630199631199632199633199634199635199636199637199638199639199640199641199642199643199644199645199646199647199648199649199650199651199652199653199654199655199656199657199658199659199660199661199662199663199664199665199666199667199668199669199670199671199672199673199674199675199676199677199678199679199680199681199682199683199684199685199686199687199688199689199690199691199692199693199694199695199696199697199698199699199700199701199702199703199704199705199706199707199708199709199710199711199712199713199714199715199716199717199718199719199720199721199722199723199724199725199726199727199728199729199730199731199732199733199734199735199736199737199738199739199740199741199742199743199744199745199746199747199748199749199750199751199752199753199754199755199756199757199758199759199760199761199762199763199764199765199766199767199768199769199770199771199772199773199774199775199776199777199778199779199780199781199782199783199784199785199786199787199788199789199790199791199792199793199794199795199796199797199798199799199800199801199802199803199804199805199806199807199808199809199810199811199812199813199814199815199816199817199818199819199820199821199822199823199824199825199826199827199828199829199830199831199832199833199834199835199836199837199838199839199840199841199842199843199844199845199846199847199848199849199850199851199852199853199854199855199856199857199858199859199860199861199862199863199864199865199866199867199868199869199870199871199872199873199874199875199876199877199878199879199880199881199882199883199884199885199886199887199888199889199890199891199892199893199894199895199896199897199898199899199900199901199902199903199904199905199906199907199908199909199910199911199912199913199914199915199916199917199918199919199920199921199922199923199924199925199926199927199928199929199930199931199932199933199934199935199936199937199938199939199940199941199942199943199944199945199946199947199948199949199950199951199952199953199954199955199956199957199958199959199960199961199962199963199964199965199966199967199968199969199970199971199972199973199974199975199976199977199978199979199980199981199982199983199984199985199986199987199988199989199990199991199992199993199994199995199996199997199998199999200000200001200002200003200004200005200006200007200008200009200010200011200012200013200014200015200016200017200018200019200020200021200022200023200024200025200026200027200028200029200030200031200032200033200034200035200036200037200038200039200040200041200042200043200044200045200046200047200048200049200050200051200052200053200054200055200056200057200058200059200060200061200062200063200064200065200066200067200068200069200070200071200072200073200074200075200076200077200078200079200080200081200082200083200084200085200086200087200088200089200090200091200092200093200094200095200096200097200098200099200100200101200102200103200104200105200106200107200108200109200110200111200112200113200114200115200116200117200118200119200120200121200122200123200124200125200126200127200128200129200130200131200132200133200134200135200136200137200138200139200140200141200142200143200144200145200146200147200148200149200150200151200152200153200154200155200156200157200158200159200160200161200162200163200164200165200166200167200168200169200170200171200172200173200174200175200176200177200178200179200180200181200182200183200184200185200186200187200188200189200190200191200192200193200194200195200196200197200198200199200200200201200202200203200204200205200206200207200208200209200210200211200212200213200214200215200216200217200218200219200220200221200222200223200224200225200226200227200228200229200230200231200232200233200234200235200236200237200238200239200240200241200242200243200244200245200246200247200248200249200250200251200252200253200254200255200256200257200258200259200260200261200262200263200264200265200266200267200268200269200270200271200272200273200274200275200276200277200278200279200280200281200282200283200284200285200286200287200288200289200290200291200292200293200294200295200296200297200298200299200300200301200302200303200304200305200306200307200308200309200310200311200312200313200314200315200316200317200318200319200320200321200322200323200324200325200326200327200328200329200330200331200332200333200334200335200336200337200338200339200340200341200342200343200344200345200346200347200348200349200350200351200352200353200354200355200356200357200358200359200360200361200362200363200364200365200366200367200368200369200370200371200372200373200374200375200376200377200378200379200380200381200382200383200384200385200386200387200388200389200390200391200392200393200394200395200396200397200398200399200400200401200402200403200404200405200406200407200408200409200410200411200412200413200414200415200416200417200418200419200420200421200422200423200424200425200426200427200428200429200430200431200432200433200434200435200436200437200438200439200440200441200442200443200444200445200446200447200448200449200450200451200452200453200454200455200456200457200458200459200460200461200462200463200464200465200466200467200468200469200470200471200472200473200474200475200476200477200478200479200480200481200482200483200484200485200486200487200488200489200490200491200492200493200494200495200496200497200498200499200500200501200502200503200504200505200506200507200508200509200510200511200512200513200514200515200516200517200518200519200520200521200522200523200524200525200526200527200528200529200530200531200532200533200534200535200536200537200538200539200540200541200542200543200544200545200546200547200548200549200550200551200552200553200554200555200556200557200558200559200560200561200562200563200564200565200566200567200568200569200570200571200572200573200574200575200576200577200578200579200580200581200582200583200584200585200586200587200588200589200590200591200592200593200594200595200596200597200598200599200600200601200602200603200604200605200606200607200608200609200610200611200612200613200614200615200616200617200618200619200620200621200622200623200624200625200626200627200628200629200630200631200632200633200634200635200636200637200638200639200640200641200642200643200644200645200646200647200648200649200650200651200652200653200654200655200656200657200658200659200660200661200662200663200664200665200666200667200668200669200670200671200672200673200674200675200676200677200678200679200680200681200682200683200684200685200686200687200688200689200690200691200692200693200694200695200696200697200698200699200700200701200702200703200704200705200706200707200708200709200710200711200712200713200714200715200716200717200718200719200720200721200722200723200724200725200726200727200728200729200730200731200732200733200734200735200736200737200738200739200740200741200742200743200744200745200746200747200748200749200750200751200752200753200754200755200756200757200758200759200760200761200762200763200764200765200766200767200768200769200770200771200772200773200774200775200776200777200778200779200780200781200782200783200784200785200786200787200788200789200790200791200792200793200794200795200796200797200798200799200800200801200802200803200804200805200806200807200808200809200810200811200812200813200814200815200816200817200818200819200820200821200822200823200824200825200826200827200828200829200830200831200832200833200834200835200836200837200838200839200840200841200842200843200844200845200846200847200848200849200850200851200852200853200854200855200856200857200858200859200860200861200862200863200864200865200866200867200868200869200870200871200872200873200874200875200876200877200878200879200880200881200882200883200884200885200886200887200888200889200890200891200892200893200894200895200896200897200898200899200900200901200902200903200904200905200906200907200908200909200910200911200912200913200914200915200916200917200918200919200920200921200922200923200924200925200926200927200928200929200930200931200932200933200934200935200936200937200938200939200940200941200942200943200944200945200946200947200948200949200950200951200952200953200954200955200956200957200958200959200960200961200962200963200964200965200966200967200968200969200970200971200972200973200974200975200976200977200978200979200980200981200982200983200984200985200986200987200988200989200990200991200992200993200994200995200996200997200998200999201000201001201002201003201004201005201006201007201008201009201010201011201012201013201014201015201016201017201018201019201020201021201022201023201024201025201026201027201028201029201030201031201032201033201034201035201036201037201038201039201040201041201042201043201044201045201046201047201048201049201050201051201052201053201054201055201056201057201058201059201060201061201062201063201064201065201066201067201068201069201070201071201072201073201074201075201076201077201078201079201080201081201082201083201084201085201086201087201088201089201090201091201092201093201094201095201096201097201098201099201100201101201102201103201104201105201106201107201108201109201110201111201112201113201114201115201116201117201118201119201120201121201122201123201124201125201126201127201128201129201130201131201132201133201134201135201136201137201138201139201140201141201142201143201144201145201146201147201148201149201150201151201152201153201154201155201156201157201158201159201160201161201162201163201164201165201166201167201168201169201170201171201172201173201174201175201176201177201178201179201180201181201182201183201184201185201186201187201188201189201190201191201192201193201194201195201196201197201198201199201200201201201202201203201204201205201206201207201208201209201210201211201212201213201214201215201216201217201218201219201220201221201222201223201224201225201226201227201228201229201230201231201232201233201234201235201236201237201238201239201240201241201242201243201244201245201246201247201248201249201250201251201252201253201254201255201256201257201258201259201260201261201262201263201264201265201266201267201268201269201270201271201272201273201274201275201276201277201278201279201280201281201282201283201284201285201286201287201288201289201290201291201292201293201294201295201296201297201298201299201300201301201302201303201304201305201306201307201308201309201310201311201312201313201314201315201316201317201318201319201320201321201322201323201324201325201326201327201328201329201330201331201332201333201334201335201336201337201338201339201340201341201342201343201344201345201346201347201348201349201350201351201352201353201354201355201356201357201358201359201360201361201362201363201364201365201366201367201368201369201370201371201372201373201374201375201376201377201378201379201380201381201382201383201384201385201386201387201388201389201390201391201392201393201394201395201396201397201398201399201400201401201402201403201404201405201406201407201408201409201410201411201412201413201414201415201416201417201418201419201420201421201422201423201424201425201426201427201428201429201430201431201432201433201434201435201436201437201438201439201440201441201442201443201444201445201446201447201448201449201450201451201452201453201454201455201456201457201458201459201460201461201462201463201464201465201466201467201468201469201470201471201472201473201474201475201476201477201478201479201480201481201482201483201484201485201486201487201488201489201490201491201492201493201494201495201496201497201498201499201500201501201502201503201504201505201506201507201508201509201510201511201512201513201514201515201516201517201518201519201520201521201522201523201524201525201526201527201528201529201530201531201532201533201534201535201536201537201538201539201540201541201542201543201544201545201546201547201548201549201550201551201552201553201554201555201556201557201558201559201560201561201562201563201564201565201566201567201568201569201570201571201572201573201574201575201576201577201578201579201580201581201582201583201584201585201586201587201588201589201590201591201592201593201594201595201596201597201598201599201600201601201602201603201604201605201606201607201608201609201610201611201612201613201614201615201616201617201618201619201620201621201622201623201624201625201626201627201628201629201630201631201632201633201634201635201636201637201638201639201640201641201642201643201644201645201646201647201648201649201650201651201652201653201654201655201656201657201658201659201660201661201662201663201664201665201666201667201668201669201670201671201672201673201674201675201676201677201678201679201680201681201682201683201684201685201686201687201688201689201690201691201692201693201694201695201696201697201698201699201700201701201702201703201704201705201706201707201708201709201710201711201712201713201714201715201716201717201718201719201720201721201722201723201724201725201726201727201728201729201730201731201732201733201734201735201736201737201738201739201740201741201742201743201744201745201746201747201748201749201750201751201752201753201754201755201756201757201758201759201760201761201762201763201764201765201766201767201768201769201770201771201772201773201774201775201776201777201778201779201780201781201782201783201784201785201786201787201788201789201790201791201792201793201794201795201796201797201798201799201800201801201802201803201804201805201806201807201808201809201810201811201812201813201814201815201816201817201818201819201820201821201822201823201824201825201826201827201828201829201830201831201832201833201834201835201836201837201838201839201840201841201842201843201844201845201846201847201848201849201850201851201852201853201854201855201856201857201858201859201860201861201862201863201864201865201866201867201868201869201870201871201872201873201874201875201876201877201878201879201880201881201882201883201884201885201886201887201888201889201890201891201892201893201894201895201896201897201898201899201900201901201902201903201904201905201906201907201908201909201910201911201912201913201914201915201916201917201918201919201920201921201922201923201924201925201926201927201928201929201930201931201932201933201934201935201936201937201938201939201940201941201942201943201944201945201946201947201948201949201950201951201952201953201954201955201956201957201958201959201960201961201962201963201964201965201966201967201968201969201970201971201972201973201974201975201976201977201978201979201980201981201982201983201984201985201986201987201988201989201990201991201992201993201994201995201996201997201998201999202000202001202002202003202004202005202006202007202008202009202010202011202012202013202014202015202016202017202018202019202020202021202022202023202024202025202026202027202028202029202030202031202032202033202034202035202036202037202038202039202040202041202042202043202044202045202046202047202048202049202050202051202052202053202054202055202056202057202058202059202060202061202062202063202064202065202066202067202068202069202070202071202072202073202074202075202076202077202078202079202080202081202082202083202084202085202086202087202088202089202090202091202092202093202094202095202096202097202098202099202100202101202102202103202104202105202106202107202108202109202110202111202112202113202114202115202116202117202118202119202120202121202122202123202124202125202126202127202128202129202130202131202132202133202134202135202136202137202138202139202140202141202142202143202144202145202146202147202148202149202150202151202152202153202154202155202156202157202158202159202160202161202162202163202164202165202166202167202168202169202170202171202172202173202174202175202176202177202178202179202180202181202182202183202184202185202186202187202188202189202190202191202192202193202194202195202196202197202198202199202200202201202202202203202204202205202206202207202208202209202210202211202212202213202214202215202216202217202218202219202220202221202222202223202224202225202226202227202228202229202230202231202232202233202234202235202236202237202238202239202240202241202242202243202244202245202246202247202248202249202250202251202252202253202254202255202256202257202258202259202260202261202262202263202264202265202266202267202268202269202270202271202272202273202274202275202276202277202278202279202280202281202282202283202284202285202286202287202288202289202290202291202292202293202294202295202296202297202298202299202300202301202302202303202304202305202306202307202308202309202310202311202312202313202314202315202316202317202318202319202320202321202322202323202324202325202326202327202328202329202330202331202332202333202334202335202336202337202338202339202340202341202342202343202344202345202346202347202348202349202350202351202352202353202354202355202356202357202358202359202360202361202362202363202364202365202366202367202368202369202370202371202372202373202374202375202376202377202378202379202380202381202382202383202384202385202386202387202388202389202390202391202392202393202394202395202396202397202398202399202400202401202402202403202404202405202406202407202408202409202410202411202412202413202414202415202416202417202418202419202420202421202422202423202424202425202426202427202428202429202430202431202432202433202434202435202436202437202438202439202440202441202442202443202444202445202446202447202448202449202450202451202452202453202454202455202456202457202458202459202460202461202462202463202464202465202466202467202468202469202470202471202472202473202474202475202476202477202478202479202480202481202482202483202484202485202486202487202488202489202490202491202492202493202494202495202496202497202498202499202500202501202502202503202504202505202506202507202508202509202510202511202512202513202514202515202516202517202518202519202520202521202522202523202524202525202526202527202528202529202530202531202532202533202534202535202536202537202538202539202540202541202542202543202544202545202546202547202548202549202550202551202552202553202554202555202556202557202558202559202560202561202562202563202564202565202566202567202568202569202570202571202572202573202574202575202576202577202578202579202580202581202582202583202584202585202586202587202588202589202590202591202592202593202594202595202596202597202598202599202600202601202602202603202604202605202606202607202608202609202610202611202612202613202614202615202616202617202618202619202620202621202622202623202624202625202626202627202628202629202630202631202632202633202634202635202636202637202638202639202640202641202642202643202644202645202646202647202648202649202650202651202652202653202654202655202656202657202658202659202660202661202662202663202664202665202666202667202668202669202670202671202672202673202674202675202676202677202678202679202680202681202682202683202684202685202686202687202688202689202690202691202692202693202694202695202696202697202698202699202700202701202702202703202704202705202706202707202708202709202710202711202712202713202714202715202716202717202718202719202720202721202722202723202724202725202726202727202728202729202730202731202732202733202734202735202736202737202738202739202740202741202742202743202744202745202746202747202748202749202750202751202752202753202754202755202756202757202758202759202760202761202762202763202764202765202766202767202768202769202770202771202772202773202774202775202776202777202778202779202780202781202782202783202784202785202786202787202788202789202790202791202792202793202794202795202796202797202798202799202800202801202802202803202804202805202806202807202808202809202810202811202812202813202814202815202816202817202818202819202820202821202822202823202824202825202826202827202828202829202830202831202832202833202834202835202836202837202838202839202840202841202842202843202844202845202846202847202848202849202850202851202852202853202854202855202856202857202858202859202860202861202862202863202864202865202866202867202868202869202870202871202872202873202874202875202876202877202878202879202880202881202882202883202884202885202886202887202888202889202890202891202892202893202894202895202896202897202898202899202900202901202902202903202904202905202906202907202908202909202910202911202912202913202914202915202916202917202918202919202920202921202922202923202924202925202926202927202928202929202930202931202932202933202934202935202936202937202938202939202940202941202942202943202944202945202946202947202948202949202950202951202952
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.19.3. By combining all the individual C code files into this
  4. ** single large file, the entire code can be compiled as a single translation
  5. ** unit. This allows many compilers to do optimizations that would not be
  6. ** possible if the files were compiled separately. Performance improvements
  7. ** of 5% or more are commonly seen when SQLite is compiled as a single
  8. ** translation unit.
  9. **
  10. ** This file is all you need to compile SQLite. To use SQLite in other
  11. ** programs, you need this file and the "sqlite3.h" header file that defines
  12. ** the programming interface to the SQLite library. (If you do not have
  13. ** the "sqlite3.h" header file at hand, you will find a copy embedded within
  14. ** the text of this file. Search for "Begin file sqlite3.h" to find the start
  15. ** of the embedded sqlite3.h header file.) Additional code files may be needed
  16. ** if you want a wrapper to interface SQLite with your choice of programming
  17. ** language. The code for the "sqlite3" command-line shell is also in a
  18. ** separate file. This file contains only code for the core SQLite library.
  19. */
  20. #define SQLITE_CORE 1
  21. #define SQLITE_AMALGAMATION 1
  22. #ifndef SQLITE_PRIVATE
  23. # define SQLITE_PRIVATE static
  24. #endif
  25. /************** Begin file sqliteInt.h ***************************************/
  26. /*
  27. ** 2001 September 15
  28. **
  29. ** The author disclaims copyright to this source code. In place of
  30. ** a legal notice, here is a blessing:
  31. **
  32. ** May you do good and not evil.
  33. ** May you find forgiveness for yourself and forgive others.
  34. ** May you share freely, never taking more than you give.
  35. **
  36. *************************************************************************
  37. ** Internal interface definitions for SQLite.
  38. **
  39. */
  40. #ifndef SQLITEINT_H
  41. #define SQLITEINT_H
  42. /* Special Comments:
  43. **
  44. ** Some comments have special meaning to the tools that measure test
  45. ** coverage:
  46. **
  47. ** NO_TEST - The branches on this line are not
  48. ** measured by branch coverage. This is
  49. ** used on lines of code that actually
  50. ** implement parts of coverage testing.
  51. **
  52. ** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
  53. ** and the correct answer is still obtained,
  54. ** though perhaps more slowly.
  55. **
  56. ** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
  57. ** and the correct answer is still obtained,
  58. ** though perhaps more slowly.
  59. **
  60. ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
  61. ** that would be harmless and undetectable
  62. ** if it did occur.
  63. **
  64. ** In all cases, the special comment must be enclosed in the usual
  65. ** slash-asterisk...asterisk-slash comment marks, with no spaces between the
  66. ** asterisks and the comment text.
  67. */
  68. /*
  69. ** Make sure the Tcl calling convention macro is defined. This macro is
  70. ** only used by test code and Tcl integration code.
  71. */
  72. #ifndef SQLITE_TCLAPI
  73. # define SQLITE_TCLAPI
  74. #endif
  75. /*
  76. ** Make sure that rand_s() is available on Windows systems with MSVC 2005
  77. ** or higher.
  78. */
  79. #if defined(_MSC_VER) && _MSC_VER>=1400
  80. # define _CRT_RAND_S
  81. #endif
  82. /*
  83. ** Include the header file used to customize the compiler options for MSVC.
  84. ** This should be done first so that it can successfully prevent spurious
  85. ** compiler warnings due to subsequent content in this file and other files
  86. ** that are included by this file.
  87. */
  88. /************** Include msvc.h in the middle of sqliteInt.h ******************/
  89. #include "sqlite_config_rtthread.h"
  90. /************** Begin file msvc.h ********************************************/
  91. /*
  92. ** 2015 January 12
  93. **
  94. ** The author disclaims copyright to this source code. In place of
  95. ** a legal notice, here is a blessing:
  96. **
  97. ** May you do good and not evil.
  98. ** May you find forgiveness for yourself and forgive others.
  99. ** May you share freely, never taking more than you give.
  100. **
  101. ******************************************************************************
  102. **
  103. ** This file contains code that is specific to MSVC.
  104. */
  105. #ifndef SQLITE_MSVC_H
  106. #define SQLITE_MSVC_H
  107. #if defined(_MSC_VER)
  108. #pragma warning(disable : 4054)
  109. #pragma warning(disable : 4055)
  110. #pragma warning(disable : 4100)
  111. #pragma warning(disable : 4127)
  112. #pragma warning(disable : 4130)
  113. #pragma warning(disable : 4152)
  114. #pragma warning(disable : 4189)
  115. #pragma warning(disable : 4206)
  116. #pragma warning(disable : 4210)
  117. #pragma warning(disable : 4232)
  118. #pragma warning(disable : 4244)
  119. #pragma warning(disable : 4305)
  120. #pragma warning(disable : 4306)
  121. #pragma warning(disable : 4702)
  122. #pragma warning(disable : 4706)
  123. #endif /* defined(_MSC_VER) */
  124. #endif /* SQLITE_MSVC_H */
  125. /************** End of msvc.h ************************************************/
  126. /************** Continuing where we left off in sqliteInt.h ******************/
  127. /*
  128. ** Special setup for VxWorks
  129. */
  130. /************** Include vxworks.h in the middle of sqliteInt.h ***************/
  131. /************** Begin file vxworks.h *****************************************/
  132. /*
  133. ** 2015-03-02
  134. **
  135. ** The author disclaims copyright to this source code. In place of
  136. ** a legal notice, here is a blessing:
  137. **
  138. ** May you do good and not evil.
  139. ** May you find forgiveness for yourself and forgive others.
  140. ** May you share freely, never taking more than you give.
  141. **
  142. ******************************************************************************
  143. **
  144. ** This file contains code that is specific to Wind River's VxWorks
  145. */
  146. #if defined(__RTP__) || defined(_WRS_KERNEL)
  147. /* This is VxWorks. Set up things specially for that OS
  148. */
  149. #include <vxWorks.h>
  150. #include <pthread.h> /* amalgamator: dontcache */
  151. #define OS_VXWORKS 1
  152. #define SQLITE_OS_OTHER 0
  153. #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
  154. #define SQLITE_OMIT_LOAD_EXTENSION 1
  155. #define SQLITE_ENABLE_LOCKING_STYLE 0
  156. #define HAVE_UTIME 1
  157. #else
  158. /* This is not VxWorks. */
  159. #define OS_VXWORKS 0
  160. #define HAVE_FCHOWN 1
  161. #define HAVE_READLINK 1
  162. #define HAVE_LSTAT 1
  163. #endif /* defined(_WRS_KERNEL) */
  164. /************** End of vxworks.h *********************************************/
  165. /************** Continuing where we left off in sqliteInt.h ******************/
  166. /*
  167. ** These #defines should enable >2GB file support on POSIX if the
  168. ** underlying operating system supports it. If the OS lacks
  169. ** large file support, or if the OS is windows, these should be no-ops.
  170. **
  171. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  172. ** system #includes. Hence, this block of code must be the very first
  173. ** code in all source files.
  174. **
  175. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  176. ** on the compiler command line. This is necessary if you are compiling
  177. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  178. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  179. ** without this option, LFS is enable. But LFS does not exist in the kernel
  180. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  181. ** portability you should omit LFS.
  182. **
  183. ** The previous paragraph was written in 2005. (This paragraph is written
  184. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  185. ** you should probably leave LFS enabled. But some embedded platforms might
  186. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  187. **
  188. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  189. */
  190. #ifndef SQLITE_DISABLE_LFS
  191. # define _LARGE_FILE 1
  192. # ifndef _FILE_OFFSET_BITS
  193. # define _FILE_OFFSET_BITS 64
  194. # endif
  195. # define _LARGEFILE_SOURCE 1
  196. #endif
  197. /* The GCC_VERSION and MSVC_VERSION macros are used to
  198. ** conditionally include optimizations for each of these compilers. A
  199. ** value of 0 means that compiler is not being used. The
  200. ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
  201. ** optimizations, and hence set all compiler macros to 0
  202. **
  203. ** There was once also a CLANG_VERSION macro. However, we learn that the
  204. ** version numbers in clang are for "marketing" only and are inconsistent
  205. ** and unreliable. Fortunately, all versions of clang also recognize the
  206. ** gcc version numbers and have reasonable settings for gcc version numbers,
  207. ** so the GCC_VERSION macro will be set to a correct non-zero value even
  208. ** when compiling with clang.
  209. */
  210. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  211. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  212. #else
  213. # define GCC_VERSION 0
  214. #endif
  215. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  216. # define MSVC_VERSION _MSC_VER
  217. #else
  218. # define MSVC_VERSION 0
  219. #endif
  220. /* Needed for various definitions... */
  221. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  222. # define _GNU_SOURCE
  223. #endif
  224. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  225. # define _BSD_SOURCE
  226. #endif
  227. /*
  228. ** For MinGW, check to see if we can include the header file containing its
  229. ** version information, among other things. Normally, this internal MinGW
  230. ** header file would [only] be included automatically by other MinGW header
  231. ** files; however, the contained version information is now required by this
  232. ** header file to work around binary compatibility issues (see below) and
  233. ** this is the only known way to reliably obtain it. This entire #if block
  234. ** would be completely unnecessary if there was any other way of detecting
  235. ** MinGW via their preprocessor (e.g. if they customized their GCC to define
  236. ** some MinGW-specific macros). When compiling for MinGW, either the
  237. ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
  238. ** defined; otherwise, detection of conditions specific to MinGW will be
  239. ** disabled.
  240. */
  241. #if defined(_HAVE_MINGW_H)
  242. # include "mingw.h"
  243. #elif defined(_HAVE__MINGW_H)
  244. # include "_mingw.h"
  245. #endif
  246. /*
  247. ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
  248. ** define is required to maintain binary compatibility with the MSVC runtime
  249. ** library in use (e.g. for Windows XP).
  250. */
  251. #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
  252. defined(_WIN32) && !defined(_WIN64) && \
  253. defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
  254. defined(__MSVCRT__)
  255. # define _USE_32BIT_TIME_T
  256. #endif
  257. /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
  258. ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
  259. ** MinGW.
  260. */
  261. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  262. /************** Begin file sqlite3.h *****************************************/
  263. /*
  264. ** 2001 September 15
  265. **
  266. ** The author disclaims copyright to this source code. In place of
  267. ** a legal notice, here is a blessing:
  268. **
  269. ** May you do good and not evil.
  270. ** May you find forgiveness for yourself and forgive others.
  271. ** May you share freely, never taking more than you give.
  272. **
  273. *************************************************************************
  274. ** This header file defines the interface that the SQLite library
  275. ** presents to client programs. If a C-function, structure, datatype,
  276. ** or constant definition does not appear in this file, then it is
  277. ** not a published API of SQLite, is subject to change without
  278. ** notice, and should not be referenced by programs that use SQLite.
  279. **
  280. ** Some of the definitions that are in this file are marked as
  281. ** "experimental". Experimental interfaces are normally new
  282. ** features recently added to SQLite. We do not anticipate changes
  283. ** to experimental interfaces but reserve the right to make minor changes
  284. ** if experience from use "in the wild" suggest such changes are prudent.
  285. **
  286. ** The official C-language API documentation for SQLite is derived
  287. ** from comments in this file. This file is the authoritative source
  288. ** on how SQLite interfaces are supposed to operate.
  289. **
  290. ** The name of this file under configuration management is "sqlite.h.in".
  291. ** The makefile makes some minor changes to this file (such as inserting
  292. ** the version number) and changes its name to "sqlite3.h" as
  293. ** part of the build process.
  294. */
  295. #ifndef SQLITE3_H
  296. #define SQLITE3_H
  297. #include <stdarg.h> /* Needed for the definition of va_list */
  298. /*
  299. ** Make sure we can call this stuff from C++.
  300. */
  301. #if 0
  302. extern "C" {
  303. #endif
  304. /*
  305. ** Provide the ability to override linkage features of the interface.
  306. */
  307. #ifndef SQLITE_EXTERN
  308. # define SQLITE_EXTERN extern
  309. #endif
  310. #ifndef SQLITE_API
  311. # define SQLITE_API
  312. #endif
  313. #ifndef SQLITE_CDECL
  314. # define SQLITE_CDECL
  315. #endif
  316. #ifndef SQLITE_APICALL
  317. # define SQLITE_APICALL
  318. #endif
  319. #ifndef SQLITE_STDCALL
  320. # define SQLITE_STDCALL SQLITE_APICALL
  321. #endif
  322. #ifndef SQLITE_CALLBACK
  323. # define SQLITE_CALLBACK
  324. #endif
  325. #ifndef SQLITE_SYSAPI
  326. # define SQLITE_SYSAPI
  327. #endif
  328. /*
  329. ** These no-op macros are used in front of interfaces to mark those
  330. ** interfaces as either deprecated or experimental. New applications
  331. ** should not use deprecated interfaces - they are supported for backwards
  332. ** compatibility only. Application writers should be aware that
  333. ** experimental interfaces are subject to change in point releases.
  334. **
  335. ** These macros used to resolve to various kinds of compiler magic that
  336. ** would generate warning messages when they were used. But that
  337. ** compiler magic ended up generating such a flurry of bug reports
  338. ** that we have taken it all out and gone back to using simple
  339. ** noop macros.
  340. */
  341. #define SQLITE_DEPRECATED
  342. #define SQLITE_EXPERIMENTAL
  343. /*
  344. ** Ensure these symbols were not defined by some previous header file.
  345. */
  346. #ifdef SQLITE_VERSION
  347. # undef SQLITE_VERSION
  348. #endif
  349. #ifdef SQLITE_VERSION_NUMBER
  350. # undef SQLITE_VERSION_NUMBER
  351. #endif
  352. /*
  353. ** CAPI3REF: Compile-Time Library Version Numbers
  354. **
  355. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  356. ** evaluates to a string literal that is the SQLite version in the
  357. ** format "X.Y.Z" where X is the major version number (always 3 for
  358. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  359. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  360. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  361. ** numbers used in [SQLITE_VERSION].)^
  362. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  363. ** be larger than the release from which it is derived. Either Y will
  364. ** be held constant and Z will be incremented or else Y will be incremented
  365. ** and Z will be reset to zero.
  366. **
  367. ** Since [version 3.6.18] ([dateof:3.6.18]),
  368. ** SQLite source code has been stored in the
  369. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  370. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  371. ** a string which identifies a particular check-in of SQLite
  372. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  373. ** string contains the date and time of the check-in (UTC) and a SHA1
  374. ** or SHA3-256 hash of the entire source tree.
  375. **
  376. ** See also: [sqlite3_libversion()],
  377. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  378. ** [sqlite_version()] and [sqlite_source_id()].
  379. */
  380. #define SQLITE_VERSION "3.19.3"
  381. #define SQLITE_VERSION_NUMBER 3019003
  382. #define SQLITE_SOURCE_ID "2017-06-08 14:26:16 0ee482a1e0eae22e08edc8978c9733a96603d4509645f348ebf55b579e89636b"
  383. /*
  384. ** CAPI3REF: Run-Time Library Version Numbers
  385. ** KEYWORDS: sqlite3_version sqlite3_sourceid
  386. **
  387. ** These interfaces provide the same information as the [SQLITE_VERSION],
  388. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  389. ** but are associated with the library instead of the header file. ^(Cautious
  390. ** programmers might include assert() statements in their application to
  391. ** verify that values returned by these interfaces match the macros in
  392. ** the header, and thus ensure that the application is
  393. ** compiled with matching library and header files.
  394. **
  395. ** <blockquote><pre>
  396. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  397. ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
  398. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  399. ** </pre></blockquote>)^
  400. **
  401. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  402. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  403. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  404. ** function is provided for use in DLLs since DLL users usually do not have
  405. ** direct access to string constants within the DLL. ^The
  406. ** sqlite3_libversion_number() function returns an integer equal to
  407. ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
  408. ** a pointer to a string constant whose value is the same as the
  409. ** [SQLITE_SOURCE_ID] C preprocessor macro.
  410. **
  411. ** See also: [sqlite_version()] and [sqlite_source_id()].
  412. */
  413. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  414. SQLITE_API const char *sqlite3_libversion(void);
  415. SQLITE_API const char *sqlite3_sourceid(void);
  416. SQLITE_API int sqlite3_libversion_number(void);
  417. /*
  418. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  419. **
  420. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  421. ** indicating whether the specified option was defined at
  422. ** compile time. ^The SQLITE_ prefix may be omitted from the
  423. ** option name passed to sqlite3_compileoption_used().
  424. **
  425. ** ^The sqlite3_compileoption_get() function allows iterating
  426. ** over the list of options that were defined at compile time by
  427. ** returning the N-th compile time option string. ^If N is out of range,
  428. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  429. ** prefix is omitted from any strings returned by
  430. ** sqlite3_compileoption_get().
  431. **
  432. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  433. ** and sqlite3_compileoption_get() may be omitted by specifying the
  434. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  435. **
  436. ** See also: SQL functions [sqlite_compileoption_used()] and
  437. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  438. */
  439. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  440. SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  441. SQLITE_API const char *sqlite3_compileoption_get(int N);
  442. #endif
  443. /*
  444. ** CAPI3REF: Test To See If The Library Is Threadsafe
  445. **
  446. ** ^The sqlite3_threadsafe() function returns zero if and only if
  447. ** SQLite was compiled with mutexing code omitted due to the
  448. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  449. **
  450. ** SQLite can be compiled with or without mutexes. When
  451. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  452. ** are enabled and SQLite is threadsafe. When the
  453. ** [SQLITE_THREADSAFE] macro is 0,
  454. ** the mutexes are omitted. Without the mutexes, it is not safe
  455. ** to use SQLite concurrently from more than one thread.
  456. **
  457. ** Enabling mutexes incurs a measurable performance penalty.
  458. ** So if speed is of utmost importance, it makes sense to disable
  459. ** the mutexes. But for maximum safety, mutexes should be enabled.
  460. ** ^The default behavior is for mutexes to be enabled.
  461. **
  462. ** This interface can be used by an application to make sure that the
  463. ** version of SQLite that it is linking against was compiled with
  464. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  465. **
  466. ** This interface only reports on the compile-time mutex setting
  467. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  468. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  469. ** can be fully or partially disabled using a call to [sqlite3_config()]
  470. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  471. ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
  472. ** sqlite3_threadsafe() function shows only the compile-time setting of
  473. ** thread safety, not any run-time changes to that setting made by
  474. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  475. ** is unchanged by calls to sqlite3_config().)^
  476. **
  477. ** See the [threading mode] documentation for additional information.
  478. */
  479. SQLITE_API int sqlite3_threadsafe(void);
  480. /*
  481. ** CAPI3REF: Database Connection Handle
  482. ** KEYWORDS: {database connection} {database connections}
  483. **
  484. ** Each open SQLite database is represented by a pointer to an instance of
  485. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  486. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  487. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  488. ** and [sqlite3_close_v2()] are its destructors. There are many other
  489. ** interfaces (such as
  490. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  491. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  492. ** sqlite3 object.
  493. */
  494. typedef struct sqlite3 sqlite3;
  495. /*
  496. ** CAPI3REF: 64-Bit Integer Types
  497. ** KEYWORDS: sqlite_int64 sqlite_uint64
  498. **
  499. ** Because there is no cross-platform way to specify 64-bit integer types
  500. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  501. **
  502. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  503. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  504. ** compatibility only.
  505. **
  506. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  507. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  508. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  509. ** between 0 and +18446744073709551615 inclusive.
  510. */
  511. #ifdef SQLITE_INT64_TYPE
  512. typedef SQLITE_INT64_TYPE sqlite_int64;
  513. # ifdef SQLITE_UINT64_TYPE
  514. typedef SQLITE_UINT64_TYPE sqlite_uint64;
  515. # else
  516. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  517. # endif
  518. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  519. typedef __int64 sqlite_int64;
  520. typedef unsigned __int64 sqlite_uint64;
  521. #else
  522. typedef long long int sqlite_int64;
  523. typedef unsigned long long int sqlite_uint64;
  524. #endif
  525. typedef sqlite_int64 sqlite3_int64;
  526. typedef sqlite_uint64 sqlite3_uint64;
  527. /*
  528. ** If compiling for a processor that lacks floating point support,
  529. ** substitute integer for floating-point.
  530. */
  531. #ifdef SQLITE_OMIT_FLOATING_POINT
  532. # define double sqlite3_int64
  533. #endif
  534. /*
  535. ** CAPI3REF: Closing A Database Connection
  536. ** DESTRUCTOR: sqlite3
  537. **
  538. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  539. ** for the [sqlite3] object.
  540. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
  541. ** the [sqlite3] object is successfully destroyed and all associated
  542. ** resources are deallocated.
  543. **
  544. ** ^If the database connection is associated with unfinalized prepared
  545. ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  546. ** will leave the database connection open and return [SQLITE_BUSY].
  547. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  548. ** and/or unfinished sqlite3_backups, then the database connection becomes
  549. ** an unusable "zombie" which will automatically be deallocated when the
  550. ** last prepared statement is finalized or the last sqlite3_backup is
  551. ** finished. The sqlite3_close_v2() interface is intended for use with
  552. ** host languages that are garbage collected, and where the order in which
  553. ** destructors are called is arbitrary.
  554. **
  555. ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  556. ** [sqlite3_blob_close | close] all [BLOB handles], and
  557. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  558. ** with the [sqlite3] object prior to attempting to close the object. ^If
  559. ** sqlite3_close_v2() is called on a [database connection] that still has
  560. ** outstanding [prepared statements], [BLOB handles], and/or
  561. ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
  562. ** of resources is deferred until all [prepared statements], [BLOB handles],
  563. ** and [sqlite3_backup] objects are also destroyed.
  564. **
  565. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  566. ** the transaction is automatically rolled back.
  567. **
  568. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  569. ** must be either a NULL
  570. ** pointer or an [sqlite3] object pointer obtained
  571. ** from [sqlite3_open()], [sqlite3_open16()], or
  572. ** [sqlite3_open_v2()], and not previously closed.
  573. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  574. ** argument is a harmless no-op.
  575. */
  576. SQLITE_API int sqlite3_close(sqlite3*);
  577. SQLITE_API int sqlite3_close_v2(sqlite3*);
  578. /*
  579. ** The type for a callback function.
  580. ** This is legacy and deprecated. It is included for historical
  581. ** compatibility and is not documented.
  582. */
  583. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  584. /*
  585. ** CAPI3REF: One-Step Query Execution Interface
  586. ** METHOD: sqlite3
  587. **
  588. ** The sqlite3_exec() interface is a convenience wrapper around
  589. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  590. ** that allows an application to run multiple statements of SQL
  591. ** without having to use a lot of C code.
  592. **
  593. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  594. ** semicolon-separate SQL statements passed into its 2nd argument,
  595. ** in the context of the [database connection] passed in as its 1st
  596. ** argument. ^If the callback function of the 3rd argument to
  597. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  598. ** coming out of the evaluated SQL statements. ^The 4th argument to
  599. ** sqlite3_exec() is relayed through to the 1st argument of each
  600. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  601. ** is NULL, then no callback is ever invoked and result rows are
  602. ** ignored.
  603. **
  604. ** ^If an error occurs while evaluating the SQL statements passed into
  605. ** sqlite3_exec(), then execution of the current statement stops and
  606. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  607. ** is not NULL then any error message is written into memory obtained
  608. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  609. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  610. ** on error message strings returned through the 5th parameter of
  611. ** sqlite3_exec() after the error message string is no longer needed.
  612. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  613. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  614. ** NULL before returning.
  615. **
  616. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  617. ** routine returns SQLITE_ABORT without invoking the callback again and
  618. ** without running any subsequent SQL statements.
  619. **
  620. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  621. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  622. ** callback is an array of pointers to strings obtained as if from
  623. ** [sqlite3_column_text()], one for each column. ^If an element of a
  624. ** result row is NULL then the corresponding string pointer for the
  625. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  626. ** sqlite3_exec() callback is an array of pointers to strings where each
  627. ** entry represents the name of corresponding result column as obtained
  628. ** from [sqlite3_column_name()].
  629. **
  630. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  631. ** to an empty string, or a pointer that contains only whitespace and/or
  632. ** SQL comments, then no SQL statements are evaluated and the database
  633. ** is not changed.
  634. **
  635. ** Restrictions:
  636. **
  637. ** <ul>
  638. ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
  639. ** is a valid and open [database connection].
  640. ** <li> The application must not close the [database connection] specified by
  641. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  642. ** <li> The application must not modify the SQL statement text passed into
  643. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  644. ** </ul>
  645. */
  646. SQLITE_API int sqlite3_exec(
  647. sqlite3*, /* An open database */
  648. const char *sql, /* SQL to be evaluated */
  649. int (*callback)(void*,int,char**,char**), /* Callback function */
  650. void *, /* 1st argument to callback */
  651. char **errmsg /* Error msg written here */
  652. );
  653. /*
  654. ** CAPI3REF: Result Codes
  655. ** KEYWORDS: {result code definitions}
  656. **
  657. ** Many SQLite functions return an integer result code from the set shown
  658. ** here in order to indicate success or failure.
  659. **
  660. ** New error codes may be added in future versions of SQLite.
  661. **
  662. ** See also: [extended result code definitions]
  663. */
  664. #define SQLITE_OK 0 /* Successful result */
  665. /* beginning-of-error-codes */
  666. #define SQLITE_ERROR 1 /* SQL error or missing database */
  667. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  668. #define SQLITE_PERM 3 /* Access permission denied */
  669. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  670. #define SQLITE_BUSY 5 /* The database file is locked */
  671. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  672. #define SQLITE_NOMEM 7 /* A malloc() failed */
  673. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  674. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  675. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  676. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  677. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  678. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  679. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  680. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  681. #define SQLITE_EMPTY 16 /* Database is empty */
  682. #define SQLITE_SCHEMA 17 /* The database schema changed */
  683. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  684. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  685. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  686. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  687. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  688. #define SQLITE_AUTH 23 /* Authorization denied */
  689. #define SQLITE_FORMAT 24 /* Auxiliary database format error */
  690. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  691. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  692. #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
  693. #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
  694. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  695. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  696. /* end-of-error-codes */
  697. /*
  698. ** CAPI3REF: Extended Result Codes
  699. ** KEYWORDS: {extended result code definitions}
  700. **
  701. ** In its default configuration, SQLite API routines return one of 30 integer
  702. ** [result codes]. However, experience has shown that many of
  703. ** these result codes are too coarse-grained. They do not provide as
  704. ** much information about problems as programmers might like. In an effort to
  705. ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
  706. ** and later) include
  707. ** support for additional result codes that provide more detailed information
  708. ** about errors. These [extended result codes] are enabled or disabled
  709. ** on a per database connection basis using the
  710. ** [sqlite3_extended_result_codes()] API. Or, the extended code for
  711. ** the most recent error can be obtained using
  712. ** [sqlite3_extended_errcode()].
  713. */
  714. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  715. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  716. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  717. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  718. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  719. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  720. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  721. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  722. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  723. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  724. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  725. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  726. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  727. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  728. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  729. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  730. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  731. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  732. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  733. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  734. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  735. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  736. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  737. #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
  738. #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
  739. #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
  740. #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
  741. #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
  742. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  743. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  744. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  745. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  746. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  747. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  748. #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
  749. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  750. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  751. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  752. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  753. #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
  754. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  755. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  756. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  757. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  758. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  759. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  760. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  761. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  762. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  763. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  764. #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
  765. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  766. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  767. #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
  768. #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
  769. #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8))
  770. /*
  771. ** CAPI3REF: Flags For File Open Operations
  772. **
  773. ** These bit values are intended for use in the
  774. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  775. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  776. */
  777. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  778. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  779. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  780. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  781. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  782. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  783. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  784. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  785. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  786. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  787. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  788. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  789. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  790. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  791. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  792. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  793. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  794. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  795. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  796. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  797. /* Reserved: 0x00F00000 */
  798. /*
  799. ** CAPI3REF: Device Characteristics
  800. **
  801. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  802. ** object returns an integer which is a vector of these
  803. ** bit values expressing I/O characteristics of the mass storage
  804. ** device that holds the file that the [sqlite3_io_methods]
  805. ** refers to.
  806. **
  807. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  808. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  809. ** mean that writes of blocks that are nnn bytes in size and
  810. ** are aligned to an address which is an integer multiple of
  811. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  812. ** that when data is appended to a file, the data is appended
  813. ** first then the size of the file is extended, never the other
  814. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  815. ** information is written to disk in the same order as calls
  816. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  817. ** after reboot following a crash or power loss, the only bytes in a
  818. ** file that were written at the application level might have changed
  819. ** and that adjacent bytes, even bytes within the same sector are
  820. ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  821. ** flag indicates that a file cannot be deleted when open. The
  822. ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
  823. ** read-only media and cannot be changed even by processes with
  824. ** elevated privileges.
  825. */
  826. #define SQLITE_IOCAP_ATOMIC 0x00000001
  827. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  828. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  829. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  830. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  831. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  832. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  833. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  834. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  835. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  836. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  837. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  838. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  839. #define SQLITE_IOCAP_IMMUTABLE 0x00002000
  840. /*
  841. ** CAPI3REF: File Locking Levels
  842. **
  843. ** SQLite uses one of these integer values as the second
  844. ** argument to calls it makes to the xLock() and xUnlock() methods
  845. ** of an [sqlite3_io_methods] object.
  846. */
  847. #define SQLITE_LOCK_NONE 0
  848. #define SQLITE_LOCK_SHARED 1
  849. #define SQLITE_LOCK_RESERVED 2
  850. #define SQLITE_LOCK_PENDING 3
  851. #define SQLITE_LOCK_EXCLUSIVE 4
  852. /*
  853. ** CAPI3REF: Synchronization Type Flags
  854. **
  855. ** When SQLite invokes the xSync() method of an
  856. ** [sqlite3_io_methods] object it uses a combination of
  857. ** these integer values as the second argument.
  858. **
  859. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  860. ** sync operation only needs to flush data to mass storage. Inode
  861. ** information need not be flushed. If the lower four bits of the flag
  862. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  863. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  864. ** to use Mac OS X style fullsync instead of fsync().
  865. **
  866. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  867. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  868. ** settings. The [synchronous pragma] determines when calls to the
  869. ** xSync VFS method occur and applies uniformly across all platforms.
  870. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  871. ** energetic or rigorous or forceful the sync operations are and
  872. ** only make a difference on Mac OSX for the default SQLite code.
  873. ** (Third-party VFS implementations might also make the distinction
  874. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  875. ** operating systems natively supported by SQLite, only Mac OSX
  876. ** cares about the difference.)
  877. */
  878. #define SQLITE_SYNC_NORMAL 0x00002
  879. #define SQLITE_SYNC_FULL 0x00003
  880. #define SQLITE_SYNC_DATAONLY 0x00010
  881. /*
  882. ** CAPI3REF: OS Interface Open File Handle
  883. **
  884. ** An [sqlite3_file] object represents an open file in the
  885. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  886. ** implementations will
  887. ** want to subclass this object by appending additional fields
  888. ** for their own use. The pMethods entry is a pointer to an
  889. ** [sqlite3_io_methods] object that defines methods for performing
  890. ** I/O operations on the open file.
  891. */
  892. typedef struct sqlite3_file sqlite3_file;
  893. struct sqlite3_file {
  894. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  895. };
  896. /*
  897. ** CAPI3REF: OS Interface File Virtual Methods Object
  898. **
  899. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  900. ** [sqlite3_file] object (or, more commonly, a subclass of the
  901. ** [sqlite3_file] object) with a pointer to an instance of this object.
  902. ** This object defines the methods used to perform various operations
  903. ** against the open file represented by the [sqlite3_file] object.
  904. **
  905. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  906. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  907. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  908. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  909. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  910. ** to NULL.
  911. **
  912. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  913. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  914. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  915. ** flag may be ORed in to indicate that only the data of the file
  916. ** and not its inode needs to be synced.
  917. **
  918. ** The integer values to xLock() and xUnlock() are one of
  919. ** <ul>
  920. ** <li> [SQLITE_LOCK_NONE],
  921. ** <li> [SQLITE_LOCK_SHARED],
  922. ** <li> [SQLITE_LOCK_RESERVED],
  923. ** <li> [SQLITE_LOCK_PENDING], or
  924. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  925. ** </ul>
  926. ** xLock() increases the lock. xUnlock() decreases the lock.
  927. ** The xCheckReservedLock() method checks whether any database connection,
  928. ** either in this process or in some other process, is holding a RESERVED,
  929. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  930. ** if such a lock exists and false otherwise.
  931. **
  932. ** The xFileControl() method is a generic interface that allows custom
  933. ** VFS implementations to directly control an open file using the
  934. ** [sqlite3_file_control()] interface. The second "op" argument is an
  935. ** integer opcode. The third argument is a generic pointer intended to
  936. ** point to a structure that may contain arguments or space in which to
  937. ** write return values. Potential uses for xFileControl() might be
  938. ** functions to enable blocking locks with timeouts, to change the
  939. ** locking strategy (for example to use dot-file locks), to inquire
  940. ** about the status of a lock, or to break stale locks. The SQLite
  941. ** core reserves all opcodes less than 100 for its own use.
  942. ** A [file control opcodes | list of opcodes] less than 100 is available.
  943. ** Applications that define a custom xFileControl method should use opcodes
  944. ** greater than 100 to avoid conflicts. VFS implementations should
  945. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  946. ** recognize.
  947. **
  948. ** The xSectorSize() method returns the sector size of the
  949. ** device that underlies the file. The sector size is the
  950. ** minimum write that can be performed without disturbing
  951. ** other bytes in the file. The xDeviceCharacteristics()
  952. ** method returns a bit vector describing behaviors of the
  953. ** underlying device:
  954. **
  955. ** <ul>
  956. ** <li> [SQLITE_IOCAP_ATOMIC]
  957. ** <li> [SQLITE_IOCAP_ATOMIC512]
  958. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  959. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  960. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  961. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  962. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  963. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  964. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  965. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  966. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  967. ** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
  968. ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
  969. ** <li> [SQLITE_IOCAP_IMMUTABLE]
  970. ** </ul>
  971. **
  972. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  973. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  974. ** mean that writes of blocks that are nnn bytes in size and
  975. ** are aligned to an address which is an integer multiple of
  976. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  977. ** that when data is appended to a file, the data is appended
  978. ** first then the size of the file is extended, never the other
  979. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  980. ** information is written to disk in the same order as calls
  981. ** to xWrite().
  982. **
  983. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  984. ** in the unread portions of the buffer with zeros. A VFS that
  985. ** fails to zero-fill short reads might seem to work. However,
  986. ** failure to zero-fill short reads will eventually lead to
  987. ** database corruption.
  988. */
  989. typedef struct sqlite3_io_methods sqlite3_io_methods;
  990. struct sqlite3_io_methods {
  991. int iVersion;
  992. int (*xClose)(sqlite3_file*);
  993. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  994. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  995. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  996. int (*xSync)(sqlite3_file*, int flags);
  997. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  998. int (*xLock)(sqlite3_file*, int);
  999. int (*xUnlock)(sqlite3_file*, int);
  1000. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  1001. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  1002. int (*xSectorSize)(sqlite3_file*);
  1003. int (*xDeviceCharacteristics)(sqlite3_file*);
  1004. /* Methods above are valid for version 1 */
  1005. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  1006. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  1007. void (*xShmBarrier)(sqlite3_file*);
  1008. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  1009. /* Methods above are valid for version 2 */
  1010. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  1011. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  1012. /* Methods above are valid for version 3 */
  1013. /* Additional methods may be added in future releases */
  1014. };
  1015. /*
  1016. ** CAPI3REF: Standard File Control Opcodes
  1017. ** KEYWORDS: {file control opcodes} {file control opcode}
  1018. **
  1019. ** These integer constants are opcodes for the xFileControl method
  1020. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  1021. ** interface.
  1022. **
  1023. ** <ul>
  1024. ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
  1025. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  1026. ** opcode causes the xFileControl method to write the current state of
  1027. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  1028. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  1029. ** into an integer that the pArg argument points to. This capability
  1030. ** is used during testing and is only available when the SQLITE_TEST
  1031. ** compile-time option is used.
  1032. **
  1033. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  1034. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  1035. ** layer a hint of how large the database file will grow to be during the
  1036. ** current transaction. This hint is not guaranteed to be accurate but it
  1037. ** is often close. The underlying VFS might choose to preallocate database
  1038. ** file space based on this hint in order to help writes to the database
  1039. ** file run faster.
  1040. **
  1041. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  1042. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  1043. ** extends and truncates the database file in chunks of a size specified
  1044. ** by the user. The fourth argument to [sqlite3_file_control()] should
  1045. ** point to an integer (type int) containing the new chunk-size to use
  1046. ** for the nominated database. Allocating database file space in large
  1047. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  1048. ** improve performance on some systems.
  1049. **
  1050. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  1051. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  1052. ** to the [sqlite3_file] object associated with a particular database
  1053. ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
  1054. **
  1055. ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
  1056. ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
  1057. ** to the [sqlite3_file] object associated with the journal file (either
  1058. ** the [rollback journal] or the [write-ahead log]) for a particular database
  1059. ** connection. See also [SQLITE_FCNTL_FILE_POINTER].
  1060. **
  1061. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  1062. ** No longer in use.
  1063. **
  1064. ** <li>[[SQLITE_FCNTL_SYNC]]
  1065. ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
  1066. ** sent to the VFS immediately before the xSync method is invoked on a
  1067. ** database file descriptor. Or, if the xSync method is not invoked
  1068. ** because the user has configured SQLite with
  1069. ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
  1070. ** of the xSync method. In most cases, the pointer argument passed with
  1071. ** this file-control is NULL. However, if the database file is being synced
  1072. ** as part of a multi-database commit, the argument points to a nul-terminated
  1073. ** string containing the transactions master-journal file name. VFSes that
  1074. ** do not need this signal should silently ignore this opcode. Applications
  1075. ** should not call [sqlite3_file_control()] with this opcode as doing so may
  1076. ** disrupt the operation of the specialized VFSes that do require it.
  1077. **
  1078. ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
  1079. ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
  1080. ** and sent to the VFS after a transaction has been committed immediately
  1081. ** but before the database is unlocked. VFSes that do not need this signal
  1082. ** should silently ignore this opcode. Applications should not call
  1083. ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
  1084. ** operation of the specialized VFSes that do require it.
  1085. **
  1086. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  1087. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  1088. ** retry counts and intervals for certain disk I/O operations for the
  1089. ** windows [VFS] in order to provide robustness in the presence of
  1090. ** anti-virus programs. By default, the windows VFS will retry file read,
  1091. ** file write, and file delete operations up to 10 times, with a delay
  1092. ** of 25 milliseconds before the first retry and with the delay increasing
  1093. ** by an additional 25 milliseconds with each subsequent retry. This
  1094. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1095. ** to be adjusted. The values are changed for all database connections
  1096. ** within the same process. The argument is a pointer to an array of two
  1097. ** integers where the first integer is the new retry count and the second
  1098. ** integer is the delay. If either integer is negative, then the setting
  1099. ** is not changed but instead the prior value of that setting is written
  1100. ** into the array entry, allowing the current retry settings to be
  1101. ** interrogated. The zDbName parameter is ignored.
  1102. **
  1103. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  1104. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1105. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  1106. ** write ahead log and shared memory files used for transaction control
  1107. ** are automatically deleted when the latest connection to the database
  1108. ** closes. Setting persistent WAL mode causes those files to persist after
  1109. ** close. Persisting the files is useful when other processes that do not
  1110. ** have write permission on the directory containing the database file want
  1111. ** to read the database file, as the WAL and shared memory files must exist
  1112. ** in order for the database to be readable. The fourth parameter to
  1113. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1114. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1115. ** WAL mode. If the integer is -1, then it is overwritten with the current
  1116. ** WAL persistence setting.
  1117. **
  1118. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  1119. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1120. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  1121. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1122. ** xDeviceCharacteristics methods. The fourth parameter to
  1123. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1124. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1125. ** mode. If the integer is -1, then it is overwritten with the current
  1126. ** zero-damage mode setting.
  1127. **
  1128. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  1129. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1130. ** a write transaction to indicate that, unless it is rolled back for some
  1131. ** reason, the entire database file will be overwritten by the current
  1132. ** transaction. This is used by VACUUM operations.
  1133. **
  1134. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  1135. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  1136. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  1137. ** final bottom-level VFS are written into memory obtained from
  1138. ** [sqlite3_malloc()] and the result is stored in the char* variable
  1139. ** that the fourth parameter of [sqlite3_file_control()] points to.
  1140. ** The caller is responsible for freeing the memory when done. As with
  1141. ** all file-control actions, there is no guarantee that this will actually
  1142. ** do anything. Callers should initialize the char* variable to a NULL
  1143. ** pointer in case this file-control is not implemented. This file-control
  1144. ** is intended for diagnostic use only.
  1145. **
  1146. ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
  1147. ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
  1148. ** [VFSes] currently in use. ^(The argument X in
  1149. ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
  1150. ** of type "[sqlite3_vfs] **". This opcodes will set *X
  1151. ** to a pointer to the top-level VFS.)^
  1152. ** ^When there are multiple VFS shims in the stack, this opcode finds the
  1153. ** upper-most shim only.
  1154. **
  1155. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  1156. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  1157. ** file control is sent to the open [sqlite3_file] object corresponding
  1158. ** to the database file to which the pragma statement refers. ^The argument
  1159. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  1160. ** pointers to strings (char**) in which the second element of the array
  1161. ** is the name of the pragma and the third element is the argument to the
  1162. ** pragma or NULL if the pragma has no argument. ^The handler for an
  1163. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  1164. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  1165. ** or the equivalent and that string will become the result of the pragma or
  1166. ** the error message if the pragma fails. ^If the
  1167. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  1168. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  1169. ** file control returns [SQLITE_OK], then the parser assumes that the
  1170. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  1171. ** prepared statement if result string is NULL, or that returns a copy
  1172. ** of the result string if the string is non-NULL.
  1173. ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  1174. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  1175. ** that the VFS encountered an error while handling the [PRAGMA] and the
  1176. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  1177. ** file control occurs at the beginning of pragma statement analysis and so
  1178. ** it is able to override built-in [PRAGMA] statements.
  1179. **
  1180. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  1181. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  1182. ** file-control may be invoked by SQLite on the database file handle
  1183. ** shortly after it is opened in order to provide a custom VFS with access
  1184. ** to the connections busy-handler callback. The argument is of type (void **)
  1185. ** - an array of two (void *) values. The first (void *) actually points
  1186. ** to a function of type (int (*)(void *)). In order to invoke the connections
  1187. ** busy-handler, this function should be invoked with the second (void *) in
  1188. ** the array as the only argument. If it returns non-zero, then the operation
  1189. ** should be retried. If it returns zero, the custom VFS should abandon the
  1190. ** current operation.
  1191. **
  1192. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1193. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  1194. ** to have SQLite generate a
  1195. ** temporary filename using the same algorithm that is followed to generate
  1196. ** temporary filenames for TEMP tables and other internal uses. The
  1197. ** argument should be a char** which will be filled with the filename
  1198. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  1199. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  1200. **
  1201. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  1202. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  1203. ** maximum number of bytes that will be used for memory-mapped I/O.
  1204. ** The argument is a pointer to a value of type sqlite3_int64 that
  1205. ** is an advisory maximum number of bytes in the file to memory map. The
  1206. ** pointer is overwritten with the old value. The limit is not changed if
  1207. ** the value originally pointed to is negative, and so the current limit
  1208. ** can be queried by passing in a pointer to a negative number. This
  1209. ** file-control is used internally to implement [PRAGMA mmap_size].
  1210. **
  1211. ** <li>[[SQLITE_FCNTL_TRACE]]
  1212. ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
  1213. ** to the VFS about what the higher layers of the SQLite stack are doing.
  1214. ** This file control is used by some VFS activity tracing [shims].
  1215. ** The argument is a zero-terminated string. Higher layers in the
  1216. ** SQLite stack may generate instances of this file control if
  1217. ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
  1218. **
  1219. ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
  1220. ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
  1221. ** pointer to an integer and it writes a boolean into that integer depending
  1222. ** on whether or not the file has been renamed, moved, or deleted since it
  1223. ** was first opened.
  1224. **
  1225. ** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
  1226. ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
  1227. ** underlying native file handle associated with a file handle. This file
  1228. ** control interprets its argument as a pointer to a native file handle and
  1229. ** writes the resulting value there.
  1230. **
  1231. ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
  1232. ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
  1233. ** opcode causes the xFileControl method to swap the file handle with the one
  1234. ** pointed to by the pArg argument. This capability is used during testing
  1235. ** and only needs to be supported when SQLITE_TEST is defined.
  1236. **
  1237. ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
  1238. ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
  1239. ** be advantageous to block on the next WAL lock if the lock is not immediately
  1240. ** available. The WAL subsystem issues this signal during rare
  1241. ** circumstances in order to fix a problem with priority inversion.
  1242. ** Applications should <em>not</em> use this file-control.
  1243. **
  1244. ** <li>[[SQLITE_FCNTL_ZIPVFS]]
  1245. ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
  1246. ** VFS should return SQLITE_NOTFOUND for this opcode.
  1247. **
  1248. ** <li>[[SQLITE_FCNTL_RBU]]
  1249. ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
  1250. ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
  1251. ** this opcode.
  1252. ** </ul>
  1253. */
  1254. #define SQLITE_FCNTL_LOCKSTATE 1
  1255. #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
  1256. #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
  1257. #define SQLITE_FCNTL_LAST_ERRNO 4
  1258. #define SQLITE_FCNTL_SIZE_HINT 5
  1259. #define SQLITE_FCNTL_CHUNK_SIZE 6
  1260. #define SQLITE_FCNTL_FILE_POINTER 7
  1261. #define SQLITE_FCNTL_SYNC_OMITTED 8
  1262. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  1263. #define SQLITE_FCNTL_PERSIST_WAL 10
  1264. #define SQLITE_FCNTL_OVERWRITE 11
  1265. #define SQLITE_FCNTL_VFSNAME 12
  1266. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  1267. #define SQLITE_FCNTL_PRAGMA 14
  1268. #define SQLITE_FCNTL_BUSYHANDLER 15
  1269. #define SQLITE_FCNTL_TEMPFILENAME 16
  1270. #define SQLITE_FCNTL_MMAP_SIZE 18
  1271. #define SQLITE_FCNTL_TRACE 19
  1272. #define SQLITE_FCNTL_HAS_MOVED 20
  1273. #define SQLITE_FCNTL_SYNC 21
  1274. #define SQLITE_FCNTL_COMMIT_PHASETWO 22
  1275. #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
  1276. #define SQLITE_FCNTL_WAL_BLOCK 24
  1277. #define SQLITE_FCNTL_ZIPVFS 25
  1278. #define SQLITE_FCNTL_RBU 26
  1279. #define SQLITE_FCNTL_VFS_POINTER 27
  1280. #define SQLITE_FCNTL_JOURNAL_POINTER 28
  1281. #define SQLITE_FCNTL_WIN32_GET_HANDLE 29
  1282. #define SQLITE_FCNTL_PDB 30
  1283. /* deprecated names */
  1284. #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
  1285. #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
  1286. #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
  1287. /*
  1288. ** CAPI3REF: Mutex Handle
  1289. **
  1290. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  1291. ** abstract type for a mutex object. The SQLite core never looks
  1292. ** at the internal representation of an [sqlite3_mutex]. It only
  1293. ** deals with pointers to the [sqlite3_mutex] object.
  1294. **
  1295. ** Mutexes are created using [sqlite3_mutex_alloc()].
  1296. */
  1297. typedef struct sqlite3_mutex sqlite3_mutex;
  1298. /*
  1299. ** CAPI3REF: Loadable Extension Thunk
  1300. **
  1301. ** A pointer to the opaque sqlite3_api_routines structure is passed as
  1302. ** the third parameter to entry points of [loadable extensions]. This
  1303. ** structure must be typedefed in order to work around compiler warnings
  1304. ** on some platforms.
  1305. */
  1306. typedef struct sqlite3_api_routines sqlite3_api_routines;
  1307. /*
  1308. ** CAPI3REF: OS Interface Object
  1309. **
  1310. ** An instance of the sqlite3_vfs object defines the interface between
  1311. ** the SQLite core and the underlying operating system. The "vfs"
  1312. ** in the name of the object stands for "virtual file system". See
  1313. ** the [VFS | VFS documentation] for further information.
  1314. **
  1315. ** The value of the iVersion field is initially 1 but may be larger in
  1316. ** future versions of SQLite. Additional fields may be appended to this
  1317. ** object when the iVersion value is increased. Note that the structure
  1318. ** of the sqlite3_vfs object changes in the transaction between
  1319. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  1320. ** modified.
  1321. **
  1322. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  1323. ** structure used by this VFS. mxPathname is the maximum length of
  1324. ** a pathname in this VFS.
  1325. **
  1326. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  1327. ** the pNext pointer. The [sqlite3_vfs_register()]
  1328. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  1329. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  1330. ** searches the list. Neither the application code nor the VFS
  1331. ** implementation should use the pNext pointer.
  1332. **
  1333. ** The pNext field is the only field in the sqlite3_vfs
  1334. ** structure that SQLite will ever modify. SQLite will only access
  1335. ** or modify this field while holding a particular static mutex.
  1336. ** The application should never modify anything within the sqlite3_vfs
  1337. ** object once the object has been registered.
  1338. **
  1339. ** The zName field holds the name of the VFS module. The name must
  1340. ** be unique across all VFS modules.
  1341. **
  1342. ** [[sqlite3_vfs.xOpen]]
  1343. ** ^SQLite guarantees that the zFilename parameter to xOpen
  1344. ** is either a NULL pointer or string obtained
  1345. ** from xFullPathname() with an optional suffix added.
  1346. ** ^If a suffix is added to the zFilename parameter, it will
  1347. ** consist of a single "-" character followed by no more than
  1348. ** 11 alphanumeric and/or "-" characters.
  1349. ** ^SQLite further guarantees that
  1350. ** the string will be valid and unchanged until xClose() is
  1351. ** called. Because of the previous sentence,
  1352. ** the [sqlite3_file] can safely store a pointer to the
  1353. ** filename if it needs to remember the filename for some reason.
  1354. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  1355. ** must invent its own temporary name for the file. ^Whenever the
  1356. ** xFilename parameter is NULL it will also be the case that the
  1357. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  1358. **
  1359. ** The flags argument to xOpen() includes all bits set in
  1360. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  1361. ** or [sqlite3_open16()] is used, then flags includes at least
  1362. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  1363. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  1364. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  1365. **
  1366. ** ^(SQLite will also add one of the following flags to the xOpen()
  1367. ** call, depending on the object being opened:
  1368. **
  1369. ** <ul>
  1370. ** <li> [SQLITE_OPEN_MAIN_DB]
  1371. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  1372. ** <li> [SQLITE_OPEN_TEMP_DB]
  1373. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  1374. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  1375. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  1376. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  1377. ** <li> [SQLITE_OPEN_WAL]
  1378. ** </ul>)^
  1379. **
  1380. ** The file I/O implementation can use the object type flags to
  1381. ** change the way it deals with files. For example, an application
  1382. ** that does not care about crash recovery or rollback might make
  1383. ** the open of a journal file a no-op. Writes to this journal would
  1384. ** also be no-ops, and any attempt to read the journal would return
  1385. ** SQLITE_IOERR. Or the implementation might recognize that a database
  1386. ** file will be doing page-aligned sector reads and writes in a random
  1387. ** order and set up its I/O subsystem accordingly.
  1388. **
  1389. ** SQLite might also add one of the following flags to the xOpen method:
  1390. **
  1391. ** <ul>
  1392. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1393. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  1394. ** </ul>
  1395. **
  1396. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1397. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  1398. ** will be set for TEMP databases and their journals, transient
  1399. ** databases, and subjournals.
  1400. **
  1401. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  1402. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  1403. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  1404. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  1405. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  1406. ** be created, and that it is an error if it already exists.
  1407. ** It is <i>not</i> used to indicate the file should be opened
  1408. ** for exclusive access.
  1409. **
  1410. ** ^At least szOsFile bytes of memory are allocated by SQLite
  1411. ** to hold the [sqlite3_file] structure passed as the third
  1412. ** argument to xOpen. The xOpen method does not have to
  1413. ** allocate the structure; it should just fill it in. Note that
  1414. ** the xOpen method must set the sqlite3_file.pMethods to either
  1415. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  1416. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  1417. ** element will be valid after xOpen returns regardless of the success
  1418. ** or failure of the xOpen call.
  1419. **
  1420. ** [[sqlite3_vfs.xAccess]]
  1421. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1422. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1423. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1424. ** to test whether a file is at least readable. The file can be a
  1425. ** directory.
  1426. **
  1427. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  1428. ** output buffer xFullPathname. The exact size of the output buffer
  1429. ** is also passed as a parameter to both methods. If the output buffer
  1430. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1431. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  1432. ** to prevent this by setting mxPathname to a sufficiently large value.
  1433. **
  1434. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  1435. ** interfaces are not strictly a part of the filesystem, but they are
  1436. ** included in the VFS structure for completeness.
  1437. ** The xRandomness() function attempts to return nBytes bytes
  1438. ** of good-quality randomness into zOut. The return value is
  1439. ** the actual number of bytes of randomness obtained.
  1440. ** The xSleep() method causes the calling thread to sleep for at
  1441. ** least the number of microseconds given. ^The xCurrentTime()
  1442. ** method returns a Julian Day Number for the current date and time as
  1443. ** a floating point value.
  1444. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  1445. ** Day Number multiplied by 86400000 (the number of milliseconds in
  1446. ** a 24-hour day).
  1447. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  1448. ** date and time if that method is available (if iVersion is 2 or
  1449. ** greater and the function pointer is not NULL) and will fall back
  1450. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  1451. **
  1452. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  1453. ** are not used by the SQLite core. These optional interfaces are provided
  1454. ** by some VFSes to facilitate testing of the VFS code. By overriding
  1455. ** system calls with functions under its control, a test program can
  1456. ** simulate faults and error conditions that would otherwise be difficult
  1457. ** or impossible to induce. The set of system calls that can be overridden
  1458. ** varies from one VFS to another, and from one version of the same VFS to the
  1459. ** next. Applications that use these interfaces must be prepared for any
  1460. ** or all of these interfaces to be NULL or for their behavior to change
  1461. ** from one release to the next. Applications must not attempt to access
  1462. ** any of these methods if the iVersion of the VFS is less than 3.
  1463. */
  1464. typedef struct sqlite3_vfs sqlite3_vfs;
  1465. typedef void (*sqlite3_syscall_ptr)(void);
  1466. struct sqlite3_vfs {
  1467. int iVersion; /* Structure version number (currently 3) */
  1468. int szOsFile; /* Size of subclassed sqlite3_file */
  1469. int mxPathname; /* Maximum file pathname length */
  1470. sqlite3_vfs *pNext; /* Next registered VFS */
  1471. const char *zName; /* Name of this virtual file system */
  1472. void *pAppData; /* Pointer to application-specific data */
  1473. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1474. int flags, int *pOutFlags);
  1475. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1476. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1477. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1478. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1479. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1480. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1481. void (*xDlClose)(sqlite3_vfs*, void*);
  1482. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1483. int (*xSleep)(sqlite3_vfs*, int microseconds);
  1484. int (*xCurrentTime)(sqlite3_vfs*, double*);
  1485. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1486. /*
  1487. ** The methods above are in version 1 of the sqlite_vfs object
  1488. ** definition. Those that follow are added in version 2 or later
  1489. */
  1490. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  1491. /*
  1492. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  1493. ** Those below are for version 3 and greater.
  1494. */
  1495. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  1496. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  1497. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  1498. /*
  1499. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  1500. ** New fields may be appended in future versions. The iVersion
  1501. ** value will increment whenever this happens.
  1502. */
  1503. };
  1504. /*
  1505. ** CAPI3REF: Flags for the xAccess VFS method
  1506. **
  1507. ** These integer constants can be used as the third parameter to
  1508. ** the xAccess method of an [sqlite3_vfs] object. They determine
  1509. ** what kind of permissions the xAccess method is looking for.
  1510. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  1511. ** simply checks whether the file exists.
  1512. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  1513. ** checks whether the named directory is both readable and writable
  1514. ** (in other words, if files can be added, removed, and renamed within
  1515. ** the directory).
  1516. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  1517. ** [temp_store_directory pragma], though this could change in a future
  1518. ** release of SQLite.
  1519. ** With SQLITE_ACCESS_READ, the xAccess method
  1520. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  1521. ** currently unused, though it might be used in a future release of
  1522. ** SQLite.
  1523. */
  1524. #define SQLITE_ACCESS_EXISTS 0
  1525. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  1526. #define SQLITE_ACCESS_READ 2 /* Unused */
  1527. /*
  1528. ** CAPI3REF: Flags for the xShmLock VFS method
  1529. **
  1530. ** These integer constants define the various locking operations
  1531. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  1532. ** following are the only legal combinations of flags to the
  1533. ** xShmLock method:
  1534. **
  1535. ** <ul>
  1536. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  1537. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  1538. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  1539. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  1540. ** </ul>
  1541. **
  1542. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  1543. ** was given on the corresponding lock.
  1544. **
  1545. ** The xShmLock method can transition between unlocked and SHARED or
  1546. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  1547. ** and EXCLUSIVE.
  1548. */
  1549. #define SQLITE_SHM_UNLOCK 1
  1550. #define SQLITE_SHM_LOCK 2
  1551. #define SQLITE_SHM_SHARED 4
  1552. #define SQLITE_SHM_EXCLUSIVE 8
  1553. /*
  1554. ** CAPI3REF: Maximum xShmLock index
  1555. **
  1556. ** The xShmLock method on [sqlite3_io_methods] may use values
  1557. ** between 0 and this upper bound as its "offset" argument.
  1558. ** The SQLite core will never attempt to acquire or release a
  1559. ** lock outside of this range
  1560. */
  1561. #define SQLITE_SHM_NLOCK 8
  1562. /*
  1563. ** CAPI3REF: Initialize The SQLite Library
  1564. **
  1565. ** ^The sqlite3_initialize() routine initializes the
  1566. ** SQLite library. ^The sqlite3_shutdown() routine
  1567. ** deallocates any resources that were allocated by sqlite3_initialize().
  1568. ** These routines are designed to aid in process initialization and
  1569. ** shutdown on embedded systems. Workstation applications using
  1570. ** SQLite normally do not need to invoke either of these routines.
  1571. **
  1572. ** A call to sqlite3_initialize() is an "effective" call if it is
  1573. ** the first time sqlite3_initialize() is invoked during the lifetime of
  1574. ** the process, or if it is the first time sqlite3_initialize() is invoked
  1575. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  1576. ** of sqlite3_initialize() does any initialization. All other calls
  1577. ** are harmless no-ops.)^
  1578. **
  1579. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  1580. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  1581. ** an effective call to sqlite3_shutdown() does any deinitialization.
  1582. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  1583. **
  1584. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  1585. ** is not. The sqlite3_shutdown() interface must only be called from a
  1586. ** single thread. All open [database connections] must be closed and all
  1587. ** other SQLite resources must be deallocated prior to invoking
  1588. ** sqlite3_shutdown().
  1589. **
  1590. ** Among other things, ^sqlite3_initialize() will invoke
  1591. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  1592. ** will invoke sqlite3_os_end().
  1593. **
  1594. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1595. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  1596. ** the library (perhaps it is unable to allocate a needed resource such
  1597. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1598. **
  1599. ** ^The sqlite3_initialize() routine is called internally by many other
  1600. ** SQLite interfaces so that an application usually does not need to
  1601. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  1602. ** calls sqlite3_initialize() so the SQLite library will be automatically
  1603. ** initialized when [sqlite3_open()] is called if it has not be initialized
  1604. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1605. ** compile-time option, then the automatic calls to sqlite3_initialize()
  1606. ** are omitted and the application must call sqlite3_initialize() directly
  1607. ** prior to using any other SQLite interface. For maximum portability,
  1608. ** it is recommended that applications always invoke sqlite3_initialize()
  1609. ** directly prior to using any other SQLite interface. Future releases
  1610. ** of SQLite may require this. In other words, the behavior exhibited
  1611. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1612. ** default behavior in some future release of SQLite.
  1613. **
  1614. ** The sqlite3_os_init() routine does operating-system specific
  1615. ** initialization of the SQLite library. The sqlite3_os_end()
  1616. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  1617. ** performed by these routines include allocation or deallocation
  1618. ** of static resources, initialization of global variables,
  1619. ** setting up a default [sqlite3_vfs] module, or setting up
  1620. ** a default configuration using [sqlite3_config()].
  1621. **
  1622. ** The application should never invoke either sqlite3_os_init()
  1623. ** or sqlite3_os_end() directly. The application should only invoke
  1624. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  1625. ** interface is called automatically by sqlite3_initialize() and
  1626. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  1627. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  1628. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  1629. ** When [custom builds | built for other platforms]
  1630. ** (using the [SQLITE_OS_OTHER=1] compile-time
  1631. ** option) the application must supply a suitable implementation for
  1632. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  1633. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  1634. ** must return [SQLITE_OK] on success and some other [error code] upon
  1635. ** failure.
  1636. */
  1637. SQLITE_API int sqlite3_initialize(void);
  1638. SQLITE_API int sqlite3_shutdown(void);
  1639. SQLITE_API int sqlite3_os_init(void);
  1640. SQLITE_API int sqlite3_os_end(void);
  1641. /*
  1642. ** CAPI3REF: Configuring The SQLite Library
  1643. **
  1644. ** The sqlite3_config() interface is used to make global configuration
  1645. ** changes to SQLite in order to tune SQLite to the specific needs of
  1646. ** the application. The default configuration is recommended for most
  1647. ** applications and so this routine is usually not necessary. It is
  1648. ** provided to support rare applications with unusual needs.
  1649. **
  1650. ** <b>The sqlite3_config() interface is not threadsafe. The application
  1651. ** must ensure that no other SQLite interfaces are invoked by other
  1652. ** threads while sqlite3_config() is running.</b>
  1653. **
  1654. ** The sqlite3_config() interface
  1655. ** may only be invoked prior to library initialization using
  1656. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1657. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  1658. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  1659. ** Note, however, that ^sqlite3_config() can be called as part of the
  1660. ** implementation of an application-defined [sqlite3_os_init()].
  1661. **
  1662. ** The first argument to sqlite3_config() is an integer
  1663. ** [configuration option] that determines
  1664. ** what property of SQLite is to be configured. Subsequent arguments
  1665. ** vary depending on the [configuration option]
  1666. ** in the first argument.
  1667. **
  1668. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1669. ** ^If the option is unknown or SQLite is unable to set the option
  1670. ** then this routine returns a non-zero [error code].
  1671. */
  1672. SQLITE_API int sqlite3_config(int, ...);
  1673. /*
  1674. ** CAPI3REF: Configure database connections
  1675. ** METHOD: sqlite3
  1676. **
  1677. ** The sqlite3_db_config() interface is used to make configuration
  1678. ** changes to a [database connection]. The interface is similar to
  1679. ** [sqlite3_config()] except that the changes apply to a single
  1680. ** [database connection] (specified in the first argument).
  1681. **
  1682. ** The second argument to sqlite3_db_config(D,V,...) is the
  1683. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  1684. ** that indicates what aspect of the [database connection] is being configured.
  1685. ** Subsequent arguments vary depending on the configuration verb.
  1686. **
  1687. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  1688. ** the call is considered successful.
  1689. */
  1690. SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  1691. /*
  1692. ** CAPI3REF: Memory Allocation Routines
  1693. **
  1694. ** An instance of this object defines the interface between SQLite
  1695. ** and low-level memory allocation routines.
  1696. **
  1697. ** This object is used in only one place in the SQLite interface.
  1698. ** A pointer to an instance of this object is the argument to
  1699. ** [sqlite3_config()] when the configuration option is
  1700. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  1701. ** By creating an instance of this object
  1702. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  1703. ** during configuration, an application can specify an alternative
  1704. ** memory allocation subsystem for SQLite to use for all of its
  1705. ** dynamic memory needs.
  1706. **
  1707. ** Note that SQLite comes with several [built-in memory allocators]
  1708. ** that are perfectly adequate for the overwhelming majority of applications
  1709. ** and that this object is only useful to a tiny minority of applications
  1710. ** with specialized memory allocation requirements. This object is
  1711. ** also used during testing of SQLite in order to specify an alternative
  1712. ** memory allocator that simulates memory out-of-memory conditions in
  1713. ** order to verify that SQLite recovers gracefully from such
  1714. ** conditions.
  1715. **
  1716. ** The xMalloc, xRealloc, and xFree methods must work like the
  1717. ** malloc(), realloc() and free() functions from the standard C library.
  1718. ** ^SQLite guarantees that the second argument to
  1719. ** xRealloc is always a value returned by a prior call to xRoundup.
  1720. **
  1721. ** xSize should return the allocated size of a memory allocation
  1722. ** previously obtained from xMalloc or xRealloc. The allocated size
  1723. ** is always at least as big as the requested size but may be larger.
  1724. **
  1725. ** The xRoundup method returns what would be the allocated size of
  1726. ** a memory allocation given a particular requested size. Most memory
  1727. ** allocators round up memory allocations at least to the next multiple
  1728. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  1729. ** Every memory allocation request coming in through [sqlite3_malloc()]
  1730. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  1731. ** that causes the corresponding memory allocation to fail.
  1732. **
  1733. ** The xInit method initializes the memory allocator. For example,
  1734. ** it might allocate any require mutexes or initialize internal data
  1735. ** structures. The xShutdown method is invoked (indirectly) by
  1736. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  1737. ** by xInit. The pAppData pointer is used as the only parameter to
  1738. ** xInit and xShutdown.
  1739. **
  1740. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  1741. ** the xInit method, so the xInit method need not be threadsafe. The
  1742. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  1743. ** not need to be threadsafe either. For all other methods, SQLite
  1744. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  1745. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  1746. ** it is by default) and so the methods are automatically serialized.
  1747. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  1748. ** methods must be threadsafe or else make their own arrangements for
  1749. ** serialization.
  1750. **
  1751. ** SQLite will never invoke xInit() more than once without an intervening
  1752. ** call to xShutdown().
  1753. */
  1754. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1755. struct sqlite3_mem_methods {
  1756. void *(*xMalloc)(int); /* Memory allocation function */
  1757. void (*xFree)(void*); /* Free a prior allocation */
  1758. void *(*xRealloc)(void*,int); /* Resize an allocation */
  1759. int (*xSize)(void*); /* Return the size of an allocation */
  1760. int (*xRoundup)(int); /* Round up request size to allocation size */
  1761. int (*xInit)(void*); /* Initialize the memory allocator */
  1762. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  1763. void *pAppData; /* Argument to xInit() and xShutdown() */
  1764. };
  1765. /*
  1766. ** CAPI3REF: Configuration Options
  1767. ** KEYWORDS: {configuration option}
  1768. **
  1769. ** These constants are the available integer configuration options that
  1770. ** can be passed as the first argument to the [sqlite3_config()] interface.
  1771. **
  1772. ** New configuration options may be added in future releases of SQLite.
  1773. ** Existing configuration options might be discontinued. Applications
  1774. ** should check the return code from [sqlite3_config()] to make sure that
  1775. ** the call worked. The [sqlite3_config()] interface will return a
  1776. ** non-zero [error code] if a discontinued or unsupported configuration option
  1777. ** is invoked.
  1778. **
  1779. ** <dl>
  1780. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1781. ** <dd>There are no arguments to this option. ^This option sets the
  1782. ** [threading mode] to Single-thread. In other words, it disables
  1783. ** all mutexing and puts SQLite into a mode where it can only be used
  1784. ** by a single thread. ^If SQLite is compiled with
  1785. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1786. ** it is not possible to change the [threading mode] from its default
  1787. ** value of Single-thread and so [sqlite3_config()] will return
  1788. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  1789. ** configuration option.</dd>
  1790. **
  1791. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1792. ** <dd>There are no arguments to this option. ^This option sets the
  1793. ** [threading mode] to Multi-thread. In other words, it disables
  1794. ** mutexing on [database connection] and [prepared statement] objects.
  1795. ** The application is responsible for serializing access to
  1796. ** [database connections] and [prepared statements]. But other mutexes
  1797. ** are enabled so that SQLite will be safe to use in a multi-threaded
  1798. ** environment as long as no two threads attempt to use the same
  1799. ** [database connection] at the same time. ^If SQLite is compiled with
  1800. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1801. ** it is not possible to set the Multi-thread [threading mode] and
  1802. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1803. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  1804. **
  1805. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1806. ** <dd>There are no arguments to this option. ^This option sets the
  1807. ** [threading mode] to Serialized. In other words, this option enables
  1808. ** all mutexes including the recursive
  1809. ** mutexes on [database connection] and [prepared statement] objects.
  1810. ** In this mode (which is the default when SQLite is compiled with
  1811. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1812. ** to [database connections] and [prepared statements] so that the
  1813. ** application is free to use the same [database connection] or the
  1814. ** same [prepared statement] in different threads at the same time.
  1815. ** ^If SQLite is compiled with
  1816. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1817. ** it is not possible to set the Serialized [threading mode] and
  1818. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1819. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  1820. **
  1821. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  1822. ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
  1823. ** a pointer to an instance of the [sqlite3_mem_methods] structure.
  1824. ** The argument specifies
  1825. ** alternative low-level memory allocation routines to be used in place of
  1826. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  1827. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  1828. ** before the [sqlite3_config()] call returns.</dd>
  1829. **
  1830. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1831. ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
  1832. ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
  1833. ** The [sqlite3_mem_methods]
  1834. ** structure is filled with the currently defined memory allocation routines.)^
  1835. ** This option can be used to overload the default memory allocation
  1836. ** routines with a wrapper that simulations memory allocation failure or
  1837. ** tracks memory usage, for example. </dd>
  1838. **
  1839. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1840. ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
  1841. ** interpreted as a boolean, which enables or disables the collection of
  1842. ** memory allocation statistics. ^(When memory allocation statistics are
  1843. ** disabled, the following SQLite interfaces become non-operational:
  1844. ** <ul>
  1845. ** <li> [sqlite3_memory_used()]
  1846. ** <li> [sqlite3_memory_highwater()]
  1847. ** <li> [sqlite3_soft_heap_limit64()]
  1848. ** <li> [sqlite3_status64()]
  1849. ** </ul>)^
  1850. ** ^Memory allocation statistics are enabled by default unless SQLite is
  1851. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  1852. ** allocation statistics are disabled by default.
  1853. ** </dd>
  1854. **
  1855. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  1856. ** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
  1857. ** that SQLite can use for scratch memory. ^(There are three arguments
  1858. ** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte
  1859. ** aligned memory buffer from which the scratch allocations will be
  1860. ** drawn, the size of each scratch allocation (sz),
  1861. ** and the maximum number of scratch allocations (N).)^
  1862. ** The first argument must be a pointer to an 8-byte aligned buffer
  1863. ** of at least sz*N bytes of memory.
  1864. ** ^SQLite will not use more than one scratch buffers per thread.
  1865. ** ^SQLite will never request a scratch buffer that is more than 6
  1866. ** times the database page size.
  1867. ** ^If SQLite needs needs additional
  1868. ** scratch memory beyond what is provided by this configuration option, then
  1869. ** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
  1870. ** ^When the application provides any amount of scratch memory using
  1871. ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
  1872. ** [sqlite3_malloc|heap allocations].
  1873. ** This can help [Robson proof|prevent memory allocation failures] due to heap
  1874. ** fragmentation in low-memory embedded systems.
  1875. ** </dd>
  1876. **
  1877. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1878. ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
  1879. ** that SQLite can use for the database page cache with the default page
  1880. ** cache implementation.
  1881. ** This configuration option is a no-op if an application-define page
  1882. ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
  1883. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
  1884. ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
  1885. ** and the number of cache lines (N).
  1886. ** The sz argument should be the size of the largest database page
  1887. ** (a power of two between 512 and 65536) plus some extra bytes for each
  1888. ** page header. ^The number of extra bytes needed by the page header
  1889. ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
  1890. ** ^It is harmless, apart from the wasted memory,
  1891. ** for the sz parameter to be larger than necessary. The pMem
  1892. ** argument must be either a NULL pointer or a pointer to an 8-byte
  1893. ** aligned block of memory of at least sz*N bytes, otherwise
  1894. ** subsequent behavior is undefined.
  1895. ** ^When pMem is not NULL, SQLite will strive to use the memory provided
  1896. ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
  1897. ** a page cache line is larger than sz bytes or if all of the pMem buffer
  1898. ** is exhausted.
  1899. ** ^If pMem is NULL and N is non-zero, then each database connection
  1900. ** does an initial bulk allocation for page cache memory
  1901. ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
  1902. ** of -1024*N bytes if N is negative, . ^If additional
  1903. ** page cache memory is needed beyond what is provided by the initial
  1904. ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
  1905. ** additional cache line. </dd>
  1906. **
  1907. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  1908. ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
  1909. ** that SQLite will use for all of its dynamic memory allocation needs
  1910. ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
  1911. ** [SQLITE_CONFIG_PAGECACHE].
  1912. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
  1913. ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
  1914. ** [SQLITE_ERROR] if invoked otherwise.
  1915. ** ^There are three arguments to SQLITE_CONFIG_HEAP:
  1916. ** An 8-byte aligned pointer to the memory,
  1917. ** the number of bytes in the memory buffer, and the minimum allocation size.
  1918. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  1919. ** to using its default memory allocator (the system malloc() implementation),
  1920. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  1921. ** memory pointer is not NULL then the alternative memory
  1922. ** allocator is engaged to handle all of SQLites memory allocation needs.
  1923. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  1924. ** boundary or subsequent behavior of SQLite will be undefined.
  1925. ** The minimum allocation size is capped at 2**12. Reasonable values
  1926. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  1927. **
  1928. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  1929. ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
  1930. ** pointer to an instance of the [sqlite3_mutex_methods] structure.
  1931. ** The argument specifies alternative low-level mutex routines to be used
  1932. ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
  1933. ** the content of the [sqlite3_mutex_methods] structure before the call to
  1934. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  1935. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1936. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1937. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  1938. ** return [SQLITE_ERROR].</dd>
  1939. **
  1940. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  1941. ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
  1942. ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
  1943. ** [sqlite3_mutex_methods]
  1944. ** structure is filled with the currently defined mutex routines.)^
  1945. ** This option can be used to overload the default mutex allocation
  1946. ** routines with a wrapper used to track mutex usage for performance
  1947. ** profiling or testing, for example. ^If SQLite is compiled with
  1948. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1949. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1950. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  1951. ** return [SQLITE_ERROR].</dd>
  1952. **
  1953. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  1954. ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
  1955. ** the default size of lookaside memory on each [database connection].
  1956. ** The first argument is the
  1957. ** size of each lookaside buffer slot and the second is the number of
  1958. ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
  1959. ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  1960. ** option to [sqlite3_db_config()] can be used to change the lookaside
  1961. ** configuration on individual connections.)^ </dd>
  1962. **
  1963. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  1964. ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
  1965. ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
  1966. ** the interface to a custom page cache implementation.)^
  1967. ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
  1968. **
  1969. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  1970. ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
  1971. ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
  1972. ** the current page cache implementation into that object.)^ </dd>
  1973. **
  1974. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  1975. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  1976. ** global [error log].
  1977. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  1978. ** function with a call signature of void(*)(void*,int,const char*),
  1979. ** and a pointer to void. ^If the function pointer is not NULL, it is
  1980. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  1981. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  1982. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  1983. ** passed through as the first parameter to the application-defined logger
  1984. ** function whenever that function is invoked. ^The second parameter to
  1985. ** the logger function is a copy of the first parameter to the corresponding
  1986. ** [sqlite3_log()] call and is intended to be a [result code] or an
  1987. ** [extended result code]. ^The third parameter passed to the logger is
  1988. ** log message after formatting via [sqlite3_snprintf()].
  1989. ** The SQLite logging interface is not reentrant; the logger function
  1990. ** supplied by the application must not invoke any SQLite interface.
  1991. ** In a multi-threaded application, the application-defined logger
  1992. ** function must be threadsafe. </dd>
  1993. **
  1994. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  1995. ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
  1996. ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
  1997. ** then URI handling is globally disabled.)^ ^If URI handling is globally
  1998. ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
  1999. ** [sqlite3_open16()] or
  2000. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  2001. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  2002. ** connection is opened. ^If it is globally disabled, filenames are
  2003. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  2004. ** database connection is opened. ^(By default, URI handling is globally
  2005. ** disabled. The default value may be changed by compiling with the
  2006. ** [SQLITE_USE_URI] symbol defined.)^
  2007. **
  2008. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  2009. ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
  2010. ** argument which is interpreted as a boolean in order to enable or disable
  2011. ** the use of covering indices for full table scans in the query optimizer.
  2012. ** ^The default setting is determined
  2013. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  2014. ** if that compile-time option is omitted.
  2015. ** The ability to disable the use of covering indices for full table scans
  2016. ** is because some incorrectly coded legacy applications might malfunction
  2017. ** when the optimization is enabled. Providing the ability to
  2018. ** disable the optimization allows the older, buggy application code to work
  2019. ** without change even with newer versions of SQLite.
  2020. **
  2021. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  2022. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  2023. ** <dd> These options are obsolete and should not be used by new code.
  2024. ** They are retained for backwards compatibility but are now no-ops.
  2025. ** </dd>
  2026. **
  2027. ** [[SQLITE_CONFIG_SQLLOG]]
  2028. ** <dt>SQLITE_CONFIG_SQLLOG
  2029. ** <dd>This option is only available if sqlite is compiled with the
  2030. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  2031. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  2032. ** The second should be of type (void*). The callback is invoked by the library
  2033. ** in three separate circumstances, identified by the value passed as the
  2034. ** fourth parameter. If the fourth parameter is 0, then the database connection
  2035. ** passed as the second argument has just been opened. The third argument
  2036. ** points to a buffer containing the name of the main database file. If the
  2037. ** fourth parameter is 1, then the SQL statement that the third parameter
  2038. ** points to has just been executed. Or, if the fourth parameter is 2, then
  2039. ** the connection being passed as the second parameter is being closed. The
  2040. ** third parameter is passed NULL In this case. An example of using this
  2041. ** configuration option can be seen in the "test_sqllog.c" source file in
  2042. ** the canonical SQLite source tree.</dd>
  2043. **
  2044. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  2045. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  2046. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  2047. ** that are the default mmap size limit (the default setting for
  2048. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  2049. ** ^The default setting can be overridden by each database connection using
  2050. ** either the [PRAGMA mmap_size] command, or by using the
  2051. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  2052. ** will be silently truncated if necessary so that it does not exceed the
  2053. ** compile-time maximum mmap size set by the
  2054. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  2055. ** ^If either argument to this option is negative, then that argument is
  2056. ** changed to its compile-time default.
  2057. **
  2058. ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  2059. ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  2060. ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
  2061. ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
  2062. ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  2063. ** that specifies the maximum size of the created heap.
  2064. **
  2065. ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
  2066. ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
  2067. ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
  2068. ** is a pointer to an integer and writes into that integer the number of extra
  2069. ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
  2070. ** The amount of extra space required can change depending on the compiler,
  2071. ** target platform, and SQLite version.
  2072. **
  2073. ** [[SQLITE_CONFIG_PMASZ]]
  2074. ** <dt>SQLITE_CONFIG_PMASZ
  2075. ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
  2076. ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
  2077. ** sorter to that integer. The default minimum PMA Size is set by the
  2078. ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
  2079. ** to help with sort operations when multithreaded sorting
  2080. ** is enabled (using the [PRAGMA threads] command) and the amount of content
  2081. ** to be sorted exceeds the page size times the minimum of the
  2082. ** [PRAGMA cache_size] setting and this value.
  2083. **
  2084. ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
  2085. ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
  2086. ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
  2087. ** becomes the [statement journal] spill-to-disk threshold.
  2088. ** [Statement journals] are held in memory until their size (in bytes)
  2089. ** exceeds this threshold, at which point they are written to disk.
  2090. ** Or if the threshold is -1, statement journals are always held
  2091. ** exclusively in memory.
  2092. ** Since many statement journals never become large, setting the spill
  2093. ** threshold to a value such as 64KiB can greatly reduce the amount of
  2094. ** I/O required to support statement rollback.
  2095. ** The default value for this setting is controlled by the
  2096. ** [SQLITE_STMTJRNL_SPILL] compile-time option.
  2097. ** </dl>
  2098. */
  2099. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  2100. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  2101. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  2102. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  2103. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  2104. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  2105. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  2106. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  2107. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  2108. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  2109. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  2110. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  2111. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  2112. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  2113. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  2114. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  2115. #define SQLITE_CONFIG_URI 17 /* int */
  2116. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  2117. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  2118. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  2119. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  2120. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  2121. #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
  2122. #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
  2123. #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
  2124. #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
  2125. /*
  2126. ** CAPI3REF: Database Connection Configuration Options
  2127. **
  2128. ** These constants are the available integer configuration options that
  2129. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  2130. **
  2131. ** New configuration options may be added in future releases of SQLite.
  2132. ** Existing configuration options might be discontinued. Applications
  2133. ** should check the return code from [sqlite3_db_config()] to make sure that
  2134. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  2135. ** non-zero [error code] if a discontinued or unsupported configuration option
  2136. ** is invoked.
  2137. **
  2138. ** <dl>
  2139. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  2140. ** <dd> ^This option takes three additional arguments that determine the
  2141. ** [lookaside memory allocator] configuration for the [database connection].
  2142. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  2143. ** pointer to a memory buffer to use for lookaside memory.
  2144. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  2145. ** may be NULL in which case SQLite will allocate the
  2146. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  2147. ** size of each lookaside buffer slot. ^The third argument is the number of
  2148. ** slots. The size of the buffer in the first argument must be greater than
  2149. ** or equal to the product of the second and third arguments. The buffer
  2150. ** must be aligned to an 8-byte boundary. ^If the second argument to
  2151. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  2152. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  2153. ** configuration for a database connection can only be changed when that
  2154. ** connection is not currently using lookaside memory, or in other words
  2155. ** when the "current value" returned by
  2156. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  2157. ** Any attempt to change the lookaside memory configuration when lookaside
  2158. ** memory is in use leaves the configuration unchanged and returns
  2159. ** [SQLITE_BUSY].)^</dd>
  2160. **
  2161. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  2162. ** <dd> ^This option is used to enable or disable the enforcement of
  2163. ** [foreign key constraints]. There should be two additional arguments.
  2164. ** The first argument is an integer which is 0 to disable FK enforcement,
  2165. ** positive to enable FK enforcement or negative to leave FK enforcement
  2166. ** unchanged. The second parameter is a pointer to an integer into which
  2167. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  2168. ** following this call. The second parameter may be a NULL pointer, in
  2169. ** which case the FK enforcement setting is not reported back. </dd>
  2170. **
  2171. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  2172. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  2173. ** There should be two additional arguments.
  2174. ** The first argument is an integer which is 0 to disable triggers,
  2175. ** positive to enable triggers or negative to leave the setting unchanged.
  2176. ** The second parameter is a pointer to an integer into which
  2177. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  2178. ** following this call. The second parameter may be a NULL pointer, in
  2179. ** which case the trigger setting is not reported back. </dd>
  2180. **
  2181. ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
  2182. ** <dd> ^This option is used to enable or disable the two-argument
  2183. ** version of the [fts3_tokenizer()] function which is part of the
  2184. ** [FTS3] full-text search engine extension.
  2185. ** There should be two additional arguments.
  2186. ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
  2187. ** positive to enable fts3_tokenizer() or negative to leave the setting
  2188. ** unchanged.
  2189. ** The second parameter is a pointer to an integer into which
  2190. ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
  2191. ** following this call. The second parameter may be a NULL pointer, in
  2192. ** which case the new setting is not reported back. </dd>
  2193. **
  2194. ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
  2195. ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
  2196. ** interface independently of the [load_extension()] SQL function.
  2197. ** The [sqlite3_enable_load_extension()] API enables or disables both the
  2198. ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
  2199. ** There should be two additional arguments.
  2200. ** When the first argument to this interface is 1, then only the C-API is
  2201. ** enabled and the SQL function remains disabled. If the first argument to
  2202. ** this interface is 0, then both the C-API and the SQL function are disabled.
  2203. ** If the first argument is -1, then no changes are made to state of either the
  2204. ** C-API or the SQL function.
  2205. ** The second parameter is a pointer to an integer into which
  2206. ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
  2207. ** is disabled or enabled following this call. The second parameter may
  2208. ** be a NULL pointer, in which case the new setting is not reported back.
  2209. ** </dd>
  2210. **
  2211. ** <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
  2212. ** <dd> ^This option is used to change the name of the "main" database
  2213. ** schema. ^The sole argument is a pointer to a constant UTF8 string
  2214. ** which will become the new schema name in place of "main". ^SQLite
  2215. ** does not make a copy of the new main schema name string, so the application
  2216. ** must ensure that the argument passed into this DBCONFIG option is unchanged
  2217. ** until after the database connection closes.
  2218. ** </dd>
  2219. **
  2220. ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
  2221. ** <dd> Usually, when a database in wal mode is closed or detached from a
  2222. ** database handle, SQLite checks if this will mean that there are now no
  2223. ** connections at all to the database. If so, it performs a checkpoint
  2224. ** operation before closing the connection. This option may be used to
  2225. ** override this behaviour. The first parameter passed to this operation
  2226. ** is an integer - non-zero to disable checkpoints-on-close, or zero (the
  2227. ** default) to enable them. The second parameter is a pointer to an integer
  2228. ** into which is written 0 or 1 to indicate whether checkpoints-on-close
  2229. ** have been disabled - 0 if they are not disabled, 1 if they are.
  2230. ** </dd>
  2231. **
  2232. ** </dl>
  2233. */
  2234. #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */
  2235. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  2236. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  2237. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  2238. #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
  2239. #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
  2240. #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */
  2241. /*
  2242. ** CAPI3REF: Enable Or Disable Extended Result Codes
  2243. ** METHOD: sqlite3
  2244. **
  2245. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  2246. ** [extended result codes] feature of SQLite. ^The extended result
  2247. ** codes are disabled by default for historical compatibility.
  2248. */
  2249. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  2250. /*
  2251. ** CAPI3REF: Last Insert Rowid
  2252. ** METHOD: sqlite3
  2253. **
  2254. ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  2255. ** has a unique 64-bit signed
  2256. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  2257. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  2258. ** names are not also used by explicitly declared columns. ^If
  2259. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  2260. ** is another alias for the rowid.
  2261. **
  2262. ** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
  2263. ** the most recent successful [INSERT] into a rowid table or [virtual table]
  2264. ** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
  2265. ** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
  2266. ** on the database connection D, then sqlite3_last_insert_rowid(D) returns
  2267. ** zero.
  2268. **
  2269. ** As well as being set automatically as rows are inserted into database
  2270. ** tables, the value returned by this function may be set explicitly by
  2271. ** [sqlite3_set_last_insert_rowid()]
  2272. **
  2273. ** Some virtual table implementations may INSERT rows into rowid tables as
  2274. ** part of committing a transaction (e.g. to flush data accumulated in memory
  2275. ** to disk). In this case subsequent calls to this function return the rowid
  2276. ** associated with these internal INSERT operations, which leads to
  2277. ** unintuitive results. Virtual table implementations that do write to rowid
  2278. ** tables in this way can avoid this problem by restoring the original
  2279. ** rowid value using [sqlite3_set_last_insert_rowid()] before returning
  2280. ** control to the user.
  2281. **
  2282. ** ^(If an [INSERT] occurs within a trigger then this routine will
  2283. ** return the [rowid] of the inserted row as long as the trigger is
  2284. ** running. Once the trigger program ends, the value returned
  2285. ** by this routine reverts to what it was before the trigger was fired.)^
  2286. **
  2287. ** ^An [INSERT] that fails due to a constraint violation is not a
  2288. ** successful [INSERT] and does not change the value returned by this
  2289. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  2290. ** and INSERT OR ABORT make no changes to the return value of this
  2291. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  2292. ** encounters a constraint violation, it does not fail. The
  2293. ** INSERT continues to completion after deleting rows that caused
  2294. ** the constraint problem so INSERT OR REPLACE will always change
  2295. ** the return value of this interface.)^
  2296. **
  2297. ** ^For the purposes of this routine, an [INSERT] is considered to
  2298. ** be successful even if it is subsequently rolled back.
  2299. **
  2300. ** This function is accessible to SQL statements via the
  2301. ** [last_insert_rowid() SQL function].
  2302. **
  2303. ** If a separate thread performs a new [INSERT] on the same
  2304. ** database connection while the [sqlite3_last_insert_rowid()]
  2305. ** function is running and thus changes the last insert [rowid],
  2306. ** then the value returned by [sqlite3_last_insert_rowid()] is
  2307. ** unpredictable and might not equal either the old or the new
  2308. ** last insert [rowid].
  2309. */
  2310. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  2311. /*
  2312. ** CAPI3REF: Set the Last Insert Rowid value.
  2313. ** METHOD: sqlite3
  2314. **
  2315. ** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
  2316. ** set the value returned by calling sqlite3_last_insert_rowid(D) to R
  2317. ** without inserting a row into the database.
  2318. */
  2319. SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
  2320. /*
  2321. ** CAPI3REF: Count The Number Of Rows Modified
  2322. ** METHOD: sqlite3
  2323. **
  2324. ** ^This function returns the number of rows modified, inserted or
  2325. ** deleted by the most recently completed INSERT, UPDATE or DELETE
  2326. ** statement on the database connection specified by the only parameter.
  2327. ** ^Executing any other type of SQL statement does not modify the value
  2328. ** returned by this function.
  2329. **
  2330. ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
  2331. ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
  2332. ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
  2333. **
  2334. ** Changes to a view that are intercepted by
  2335. ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
  2336. ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
  2337. ** DELETE statement run on a view is always zero. Only changes made to real
  2338. ** tables are counted.
  2339. **
  2340. ** Things are more complicated if the sqlite3_changes() function is
  2341. ** executed while a trigger program is running. This may happen if the
  2342. ** program uses the [changes() SQL function], or if some other callback
  2343. ** function invokes sqlite3_changes() directly. Essentially:
  2344. **
  2345. ** <ul>
  2346. ** <li> ^(Before entering a trigger program the value returned by
  2347. ** sqlite3_changes() function is saved. After the trigger program
  2348. ** has finished, the original value is restored.)^
  2349. **
  2350. ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
  2351. ** statement sets the value returned by sqlite3_changes()
  2352. ** upon completion as normal. Of course, this value will not include
  2353. ** any changes performed by sub-triggers, as the sqlite3_changes()
  2354. ** value will be saved and restored after each sub-trigger has run.)^
  2355. ** </ul>
  2356. **
  2357. ** ^This means that if the changes() SQL function (or similar) is used
  2358. ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
  2359. ** returns the value as set when the calling statement began executing.
  2360. ** ^If it is used by the second or subsequent such statement within a trigger
  2361. ** program, the value returned reflects the number of rows modified by the
  2362. ** previous INSERT, UPDATE or DELETE statement within the same trigger.
  2363. **
  2364. ** See also the [sqlite3_total_changes()] interface, the
  2365. ** [count_changes pragma], and the [changes() SQL function].
  2366. **
  2367. ** If a separate thread makes changes on the same database connection
  2368. ** while [sqlite3_changes()] is running then the value returned
  2369. ** is unpredictable and not meaningful.
  2370. */
  2371. SQLITE_API int sqlite3_changes(sqlite3*);
  2372. /*
  2373. ** CAPI3REF: Total Number Of Rows Modified
  2374. ** METHOD: sqlite3
  2375. **
  2376. ** ^This function returns the total number of rows inserted, modified or
  2377. ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
  2378. ** since the database connection was opened, including those executed as
  2379. ** part of trigger programs. ^Executing any other type of SQL statement
  2380. ** does not affect the value returned by sqlite3_total_changes().
  2381. **
  2382. ** ^Changes made as part of [foreign key actions] are included in the
  2383. ** count, but those made as part of REPLACE constraint resolution are
  2384. ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
  2385. ** are not counted.
  2386. **
  2387. ** See also the [sqlite3_changes()] interface, the
  2388. ** [count_changes pragma], and the [total_changes() SQL function].
  2389. **
  2390. ** If a separate thread makes changes on the same database connection
  2391. ** while [sqlite3_total_changes()] is running then the value
  2392. ** returned is unpredictable and not meaningful.
  2393. */
  2394. SQLITE_API int sqlite3_total_changes(sqlite3*);
  2395. /*
  2396. ** CAPI3REF: Interrupt A Long-Running Query
  2397. ** METHOD: sqlite3
  2398. **
  2399. ** ^This function causes any pending database operation to abort and
  2400. ** return at its earliest opportunity. This routine is typically
  2401. ** called in response to a user action such as pressing "Cancel"
  2402. ** or Ctrl-C where the user wants a long query operation to halt
  2403. ** immediately.
  2404. **
  2405. ** ^It is safe to call this routine from a thread different from the
  2406. ** thread that is currently running the database operation. But it
  2407. ** is not safe to call this routine with a [database connection] that
  2408. ** is closed or might close before sqlite3_interrupt() returns.
  2409. **
  2410. ** ^If an SQL operation is very nearly finished at the time when
  2411. ** sqlite3_interrupt() is called, then it might not have an opportunity
  2412. ** to be interrupted and might continue to completion.
  2413. **
  2414. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  2415. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  2416. ** that is inside an explicit transaction, then the entire transaction
  2417. ** will be rolled back automatically.
  2418. **
  2419. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  2420. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  2421. ** that are started after the sqlite3_interrupt() call and before the
  2422. ** running statements reaches zero are interrupted as if they had been
  2423. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  2424. ** that are started after the running statement count reaches zero are
  2425. ** not effected by the sqlite3_interrupt().
  2426. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  2427. ** SQL statements is a no-op and has no effect on SQL statements
  2428. ** that are started after the sqlite3_interrupt() call returns.
  2429. */
  2430. SQLITE_API void sqlite3_interrupt(sqlite3*);
  2431. /*
  2432. ** CAPI3REF: Determine If An SQL Statement Is Complete
  2433. **
  2434. ** These routines are useful during command-line input to determine if the
  2435. ** currently entered text seems to form a complete SQL statement or
  2436. ** if additional input is needed before sending the text into
  2437. ** SQLite for parsing. ^These routines return 1 if the input string
  2438. ** appears to be a complete SQL statement. ^A statement is judged to be
  2439. ** complete if it ends with a semicolon token and is not a prefix of a
  2440. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  2441. ** string literals or quoted identifier names or comments are not
  2442. ** independent tokens (they are part of the token in which they are
  2443. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  2444. ** and comments that follow the final semicolon are ignored.
  2445. **
  2446. ** ^These routines return 0 if the statement is incomplete. ^If a
  2447. ** memory allocation fails, then SQLITE_NOMEM is returned.
  2448. **
  2449. ** ^These routines do not parse the SQL statements thus
  2450. ** will not detect syntactically incorrect SQL.
  2451. **
  2452. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  2453. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  2454. ** automatically by sqlite3_complete16(). If that initialization fails,
  2455. ** then the return value from sqlite3_complete16() will be non-zero
  2456. ** regardless of whether or not the input SQL is complete.)^
  2457. **
  2458. ** The input to [sqlite3_complete()] must be a zero-terminated
  2459. ** UTF-8 string.
  2460. **
  2461. ** The input to [sqlite3_complete16()] must be a zero-terminated
  2462. ** UTF-16 string in native byte order.
  2463. */
  2464. SQLITE_API int sqlite3_complete(const char *sql);
  2465. SQLITE_API int sqlite3_complete16(const void *sql);
  2466. /*
  2467. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  2468. ** KEYWORDS: {busy-handler callback} {busy handler}
  2469. ** METHOD: sqlite3
  2470. **
  2471. ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
  2472. ** that might be invoked with argument P whenever
  2473. ** an attempt is made to access a database table associated with
  2474. ** [database connection] D when another thread
  2475. ** or process has the table locked.
  2476. ** The sqlite3_busy_handler() interface is used to implement
  2477. ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  2478. **
  2479. ** ^If the busy callback is NULL, then [SQLITE_BUSY]
  2480. ** is returned immediately upon encountering the lock. ^If the busy callback
  2481. ** is not NULL, then the callback might be invoked with two arguments.
  2482. **
  2483. ** ^The first argument to the busy handler is a copy of the void* pointer which
  2484. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  2485. ** the busy handler callback is the number of times that the busy handler has
  2486. ** been invoked previously for the same locking event. ^If the
  2487. ** busy callback returns 0, then no additional attempts are made to
  2488. ** access the database and [SQLITE_BUSY] is returned
  2489. ** to the application.
  2490. ** ^If the callback returns non-zero, then another attempt
  2491. ** is made to access the database and the cycle repeats.
  2492. **
  2493. ** The presence of a busy handler does not guarantee that it will be invoked
  2494. ** when there is lock contention. ^If SQLite determines that invoking the busy
  2495. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  2496. ** to the application instead of invoking the
  2497. ** busy handler.
  2498. ** Consider a scenario where one process is holding a read lock that
  2499. ** it is trying to promote to a reserved lock and
  2500. ** a second process is holding a reserved lock that it is trying
  2501. ** to promote to an exclusive lock. The first process cannot proceed
  2502. ** because it is blocked by the second and the second process cannot
  2503. ** proceed because it is blocked by the first. If both processes
  2504. ** invoke the busy handlers, neither will make any progress. Therefore,
  2505. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  2506. ** will induce the first process to release its read lock and allow
  2507. ** the second process to proceed.
  2508. **
  2509. ** ^The default busy callback is NULL.
  2510. **
  2511. ** ^(There can only be a single busy handler defined for each
  2512. ** [database connection]. Setting a new busy handler clears any
  2513. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  2514. ** or evaluating [PRAGMA busy_timeout=N] will change the
  2515. ** busy handler and thus clear any previously set busy handler.
  2516. **
  2517. ** The busy callback should not take any actions which modify the
  2518. ** database connection that invoked the busy handler. In other words,
  2519. ** the busy handler is not reentrant. Any such actions
  2520. ** result in undefined behavior.
  2521. **
  2522. ** A busy handler must not close the database connection
  2523. ** or [prepared statement] that invoked the busy handler.
  2524. */
  2525. SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
  2526. /*
  2527. ** CAPI3REF: Set A Busy Timeout
  2528. ** METHOD: sqlite3
  2529. **
  2530. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2531. ** for a specified amount of time when a table is locked. ^The handler
  2532. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2533. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  2534. ** the handler returns 0 which causes [sqlite3_step()] to return
  2535. ** [SQLITE_BUSY].
  2536. **
  2537. ** ^Calling this routine with an argument less than or equal to zero
  2538. ** turns off all busy handlers.
  2539. **
  2540. ** ^(There can only be a single busy handler for a particular
  2541. ** [database connection] at any given moment. If another busy handler
  2542. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  2543. ** this routine, that other busy handler is cleared.)^
  2544. **
  2545. ** See also: [PRAGMA busy_timeout]
  2546. */
  2547. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  2548. /*
  2549. ** CAPI3REF: Convenience Routines For Running Queries
  2550. ** METHOD: sqlite3
  2551. **
  2552. ** This is a legacy interface that is preserved for backwards compatibility.
  2553. ** Use of this interface is not recommended.
  2554. **
  2555. ** Definition: A <b>result table</b> is memory data structure created by the
  2556. ** [sqlite3_get_table()] interface. A result table records the
  2557. ** complete query results from one or more queries.
  2558. **
  2559. ** The table conceptually has a number of rows and columns. But
  2560. ** these numbers are not part of the result table itself. These
  2561. ** numbers are obtained separately. Let N be the number of rows
  2562. ** and M be the number of columns.
  2563. **
  2564. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  2565. ** There are (N+1)*M elements in the array. The first M pointers point
  2566. ** to zero-terminated strings that contain the names of the columns.
  2567. ** The remaining entries all point to query results. NULL values result
  2568. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  2569. ** string representation as returned by [sqlite3_column_text()].
  2570. **
  2571. ** A result table might consist of one or more memory allocations.
  2572. ** It is not safe to pass a result table directly to [sqlite3_free()].
  2573. ** A result table should be deallocated using [sqlite3_free_table()].
  2574. **
  2575. ** ^(As an example of the result table format, suppose a query result
  2576. ** is as follows:
  2577. **
  2578. ** <blockquote><pre>
  2579. ** Name | Age
  2580. ** -----------------------
  2581. ** Alice | 43
  2582. ** Bob | 28
  2583. ** Cindy | 21
  2584. ** </pre></blockquote>
  2585. **
  2586. ** There are two column (M==2) and three rows (N==3). Thus the
  2587. ** result table has 8 entries. Suppose the result table is stored
  2588. ** in an array names azResult. Then azResult holds this content:
  2589. **
  2590. ** <blockquote><pre>
  2591. ** azResult&#91;0] = "Name";
  2592. ** azResult&#91;1] = "Age";
  2593. ** azResult&#91;2] = "Alice";
  2594. ** azResult&#91;3] = "43";
  2595. ** azResult&#91;4] = "Bob";
  2596. ** azResult&#91;5] = "28";
  2597. ** azResult&#91;6] = "Cindy";
  2598. ** azResult&#91;7] = "21";
  2599. ** </pre></blockquote>)^
  2600. **
  2601. ** ^The sqlite3_get_table() function evaluates one or more
  2602. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  2603. ** string of its 2nd parameter and returns a result table to the
  2604. ** pointer given in its 3rd parameter.
  2605. **
  2606. ** After the application has finished with the result from sqlite3_get_table(),
  2607. ** it must pass the result table pointer to sqlite3_free_table() in order to
  2608. ** release the memory that was malloced. Because of the way the
  2609. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  2610. ** function must not try to call [sqlite3_free()] directly. Only
  2611. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  2612. **
  2613. ** The sqlite3_get_table() interface is implemented as a wrapper around
  2614. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  2615. ** to any internal data structures of SQLite. It uses only the public
  2616. ** interface defined here. As a consequence, errors that occur in the
  2617. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  2618. ** reflected in subsequent calls to [sqlite3_errcode()] or
  2619. ** [sqlite3_errmsg()].
  2620. */
  2621. SQLITE_API int sqlite3_get_table(
  2622. sqlite3 *db, /* An open database */
  2623. const char *zSql, /* SQL to be evaluated */
  2624. char ***pazResult, /* Results of the query */
  2625. int *pnRow, /* Number of result rows written here */
  2626. int *pnColumn, /* Number of result columns written here */
  2627. char **pzErrmsg /* Error msg written here */
  2628. );
  2629. SQLITE_API void sqlite3_free_table(char **result);
  2630. /*
  2631. ** CAPI3REF: Formatted String Printing Functions
  2632. **
  2633. ** These routines are work-alikes of the "printf()" family of functions
  2634. ** from the standard C library.
  2635. ** These routines understand most of the common K&R formatting options,
  2636. ** plus some additional non-standard formats, detailed below.
  2637. ** Note that some of the more obscure formatting options from recent
  2638. ** C-library standards are omitted from this implementation.
  2639. **
  2640. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  2641. ** results into memory obtained from [sqlite3_malloc()].
  2642. ** The strings returned by these two routines should be
  2643. ** released by [sqlite3_free()]. ^Both routines return a
  2644. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  2645. ** memory to hold the resulting string.
  2646. **
  2647. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  2648. ** the standard C library. The result is written into the
  2649. ** buffer supplied as the second parameter whose size is given by
  2650. ** the first parameter. Note that the order of the
  2651. ** first two parameters is reversed from snprintf().)^ This is an
  2652. ** historical accident that cannot be fixed without breaking
  2653. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  2654. ** returns a pointer to its buffer instead of the number of
  2655. ** characters actually written into the buffer.)^ We admit that
  2656. ** the number of characters written would be a more useful return
  2657. ** value but we cannot change the implementation of sqlite3_snprintf()
  2658. ** now without breaking compatibility.
  2659. **
  2660. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  2661. ** guarantees that the buffer is always zero-terminated. ^The first
  2662. ** parameter "n" is the total size of the buffer, including space for
  2663. ** the zero terminator. So the longest string that can be completely
  2664. ** written will be n-1 characters.
  2665. **
  2666. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  2667. **
  2668. ** These routines all implement some additional formatting
  2669. ** options that are useful for constructing SQL statements.
  2670. ** All of the usual printf() formatting options apply. In addition, there
  2671. ** is are "%q", "%Q", "%w" and "%z" options.
  2672. **
  2673. ** ^(The %q option works like %s in that it substitutes a nul-terminated
  2674. ** string from the argument list. But %q also doubles every '\'' character.
  2675. ** %q is designed for use inside a string literal.)^ By doubling each '\''
  2676. ** character it escapes that character and allows it to be inserted into
  2677. ** the string.
  2678. **
  2679. ** For example, assume the string variable zText contains text as follows:
  2680. **
  2681. ** <blockquote><pre>
  2682. ** char *zText = "It's a happy day!";
  2683. ** </pre></blockquote>
  2684. **
  2685. ** One can use this text in an SQL statement as follows:
  2686. **
  2687. ** <blockquote><pre>
  2688. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2689. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2690. ** sqlite3_free(zSQL);
  2691. ** </pre></blockquote>
  2692. **
  2693. ** Because the %q format string is used, the '\'' character in zText
  2694. ** is escaped and the SQL generated is as follows:
  2695. **
  2696. ** <blockquote><pre>
  2697. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2698. ** </pre></blockquote>
  2699. **
  2700. ** This is correct. Had we used %s instead of %q, the generated SQL
  2701. ** would have looked like this:
  2702. **
  2703. ** <blockquote><pre>
  2704. ** INSERT INTO table1 VALUES('It's a happy day!');
  2705. ** </pre></blockquote>
  2706. **
  2707. ** This second example is an SQL syntax error. As a general rule you should
  2708. ** always use %q instead of %s when inserting text into a string literal.
  2709. **
  2710. ** ^(The %Q option works like %q except it also adds single quotes around
  2711. ** the outside of the total string. Additionally, if the parameter in the
  2712. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2713. ** single quotes).)^ So, for example, one could say:
  2714. **
  2715. ** <blockquote><pre>
  2716. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2717. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2718. ** sqlite3_free(zSQL);
  2719. ** </pre></blockquote>
  2720. **
  2721. ** The code above will render a correct SQL statement in the zSQL
  2722. ** variable even if the zText variable is a NULL pointer.
  2723. **
  2724. ** ^(The "%w" formatting option is like "%q" except that it expects to
  2725. ** be contained within double-quotes instead of single quotes, and it
  2726. ** escapes the double-quote character instead of the single-quote
  2727. ** character.)^ The "%w" formatting option is intended for safely inserting
  2728. ** table and column names into a constructed SQL statement.
  2729. **
  2730. ** ^(The "%z" formatting option works like "%s" but with the
  2731. ** addition that after the string has been read and copied into
  2732. ** the result, [sqlite3_free()] is called on the input string.)^
  2733. */
  2734. SQLITE_API char *sqlite3_mprintf(const char*,...);
  2735. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  2736. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  2737. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  2738. /*
  2739. ** CAPI3REF: Memory Allocation Subsystem
  2740. **
  2741. ** The SQLite core uses these three routines for all of its own
  2742. ** internal memory allocation needs. "Core" in the previous sentence
  2743. ** does not include operating-system specific VFS implementation. The
  2744. ** Windows VFS uses native malloc() and free() for some operations.
  2745. **
  2746. ** ^The sqlite3_malloc() routine returns a pointer to a block
  2747. ** of memory at least N bytes in length, where N is the parameter.
  2748. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  2749. ** memory, it returns a NULL pointer. ^If the parameter N to
  2750. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2751. ** a NULL pointer.
  2752. **
  2753. ** ^The sqlite3_malloc64(N) routine works just like
  2754. ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
  2755. ** of a signed 32-bit integer.
  2756. **
  2757. ** ^Calling sqlite3_free() with a pointer previously returned
  2758. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2759. ** that it might be reused. ^The sqlite3_free() routine is
  2760. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2761. ** to sqlite3_free() is harmless. After being freed, memory
  2762. ** should neither be read nor written. Even reading previously freed
  2763. ** memory might result in a segmentation fault or other severe error.
  2764. ** Memory corruption, a segmentation fault, or other severe error
  2765. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2766. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2767. **
  2768. ** ^The sqlite3_realloc(X,N) interface attempts to resize a
  2769. ** prior memory allocation X to be at least N bytes.
  2770. ** ^If the X parameter to sqlite3_realloc(X,N)
  2771. ** is a NULL pointer then its behavior is identical to calling
  2772. ** sqlite3_malloc(N).
  2773. ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
  2774. ** negative then the behavior is exactly the same as calling
  2775. ** sqlite3_free(X).
  2776. ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
  2777. ** of at least N bytes in size or NULL if insufficient memory is available.
  2778. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  2779. ** of the prior allocation are copied into the beginning of buffer returned
  2780. ** by sqlite3_realloc(X,N) and the prior allocation is freed.
  2781. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
  2782. ** prior allocation is not freed.
  2783. **
  2784. ** ^The sqlite3_realloc64(X,N) interfaces works the same as
  2785. ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
  2786. ** of a 32-bit signed integer.
  2787. **
  2788. ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
  2789. ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
  2790. ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
  2791. ** ^The value returned by sqlite3_msize(X) might be larger than the number
  2792. ** of bytes requested when X was allocated. ^If X is a NULL pointer then
  2793. ** sqlite3_msize(X) returns zero. If X points to something that is not
  2794. ** the beginning of memory allocation, or if it points to a formerly
  2795. ** valid memory allocation that has now been freed, then the behavior
  2796. ** of sqlite3_msize(X) is undefined and possibly harmful.
  2797. **
  2798. ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
  2799. ** sqlite3_malloc64(), and sqlite3_realloc64()
  2800. ** is always aligned to at least an 8 byte boundary, or to a
  2801. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  2802. ** option is used.
  2803. **
  2804. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2805. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2806. ** implementation of these routines to be omitted. That capability
  2807. ** is no longer provided. Only built-in memory allocators can be used.
  2808. **
  2809. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  2810. ** the system malloc() and free() directly when converting
  2811. ** filenames between the UTF-8 encoding used by SQLite
  2812. ** and whatever filename encoding is used by the particular Windows
  2813. ** installation. Memory allocation errors were detected, but
  2814. ** they were reported back as [SQLITE_CANTOPEN] or
  2815. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2816. **
  2817. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2818. ** must be either NULL or else pointers obtained from a prior
  2819. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2820. ** not yet been released.
  2821. **
  2822. ** The application must not read or write any part of
  2823. ** a block of memory after it has been released using
  2824. ** [sqlite3_free()] or [sqlite3_realloc()].
  2825. */
  2826. SQLITE_API void *sqlite3_malloc(int);
  2827. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
  2828. SQLITE_API void *sqlite3_realloc(void*, int);
  2829. SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
  2830. SQLITE_API void sqlite3_free(void*);
  2831. SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
  2832. /*
  2833. ** CAPI3REF: Memory Allocator Statistics
  2834. **
  2835. ** SQLite provides these two interfaces for reporting on the status
  2836. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2837. ** routines, which form the built-in memory allocation subsystem.
  2838. **
  2839. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  2840. ** of memory currently outstanding (malloced but not freed).
  2841. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  2842. ** value of [sqlite3_memory_used()] since the high-water mark
  2843. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  2844. ** [sqlite3_memory_highwater()] include any overhead
  2845. ** added by SQLite in its implementation of [sqlite3_malloc()],
  2846. ** but not overhead added by the any underlying system library
  2847. ** routines that [sqlite3_malloc()] may call.
  2848. **
  2849. ** ^The memory high-water mark is reset to the current value of
  2850. ** [sqlite3_memory_used()] if and only if the parameter to
  2851. ** [sqlite3_memory_highwater()] is true. ^The value returned
  2852. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  2853. ** prior to the reset.
  2854. */
  2855. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  2856. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  2857. /*
  2858. ** CAPI3REF: Pseudo-Random Number Generator
  2859. **
  2860. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2861. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2862. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2863. ** the build-in random() and randomblob() SQL functions. This interface allows
  2864. ** applications to access the same PRNG for other purposes.
  2865. **
  2866. ** ^A call to this routine stores N bytes of randomness into buffer P.
  2867. ** ^The P parameter can be a NULL pointer.
  2868. **
  2869. ** ^If this routine has not been previously called or if the previous
  2870. ** call had N less than one or a NULL pointer for P, then the PRNG is
  2871. ** seeded using randomness obtained from the xRandomness method of
  2872. ** the default [sqlite3_vfs] object.
  2873. ** ^If the previous call to this routine had an N of 1 or more and a
  2874. ** non-NULL P then the pseudo-randomness is generated
  2875. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2876. ** method.
  2877. */
  2878. SQLITE_API void sqlite3_randomness(int N, void *P);
  2879. /*
  2880. ** CAPI3REF: Compile-Time Authorization Callbacks
  2881. ** METHOD: sqlite3
  2882. ** KEYWORDS: {authorizer callback}
  2883. **
  2884. ** ^This routine registers an authorizer callback with a particular
  2885. ** [database connection], supplied in the first argument.
  2886. ** ^The authorizer callback is invoked as SQL statements are being compiled
  2887. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2888. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
  2889. ** points during the compilation process, as logic is being created
  2890. ** to perform various actions, the authorizer callback is invoked to
  2891. ** see if those actions are allowed. ^The authorizer callback should
  2892. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2893. ** specific action but allow the SQL statement to continue to be
  2894. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2895. ** rejected with an error. ^If the authorizer callback returns
  2896. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2897. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2898. ** the authorizer will fail with an error message.
  2899. **
  2900. ** When the callback returns [SQLITE_OK], that means the operation
  2901. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  2902. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2903. ** authorizer will fail with an error message explaining that
  2904. ** access is denied.
  2905. **
  2906. ** ^The first parameter to the authorizer callback is a copy of the third
  2907. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  2908. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2909. ** the particular action to be authorized. ^The third through sixth parameters
  2910. ** to the callback are either NULL pointers or zero-terminated strings
  2911. ** that contain additional details about the action to be authorized.
  2912. ** Applications must always be prepared to encounter a NULL pointer in any
  2913. ** of the third through the sixth parameters of the authorization callback.
  2914. **
  2915. ** ^If the action code is [SQLITE_READ]
  2916. ** and the callback returns [SQLITE_IGNORE] then the
  2917. ** [prepared statement] statement is constructed to substitute
  2918. ** a NULL value in place of the table column that would have
  2919. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2920. ** return can be used to deny an untrusted user access to individual
  2921. ** columns of a table.
  2922. ** ^When a table is referenced by a [SELECT] but no column values are
  2923. ** extracted from that table (for example in a query like
  2924. ** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
  2925. ** is invoked once for that table with a column name that is an empty string.
  2926. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  2927. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  2928. ** [truncate optimization] is disabled and all rows are deleted individually.
  2929. **
  2930. ** An authorizer is used when [sqlite3_prepare | preparing]
  2931. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2932. ** do not try to access data they are not allowed to see, or that they do not
  2933. ** try to execute malicious statements that damage the database. For
  2934. ** example, an application may allow a user to enter arbitrary
  2935. ** SQL queries for evaluation by a database. But the application does
  2936. ** not want the user to be able to make arbitrary changes to the
  2937. ** database. An authorizer could then be put in place while the
  2938. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2939. ** disallows everything except [SELECT] statements.
  2940. **
  2941. ** Applications that need to process SQL from untrusted sources
  2942. ** might also consider lowering resource limits using [sqlite3_limit()]
  2943. ** and limiting database size using the [max_page_count] [PRAGMA]
  2944. ** in addition to using an authorizer.
  2945. **
  2946. ** ^(Only a single authorizer can be in place on a database connection
  2947. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2948. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  2949. ** The authorizer is disabled by default.
  2950. **
  2951. ** The authorizer callback must not do anything that will modify
  2952. ** the database connection that invoked the authorizer callback.
  2953. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2954. ** database connections for the meaning of "modify" in this paragraph.
  2955. **
  2956. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2957. ** statement might be re-prepared during [sqlite3_step()] due to a
  2958. ** schema change. Hence, the application should ensure that the
  2959. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2960. **
  2961. ** ^Note that the authorizer callback is invoked only during
  2962. ** [sqlite3_prepare()] or its variants. Authorization is not
  2963. ** performed during statement evaluation in [sqlite3_step()], unless
  2964. ** as stated in the previous paragraph, sqlite3_step() invokes
  2965. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  2966. */
  2967. SQLITE_API int sqlite3_set_authorizer(
  2968. sqlite3*,
  2969. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2970. void *pUserData
  2971. );
  2972. /*
  2973. ** CAPI3REF: Authorizer Return Codes
  2974. **
  2975. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2976. ** return either [SQLITE_OK] or one of these two constants in order
  2977. ** to signal SQLite whether or not the action is permitted. See the
  2978. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2979. ** information.
  2980. **
  2981. ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
  2982. ** returned from the [sqlite3_vtab_on_conflict()] interface.
  2983. */
  2984. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2985. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2986. /*
  2987. ** CAPI3REF: Authorizer Action Codes
  2988. **
  2989. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2990. ** that is invoked to authorize certain SQL statement actions. The
  2991. ** second parameter to the callback is an integer code that specifies
  2992. ** what action is being authorized. These are the integer action codes that
  2993. ** the authorizer callback may be passed.
  2994. **
  2995. ** These action code values signify what kind of operation is to be
  2996. ** authorized. The 3rd and 4th parameters to the authorization
  2997. ** callback function will be parameters or NULL depending on which of these
  2998. ** codes is used as the second parameter. ^(The 5th parameter to the
  2999. ** authorizer callback is the name of the database ("main", "temp",
  3000. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  3001. ** is the name of the inner-most trigger or view that is responsible for
  3002. ** the access attempt or NULL if this access attempt is directly from
  3003. ** top-level SQL code.
  3004. */
  3005. /******************************************* 3rd ************ 4th ***********/
  3006. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  3007. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  3008. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  3009. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  3010. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  3011. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  3012. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  3013. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  3014. #define SQLITE_DELETE 9 /* Table Name NULL */
  3015. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  3016. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  3017. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  3018. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  3019. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  3020. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  3021. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  3022. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  3023. #define SQLITE_INSERT 18 /* Table Name NULL */
  3024. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  3025. #define SQLITE_READ 20 /* Table Name Column Name */
  3026. #define SQLITE_SELECT 21 /* NULL NULL */
  3027. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  3028. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  3029. #define SQLITE_ATTACH 24 /* Filename NULL */
  3030. #define SQLITE_DETACH 25 /* Database Name NULL */
  3031. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  3032. #define SQLITE_REINDEX 27 /* Index Name NULL */
  3033. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  3034. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  3035. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  3036. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  3037. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  3038. #define SQLITE_COPY 0 /* No longer used */
  3039. #define SQLITE_RECURSIVE 33 /* NULL NULL */
  3040. /*
  3041. ** CAPI3REF: Tracing And Profiling Functions
  3042. ** METHOD: sqlite3
  3043. **
  3044. ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
  3045. ** instead of the routines described here.
  3046. **
  3047. ** These routines register callback functions that can be used for
  3048. ** tracing and profiling the execution of SQL statements.
  3049. **
  3050. ** ^The callback function registered by sqlite3_trace() is invoked at
  3051. ** various times when an SQL statement is being run by [sqlite3_step()].
  3052. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  3053. ** SQL statement text as the statement first begins executing.
  3054. ** ^(Additional sqlite3_trace() callbacks might occur
  3055. ** as each triggered subprogram is entered. The callbacks for triggers
  3056. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  3057. **
  3058. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  3059. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  3060. **
  3061. ** ^The callback function registered by sqlite3_profile() is invoked
  3062. ** as each SQL statement finishes. ^The profile callback contains
  3063. ** the original statement text and an estimate of wall-clock time
  3064. ** of how long that statement took to run. ^The profile callback
  3065. ** time is in units of nanoseconds, however the current implementation
  3066. ** is only capable of millisecond resolution so the six least significant
  3067. ** digits in the time are meaningless. Future versions of SQLite
  3068. ** might provide greater resolution on the profiler callback. The
  3069. ** sqlite3_profile() function is considered experimental and is
  3070. ** subject to change in future versions of SQLite.
  3071. */
  3072. SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
  3073. void(*xTrace)(void*,const char*), void*);
  3074. SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
  3075. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  3076. /*
  3077. ** CAPI3REF: SQL Trace Event Codes
  3078. ** KEYWORDS: SQLITE_TRACE
  3079. **
  3080. ** These constants identify classes of events that can be monitored
  3081. ** using the [sqlite3_trace_v2()] tracing logic. The third argument
  3082. ** to [sqlite3_trace_v2()] is an OR-ed combination of one or more of
  3083. ** the following constants. ^The first argument to the trace callback
  3084. ** is one of the following constants.
  3085. **
  3086. ** New tracing constants may be added in future releases.
  3087. **
  3088. ** ^A trace callback has four arguments: xCallback(T,C,P,X).
  3089. ** ^The T argument is one of the integer type codes above.
  3090. ** ^The C argument is a copy of the context pointer passed in as the
  3091. ** fourth argument to [sqlite3_trace_v2()].
  3092. ** The P and X arguments are pointers whose meanings depend on T.
  3093. **
  3094. ** <dl>
  3095. ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
  3096. ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
  3097. ** first begins running and possibly at other times during the
  3098. ** execution of the prepared statement, such as at the start of each
  3099. ** trigger subprogram. ^The P argument is a pointer to the
  3100. ** [prepared statement]. ^The X argument is a pointer to a string which
  3101. ** is the unexpanded SQL text of the prepared statement or an SQL comment
  3102. ** that indicates the invocation of a trigger. ^The callback can compute
  3103. ** the same text that would have been returned by the legacy [sqlite3_trace()]
  3104. ** interface by using the X argument when X begins with "--" and invoking
  3105. ** [sqlite3_expanded_sql(P)] otherwise.
  3106. **
  3107. ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
  3108. ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
  3109. ** information as is provided by the [sqlite3_profile()] callback.
  3110. ** ^The P argument is a pointer to the [prepared statement] and the
  3111. ** X argument points to a 64-bit integer which is the estimated of
  3112. ** the number of nanosecond that the prepared statement took to run.
  3113. ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
  3114. **
  3115. ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
  3116. ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
  3117. ** statement generates a single row of result.
  3118. ** ^The P argument is a pointer to the [prepared statement] and the
  3119. ** X argument is unused.
  3120. **
  3121. ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
  3122. ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
  3123. ** connection closes.
  3124. ** ^The P argument is a pointer to the [database connection] object
  3125. ** and the X argument is unused.
  3126. ** </dl>
  3127. */
  3128. #define SQLITE_TRACE_STMT 0x01
  3129. #define SQLITE_TRACE_PROFILE 0x02
  3130. #define SQLITE_TRACE_ROW 0x04
  3131. #define SQLITE_TRACE_CLOSE 0x08
  3132. /*
  3133. ** CAPI3REF: SQL Trace Hook
  3134. ** METHOD: sqlite3
  3135. **
  3136. ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
  3137. ** function X against [database connection] D, using property mask M
  3138. ** and context pointer P. ^If the X callback is
  3139. ** NULL or if the M mask is zero, then tracing is disabled. The
  3140. ** M argument should be the bitwise OR-ed combination of
  3141. ** zero or more [SQLITE_TRACE] constants.
  3142. **
  3143. ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
  3144. ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
  3145. **
  3146. ** ^The X callback is invoked whenever any of the events identified by
  3147. ** mask M occur. ^The integer return value from the callback is currently
  3148. ** ignored, though this may change in future releases. Callback
  3149. ** implementations should return zero to ensure future compatibility.
  3150. **
  3151. ** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
  3152. ** ^The T argument is one of the [SQLITE_TRACE]
  3153. ** constants to indicate why the callback was invoked.
  3154. ** ^The C argument is a copy of the context pointer.
  3155. ** The P and X arguments are pointers whose meanings depend on T.
  3156. **
  3157. ** The sqlite3_trace_v2() interface is intended to replace the legacy
  3158. ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
  3159. ** are deprecated.
  3160. */
  3161. SQLITE_API int sqlite3_trace_v2(
  3162. sqlite3*,
  3163. unsigned uMask,
  3164. int(*xCallback)(unsigned,void*,void*,void*),
  3165. void *pCtx
  3166. );
  3167. /*
  3168. ** CAPI3REF: Query Progress Callbacks
  3169. ** METHOD: sqlite3
  3170. **
  3171. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  3172. ** function X to be invoked periodically during long running calls to
  3173. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  3174. ** database connection D. An example use for this
  3175. ** interface is to keep a GUI updated during a large query.
  3176. **
  3177. ** ^The parameter P is passed through as the only parameter to the
  3178. ** callback function X. ^The parameter N is the approximate number of
  3179. ** [virtual machine instructions] that are evaluated between successive
  3180. ** invocations of the callback X. ^If N is less than one then the progress
  3181. ** handler is disabled.
  3182. **
  3183. ** ^Only a single progress handler may be defined at one time per
  3184. ** [database connection]; setting a new progress handler cancels the
  3185. ** old one. ^Setting parameter X to NULL disables the progress handler.
  3186. ** ^The progress handler is also disabled by setting N to a value less
  3187. ** than 1.
  3188. **
  3189. ** ^If the progress callback returns non-zero, the operation is
  3190. ** interrupted. This feature can be used to implement a
  3191. ** "Cancel" button on a GUI progress dialog box.
  3192. **
  3193. ** The progress handler callback must not do anything that will modify
  3194. ** the database connection that invoked the progress handler.
  3195. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  3196. ** database connections for the meaning of "modify" in this paragraph.
  3197. **
  3198. */
  3199. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  3200. /*
  3201. ** CAPI3REF: Opening A New Database Connection
  3202. ** CONSTRUCTOR: sqlite3
  3203. **
  3204. ** ^These routines open an SQLite database file as specified by the
  3205. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  3206. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  3207. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  3208. ** returned in *ppDb, even if an error occurs. The only exception is that
  3209. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  3210. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  3211. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  3212. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  3213. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  3214. ** an English language description of the error following a failure of any
  3215. ** of the sqlite3_open() routines.
  3216. **
  3217. ** ^The default encoding will be UTF-8 for databases created using
  3218. ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
  3219. ** created using sqlite3_open16() will be UTF-16 in the native byte order.
  3220. **
  3221. ** Whether or not an error occurs when it is opened, resources
  3222. ** associated with the [database connection] handle should be released by
  3223. ** passing it to [sqlite3_close()] when it is no longer required.
  3224. **
  3225. ** The sqlite3_open_v2() interface works like sqlite3_open()
  3226. ** except that it accepts two additional parameters for additional control
  3227. ** over the new database connection. ^(The flags parameter to
  3228. ** sqlite3_open_v2() can take one of
  3229. ** the following three values, optionally combined with the
  3230. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  3231. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  3232. **
  3233. ** <dl>
  3234. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  3235. ** <dd>The database is opened in read-only mode. If the database does not
  3236. ** already exist, an error is returned.</dd>)^
  3237. **
  3238. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  3239. ** <dd>The database is opened for reading and writing if possible, or reading
  3240. ** only if the file is write protected by the operating system. In either
  3241. ** case the database must already exist, otherwise an error is returned.</dd>)^
  3242. **
  3243. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  3244. ** <dd>The database is opened for reading and writing, and is created if
  3245. ** it does not already exist. This is the behavior that is always used for
  3246. ** sqlite3_open() and sqlite3_open16().</dd>)^
  3247. ** </dl>
  3248. **
  3249. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  3250. ** combinations shown above optionally combined with other
  3251. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  3252. ** then the behavior is undefined.
  3253. **
  3254. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  3255. ** opens in the multi-thread [threading mode] as long as the single-thread
  3256. ** mode has not been set at compile-time or start-time. ^If the
  3257. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  3258. ** in the serialized [threading mode] unless single-thread was
  3259. ** previously selected at compile-time or start-time.
  3260. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  3261. ** eligible to use [shared cache mode], regardless of whether or not shared
  3262. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  3263. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  3264. ** participate in [shared cache mode] even if it is enabled.
  3265. **
  3266. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  3267. ** [sqlite3_vfs] object that defines the operating system interface that
  3268. ** the new database connection should use. ^If the fourth parameter is
  3269. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  3270. **
  3271. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  3272. ** is created for the connection. ^This in-memory database will vanish when
  3273. ** the database connection is closed. Future versions of SQLite might
  3274. ** make use of additional special filenames that begin with the ":" character.
  3275. ** It is recommended that when a database filename actually does begin with
  3276. ** a ":" character you should prefix the filename with a pathname such as
  3277. ** "./" to avoid ambiguity.
  3278. **
  3279. ** ^If the filename is an empty string, then a private, temporary
  3280. ** on-disk database will be created. ^This private database will be
  3281. ** automatically deleted as soon as the database connection is closed.
  3282. **
  3283. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  3284. **
  3285. ** ^If [URI filename] interpretation is enabled, and the filename argument
  3286. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  3287. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  3288. ** set in the fourth argument to sqlite3_open_v2(), or if it has
  3289. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  3290. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  3291. ** As of SQLite version 3.7.7, URI filename interpretation is turned off
  3292. ** by default, but future releases of SQLite might enable URI filename
  3293. ** interpretation by default. See "[URI filenames]" for additional
  3294. ** information.
  3295. **
  3296. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  3297. ** authority, then it must be either an empty string or the string
  3298. ** "localhost". ^If the authority is not an empty string or "localhost", an
  3299. ** error is returned to the caller. ^The fragment component of a URI, if
  3300. ** present, is ignored.
  3301. **
  3302. ** ^SQLite uses the path component of the URI as the name of the disk file
  3303. ** which contains the database. ^If the path begins with a '/' character,
  3304. ** then it is interpreted as an absolute path. ^If the path does not begin
  3305. ** with a '/' (meaning that the authority section is omitted from the URI)
  3306. ** then the path is interpreted as a relative path.
  3307. ** ^(On windows, the first component of an absolute path
  3308. ** is a drive specification (e.g. "C:").)^
  3309. **
  3310. ** [[core URI query parameters]]
  3311. ** The query component of a URI may contain parameters that are interpreted
  3312. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  3313. ** SQLite and its built-in [VFSes] interpret the
  3314. ** following query parameters:
  3315. **
  3316. ** <ul>
  3317. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  3318. ** a VFS object that provides the operating system interface that should
  3319. ** be used to access the database file on disk. ^If this option is set to
  3320. ** an empty string the default VFS object is used. ^Specifying an unknown
  3321. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  3322. ** present, then the VFS specified by the option takes precedence over
  3323. ** the value passed as the fourth parameter to sqlite3_open_v2().
  3324. **
  3325. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  3326. ** "rwc", or "memory". Attempting to set it to any other value is
  3327. ** an error)^.
  3328. ** ^If "ro" is specified, then the database is opened for read-only
  3329. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  3330. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  3331. ** "rw", then the database is opened for read-write (but not create)
  3332. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  3333. ** been set. ^Value "rwc" is equivalent to setting both
  3334. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  3335. ** set to "memory" then a pure [in-memory database] that never reads
  3336. ** or writes from disk is used. ^It is an error to specify a value for
  3337. ** the mode parameter that is less restrictive than that specified by
  3338. ** the flags passed in the third parameter to sqlite3_open_v2().
  3339. **
  3340. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  3341. ** "private". ^Setting it to "shared" is equivalent to setting the
  3342. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  3343. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  3344. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  3345. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  3346. ** a URI filename, its value overrides any behavior requested by setting
  3347. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  3348. **
  3349. ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
  3350. ** [powersafe overwrite] property does or does not apply to the
  3351. ** storage media on which the database file resides.
  3352. **
  3353. ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
  3354. ** which if set disables file locking in rollback journal modes. This
  3355. ** is useful for accessing a database on a filesystem that does not
  3356. ** support locking. Caution: Database corruption might result if two
  3357. ** or more processes write to the same database and any one of those
  3358. ** processes uses nolock=1.
  3359. **
  3360. ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
  3361. ** parameter that indicates that the database file is stored on
  3362. ** read-only media. ^When immutable is set, SQLite assumes that the
  3363. ** database file cannot be changed, even by a process with higher
  3364. ** privilege, and so the database is opened read-only and all locking
  3365. ** and change detection is disabled. Caution: Setting the immutable
  3366. ** property on a database file that does in fact change can result
  3367. ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
  3368. ** See also: [SQLITE_IOCAP_IMMUTABLE].
  3369. **
  3370. ** </ul>
  3371. **
  3372. ** ^Specifying an unknown parameter in the query component of a URI is not an
  3373. ** error. Future versions of SQLite might understand additional query
  3374. ** parameters. See "[query parameters with special meaning to SQLite]" for
  3375. ** additional information.
  3376. **
  3377. ** [[URI filename examples]] <h3>URI filename examples</h3>
  3378. **
  3379. ** <table border="1" align=center cellpadding=5>
  3380. ** <tr><th> URI filenames <th> Results
  3381. ** <tr><td> file:data.db <td>
  3382. ** Open the file "data.db" in the current directory.
  3383. ** <tr><td> file:/home/fred/data.db<br>
  3384. ** file:///home/fred/data.db <br>
  3385. ** file://localhost/home/fred/data.db <br> <td>
  3386. ** Open the database file "/home/fred/data.db".
  3387. ** <tr><td> file://darkstar/home/fred/data.db <td>
  3388. ** An error. "darkstar" is not a recognized authority.
  3389. ** <tr><td style="white-space:nowrap">
  3390. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  3391. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  3392. ** C:. Note that the %20 escaping in this example is not strictly
  3393. ** necessary - space characters can be used literally
  3394. ** in URI filenames.
  3395. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  3396. ** Open file "data.db" in the current directory for read-only access.
  3397. ** Regardless of whether or not shared-cache mode is enabled by
  3398. ** default, use a private cache.
  3399. ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
  3400. ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
  3401. ** that uses dot-files in place of posix advisory locking.
  3402. ** <tr><td> file:data.db?mode=readonly <td>
  3403. ** An error. "readonly" is not a valid option for the "mode" parameter.
  3404. ** </table>
  3405. **
  3406. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  3407. ** query components of a URI. A hexadecimal escape sequence consists of a
  3408. ** percent sign - "%" - followed by exactly two hexadecimal digits
  3409. ** specifying an octet value. ^Before the path or query components of a
  3410. ** URI filename are interpreted, they are encoded using UTF-8 and all
  3411. ** hexadecimal escape sequences replaced by a single byte containing the
  3412. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  3413. ** the results are undefined.
  3414. **
  3415. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  3416. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  3417. ** codepage is currently defined. Filenames containing international
  3418. ** characters must be converted to UTF-8 prior to passing them into
  3419. ** sqlite3_open() or sqlite3_open_v2().
  3420. **
  3421. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  3422. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  3423. ** features that require the use of temporary files may fail.
  3424. **
  3425. ** See also: [sqlite3_temp_directory]
  3426. */
  3427. SQLITE_API int sqlite3_open(
  3428. const char *filename, /* Database filename (UTF-8) */
  3429. sqlite3 **ppDb /* OUT: SQLite db handle */
  3430. );
  3431. SQLITE_API int sqlite3_open16(
  3432. const void *filename, /* Database filename (UTF-16) */
  3433. sqlite3 **ppDb /* OUT: SQLite db handle */
  3434. );
  3435. SQLITE_API int sqlite3_open_v2(
  3436. const char *filename, /* Database filename (UTF-8) */
  3437. sqlite3 **ppDb, /* OUT: SQLite db handle */
  3438. int flags, /* Flags */
  3439. const char *zVfs /* Name of VFS module to use */
  3440. );
  3441. /*
  3442. ** CAPI3REF: Obtain Values For URI Parameters
  3443. **
  3444. ** These are utility routines, useful to VFS implementations, that check
  3445. ** to see if a database file was a URI that contained a specific query
  3446. ** parameter, and if so obtains the value of that query parameter.
  3447. **
  3448. ** If F is the database filename pointer passed into the xOpen() method of
  3449. ** a VFS implementation when the flags parameter to xOpen() has one or
  3450. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  3451. ** P is the name of the query parameter, then
  3452. ** sqlite3_uri_parameter(F,P) returns the value of the P
  3453. ** parameter if it exists or a NULL pointer if P does not appear as a
  3454. ** query parameter on F. If P is a query parameter of F
  3455. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  3456. ** a pointer to an empty string.
  3457. **
  3458. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  3459. ** parameter and returns true (1) or false (0) according to the value
  3460. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  3461. ** value of query parameter P is one of "yes", "true", or "on" in any
  3462. ** case or if the value begins with a non-zero number. The
  3463. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  3464. ** query parameter P is one of "no", "false", or "off" in any case or
  3465. ** if the value begins with a numeric zero. If P is not a query
  3466. ** parameter on F or if the value of P is does not match any of the
  3467. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  3468. **
  3469. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  3470. ** 64-bit signed integer and returns that integer, or D if P does not
  3471. ** exist. If the value of P is something other than an integer, then
  3472. ** zero is returned.
  3473. **
  3474. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  3475. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  3476. ** is not a database file pathname pointer that SQLite passed into the xOpen
  3477. ** VFS method, then the behavior of this routine is undefined and probably
  3478. ** undesirable.
  3479. */
  3480. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  3481. SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  3482. SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  3483. /*
  3484. ** CAPI3REF: Error Codes And Messages
  3485. ** METHOD: sqlite3
  3486. **
  3487. ** ^If the most recent sqlite3_* API call associated with
  3488. ** [database connection] D failed, then the sqlite3_errcode(D) interface
  3489. ** returns the numeric [result code] or [extended result code] for that
  3490. ** API call.
  3491. ** If the most recent API call was successful,
  3492. ** then the return value from sqlite3_errcode() is undefined.
  3493. ** ^The sqlite3_extended_errcode()
  3494. ** interface is the same except that it always returns the
  3495. ** [extended result code] even when extended result codes are
  3496. ** disabled.
  3497. **
  3498. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  3499. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  3500. ** ^(Memory to hold the error message string is managed internally.
  3501. ** The application does not need to worry about freeing the result.
  3502. ** However, the error string might be overwritten or deallocated by
  3503. ** subsequent calls to other SQLite interface functions.)^
  3504. **
  3505. ** ^The sqlite3_errstr() interface returns the English-language text
  3506. ** that describes the [result code], as UTF-8.
  3507. ** ^(Memory to hold the error message string is managed internally
  3508. ** and must not be freed by the application)^.
  3509. **
  3510. ** When the serialized [threading mode] is in use, it might be the
  3511. ** case that a second error occurs on a separate thread in between
  3512. ** the time of the first error and the call to these interfaces.
  3513. ** When that happens, the second error will be reported since these
  3514. ** interfaces always report the most recent result. To avoid
  3515. ** this, each thread can obtain exclusive use of the [database connection] D
  3516. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  3517. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  3518. ** all calls to the interfaces listed here are completed.
  3519. **
  3520. ** If an interface fails with SQLITE_MISUSE, that means the interface
  3521. ** was invoked incorrectly by the application. In that case, the
  3522. ** error code and message may or may not be set.
  3523. */
  3524. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  3525. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  3526. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  3527. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  3528. SQLITE_API const char *sqlite3_errstr(int);
  3529. /*
  3530. ** CAPI3REF: Prepared Statement Object
  3531. ** KEYWORDS: {prepared statement} {prepared statements}
  3532. **
  3533. ** An instance of this object represents a single SQL statement that
  3534. ** has been compiled into binary form and is ready to be evaluated.
  3535. **
  3536. ** Think of each SQL statement as a separate computer program. The
  3537. ** original SQL text is source code. A prepared statement object
  3538. ** is the compiled object code. All SQL must be converted into a
  3539. ** prepared statement before it can be run.
  3540. **
  3541. ** The life-cycle of a prepared statement object usually goes like this:
  3542. **
  3543. ** <ol>
  3544. ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
  3545. ** <li> Bind values to [parameters] using the sqlite3_bind_*()
  3546. ** interfaces.
  3547. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  3548. ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
  3549. ** to step 2. Do this zero or more times.
  3550. ** <li> Destroy the object using [sqlite3_finalize()].
  3551. ** </ol>
  3552. */
  3553. typedef struct sqlite3_stmt sqlite3_stmt;
  3554. /*
  3555. ** CAPI3REF: Run-time Limits
  3556. ** METHOD: sqlite3
  3557. **
  3558. ** ^(This interface allows the size of various constructs to be limited
  3559. ** on a connection by connection basis. The first parameter is the
  3560. ** [database connection] whose limit is to be set or queried. The
  3561. ** second parameter is one of the [limit categories] that define a
  3562. ** class of constructs to be size limited. The third parameter is the
  3563. ** new limit for that construct.)^
  3564. **
  3565. ** ^If the new limit is a negative number, the limit is unchanged.
  3566. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  3567. ** [limits | hard upper bound]
  3568. ** set at compile-time by a C preprocessor macro called
  3569. ** [limits | SQLITE_MAX_<i>NAME</i>].
  3570. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  3571. ** ^Attempts to increase a limit above its hard upper bound are
  3572. ** silently truncated to the hard upper bound.
  3573. **
  3574. ** ^Regardless of whether or not the limit was changed, the
  3575. ** [sqlite3_limit()] interface returns the prior value of the limit.
  3576. ** ^Hence, to find the current value of a limit without changing it,
  3577. ** simply invoke this interface with the third parameter set to -1.
  3578. **
  3579. ** Run-time limits are intended for use in applications that manage
  3580. ** both their own internal database and also databases that are controlled
  3581. ** by untrusted external sources. An example application might be a
  3582. ** web browser that has its own databases for storing history and
  3583. ** separate databases controlled by JavaScript applications downloaded
  3584. ** off the Internet. The internal databases can be given the
  3585. ** large, default limits. Databases managed by external sources can
  3586. ** be given much smaller limits designed to prevent a denial of service
  3587. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  3588. ** interface to further control untrusted SQL. The size of the database
  3589. ** created by an untrusted script can be contained using the
  3590. ** [max_page_count] [PRAGMA].
  3591. **
  3592. ** New run-time limit categories may be added in future releases.
  3593. */
  3594. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  3595. /*
  3596. ** CAPI3REF: Run-Time Limit Categories
  3597. ** KEYWORDS: {limit category} {*limit categories}
  3598. **
  3599. ** These constants define various performance limits
  3600. ** that can be lowered at run-time using [sqlite3_limit()].
  3601. ** The synopsis of the meanings of the various limits is shown below.
  3602. ** Additional information is available at [limits | Limits in SQLite].
  3603. **
  3604. ** <dl>
  3605. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  3606. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  3607. **
  3608. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  3609. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  3610. **
  3611. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  3612. ** <dd>The maximum number of columns in a table definition or in the
  3613. ** result set of a [SELECT] or the maximum number of columns in an index
  3614. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  3615. **
  3616. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  3617. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  3618. **
  3619. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  3620. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  3621. **
  3622. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  3623. ** <dd>The maximum number of instructions in a virtual machine program
  3624. ** used to implement an SQL statement. If [sqlite3_prepare_v2()] or
  3625. ** the equivalent tries to allocate space for more than this many opcodes
  3626. ** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
  3627. **
  3628. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  3629. ** <dd>The maximum number of arguments on a function.</dd>)^
  3630. **
  3631. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  3632. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  3633. **
  3634. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  3635. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  3636. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  3637. ** [GLOB] operators.</dd>)^
  3638. **
  3639. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  3640. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  3641. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  3642. **
  3643. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  3644. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  3645. **
  3646. ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
  3647. ** <dd>The maximum number of auxiliary worker threads that a single
  3648. ** [prepared statement] may start.</dd>)^
  3649. ** </dl>
  3650. */
  3651. #define SQLITE_LIMIT_LENGTH 0
  3652. #define SQLITE_LIMIT_SQL_LENGTH 1
  3653. #define SQLITE_LIMIT_COLUMN 2
  3654. #define SQLITE_LIMIT_EXPR_DEPTH 3
  3655. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  3656. #define SQLITE_LIMIT_VDBE_OP 5
  3657. #define SQLITE_LIMIT_FUNCTION_ARG 6
  3658. #define SQLITE_LIMIT_ATTACHED 7
  3659. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  3660. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  3661. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  3662. #define SQLITE_LIMIT_WORKER_THREADS 11
  3663. /*
  3664. ** CAPI3REF: Compiling An SQL Statement
  3665. ** KEYWORDS: {SQL statement compiler}
  3666. ** METHOD: sqlite3
  3667. ** CONSTRUCTOR: sqlite3_stmt
  3668. **
  3669. ** To execute an SQL query, it must first be compiled into a byte-code
  3670. ** program using one of these routines.
  3671. **
  3672. ** The first argument, "db", is a [database connection] obtained from a
  3673. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  3674. ** [sqlite3_open16()]. The database connection must not have been closed.
  3675. **
  3676. ** The second argument, "zSql", is the statement to be compiled, encoded
  3677. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  3678. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  3679. ** use UTF-16.
  3680. **
  3681. ** ^If the nByte argument is negative, then zSql is read up to the
  3682. ** first zero terminator. ^If nByte is positive, then it is the
  3683. ** number of bytes read from zSql. ^If nByte is zero, then no prepared
  3684. ** statement is generated.
  3685. ** If the caller knows that the supplied string is nul-terminated, then
  3686. ** there is a small performance advantage to passing an nByte parameter that
  3687. ** is the number of bytes in the input string <i>including</i>
  3688. ** the nul-terminator.
  3689. **
  3690. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  3691. ** past the end of the first SQL statement in zSql. These routines only
  3692. ** compile the first statement in zSql, so *pzTail is left pointing to
  3693. ** what remains uncompiled.
  3694. **
  3695. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  3696. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  3697. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  3698. ** string or a comment) then *ppStmt is set to NULL.
  3699. ** The calling procedure is responsible for deleting the compiled
  3700. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  3701. ** ppStmt may not be NULL.
  3702. **
  3703. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  3704. ** otherwise an [error code] is returned.
  3705. **
  3706. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  3707. ** recommended for all new programs. The two older interfaces are retained
  3708. ** for backwards compatibility, but their use is discouraged.
  3709. ** ^In the "v2" interfaces, the prepared statement
  3710. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  3711. ** original SQL text. This causes the [sqlite3_step()] interface to
  3712. ** behave differently in three ways:
  3713. **
  3714. ** <ol>
  3715. ** <li>
  3716. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  3717. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  3718. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  3719. ** retries will occur before sqlite3_step() gives up and returns an error.
  3720. ** </li>
  3721. **
  3722. ** <li>
  3723. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  3724. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  3725. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  3726. ** and the application would have to make a second call to [sqlite3_reset()]
  3727. ** in order to find the underlying cause of the problem. With the "v2" prepare
  3728. ** interfaces, the underlying reason for the error is returned immediately.
  3729. ** </li>
  3730. **
  3731. ** <li>
  3732. ** ^If the specific value bound to [parameter | host parameter] in the
  3733. ** WHERE clause might influence the choice of query plan for a statement,
  3734. ** then the statement will be automatically recompiled, as if there had been
  3735. ** a schema change, on the first [sqlite3_step()] call following any change
  3736. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  3737. ** ^The specific value of WHERE-clause [parameter] might influence the
  3738. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  3739. ** or [GLOB] operator or if the parameter is compared to an indexed column
  3740. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  3741. ** </li>
  3742. ** </ol>
  3743. */
  3744. SQLITE_API int sqlite3_prepare(
  3745. sqlite3 *db, /* Database handle */
  3746. const char *zSql, /* SQL statement, UTF-8 encoded */
  3747. int nByte, /* Maximum length of zSql in bytes. */
  3748. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3749. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3750. );
  3751. SQLITE_API int sqlite3_prepare_v2(
  3752. sqlite3 *db, /* Database handle */
  3753. const char *zSql, /* SQL statement, UTF-8 encoded */
  3754. int nByte, /* Maximum length of zSql in bytes. */
  3755. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3756. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3757. );
  3758. SQLITE_API int sqlite3_prepare16(
  3759. sqlite3 *db, /* Database handle */
  3760. const void *zSql, /* SQL statement, UTF-16 encoded */
  3761. int nByte, /* Maximum length of zSql in bytes. */
  3762. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3763. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3764. );
  3765. SQLITE_API int sqlite3_prepare16_v2(
  3766. sqlite3 *db, /* Database handle */
  3767. const void *zSql, /* SQL statement, UTF-16 encoded */
  3768. int nByte, /* Maximum length of zSql in bytes. */
  3769. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3770. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3771. );
  3772. /*
  3773. ** CAPI3REF: Retrieving Statement SQL
  3774. ** METHOD: sqlite3_stmt
  3775. **
  3776. ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
  3777. ** SQL text used to create [prepared statement] P if P was
  3778. ** created by either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  3779. ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
  3780. ** string containing the SQL text of prepared statement P with
  3781. ** [bound parameters] expanded.
  3782. **
  3783. ** ^(For example, if a prepared statement is created using the SQL
  3784. ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
  3785. ** and parameter :xyz is unbound, then sqlite3_sql() will return
  3786. ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
  3787. ** will return "SELECT 2345,NULL".)^
  3788. **
  3789. ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
  3790. ** is available to hold the result, or if the result would exceed the
  3791. ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
  3792. **
  3793. ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
  3794. ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
  3795. ** option causes sqlite3_expanded_sql() to always return NULL.
  3796. **
  3797. ** ^The string returned by sqlite3_sql(P) is managed by SQLite and is
  3798. ** automatically freed when the prepared statement is finalized.
  3799. ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
  3800. ** is obtained from [sqlite3_malloc()] and must be free by the application
  3801. ** by passing it to [sqlite3_free()].
  3802. */
  3803. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  3804. SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
  3805. /*
  3806. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  3807. ** METHOD: sqlite3_stmt
  3808. **
  3809. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  3810. ** and only if the [prepared statement] X makes no direct changes to
  3811. ** the content of the database file.
  3812. **
  3813. ** Note that [application-defined SQL functions] or
  3814. ** [virtual tables] might change the database indirectly as a side effect.
  3815. ** ^(For example, if an application defines a function "eval()" that
  3816. ** calls [sqlite3_exec()], then the following SQL statement would
  3817. ** change the database file through side-effects:
  3818. **
  3819. ** <blockquote><pre>
  3820. ** SELECT eval('DELETE FROM t1') FROM t2;
  3821. ** </pre></blockquote>
  3822. **
  3823. ** But because the [SELECT] statement does not change the database file
  3824. ** directly, sqlite3_stmt_readonly() would still return true.)^
  3825. **
  3826. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  3827. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  3828. ** since the statements themselves do not actually modify the database but
  3829. ** rather they control the timing of when other statements modify the
  3830. ** database. ^The [ATTACH] and [DETACH] statements also cause
  3831. ** sqlite3_stmt_readonly() to return true since, while those statements
  3832. ** change the configuration of a database connection, they do not make
  3833. ** changes to the content of the database files on disk.
  3834. ** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
  3835. ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
  3836. ** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
  3837. ** sqlite3_stmt_readonly() returns false for those commands.
  3838. */
  3839. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  3840. /*
  3841. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  3842. ** METHOD: sqlite3_stmt
  3843. **
  3844. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  3845. ** [prepared statement] S has been stepped at least once using
  3846. ** [sqlite3_step(S)] but has neither run to completion (returned
  3847. ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
  3848. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  3849. ** interface returns false if S is a NULL pointer. If S is not a
  3850. ** NULL pointer and is not a pointer to a valid [prepared statement]
  3851. ** object, then the behavior is undefined and probably undesirable.
  3852. **
  3853. ** This interface can be used in combination [sqlite3_next_stmt()]
  3854. ** to locate all prepared statements associated with a database
  3855. ** connection that are in need of being reset. This can be used,
  3856. ** for example, in diagnostic routines to search for prepared
  3857. ** statements that are holding a transaction open.
  3858. */
  3859. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  3860. /*
  3861. ** CAPI3REF: Dynamically Typed Value Object
  3862. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  3863. **
  3864. ** SQLite uses the sqlite3_value object to represent all values
  3865. ** that can be stored in a database table. SQLite uses dynamic typing
  3866. ** for the values it stores. ^Values stored in sqlite3_value objects
  3867. ** can be integers, floating point values, strings, BLOBs, or NULL.
  3868. **
  3869. ** An sqlite3_value object may be either "protected" or "unprotected".
  3870. ** Some interfaces require a protected sqlite3_value. Other interfaces
  3871. ** will accept either a protected or an unprotected sqlite3_value.
  3872. ** Every interface that accepts sqlite3_value arguments specifies
  3873. ** whether or not it requires a protected sqlite3_value. The
  3874. ** [sqlite3_value_dup()] interface can be used to construct a new
  3875. ** protected sqlite3_value from an unprotected sqlite3_value.
  3876. **
  3877. ** The terms "protected" and "unprotected" refer to whether or not
  3878. ** a mutex is held. An internal mutex is held for a protected
  3879. ** sqlite3_value object but no mutex is held for an unprotected
  3880. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  3881. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  3882. ** or if SQLite is run in one of reduced mutex modes
  3883. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  3884. ** then there is no distinction between protected and unprotected
  3885. ** sqlite3_value objects and they can be used interchangeably. However,
  3886. ** for maximum code portability it is recommended that applications
  3887. ** still make the distinction between protected and unprotected
  3888. ** sqlite3_value objects even when not strictly required.
  3889. **
  3890. ** ^The sqlite3_value objects that are passed as parameters into the
  3891. ** implementation of [application-defined SQL functions] are protected.
  3892. ** ^The sqlite3_value object returned by
  3893. ** [sqlite3_column_value()] is unprotected.
  3894. ** Unprotected sqlite3_value objects may only be used with
  3895. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  3896. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  3897. ** interfaces require protected sqlite3_value objects.
  3898. */
  3899. typedef struct sqlite3_value sqlite3_value;
  3900. /*
  3901. ** CAPI3REF: SQL Function Context Object
  3902. **
  3903. ** The context in which an SQL function executes is stored in an
  3904. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  3905. ** is always first parameter to [application-defined SQL functions].
  3906. ** The application-defined SQL function implementation will pass this
  3907. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  3908. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  3909. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  3910. ** and/or [sqlite3_set_auxdata()].
  3911. */
  3912. typedef struct sqlite3_context sqlite3_context;
  3913. /*
  3914. ** CAPI3REF: Binding Values To Prepared Statements
  3915. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  3916. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  3917. ** METHOD: sqlite3_stmt
  3918. **
  3919. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  3920. ** literals may be replaced by a [parameter] that matches one of following
  3921. ** templates:
  3922. **
  3923. ** <ul>
  3924. ** <li> ?
  3925. ** <li> ?NNN
  3926. ** <li> :VVV
  3927. ** <li> @VVV
  3928. ** <li> $VVV
  3929. ** </ul>
  3930. **
  3931. ** In the templates above, NNN represents an integer literal,
  3932. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  3933. ** parameters (also called "host parameter names" or "SQL parameters")
  3934. ** can be set using the sqlite3_bind_*() routines defined here.
  3935. **
  3936. ** ^The first argument to the sqlite3_bind_*() routines is always
  3937. ** a pointer to the [sqlite3_stmt] object returned from
  3938. ** [sqlite3_prepare_v2()] or its variants.
  3939. **
  3940. ** ^The second argument is the index of the SQL parameter to be set.
  3941. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  3942. ** SQL parameter is used more than once, second and subsequent
  3943. ** occurrences have the same index as the first occurrence.
  3944. ** ^The index for named parameters can be looked up using the
  3945. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  3946. ** for "?NNN" parameters is the value of NNN.
  3947. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  3948. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  3949. **
  3950. ** ^The third argument is the value to bind to the parameter.
  3951. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3952. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  3953. ** is ignored and the end result is the same as sqlite3_bind_null().
  3954. **
  3955. ** ^(In those routines that have a fourth argument, its value is the
  3956. ** number of bytes in the parameter. To be clear: the value is the
  3957. ** number of <u>bytes</u> in the value, not the number of characters.)^
  3958. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3959. ** is negative, then the length of the string is
  3960. ** the number of bytes up to the first zero terminator.
  3961. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  3962. ** the behavior is undefined.
  3963. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  3964. ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
  3965. ** that parameter must be the byte offset
  3966. ** where the NUL terminator would occur assuming the string were NUL
  3967. ** terminated. If any NUL characters occur at byte offsets less than
  3968. ** the value of the fourth parameter then the resulting string value will
  3969. ** contain embedded NULs. The result of expressions involving strings
  3970. ** with embedded NULs is undefined.
  3971. **
  3972. ** ^The fifth argument to the BLOB and string binding interfaces
  3973. ** is a destructor used to dispose of the BLOB or
  3974. ** string after SQLite has finished with it. ^The destructor is called
  3975. ** to dispose of the BLOB or string even if the call to bind API fails.
  3976. ** ^If the fifth argument is
  3977. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  3978. ** information is in static, unmanaged space and does not need to be freed.
  3979. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  3980. ** SQLite makes its own private copy of the data immediately, before
  3981. ** the sqlite3_bind_*() routine returns.
  3982. **
  3983. ** ^The sixth argument to sqlite3_bind_text64() must be one of
  3984. ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
  3985. ** to specify the encoding of the text in the third parameter. If
  3986. ** the sixth argument to sqlite3_bind_text64() is not one of the
  3987. ** allowed values shown above, or if the text encoding is different
  3988. ** from the encoding specified by the sixth parameter, then the behavior
  3989. ** is undefined.
  3990. **
  3991. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  3992. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  3993. ** (just an integer to hold its size) while it is being processed.
  3994. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  3995. ** content is later written using
  3996. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  3997. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  3998. **
  3999. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  4000. ** for the [prepared statement] or with a prepared statement for which
  4001. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  4002. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  4003. ** routine is passed a [prepared statement] that has been finalized, the
  4004. ** result is undefined and probably harmful.
  4005. **
  4006. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  4007. ** ^Unbound parameters are interpreted as NULL.
  4008. **
  4009. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  4010. ** [error code] if anything goes wrong.
  4011. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
  4012. ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
  4013. ** [SQLITE_MAX_LENGTH].
  4014. ** ^[SQLITE_RANGE] is returned if the parameter
  4015. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  4016. **
  4017. ** See also: [sqlite3_bind_parameter_count()],
  4018. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  4019. */
  4020. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  4021. SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
  4022. void(*)(void*));
  4023. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  4024. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  4025. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  4026. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  4027. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
  4028. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  4029. SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
  4030. void(*)(void*), unsigned char encoding);
  4031. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  4032. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  4033. SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
  4034. /*
  4035. ** CAPI3REF: Number Of SQL Parameters
  4036. ** METHOD: sqlite3_stmt
  4037. **
  4038. ** ^This routine can be used to find the number of [SQL parameters]
  4039. ** in a [prepared statement]. SQL parameters are tokens of the
  4040. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  4041. ** placeholders for values that are [sqlite3_bind_blob | bound]
  4042. ** to the parameters at a later time.
  4043. **
  4044. ** ^(This routine actually returns the index of the largest (rightmost)
  4045. ** parameter. For all forms except ?NNN, this will correspond to the
  4046. ** number of unique parameters. If parameters of the ?NNN form are used,
  4047. ** there may be gaps in the list.)^
  4048. **
  4049. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  4050. ** [sqlite3_bind_parameter_name()], and
  4051. ** [sqlite3_bind_parameter_index()].
  4052. */
  4053. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  4054. /*
  4055. ** CAPI3REF: Name Of A Host Parameter
  4056. ** METHOD: sqlite3_stmt
  4057. **
  4058. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  4059. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  4060. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  4061. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  4062. ** respectively.
  4063. ** In other words, the initial ":" or "$" or "@" or "?"
  4064. ** is included as part of the name.)^
  4065. ** ^Parameters of the form "?" without a following integer have no name
  4066. ** and are referred to as "nameless" or "anonymous parameters".
  4067. **
  4068. ** ^The first host parameter has an index of 1, not 0.
  4069. **
  4070. ** ^If the value N is out of range or if the N-th parameter is
  4071. ** nameless, then NULL is returned. ^The returned string is
  4072. ** always in UTF-8 encoding even if the named parameter was
  4073. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  4074. ** [sqlite3_prepare16_v2()].
  4075. **
  4076. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  4077. ** [sqlite3_bind_parameter_count()], and
  4078. ** [sqlite3_bind_parameter_index()].
  4079. */
  4080. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  4081. /*
  4082. ** CAPI3REF: Index Of A Parameter With A Given Name
  4083. ** METHOD: sqlite3_stmt
  4084. **
  4085. ** ^Return the index of an SQL parameter given its name. ^The
  4086. ** index value returned is suitable for use as the second
  4087. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  4088. ** is returned if no matching parameter is found. ^The parameter
  4089. ** name must be given in UTF-8 even if the original statement
  4090. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  4091. **
  4092. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  4093. ** [sqlite3_bind_parameter_count()], and
  4094. ** [sqlite3_bind_parameter_name()].
  4095. */
  4096. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  4097. /*
  4098. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  4099. ** METHOD: sqlite3_stmt
  4100. **
  4101. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  4102. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  4103. ** ^Use this routine to reset all host parameters to NULL.
  4104. */
  4105. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  4106. /*
  4107. ** CAPI3REF: Number Of Columns In A Result Set
  4108. ** METHOD: sqlite3_stmt
  4109. **
  4110. ** ^Return the number of columns in the result set returned by the
  4111. ** [prepared statement]. ^If this routine returns 0, that means the
  4112. ** [prepared statement] returns no data (for example an [UPDATE]).
  4113. ** ^However, just because this routine returns a positive number does not
  4114. ** mean that one or more rows of data will be returned. ^A SELECT statement
  4115. ** will always have a positive sqlite3_column_count() but depending on the
  4116. ** WHERE clause constraints and the table content, it might return no rows.
  4117. **
  4118. ** See also: [sqlite3_data_count()]
  4119. */
  4120. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  4121. /*
  4122. ** CAPI3REF: Column Names In A Result Set
  4123. ** METHOD: sqlite3_stmt
  4124. **
  4125. ** ^These routines return the name assigned to a particular column
  4126. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  4127. ** interface returns a pointer to a zero-terminated UTF-8 string
  4128. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  4129. ** UTF-16 string. ^The first parameter is the [prepared statement]
  4130. ** that implements the [SELECT] statement. ^The second parameter is the
  4131. ** column number. ^The leftmost column is number 0.
  4132. **
  4133. ** ^The returned string pointer is valid until either the [prepared statement]
  4134. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  4135. ** reprepared by the first call to [sqlite3_step()] for a particular run
  4136. ** or until the next call to
  4137. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  4138. **
  4139. ** ^If sqlite3_malloc() fails during the processing of either routine
  4140. ** (for example during a conversion from UTF-8 to UTF-16) then a
  4141. ** NULL pointer is returned.
  4142. **
  4143. ** ^The name of a result column is the value of the "AS" clause for
  4144. ** that column, if there is an AS clause. If there is no AS clause
  4145. ** then the name of the column is unspecified and may change from
  4146. ** one release of SQLite to the next.
  4147. */
  4148. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  4149. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  4150. /*
  4151. ** CAPI3REF: Source Of Data In A Query Result
  4152. ** METHOD: sqlite3_stmt
  4153. **
  4154. ** ^These routines provide a means to determine the database, table, and
  4155. ** table column that is the origin of a particular result column in
  4156. ** [SELECT] statement.
  4157. ** ^The name of the database or table or column can be returned as
  4158. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  4159. ** the database name, the _table_ routines return the table name, and
  4160. ** the origin_ routines return the column name.
  4161. ** ^The returned string is valid until the [prepared statement] is destroyed
  4162. ** using [sqlite3_finalize()] or until the statement is automatically
  4163. ** reprepared by the first call to [sqlite3_step()] for a particular run
  4164. ** or until the same information is requested
  4165. ** again in a different encoding.
  4166. **
  4167. ** ^The names returned are the original un-aliased names of the
  4168. ** database, table, and column.
  4169. **
  4170. ** ^The first argument to these interfaces is a [prepared statement].
  4171. ** ^These functions return information about the Nth result column returned by
  4172. ** the statement, where N is the second function argument.
  4173. ** ^The left-most column is column 0 for these routines.
  4174. **
  4175. ** ^If the Nth column returned by the statement is an expression or
  4176. ** subquery and is not a column value, then all of these functions return
  4177. ** NULL. ^These routine might also return NULL if a memory allocation error
  4178. ** occurs. ^Otherwise, they return the name of the attached database, table,
  4179. ** or column that query result column was extracted from.
  4180. **
  4181. ** ^As with all other SQLite APIs, those whose names end with "16" return
  4182. ** UTF-16 encoded strings and the other functions return UTF-8.
  4183. **
  4184. ** ^These APIs are only available if the library was compiled with the
  4185. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  4186. **
  4187. ** If two or more threads call one or more of these routines against the same
  4188. ** prepared statement and column at the same time then the results are
  4189. ** undefined.
  4190. **
  4191. ** If two or more threads call one or more
  4192. ** [sqlite3_column_database_name | column metadata interfaces]
  4193. ** for the same [prepared statement] and result column
  4194. ** at the same time then the results are undefined.
  4195. */
  4196. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  4197. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  4198. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  4199. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  4200. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  4201. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  4202. /*
  4203. ** CAPI3REF: Declared Datatype Of A Query Result
  4204. ** METHOD: sqlite3_stmt
  4205. **
  4206. ** ^(The first parameter is a [prepared statement].
  4207. ** If this statement is a [SELECT] statement and the Nth column of the
  4208. ** returned result set of that [SELECT] is a table column (not an
  4209. ** expression or subquery) then the declared type of the table
  4210. ** column is returned.)^ ^If the Nth column of the result set is an
  4211. ** expression or subquery, then a NULL pointer is returned.
  4212. ** ^The returned string is always UTF-8 encoded.
  4213. **
  4214. ** ^(For example, given the database schema:
  4215. **
  4216. ** CREATE TABLE t1(c1 VARIANT);
  4217. **
  4218. ** and the following statement to be compiled:
  4219. **
  4220. ** SELECT c1 + 1, c1 FROM t1;
  4221. **
  4222. ** this routine would return the string "VARIANT" for the second result
  4223. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  4224. **
  4225. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  4226. ** is declared to contain a particular type does not mean that the
  4227. ** data stored in that column is of the declared type. SQLite is
  4228. ** strongly typed, but the typing is dynamic not static. ^Type
  4229. ** is associated with individual values, not with the containers
  4230. ** used to hold those values.
  4231. */
  4232. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  4233. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  4234. /*
  4235. ** CAPI3REF: Evaluate An SQL Statement
  4236. ** METHOD: sqlite3_stmt
  4237. **
  4238. ** After a [prepared statement] has been prepared using either
  4239. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  4240. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  4241. ** must be called one or more times to evaluate the statement.
  4242. **
  4243. ** The details of the behavior of the sqlite3_step() interface depend
  4244. ** on whether the statement was prepared using the newer "v2" interface
  4245. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  4246. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  4247. ** new "v2" interface is recommended for new applications but the legacy
  4248. ** interface will continue to be supported.
  4249. **
  4250. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  4251. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  4252. ** ^With the "v2" interface, any of the other [result codes] or
  4253. ** [extended result codes] might be returned as well.
  4254. **
  4255. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  4256. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  4257. ** or occurs outside of an explicit transaction, then you can retry the
  4258. ** statement. If the statement is not a [COMMIT] and occurs within an
  4259. ** explicit transaction then you should rollback the transaction before
  4260. ** continuing.
  4261. **
  4262. ** ^[SQLITE_DONE] means that the statement has finished executing
  4263. ** successfully. sqlite3_step() should not be called again on this virtual
  4264. ** machine without first calling [sqlite3_reset()] to reset the virtual
  4265. ** machine back to its initial state.
  4266. **
  4267. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  4268. ** is returned each time a new row of data is ready for processing by the
  4269. ** caller. The values may be accessed using the [column access functions].
  4270. ** sqlite3_step() is called again to retrieve the next row of data.
  4271. **
  4272. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  4273. ** violation) has occurred. sqlite3_step() should not be called again on
  4274. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  4275. ** ^With the legacy interface, a more specific error code (for example,
  4276. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  4277. ** can be obtained by calling [sqlite3_reset()] on the
  4278. ** [prepared statement]. ^In the "v2" interface,
  4279. ** the more specific error code is returned directly by sqlite3_step().
  4280. **
  4281. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  4282. ** Perhaps it was called on a [prepared statement] that has
  4283. ** already been [sqlite3_finalize | finalized] or on one that had
  4284. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  4285. ** be the case that the same database connection is being used by two or
  4286. ** more threads at the same moment in time.
  4287. **
  4288. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  4289. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  4290. ** other than [SQLITE_ROW] before any subsequent invocation of
  4291. ** sqlite3_step(). Failure to reset the prepared statement using
  4292. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  4293. ** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1],
  4294. ** sqlite3_step() began
  4295. ** calling [sqlite3_reset()] automatically in this circumstance rather
  4296. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  4297. ** break because any application that ever receives an SQLITE_MISUSE error
  4298. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  4299. ** can be used to restore the legacy behavior.
  4300. **
  4301. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  4302. ** API always returns a generic error code, [SQLITE_ERROR], following any
  4303. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  4304. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  4305. ** specific [error codes] that better describes the error.
  4306. ** We admit that this is a goofy design. The problem has been fixed
  4307. ** with the "v2" interface. If you prepare all of your SQL statements
  4308. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  4309. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  4310. ** then the more specific [error codes] are returned directly
  4311. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  4312. */
  4313. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  4314. /*
  4315. ** CAPI3REF: Number of columns in a result set
  4316. ** METHOD: sqlite3_stmt
  4317. **
  4318. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  4319. ** current row of the result set of [prepared statement] P.
  4320. ** ^If prepared statement P does not have results ready to return
  4321. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  4322. ** interfaces) then sqlite3_data_count(P) returns 0.
  4323. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  4324. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  4325. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  4326. ** will return non-zero if previous call to [sqlite3_step](P) returned
  4327. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  4328. ** where it always returns zero since each step of that multi-step
  4329. ** pragma returns 0 columns of data.
  4330. **
  4331. ** See also: [sqlite3_column_count()]
  4332. */
  4333. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  4334. /*
  4335. ** CAPI3REF: Fundamental Datatypes
  4336. ** KEYWORDS: SQLITE_TEXT
  4337. **
  4338. ** ^(Every value in SQLite has one of five fundamental datatypes:
  4339. **
  4340. ** <ul>
  4341. ** <li> 64-bit signed integer
  4342. ** <li> 64-bit IEEE floating point number
  4343. ** <li> string
  4344. ** <li> BLOB
  4345. ** <li> NULL
  4346. ** </ul>)^
  4347. **
  4348. ** These constants are codes for each of those types.
  4349. **
  4350. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  4351. ** for a completely different meaning. Software that links against both
  4352. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  4353. ** SQLITE_TEXT.
  4354. */
  4355. #define SQLITE_INTEGER 1
  4356. #define SQLITE_FLOAT 2
  4357. #define SQLITE_BLOB 4
  4358. #define SQLITE_NULL 5
  4359. #ifdef SQLITE_TEXT
  4360. # undef SQLITE_TEXT
  4361. #else
  4362. # define SQLITE_TEXT 3
  4363. #endif
  4364. #define SQLITE3_TEXT 3
  4365. /*
  4366. ** CAPI3REF: Result Values From A Query
  4367. ** KEYWORDS: {column access functions}
  4368. ** METHOD: sqlite3_stmt
  4369. **
  4370. ** ^These routines return information about a single column of the current
  4371. ** result row of a query. ^In every case the first argument is a pointer
  4372. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  4373. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  4374. ** and the second argument is the index of the column for which information
  4375. ** should be returned. ^The leftmost column of the result set has the index 0.
  4376. ** ^The number of columns in the result can be determined using
  4377. ** [sqlite3_column_count()].
  4378. **
  4379. ** If the SQL statement does not currently point to a valid row, or if the
  4380. ** column index is out of range, the result is undefined.
  4381. ** These routines may only be called when the most recent call to
  4382. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  4383. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  4384. ** If any of these routines are called after [sqlite3_reset()] or
  4385. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  4386. ** something other than [SQLITE_ROW], the results are undefined.
  4387. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  4388. ** are called from a different thread while any of these routines
  4389. ** are pending, then the results are undefined.
  4390. **
  4391. ** ^The sqlite3_column_type() routine returns the
  4392. ** [SQLITE_INTEGER | datatype code] for the initial data type
  4393. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  4394. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  4395. ** returned by sqlite3_column_type() is only meaningful if no type
  4396. ** conversions have occurred as described below. After a type conversion,
  4397. ** the value returned by sqlite3_column_type() is undefined. Future
  4398. ** versions of SQLite may change the behavior of sqlite3_column_type()
  4399. ** following a type conversion.
  4400. **
  4401. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  4402. ** routine returns the number of bytes in that BLOB or string.
  4403. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  4404. ** the string to UTF-8 and then returns the number of bytes.
  4405. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  4406. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  4407. ** the number of bytes in that string.
  4408. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  4409. **
  4410. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  4411. ** routine returns the number of bytes in that BLOB or string.
  4412. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  4413. ** the string to UTF-16 and then returns the number of bytes.
  4414. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  4415. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  4416. ** the number of bytes in that string.
  4417. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  4418. **
  4419. ** ^The values returned by [sqlite3_column_bytes()] and
  4420. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  4421. ** of the string. ^For clarity: the values returned by
  4422. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  4423. ** bytes in the string, not the number of characters.
  4424. **
  4425. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  4426. ** even empty strings, are always zero-terminated. ^The return
  4427. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  4428. **
  4429. ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
  4430. ** [unprotected sqlite3_value] object. In a multithreaded environment,
  4431. ** an unprotected sqlite3_value object may only be used safely with
  4432. ** [sqlite3_bind_value()] and [sqlite3_result_value()].
  4433. ** If the [unprotected sqlite3_value] object returned by
  4434. ** [sqlite3_column_value()] is used in any other way, including calls
  4435. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  4436. ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
  4437. **
  4438. ** These routines attempt to convert the value where appropriate. ^For
  4439. ** example, if the internal representation is FLOAT and a text result
  4440. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  4441. ** conversion automatically. ^(The following table details the conversions
  4442. ** that are applied:
  4443. **
  4444. ** <blockquote>
  4445. ** <table border="1">
  4446. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  4447. **
  4448. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  4449. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  4450. ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
  4451. ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
  4452. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  4453. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  4454. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  4455. ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
  4456. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  4457. ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
  4458. ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
  4459. ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
  4460. ** <tr><td> TEXT <td> BLOB <td> No change
  4461. ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
  4462. ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
  4463. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  4464. ** </table>
  4465. ** </blockquote>)^
  4466. **
  4467. ** Note that when type conversions occur, pointers returned by prior
  4468. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  4469. ** sqlite3_column_text16() may be invalidated.
  4470. ** Type conversions and pointer invalidations might occur
  4471. ** in the following cases:
  4472. **
  4473. ** <ul>
  4474. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  4475. ** sqlite3_column_text16() is called. A zero-terminator might
  4476. ** need to be added to the string.</li>
  4477. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  4478. ** sqlite3_column_text16() is called. The content must be converted
  4479. ** to UTF-16.</li>
  4480. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  4481. ** sqlite3_column_text() is called. The content must be converted
  4482. ** to UTF-8.</li>
  4483. ** </ul>
  4484. **
  4485. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  4486. ** not invalidate a prior pointer, though of course the content of the buffer
  4487. ** that the prior pointer references will have been modified. Other kinds
  4488. ** of conversion are done in place when it is possible, but sometimes they
  4489. ** are not possible and in those cases prior pointers are invalidated.
  4490. **
  4491. ** The safest policy is to invoke these routines
  4492. ** in one of the following ways:
  4493. **
  4494. ** <ul>
  4495. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  4496. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  4497. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  4498. ** </ul>
  4499. **
  4500. ** In other words, you should call sqlite3_column_text(),
  4501. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  4502. ** into the desired format, then invoke sqlite3_column_bytes() or
  4503. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  4504. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  4505. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  4506. ** with calls to sqlite3_column_bytes().
  4507. **
  4508. ** ^The pointers returned are valid until a type conversion occurs as
  4509. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  4510. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  4511. ** and BLOBs is freed automatically. Do <em>not</em> pass the pointers returned
  4512. ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  4513. ** [sqlite3_free()].
  4514. **
  4515. ** ^(If a memory allocation error occurs during the evaluation of any
  4516. ** of these routines, a default value is returned. The default value
  4517. ** is either the integer 0, the floating point number 0.0, or a NULL
  4518. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  4519. ** [SQLITE_NOMEM].)^
  4520. */
  4521. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  4522. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  4523. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  4524. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  4525. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  4526. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  4527. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  4528. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  4529. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  4530. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  4531. /*
  4532. ** CAPI3REF: Destroy A Prepared Statement Object
  4533. ** DESTRUCTOR: sqlite3_stmt
  4534. **
  4535. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  4536. ** ^If the most recent evaluation of the statement encountered no errors
  4537. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  4538. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  4539. ** sqlite3_finalize(S) returns the appropriate [error code] or
  4540. ** [extended error code].
  4541. **
  4542. ** ^The sqlite3_finalize(S) routine can be called at any point during
  4543. ** the life cycle of [prepared statement] S:
  4544. ** before statement S is ever evaluated, after
  4545. ** one or more calls to [sqlite3_reset()], or after any call
  4546. ** to [sqlite3_step()] regardless of whether or not the statement has
  4547. ** completed execution.
  4548. **
  4549. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  4550. **
  4551. ** The application must finalize every [prepared statement] in order to avoid
  4552. ** resource leaks. It is a grievous error for the application to try to use
  4553. ** a prepared statement after it has been finalized. Any use of a prepared
  4554. ** statement after it has been finalized can result in undefined and
  4555. ** undesirable behavior such as segfaults and heap corruption.
  4556. */
  4557. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  4558. /*
  4559. ** CAPI3REF: Reset A Prepared Statement Object
  4560. ** METHOD: sqlite3_stmt
  4561. **
  4562. ** The sqlite3_reset() function is called to reset a [prepared statement]
  4563. ** object back to its initial state, ready to be re-executed.
  4564. ** ^Any SQL statement variables that had values bound to them using
  4565. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  4566. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  4567. **
  4568. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  4569. ** back to the beginning of its program.
  4570. **
  4571. ** ^If the most recent call to [sqlite3_step(S)] for the
  4572. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  4573. ** or if [sqlite3_step(S)] has never before been called on S,
  4574. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  4575. **
  4576. ** ^If the most recent call to [sqlite3_step(S)] for the
  4577. ** [prepared statement] S indicated an error, then
  4578. ** [sqlite3_reset(S)] returns an appropriate [error code].
  4579. **
  4580. ** ^The [sqlite3_reset(S)] interface does not change the values
  4581. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  4582. */
  4583. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  4584. /*
  4585. ** CAPI3REF: Create Or Redefine SQL Functions
  4586. ** KEYWORDS: {function creation routines}
  4587. ** KEYWORDS: {application-defined SQL function}
  4588. ** KEYWORDS: {application-defined SQL functions}
  4589. ** METHOD: sqlite3
  4590. **
  4591. ** ^These functions (collectively known as "function creation routines")
  4592. ** are used to add SQL functions or aggregates or to redefine the behavior
  4593. ** of existing SQL functions or aggregates. The only differences between
  4594. ** these routines are the text encoding expected for
  4595. ** the second parameter (the name of the function being created)
  4596. ** and the presence or absence of a destructor callback for
  4597. ** the application data pointer.
  4598. **
  4599. ** ^The first parameter is the [database connection] to which the SQL
  4600. ** function is to be added. ^If an application uses more than one database
  4601. ** connection then application-defined SQL functions must be added
  4602. ** to each database connection separately.
  4603. **
  4604. ** ^The second parameter is the name of the SQL function to be created or
  4605. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  4606. ** representation, exclusive of the zero-terminator. ^Note that the name
  4607. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  4608. ** ^Any attempt to create a function with a longer name
  4609. ** will result in [SQLITE_MISUSE] being returned.
  4610. **
  4611. ** ^The third parameter (nArg)
  4612. ** is the number of arguments that the SQL function or
  4613. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  4614. ** aggregate may take any number of arguments between 0 and the limit
  4615. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  4616. ** parameter is less than -1 or greater than 127 then the behavior is
  4617. ** undefined.
  4618. **
  4619. ** ^The fourth parameter, eTextRep, specifies what
  4620. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  4621. ** its parameters. The application should set this parameter to
  4622. ** [SQLITE_UTF16LE] if the function implementation invokes
  4623. ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  4624. ** implementation invokes [sqlite3_value_text16be()] on an input, or
  4625. ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  4626. ** otherwise. ^The same SQL function may be registered multiple times using
  4627. ** different preferred text encodings, with different implementations for
  4628. ** each encoding.
  4629. ** ^When multiple implementations of the same function are available, SQLite
  4630. ** will pick the one that involves the least amount of data conversion.
  4631. **
  4632. ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  4633. ** to signal that the function will always return the same result given
  4634. ** the same inputs within a single SQL statement. Most SQL functions are
  4635. ** deterministic. The built-in [random()] SQL function is an example of a
  4636. ** function that is not deterministic. The SQLite query planner is able to
  4637. ** perform additional optimizations on deterministic functions, so use
  4638. ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  4639. **
  4640. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  4641. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  4642. **
  4643. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  4644. ** pointers to C-language functions that implement the SQL function or
  4645. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  4646. ** callback only; NULL pointers must be passed as the xStep and xFinal
  4647. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  4648. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  4649. ** SQL function or aggregate, pass NULL pointers for all three function
  4650. ** callbacks.
  4651. **
  4652. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  4653. ** then it is destructor for the application data pointer.
  4654. ** The destructor is invoked when the function is deleted, either by being
  4655. ** overloaded or when the database connection closes.)^
  4656. ** ^The destructor is also invoked if the call to
  4657. ** sqlite3_create_function_v2() fails.
  4658. ** ^When the destructor callback of the tenth parameter is invoked, it
  4659. ** is passed a single argument which is a copy of the application data
  4660. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  4661. **
  4662. ** ^It is permitted to register multiple implementations of the same
  4663. ** functions with the same name but with either differing numbers of
  4664. ** arguments or differing preferred text encodings. ^SQLite will use
  4665. ** the implementation that most closely matches the way in which the
  4666. ** SQL function is used. ^A function implementation with a non-negative
  4667. ** nArg parameter is a better match than a function implementation with
  4668. ** a negative nArg. ^A function where the preferred text encoding
  4669. ** matches the database encoding is a better
  4670. ** match than a function where the encoding is different.
  4671. ** ^A function where the encoding difference is between UTF16le and UTF16be
  4672. ** is a closer match than a function where the encoding difference is
  4673. ** between UTF8 and UTF16.
  4674. **
  4675. ** ^Built-in functions may be overloaded by new application-defined functions.
  4676. **
  4677. ** ^An application-defined function is permitted to call other
  4678. ** SQLite interfaces. However, such calls must not
  4679. ** close the database connection nor finalize or reset the prepared
  4680. ** statement in which the function is running.
  4681. */
  4682. SQLITE_API int sqlite3_create_function(
  4683. sqlite3 *db,
  4684. const char *zFunctionName,
  4685. int nArg,
  4686. int eTextRep,
  4687. void *pApp,
  4688. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4689. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4690. void (*xFinal)(sqlite3_context*)
  4691. );
  4692. SQLITE_API int sqlite3_create_function16(
  4693. sqlite3 *db,
  4694. const void *zFunctionName,
  4695. int nArg,
  4696. int eTextRep,
  4697. void *pApp,
  4698. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4699. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4700. void (*xFinal)(sqlite3_context*)
  4701. );
  4702. SQLITE_API int sqlite3_create_function_v2(
  4703. sqlite3 *db,
  4704. const char *zFunctionName,
  4705. int nArg,
  4706. int eTextRep,
  4707. void *pApp,
  4708. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4709. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4710. void (*xFinal)(sqlite3_context*),
  4711. void(*xDestroy)(void*)
  4712. );
  4713. /*
  4714. ** CAPI3REF: Text Encodings
  4715. **
  4716. ** These constant define integer codes that represent the various
  4717. ** text encodings supported by SQLite.
  4718. */
  4719. #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
  4720. #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
  4721. #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
  4722. #define SQLITE_UTF16 4 /* Use native byte order */
  4723. #define SQLITE_ANY 5 /* Deprecated */
  4724. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  4725. /*
  4726. ** CAPI3REF: Function Flags
  4727. **
  4728. ** These constants may be ORed together with the
  4729. ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  4730. ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  4731. ** [sqlite3_create_function_v2()].
  4732. */
  4733. #define SQLITE_DETERMINISTIC 0x800
  4734. /*
  4735. ** CAPI3REF: Deprecated Functions
  4736. ** DEPRECATED
  4737. **
  4738. ** These functions are [deprecated]. In order to maintain
  4739. ** backwards compatibility with older code, these functions continue
  4740. ** to be supported. However, new applications should avoid
  4741. ** the use of these functions. To encourage programmers to avoid
  4742. ** these functions, we will not explain what they do.
  4743. */
  4744. #ifndef SQLITE_OMIT_DEPRECATED
  4745. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  4746. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  4747. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  4748. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  4749. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  4750. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  4751. void*,sqlite3_int64);
  4752. #endif
  4753. /*
  4754. ** CAPI3REF: Obtaining SQL Values
  4755. ** METHOD: sqlite3_value
  4756. **
  4757. ** The C-language implementation of SQL functions and aggregates uses
  4758. ** this set of interface routines to access the parameter values on
  4759. ** the function or aggregate.
  4760. **
  4761. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  4762. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  4763. ** define callbacks that implement the SQL functions and aggregates.
  4764. ** The 3rd parameter to these callbacks is an array of pointers to
  4765. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  4766. ** each parameter to the SQL function. These routines are used to
  4767. ** extract values from the [sqlite3_value] objects.
  4768. **
  4769. ** These routines work only with [protected sqlite3_value] objects.
  4770. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  4771. ** object results in undefined behavior.
  4772. **
  4773. ** ^These routines work just like the corresponding [column access functions]
  4774. ** except that these routines take a single [protected sqlite3_value] object
  4775. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  4776. **
  4777. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  4778. ** in the native byte-order of the host machine. ^The
  4779. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  4780. ** extract UTF-16 strings as big-endian and little-endian respectively.
  4781. **
  4782. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  4783. ** numeric affinity to the value. This means that an attempt is
  4784. ** made to convert the value to an integer or floating point. If
  4785. ** such a conversion is possible without loss of information (in other
  4786. ** words, if the value is a string that looks like a number)
  4787. ** then the conversion is performed. Otherwise no conversion occurs.
  4788. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  4789. **
  4790. ** Please pay particular attention to the fact that the pointer returned
  4791. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  4792. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  4793. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  4794. ** or [sqlite3_value_text16()].
  4795. **
  4796. ** These routines must be called from the same thread as
  4797. ** the SQL function that supplied the [sqlite3_value*] parameters.
  4798. */
  4799. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  4800. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  4801. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  4802. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  4803. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  4804. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  4805. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  4806. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  4807. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  4808. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  4809. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  4810. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  4811. /*
  4812. ** CAPI3REF: Finding The Subtype Of SQL Values
  4813. ** METHOD: sqlite3_value
  4814. **
  4815. ** The sqlite3_value_subtype(V) function returns the subtype for
  4816. ** an [application-defined SQL function] argument V. The subtype
  4817. ** information can be used to pass a limited amount of context from
  4818. ** one SQL function to another. Use the [sqlite3_result_subtype()]
  4819. ** routine to set the subtype for the return value of an SQL function.
  4820. **
  4821. ** SQLite makes no use of subtype itself. It merely passes the subtype
  4822. ** from the result of one [application-defined SQL function] into the
  4823. ** input of another.
  4824. */
  4825. SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
  4826. /*
  4827. ** CAPI3REF: Copy And Free SQL Values
  4828. ** METHOD: sqlite3_value
  4829. **
  4830. ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
  4831. ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
  4832. ** is a [protected sqlite3_value] object even if the input is not.
  4833. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
  4834. ** memory allocation fails.
  4835. **
  4836. ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
  4837. ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
  4838. ** then sqlite3_value_free(V) is a harmless no-op.
  4839. */
  4840. SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
  4841. SQLITE_API void sqlite3_value_free(sqlite3_value*);
  4842. /*
  4843. ** CAPI3REF: Obtain Aggregate Function Context
  4844. ** METHOD: sqlite3_context
  4845. **
  4846. ** Implementations of aggregate SQL functions use this
  4847. ** routine to allocate memory for storing their state.
  4848. **
  4849. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  4850. ** for a particular aggregate function, SQLite
  4851. ** allocates N of memory, zeroes out that memory, and returns a pointer
  4852. ** to the new memory. ^On second and subsequent calls to
  4853. ** sqlite3_aggregate_context() for the same aggregate function instance,
  4854. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  4855. ** called once for each invocation of the xStep callback and then one
  4856. ** last time when the xFinal callback is invoked. ^(When no rows match
  4857. ** an aggregate query, the xStep() callback of the aggregate function
  4858. ** implementation is never called and xFinal() is called exactly once.
  4859. ** In those cases, sqlite3_aggregate_context() might be called for the
  4860. ** first time from within xFinal().)^
  4861. **
  4862. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  4863. ** when first called if N is less than or equal to zero or if a memory
  4864. ** allocate error occurs.
  4865. **
  4866. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  4867. ** determined by the N parameter on first successful call. Changing the
  4868. ** value of N in subsequent call to sqlite3_aggregate_context() within
  4869. ** the same aggregate function instance will not resize the memory
  4870. ** allocation.)^ Within the xFinal callback, it is customary to set
  4871. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  4872. ** pointless memory allocations occur.
  4873. **
  4874. ** ^SQLite automatically frees the memory allocated by
  4875. ** sqlite3_aggregate_context() when the aggregate query concludes.
  4876. **
  4877. ** The first parameter must be a copy of the
  4878. ** [sqlite3_context | SQL function context] that is the first parameter
  4879. ** to the xStep or xFinal callback routine that implements the aggregate
  4880. ** function.
  4881. **
  4882. ** This routine must be called from the same thread in which
  4883. ** the aggregate SQL function is running.
  4884. */
  4885. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  4886. /*
  4887. ** CAPI3REF: User Data For Functions
  4888. ** METHOD: sqlite3_context
  4889. **
  4890. ** ^The sqlite3_user_data() interface returns a copy of
  4891. ** the pointer that was the pUserData parameter (the 5th parameter)
  4892. ** of the [sqlite3_create_function()]
  4893. ** and [sqlite3_create_function16()] routines that originally
  4894. ** registered the application defined function.
  4895. **
  4896. ** This routine must be called from the same thread in which
  4897. ** the application-defined function is running.
  4898. */
  4899. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  4900. /*
  4901. ** CAPI3REF: Database Connection For Functions
  4902. ** METHOD: sqlite3_context
  4903. **
  4904. ** ^The sqlite3_context_db_handle() interface returns a copy of
  4905. ** the pointer to the [database connection] (the 1st parameter)
  4906. ** of the [sqlite3_create_function()]
  4907. ** and [sqlite3_create_function16()] routines that originally
  4908. ** registered the application defined function.
  4909. */
  4910. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  4911. /*
  4912. ** CAPI3REF: Function Auxiliary Data
  4913. ** METHOD: sqlite3_context
  4914. **
  4915. ** These functions may be used by (non-aggregate) SQL functions to
  4916. ** associate metadata with argument values. If the same value is passed to
  4917. ** multiple invocations of the same SQL function during query execution, under
  4918. ** some circumstances the associated metadata may be preserved. An example
  4919. ** of where this might be useful is in a regular-expression matching
  4920. ** function. The compiled version of the regular expression can be stored as
  4921. ** metadata associated with the pattern string.
  4922. ** Then as long as the pattern string remains the same,
  4923. ** the compiled regular expression can be reused on multiple
  4924. ** invocations of the same function.
  4925. **
  4926. ** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
  4927. ** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
  4928. ** value to the application-defined function. ^N is zero for the left-most
  4929. ** function argument. ^If there is no metadata
  4930. ** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
  4931. ** returns a NULL pointer.
  4932. **
  4933. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  4934. ** argument of the application-defined function. ^Subsequent
  4935. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  4936. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  4937. ** NULL if the metadata has been discarded.
  4938. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  4939. ** SQLite will invoke the destructor function X with parameter P exactly
  4940. ** once, when the metadata is discarded.
  4941. ** SQLite is free to discard the metadata at any time, including: <ul>
  4942. ** <li> ^(when the corresponding function parameter changes)^, or
  4943. ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  4944. ** SQL statement)^, or
  4945. ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
  4946. ** parameter)^, or
  4947. ** <li> ^(during the original sqlite3_set_auxdata() call when a memory
  4948. ** allocation error occurs.)^ </ul>
  4949. **
  4950. ** Note the last bullet in particular. The destructor X in
  4951. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  4952. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  4953. ** should be called near the end of the function implementation and the
  4954. ** function implementation should not make any use of P after
  4955. ** sqlite3_set_auxdata() has been called.
  4956. **
  4957. ** ^(In practice, metadata is preserved between function calls for
  4958. ** function parameters that are compile-time constants, including literal
  4959. ** values and [parameters] and expressions composed from the same.)^
  4960. **
  4961. ** The value of the N parameter to these interfaces should be non-negative.
  4962. ** Future enhancements may make use of negative N values to define new
  4963. ** kinds of function caching behavior.
  4964. **
  4965. ** These routines must be called from the same thread in which
  4966. ** the SQL function is running.
  4967. */
  4968. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  4969. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  4970. /*
  4971. ** CAPI3REF: Constants Defining Special Destructor Behavior
  4972. **
  4973. ** These are special values for the destructor that is passed in as the
  4974. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  4975. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  4976. ** and will never change. It does not need to be destroyed. ^The
  4977. ** SQLITE_TRANSIENT value means that the content will likely change in
  4978. ** the near future and that SQLite should make its own private copy of
  4979. ** the content before returning.
  4980. **
  4981. ** The typedef is necessary to work around problems in certain
  4982. ** C++ compilers.
  4983. */
  4984. typedef void (*sqlite3_destructor_type)(void*);
  4985. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  4986. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  4987. /*
  4988. ** CAPI3REF: Setting The Result Of An SQL Function
  4989. ** METHOD: sqlite3_context
  4990. **
  4991. ** These routines are used by the xFunc or xFinal callbacks that
  4992. ** implement SQL functions and aggregates. See
  4993. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  4994. ** for additional information.
  4995. **
  4996. ** These functions work very much like the [parameter binding] family of
  4997. ** functions used to bind values to host parameters in prepared statements.
  4998. ** Refer to the [SQL parameter] documentation for additional information.
  4999. **
  5000. ** ^The sqlite3_result_blob() interface sets the result from
  5001. ** an application-defined function to be the BLOB whose content is pointed
  5002. ** to by the second parameter and which is N bytes long where N is the
  5003. ** third parameter.
  5004. **
  5005. ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
  5006. ** interfaces set the result of the application-defined function to be
  5007. ** a BLOB containing all zero bytes and N bytes in size.
  5008. **
  5009. ** ^The sqlite3_result_double() interface sets the result from
  5010. ** an application-defined function to be a floating point value specified
  5011. ** by its 2nd argument.
  5012. **
  5013. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  5014. ** cause the implemented SQL function to throw an exception.
  5015. ** ^SQLite uses the string pointed to by the
  5016. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  5017. ** as the text of an error message. ^SQLite interprets the error
  5018. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  5019. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  5020. ** byte order. ^If the third parameter to sqlite3_result_error()
  5021. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  5022. ** message all text up through the first zero character.
  5023. ** ^If the third parameter to sqlite3_result_error() or
  5024. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  5025. ** bytes (not characters) from the 2nd parameter as the error message.
  5026. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  5027. ** routines make a private copy of the error message text before
  5028. ** they return. Hence, the calling function can deallocate or
  5029. ** modify the text after they return without harm.
  5030. ** ^The sqlite3_result_error_code() function changes the error code
  5031. ** returned by SQLite as a result of an error in a function. ^By default,
  5032. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  5033. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  5034. **
  5035. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  5036. ** error indicating that a string or BLOB is too long to represent.
  5037. **
  5038. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  5039. ** error indicating that a memory allocation failed.
  5040. **
  5041. ** ^The sqlite3_result_int() interface sets the return value
  5042. ** of the application-defined function to be the 32-bit signed integer
  5043. ** value given in the 2nd argument.
  5044. ** ^The sqlite3_result_int64() interface sets the return value
  5045. ** of the application-defined function to be the 64-bit signed integer
  5046. ** value given in the 2nd argument.
  5047. **
  5048. ** ^The sqlite3_result_null() interface sets the return value
  5049. ** of the application-defined function to be NULL.
  5050. **
  5051. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  5052. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  5053. ** set the return value of the application-defined function to be
  5054. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  5055. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  5056. ** ^The sqlite3_result_text64() interface sets the return value of an
  5057. ** application-defined function to be a text string in an encoding
  5058. ** specified by the fifth (and last) parameter, which must be one
  5059. ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
  5060. ** ^SQLite takes the text result from the application from
  5061. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  5062. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  5063. ** is negative, then SQLite takes result text from the 2nd parameter
  5064. ** through the first zero character.
  5065. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  5066. ** is non-negative, then as many bytes (not characters) of the text
  5067. ** pointed to by the 2nd parameter are taken as the application-defined
  5068. ** function result. If the 3rd parameter is non-negative, then it
  5069. ** must be the byte offset into the string where the NUL terminator would
  5070. ** appear if the string where NUL terminated. If any NUL characters occur
  5071. ** in the string at a byte offset that is less than the value of the 3rd
  5072. ** parameter, then the resulting string will contain embedded NULs and the
  5073. ** result of expressions operating on strings with embedded NULs is undefined.
  5074. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  5075. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  5076. ** function as the destructor on the text or BLOB result when it has
  5077. ** finished using that result.
  5078. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  5079. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  5080. ** assumes that the text or BLOB result is in constant space and does not
  5081. ** copy the content of the parameter nor call a destructor on the content
  5082. ** when it has finished using that result.
  5083. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  5084. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  5085. ** then SQLite makes a copy of the result into space obtained from
  5086. ** from [sqlite3_malloc()] before it returns.
  5087. **
  5088. ** ^The sqlite3_result_value() interface sets the result of
  5089. ** the application-defined function to be a copy of the
  5090. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  5091. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  5092. ** so that the [sqlite3_value] specified in the parameter may change or
  5093. ** be deallocated after sqlite3_result_value() returns without harm.
  5094. ** ^A [protected sqlite3_value] object may always be used where an
  5095. ** [unprotected sqlite3_value] object is required, so either
  5096. ** kind of [sqlite3_value] object can be used with this interface.
  5097. **
  5098. ** If these routines are called from within the different thread
  5099. ** than the one containing the application-defined function that received
  5100. ** the [sqlite3_context] pointer, the results are undefined.
  5101. */
  5102. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  5103. SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
  5104. sqlite3_uint64,void(*)(void*));
  5105. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  5106. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  5107. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  5108. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  5109. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  5110. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  5111. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  5112. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  5113. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  5114. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  5115. SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
  5116. void(*)(void*), unsigned char encoding);
  5117. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  5118. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  5119. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  5120. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  5121. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  5122. SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
  5123. /*
  5124. ** CAPI3REF: Setting The Subtype Of An SQL Function
  5125. ** METHOD: sqlite3_context
  5126. **
  5127. ** The sqlite3_result_subtype(C,T) function causes the subtype of
  5128. ** the result from the [application-defined SQL function] with
  5129. ** [sqlite3_context] C to be the value T. Only the lower 8 bits
  5130. ** of the subtype T are preserved in current versions of SQLite;
  5131. ** higher order bits are discarded.
  5132. ** The number of subtype bytes preserved by SQLite might increase
  5133. ** in future releases of SQLite.
  5134. */
  5135. SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
  5136. /*
  5137. ** CAPI3REF: Define New Collating Sequences
  5138. ** METHOD: sqlite3
  5139. **
  5140. ** ^These functions add, remove, or modify a [collation] associated
  5141. ** with the [database connection] specified as the first argument.
  5142. **
  5143. ** ^The name of the collation is a UTF-8 string
  5144. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  5145. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  5146. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  5147. ** considered to be the same name.
  5148. **
  5149. ** ^(The third argument (eTextRep) must be one of the constants:
  5150. ** <ul>
  5151. ** <li> [SQLITE_UTF8],
  5152. ** <li> [SQLITE_UTF16LE],
  5153. ** <li> [SQLITE_UTF16BE],
  5154. ** <li> [SQLITE_UTF16], or
  5155. ** <li> [SQLITE_UTF16_ALIGNED].
  5156. ** </ul>)^
  5157. ** ^The eTextRep argument determines the encoding of strings passed
  5158. ** to the collating function callback, xCallback.
  5159. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  5160. ** force strings to be UTF16 with native byte order.
  5161. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  5162. ** on an even byte address.
  5163. **
  5164. ** ^The fourth argument, pArg, is an application data pointer that is passed
  5165. ** through as the first argument to the collating function callback.
  5166. **
  5167. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  5168. ** ^Multiple collating functions can be registered using the same name but
  5169. ** with different eTextRep parameters and SQLite will use whichever
  5170. ** function requires the least amount of data transformation.
  5171. ** ^If the xCallback argument is NULL then the collating function is
  5172. ** deleted. ^When all collating functions having the same name are deleted,
  5173. ** that collation is no longer usable.
  5174. **
  5175. ** ^The collating function callback is invoked with a copy of the pArg
  5176. ** application data pointer and with two strings in the encoding specified
  5177. ** by the eTextRep argument. The collating function must return an
  5178. ** integer that is negative, zero, or positive
  5179. ** if the first string is less than, equal to, or greater than the second,
  5180. ** respectively. A collating function must always return the same answer
  5181. ** given the same inputs. If two or more collating functions are registered
  5182. ** to the same collation name (using different eTextRep values) then all
  5183. ** must give an equivalent answer when invoked with equivalent strings.
  5184. ** The collating function must obey the following properties for all
  5185. ** strings A, B, and C:
  5186. **
  5187. ** <ol>
  5188. ** <li> If A==B then B==A.
  5189. ** <li> If A==B and B==C then A==C.
  5190. ** <li> If A&lt;B THEN B&gt;A.
  5191. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  5192. ** </ol>
  5193. **
  5194. ** If a collating function fails any of the above constraints and that
  5195. ** collating function is registered and used, then the behavior of SQLite
  5196. ** is undefined.
  5197. **
  5198. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  5199. ** with the addition that the xDestroy callback is invoked on pArg when
  5200. ** the collating function is deleted.
  5201. ** ^Collating functions are deleted when they are overridden by later
  5202. ** calls to the collation creation functions or when the
  5203. ** [database connection] is closed using [sqlite3_close()].
  5204. **
  5205. ** ^The xDestroy callback is <u>not</u> called if the
  5206. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  5207. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  5208. ** check the return code and dispose of the application data pointer
  5209. ** themselves rather than expecting SQLite to deal with it for them.
  5210. ** This is different from every other SQLite interface. The inconsistency
  5211. ** is unfortunate but cannot be changed without breaking backwards
  5212. ** compatibility.
  5213. **
  5214. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  5215. */
  5216. SQLITE_API int sqlite3_create_collation(
  5217. sqlite3*,
  5218. const char *zName,
  5219. int eTextRep,
  5220. void *pArg,
  5221. int(*xCompare)(void*,int,const void*,int,const void*)
  5222. );
  5223. SQLITE_API int sqlite3_create_collation_v2(
  5224. sqlite3*,
  5225. const char *zName,
  5226. int eTextRep,
  5227. void *pArg,
  5228. int(*xCompare)(void*,int,const void*,int,const void*),
  5229. void(*xDestroy)(void*)
  5230. );
  5231. SQLITE_API int sqlite3_create_collation16(
  5232. sqlite3*,
  5233. const void *zName,
  5234. int eTextRep,
  5235. void *pArg,
  5236. int(*xCompare)(void*,int,const void*,int,const void*)
  5237. );
  5238. /*
  5239. ** CAPI3REF: Collation Needed Callbacks
  5240. ** METHOD: sqlite3
  5241. **
  5242. ** ^To avoid having to register all collation sequences before a database
  5243. ** can be used, a single callback function may be registered with the
  5244. ** [database connection] to be invoked whenever an undefined collation
  5245. ** sequence is required.
  5246. **
  5247. ** ^If the function is registered using the sqlite3_collation_needed() API,
  5248. ** then it is passed the names of undefined collation sequences as strings
  5249. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  5250. ** the names are passed as UTF-16 in machine native byte order.
  5251. ** ^A call to either function replaces the existing collation-needed callback.
  5252. **
  5253. ** ^(When the callback is invoked, the first argument passed is a copy
  5254. ** of the second argument to sqlite3_collation_needed() or
  5255. ** sqlite3_collation_needed16(). The second argument is the database
  5256. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  5257. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  5258. ** sequence function required. The fourth parameter is the name of the
  5259. ** required collation sequence.)^
  5260. **
  5261. ** The callback function should register the desired collation using
  5262. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  5263. ** [sqlite3_create_collation_v2()].
  5264. */
  5265. SQLITE_API int sqlite3_collation_needed(
  5266. sqlite3*,
  5267. void*,
  5268. void(*)(void*,sqlite3*,int eTextRep,const char*)
  5269. );
  5270. SQLITE_API int sqlite3_collation_needed16(
  5271. sqlite3*,
  5272. void*,
  5273. void(*)(void*,sqlite3*,int eTextRep,const void*)
  5274. );
  5275. #ifdef SQLITE_HAS_CODEC
  5276. /*
  5277. ** Specify the key for an encrypted database. This routine should be
  5278. ** called right after sqlite3_open().
  5279. **
  5280. ** The code to implement this API is not available in the public release
  5281. ** of SQLite.
  5282. */
  5283. SQLITE_API int sqlite3_key(
  5284. sqlite3 *db, /* Database to be rekeyed */
  5285. const void *pKey, int nKey /* The key */
  5286. );
  5287. SQLITE_API int sqlite3_key_v2(
  5288. sqlite3 *db, /* Database to be rekeyed */
  5289. const char *zDbName, /* Name of the database */
  5290. const void *pKey, int nKey /* The key */
  5291. );
  5292. /*
  5293. ** Change the key on an open database. If the current database is not
  5294. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  5295. ** database is decrypted.
  5296. **
  5297. ** The code to implement this API is not available in the public release
  5298. ** of SQLite.
  5299. */
  5300. SQLITE_API int sqlite3_rekey(
  5301. sqlite3 *db, /* Database to be rekeyed */
  5302. const void *pKey, int nKey /* The new key */
  5303. );
  5304. SQLITE_API int sqlite3_rekey_v2(
  5305. sqlite3 *db, /* Database to be rekeyed */
  5306. const char *zDbName, /* Name of the database */
  5307. const void *pKey, int nKey /* The new key */
  5308. );
  5309. /*
  5310. ** Specify the activation key for a SEE database. Unless
  5311. ** activated, none of the SEE routines will work.
  5312. */
  5313. SQLITE_API void sqlite3_activate_see(
  5314. const char *zPassPhrase /* Activation phrase */
  5315. );
  5316. #endif
  5317. #ifdef SQLITE_ENABLE_CEROD
  5318. /*
  5319. ** Specify the activation key for a CEROD database. Unless
  5320. ** activated, none of the CEROD routines will work.
  5321. */
  5322. SQLITE_API void sqlite3_activate_cerod(
  5323. const char *zPassPhrase /* Activation phrase */
  5324. );
  5325. #endif
  5326. /*
  5327. ** CAPI3REF: Suspend Execution For A Short Time
  5328. **
  5329. ** The sqlite3_sleep() function causes the current thread to suspend execution
  5330. ** for at least a number of milliseconds specified in its parameter.
  5331. **
  5332. ** If the operating system does not support sleep requests with
  5333. ** millisecond time resolution, then the time will be rounded up to
  5334. ** the nearest second. The number of milliseconds of sleep actually
  5335. ** requested from the operating system is returned.
  5336. **
  5337. ** ^SQLite implements this interface by calling the xSleep()
  5338. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  5339. ** of the default VFS is not implemented correctly, or not implemented at
  5340. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  5341. ** in the previous paragraphs.
  5342. */
  5343. SQLITE_API int sqlite3_sleep(int);
  5344. /*
  5345. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  5346. **
  5347. ** ^(If this global variable is made to point to a string which is
  5348. ** the name of a folder (a.k.a. directory), then all temporary files
  5349. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  5350. ** will be placed in that directory.)^ ^If this variable
  5351. ** is a NULL pointer, then SQLite performs a search for an appropriate
  5352. ** temporary file directory.
  5353. **
  5354. ** Applications are strongly discouraged from using this global variable.
  5355. ** It is required to set a temporary folder on Windows Runtime (WinRT).
  5356. ** But for all other platforms, it is highly recommended that applications
  5357. ** neither read nor write this variable. This global variable is a relic
  5358. ** that exists for backwards compatibility of legacy applications and should
  5359. ** be avoided in new projects.
  5360. **
  5361. ** It is not safe to read or modify this variable in more than one
  5362. ** thread at a time. It is not safe to read or modify this variable
  5363. ** if a [database connection] is being used at the same time in a separate
  5364. ** thread.
  5365. ** It is intended that this variable be set once
  5366. ** as part of process initialization and before any SQLite interface
  5367. ** routines have been called and that this variable remain unchanged
  5368. ** thereafter.
  5369. **
  5370. ** ^The [temp_store_directory pragma] may modify this variable and cause
  5371. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  5372. ** the [temp_store_directory pragma] always assumes that any string
  5373. ** that this variable points to is held in memory obtained from
  5374. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  5375. ** using [sqlite3_free].
  5376. ** Hence, if this variable is modified directly, either it should be
  5377. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  5378. ** or else the use of the [temp_store_directory pragma] should be avoided.
  5379. ** Except when requested by the [temp_store_directory pragma], SQLite
  5380. ** does not free the memory that sqlite3_temp_directory points to. If
  5381. ** the application wants that memory to be freed, it must do
  5382. ** so itself, taking care to only do so after all [database connection]
  5383. ** objects have been destroyed.
  5384. **
  5385. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  5386. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  5387. ** features that require the use of temporary files may fail. Here is an
  5388. ** example of how to do this using C++ with the Windows Runtime:
  5389. **
  5390. ** <blockquote><pre>
  5391. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  5392. ** &nbsp; TemporaryFolder->Path->Data();
  5393. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  5394. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  5395. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  5396. ** &nbsp; NULL, NULL);
  5397. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  5398. ** </pre></blockquote>
  5399. */
  5400. SQLITE_API char *sqlite3_temp_directory;
  5401. /*
  5402. ** CAPI3REF: Name Of The Folder Holding Database Files
  5403. **
  5404. ** ^(If this global variable is made to point to a string which is
  5405. ** the name of a folder (a.k.a. directory), then all database files
  5406. ** specified with a relative pathname and created or accessed by
  5407. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  5408. ** to be relative to that directory.)^ ^If this variable is a NULL
  5409. ** pointer, then SQLite assumes that all database files specified
  5410. ** with a relative pathname are relative to the current directory
  5411. ** for the process. Only the windows VFS makes use of this global
  5412. ** variable; it is ignored by the unix VFS.
  5413. **
  5414. ** Changing the value of this variable while a database connection is
  5415. ** open can result in a corrupt database.
  5416. **
  5417. ** It is not safe to read or modify this variable in more than one
  5418. ** thread at a time. It is not safe to read or modify this variable
  5419. ** if a [database connection] is being used at the same time in a separate
  5420. ** thread.
  5421. ** It is intended that this variable be set once
  5422. ** as part of process initialization and before any SQLite interface
  5423. ** routines have been called and that this variable remain unchanged
  5424. ** thereafter.
  5425. **
  5426. ** ^The [data_store_directory pragma] may modify this variable and cause
  5427. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  5428. ** the [data_store_directory pragma] always assumes that any string
  5429. ** that this variable points to is held in memory obtained from
  5430. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  5431. ** using [sqlite3_free].
  5432. ** Hence, if this variable is modified directly, either it should be
  5433. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  5434. ** or else the use of the [data_store_directory pragma] should be avoided.
  5435. */
  5436. SQLITE_API char *sqlite3_data_directory;
  5437. /*
  5438. ** CAPI3REF: Test For Auto-Commit Mode
  5439. ** KEYWORDS: {autocommit mode}
  5440. ** METHOD: sqlite3
  5441. **
  5442. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  5443. ** zero if the given database connection is or is not in autocommit mode,
  5444. ** respectively. ^Autocommit mode is on by default.
  5445. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  5446. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  5447. **
  5448. ** If certain kinds of errors occur on a statement within a multi-statement
  5449. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  5450. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  5451. ** transaction might be rolled back automatically. The only way to
  5452. ** find out whether SQLite automatically rolled back the transaction after
  5453. ** an error is to use this function.
  5454. **
  5455. ** If another thread changes the autocommit status of the database
  5456. ** connection while this routine is running, then the return value
  5457. ** is undefined.
  5458. */
  5459. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  5460. /*
  5461. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  5462. ** METHOD: sqlite3_stmt
  5463. **
  5464. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  5465. ** to which a [prepared statement] belongs. ^The [database connection]
  5466. ** returned by sqlite3_db_handle is the same [database connection]
  5467. ** that was the first argument
  5468. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  5469. ** create the statement in the first place.
  5470. */
  5471. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  5472. /*
  5473. ** CAPI3REF: Return The Filename For A Database Connection
  5474. ** METHOD: sqlite3
  5475. **
  5476. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  5477. ** associated with database N of connection D. ^The main database file
  5478. ** has the name "main". If there is no attached database N on the database
  5479. ** connection D, or if database N is a temporary or in-memory database, then
  5480. ** a NULL pointer is returned.
  5481. **
  5482. ** ^The filename returned by this function is the output of the
  5483. ** xFullPathname method of the [VFS]. ^In other words, the filename
  5484. ** will be an absolute pathname, even if the filename used
  5485. ** to open the database originally was a URI or relative pathname.
  5486. */
  5487. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  5488. /*
  5489. ** CAPI3REF: Determine if a database is read-only
  5490. ** METHOD: sqlite3
  5491. **
  5492. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  5493. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  5494. ** the name of a database on connection D.
  5495. */
  5496. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  5497. /*
  5498. ** CAPI3REF: Find the next prepared statement
  5499. ** METHOD: sqlite3
  5500. **
  5501. ** ^This interface returns a pointer to the next [prepared statement] after
  5502. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  5503. ** then this interface returns a pointer to the first prepared statement
  5504. ** associated with the database connection pDb. ^If no prepared statement
  5505. ** satisfies the conditions of this routine, it returns NULL.
  5506. **
  5507. ** The [database connection] pointer D in a call to
  5508. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  5509. ** connection and in particular must not be a NULL pointer.
  5510. */
  5511. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  5512. /*
  5513. ** CAPI3REF: Commit And Rollback Notification Callbacks
  5514. ** METHOD: sqlite3
  5515. **
  5516. ** ^The sqlite3_commit_hook() interface registers a callback
  5517. ** function to be invoked whenever a transaction is [COMMIT | committed].
  5518. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  5519. ** for the same database connection is overridden.
  5520. ** ^The sqlite3_rollback_hook() interface registers a callback
  5521. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  5522. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  5523. ** for the same database connection is overridden.
  5524. ** ^The pArg argument is passed through to the callback.
  5525. ** ^If the callback on a commit hook function returns non-zero,
  5526. ** then the commit is converted into a rollback.
  5527. **
  5528. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  5529. ** return the P argument from the previous call of the same function
  5530. ** on the same [database connection] D, or NULL for
  5531. ** the first call for each function on D.
  5532. **
  5533. ** The commit and rollback hook callbacks are not reentrant.
  5534. ** The callback implementation must not do anything that will modify
  5535. ** the database connection that invoked the callback. Any actions
  5536. ** to modify the database connection must be deferred until after the
  5537. ** completion of the [sqlite3_step()] call that triggered the commit
  5538. ** or rollback hook in the first place.
  5539. ** Note that running any other SQL statements, including SELECT statements,
  5540. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  5541. ** the database connections for the meaning of "modify" in this paragraph.
  5542. **
  5543. ** ^Registering a NULL function disables the callback.
  5544. **
  5545. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  5546. ** operation is allowed to continue normally. ^If the commit hook
  5547. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  5548. ** ^The rollback hook is invoked on a rollback that results from a commit
  5549. ** hook returning non-zero, just as it would be with any other rollback.
  5550. **
  5551. ** ^For the purposes of this API, a transaction is said to have been
  5552. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  5553. ** an error or constraint causes an implicit rollback to occur.
  5554. ** ^The rollback callback is not invoked if a transaction is
  5555. ** automatically rolled back because the database connection is closed.
  5556. **
  5557. ** See also the [sqlite3_update_hook()] interface.
  5558. */
  5559. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  5560. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  5561. /*
  5562. ** CAPI3REF: Data Change Notification Callbacks
  5563. ** METHOD: sqlite3
  5564. **
  5565. ** ^The sqlite3_update_hook() interface registers a callback function
  5566. ** with the [database connection] identified by the first argument
  5567. ** to be invoked whenever a row is updated, inserted or deleted in
  5568. ** a [rowid table].
  5569. ** ^Any callback set by a previous call to this function
  5570. ** for the same database connection is overridden.
  5571. **
  5572. ** ^The second argument is a pointer to the function to invoke when a
  5573. ** row is updated, inserted or deleted in a rowid table.
  5574. ** ^The first argument to the callback is a copy of the third argument
  5575. ** to sqlite3_update_hook().
  5576. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  5577. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  5578. ** to be invoked.
  5579. ** ^The third and fourth arguments to the callback contain pointers to the
  5580. ** database and table name containing the affected row.
  5581. ** ^The final callback parameter is the [rowid] of the row.
  5582. ** ^In the case of an update, this is the [rowid] after the update takes place.
  5583. **
  5584. ** ^(The update hook is not invoked when internal system tables are
  5585. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  5586. ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  5587. **
  5588. ** ^In the current implementation, the update hook
  5589. ** is not invoked when conflicting rows are deleted because of an
  5590. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  5591. ** invoked when rows are deleted using the [truncate optimization].
  5592. ** The exceptions defined in this paragraph might change in a future
  5593. ** release of SQLite.
  5594. **
  5595. ** The update hook implementation must not do anything that will modify
  5596. ** the database connection that invoked the update hook. Any actions
  5597. ** to modify the database connection must be deferred until after the
  5598. ** completion of the [sqlite3_step()] call that triggered the update hook.
  5599. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  5600. ** database connections for the meaning of "modify" in this paragraph.
  5601. **
  5602. ** ^The sqlite3_update_hook(D,C,P) function
  5603. ** returns the P argument from the previous call
  5604. ** on the same [database connection] D, or NULL for
  5605. ** the first call on D.
  5606. **
  5607. ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
  5608. ** and [sqlite3_preupdate_hook()] interfaces.
  5609. */
  5610. SQLITE_API void *sqlite3_update_hook(
  5611. sqlite3*,
  5612. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  5613. void*
  5614. );
  5615. /*
  5616. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  5617. **
  5618. ** ^(This routine enables or disables the sharing of the database cache
  5619. ** and schema data structures between [database connection | connections]
  5620. ** to the same database. Sharing is enabled if the argument is true
  5621. ** and disabled if the argument is false.)^
  5622. **
  5623. ** ^Cache sharing is enabled and disabled for an entire process.
  5624. ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
  5625. ** In prior versions of SQLite,
  5626. ** sharing was enabled or disabled for each thread separately.
  5627. **
  5628. ** ^(The cache sharing mode set by this interface effects all subsequent
  5629. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  5630. ** Existing database connections continue use the sharing mode
  5631. ** that was in effect at the time they were opened.)^
  5632. **
  5633. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  5634. ** successfully. An [error code] is returned otherwise.)^
  5635. **
  5636. ** ^Shared cache is disabled by default. But this might change in
  5637. ** future releases of SQLite. Applications that care about shared
  5638. ** cache setting should set it explicitly.
  5639. **
  5640. ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
  5641. ** and will always return SQLITE_MISUSE. On those systems,
  5642. ** shared cache mode should be enabled per-database connection via
  5643. ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
  5644. **
  5645. ** This interface is threadsafe on processors where writing a
  5646. ** 32-bit integer is atomic.
  5647. **
  5648. ** See Also: [SQLite Shared-Cache Mode]
  5649. */
  5650. SQLITE_API int sqlite3_enable_shared_cache(int);
  5651. /*
  5652. ** CAPI3REF: Attempt To Free Heap Memory
  5653. **
  5654. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  5655. ** of heap memory by deallocating non-essential memory allocations
  5656. ** held by the database library. Memory used to cache database
  5657. ** pages to improve performance is an example of non-essential memory.
  5658. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  5659. ** which might be more or less than the amount requested.
  5660. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  5661. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5662. **
  5663. ** See also: [sqlite3_db_release_memory()]
  5664. */
  5665. SQLITE_API int sqlite3_release_memory(int);
  5666. /*
  5667. ** CAPI3REF: Free Memory Used By A Database Connection
  5668. ** METHOD: sqlite3
  5669. **
  5670. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  5671. ** memory as possible from database connection D. Unlike the
  5672. ** [sqlite3_release_memory()] interface, this interface is in effect even
  5673. ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  5674. ** omitted.
  5675. **
  5676. ** See also: [sqlite3_release_memory()]
  5677. */
  5678. SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  5679. /*
  5680. ** CAPI3REF: Impose A Limit On Heap Size
  5681. **
  5682. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  5683. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  5684. ** ^SQLite strives to keep heap memory utilization below the soft heap
  5685. ** limit by reducing the number of pages held in the page cache
  5686. ** as heap memory usages approaches the limit.
  5687. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  5688. ** below the limit, it will exceed the limit rather than generate
  5689. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  5690. ** is advisory only.
  5691. **
  5692. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  5693. ** the soft heap limit prior to the call, or negative in the case of an
  5694. ** error. ^If the argument N is negative
  5695. ** then no change is made to the soft heap limit. Hence, the current
  5696. ** size of the soft heap limit can be determined by invoking
  5697. ** sqlite3_soft_heap_limit64() with a negative argument.
  5698. **
  5699. ** ^If the argument N is zero then the soft heap limit is disabled.
  5700. **
  5701. ** ^(The soft heap limit is not enforced in the current implementation
  5702. ** if one or more of following conditions are true:
  5703. **
  5704. ** <ul>
  5705. ** <li> The soft heap limit is set to zero.
  5706. ** <li> Memory accounting is disabled using a combination of the
  5707. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  5708. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  5709. ** <li> An alternative page cache implementation is specified using
  5710. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  5711. ** <li> The page cache allocates from its own memory pool supplied
  5712. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  5713. ** from the heap.
  5714. ** </ul>)^
  5715. **
  5716. ** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]),
  5717. ** the soft heap limit is enforced
  5718. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  5719. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  5720. ** the soft heap limit is enforced on every memory allocation. Without
  5721. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  5722. ** when memory is allocated by the page cache. Testing suggests that because
  5723. ** the page cache is the predominate memory user in SQLite, most
  5724. ** applications will achieve adequate soft heap limit enforcement without
  5725. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5726. **
  5727. ** The circumstances under which SQLite will enforce the soft heap limit may
  5728. ** changes in future releases of SQLite.
  5729. */
  5730. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  5731. /*
  5732. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  5733. ** DEPRECATED
  5734. **
  5735. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  5736. ** interface. This routine is provided for historical compatibility
  5737. ** only. All new applications should use the
  5738. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  5739. */
  5740. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  5741. /*
  5742. ** CAPI3REF: Extract Metadata About A Column Of A Table
  5743. ** METHOD: sqlite3
  5744. **
  5745. ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
  5746. ** information about column C of table T in database D
  5747. ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
  5748. ** interface returns SQLITE_OK and fills in the non-NULL pointers in
  5749. ** the final five arguments with appropriate values if the specified
  5750. ** column exists. ^The sqlite3_table_column_metadata() interface returns
  5751. ** SQLITE_ERROR and if the specified column does not exist.
  5752. ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
  5753. ** NULL pointer, then this routine simply checks for the existence of the
  5754. ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
  5755. ** does not.
  5756. **
  5757. ** ^The column is identified by the second, third and fourth parameters to
  5758. ** this function. ^(The second parameter is either the name of the database
  5759. ** (i.e. "main", "temp", or an attached database) containing the specified
  5760. ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
  5761. ** for the table using the same algorithm used by the database engine to
  5762. ** resolve unqualified table references.
  5763. **
  5764. ** ^The third and fourth parameters to this function are the table and column
  5765. ** name of the desired column, respectively.
  5766. **
  5767. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  5768. ** and subsequent parameters to this function. ^Any of these arguments may be
  5769. ** NULL, in which case the corresponding element of metadata is omitted.
  5770. **
  5771. ** ^(<blockquote>
  5772. ** <table border="1">
  5773. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  5774. **
  5775. ** <tr><td> 5th <td> const char* <td> Data type
  5776. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  5777. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  5778. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  5779. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  5780. ** </table>
  5781. ** </blockquote>)^
  5782. **
  5783. ** ^The memory pointed to by the character pointers returned for the
  5784. ** declaration type and collation sequence is valid until the next
  5785. ** call to any SQLite API function.
  5786. **
  5787. ** ^If the specified table is actually a view, an [error code] is returned.
  5788. **
  5789. ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
  5790. ** is not a [WITHOUT ROWID] table and an
  5791. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  5792. ** parameters are set for the explicitly declared column. ^(If there is no
  5793. ** [INTEGER PRIMARY KEY] column, then the outputs
  5794. ** for the [rowid] are set as follows:
  5795. **
  5796. ** <pre>
  5797. ** data type: "INTEGER"
  5798. ** collation sequence: "BINARY"
  5799. ** not null: 0
  5800. ** primary key: 1
  5801. ** auto increment: 0
  5802. ** </pre>)^
  5803. **
  5804. ** ^This function causes all database schemas to be read from disk and
  5805. ** parsed, if that has not already been done, and returns an error if
  5806. ** any errors are encountered while loading the schema.
  5807. */
  5808. SQLITE_API int sqlite3_table_column_metadata(
  5809. sqlite3 *db, /* Connection handle */
  5810. const char *zDbName, /* Database name or NULL */
  5811. const char *zTableName, /* Table name */
  5812. const char *zColumnName, /* Column name */
  5813. char const **pzDataType, /* OUTPUT: Declared data type */
  5814. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  5815. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  5816. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  5817. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  5818. );
  5819. /*
  5820. ** CAPI3REF: Load An Extension
  5821. ** METHOD: sqlite3
  5822. **
  5823. ** ^This interface loads an SQLite extension library from the named file.
  5824. **
  5825. ** ^The sqlite3_load_extension() interface attempts to load an
  5826. ** [SQLite extension] library contained in the file zFile. If
  5827. ** the file cannot be loaded directly, attempts are made to load
  5828. ** with various operating-system specific extensions added.
  5829. ** So for example, if "samplelib" cannot be loaded, then names like
  5830. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  5831. ** be tried also.
  5832. **
  5833. ** ^The entry point is zProc.
  5834. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  5835. ** entry point name on its own. It first tries "sqlite3_extension_init".
  5836. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  5837. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  5838. ** characters in the filename from the last "/" to the first following
  5839. ** "." and omitting any initial "lib".)^
  5840. ** ^The sqlite3_load_extension() interface returns
  5841. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  5842. ** ^If an error occurs and pzErrMsg is not 0, then the
  5843. ** [sqlite3_load_extension()] interface shall attempt to
  5844. ** fill *pzErrMsg with error message text stored in memory
  5845. ** obtained from [sqlite3_malloc()]. The calling function
  5846. ** should free this memory by calling [sqlite3_free()].
  5847. **
  5848. ** ^Extension loading must be enabled using
  5849. ** [sqlite3_enable_load_extension()] or
  5850. ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
  5851. ** prior to calling this API,
  5852. ** otherwise an error will be returned.
  5853. **
  5854. ** <b>Security warning:</b> It is recommended that the
  5855. ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
  5856. ** interface. The use of the [sqlite3_enable_load_extension()] interface
  5857. ** should be avoided. This will keep the SQL function [load_extension()]
  5858. ** disabled and prevent SQL injections from giving attackers
  5859. ** access to extension loading capabilities.
  5860. **
  5861. ** See also the [load_extension() SQL function].
  5862. */
  5863. SQLITE_API int sqlite3_load_extension(
  5864. sqlite3 *db, /* Load the extension into this database connection */
  5865. const char *zFile, /* Name of the shared library containing extension */
  5866. const char *zProc, /* Entry point. Derived from zFile if 0 */
  5867. char **pzErrMsg /* Put error message here if not 0 */
  5868. );
  5869. /*
  5870. ** CAPI3REF: Enable Or Disable Extension Loading
  5871. ** METHOD: sqlite3
  5872. **
  5873. ** ^So as not to open security holes in older applications that are
  5874. ** unprepared to deal with [extension loading], and as a means of disabling
  5875. ** [extension loading] while evaluating user-entered SQL, the following API
  5876. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  5877. **
  5878. ** ^Extension loading is off by default.
  5879. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  5880. ** to turn extension loading on and call it with onoff==0 to turn
  5881. ** it back off again.
  5882. **
  5883. ** ^This interface enables or disables both the C-API
  5884. ** [sqlite3_load_extension()] and the SQL function [load_extension()].
  5885. ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
  5886. ** to enable or disable only the C-API.)^
  5887. **
  5888. ** <b>Security warning:</b> It is recommended that extension loading
  5889. ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
  5890. ** rather than this interface, so the [load_extension()] SQL function
  5891. ** remains disabled. This will prevent SQL injections from giving attackers
  5892. ** access to extension loading capabilities.
  5893. */
  5894. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  5895. /*
  5896. ** CAPI3REF: Automatically Load Statically Linked Extensions
  5897. **
  5898. ** ^This interface causes the xEntryPoint() function to be invoked for
  5899. ** each new [database connection] that is created. The idea here is that
  5900. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  5901. ** that is to be automatically loaded into all new database connections.
  5902. **
  5903. ** ^(Even though the function prototype shows that xEntryPoint() takes
  5904. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  5905. ** arguments and expects an integer result as if the signature of the
  5906. ** entry point where as follows:
  5907. **
  5908. ** <blockquote><pre>
  5909. ** &nbsp; int xEntryPoint(
  5910. ** &nbsp; sqlite3 *db,
  5911. ** &nbsp; const char **pzErrMsg,
  5912. ** &nbsp; const struct sqlite3_api_routines *pThunk
  5913. ** &nbsp; );
  5914. ** </pre></blockquote>)^
  5915. **
  5916. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  5917. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  5918. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  5919. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  5920. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  5921. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  5922. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  5923. **
  5924. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  5925. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  5926. ** will be called more than once for each database connection that is opened.
  5927. **
  5928. ** See also: [sqlite3_reset_auto_extension()]
  5929. ** and [sqlite3_cancel_auto_extension()]
  5930. */
  5931. SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
  5932. /*
  5933. ** CAPI3REF: Cancel Automatic Extension Loading
  5934. **
  5935. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  5936. ** initialization routine X that was registered using a prior call to
  5937. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  5938. ** routine returns 1 if initialization routine X was successfully
  5939. ** unregistered and it returns 0 if X was not on the list of initialization
  5940. ** routines.
  5941. */
  5942. SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
  5943. /*
  5944. ** CAPI3REF: Reset Automatic Extension Loading
  5945. **
  5946. ** ^This interface disables all automatic extensions previously
  5947. ** registered using [sqlite3_auto_extension()].
  5948. */
  5949. SQLITE_API void sqlite3_reset_auto_extension(void);
  5950. /*
  5951. ** The interface to the virtual-table mechanism is currently considered
  5952. ** to be experimental. The interface might change in incompatible ways.
  5953. ** If this is a problem for you, do not use the interface at this time.
  5954. **
  5955. ** When the virtual-table mechanism stabilizes, we will declare the
  5956. ** interface fixed, support it indefinitely, and remove this comment.
  5957. */
  5958. /*
  5959. ** Structures used by the virtual table interface
  5960. */
  5961. typedef struct sqlite3_vtab sqlite3_vtab;
  5962. typedef struct sqlite3_index_info sqlite3_index_info;
  5963. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  5964. typedef struct sqlite3_module sqlite3_module;
  5965. /*
  5966. ** CAPI3REF: Virtual Table Object
  5967. ** KEYWORDS: sqlite3_module {virtual table module}
  5968. **
  5969. ** This structure, sometimes called a "virtual table module",
  5970. ** defines the implementation of a [virtual tables].
  5971. ** This structure consists mostly of methods for the module.
  5972. **
  5973. ** ^A virtual table module is created by filling in a persistent
  5974. ** instance of this structure and passing a pointer to that instance
  5975. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  5976. ** ^The registration remains valid until it is replaced by a different
  5977. ** module or until the [database connection] closes. The content
  5978. ** of this structure must not change while it is registered with
  5979. ** any database connection.
  5980. */
  5981. struct sqlite3_module {
  5982. int iVersion;
  5983. int (*xCreate)(sqlite3*, void *pAux,
  5984. int argc, const char *const*argv,
  5985. sqlite3_vtab **ppVTab, char**);
  5986. int (*xConnect)(sqlite3*, void *pAux,
  5987. int argc, const char *const*argv,
  5988. sqlite3_vtab **ppVTab, char**);
  5989. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  5990. int (*xDisconnect)(sqlite3_vtab *pVTab);
  5991. int (*xDestroy)(sqlite3_vtab *pVTab);
  5992. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  5993. int (*xClose)(sqlite3_vtab_cursor*);
  5994. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  5995. int argc, sqlite3_value **argv);
  5996. int (*xNext)(sqlite3_vtab_cursor*);
  5997. int (*xEof)(sqlite3_vtab_cursor*);
  5998. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  5999. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  6000. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  6001. int (*xBegin)(sqlite3_vtab *pVTab);
  6002. int (*xSync)(sqlite3_vtab *pVTab);
  6003. int (*xCommit)(sqlite3_vtab *pVTab);
  6004. int (*xRollback)(sqlite3_vtab *pVTab);
  6005. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  6006. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  6007. void **ppArg);
  6008. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  6009. /* The methods above are in version 1 of the sqlite_module object. Those
  6010. ** below are for version 2 and greater. */
  6011. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  6012. int (*xRelease)(sqlite3_vtab *pVTab, int);
  6013. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  6014. };
  6015. /*
  6016. ** CAPI3REF: Virtual Table Indexing Information
  6017. ** KEYWORDS: sqlite3_index_info
  6018. **
  6019. ** The sqlite3_index_info structure and its substructures is used as part
  6020. ** of the [virtual table] interface to
  6021. ** pass information into and receive the reply from the [xBestIndex]
  6022. ** method of a [virtual table module]. The fields under **Inputs** are the
  6023. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  6024. ** results into the **Outputs** fields.
  6025. **
  6026. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  6027. **
  6028. ** <blockquote>column OP expr</blockquote>
  6029. **
  6030. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  6031. ** stored in aConstraint[].op using one of the
  6032. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  6033. ** ^(The index of the column is stored in
  6034. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  6035. ** expr on the right-hand side can be evaluated (and thus the constraint
  6036. ** is usable) and false if it cannot.)^
  6037. **
  6038. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  6039. ** and makes other simplifications to the WHERE clause in an attempt to
  6040. ** get as many WHERE clause terms into the form shown above as possible.
  6041. ** ^The aConstraint[] array only reports WHERE clause terms that are
  6042. ** relevant to the particular virtual table being queried.
  6043. **
  6044. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  6045. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  6046. **
  6047. ** The colUsed field indicates which columns of the virtual table may be
  6048. ** required by the current scan. Virtual table columns are numbered from
  6049. ** zero in the order in which they appear within the CREATE TABLE statement
  6050. ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
  6051. ** the corresponding bit is set within the colUsed mask if the column may be
  6052. ** required by SQLite. If the table has at least 64 columns and any column
  6053. ** to the right of the first 63 is required, then bit 63 of colUsed is also
  6054. ** set. In other words, column iCol may be required if the expression
  6055. ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
  6056. ** non-zero.
  6057. **
  6058. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  6059. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  6060. ** the right-hand side of the corresponding aConstraint[] is evaluated
  6061. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  6062. ** is true, then the constraint is assumed to be fully handled by the
  6063. ** virtual table and is not checked again by SQLite.)^
  6064. **
  6065. ** ^The idxNum and idxPtr values are recorded and passed into the
  6066. ** [xFilter] method.
  6067. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  6068. ** needToFreeIdxPtr is true.
  6069. **
  6070. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  6071. ** the correct order to satisfy the ORDER BY clause so that no separate
  6072. ** sorting step is required.
  6073. **
  6074. ** ^The estimatedCost value is an estimate of the cost of a particular
  6075. ** strategy. A cost of N indicates that the cost of the strategy is similar
  6076. ** to a linear scan of an SQLite table with N rows. A cost of log(N)
  6077. ** indicates that the expense of the operation is similar to that of a
  6078. ** binary search on a unique indexed field of an SQLite table with N rows.
  6079. **
  6080. ** ^The estimatedRows value is an estimate of the number of rows that
  6081. ** will be returned by the strategy.
  6082. **
  6083. ** The xBestIndex method may optionally populate the idxFlags field with a
  6084. ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
  6085. ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
  6086. ** assumes that the strategy may visit at most one row.
  6087. **
  6088. ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
  6089. ** SQLite also assumes that if a call to the xUpdate() method is made as
  6090. ** part of the same statement to delete or update a virtual table row and the
  6091. ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
  6092. ** any database changes. In other words, if the xUpdate() returns
  6093. ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
  6094. ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
  6095. ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
  6096. ** the xUpdate method are automatically rolled back by SQLite.
  6097. **
  6098. ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  6099. ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
  6100. ** If a virtual table extension is
  6101. ** used with an SQLite version earlier than 3.8.2, the results of attempting
  6102. ** to read or write the estimatedRows field are undefined (but are likely
  6103. ** to included crashing the application). The estimatedRows field should
  6104. ** therefore only be used if [sqlite3_libversion_number()] returns a
  6105. ** value greater than or equal to 3008002. Similarly, the idxFlags field
  6106. ** was added for [version 3.9.0] ([dateof:3.9.0]).
  6107. ** It may therefore only be used if
  6108. ** sqlite3_libversion_number() returns a value greater than or equal to
  6109. ** 3009000.
  6110. */
  6111. struct sqlite3_index_info {
  6112. /* Inputs */
  6113. int nConstraint; /* Number of entries in aConstraint */
  6114. struct sqlite3_index_constraint {
  6115. int iColumn; /* Column constrained. -1 for ROWID */
  6116. unsigned char op; /* Constraint operator */
  6117. unsigned char usable; /* True if this constraint is usable */
  6118. int iTermOffset; /* Used internally - xBestIndex should ignore */
  6119. } *aConstraint; /* Table of WHERE clause constraints */
  6120. int nOrderBy; /* Number of terms in the ORDER BY clause */
  6121. struct sqlite3_index_orderby {
  6122. int iColumn; /* Column number */
  6123. unsigned char desc; /* True for DESC. False for ASC. */
  6124. } *aOrderBy; /* The ORDER BY clause */
  6125. /* Outputs */
  6126. struct sqlite3_index_constraint_usage {
  6127. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  6128. unsigned char omit; /* Do not code a test for this constraint */
  6129. } *aConstraintUsage;
  6130. int idxNum; /* Number used to identify the index */
  6131. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  6132. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  6133. int orderByConsumed; /* True if output is already ordered */
  6134. double estimatedCost; /* Estimated cost of using this index */
  6135. /* Fields below are only available in SQLite 3.8.2 and later */
  6136. sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
  6137. /* Fields below are only available in SQLite 3.9.0 and later */
  6138. int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
  6139. /* Fields below are only available in SQLite 3.10.0 and later */
  6140. sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
  6141. };
  6142. /*
  6143. ** CAPI3REF: Virtual Table Scan Flags
  6144. */
  6145. #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
  6146. /*
  6147. ** CAPI3REF: Virtual Table Constraint Operator Codes
  6148. **
  6149. ** These macros defined the allowed values for the
  6150. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  6151. ** an operator that is part of a constraint term in the wHERE clause of
  6152. ** a query that uses a [virtual table].
  6153. */
  6154. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  6155. #define SQLITE_INDEX_CONSTRAINT_GT 4
  6156. #define SQLITE_INDEX_CONSTRAINT_LE 8
  6157. #define SQLITE_INDEX_CONSTRAINT_LT 16
  6158. #define SQLITE_INDEX_CONSTRAINT_GE 32
  6159. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  6160. #define SQLITE_INDEX_CONSTRAINT_LIKE 65
  6161. #define SQLITE_INDEX_CONSTRAINT_GLOB 66
  6162. #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
  6163. /*
  6164. ** CAPI3REF: Register A Virtual Table Implementation
  6165. ** METHOD: sqlite3
  6166. **
  6167. ** ^These routines are used to register a new [virtual table module] name.
  6168. ** ^Module names must be registered before
  6169. ** creating a new [virtual table] using the module and before using a
  6170. ** preexisting [virtual table] for the module.
  6171. **
  6172. ** ^The module name is registered on the [database connection] specified
  6173. ** by the first parameter. ^The name of the module is given by the
  6174. ** second parameter. ^The third parameter is a pointer to
  6175. ** the implementation of the [virtual table module]. ^The fourth
  6176. ** parameter is an arbitrary client data pointer that is passed through
  6177. ** into the [xCreate] and [xConnect] methods of the virtual table module
  6178. ** when a new virtual table is be being created or reinitialized.
  6179. **
  6180. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  6181. ** is a pointer to a destructor for the pClientData. ^SQLite will
  6182. ** invoke the destructor function (if it is not NULL) when SQLite
  6183. ** no longer needs the pClientData pointer. ^The destructor will also
  6184. ** be invoked if the call to sqlite3_create_module_v2() fails.
  6185. ** ^The sqlite3_create_module()
  6186. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  6187. ** destructor.
  6188. */
  6189. SQLITE_API int sqlite3_create_module(
  6190. sqlite3 *db, /* SQLite connection to register module with */
  6191. const char *zName, /* Name of the module */
  6192. const sqlite3_module *p, /* Methods for the module */
  6193. void *pClientData /* Client data for xCreate/xConnect */
  6194. );
  6195. SQLITE_API int sqlite3_create_module_v2(
  6196. sqlite3 *db, /* SQLite connection to register module with */
  6197. const char *zName, /* Name of the module */
  6198. const sqlite3_module *p, /* Methods for the module */
  6199. void *pClientData, /* Client data for xCreate/xConnect */
  6200. void(*xDestroy)(void*) /* Module destructor function */
  6201. );
  6202. /*
  6203. ** CAPI3REF: Virtual Table Instance Object
  6204. ** KEYWORDS: sqlite3_vtab
  6205. **
  6206. ** Every [virtual table module] implementation uses a subclass
  6207. ** of this object to describe a particular instance
  6208. ** of the [virtual table]. Each subclass will
  6209. ** be tailored to the specific needs of the module implementation.
  6210. ** The purpose of this superclass is to define certain fields that are
  6211. ** common to all module implementations.
  6212. **
  6213. ** ^Virtual tables methods can set an error message by assigning a
  6214. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  6215. ** take care that any prior string is freed by a call to [sqlite3_free()]
  6216. ** prior to assigning a new string to zErrMsg. ^After the error message
  6217. ** is delivered up to the client application, the string will be automatically
  6218. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  6219. */
  6220. struct sqlite3_vtab {
  6221. const sqlite3_module *pModule; /* The module for this virtual table */
  6222. int nRef; /* Number of open cursors */
  6223. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  6224. /* Virtual table implementations will typically add additional fields */
  6225. };
  6226. /*
  6227. ** CAPI3REF: Virtual Table Cursor Object
  6228. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  6229. **
  6230. ** Every [virtual table module] implementation uses a subclass of the
  6231. ** following structure to describe cursors that point into the
  6232. ** [virtual table] and are used
  6233. ** to loop through the virtual table. Cursors are created using the
  6234. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  6235. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  6236. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  6237. ** of the module. Each module implementation will define
  6238. ** the content of a cursor structure to suit its own needs.
  6239. **
  6240. ** This superclass exists in order to define fields of the cursor that
  6241. ** are common to all implementations.
  6242. */
  6243. struct sqlite3_vtab_cursor {
  6244. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  6245. /* Virtual table implementations will typically add additional fields */
  6246. };
  6247. /*
  6248. ** CAPI3REF: Declare The Schema Of A Virtual Table
  6249. **
  6250. ** ^The [xCreate] and [xConnect] methods of a
  6251. ** [virtual table module] call this interface
  6252. ** to declare the format (the names and datatypes of the columns) of
  6253. ** the virtual tables they implement.
  6254. */
  6255. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  6256. /*
  6257. ** CAPI3REF: Overload A Function For A Virtual Table
  6258. ** METHOD: sqlite3
  6259. **
  6260. ** ^(Virtual tables can provide alternative implementations of functions
  6261. ** using the [xFindFunction] method of the [virtual table module].
  6262. ** But global versions of those functions
  6263. ** must exist in order to be overloaded.)^
  6264. **
  6265. ** ^(This API makes sure a global version of a function with a particular
  6266. ** name and number of parameters exists. If no such function exists
  6267. ** before this API is called, a new function is created.)^ ^The implementation
  6268. ** of the new function always causes an exception to be thrown. So
  6269. ** the new function is not good for anything by itself. Its only
  6270. ** purpose is to be a placeholder function that can be overloaded
  6271. ** by a [virtual table].
  6272. */
  6273. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  6274. /*
  6275. ** The interface to the virtual-table mechanism defined above (back up
  6276. ** to a comment remarkably similar to this one) is currently considered
  6277. ** to be experimental. The interface might change in incompatible ways.
  6278. ** If this is a problem for you, do not use the interface at this time.
  6279. **
  6280. ** When the virtual-table mechanism stabilizes, we will declare the
  6281. ** interface fixed, support it indefinitely, and remove this comment.
  6282. */
  6283. /*
  6284. ** CAPI3REF: A Handle To An Open BLOB
  6285. ** KEYWORDS: {BLOB handle} {BLOB handles}
  6286. **
  6287. ** An instance of this object represents an open BLOB on which
  6288. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  6289. ** ^Objects of this type are created by [sqlite3_blob_open()]
  6290. ** and destroyed by [sqlite3_blob_close()].
  6291. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  6292. ** can be used to read or write small subsections of the BLOB.
  6293. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  6294. */
  6295. typedef struct sqlite3_blob sqlite3_blob;
  6296. /*
  6297. ** CAPI3REF: Open A BLOB For Incremental I/O
  6298. ** METHOD: sqlite3
  6299. ** CONSTRUCTOR: sqlite3_blob
  6300. **
  6301. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  6302. ** in row iRow, column zColumn, table zTable in database zDb;
  6303. ** in other words, the same BLOB that would be selected by:
  6304. **
  6305. ** <pre>
  6306. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  6307. ** </pre>)^
  6308. **
  6309. ** ^(Parameter zDb is not the filename that contains the database, but
  6310. ** rather the symbolic name of the database. For attached databases, this is
  6311. ** the name that appears after the AS keyword in the [ATTACH] statement.
  6312. ** For the main database file, the database name is "main". For TEMP
  6313. ** tables, the database name is "temp".)^
  6314. **
  6315. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  6316. ** and write access. ^If the flags parameter is zero, the BLOB is opened for
  6317. ** read-only access.
  6318. **
  6319. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
  6320. ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
  6321. ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
  6322. ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
  6323. ** on *ppBlob after this function it returns.
  6324. **
  6325. ** This function fails with SQLITE_ERROR if any of the following are true:
  6326. ** <ul>
  6327. ** <li> ^(Database zDb does not exist)^,
  6328. ** <li> ^(Table zTable does not exist within database zDb)^,
  6329. ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
  6330. ** <li> ^(Column zColumn does not exist)^,
  6331. ** <li> ^(Row iRow is not present in the table)^,
  6332. ** <li> ^(The specified column of row iRow contains a value that is not
  6333. ** a TEXT or BLOB value)^,
  6334. ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
  6335. ** constraint and the blob is being opened for read/write access)^,
  6336. ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
  6337. ** column zColumn is part of a [child key] definition and the blob is
  6338. ** being opened for read/write access)^.
  6339. ** </ul>
  6340. **
  6341. ** ^Unless it returns SQLITE_MISUSE, this function sets the
  6342. ** [database connection] error code and message accessible via
  6343. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  6344. **
  6345. ** A BLOB referenced by sqlite3_blob_open() may be read using the
  6346. ** [sqlite3_blob_read()] interface and modified by using
  6347. ** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a
  6348. ** different row of the same table using the [sqlite3_blob_reopen()]
  6349. ** interface. However, the column, table, or database of a [BLOB handle]
  6350. ** cannot be changed after the [BLOB handle] is opened.
  6351. **
  6352. ** ^(If the row that a BLOB handle points to is modified by an
  6353. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  6354. ** then the BLOB handle is marked as "expired".
  6355. ** This is true if any column of the row is changed, even a column
  6356. ** other than the one the BLOB handle is open on.)^
  6357. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  6358. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  6359. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  6360. ** rolled back by the expiration of the BLOB. Such changes will eventually
  6361. ** commit if the transaction continues to completion.)^
  6362. **
  6363. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  6364. ** the opened blob. ^The size of a blob may not be changed by this
  6365. ** interface. Use the [UPDATE] SQL command to change the size of a
  6366. ** blob.
  6367. **
  6368. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  6369. ** and the built-in [zeroblob] SQL function may be used to create a
  6370. ** zero-filled blob to read or write using the incremental-blob interface.
  6371. **
  6372. ** To avoid a resource leak, every open [BLOB handle] should eventually
  6373. ** be released by a call to [sqlite3_blob_close()].
  6374. **
  6375. ** See also: [sqlite3_blob_close()],
  6376. ** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
  6377. ** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
  6378. */
  6379. SQLITE_API int sqlite3_blob_open(
  6380. sqlite3*,
  6381. const char *zDb,
  6382. const char *zTable,
  6383. const char *zColumn,
  6384. sqlite3_int64 iRow,
  6385. int flags,
  6386. sqlite3_blob **ppBlob
  6387. );
  6388. /*
  6389. ** CAPI3REF: Move a BLOB Handle to a New Row
  6390. ** METHOD: sqlite3_blob
  6391. **
  6392. ** ^This function is used to move an existing [BLOB handle] so that it points
  6393. ** to a different row of the same database table. ^The new row is identified
  6394. ** by the rowid value passed as the second argument. Only the row can be
  6395. ** changed. ^The database, table and column on which the blob handle is open
  6396. ** remain the same. Moving an existing [BLOB handle] to a new row is
  6397. ** faster than closing the existing handle and opening a new one.
  6398. **
  6399. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  6400. ** it must exist and there must be either a blob or text value stored in
  6401. ** the nominated column.)^ ^If the new row is not present in the table, or if
  6402. ** it does not contain a blob or text value, or if another error occurs, an
  6403. ** SQLite error code is returned and the blob handle is considered aborted.
  6404. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  6405. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  6406. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  6407. ** always returns zero.
  6408. **
  6409. ** ^This function sets the database handle error code and message.
  6410. */
  6411. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  6412. /*
  6413. ** CAPI3REF: Close A BLOB Handle
  6414. ** DESTRUCTOR: sqlite3_blob
  6415. **
  6416. ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
  6417. ** unconditionally. Even if this routine returns an error code, the
  6418. ** handle is still closed.)^
  6419. **
  6420. ** ^If the blob handle being closed was opened for read-write access, and if
  6421. ** the database is in auto-commit mode and there are no other open read-write
  6422. ** blob handles or active write statements, the current transaction is
  6423. ** committed. ^If an error occurs while committing the transaction, an error
  6424. ** code is returned and the transaction rolled back.
  6425. **
  6426. ** Calling this function with an argument that is not a NULL pointer or an
  6427. ** open blob handle results in undefined behaviour. ^Calling this routine
  6428. ** with a null pointer (such as would be returned by a failed call to
  6429. ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
  6430. ** is passed a valid open blob handle, the values returned by the
  6431. ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
  6432. */
  6433. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  6434. /*
  6435. ** CAPI3REF: Return The Size Of An Open BLOB
  6436. ** METHOD: sqlite3_blob
  6437. **
  6438. ** ^Returns the size in bytes of the BLOB accessible via the
  6439. ** successfully opened [BLOB handle] in its only argument. ^The
  6440. ** incremental blob I/O routines can only read or overwriting existing
  6441. ** blob content; they cannot change the size of a blob.
  6442. **
  6443. ** This routine only works on a [BLOB handle] which has been created
  6444. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6445. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6446. ** to this routine results in undefined and probably undesirable behavior.
  6447. */
  6448. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  6449. /*
  6450. ** CAPI3REF: Read Data From A BLOB Incrementally
  6451. ** METHOD: sqlite3_blob
  6452. **
  6453. ** ^(This function is used to read data from an open [BLOB handle] into a
  6454. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  6455. ** from the open BLOB, starting at offset iOffset.)^
  6456. **
  6457. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  6458. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  6459. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  6460. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  6461. ** can be determined using the [sqlite3_blob_bytes()] interface.
  6462. **
  6463. ** ^An attempt to read from an expired [BLOB handle] fails with an
  6464. ** error code of [SQLITE_ABORT].
  6465. **
  6466. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  6467. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  6468. **
  6469. ** This routine only works on a [BLOB handle] which has been created
  6470. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6471. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6472. ** to this routine results in undefined and probably undesirable behavior.
  6473. **
  6474. ** See also: [sqlite3_blob_write()].
  6475. */
  6476. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  6477. /*
  6478. ** CAPI3REF: Write Data Into A BLOB Incrementally
  6479. ** METHOD: sqlite3_blob
  6480. **
  6481. ** ^(This function is used to write data into an open [BLOB handle] from a
  6482. ** caller-supplied buffer. N bytes of data are copied from the buffer Z
  6483. ** into the open BLOB, starting at offset iOffset.)^
  6484. **
  6485. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  6486. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  6487. ** ^Unless SQLITE_MISUSE is returned, this function sets the
  6488. ** [database connection] error code and message accessible via
  6489. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  6490. **
  6491. ** ^If the [BLOB handle] passed as the first argument was not opened for
  6492. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  6493. ** this function returns [SQLITE_READONLY].
  6494. **
  6495. ** This function may only modify the contents of the BLOB; it is
  6496. ** not possible to increase the size of a BLOB using this API.
  6497. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  6498. ** [SQLITE_ERROR] is returned and no data is written. The size of the
  6499. ** BLOB (and hence the maximum value of N+iOffset) can be determined
  6500. ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
  6501. ** than zero [SQLITE_ERROR] is returned and no data is written.
  6502. **
  6503. ** ^An attempt to write to an expired [BLOB handle] fails with an
  6504. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  6505. ** before the [BLOB handle] expired are not rolled back by the
  6506. ** expiration of the handle, though of course those changes might
  6507. ** have been overwritten by the statement that expired the BLOB handle
  6508. ** or by other independent statements.
  6509. **
  6510. ** This routine only works on a [BLOB handle] which has been created
  6511. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6512. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6513. ** to this routine results in undefined and probably undesirable behavior.
  6514. **
  6515. ** See also: [sqlite3_blob_read()].
  6516. */
  6517. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  6518. /*
  6519. ** CAPI3REF: Virtual File System Objects
  6520. **
  6521. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  6522. ** that SQLite uses to interact
  6523. ** with the underlying operating system. Most SQLite builds come with a
  6524. ** single default VFS that is appropriate for the host computer.
  6525. ** New VFSes can be registered and existing VFSes can be unregistered.
  6526. ** The following interfaces are provided.
  6527. **
  6528. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  6529. ** ^Names are case sensitive.
  6530. ** ^Names are zero-terminated UTF-8 strings.
  6531. ** ^If there is no match, a NULL pointer is returned.
  6532. ** ^If zVfsName is NULL then the default VFS is returned.
  6533. **
  6534. ** ^New VFSes are registered with sqlite3_vfs_register().
  6535. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  6536. ** ^The same VFS can be registered multiple times without injury.
  6537. ** ^To make an existing VFS into the default VFS, register it again
  6538. ** with the makeDflt flag set. If two different VFSes with the
  6539. ** same name are registered, the behavior is undefined. If a
  6540. ** VFS is registered with a name that is NULL or an empty string,
  6541. ** then the behavior is undefined.
  6542. **
  6543. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  6544. ** ^(If the default VFS is unregistered, another VFS is chosen as
  6545. ** the default. The choice for the new VFS is arbitrary.)^
  6546. */
  6547. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  6548. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  6549. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  6550. /*
  6551. ** CAPI3REF: Mutexes
  6552. **
  6553. ** The SQLite core uses these routines for thread
  6554. ** synchronization. Though they are intended for internal
  6555. ** use by SQLite, code that links against SQLite is
  6556. ** permitted to use any of these routines.
  6557. **
  6558. ** The SQLite source code contains multiple implementations
  6559. ** of these mutex routines. An appropriate implementation
  6560. ** is selected automatically at compile-time. The following
  6561. ** implementations are available in the SQLite core:
  6562. **
  6563. ** <ul>
  6564. ** <li> SQLITE_MUTEX_PTHREADS
  6565. ** <li> SQLITE_MUTEX_W32
  6566. ** <li> SQLITE_MUTEX_NOOP
  6567. ** </ul>
  6568. **
  6569. ** The SQLITE_MUTEX_NOOP implementation is a set of routines
  6570. ** that does no real locking and is appropriate for use in
  6571. ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
  6572. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  6573. ** and Windows.
  6574. **
  6575. ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  6576. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  6577. ** implementation is included with the library. In this case the
  6578. ** application must supply a custom mutex implementation using the
  6579. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  6580. ** before calling sqlite3_initialize() or any other public sqlite3_
  6581. ** function that calls sqlite3_initialize().
  6582. **
  6583. ** ^The sqlite3_mutex_alloc() routine allocates a new
  6584. ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
  6585. ** routine returns NULL if it is unable to allocate the requested
  6586. ** mutex. The argument to sqlite3_mutex_alloc() must one of these
  6587. ** integer constants:
  6588. **
  6589. ** <ul>
  6590. ** <li> SQLITE_MUTEX_FAST
  6591. ** <li> SQLITE_MUTEX_RECURSIVE
  6592. ** <li> SQLITE_MUTEX_STATIC_MASTER
  6593. ** <li> SQLITE_MUTEX_STATIC_MEM
  6594. ** <li> SQLITE_MUTEX_STATIC_OPEN
  6595. ** <li> SQLITE_MUTEX_STATIC_PRNG
  6596. ** <li> SQLITE_MUTEX_STATIC_LRU
  6597. ** <li> SQLITE_MUTEX_STATIC_PMEM
  6598. ** <li> SQLITE_MUTEX_STATIC_APP1
  6599. ** <li> SQLITE_MUTEX_STATIC_APP2
  6600. ** <li> SQLITE_MUTEX_STATIC_APP3
  6601. ** <li> SQLITE_MUTEX_STATIC_VFS1
  6602. ** <li> SQLITE_MUTEX_STATIC_VFS2
  6603. ** <li> SQLITE_MUTEX_STATIC_VFS3
  6604. ** </ul>
  6605. **
  6606. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  6607. ** cause sqlite3_mutex_alloc() to create
  6608. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  6609. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  6610. ** The mutex implementation does not need to make a distinction
  6611. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  6612. ** not want to. SQLite will only request a recursive mutex in
  6613. ** cases where it really needs one. If a faster non-recursive mutex
  6614. ** implementation is available on the host platform, the mutex subsystem
  6615. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  6616. **
  6617. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  6618. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  6619. ** a pointer to a static preexisting mutex. ^Nine static mutexes are
  6620. ** used by the current version of SQLite. Future versions of SQLite
  6621. ** may add additional static mutexes. Static mutexes are for internal
  6622. ** use by SQLite only. Applications that use SQLite mutexes should
  6623. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  6624. ** SQLITE_MUTEX_RECURSIVE.
  6625. **
  6626. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  6627. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  6628. ** returns a different mutex on every call. ^For the static
  6629. ** mutex types, the same mutex is returned on every call that has
  6630. ** the same type number.
  6631. **
  6632. ** ^The sqlite3_mutex_free() routine deallocates a previously
  6633. ** allocated dynamic mutex. Attempting to deallocate a static
  6634. ** mutex results in undefined behavior.
  6635. **
  6636. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  6637. ** to enter a mutex. ^If another thread is already within the mutex,
  6638. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  6639. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  6640. ** upon successful entry. ^(Mutexes created using
  6641. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  6642. ** In such cases, the
  6643. ** mutex must be exited an equal number of times before another thread
  6644. ** can enter.)^ If the same thread tries to enter any mutex other
  6645. ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
  6646. **
  6647. ** ^(Some systems (for example, Windows 95) do not support the operation
  6648. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  6649. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  6650. ** sqlite3_mutex_try() as an optimization so this is acceptable
  6651. ** behavior.)^
  6652. **
  6653. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  6654. ** previously entered by the same thread. The behavior
  6655. ** is undefined if the mutex is not currently entered by the
  6656. ** calling thread or is not currently allocated.
  6657. **
  6658. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  6659. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  6660. ** behave as no-ops.
  6661. **
  6662. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  6663. */
  6664. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  6665. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  6666. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  6667. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  6668. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  6669. /*
  6670. ** CAPI3REF: Mutex Methods Object
  6671. **
  6672. ** An instance of this structure defines the low-level routines
  6673. ** used to allocate and use mutexes.
  6674. **
  6675. ** Usually, the default mutex implementations provided by SQLite are
  6676. ** sufficient, however the application has the option of substituting a custom
  6677. ** implementation for specialized deployments or systems for which SQLite
  6678. ** does not provide a suitable implementation. In this case, the application
  6679. ** creates and populates an instance of this structure to pass
  6680. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  6681. ** Additionally, an instance of this structure can be used as an
  6682. ** output variable when querying the system for the current mutex
  6683. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  6684. **
  6685. ** ^The xMutexInit method defined by this structure is invoked as
  6686. ** part of system initialization by the sqlite3_initialize() function.
  6687. ** ^The xMutexInit routine is called by SQLite exactly once for each
  6688. ** effective call to [sqlite3_initialize()].
  6689. **
  6690. ** ^The xMutexEnd method defined by this structure is invoked as
  6691. ** part of system shutdown by the sqlite3_shutdown() function. The
  6692. ** implementation of this method is expected to release all outstanding
  6693. ** resources obtained by the mutex methods implementation, especially
  6694. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  6695. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  6696. **
  6697. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  6698. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  6699. ** xMutexNotheld) implement the following interfaces (respectively):
  6700. **
  6701. ** <ul>
  6702. ** <li> [sqlite3_mutex_alloc()] </li>
  6703. ** <li> [sqlite3_mutex_free()] </li>
  6704. ** <li> [sqlite3_mutex_enter()] </li>
  6705. ** <li> [sqlite3_mutex_try()] </li>
  6706. ** <li> [sqlite3_mutex_leave()] </li>
  6707. ** <li> [sqlite3_mutex_held()] </li>
  6708. ** <li> [sqlite3_mutex_notheld()] </li>
  6709. ** </ul>)^
  6710. **
  6711. ** The only difference is that the public sqlite3_XXX functions enumerated
  6712. ** above silently ignore any invocations that pass a NULL pointer instead
  6713. ** of a valid mutex handle. The implementations of the methods defined
  6714. ** by this structure are not required to handle this case, the results
  6715. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  6716. ** (i.e. it is acceptable to provide an implementation that segfaults if
  6717. ** it is passed a NULL pointer).
  6718. **
  6719. ** The xMutexInit() method must be threadsafe. It must be harmless to
  6720. ** invoke xMutexInit() multiple times within the same process and without
  6721. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  6722. ** xMutexInit() must be no-ops.
  6723. **
  6724. ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  6725. ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
  6726. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  6727. ** memory allocation for a fast or recursive mutex.
  6728. **
  6729. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  6730. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  6731. ** If xMutexInit fails in any way, it is expected to clean up after itself
  6732. ** prior to returning.
  6733. */
  6734. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  6735. struct sqlite3_mutex_methods {
  6736. int (*xMutexInit)(void);
  6737. int (*xMutexEnd)(void);
  6738. sqlite3_mutex *(*xMutexAlloc)(int);
  6739. void (*xMutexFree)(sqlite3_mutex *);
  6740. void (*xMutexEnter)(sqlite3_mutex *);
  6741. int (*xMutexTry)(sqlite3_mutex *);
  6742. void (*xMutexLeave)(sqlite3_mutex *);
  6743. int (*xMutexHeld)(sqlite3_mutex *);
  6744. int (*xMutexNotheld)(sqlite3_mutex *);
  6745. };
  6746. /*
  6747. ** CAPI3REF: Mutex Verification Routines
  6748. **
  6749. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  6750. ** are intended for use inside assert() statements. The SQLite core
  6751. ** never uses these routines except inside an assert() and applications
  6752. ** are advised to follow the lead of the core. The SQLite core only
  6753. ** provides implementations for these routines when it is compiled
  6754. ** with the SQLITE_DEBUG flag. External mutex implementations
  6755. ** are only required to provide these routines if SQLITE_DEBUG is
  6756. ** defined and if NDEBUG is not defined.
  6757. **
  6758. ** These routines should return true if the mutex in their argument
  6759. ** is held or not held, respectively, by the calling thread.
  6760. **
  6761. ** The implementation is not required to provide versions of these
  6762. ** routines that actually work. If the implementation does not provide working
  6763. ** versions of these routines, it should at least provide stubs that always
  6764. ** return true so that one does not get spurious assertion failures.
  6765. **
  6766. ** If the argument to sqlite3_mutex_held() is a NULL pointer then
  6767. ** the routine should return 1. This seems counter-intuitive since
  6768. ** clearly the mutex cannot be held if it does not exist. But
  6769. ** the reason the mutex does not exist is because the build is not
  6770. ** using mutexes. And we do not want the assert() containing the
  6771. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  6772. ** the appropriate thing to do. The sqlite3_mutex_notheld()
  6773. ** interface should also return 1 when given a NULL pointer.
  6774. */
  6775. #ifndef NDEBUG
  6776. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  6777. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  6778. #endif
  6779. /*
  6780. ** CAPI3REF: Mutex Types
  6781. **
  6782. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  6783. ** which is one of these integer constants.
  6784. **
  6785. ** The set of static mutexes may change from one SQLite release to the
  6786. ** next. Applications that override the built-in mutex logic must be
  6787. ** prepared to accommodate additional static mutexes.
  6788. */
  6789. #define SQLITE_MUTEX_FAST 0
  6790. #define SQLITE_MUTEX_RECURSIVE 1
  6791. #define SQLITE_MUTEX_STATIC_MASTER 2
  6792. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  6793. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  6794. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  6795. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */
  6796. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  6797. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  6798. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  6799. #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
  6800. #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
  6801. #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
  6802. #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
  6803. #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
  6804. #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
  6805. /*
  6806. ** CAPI3REF: Retrieve the mutex for a database connection
  6807. ** METHOD: sqlite3
  6808. **
  6809. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  6810. ** serializes access to the [database connection] given in the argument
  6811. ** when the [threading mode] is Serialized.
  6812. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  6813. ** routine returns a NULL pointer.
  6814. */
  6815. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  6816. /*
  6817. ** CAPI3REF: Low-Level Control Of Database Files
  6818. ** METHOD: sqlite3
  6819. **
  6820. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  6821. ** xFileControl method for the [sqlite3_io_methods] object associated
  6822. ** with a particular database identified by the second argument. ^The
  6823. ** name of the database is "main" for the main database or "temp" for the
  6824. ** TEMP database, or the name that appears after the AS keyword for
  6825. ** databases that are added using the [ATTACH] SQL command.
  6826. ** ^A NULL pointer can be used in place of "main" to refer to the
  6827. ** main database file.
  6828. ** ^The third and fourth parameters to this routine
  6829. ** are passed directly through to the second and third parameters of
  6830. ** the xFileControl method. ^The return value of the xFileControl
  6831. ** method becomes the return value of this routine.
  6832. **
  6833. ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  6834. ** a pointer to the underlying [sqlite3_file] object to be written into
  6835. ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
  6836. ** case is a short-circuit path which does not actually invoke the
  6837. ** underlying sqlite3_io_methods.xFileControl method.
  6838. **
  6839. ** ^If the second parameter (zDbName) does not match the name of any
  6840. ** open database file, then SQLITE_ERROR is returned. ^This error
  6841. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  6842. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  6843. ** also return SQLITE_ERROR. There is no way to distinguish between
  6844. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  6845. ** xFileControl method.
  6846. **
  6847. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  6848. */
  6849. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  6850. /*
  6851. ** CAPI3REF: Testing Interface
  6852. **
  6853. ** ^The sqlite3_test_control() interface is used to read out internal
  6854. ** state of SQLite and to inject faults into SQLite for testing
  6855. ** purposes. ^The first parameter is an operation code that determines
  6856. ** the number, meaning, and operation of all subsequent parameters.
  6857. **
  6858. ** This interface is not for use by applications. It exists solely
  6859. ** for verifying the correct operation of the SQLite library. Depending
  6860. ** on how the SQLite library is compiled, this interface might not exist.
  6861. **
  6862. ** The details of the operation codes, their meanings, the parameters
  6863. ** they take, and what they do are all subject to change without notice.
  6864. ** Unlike most of the SQLite API, this function is not guaranteed to
  6865. ** operate consistently from one release to the next.
  6866. */
  6867. SQLITE_API int sqlite3_test_control(int op, ...);
  6868. /*
  6869. ** CAPI3REF: Testing Interface Operation Codes
  6870. **
  6871. ** These constants are the valid operation code parameters used
  6872. ** as the first argument to [sqlite3_test_control()].
  6873. **
  6874. ** These parameters and their meanings are subject to change
  6875. ** without notice. These values are for testing purposes only.
  6876. ** Applications should not use any of these parameters or the
  6877. ** [sqlite3_test_control()] interface.
  6878. */
  6879. #define SQLITE_TESTCTRL_FIRST 5
  6880. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  6881. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  6882. #define SQLITE_TESTCTRL_PRNG_RESET 7
  6883. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  6884. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  6885. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  6886. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  6887. #define SQLITE_TESTCTRL_ASSERT 12
  6888. #define SQLITE_TESTCTRL_ALWAYS 13
  6889. #define SQLITE_TESTCTRL_RESERVE 14
  6890. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  6891. #define SQLITE_TESTCTRL_ISKEYWORD 16
  6892. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
  6893. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  6894. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
  6895. #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19
  6896. #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
  6897. #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
  6898. #define SQLITE_TESTCTRL_BYTEORDER 22
  6899. #define SQLITE_TESTCTRL_ISINIT 23
  6900. #define SQLITE_TESTCTRL_SORTER_MMAP 24
  6901. #define SQLITE_TESTCTRL_IMPOSTER 25
  6902. #define SQLITE_TESTCTRL_LAST 25
  6903. /*
  6904. ** CAPI3REF: SQLite Runtime Status
  6905. **
  6906. ** ^These interfaces are used to retrieve runtime status information
  6907. ** about the performance of SQLite, and optionally to reset various
  6908. ** highwater marks. ^The first argument is an integer code for
  6909. ** the specific parameter to measure. ^(Recognized integer codes
  6910. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  6911. ** ^The current value of the parameter is returned into *pCurrent.
  6912. ** ^The highest recorded value is returned in *pHighwater. ^If the
  6913. ** resetFlag is true, then the highest record value is reset after
  6914. ** *pHighwater is written. ^(Some parameters do not record the highest
  6915. ** value. For those parameters
  6916. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  6917. ** ^(Other parameters record only the highwater mark and not the current
  6918. ** value. For these latter parameters nothing is written into *pCurrent.)^
  6919. **
  6920. ** ^The sqlite3_status() and sqlite3_status64() routines return
  6921. ** SQLITE_OK on success and a non-zero [error code] on failure.
  6922. **
  6923. ** If either the current value or the highwater mark is too large to
  6924. ** be represented by a 32-bit integer, then the values returned by
  6925. ** sqlite3_status() are undefined.
  6926. **
  6927. ** See also: [sqlite3_db_status()]
  6928. */
  6929. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  6930. SQLITE_API int sqlite3_status64(
  6931. int op,
  6932. sqlite3_int64 *pCurrent,
  6933. sqlite3_int64 *pHighwater,
  6934. int resetFlag
  6935. );
  6936. /*
  6937. ** CAPI3REF: Status Parameters
  6938. ** KEYWORDS: {status parameters}
  6939. **
  6940. ** These integer constants designate various run-time status parameters
  6941. ** that can be returned by [sqlite3_status()].
  6942. **
  6943. ** <dl>
  6944. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  6945. ** <dd>This parameter is the current amount of memory checked out
  6946. ** using [sqlite3_malloc()], either directly or indirectly. The
  6947. ** figure includes calls made to [sqlite3_malloc()] by the application
  6948. ** and internal memory usage by the SQLite library. Scratch memory
  6949. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  6950. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  6951. ** this parameter. The amount returned is the sum of the allocation
  6952. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  6953. **
  6954. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  6955. ** <dd>This parameter records the largest memory allocation request
  6956. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  6957. ** internal equivalents). Only the value returned in the
  6958. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6959. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6960. **
  6961. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  6962. ** <dd>This parameter records the number of separate memory allocations
  6963. ** currently checked out.</dd>)^
  6964. **
  6965. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  6966. ** <dd>This parameter returns the number of pages used out of the
  6967. ** [pagecache memory allocator] that was configured using
  6968. ** [SQLITE_CONFIG_PAGECACHE]. The
  6969. ** value returned is in pages, not in bytes.</dd>)^
  6970. **
  6971. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  6972. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  6973. ** <dd>This parameter returns the number of bytes of page cache
  6974. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  6975. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  6976. ** returned value includes allocations that overflowed because they
  6977. ** where too large (they were larger than the "sz" parameter to
  6978. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  6979. ** no space was left in the page cache.</dd>)^
  6980. **
  6981. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  6982. ** <dd>This parameter records the largest memory allocation request
  6983. ** handed to [pagecache memory allocator]. Only the value returned in the
  6984. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6985. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6986. **
  6987. ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
  6988. ** <dd>This parameter returns the number of allocations used out of the
  6989. ** [scratch memory allocator] configured using
  6990. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  6991. ** in bytes. Since a single thread may only have one scratch allocation
  6992. ** outstanding at time, this parameter also reports the number of threads
  6993. ** using scratch memory at the same time.</dd>)^
  6994. **
  6995. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  6996. ** <dd>This parameter returns the number of bytes of scratch memory
  6997. ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
  6998. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  6999. ** returned include overflows because the requested allocation was too
  7000. ** larger (that is, because the requested allocation was larger than the
  7001. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  7002. ** slots were available.
  7003. ** </dd>)^
  7004. **
  7005. ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  7006. ** <dd>This parameter records the largest memory allocation request
  7007. ** handed to [scratch memory allocator]. Only the value returned in the
  7008. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  7009. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  7010. **
  7011. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  7012. ** <dd>The *pHighwater parameter records the deepest parser stack.
  7013. ** The *pCurrent value is undefined. The *pHighwater value is only
  7014. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  7015. ** </dl>
  7016. **
  7017. ** New status parameters may be added from time to time.
  7018. */
  7019. #define SQLITE_STATUS_MEMORY_USED 0
  7020. #define SQLITE_STATUS_PAGECACHE_USED 1
  7021. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  7022. #define SQLITE_STATUS_SCRATCH_USED 3
  7023. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  7024. #define SQLITE_STATUS_MALLOC_SIZE 5
  7025. #define SQLITE_STATUS_PARSER_STACK 6
  7026. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  7027. #define SQLITE_STATUS_SCRATCH_SIZE 8
  7028. #define SQLITE_STATUS_MALLOC_COUNT 9
  7029. /*
  7030. ** CAPI3REF: Database Connection Status
  7031. ** METHOD: sqlite3
  7032. **
  7033. ** ^This interface is used to retrieve runtime status information
  7034. ** about a single [database connection]. ^The first argument is the
  7035. ** database connection object to be interrogated. ^The second argument
  7036. ** is an integer constant, taken from the set of
  7037. ** [SQLITE_DBSTATUS options], that
  7038. ** determines the parameter to interrogate. The set of
  7039. ** [SQLITE_DBSTATUS options] is likely
  7040. ** to grow in future releases of SQLite.
  7041. **
  7042. ** ^The current value of the requested parameter is written into *pCur
  7043. ** and the highest instantaneous value is written into *pHiwtr. ^If
  7044. ** the resetFlg is true, then the highest instantaneous value is
  7045. ** reset back down to the current value.
  7046. **
  7047. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  7048. ** non-zero [error code] on failure.
  7049. **
  7050. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  7051. */
  7052. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  7053. /*
  7054. ** CAPI3REF: Status Parameters for database connections
  7055. ** KEYWORDS: {SQLITE_DBSTATUS options}
  7056. **
  7057. ** These constants are the available integer "verbs" that can be passed as
  7058. ** the second argument to the [sqlite3_db_status()] interface.
  7059. **
  7060. ** New verbs may be added in future releases of SQLite. Existing verbs
  7061. ** might be discontinued. Applications should check the return code from
  7062. ** [sqlite3_db_status()] to make sure that the call worked.
  7063. ** The [sqlite3_db_status()] interface will return a non-zero error code
  7064. ** if a discontinued or unsupported verb is invoked.
  7065. **
  7066. ** <dl>
  7067. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  7068. ** <dd>This parameter returns the number of lookaside memory slots currently
  7069. ** checked out.</dd>)^
  7070. **
  7071. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  7072. ** <dd>This parameter returns the number malloc attempts that were
  7073. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  7074. ** the current value is always zero.)^
  7075. **
  7076. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  7077. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  7078. ** <dd>This parameter returns the number malloc attempts that might have
  7079. ** been satisfied using lookaside memory but failed due to the amount of
  7080. ** memory requested being larger than the lookaside slot size.
  7081. ** Only the high-water value is meaningful;
  7082. ** the current value is always zero.)^
  7083. **
  7084. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  7085. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  7086. ** <dd>This parameter returns the number malloc attempts that might have
  7087. ** been satisfied using lookaside memory but failed due to all lookaside
  7088. ** memory already being in use.
  7089. ** Only the high-water value is meaningful;
  7090. ** the current value is always zero.)^
  7091. **
  7092. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  7093. ** <dd>This parameter returns the approximate number of bytes of heap
  7094. ** memory used by all pager caches associated with the database connection.)^
  7095. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  7096. **
  7097. ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
  7098. ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
  7099. ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
  7100. ** pager cache is shared between two or more connections the bytes of heap
  7101. ** memory used by that pager cache is divided evenly between the attached
  7102. ** connections.)^ In other words, if none of the pager caches associated
  7103. ** with the database connection are shared, this request returns the same
  7104. ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
  7105. ** shared, the value returned by this call will be smaller than that returned
  7106. ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
  7107. ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
  7108. **
  7109. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  7110. ** <dd>This parameter returns the approximate number of bytes of heap
  7111. ** memory used to store the schema for all databases associated
  7112. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  7113. ** ^The full amount of memory used by the schemas is reported, even if the
  7114. ** schema memory is shared with other database connections due to
  7115. ** [shared cache mode] being enabled.
  7116. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  7117. **
  7118. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  7119. ** <dd>This parameter returns the approximate number of bytes of heap
  7120. ** and lookaside memory used by all prepared statements associated with
  7121. ** the database connection.)^
  7122. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  7123. ** </dd>
  7124. **
  7125. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  7126. ** <dd>This parameter returns the number of pager cache hits that have
  7127. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  7128. ** is always 0.
  7129. ** </dd>
  7130. **
  7131. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  7132. ** <dd>This parameter returns the number of pager cache misses that have
  7133. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  7134. ** is always 0.
  7135. ** </dd>
  7136. **
  7137. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  7138. ** <dd>This parameter returns the number of dirty cache entries that have
  7139. ** been written to disk. Specifically, the number of pages written to the
  7140. ** wal file in wal mode databases, or the number of pages written to the
  7141. ** database file in rollback mode databases. Any pages written as part of
  7142. ** transaction rollback or database recovery operations are not included.
  7143. ** If an IO or other error occurs while writing a page to disk, the effect
  7144. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  7145. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  7146. ** </dd>
  7147. **
  7148. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  7149. ** <dd>This parameter returns zero for the current value if and only if
  7150. ** all foreign key constraints (deferred or immediate) have been
  7151. ** resolved.)^ ^The highwater mark is always 0.
  7152. ** </dd>
  7153. ** </dl>
  7154. */
  7155. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  7156. #define SQLITE_DBSTATUS_CACHE_USED 1
  7157. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  7158. #define SQLITE_DBSTATUS_STMT_USED 3
  7159. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  7160. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  7161. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  7162. #define SQLITE_DBSTATUS_CACHE_HIT 7
  7163. #define SQLITE_DBSTATUS_CACHE_MISS 8
  7164. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  7165. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  7166. #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11
  7167. #define SQLITE_DBSTATUS_MAX 11 /* Largest defined DBSTATUS */
  7168. /*
  7169. ** CAPI3REF: Prepared Statement Status
  7170. ** METHOD: sqlite3_stmt
  7171. **
  7172. ** ^(Each prepared statement maintains various
  7173. ** [SQLITE_STMTSTATUS counters] that measure the number
  7174. ** of times it has performed specific operations.)^ These counters can
  7175. ** be used to monitor the performance characteristics of the prepared
  7176. ** statements. For example, if the number of table steps greatly exceeds
  7177. ** the number of table searches or result rows, that would tend to indicate
  7178. ** that the prepared statement is using a full table scan rather than
  7179. ** an index.
  7180. **
  7181. ** ^(This interface is used to retrieve and reset counter values from
  7182. ** a [prepared statement]. The first argument is the prepared statement
  7183. ** object to be interrogated. The second argument
  7184. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  7185. ** to be interrogated.)^
  7186. ** ^The current value of the requested counter is returned.
  7187. ** ^If the resetFlg is true, then the counter is reset to zero after this
  7188. ** interface call returns.
  7189. **
  7190. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  7191. */
  7192. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  7193. /*
  7194. ** CAPI3REF: Status Parameters for prepared statements
  7195. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  7196. **
  7197. ** These preprocessor macros define integer codes that name counter
  7198. ** values associated with the [sqlite3_stmt_status()] interface.
  7199. ** The meanings of the various counters are as follows:
  7200. **
  7201. ** <dl>
  7202. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  7203. ** <dd>^This is the number of times that SQLite has stepped forward in
  7204. ** a table as part of a full table scan. Large numbers for this counter
  7205. ** may indicate opportunities for performance improvement through
  7206. ** careful use of indices.</dd>
  7207. **
  7208. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  7209. ** <dd>^This is the number of sort operations that have occurred.
  7210. ** A non-zero value in this counter may indicate an opportunity to
  7211. ** improvement performance through careful use of indices.</dd>
  7212. **
  7213. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  7214. ** <dd>^This is the number of rows inserted into transient indices that
  7215. ** were created automatically in order to help joins run faster.
  7216. ** A non-zero value in this counter may indicate an opportunity to
  7217. ** improvement performance by adding permanent indices that do not
  7218. ** need to be reinitialized each time the statement is run.</dd>
  7219. **
  7220. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  7221. ** <dd>^This is the number of virtual machine operations executed
  7222. ** by the prepared statement if that number is less than or equal
  7223. ** to 2147483647. The number of virtual machine operations can be
  7224. ** used as a proxy for the total work done by the prepared statement.
  7225. ** If the number of virtual machine operations exceeds 2147483647
  7226. ** then the value returned by this statement status code is undefined.
  7227. ** </dd>
  7228. ** </dl>
  7229. */
  7230. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  7231. #define SQLITE_STMTSTATUS_SORT 2
  7232. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  7233. #define SQLITE_STMTSTATUS_VM_STEP 4
  7234. /*
  7235. ** CAPI3REF: Custom Page Cache Object
  7236. **
  7237. ** The sqlite3_pcache type is opaque. It is implemented by
  7238. ** the pluggable module. The SQLite core has no knowledge of
  7239. ** its size or internal structure and never deals with the
  7240. ** sqlite3_pcache object except by holding and passing pointers
  7241. ** to the object.
  7242. **
  7243. ** See [sqlite3_pcache_methods2] for additional information.
  7244. */
  7245. typedef struct sqlite3_pcache sqlite3_pcache;
  7246. /*
  7247. ** CAPI3REF: Custom Page Cache Object
  7248. **
  7249. ** The sqlite3_pcache_page object represents a single page in the
  7250. ** page cache. The page cache will allocate instances of this
  7251. ** object. Various methods of the page cache use pointers to instances
  7252. ** of this object as parameters or as their return value.
  7253. **
  7254. ** See [sqlite3_pcache_methods2] for additional information.
  7255. */
  7256. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  7257. struct sqlite3_pcache_page {
  7258. void *pBuf; /* The content of the page */
  7259. void *pExtra; /* Extra information associated with the page */
  7260. };
  7261. /*
  7262. ** CAPI3REF: Application Defined Page Cache.
  7263. ** KEYWORDS: {page cache}
  7264. **
  7265. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  7266. ** register an alternative page cache implementation by passing in an
  7267. ** instance of the sqlite3_pcache_methods2 structure.)^
  7268. ** In many applications, most of the heap memory allocated by
  7269. ** SQLite is used for the page cache.
  7270. ** By implementing a
  7271. ** custom page cache using this API, an application can better control
  7272. ** the amount of memory consumed by SQLite, the way in which
  7273. ** that memory is allocated and released, and the policies used to
  7274. ** determine exactly which parts of a database file are cached and for
  7275. ** how long.
  7276. **
  7277. ** The alternative page cache mechanism is an
  7278. ** extreme measure that is only needed by the most demanding applications.
  7279. ** The built-in page cache is recommended for most uses.
  7280. **
  7281. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  7282. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  7283. ** the application may discard the parameter after the call to
  7284. ** [sqlite3_config()] returns.)^
  7285. **
  7286. ** [[the xInit() page cache method]]
  7287. ** ^(The xInit() method is called once for each effective
  7288. ** call to [sqlite3_initialize()])^
  7289. ** (usually only once during the lifetime of the process). ^(The xInit()
  7290. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  7291. ** The intent of the xInit() method is to set up global data structures
  7292. ** required by the custom page cache implementation.
  7293. ** ^(If the xInit() method is NULL, then the
  7294. ** built-in default page cache is used instead of the application defined
  7295. ** page cache.)^
  7296. **
  7297. ** [[the xShutdown() page cache method]]
  7298. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  7299. ** It can be used to clean up
  7300. ** any outstanding resources before process shutdown, if required.
  7301. ** ^The xShutdown() method may be NULL.
  7302. **
  7303. ** ^SQLite automatically serializes calls to the xInit method,
  7304. ** so the xInit method need not be threadsafe. ^The
  7305. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  7306. ** not need to be threadsafe either. All other methods must be threadsafe
  7307. ** in multithreaded applications.
  7308. **
  7309. ** ^SQLite will never invoke xInit() more than once without an intervening
  7310. ** call to xShutdown().
  7311. **
  7312. ** [[the xCreate() page cache methods]]
  7313. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  7314. ** SQLite will typically create one cache instance for each open database file,
  7315. ** though this is not guaranteed. ^The
  7316. ** first parameter, szPage, is the size in bytes of the pages that must
  7317. ** be allocated by the cache. ^szPage will always a power of two. ^The
  7318. ** second parameter szExtra is a number of bytes of extra storage
  7319. ** associated with each page cache entry. ^The szExtra parameter will
  7320. ** a number less than 250. SQLite will use the
  7321. ** extra szExtra bytes on each page to store metadata about the underlying
  7322. ** database page on disk. The value passed into szExtra depends
  7323. ** on the SQLite version, the target platform, and how SQLite was compiled.
  7324. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  7325. ** created will be used to cache database pages of a file stored on disk, or
  7326. ** false if it is used for an in-memory database. The cache implementation
  7327. ** does not have to do anything special based with the value of bPurgeable;
  7328. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  7329. ** never invoke xUnpin() except to deliberately delete a page.
  7330. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  7331. ** false will always have the "discard" flag set to true.
  7332. ** ^Hence, a cache created with bPurgeable false will
  7333. ** never contain any unpinned pages.
  7334. **
  7335. ** [[the xCachesize() page cache method]]
  7336. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  7337. ** suggested maximum cache-size (number of pages stored by) the cache
  7338. ** instance passed as the first argument. This is the value configured using
  7339. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  7340. ** parameter, the implementation is not required to do anything with this
  7341. ** value; it is advisory only.
  7342. **
  7343. ** [[the xPagecount() page cache methods]]
  7344. ** The xPagecount() method must return the number of pages currently
  7345. ** stored in the cache, both pinned and unpinned.
  7346. **
  7347. ** [[the xFetch() page cache methods]]
  7348. ** The xFetch() method locates a page in the cache and returns a pointer to
  7349. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  7350. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  7351. ** pointer to a buffer of szPage bytes used to store the content of a
  7352. ** single database page. The pExtra element of sqlite3_pcache_page will be
  7353. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  7354. ** for each entry in the page cache.
  7355. **
  7356. ** The page to be fetched is determined by the key. ^The minimum key value
  7357. ** is 1. After it has been retrieved using xFetch, the page is considered
  7358. ** to be "pinned".
  7359. **
  7360. ** If the requested page is already in the page cache, then the page cache
  7361. ** implementation must return a pointer to the page buffer with its content
  7362. ** intact. If the requested page is not already in the cache, then the
  7363. ** cache implementation should use the value of the createFlag
  7364. ** parameter to help it determined what action to take:
  7365. **
  7366. ** <table border=1 width=85% align=center>
  7367. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  7368. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  7369. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  7370. ** Otherwise return NULL.
  7371. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  7372. ** NULL if allocating a new page is effectively impossible.
  7373. ** </table>
  7374. **
  7375. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  7376. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  7377. ** failed.)^ In between the to xFetch() calls, SQLite may
  7378. ** attempt to unpin one or more cache pages by spilling the content of
  7379. ** pinned pages to disk and synching the operating system disk cache.
  7380. **
  7381. ** [[the xUnpin() page cache method]]
  7382. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  7383. ** as its second argument. If the third parameter, discard, is non-zero,
  7384. ** then the page must be evicted from the cache.
  7385. ** ^If the discard parameter is
  7386. ** zero, then the page may be discarded or retained at the discretion of
  7387. ** page cache implementation. ^The page cache implementation
  7388. ** may choose to evict unpinned pages at any time.
  7389. **
  7390. ** The cache must not perform any reference counting. A single
  7391. ** call to xUnpin() unpins the page regardless of the number of prior calls
  7392. ** to xFetch().
  7393. **
  7394. ** [[the xRekey() page cache methods]]
  7395. ** The xRekey() method is used to change the key value associated with the
  7396. ** page passed as the second argument. If the cache
  7397. ** previously contains an entry associated with newKey, it must be
  7398. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  7399. ** to be pinned.
  7400. **
  7401. ** When SQLite calls the xTruncate() method, the cache must discard all
  7402. ** existing cache entries with page numbers (keys) greater than or equal
  7403. ** to the value of the iLimit parameter passed to xTruncate(). If any
  7404. ** of these pages are pinned, they are implicitly unpinned, meaning that
  7405. ** they can be safely discarded.
  7406. **
  7407. ** [[the xDestroy() page cache method]]
  7408. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  7409. ** All resources associated with the specified cache should be freed. ^After
  7410. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  7411. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  7412. ** functions.
  7413. **
  7414. ** [[the xShrink() page cache method]]
  7415. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  7416. ** free up as much of heap memory as possible. The page cache implementation
  7417. ** is not obligated to free any memory, but well-behaved implementations should
  7418. ** do their best.
  7419. */
  7420. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  7421. struct sqlite3_pcache_methods2 {
  7422. int iVersion;
  7423. void *pArg;
  7424. int (*xInit)(void*);
  7425. void (*xShutdown)(void*);
  7426. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  7427. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  7428. int (*xPagecount)(sqlite3_pcache*);
  7429. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  7430. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  7431. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  7432. unsigned oldKey, unsigned newKey);
  7433. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  7434. void (*xDestroy)(sqlite3_pcache*);
  7435. void (*xShrink)(sqlite3_pcache*);
  7436. };
  7437. /*
  7438. ** This is the obsolete pcache_methods object that has now been replaced
  7439. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  7440. ** retained in the header file for backwards compatibility only.
  7441. */
  7442. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  7443. struct sqlite3_pcache_methods {
  7444. void *pArg;
  7445. int (*xInit)(void*);
  7446. void (*xShutdown)(void*);
  7447. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  7448. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  7449. int (*xPagecount)(sqlite3_pcache*);
  7450. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  7451. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  7452. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  7453. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  7454. void (*xDestroy)(sqlite3_pcache*);
  7455. };
  7456. /*
  7457. ** CAPI3REF: Online Backup Object
  7458. **
  7459. ** The sqlite3_backup object records state information about an ongoing
  7460. ** online backup operation. ^The sqlite3_backup object is created by
  7461. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  7462. ** [sqlite3_backup_finish()].
  7463. **
  7464. ** See Also: [Using the SQLite Online Backup API]
  7465. */
  7466. typedef struct sqlite3_backup sqlite3_backup;
  7467. /*
  7468. ** CAPI3REF: Online Backup API.
  7469. **
  7470. ** The backup API copies the content of one database into another.
  7471. ** It is useful either for creating backups of databases or
  7472. ** for copying in-memory databases to or from persistent files.
  7473. **
  7474. ** See Also: [Using the SQLite Online Backup API]
  7475. **
  7476. ** ^SQLite holds a write transaction open on the destination database file
  7477. ** for the duration of the backup operation.
  7478. ** ^The source database is read-locked only while it is being read;
  7479. ** it is not locked continuously for the entire backup operation.
  7480. ** ^Thus, the backup may be performed on a live source database without
  7481. ** preventing other database connections from
  7482. ** reading or writing to the source database while the backup is underway.
  7483. **
  7484. ** ^(To perform a backup operation:
  7485. ** <ol>
  7486. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  7487. ** backup,
  7488. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  7489. ** the data between the two databases, and finally
  7490. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  7491. ** associated with the backup operation.
  7492. ** </ol>)^
  7493. ** There should be exactly one call to sqlite3_backup_finish() for each
  7494. ** successful call to sqlite3_backup_init().
  7495. **
  7496. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  7497. **
  7498. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  7499. ** [database connection] associated with the destination database
  7500. ** and the database name, respectively.
  7501. ** ^The database name is "main" for the main database, "temp" for the
  7502. ** temporary database, or the name specified after the AS keyword in
  7503. ** an [ATTACH] statement for an attached database.
  7504. ** ^The S and M arguments passed to
  7505. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  7506. ** and database name of the source database, respectively.
  7507. ** ^The source and destination [database connections] (parameters S and D)
  7508. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  7509. ** an error.
  7510. **
  7511. ** ^A call to sqlite3_backup_init() will fail, returning NULL, if
  7512. ** there is already a read or read-write transaction open on the
  7513. ** destination database.
  7514. **
  7515. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  7516. ** returned and an error code and error message are stored in the
  7517. ** destination [database connection] D.
  7518. ** ^The error code and message for the failed call to sqlite3_backup_init()
  7519. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  7520. ** [sqlite3_errmsg16()] functions.
  7521. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  7522. ** [sqlite3_backup] object.
  7523. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  7524. ** sqlite3_backup_finish() functions to perform the specified backup
  7525. ** operation.
  7526. **
  7527. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  7528. **
  7529. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  7530. ** the source and destination databases specified by [sqlite3_backup] object B.
  7531. ** ^If N is negative, all remaining source pages are copied.
  7532. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  7533. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  7534. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  7535. ** from source to destination, then it returns [SQLITE_DONE].
  7536. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  7537. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  7538. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  7539. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  7540. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  7541. **
  7542. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  7543. ** <ol>
  7544. ** <li> the destination database was opened read-only, or
  7545. ** <li> the destination database is using write-ahead-log journaling
  7546. ** and the destination and source page sizes differ, or
  7547. ** <li> the destination database is an in-memory database and the
  7548. ** destination and source page sizes differ.
  7549. ** </ol>)^
  7550. **
  7551. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  7552. ** the [sqlite3_busy_handler | busy-handler function]
  7553. ** is invoked (if one is specified). ^If the
  7554. ** busy-handler returns non-zero before the lock is available, then
  7555. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  7556. ** sqlite3_backup_step() can be retried later. ^If the source
  7557. ** [database connection]
  7558. ** is being used to write to the source database when sqlite3_backup_step()
  7559. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  7560. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  7561. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  7562. ** [SQLITE_READONLY] is returned, then
  7563. ** there is no point in retrying the call to sqlite3_backup_step(). These
  7564. ** errors are considered fatal.)^ The application must accept
  7565. ** that the backup operation has failed and pass the backup operation handle
  7566. ** to the sqlite3_backup_finish() to release associated resources.
  7567. **
  7568. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  7569. ** on the destination file. ^The exclusive lock is not released until either
  7570. ** sqlite3_backup_finish() is called or the backup operation is complete
  7571. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  7572. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  7573. ** lasts for the duration of the sqlite3_backup_step() call.
  7574. ** ^Because the source database is not locked between calls to
  7575. ** sqlite3_backup_step(), the source database may be modified mid-way
  7576. ** through the backup process. ^If the source database is modified by an
  7577. ** external process or via a database connection other than the one being
  7578. ** used by the backup operation, then the backup will be automatically
  7579. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  7580. ** database is modified by the using the same database connection as is used
  7581. ** by the backup operation, then the backup database is automatically
  7582. ** updated at the same time.
  7583. **
  7584. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  7585. **
  7586. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  7587. ** application wishes to abandon the backup operation, the application
  7588. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  7589. ** ^The sqlite3_backup_finish() interfaces releases all
  7590. ** resources associated with the [sqlite3_backup] object.
  7591. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  7592. ** active write-transaction on the destination database is rolled back.
  7593. ** The [sqlite3_backup] object is invalid
  7594. ** and may not be used following a call to sqlite3_backup_finish().
  7595. **
  7596. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  7597. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  7598. ** sqlite3_backup_step() completed.
  7599. ** ^If an out-of-memory condition or IO error occurred during any prior
  7600. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  7601. ** sqlite3_backup_finish() returns the corresponding [error code].
  7602. **
  7603. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  7604. ** is not a permanent error and does not affect the return value of
  7605. ** sqlite3_backup_finish().
  7606. **
  7607. ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
  7608. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  7609. **
  7610. ** ^The sqlite3_backup_remaining() routine returns the number of pages still
  7611. ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
  7612. ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
  7613. ** in the source database at the conclusion of the most recent
  7614. ** sqlite3_backup_step().
  7615. ** ^(The values returned by these functions are only updated by
  7616. ** sqlite3_backup_step(). If the source database is modified in a way that
  7617. ** changes the size of the source database or the number of pages remaining,
  7618. ** those changes are not reflected in the output of sqlite3_backup_pagecount()
  7619. ** and sqlite3_backup_remaining() until after the next
  7620. ** sqlite3_backup_step().)^
  7621. **
  7622. ** <b>Concurrent Usage of Database Handles</b>
  7623. **
  7624. ** ^The source [database connection] may be used by the application for other
  7625. ** purposes while a backup operation is underway or being initialized.
  7626. ** ^If SQLite is compiled and configured to support threadsafe database
  7627. ** connections, then the source database connection may be used concurrently
  7628. ** from within other threads.
  7629. **
  7630. ** However, the application must guarantee that the destination
  7631. ** [database connection] is not passed to any other API (by any thread) after
  7632. ** sqlite3_backup_init() is called and before the corresponding call to
  7633. ** sqlite3_backup_finish(). SQLite does not currently check to see
  7634. ** if the application incorrectly accesses the destination [database connection]
  7635. ** and so no error code is reported, but the operations may malfunction
  7636. ** nevertheless. Use of the destination database connection while a
  7637. ** backup is in progress might also also cause a mutex deadlock.
  7638. **
  7639. ** If running in [shared cache mode], the application must
  7640. ** guarantee that the shared cache used by the destination database
  7641. ** is not accessed while the backup is running. In practice this means
  7642. ** that the application must guarantee that the disk file being
  7643. ** backed up to is not accessed by any connection within the process,
  7644. ** not just the specific connection that was passed to sqlite3_backup_init().
  7645. **
  7646. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  7647. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  7648. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  7649. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  7650. ** same time as another thread is invoking sqlite3_backup_step() it is
  7651. ** possible that they return invalid values.
  7652. */
  7653. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  7654. sqlite3 *pDest, /* Destination database handle */
  7655. const char *zDestName, /* Destination database name */
  7656. sqlite3 *pSource, /* Source database handle */
  7657. const char *zSourceName /* Source database name */
  7658. );
  7659. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  7660. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  7661. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  7662. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  7663. /*
  7664. ** CAPI3REF: Unlock Notification
  7665. ** METHOD: sqlite3
  7666. **
  7667. ** ^When running in shared-cache mode, a database operation may fail with
  7668. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  7669. ** individual tables within the shared-cache cannot be obtained. See
  7670. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  7671. ** ^This API may be used to register a callback that SQLite will invoke
  7672. ** when the connection currently holding the required lock relinquishes it.
  7673. ** ^This API is only available if the library was compiled with the
  7674. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  7675. **
  7676. ** See Also: [Using the SQLite Unlock Notification Feature].
  7677. **
  7678. ** ^Shared-cache locks are released when a database connection concludes
  7679. ** its current transaction, either by committing it or rolling it back.
  7680. **
  7681. ** ^When a connection (known as the blocked connection) fails to obtain a
  7682. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  7683. ** identity of the database connection (the blocking connection) that
  7684. ** has locked the required resource is stored internally. ^After an
  7685. ** application receives an SQLITE_LOCKED error, it may call the
  7686. ** sqlite3_unlock_notify() method with the blocked connection handle as
  7687. ** the first argument to register for a callback that will be invoked
  7688. ** when the blocking connections current transaction is concluded. ^The
  7689. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  7690. ** call that concludes the blocking connections transaction.
  7691. **
  7692. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  7693. ** there is a chance that the blocking connection will have already
  7694. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  7695. ** If this happens, then the specified callback is invoked immediately,
  7696. ** from within the call to sqlite3_unlock_notify().)^
  7697. **
  7698. ** ^If the blocked connection is attempting to obtain a write-lock on a
  7699. ** shared-cache table, and more than one other connection currently holds
  7700. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  7701. ** the other connections to use as the blocking connection.
  7702. **
  7703. ** ^(There may be at most one unlock-notify callback registered by a
  7704. ** blocked connection. If sqlite3_unlock_notify() is called when the
  7705. ** blocked connection already has a registered unlock-notify callback,
  7706. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  7707. ** called with a NULL pointer as its second argument, then any existing
  7708. ** unlock-notify callback is canceled. ^The blocked connections
  7709. ** unlock-notify callback may also be canceled by closing the blocked
  7710. ** connection using [sqlite3_close()].
  7711. **
  7712. ** The unlock-notify callback is not reentrant. If an application invokes
  7713. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  7714. ** crash or deadlock may be the result.
  7715. **
  7716. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  7717. ** returns SQLITE_OK.
  7718. **
  7719. ** <b>Callback Invocation Details</b>
  7720. **
  7721. ** When an unlock-notify callback is registered, the application provides a
  7722. ** single void* pointer that is passed to the callback when it is invoked.
  7723. ** However, the signature of the callback function allows SQLite to pass
  7724. ** it an array of void* context pointers. The first argument passed to
  7725. ** an unlock-notify callback is a pointer to an array of void* pointers,
  7726. ** and the second is the number of entries in the array.
  7727. **
  7728. ** When a blocking connections transaction is concluded, there may be
  7729. ** more than one blocked connection that has registered for an unlock-notify
  7730. ** callback. ^If two or more such blocked connections have specified the
  7731. ** same callback function, then instead of invoking the callback function
  7732. ** multiple times, it is invoked once with the set of void* context pointers
  7733. ** specified by the blocked connections bundled together into an array.
  7734. ** This gives the application an opportunity to prioritize any actions
  7735. ** related to the set of unblocked database connections.
  7736. **
  7737. ** <b>Deadlock Detection</b>
  7738. **
  7739. ** Assuming that after registering for an unlock-notify callback a
  7740. ** database waits for the callback to be issued before taking any further
  7741. ** action (a reasonable assumption), then using this API may cause the
  7742. ** application to deadlock. For example, if connection X is waiting for
  7743. ** connection Y's transaction to be concluded, and similarly connection
  7744. ** Y is waiting on connection X's transaction, then neither connection
  7745. ** will proceed and the system may remain deadlocked indefinitely.
  7746. **
  7747. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  7748. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  7749. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  7750. ** unlock-notify callback is registered. The system is said to be in
  7751. ** a deadlocked state if connection A has registered for an unlock-notify
  7752. ** callback on the conclusion of connection B's transaction, and connection
  7753. ** B has itself registered for an unlock-notify callback when connection
  7754. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  7755. ** the system is also considered to be deadlocked if connection B has
  7756. ** registered for an unlock-notify callback on the conclusion of connection
  7757. ** C's transaction, where connection C is waiting on connection A. ^Any
  7758. ** number of levels of indirection are allowed.
  7759. **
  7760. ** <b>The "DROP TABLE" Exception</b>
  7761. **
  7762. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  7763. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  7764. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  7765. ** SQLite checks if there are any currently executing SELECT statements
  7766. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  7767. ** returned. In this case there is no "blocking connection", so invoking
  7768. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  7769. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  7770. ** or "DROP INDEX" query, an infinite loop might be the result.
  7771. **
  7772. ** One way around this problem is to check the extended error code returned
  7773. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  7774. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  7775. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  7776. ** SQLITE_LOCKED.)^
  7777. */
  7778. SQLITE_API int sqlite3_unlock_notify(
  7779. sqlite3 *pBlocked, /* Waiting connection */
  7780. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  7781. void *pNotifyArg /* Argument to pass to xNotify */
  7782. );
  7783. /*
  7784. ** CAPI3REF: String Comparison
  7785. **
  7786. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  7787. ** and extensions to compare the contents of two buffers containing UTF-8
  7788. ** strings in a case-independent fashion, using the same definition of "case
  7789. ** independence" that SQLite uses internally when comparing identifiers.
  7790. */
  7791. SQLITE_API int sqlite3_stricmp(const char *, const char *);
  7792. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  7793. /*
  7794. ** CAPI3REF: String Globbing
  7795. *
  7796. ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
  7797. ** string X matches the [GLOB] pattern P.
  7798. ** ^The definition of [GLOB] pattern matching used in
  7799. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  7800. ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
  7801. ** is case sensitive.
  7802. **
  7803. ** Note that this routine returns zero on a match and non-zero if the strings
  7804. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  7805. **
  7806. ** See also: [sqlite3_strlike()].
  7807. */
  7808. SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  7809. /*
  7810. ** CAPI3REF: String LIKE Matching
  7811. *
  7812. ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
  7813. ** string X matches the [LIKE] pattern P with escape character E.
  7814. ** ^The definition of [LIKE] pattern matching used in
  7815. ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
  7816. ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
  7817. ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
  7818. ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
  7819. ** insensitive - equivalent upper and lower case ASCII characters match
  7820. ** one another.
  7821. **
  7822. ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
  7823. ** only ASCII characters are case folded.
  7824. **
  7825. ** Note that this routine returns zero on a match and non-zero if the strings
  7826. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  7827. **
  7828. ** See also: [sqlite3_strglob()].
  7829. */
  7830. SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
  7831. /*
  7832. ** CAPI3REF: Error Logging Interface
  7833. **
  7834. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  7835. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  7836. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  7837. ** used with [sqlite3_snprintf()] to generate the final output string.
  7838. **
  7839. ** The sqlite3_log() interface is intended for use by extensions such as
  7840. ** virtual tables, collating functions, and SQL functions. While there is
  7841. ** nothing to prevent an application from calling sqlite3_log(), doing so
  7842. ** is considered bad form.
  7843. **
  7844. ** The zFormat string must not be NULL.
  7845. **
  7846. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  7847. ** will not use dynamically allocated memory. The log message is stored in
  7848. ** a fixed-length buffer on the stack. If the log message is longer than
  7849. ** a few hundred characters, it will be truncated to the length of the
  7850. ** buffer.
  7851. */
  7852. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  7853. /*
  7854. ** CAPI3REF: Write-Ahead Log Commit Hook
  7855. ** METHOD: sqlite3
  7856. **
  7857. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  7858. ** is invoked each time data is committed to a database in wal mode.
  7859. **
  7860. ** ^(The callback is invoked by SQLite after the commit has taken place and
  7861. ** the associated write-lock on the database released)^, so the implementation
  7862. ** may read, write or [checkpoint] the database as required.
  7863. **
  7864. ** ^The first parameter passed to the callback function when it is invoked
  7865. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  7866. ** registering the callback. ^The second is a copy of the database handle.
  7867. ** ^The third parameter is the name of the database that was written to -
  7868. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  7869. ** is the number of pages currently in the write-ahead log file,
  7870. ** including those that were just committed.
  7871. **
  7872. ** The callback function should normally return [SQLITE_OK]. ^If an error
  7873. ** code is returned, that error will propagate back up through the
  7874. ** SQLite code base to cause the statement that provoked the callback
  7875. ** to report an error, though the commit will have still occurred. If the
  7876. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  7877. ** that does not correspond to any valid SQLite error code, the results
  7878. ** are undefined.
  7879. **
  7880. ** A single database handle may have at most a single write-ahead log callback
  7881. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  7882. ** previously registered write-ahead log callback. ^Note that the
  7883. ** [sqlite3_wal_autocheckpoint()] interface and the
  7884. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  7885. ** overwrite any prior [sqlite3_wal_hook()] settings.
  7886. */
  7887. SQLITE_API void *sqlite3_wal_hook(
  7888. sqlite3*,
  7889. int(*)(void *,sqlite3*,const char*,int),
  7890. void*
  7891. );
  7892. /*
  7893. ** CAPI3REF: Configure an auto-checkpoint
  7894. ** METHOD: sqlite3
  7895. **
  7896. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  7897. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  7898. ** to automatically [checkpoint]
  7899. ** after committing a transaction if there are N or
  7900. ** more frames in the [write-ahead log] file. ^Passing zero or
  7901. ** a negative value as the nFrame parameter disables automatic
  7902. ** checkpoints entirely.
  7903. **
  7904. ** ^The callback registered by this function replaces any existing callback
  7905. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  7906. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  7907. ** configured by this function.
  7908. **
  7909. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  7910. ** from SQL.
  7911. **
  7912. ** ^Checkpoints initiated by this mechanism are
  7913. ** [sqlite3_wal_checkpoint_v2|PASSIVE].
  7914. **
  7915. ** ^Every new [database connection] defaults to having the auto-checkpoint
  7916. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  7917. ** pages. The use of this interface
  7918. ** is only necessary if the default setting is found to be suboptimal
  7919. ** for a particular application.
  7920. */
  7921. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  7922. /*
  7923. ** CAPI3REF: Checkpoint a database
  7924. ** METHOD: sqlite3
  7925. **
  7926. ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
  7927. ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
  7928. **
  7929. ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
  7930. ** [write-ahead log] for database X on [database connection] D to be
  7931. ** transferred into the database file and for the write-ahead log to
  7932. ** be reset. See the [checkpointing] documentation for addition
  7933. ** information.
  7934. **
  7935. ** This interface used to be the only way to cause a checkpoint to
  7936. ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
  7937. ** interface was added. This interface is retained for backwards
  7938. ** compatibility and as a convenience for applications that need to manually
  7939. ** start a callback but which do not need the full power (and corresponding
  7940. ** complication) of [sqlite3_wal_checkpoint_v2()].
  7941. */
  7942. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  7943. /*
  7944. ** CAPI3REF: Checkpoint a database
  7945. ** METHOD: sqlite3
  7946. **
  7947. ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
  7948. ** operation on database X of [database connection] D in mode M. Status
  7949. ** information is written back into integers pointed to by L and C.)^
  7950. ** ^(The M parameter must be a valid [checkpoint mode]:)^
  7951. **
  7952. ** <dl>
  7953. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  7954. ** ^Checkpoint as many frames as possible without waiting for any database
  7955. ** readers or writers to finish, then sync the database file if all frames
  7956. ** in the log were checkpointed. ^The [busy-handler callback]
  7957. ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
  7958. ** ^On the other hand, passive mode might leave the checkpoint unfinished
  7959. ** if there are concurrent readers or writers.
  7960. **
  7961. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  7962. ** ^This mode blocks (it invokes the
  7963. ** [sqlite3_busy_handler|busy-handler callback]) until there is no
  7964. ** database writer and all readers are reading from the most recent database
  7965. ** snapshot. ^It then checkpoints all frames in the log file and syncs the
  7966. ** database file. ^This mode blocks new database writers while it is pending,
  7967. ** but new database readers are allowed to continue unimpeded.
  7968. **
  7969. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  7970. ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
  7971. ** that after checkpointing the log file it blocks (calls the
  7972. ** [busy-handler callback])
  7973. ** until all readers are reading from the database file only. ^This ensures
  7974. ** that the next writer will restart the log file from the beginning.
  7975. ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
  7976. ** database writer attempts while it is pending, but does not impede readers.
  7977. **
  7978. ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
  7979. ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
  7980. ** addition that it also truncates the log file to zero bytes just prior
  7981. ** to a successful return.
  7982. ** </dl>
  7983. **
  7984. ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
  7985. ** the log file or to -1 if the checkpoint could not run because
  7986. ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
  7987. ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
  7988. ** log file (including any that were already checkpointed before the function
  7989. ** was called) or to -1 if the checkpoint could not run due to an error or
  7990. ** because the database is not in WAL mode. ^Note that upon successful
  7991. ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
  7992. ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
  7993. **
  7994. ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
  7995. ** any other process is running a checkpoint operation at the same time, the
  7996. ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
  7997. ** busy-handler configured, it will not be invoked in this case.
  7998. **
  7999. ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
  8000. ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
  8001. ** obtained immediately, and a busy-handler is configured, it is invoked and
  8002. ** the writer lock retried until either the busy-handler returns 0 or the lock
  8003. ** is successfully obtained. ^The busy-handler is also invoked while waiting for
  8004. ** database readers as described above. ^If the busy-handler returns 0 before
  8005. ** the writer lock is obtained or while waiting for database readers, the
  8006. ** checkpoint operation proceeds from that point in the same way as
  8007. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  8008. ** without blocking any further. ^SQLITE_BUSY is returned in this case.
  8009. **
  8010. ** ^If parameter zDb is NULL or points to a zero length string, then the
  8011. ** specified operation is attempted on all WAL databases [attached] to
  8012. ** [database connection] db. In this case the
  8013. ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
  8014. ** an SQLITE_BUSY error is encountered when processing one or more of the
  8015. ** attached WAL databases, the operation is still attempted on any remaining
  8016. ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
  8017. ** error occurs while processing an attached database, processing is abandoned
  8018. ** and the error code is returned to the caller immediately. ^If no error
  8019. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  8020. ** databases, SQLITE_OK is returned.
  8021. **
  8022. ** ^If database zDb is the name of an attached database that is not in WAL
  8023. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
  8024. ** zDb is not NULL (or a zero length string) and is not the name of any
  8025. ** attached database, SQLITE_ERROR is returned to the caller.
  8026. **
  8027. ** ^Unless it returns SQLITE_MISUSE,
  8028. ** the sqlite3_wal_checkpoint_v2() interface
  8029. ** sets the error information that is queried by
  8030. ** [sqlite3_errcode()] and [sqlite3_errmsg()].
  8031. **
  8032. ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
  8033. ** from SQL.
  8034. */
  8035. SQLITE_API int sqlite3_wal_checkpoint_v2(
  8036. sqlite3 *db, /* Database handle */
  8037. const char *zDb, /* Name of attached database (or NULL) */
  8038. int eMode, /* SQLITE_CHECKPOINT_* value */
  8039. int *pnLog, /* OUT: Size of WAL log in frames */
  8040. int *pnCkpt /* OUT: Total number of frames checkpointed */
  8041. );
  8042. /*
  8043. ** CAPI3REF: Checkpoint Mode Values
  8044. ** KEYWORDS: {checkpoint mode}
  8045. **
  8046. ** These constants define all valid values for the "checkpoint mode" passed
  8047. ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
  8048. ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
  8049. ** meaning of each of these checkpoint modes.
  8050. */
  8051. #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
  8052. #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
  8053. #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
  8054. #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
  8055. /*
  8056. ** CAPI3REF: Virtual Table Interface Configuration
  8057. **
  8058. ** This function may be called by either the [xConnect] or [xCreate] method
  8059. ** of a [virtual table] implementation to configure
  8060. ** various facets of the virtual table interface.
  8061. **
  8062. ** If this interface is invoked outside the context of an xConnect or
  8063. ** xCreate virtual table method then the behavior is undefined.
  8064. **
  8065. ** At present, there is only one option that may be configured using
  8066. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  8067. ** may be added in the future.
  8068. */
  8069. SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  8070. /*
  8071. ** CAPI3REF: Virtual Table Configuration Options
  8072. **
  8073. ** These macros define the various options to the
  8074. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  8075. ** can use to customize and optimize their behavior.
  8076. **
  8077. ** <dl>
  8078. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  8079. ** <dd>Calls of the form
  8080. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  8081. ** where X is an integer. If X is zero, then the [virtual table] whose
  8082. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  8083. ** support constraints. In this configuration (which is the default) if
  8084. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  8085. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  8086. ** specified as part of the users SQL statement, regardless of the actual
  8087. ** ON CONFLICT mode specified.
  8088. **
  8089. ** If X is non-zero, then the virtual table implementation guarantees
  8090. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  8091. ** any modifications to internal or persistent data structures have been made.
  8092. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  8093. ** is able to roll back a statement or database transaction, and abandon
  8094. ** or continue processing the current SQL statement as appropriate.
  8095. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  8096. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  8097. ** had been ABORT.
  8098. **
  8099. ** Virtual table implementations that are required to handle OR REPLACE
  8100. ** must do so within the [xUpdate] method. If a call to the
  8101. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  8102. ** CONFLICT policy is REPLACE, the virtual table implementation should
  8103. ** silently replace the appropriate rows within the xUpdate callback and
  8104. ** return SQLITE_OK. Or, if this is not possible, it may return
  8105. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  8106. ** constraint handling.
  8107. ** </dl>
  8108. */
  8109. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  8110. /*
  8111. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  8112. **
  8113. ** This function may only be called from within a call to the [xUpdate] method
  8114. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  8115. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  8116. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  8117. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  8118. ** [virtual table].
  8119. */
  8120. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  8121. /*
  8122. ** CAPI3REF: Conflict resolution modes
  8123. ** KEYWORDS: {conflict resolution mode}
  8124. **
  8125. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  8126. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  8127. ** is for the SQL statement being evaluated.
  8128. **
  8129. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  8130. ** return value from the [sqlite3_set_authorizer()] callback and that
  8131. ** [SQLITE_ABORT] is also a [result code].
  8132. */
  8133. #define SQLITE_ROLLBACK 1
  8134. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  8135. #define SQLITE_FAIL 3
  8136. /* #define SQLITE_ABORT 4 // Also an error code */
  8137. #define SQLITE_REPLACE 5
  8138. /*
  8139. ** CAPI3REF: Prepared Statement Scan Status Opcodes
  8140. ** KEYWORDS: {scanstatus options}
  8141. **
  8142. ** The following constants can be used for the T parameter to the
  8143. ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
  8144. ** different metric for sqlite3_stmt_scanstatus() to return.
  8145. **
  8146. ** When the value returned to V is a string, space to hold that string is
  8147. ** managed by the prepared statement S and will be automatically freed when
  8148. ** S is finalized.
  8149. **
  8150. ** <dl>
  8151. ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
  8152. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
  8153. ** set to the total number of times that the X-th loop has run.</dd>
  8154. **
  8155. ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
  8156. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
  8157. ** to the total number of rows examined by all iterations of the X-th loop.</dd>
  8158. **
  8159. ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
  8160. ** <dd>^The "double" variable pointed to by the T parameter will be set to the
  8161. ** query planner's estimate for the average number of rows output from each
  8162. ** iteration of the X-th loop. If the query planner's estimates was accurate,
  8163. ** then this value will approximate the quotient NVISIT/NLOOP and the
  8164. ** product of this value for all prior loops with the same SELECTID will
  8165. ** be the NLOOP value for the current loop.
  8166. **
  8167. ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
  8168. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  8169. ** to a zero-terminated UTF-8 string containing the name of the index or table
  8170. ** used for the X-th loop.
  8171. **
  8172. ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
  8173. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  8174. ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
  8175. ** description for the X-th loop.
  8176. **
  8177. ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
  8178. ** <dd>^The "int" variable pointed to by the T parameter will be set to the
  8179. ** "select-id" for the X-th loop. The select-id identifies which query or
  8180. ** subquery the loop is part of. The main query has a select-id of zero.
  8181. ** The select-id is the same value as is output in the first column
  8182. ** of an [EXPLAIN QUERY PLAN] query.
  8183. ** </dl>
  8184. */
  8185. #define SQLITE_SCANSTAT_NLOOP 0
  8186. #define SQLITE_SCANSTAT_NVISIT 1
  8187. #define SQLITE_SCANSTAT_EST 2
  8188. #define SQLITE_SCANSTAT_NAME 3
  8189. #define SQLITE_SCANSTAT_EXPLAIN 4
  8190. #define SQLITE_SCANSTAT_SELECTID 5
  8191. /*
  8192. ** CAPI3REF: Prepared Statement Scan Status
  8193. ** METHOD: sqlite3_stmt
  8194. **
  8195. ** This interface returns information about the predicted and measured
  8196. ** performance for pStmt. Advanced applications can use this
  8197. ** interface to compare the predicted and the measured performance and
  8198. ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
  8199. **
  8200. ** Since this interface is expected to be rarely used, it is only
  8201. ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
  8202. ** compile-time option.
  8203. **
  8204. ** The "iScanStatusOp" parameter determines which status information to return.
  8205. ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
  8206. ** of this interface is undefined.
  8207. ** ^The requested measurement is written into a variable pointed to by
  8208. ** the "pOut" parameter.
  8209. ** Parameter "idx" identifies the specific loop to retrieve statistics for.
  8210. ** Loops are numbered starting from zero. ^If idx is out of range - less than
  8211. ** zero or greater than or equal to the total number of loops used to implement
  8212. ** the statement - a non-zero value is returned and the variable that pOut
  8213. ** points to is unchanged.
  8214. **
  8215. ** ^Statistics might not be available for all loops in all statements. ^In cases
  8216. ** where there exist loops with no available statistics, this function behaves
  8217. ** as if the loop did not exist - it returns non-zero and leave the variable
  8218. ** that pOut points to unchanged.
  8219. **
  8220. ** See also: [sqlite3_stmt_scanstatus_reset()]
  8221. */
  8222. SQLITE_API int sqlite3_stmt_scanstatus(
  8223. sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
  8224. int idx, /* Index of loop to report on */
  8225. int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
  8226. void *pOut /* Result written here */
  8227. );
  8228. /*
  8229. ** CAPI3REF: Zero Scan-Status Counters
  8230. ** METHOD: sqlite3_stmt
  8231. **
  8232. ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
  8233. **
  8234. ** This API is only available if the library is built with pre-processor
  8235. ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
  8236. */
  8237. SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
  8238. /*
  8239. ** CAPI3REF: Flush caches to disk mid-transaction
  8240. **
  8241. ** ^If a write-transaction is open on [database connection] D when the
  8242. ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
  8243. ** pages in the pager-cache that are not currently in use are written out
  8244. ** to disk. A dirty page may be in use if a database cursor created by an
  8245. ** active SQL statement is reading from it, or if it is page 1 of a database
  8246. ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
  8247. ** interface flushes caches for all schemas - "main", "temp", and
  8248. ** any [attached] databases.
  8249. **
  8250. ** ^If this function needs to obtain extra database locks before dirty pages
  8251. ** can be flushed to disk, it does so. ^If those locks cannot be obtained
  8252. ** immediately and there is a busy-handler callback configured, it is invoked
  8253. ** in the usual manner. ^If the required lock still cannot be obtained, then
  8254. ** the database is skipped and an attempt made to flush any dirty pages
  8255. ** belonging to the next (if any) database. ^If any databases are skipped
  8256. ** because locks cannot be obtained, but no other error occurs, this
  8257. ** function returns SQLITE_BUSY.
  8258. **
  8259. ** ^If any other error occurs while flushing dirty pages to disk (for
  8260. ** example an IO error or out-of-memory condition), then processing is
  8261. ** abandoned and an SQLite [error code] is returned to the caller immediately.
  8262. **
  8263. ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
  8264. **
  8265. ** ^This function does not set the database handle error code or message
  8266. ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
  8267. */
  8268. SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
  8269. /*
  8270. ** CAPI3REF: The pre-update hook.
  8271. **
  8272. ** ^These interfaces are only available if SQLite is compiled using the
  8273. ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
  8274. **
  8275. ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
  8276. ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
  8277. ** on a database table.
  8278. ** ^At most one preupdate hook may be registered at a time on a single
  8279. ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
  8280. ** the previous setting.
  8281. ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
  8282. ** with a NULL pointer as the second parameter.
  8283. ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
  8284. ** the first parameter to callbacks.
  8285. **
  8286. ** ^The preupdate hook only fires for changes to real database tables; the
  8287. ** preupdate hook is not invoked for changes to [virtual tables] or to
  8288. ** system tables like sqlite_master or sqlite_stat1.
  8289. **
  8290. ** ^The second parameter to the preupdate callback is a pointer to
  8291. ** the [database connection] that registered the preupdate hook.
  8292. ** ^The third parameter to the preupdate callback is one of the constants
  8293. ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
  8294. ** kind of update operation that is about to occur.
  8295. ** ^(The fourth parameter to the preupdate callback is the name of the
  8296. ** database within the database connection that is being modified. This
  8297. ** will be "main" for the main database or "temp" for TEMP tables or
  8298. ** the name given after the AS keyword in the [ATTACH] statement for attached
  8299. ** databases.)^
  8300. ** ^The fifth parameter to the preupdate callback is the name of the
  8301. ** table that is being modified.
  8302. **
  8303. ** For an UPDATE or DELETE operation on a [rowid table], the sixth
  8304. ** parameter passed to the preupdate callback is the initial [rowid] of the
  8305. ** row being modified or deleted. For an INSERT operation on a rowid table,
  8306. ** or any operation on a WITHOUT ROWID table, the value of the sixth
  8307. ** parameter is undefined. For an INSERT or UPDATE on a rowid table the
  8308. ** seventh parameter is the final rowid value of the row being inserted
  8309. ** or updated. The value of the seventh parameter passed to the callback
  8310. ** function is not defined for operations on WITHOUT ROWID tables, or for
  8311. ** INSERT operations on rowid tables.
  8312. **
  8313. ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
  8314. ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
  8315. ** provide additional information about a preupdate event. These routines
  8316. ** may only be called from within a preupdate callback. Invoking any of
  8317. ** these routines from outside of a preupdate callback or with a
  8318. ** [database connection] pointer that is different from the one supplied
  8319. ** to the preupdate callback results in undefined and probably undesirable
  8320. ** behavior.
  8321. **
  8322. ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
  8323. ** in the row that is being inserted, updated, or deleted.
  8324. **
  8325. ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
  8326. ** a [protected sqlite3_value] that contains the value of the Nth column of
  8327. ** the table row before it is updated. The N parameter must be between 0
  8328. ** and one less than the number of columns or the behavior will be
  8329. ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
  8330. ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
  8331. ** behavior is undefined. The [sqlite3_value] that P points to
  8332. ** will be destroyed when the preupdate callback returns.
  8333. **
  8334. ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
  8335. ** a [protected sqlite3_value] that contains the value of the Nth column of
  8336. ** the table row after it is updated. The N parameter must be between 0
  8337. ** and one less than the number of columns or the behavior will be
  8338. ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
  8339. ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
  8340. ** behavior is undefined. The [sqlite3_value] that P points to
  8341. ** will be destroyed when the preupdate callback returns.
  8342. **
  8343. ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
  8344. ** callback was invoked as a result of a direct insert, update, or delete
  8345. ** operation; or 1 for inserts, updates, or deletes invoked by top-level
  8346. ** triggers; or 2 for changes resulting from triggers called by top-level
  8347. ** triggers; and so forth.
  8348. **
  8349. ** See also: [sqlite3_update_hook()]
  8350. */
  8351. #if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  8352. SQLITE_API void *sqlite3_preupdate_hook(
  8353. sqlite3 *db,
  8354. void(*xPreUpdate)(
  8355. void *pCtx, /* Copy of third arg to preupdate_hook() */
  8356. sqlite3 *db, /* Database handle */
  8357. int op, /* SQLITE_UPDATE, DELETE or INSERT */
  8358. char const *zDb, /* Database name */
  8359. char const *zName, /* Table name */
  8360. sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
  8361. sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
  8362. ),
  8363. void*
  8364. );
  8365. SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
  8366. SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
  8367. SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
  8368. SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
  8369. #endif
  8370. /*
  8371. ** CAPI3REF: Low-level system error code
  8372. **
  8373. ** ^Attempt to return the underlying operating system error code or error
  8374. ** number that caused the most recent I/O error or failure to open a file.
  8375. ** The return value is OS-dependent. For example, on unix systems, after
  8376. ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
  8377. ** called to get back the underlying "errno" that caused the problem, such
  8378. ** as ENOSPC, EAUTH, EISDIR, and so forth.
  8379. */
  8380. SQLITE_API int sqlite3_system_errno(sqlite3*);
  8381. /*
  8382. ** CAPI3REF: Database Snapshot
  8383. ** KEYWORDS: {snapshot} {sqlite3_snapshot}
  8384. ** EXPERIMENTAL
  8385. **
  8386. ** An instance of the snapshot object records the state of a [WAL mode]
  8387. ** database for some specific point in history.
  8388. **
  8389. ** In [WAL mode], multiple [database connections] that are open on the
  8390. ** same database file can each be reading a different historical version
  8391. ** of the database file. When a [database connection] begins a read
  8392. ** transaction, that connection sees an unchanging copy of the database
  8393. ** as it existed for the point in time when the transaction first started.
  8394. ** Subsequent changes to the database from other connections are not seen
  8395. ** by the reader until a new read transaction is started.
  8396. **
  8397. ** The sqlite3_snapshot object records state information about an historical
  8398. ** version of the database file so that it is possible to later open a new read
  8399. ** transaction that sees that historical version of the database rather than
  8400. ** the most recent version.
  8401. **
  8402. ** The constructor for this object is [sqlite3_snapshot_get()]. The
  8403. ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
  8404. ** to an historical snapshot (if possible). The destructor for
  8405. ** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
  8406. */
  8407. typedef struct sqlite3_snapshot {
  8408. unsigned char hidden[48];
  8409. } sqlite3_snapshot;
  8410. /*
  8411. ** CAPI3REF: Record A Database Snapshot
  8412. ** EXPERIMENTAL
  8413. **
  8414. ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
  8415. ** new [sqlite3_snapshot] object that records the current state of
  8416. ** schema S in database connection D. ^On success, the
  8417. ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
  8418. ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
  8419. ** If there is not already a read-transaction open on schema S when
  8420. ** this function is called, one is opened automatically.
  8421. **
  8422. ** The following must be true for this function to succeed. If any of
  8423. ** the following statements are false when sqlite3_snapshot_get() is
  8424. ** called, SQLITE_ERROR is returned. The final value of *P is undefined
  8425. ** in this case.
  8426. **
  8427. ** <ul>
  8428. ** <li> The database handle must be in [autocommit mode].
  8429. **
  8430. ** <li> Schema S of [database connection] D must be a [WAL mode] database.
  8431. **
  8432. ** <li> There must not be a write transaction open on schema S of database
  8433. ** connection D.
  8434. **
  8435. ** <li> One or more transactions must have been written to the current wal
  8436. ** file since it was created on disk (by any connection). This means
  8437. ** that a snapshot cannot be taken on a wal mode database with no wal
  8438. ** file immediately after it is first opened. At least one transaction
  8439. ** must be written to it first.
  8440. ** </ul>
  8441. **
  8442. ** This function may also return SQLITE_NOMEM. If it is called with the
  8443. ** database handle in autocommit mode but fails for some other reason,
  8444. ** whether or not a read transaction is opened on schema S is undefined.
  8445. **
  8446. ** The [sqlite3_snapshot] object returned from a successful call to
  8447. ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
  8448. ** to avoid a memory leak.
  8449. **
  8450. ** The [sqlite3_snapshot_get()] interface is only available when the
  8451. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  8452. */
  8453. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
  8454. sqlite3 *db,
  8455. const char *zSchema,
  8456. sqlite3_snapshot **ppSnapshot
  8457. );
  8458. /*
  8459. ** CAPI3REF: Start a read transaction on an historical snapshot
  8460. ** EXPERIMENTAL
  8461. **
  8462. ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
  8463. ** read transaction for schema S of
  8464. ** [database connection] D such that the read transaction
  8465. ** refers to historical [snapshot] P, rather than the most
  8466. ** recent change to the database.
  8467. ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
  8468. ** or an appropriate [error code] if it fails.
  8469. **
  8470. ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
  8471. ** the first operation following the [BEGIN] that takes the schema S
  8472. ** out of [autocommit mode].
  8473. ** ^In other words, schema S must not currently be in
  8474. ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
  8475. ** database connection D must be out of [autocommit mode].
  8476. ** ^A [snapshot] will fail to open if it has been overwritten by a
  8477. ** [checkpoint].
  8478. ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
  8479. ** database connection D does not know that the database file for
  8480. ** schema S is in [WAL mode]. A database connection might not know
  8481. ** that the database file is in [WAL mode] if there has been no prior
  8482. ** I/O on that database connection, or if the database entered [WAL mode]
  8483. ** after the most recent I/O on the database connection.)^
  8484. ** (Hint: Run "[PRAGMA application_id]" against a newly opened
  8485. ** database connection in order to make it ready to use snapshots.)
  8486. **
  8487. ** The [sqlite3_snapshot_open()] interface is only available when the
  8488. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  8489. */
  8490. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
  8491. sqlite3 *db,
  8492. const char *zSchema,
  8493. sqlite3_snapshot *pSnapshot
  8494. );
  8495. /*
  8496. ** CAPI3REF: Destroy a snapshot
  8497. ** EXPERIMENTAL
  8498. **
  8499. ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
  8500. ** The application must eventually free every [sqlite3_snapshot] object
  8501. ** using this routine to avoid a memory leak.
  8502. **
  8503. ** The [sqlite3_snapshot_free()] interface is only available when the
  8504. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  8505. */
  8506. SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
  8507. /*
  8508. ** CAPI3REF: Compare the ages of two snapshot handles.
  8509. ** EXPERIMENTAL
  8510. **
  8511. ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
  8512. ** of two valid snapshot handles.
  8513. **
  8514. ** If the two snapshot handles are not associated with the same database
  8515. ** file, the result of the comparison is undefined.
  8516. **
  8517. ** Additionally, the result of the comparison is only valid if both of the
  8518. ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
  8519. ** last time the wal file was deleted. The wal file is deleted when the
  8520. ** database is changed back to rollback mode or when the number of database
  8521. ** clients drops to zero. If either snapshot handle was obtained before the
  8522. ** wal file was last deleted, the value returned by this function
  8523. ** is undefined.
  8524. **
  8525. ** Otherwise, this API returns a negative value if P1 refers to an older
  8526. ** snapshot than P2, zero if the two handles refer to the same database
  8527. ** snapshot, and a positive value if P1 is a newer snapshot than P2.
  8528. */
  8529. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
  8530. sqlite3_snapshot *p1,
  8531. sqlite3_snapshot *p2
  8532. );
  8533. /*
  8534. ** CAPI3REF: Recover snapshots from a wal file
  8535. ** EXPERIMENTAL
  8536. **
  8537. ** If all connections disconnect from a database file but do not perform
  8538. ** a checkpoint, the existing wal file is opened along with the database
  8539. ** file the next time the database is opened. At this point it is only
  8540. ** possible to successfully call sqlite3_snapshot_open() to open the most
  8541. ** recent snapshot of the database (the one at the head of the wal file),
  8542. ** even though the wal file may contain other valid snapshots for which
  8543. ** clients have sqlite3_snapshot handles.
  8544. **
  8545. ** This function attempts to scan the wal file associated with database zDb
  8546. ** of database handle db and make all valid snapshots available to
  8547. ** sqlite3_snapshot_open(). It is an error if there is already a read
  8548. ** transaction open on the database, or if the database is not a wal mode
  8549. ** database.
  8550. **
  8551. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  8552. */
  8553. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
  8554. /*
  8555. ** Undo the hack that converts floating point types to integer for
  8556. ** builds on processors without floating point support.
  8557. */
  8558. #ifdef SQLITE_OMIT_FLOATING_POINT
  8559. # undef double
  8560. #endif
  8561. #if 0
  8562. } /* End of the 'extern "C"' block */
  8563. #endif
  8564. #endif /* SQLITE3_H */
  8565. /******** Begin file sqlite3rtree.h *********/
  8566. /*
  8567. ** 2010 August 30
  8568. **
  8569. ** The author disclaims copyright to this source code. In place of
  8570. ** a legal notice, here is a blessing:
  8571. **
  8572. ** May you do good and not evil.
  8573. ** May you find forgiveness for yourself and forgive others.
  8574. ** May you share freely, never taking more than you give.
  8575. **
  8576. *************************************************************************
  8577. */
  8578. #ifndef _SQLITE3RTREE_H_
  8579. #define _SQLITE3RTREE_H_
  8580. #if 0
  8581. extern "C" {
  8582. #endif
  8583. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  8584. typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
  8585. /* The double-precision datatype used by RTree depends on the
  8586. ** SQLITE_RTREE_INT_ONLY compile-time option.
  8587. */
  8588. #ifdef SQLITE_RTREE_INT_ONLY
  8589. typedef sqlite3_int64 sqlite3_rtree_dbl;
  8590. #else
  8591. typedef double sqlite3_rtree_dbl;
  8592. #endif
  8593. /*
  8594. ** Register a geometry callback named zGeom that can be used as part of an
  8595. ** R-Tree geometry query as follows:
  8596. **
  8597. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  8598. */
  8599. SQLITE_API int sqlite3_rtree_geometry_callback(
  8600. sqlite3 *db,
  8601. const char *zGeom,
  8602. int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
  8603. void *pContext
  8604. );
  8605. /*
  8606. ** A pointer to a structure of the following type is passed as the first
  8607. ** argument to callbacks registered using rtree_geometry_callback().
  8608. */
  8609. struct sqlite3_rtree_geometry {
  8610. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  8611. int nParam; /* Size of array aParam[] */
  8612. sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
  8613. void *pUser; /* Callback implementation user data */
  8614. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  8615. };
  8616. /*
  8617. ** Register a 2nd-generation geometry callback named zScore that can be
  8618. ** used as part of an R-Tree geometry query as follows:
  8619. **
  8620. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
  8621. */
  8622. SQLITE_API int sqlite3_rtree_query_callback(
  8623. sqlite3 *db,
  8624. const char *zQueryFunc,
  8625. int (*xQueryFunc)(sqlite3_rtree_query_info*),
  8626. void *pContext,
  8627. void (*xDestructor)(void*)
  8628. );
  8629. /*
  8630. ** A pointer to a structure of the following type is passed as the
  8631. ** argument to scored geometry callback registered using
  8632. ** sqlite3_rtree_query_callback().
  8633. **
  8634. ** Note that the first 5 fields of this structure are identical to
  8635. ** sqlite3_rtree_geometry. This structure is a subclass of
  8636. ** sqlite3_rtree_geometry.
  8637. */
  8638. struct sqlite3_rtree_query_info {
  8639. void *pContext; /* pContext from when function registered */
  8640. int nParam; /* Number of function parameters */
  8641. sqlite3_rtree_dbl *aParam; /* value of function parameters */
  8642. void *pUser; /* callback can use this, if desired */
  8643. void (*xDelUser)(void*); /* function to free pUser */
  8644. sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
  8645. unsigned int *anQueue; /* Number of pending entries in the queue */
  8646. int nCoord; /* Number of coordinates */
  8647. int iLevel; /* Level of current node or entry */
  8648. int mxLevel; /* The largest iLevel value in the tree */
  8649. sqlite3_int64 iRowid; /* Rowid for current entry */
  8650. sqlite3_rtree_dbl rParentScore; /* Score of parent node */
  8651. int eParentWithin; /* Visibility of parent node */
  8652. int eWithin; /* OUT: Visiblity */
  8653. sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
  8654. /* The following fields are only available in 3.8.11 and later */
  8655. sqlite3_value **apSqlParam; /* Original SQL values of parameters */
  8656. };
  8657. /*
  8658. ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
  8659. */
  8660. #define NOT_WITHIN 0 /* Object completely outside of query region */
  8661. #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
  8662. #define FULLY_WITHIN 2 /* Object fully contained within query region */
  8663. #if 0
  8664. } /* end of the 'extern "C"' block */
  8665. #endif
  8666. #endif /* ifndef _SQLITE3RTREE_H_ */
  8667. /******** End of sqlite3rtree.h *********/
  8668. /******** Begin file sqlite3session.h *********/
  8669. #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
  8670. #define __SQLITESESSION_H_ 1
  8671. /*
  8672. ** Make sure we can call this stuff from C++.
  8673. */
  8674. #if 0
  8675. extern "C" {
  8676. #endif
  8677. /*
  8678. ** CAPI3REF: Session Object Handle
  8679. */
  8680. typedef struct sqlite3_session sqlite3_session;
  8681. /*
  8682. ** CAPI3REF: Changeset Iterator Handle
  8683. */
  8684. typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
  8685. /*
  8686. ** CAPI3REF: Create A New Session Object
  8687. **
  8688. ** Create a new session object attached to database handle db. If successful,
  8689. ** a pointer to the new object is written to *ppSession and SQLITE_OK is
  8690. ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
  8691. ** error code (e.g. SQLITE_NOMEM) is returned.
  8692. **
  8693. ** It is possible to create multiple session objects attached to a single
  8694. ** database handle.
  8695. **
  8696. ** Session objects created using this function should be deleted using the
  8697. ** [sqlite3session_delete()] function before the database handle that they
  8698. ** are attached to is itself closed. If the database handle is closed before
  8699. ** the session object is deleted, then the results of calling any session
  8700. ** module function, including [sqlite3session_delete()] on the session object
  8701. ** are undefined.
  8702. **
  8703. ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
  8704. ** is not possible for an application to register a pre-update hook on a
  8705. ** database handle that has one or more session objects attached. Nor is
  8706. ** it possible to create a session object attached to a database handle for
  8707. ** which a pre-update hook is already defined. The results of attempting
  8708. ** either of these things are undefined.
  8709. **
  8710. ** The session object will be used to create changesets for tables in
  8711. ** database zDb, where zDb is either "main", or "temp", or the name of an
  8712. ** attached database. It is not an error if database zDb is not attached
  8713. ** to the database when the session object is created.
  8714. */
  8715. SQLITE_API int sqlite3session_create(
  8716. sqlite3 *db, /* Database handle */
  8717. const char *zDb, /* Name of db (e.g. "main") */
  8718. sqlite3_session **ppSession /* OUT: New session object */
  8719. );
  8720. /*
  8721. ** CAPI3REF: Delete A Session Object
  8722. **
  8723. ** Delete a session object previously allocated using
  8724. ** [sqlite3session_create()]. Once a session object has been deleted, the
  8725. ** results of attempting to use pSession with any other session module
  8726. ** function are undefined.
  8727. **
  8728. ** Session objects must be deleted before the database handle to which they
  8729. ** are attached is closed. Refer to the documentation for
  8730. ** [sqlite3session_create()] for details.
  8731. */
  8732. SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
  8733. /*
  8734. ** CAPI3REF: Enable Or Disable A Session Object
  8735. **
  8736. ** Enable or disable the recording of changes by a session object. When
  8737. ** enabled, a session object records changes made to the database. When
  8738. ** disabled - it does not. A newly created session object is enabled.
  8739. ** Refer to the documentation for [sqlite3session_changeset()] for further
  8740. ** details regarding how enabling and disabling a session object affects
  8741. ** the eventual changesets.
  8742. **
  8743. ** Passing zero to this function disables the session. Passing a value
  8744. ** greater than zero enables it. Passing a value less than zero is a
  8745. ** no-op, and may be used to query the current state of the session.
  8746. **
  8747. ** The return value indicates the final state of the session object: 0 if
  8748. ** the session is disabled, or 1 if it is enabled.
  8749. */
  8750. SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
  8751. /*
  8752. ** CAPI3REF: Set Or Clear the Indirect Change Flag
  8753. **
  8754. ** Each change recorded by a session object is marked as either direct or
  8755. ** indirect. A change is marked as indirect if either:
  8756. **
  8757. ** <ul>
  8758. ** <li> The session object "indirect" flag is set when the change is
  8759. ** made, or
  8760. ** <li> The change is made by an SQL trigger or foreign key action
  8761. ** instead of directly as a result of a users SQL statement.
  8762. ** </ul>
  8763. **
  8764. ** If a single row is affected by more than one operation within a session,
  8765. ** then the change is considered indirect if all operations meet the criteria
  8766. ** for an indirect change above, or direct otherwise.
  8767. **
  8768. ** This function is used to set, clear or query the session object indirect
  8769. ** flag. If the second argument passed to this function is zero, then the
  8770. ** indirect flag is cleared. If it is greater than zero, the indirect flag
  8771. ** is set. Passing a value less than zero does not modify the current value
  8772. ** of the indirect flag, and may be used to query the current state of the
  8773. ** indirect flag for the specified session object.
  8774. **
  8775. ** The return value indicates the final state of the indirect flag: 0 if
  8776. ** it is clear, or 1 if it is set.
  8777. */
  8778. SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
  8779. /*
  8780. ** CAPI3REF: Attach A Table To A Session Object
  8781. **
  8782. ** If argument zTab is not NULL, then it is the name of a table to attach
  8783. ** to the session object passed as the first argument. All subsequent changes
  8784. ** made to the table while the session object is enabled will be recorded. See
  8785. ** documentation for [sqlite3session_changeset()] for further details.
  8786. **
  8787. ** Or, if argument zTab is NULL, then changes are recorded for all tables
  8788. ** in the database. If additional tables are added to the database (by
  8789. ** executing "CREATE TABLE" statements) after this call is made, changes for
  8790. ** the new tables are also recorded.
  8791. **
  8792. ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
  8793. ** defined as part of their CREATE TABLE statement. It does not matter if the
  8794. ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
  8795. ** KEY may consist of a single column, or may be a composite key.
  8796. **
  8797. ** It is not an error if the named table does not exist in the database. Nor
  8798. ** is it an error if the named table does not have a PRIMARY KEY. However,
  8799. ** no changes will be recorded in either of these scenarios.
  8800. **
  8801. ** Changes are not recorded for individual rows that have NULL values stored
  8802. ** in one or more of their PRIMARY KEY columns.
  8803. **
  8804. ** SQLITE_OK is returned if the call completes without error. Or, if an error
  8805. ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
  8806. */
  8807. SQLITE_API int sqlite3session_attach(
  8808. sqlite3_session *pSession, /* Session object */
  8809. const char *zTab /* Table name */
  8810. );
  8811. /*
  8812. ** CAPI3REF: Set a table filter on a Session Object.
  8813. **
  8814. ** The second argument (xFilter) is the "filter callback". For changes to rows
  8815. ** in tables that are not attached to the Session object, the filter is called
  8816. ** to determine whether changes to the table's rows should be tracked or not.
  8817. ** If xFilter returns 0, changes is not tracked. Note that once a table is
  8818. ** attached, xFilter will not be called again.
  8819. */
  8820. SQLITE_API void sqlite3session_table_filter(
  8821. sqlite3_session *pSession, /* Session object */
  8822. int(*xFilter)(
  8823. void *pCtx, /* Copy of third arg to _filter_table() */
  8824. const char *zTab /* Table name */
  8825. ),
  8826. void *pCtx /* First argument passed to xFilter */
  8827. );
  8828. /*
  8829. ** CAPI3REF: Generate A Changeset From A Session Object
  8830. **
  8831. ** Obtain a changeset containing changes to the tables attached to the
  8832. ** session object passed as the first argument. If successful,
  8833. ** set *ppChangeset to point to a buffer containing the changeset
  8834. ** and *pnChangeset to the size of the changeset in bytes before returning
  8835. ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
  8836. ** zero and return an SQLite error code.
  8837. **
  8838. ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
  8839. ** each representing a change to a single row of an attached table. An INSERT
  8840. ** change contains the values of each field of a new database row. A DELETE
  8841. ** contains the original values of each field of a deleted database row. An
  8842. ** UPDATE change contains the original values of each field of an updated
  8843. ** database row along with the updated values for each updated non-primary-key
  8844. ** column. It is not possible for an UPDATE change to represent a change that
  8845. ** modifies the values of primary key columns. If such a change is made, it
  8846. ** is represented in a changeset as a DELETE followed by an INSERT.
  8847. **
  8848. ** Changes are not recorded for rows that have NULL values stored in one or
  8849. ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
  8850. ** no corresponding change is present in the changesets returned by this
  8851. ** function. If an existing row with one or more NULL values stored in
  8852. ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
  8853. ** only an INSERT is appears in the changeset. Similarly, if an existing row
  8854. ** with non-NULL PRIMARY KEY values is updated so that one or more of its
  8855. ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
  8856. ** DELETE change only.
  8857. **
  8858. ** The contents of a changeset may be traversed using an iterator created
  8859. ** using the [sqlite3changeset_start()] API. A changeset may be applied to
  8860. ** a database with a compatible schema using the [sqlite3changeset_apply()]
  8861. ** API.
  8862. **
  8863. ** Within a changeset generated by this function, all changes related to a
  8864. ** single table are grouped together. In other words, when iterating through
  8865. ** a changeset or when applying a changeset to a database, all changes related
  8866. ** to a single table are processed before moving on to the next table. Tables
  8867. ** are sorted in the same order in which they were attached (or auto-attached)
  8868. ** to the sqlite3_session object. The order in which the changes related to
  8869. ** a single table are stored is undefined.
  8870. **
  8871. ** Following a successful call to this function, it is the responsibility of
  8872. ** the caller to eventually free the buffer that *ppChangeset points to using
  8873. ** [sqlite3_free()].
  8874. **
  8875. ** <h3>Changeset Generation</h3>
  8876. **
  8877. ** Once a table has been attached to a session object, the session object
  8878. ** records the primary key values of all new rows inserted into the table.
  8879. ** It also records the original primary key and other column values of any
  8880. ** deleted or updated rows. For each unique primary key value, data is only
  8881. ** recorded once - the first time a row with said primary key is inserted,
  8882. ** updated or deleted in the lifetime of the session.
  8883. **
  8884. ** There is one exception to the previous paragraph: when a row is inserted,
  8885. ** updated or deleted, if one or more of its primary key columns contain a
  8886. ** NULL value, no record of the change is made.
  8887. **
  8888. ** The session object therefore accumulates two types of records - those
  8889. ** that consist of primary key values only (created when the user inserts
  8890. ** a new record) and those that consist of the primary key values and the
  8891. ** original values of other table columns (created when the users deletes
  8892. ** or updates a record).
  8893. **
  8894. ** When this function is called, the requested changeset is created using
  8895. ** both the accumulated records and the current contents of the database
  8896. ** file. Specifically:
  8897. **
  8898. ** <ul>
  8899. ** <li> For each record generated by an insert, the database is queried
  8900. ** for a row with a matching primary key. If one is found, an INSERT
  8901. ** change is added to the changeset. If no such row is found, no change
  8902. ** is added to the changeset.
  8903. **
  8904. ** <li> For each record generated by an update or delete, the database is
  8905. ** queried for a row with a matching primary key. If such a row is
  8906. ** found and one or more of the non-primary key fields have been
  8907. ** modified from their original values, an UPDATE change is added to
  8908. ** the changeset. Or, if no such row is found in the table, a DELETE
  8909. ** change is added to the changeset. If there is a row with a matching
  8910. ** primary key in the database, but all fields contain their original
  8911. ** values, no change is added to the changeset.
  8912. ** </ul>
  8913. **
  8914. ** This means, amongst other things, that if a row is inserted and then later
  8915. ** deleted while a session object is active, neither the insert nor the delete
  8916. ** will be present in the changeset. Or if a row is deleted and then later a
  8917. ** row with the same primary key values inserted while a session object is
  8918. ** active, the resulting changeset will contain an UPDATE change instead of
  8919. ** a DELETE and an INSERT.
  8920. **
  8921. ** When a session object is disabled (see the [sqlite3session_enable()] API),
  8922. ** it does not accumulate records when rows are inserted, updated or deleted.
  8923. ** This may appear to have some counter-intuitive effects if a single row
  8924. ** is written to more than once during a session. For example, if a row
  8925. ** is inserted while a session object is enabled, then later deleted while
  8926. ** the same session object is disabled, no INSERT record will appear in the
  8927. ** changeset, even though the delete took place while the session was disabled.
  8928. ** Or, if one field of a row is updated while a session is disabled, and
  8929. ** another field of the same row is updated while the session is enabled, the
  8930. ** resulting changeset will contain an UPDATE change that updates both fields.
  8931. */
  8932. SQLITE_API int sqlite3session_changeset(
  8933. sqlite3_session *pSession, /* Session object */
  8934. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  8935. void **ppChangeset /* OUT: Buffer containing changeset */
  8936. );
  8937. /*
  8938. ** CAPI3REF: Load The Difference Between Tables Into A Session
  8939. **
  8940. ** If it is not already attached to the session object passed as the first
  8941. ** argument, this function attaches table zTbl in the same manner as the
  8942. ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
  8943. ** does not have a primary key, this function is a no-op (but does not return
  8944. ** an error).
  8945. **
  8946. ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
  8947. ** attached to the same database handle as the session object that contains
  8948. ** a table compatible with the table attached to the session by this function.
  8949. ** A table is considered compatible if it:
  8950. **
  8951. ** <ul>
  8952. ** <li> Has the same name,
  8953. ** <li> Has the same set of columns declared in the same order, and
  8954. ** <li> Has the same PRIMARY KEY definition.
  8955. ** </ul>
  8956. **
  8957. ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
  8958. ** are compatible but do not have any PRIMARY KEY columns, it is not an error
  8959. ** but no changes are added to the session object. As with other session
  8960. ** APIs, tables without PRIMARY KEYs are simply ignored.
  8961. **
  8962. ** This function adds a set of changes to the session object that could be
  8963. ** used to update the table in database zFrom (call this the "from-table")
  8964. ** so that its content is the same as the table attached to the session
  8965. ** object (call this the "to-table"). Specifically:
  8966. **
  8967. ** <ul>
  8968. ** <li> For each row (primary key) that exists in the to-table but not in
  8969. ** the from-table, an INSERT record is added to the session object.
  8970. **
  8971. ** <li> For each row (primary key) that exists in the to-table but not in
  8972. ** the from-table, a DELETE record is added to the session object.
  8973. **
  8974. ** <li> For each row (primary key) that exists in both tables, but features
  8975. ** different non-PK values in each, an UPDATE record is added to the
  8976. ** session.
  8977. ** </ul>
  8978. **
  8979. ** To clarify, if this function is called and then a changeset constructed
  8980. ** using [sqlite3session_changeset()], then after applying that changeset to
  8981. ** database zFrom the contents of the two compatible tables would be
  8982. ** identical.
  8983. **
  8984. ** It an error if database zFrom does not exist or does not contain the
  8985. ** required compatible table.
  8986. **
  8987. ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
  8988. ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
  8989. ** may be set to point to a buffer containing an English language error
  8990. ** message. It is the responsibility of the caller to free this buffer using
  8991. ** sqlite3_free().
  8992. */
  8993. SQLITE_API int sqlite3session_diff(
  8994. sqlite3_session *pSession,
  8995. const char *zFromDb,
  8996. const char *zTbl,
  8997. char **pzErrMsg
  8998. );
  8999. /*
  9000. ** CAPI3REF: Generate A Patchset From A Session Object
  9001. **
  9002. ** The differences between a patchset and a changeset are that:
  9003. **
  9004. ** <ul>
  9005. ** <li> DELETE records consist of the primary key fields only. The
  9006. ** original values of other fields are omitted.
  9007. ** <li> The original values of any modified fields are omitted from
  9008. ** UPDATE records.
  9009. ** </ul>
  9010. **
  9011. ** A patchset blob may be used with up to date versions of all
  9012. ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
  9013. ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
  9014. ** attempting to use a patchset blob with old versions of the
  9015. ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
  9016. **
  9017. ** Because the non-primary key "old.*" fields are omitted, no
  9018. ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
  9019. ** is passed to the sqlite3changeset_apply() API. Other conflict types work
  9020. ** in the same way as for changesets.
  9021. **
  9022. ** Changes within a patchset are ordered in the same way as for changesets
  9023. ** generated by the sqlite3session_changeset() function (i.e. all changes for
  9024. ** a single table are grouped together, tables appear in the order in which
  9025. ** they were attached to the session object).
  9026. */
  9027. SQLITE_API int sqlite3session_patchset(
  9028. sqlite3_session *pSession, /* Session object */
  9029. int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
  9030. void **ppPatchset /* OUT: Buffer containing changeset */
  9031. );
  9032. /*
  9033. ** CAPI3REF: Test if a changeset has recorded any changes.
  9034. **
  9035. ** Return non-zero if no changes to attached tables have been recorded by
  9036. ** the session object passed as the first argument. Otherwise, if one or
  9037. ** more changes have been recorded, return zero.
  9038. **
  9039. ** Even if this function returns zero, it is possible that calling
  9040. ** [sqlite3session_changeset()] on the session handle may still return a
  9041. ** changeset that contains no changes. This can happen when a row in
  9042. ** an attached table is modified and then later on the original values
  9043. ** are restored. However, if this function returns non-zero, then it is
  9044. ** guaranteed that a call to sqlite3session_changeset() will return a
  9045. ** changeset containing zero changes.
  9046. */
  9047. SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
  9048. /*
  9049. ** CAPI3REF: Create An Iterator To Traverse A Changeset
  9050. **
  9051. ** Create an iterator used to iterate through the contents of a changeset.
  9052. ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
  9053. ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
  9054. ** SQLite error code is returned.
  9055. **
  9056. ** The following functions can be used to advance and query a changeset
  9057. ** iterator created by this function:
  9058. **
  9059. ** <ul>
  9060. ** <li> [sqlite3changeset_next()]
  9061. ** <li> [sqlite3changeset_op()]
  9062. ** <li> [sqlite3changeset_new()]
  9063. ** <li> [sqlite3changeset_old()]
  9064. ** </ul>
  9065. **
  9066. ** It is the responsibility of the caller to eventually destroy the iterator
  9067. ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
  9068. ** changeset (pChangeset) must remain valid until after the iterator is
  9069. ** destroyed.
  9070. **
  9071. ** Assuming the changeset blob was created by one of the
  9072. ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
  9073. ** [sqlite3changeset_invert()] functions, all changes within the changeset
  9074. ** that apply to a single table are grouped together. This means that when
  9075. ** an application iterates through a changeset using an iterator created by
  9076. ** this function, all changes that relate to a single table are visited
  9077. ** consecutively. There is no chance that the iterator will visit a change
  9078. ** the applies to table X, then one for table Y, and then later on visit
  9079. ** another change for table X.
  9080. */
  9081. SQLITE_API int sqlite3changeset_start(
  9082. sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
  9083. int nChangeset, /* Size of changeset blob in bytes */
  9084. void *pChangeset /* Pointer to blob containing changeset */
  9085. );
  9086. /*
  9087. ** CAPI3REF: Advance A Changeset Iterator
  9088. **
  9089. ** This function may only be used with iterators created by function
  9090. ** [sqlite3changeset_start()]. If it is called on an iterator passed to
  9091. ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
  9092. ** is returned and the call has no effect.
  9093. **
  9094. ** Immediately after an iterator is created by sqlite3changeset_start(), it
  9095. ** does not point to any change in the changeset. Assuming the changeset
  9096. ** is not empty, the first call to this function advances the iterator to
  9097. ** point to the first change in the changeset. Each subsequent call advances
  9098. ** the iterator to point to the next change in the changeset (if any). If
  9099. ** no error occurs and the iterator points to a valid change after a call
  9100. ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
  9101. ** Otherwise, if all changes in the changeset have already been visited,
  9102. ** SQLITE_DONE is returned.
  9103. **
  9104. ** If an error occurs, an SQLite error code is returned. Possible error
  9105. ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
  9106. ** SQLITE_NOMEM.
  9107. */
  9108. SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
  9109. /*
  9110. ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
  9111. **
  9112. ** The pIter argument passed to this function may either be an iterator
  9113. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  9114. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  9115. ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
  9116. ** is not the case, this function returns [SQLITE_MISUSE].
  9117. **
  9118. ** If argument pzTab is not NULL, then *pzTab is set to point to a
  9119. ** nul-terminated utf-8 encoded string containing the name of the table
  9120. ** affected by the current change. The buffer remains valid until either
  9121. ** sqlite3changeset_next() is called on the iterator or until the
  9122. ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
  9123. ** set to the number of columns in the table affected by the change. If
  9124. ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
  9125. ** is an indirect change, or false (0) otherwise. See the documentation for
  9126. ** [sqlite3session_indirect()] for a description of direct and indirect
  9127. ** changes. Finally, if pOp is not NULL, then *pOp is set to one of
  9128. ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
  9129. ** type of change that the iterator currently points to.
  9130. **
  9131. ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
  9132. ** SQLite error code is returned. The values of the output variables may not
  9133. ** be trusted in this case.
  9134. */
  9135. SQLITE_API int sqlite3changeset_op(
  9136. sqlite3_changeset_iter *pIter, /* Iterator object */
  9137. const char **pzTab, /* OUT: Pointer to table name */
  9138. int *pnCol, /* OUT: Number of columns in table */
  9139. int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
  9140. int *pbIndirect /* OUT: True for an 'indirect' change */
  9141. );
  9142. /*
  9143. ** CAPI3REF: Obtain The Primary Key Definition Of A Table
  9144. **
  9145. ** For each modified table, a changeset includes the following:
  9146. **
  9147. ** <ul>
  9148. ** <li> The number of columns in the table, and
  9149. ** <li> Which of those columns make up the tables PRIMARY KEY.
  9150. ** </ul>
  9151. **
  9152. ** This function is used to find which columns comprise the PRIMARY KEY of
  9153. ** the table modified by the change that iterator pIter currently points to.
  9154. ** If successful, *pabPK is set to point to an array of nCol entries, where
  9155. ** nCol is the number of columns in the table. Elements of *pabPK are set to
  9156. ** 0x01 if the corresponding column is part of the tables primary key, or
  9157. ** 0x00 if it is not.
  9158. **
  9159. ** If argument pnCol is not NULL, then *pnCol is set to the number of columns
  9160. ** in the table.
  9161. **
  9162. ** If this function is called when the iterator does not point to a valid
  9163. ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
  9164. ** SQLITE_OK is returned and the output variables populated as described
  9165. ** above.
  9166. */
  9167. SQLITE_API int sqlite3changeset_pk(
  9168. sqlite3_changeset_iter *pIter, /* Iterator object */
  9169. unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
  9170. int *pnCol /* OUT: Number of entries in output array */
  9171. );
  9172. /*
  9173. ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
  9174. **
  9175. ** The pIter argument passed to this function may either be an iterator
  9176. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  9177. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  9178. ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
  9179. ** Furthermore, it may only be called if the type of change that the iterator
  9180. ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
  9181. ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
  9182. **
  9183. ** Argument iVal must be greater than or equal to 0, and less than the number
  9184. ** of columns in the table affected by the current change. Otherwise,
  9185. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  9186. **
  9187. ** If successful, this function sets *ppValue to point to a protected
  9188. ** sqlite3_value object containing the iVal'th value from the vector of
  9189. ** original row values stored as part of the UPDATE or DELETE change and
  9190. ** returns SQLITE_OK. The name of the function comes from the fact that this
  9191. ** is similar to the "old.*" columns available to update or delete triggers.
  9192. **
  9193. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  9194. ** is returned and *ppValue is set to NULL.
  9195. */
  9196. SQLITE_API int sqlite3changeset_old(
  9197. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  9198. int iVal, /* Column number */
  9199. sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
  9200. );
  9201. /*
  9202. ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
  9203. **
  9204. ** The pIter argument passed to this function may either be an iterator
  9205. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  9206. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  9207. ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
  9208. ** Furthermore, it may only be called if the type of change that the iterator
  9209. ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
  9210. ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
  9211. **
  9212. ** Argument iVal must be greater than or equal to 0, and less than the number
  9213. ** of columns in the table affected by the current change. Otherwise,
  9214. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  9215. **
  9216. ** If successful, this function sets *ppValue to point to a protected
  9217. ** sqlite3_value object containing the iVal'th value from the vector of
  9218. ** new row values stored as part of the UPDATE or INSERT change and
  9219. ** returns SQLITE_OK. If the change is an UPDATE and does not include
  9220. ** a new value for the requested column, *ppValue is set to NULL and
  9221. ** SQLITE_OK returned. The name of the function comes from the fact that
  9222. ** this is similar to the "new.*" columns available to update or delete
  9223. ** triggers.
  9224. **
  9225. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  9226. ** is returned and *ppValue is set to NULL.
  9227. */
  9228. SQLITE_API int sqlite3changeset_new(
  9229. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  9230. int iVal, /* Column number */
  9231. sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
  9232. );
  9233. /*
  9234. ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
  9235. **
  9236. ** This function should only be used with iterator objects passed to a
  9237. ** conflict-handler callback by [sqlite3changeset_apply()] with either
  9238. ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
  9239. ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
  9240. ** is set to NULL.
  9241. **
  9242. ** Argument iVal must be greater than or equal to 0, and less than the number
  9243. ** of columns in the table affected by the current change. Otherwise,
  9244. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  9245. **
  9246. ** If successful, this function sets *ppValue to point to a protected
  9247. ** sqlite3_value object containing the iVal'th value from the
  9248. ** "conflicting row" associated with the current conflict-handler callback
  9249. ** and returns SQLITE_OK.
  9250. **
  9251. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  9252. ** is returned and *ppValue is set to NULL.
  9253. */
  9254. SQLITE_API int sqlite3changeset_conflict(
  9255. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  9256. int iVal, /* Column number */
  9257. sqlite3_value **ppValue /* OUT: Value from conflicting row */
  9258. );
  9259. /*
  9260. ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
  9261. **
  9262. ** This function may only be called with an iterator passed to an
  9263. ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
  9264. ** it sets the output variable to the total number of known foreign key
  9265. ** violations in the destination database and returns SQLITE_OK.
  9266. **
  9267. ** In all other cases this function returns SQLITE_MISUSE.
  9268. */
  9269. SQLITE_API int sqlite3changeset_fk_conflicts(
  9270. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  9271. int *pnOut /* OUT: Number of FK violations */
  9272. );
  9273. /*
  9274. ** CAPI3REF: Finalize A Changeset Iterator
  9275. **
  9276. ** This function is used to finalize an iterator allocated with
  9277. ** [sqlite3changeset_start()].
  9278. **
  9279. ** This function should only be called on iterators created using the
  9280. ** [sqlite3changeset_start()] function. If an application calls this
  9281. ** function with an iterator passed to a conflict-handler by
  9282. ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
  9283. ** call has no effect.
  9284. **
  9285. ** If an error was encountered within a call to an sqlite3changeset_xxx()
  9286. ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
  9287. ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
  9288. ** to that error is returned by this function. Otherwise, SQLITE_OK is
  9289. ** returned. This is to allow the following pattern (pseudo-code):
  9290. **
  9291. ** sqlite3changeset_start();
  9292. ** while( SQLITE_ROW==sqlite3changeset_next() ){
  9293. ** // Do something with change.
  9294. ** }
  9295. ** rc = sqlite3changeset_finalize();
  9296. ** if( rc!=SQLITE_OK ){
  9297. ** // An error has occurred
  9298. ** }
  9299. */
  9300. SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
  9301. /*
  9302. ** CAPI3REF: Invert A Changeset
  9303. **
  9304. ** This function is used to "invert" a changeset object. Applying an inverted
  9305. ** changeset to a database reverses the effects of applying the uninverted
  9306. ** changeset. Specifically:
  9307. **
  9308. ** <ul>
  9309. ** <li> Each DELETE change is changed to an INSERT, and
  9310. ** <li> Each INSERT change is changed to a DELETE, and
  9311. ** <li> For each UPDATE change, the old.* and new.* values are exchanged.
  9312. ** </ul>
  9313. **
  9314. ** This function does not change the order in which changes appear within
  9315. ** the changeset. It merely reverses the sense of each individual change.
  9316. **
  9317. ** If successful, a pointer to a buffer containing the inverted changeset
  9318. ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
  9319. ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
  9320. ** zeroed and an SQLite error code returned.
  9321. **
  9322. ** It is the responsibility of the caller to eventually call sqlite3_free()
  9323. ** on the *ppOut pointer to free the buffer allocation following a successful
  9324. ** call to this function.
  9325. **
  9326. ** WARNING/TODO: This function currently assumes that the input is a valid
  9327. ** changeset. If it is not, the results are undefined.
  9328. */
  9329. SQLITE_API int sqlite3changeset_invert(
  9330. int nIn, const void *pIn, /* Input changeset */
  9331. int *pnOut, void **ppOut /* OUT: Inverse of input */
  9332. );
  9333. /*
  9334. ** CAPI3REF: Concatenate Two Changeset Objects
  9335. **
  9336. ** This function is used to concatenate two changesets, A and B, into a
  9337. ** single changeset. The result is a changeset equivalent to applying
  9338. ** changeset A followed by changeset B.
  9339. **
  9340. ** This function combines the two input changesets using an
  9341. ** sqlite3_changegroup object. Calling it produces similar results as the
  9342. ** following code fragment:
  9343. **
  9344. ** sqlite3_changegroup *pGrp;
  9345. ** rc = sqlite3_changegroup_new(&pGrp);
  9346. ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
  9347. ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
  9348. ** if( rc==SQLITE_OK ){
  9349. ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
  9350. ** }else{
  9351. ** *ppOut = 0;
  9352. ** *pnOut = 0;
  9353. ** }
  9354. **
  9355. ** Refer to the sqlite3_changegroup documentation below for details.
  9356. */
  9357. SQLITE_API int sqlite3changeset_concat(
  9358. int nA, /* Number of bytes in buffer pA */
  9359. void *pA, /* Pointer to buffer containing changeset A */
  9360. int nB, /* Number of bytes in buffer pB */
  9361. void *pB, /* Pointer to buffer containing changeset B */
  9362. int *pnOut, /* OUT: Number of bytes in output changeset */
  9363. void **ppOut /* OUT: Buffer containing output changeset */
  9364. );
  9365. /*
  9366. ** CAPI3REF: Changegroup Handle
  9367. */
  9368. typedef struct sqlite3_changegroup sqlite3_changegroup;
  9369. /*
  9370. ** CAPI3REF: Create A New Changegroup Object
  9371. **
  9372. ** An sqlite3_changegroup object is used to combine two or more changesets
  9373. ** (or patchsets) into a single changeset (or patchset). A single changegroup
  9374. ** object may combine changesets or patchsets, but not both. The output is
  9375. ** always in the same format as the input.
  9376. **
  9377. ** If successful, this function returns SQLITE_OK and populates (*pp) with
  9378. ** a pointer to a new sqlite3_changegroup object before returning. The caller
  9379. ** should eventually free the returned object using a call to
  9380. ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
  9381. ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
  9382. **
  9383. ** The usual usage pattern for an sqlite3_changegroup object is as follows:
  9384. **
  9385. ** <ul>
  9386. ** <li> It is created using a call to sqlite3changegroup_new().
  9387. **
  9388. ** <li> Zero or more changesets (or patchsets) are added to the object
  9389. ** by calling sqlite3changegroup_add().
  9390. **
  9391. ** <li> The result of combining all input changesets together is obtained
  9392. ** by the application via a call to sqlite3changegroup_output().
  9393. **
  9394. ** <li> The object is deleted using a call to sqlite3changegroup_delete().
  9395. ** </ul>
  9396. **
  9397. ** Any number of calls to add() and output() may be made between the calls to
  9398. ** new() and delete(), and in any order.
  9399. **
  9400. ** As well as the regular sqlite3changegroup_add() and
  9401. ** sqlite3changegroup_output() functions, also available are the streaming
  9402. ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
  9403. */
  9404. SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
  9405. /*
  9406. ** CAPI3REF: Add A Changeset To A Changegroup
  9407. **
  9408. ** Add all changes within the changeset (or patchset) in buffer pData (size
  9409. ** nData bytes) to the changegroup.
  9410. **
  9411. ** If the buffer contains a patchset, then all prior calls to this function
  9412. ** on the same changegroup object must also have specified patchsets. Or, if
  9413. ** the buffer contains a changeset, so must have the earlier calls to this
  9414. ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
  9415. ** to the changegroup.
  9416. **
  9417. ** Rows within the changeset and changegroup are identified by the values in
  9418. ** their PRIMARY KEY columns. A change in the changeset is considered to
  9419. ** apply to the same row as a change already present in the changegroup if
  9420. ** the two rows have the same primary key.
  9421. **
  9422. ** Changes to rows that do not already appear in the changegroup are
  9423. ** simply copied into it. Or, if both the new changeset and the changegroup
  9424. ** contain changes that apply to a single row, the final contents of the
  9425. ** changegroup depends on the type of each change, as follows:
  9426. **
  9427. ** <table border=1 style="margin-left:8ex;margin-right:8ex">
  9428. ** <tr><th style="white-space:pre">Existing Change </th>
  9429. ** <th style="white-space:pre">New Change </th>
  9430. ** <th>Output Change
  9431. ** <tr><td>INSERT <td>INSERT <td>
  9432. ** The new change is ignored. This case does not occur if the new
  9433. ** changeset was recorded immediately after the changesets already
  9434. ** added to the changegroup.
  9435. ** <tr><td>INSERT <td>UPDATE <td>
  9436. ** The INSERT change remains in the changegroup. The values in the
  9437. ** INSERT change are modified as if the row was inserted by the
  9438. ** existing change and then updated according to the new change.
  9439. ** <tr><td>INSERT <td>DELETE <td>
  9440. ** The existing INSERT is removed from the changegroup. The DELETE is
  9441. ** not added.
  9442. ** <tr><td>UPDATE <td>INSERT <td>
  9443. ** The new change is ignored. This case does not occur if the new
  9444. ** changeset was recorded immediately after the changesets already
  9445. ** added to the changegroup.
  9446. ** <tr><td>UPDATE <td>UPDATE <td>
  9447. ** The existing UPDATE remains within the changegroup. It is amended
  9448. ** so that the accompanying values are as if the row was updated once
  9449. ** by the existing change and then again by the new change.
  9450. ** <tr><td>UPDATE <td>DELETE <td>
  9451. ** The existing UPDATE is replaced by the new DELETE within the
  9452. ** changegroup.
  9453. ** <tr><td>DELETE <td>INSERT <td>
  9454. ** If one or more of the column values in the row inserted by the
  9455. ** new change differ from those in the row deleted by the existing
  9456. ** change, the existing DELETE is replaced by an UPDATE within the
  9457. ** changegroup. Otherwise, if the inserted row is exactly the same
  9458. ** as the deleted row, the existing DELETE is simply discarded.
  9459. ** <tr><td>DELETE <td>UPDATE <td>
  9460. ** The new change is ignored. This case does not occur if the new
  9461. ** changeset was recorded immediately after the changesets already
  9462. ** added to the changegroup.
  9463. ** <tr><td>DELETE <td>DELETE <td>
  9464. ** The new change is ignored. This case does not occur if the new
  9465. ** changeset was recorded immediately after the changesets already
  9466. ** added to the changegroup.
  9467. ** </table>
  9468. **
  9469. ** If the new changeset contains changes to a table that is already present
  9470. ** in the changegroup, then the number of columns and the position of the
  9471. ** primary key columns for the table must be consistent. If this is not the
  9472. ** case, this function fails with SQLITE_SCHEMA. If the input changeset
  9473. ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
  9474. ** returned. Or, if an out-of-memory condition occurs during processing, this
  9475. ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
  9476. ** final contents of the changegroup is undefined.
  9477. **
  9478. ** If no error occurs, SQLITE_OK is returned.
  9479. */
  9480. SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
  9481. /*
  9482. ** CAPI3REF: Obtain A Composite Changeset From A Changegroup
  9483. **
  9484. ** Obtain a buffer containing a changeset (or patchset) representing the
  9485. ** current contents of the changegroup. If the inputs to the changegroup
  9486. ** were themselves changesets, the output is a changeset. Or, if the
  9487. ** inputs were patchsets, the output is also a patchset.
  9488. **
  9489. ** As with the output of the sqlite3session_changeset() and
  9490. ** sqlite3session_patchset() functions, all changes related to a single
  9491. ** table are grouped together in the output of this function. Tables appear
  9492. ** in the same order as for the very first changeset added to the changegroup.
  9493. ** If the second or subsequent changesets added to the changegroup contain
  9494. ** changes for tables that do not appear in the first changeset, they are
  9495. ** appended onto the end of the output changeset, again in the order in
  9496. ** which they are first encountered.
  9497. **
  9498. ** If an error occurs, an SQLite error code is returned and the output
  9499. ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
  9500. ** is returned and the output variables are set to the size of and a
  9501. ** pointer to the output buffer, respectively. In this case it is the
  9502. ** responsibility of the caller to eventually free the buffer using a
  9503. ** call to sqlite3_free().
  9504. */
  9505. SQLITE_API int sqlite3changegroup_output(
  9506. sqlite3_changegroup*,
  9507. int *pnData, /* OUT: Size of output buffer in bytes */
  9508. void **ppData /* OUT: Pointer to output buffer */
  9509. );
  9510. /*
  9511. ** CAPI3REF: Delete A Changegroup Object
  9512. */
  9513. SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
  9514. /*
  9515. ** CAPI3REF: Apply A Changeset To A Database
  9516. **
  9517. ** Apply a changeset to a database. This function attempts to update the
  9518. ** "main" database attached to handle db with the changes found in the
  9519. ** changeset passed via the second and third arguments.
  9520. **
  9521. ** The fourth argument (xFilter) passed to this function is the "filter
  9522. ** callback". If it is not NULL, then for each table affected by at least one
  9523. ** change in the changeset, the filter callback is invoked with
  9524. ** the table name as the second argument, and a copy of the context pointer
  9525. ** passed as the sixth argument to this function as the first. If the "filter
  9526. ** callback" returns zero, then no attempt is made to apply any changes to
  9527. ** the table. Otherwise, if the return value is non-zero or the xFilter
  9528. ** argument to this function is NULL, all changes related to the table are
  9529. ** attempted.
  9530. **
  9531. ** For each table that is not excluded by the filter callback, this function
  9532. ** tests that the target database contains a compatible table. A table is
  9533. ** considered compatible if all of the following are true:
  9534. **
  9535. ** <ul>
  9536. ** <li> The table has the same name as the name recorded in the
  9537. ** changeset, and
  9538. ** <li> The table has at least as many columns as recorded in the
  9539. ** changeset, and
  9540. ** <li> The table has primary key columns in the same position as
  9541. ** recorded in the changeset.
  9542. ** </ul>
  9543. **
  9544. ** If there is no compatible table, it is not an error, but none of the
  9545. ** changes associated with the table are applied. A warning message is issued
  9546. ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
  9547. ** one such warning is issued for each table in the changeset.
  9548. **
  9549. ** For each change for which there is a compatible table, an attempt is made
  9550. ** to modify the table contents according to the UPDATE, INSERT or DELETE
  9551. ** change. If a change cannot be applied cleanly, the conflict handler
  9552. ** function passed as the fifth argument to sqlite3changeset_apply() may be
  9553. ** invoked. A description of exactly when the conflict handler is invoked for
  9554. ** each type of change is below.
  9555. **
  9556. ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
  9557. ** of passing anything other than a valid function pointer as the xConflict
  9558. ** argument are undefined.
  9559. **
  9560. ** Each time the conflict handler function is invoked, it must return one
  9561. ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
  9562. ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
  9563. ** if the second argument passed to the conflict handler is either
  9564. ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
  9565. ** returns an illegal value, any changes already made are rolled back and
  9566. ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
  9567. ** actions are taken by sqlite3changeset_apply() depending on the value
  9568. ** returned by each invocation of the conflict-handler function. Refer to
  9569. ** the documentation for the three
  9570. ** [SQLITE_CHANGESET_OMIT|available return values] for details.
  9571. **
  9572. ** <dl>
  9573. ** <dt>DELETE Changes<dd>
  9574. ** For each DELETE change, this function checks if the target database
  9575. ** contains a row with the same primary key value (or values) as the
  9576. ** original row values stored in the changeset. If it does, and the values
  9577. ** stored in all non-primary key columns also match the values stored in
  9578. ** the changeset the row is deleted from the target database.
  9579. **
  9580. ** If a row with matching primary key values is found, but one or more of
  9581. ** the non-primary key fields contains a value different from the original
  9582. ** row value stored in the changeset, the conflict-handler function is
  9583. ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
  9584. ** database table has more columns than are recorded in the changeset,
  9585. ** only the values of those non-primary key fields are compared against
  9586. ** the current database contents - any trailing database table columns
  9587. ** are ignored.
  9588. **
  9589. ** If no row with matching primary key values is found in the database,
  9590. ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
  9591. ** passed as the second argument.
  9592. **
  9593. ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
  9594. ** (which can only happen if a foreign key constraint is violated), the
  9595. ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
  9596. ** passed as the second argument. This includes the case where the DELETE
  9597. ** operation is attempted because an earlier call to the conflict handler
  9598. ** function returned [SQLITE_CHANGESET_REPLACE].
  9599. **
  9600. ** <dt>INSERT Changes<dd>
  9601. ** For each INSERT change, an attempt is made to insert the new row into
  9602. ** the database. If the changeset row contains fewer fields than the
  9603. ** database table, the trailing fields are populated with their default
  9604. ** values.
  9605. **
  9606. ** If the attempt to insert the row fails because the database already
  9607. ** contains a row with the same primary key values, the conflict handler
  9608. ** function is invoked with the second argument set to
  9609. ** [SQLITE_CHANGESET_CONFLICT].
  9610. **
  9611. ** If the attempt to insert the row fails because of some other constraint
  9612. ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
  9613. ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
  9614. ** This includes the case where the INSERT operation is re-attempted because
  9615. ** an earlier call to the conflict handler function returned
  9616. ** [SQLITE_CHANGESET_REPLACE].
  9617. **
  9618. ** <dt>UPDATE Changes<dd>
  9619. ** For each UPDATE change, this function checks if the target database
  9620. ** contains a row with the same primary key value (or values) as the
  9621. ** original row values stored in the changeset. If it does, and the values
  9622. ** stored in all modified non-primary key columns also match the values
  9623. ** stored in the changeset the row is updated within the target database.
  9624. **
  9625. ** If a row with matching primary key values is found, but one or more of
  9626. ** the modified non-primary key fields contains a value different from an
  9627. ** original row value stored in the changeset, the conflict-handler function
  9628. ** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
  9629. ** UPDATE changes only contain values for non-primary key fields that are
  9630. ** to be modified, only those fields need to match the original values to
  9631. ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
  9632. **
  9633. ** If no row with matching primary key values is found in the database,
  9634. ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
  9635. ** passed as the second argument.
  9636. **
  9637. ** If the UPDATE operation is attempted, but SQLite returns
  9638. ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
  9639. ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
  9640. ** This includes the case where the UPDATE operation is attempted after
  9641. ** an earlier call to the conflict handler function returned
  9642. ** [SQLITE_CHANGESET_REPLACE].
  9643. ** </dl>
  9644. **
  9645. ** It is safe to execute SQL statements, including those that write to the
  9646. ** table that the callback related to, from within the xConflict callback.
  9647. ** This can be used to further customize the applications conflict
  9648. ** resolution strategy.
  9649. **
  9650. ** All changes made by this function are enclosed in a savepoint transaction.
  9651. ** If any other error (aside from a constraint failure when attempting to
  9652. ** write to the target database) occurs, then the savepoint transaction is
  9653. ** rolled back, restoring the target database to its original state, and an
  9654. ** SQLite error code returned.
  9655. */
  9656. SQLITE_API int sqlite3changeset_apply(
  9657. sqlite3 *db, /* Apply change to "main" db of this handle */
  9658. int nChangeset, /* Size of changeset in bytes */
  9659. void *pChangeset, /* Changeset blob */
  9660. int(*xFilter)(
  9661. void *pCtx, /* Copy of sixth arg to _apply() */
  9662. const char *zTab /* Table name */
  9663. ),
  9664. int(*xConflict)(
  9665. void *pCtx, /* Copy of sixth arg to _apply() */
  9666. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  9667. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  9668. ),
  9669. void *pCtx /* First argument passed to xConflict */
  9670. );
  9671. /*
  9672. ** CAPI3REF: Constants Passed To The Conflict Handler
  9673. **
  9674. ** Values that may be passed as the second argument to a conflict-handler.
  9675. **
  9676. ** <dl>
  9677. ** <dt>SQLITE_CHANGESET_DATA<dd>
  9678. ** The conflict handler is invoked with CHANGESET_DATA as the second argument
  9679. ** when processing a DELETE or UPDATE change if a row with the required
  9680. ** PRIMARY KEY fields is present in the database, but one or more other
  9681. ** (non primary-key) fields modified by the update do not contain the
  9682. ** expected "before" values.
  9683. **
  9684. ** The conflicting row, in this case, is the database row with the matching
  9685. ** primary key.
  9686. **
  9687. ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
  9688. ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
  9689. ** argument when processing a DELETE or UPDATE change if a row with the
  9690. ** required PRIMARY KEY fields is not present in the database.
  9691. **
  9692. ** There is no conflicting row in this case. The results of invoking the
  9693. ** sqlite3changeset_conflict() API are undefined.
  9694. **
  9695. ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
  9696. ** CHANGESET_CONFLICT is passed as the second argument to the conflict
  9697. ** handler while processing an INSERT change if the operation would result
  9698. ** in duplicate primary key values.
  9699. **
  9700. ** The conflicting row in this case is the database row with the matching
  9701. ** primary key.
  9702. **
  9703. ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
  9704. ** If foreign key handling is enabled, and applying a changeset leaves the
  9705. ** database in a state containing foreign key violations, the conflict
  9706. ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
  9707. ** exactly once before the changeset is committed. If the conflict handler
  9708. ** returns CHANGESET_OMIT, the changes, including those that caused the
  9709. ** foreign key constraint violation, are committed. Or, if it returns
  9710. ** CHANGESET_ABORT, the changeset is rolled back.
  9711. **
  9712. ** No current or conflicting row information is provided. The only function
  9713. ** it is possible to call on the supplied sqlite3_changeset_iter handle
  9714. ** is sqlite3changeset_fk_conflicts().
  9715. **
  9716. ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
  9717. ** If any other constraint violation occurs while applying a change (i.e.
  9718. ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
  9719. ** invoked with CHANGESET_CONSTRAINT as the second argument.
  9720. **
  9721. ** There is no conflicting row in this case. The results of invoking the
  9722. ** sqlite3changeset_conflict() API are undefined.
  9723. **
  9724. ** </dl>
  9725. */
  9726. #define SQLITE_CHANGESET_DATA 1
  9727. #define SQLITE_CHANGESET_NOTFOUND 2
  9728. #define SQLITE_CHANGESET_CONFLICT 3
  9729. #define SQLITE_CHANGESET_CONSTRAINT 4
  9730. #define SQLITE_CHANGESET_FOREIGN_KEY 5
  9731. /*
  9732. ** CAPI3REF: Constants Returned By The Conflict Handler
  9733. **
  9734. ** A conflict handler callback must return one of the following three values.
  9735. **
  9736. ** <dl>
  9737. ** <dt>SQLITE_CHANGESET_OMIT<dd>
  9738. ** If a conflict handler returns this value no special action is taken. The
  9739. ** change that caused the conflict is not applied. The session module
  9740. ** continues to the next change in the changeset.
  9741. **
  9742. ** <dt>SQLITE_CHANGESET_REPLACE<dd>
  9743. ** This value may only be returned if the second argument to the conflict
  9744. ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
  9745. ** is not the case, any changes applied so far are rolled back and the
  9746. ** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
  9747. **
  9748. ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
  9749. ** handler, then the conflicting row is either updated or deleted, depending
  9750. ** on the type of change.
  9751. **
  9752. ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
  9753. ** handler, then the conflicting row is removed from the database and a
  9754. ** second attempt to apply the change is made. If this second attempt fails,
  9755. ** the original row is restored to the database before continuing.
  9756. **
  9757. ** <dt>SQLITE_CHANGESET_ABORT<dd>
  9758. ** If this value is returned, any changes applied so far are rolled back
  9759. ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
  9760. ** </dl>
  9761. */
  9762. #define SQLITE_CHANGESET_OMIT 0
  9763. #define SQLITE_CHANGESET_REPLACE 1
  9764. #define SQLITE_CHANGESET_ABORT 2
  9765. /*
  9766. ** CAPI3REF: Streaming Versions of API functions.
  9767. **
  9768. ** The six streaming API xxx_strm() functions serve similar purposes to the
  9769. ** corresponding non-streaming API functions:
  9770. **
  9771. ** <table border=1 style="margin-left:8ex;margin-right:8ex">
  9772. ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
  9773. ** <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply]
  9774. ** <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat]
  9775. ** <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert]
  9776. ** <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start]
  9777. ** <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset]
  9778. ** <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset]
  9779. ** </table>
  9780. **
  9781. ** Non-streaming functions that accept changesets (or patchsets) as input
  9782. ** require that the entire changeset be stored in a single buffer in memory.
  9783. ** Similarly, those that return a changeset or patchset do so by returning
  9784. ** a pointer to a single large buffer allocated using sqlite3_malloc().
  9785. ** Normally this is convenient. However, if an application running in a
  9786. ** low-memory environment is required to handle very large changesets, the
  9787. ** large contiguous memory allocations required can become onerous.
  9788. **
  9789. ** In order to avoid this problem, instead of a single large buffer, input
  9790. ** is passed to a streaming API functions by way of a callback function that
  9791. ** the sessions module invokes to incrementally request input data as it is
  9792. ** required. In all cases, a pair of API function parameters such as
  9793. **
  9794. ** <pre>
  9795. ** &nbsp; int nChangeset,
  9796. ** &nbsp; void *pChangeset,
  9797. ** </pre>
  9798. **
  9799. ** Is replaced by:
  9800. **
  9801. ** <pre>
  9802. ** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
  9803. ** &nbsp; void *pIn,
  9804. ** </pre>
  9805. **
  9806. ** Each time the xInput callback is invoked by the sessions module, the first
  9807. ** argument passed is a copy of the supplied pIn context pointer. The second
  9808. ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
  9809. ** error occurs the xInput method should copy up to (*pnData) bytes of data
  9810. ** into the buffer and set (*pnData) to the actual number of bytes copied
  9811. ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
  9812. ** should be set to zero to indicate this. Or, if an error occurs, an SQLite
  9813. ** error code should be returned. In all cases, if an xInput callback returns
  9814. ** an error, all processing is abandoned and the streaming API function
  9815. ** returns a copy of the error code to the caller.
  9816. **
  9817. ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
  9818. ** invoked by the sessions module at any point during the lifetime of the
  9819. ** iterator. If such an xInput callback returns an error, the iterator enters
  9820. ** an error state, whereby all subsequent calls to iterator functions
  9821. ** immediately fail with the same error code as returned by xInput.
  9822. **
  9823. ** Similarly, streaming API functions that return changesets (or patchsets)
  9824. ** return them in chunks by way of a callback function instead of via a
  9825. ** pointer to a single large buffer. In this case, a pair of parameters such
  9826. ** as:
  9827. **
  9828. ** <pre>
  9829. ** &nbsp; int *pnChangeset,
  9830. ** &nbsp; void **ppChangeset,
  9831. ** </pre>
  9832. **
  9833. ** Is replaced by:
  9834. **
  9835. ** <pre>
  9836. ** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
  9837. ** &nbsp; void *pOut
  9838. ** </pre>
  9839. **
  9840. ** The xOutput callback is invoked zero or more times to return data to
  9841. ** the application. The first parameter passed to each call is a copy of the
  9842. ** pOut pointer supplied by the application. The second parameter, pData,
  9843. ** points to a buffer nData bytes in size containing the chunk of output
  9844. ** data being returned. If the xOutput callback successfully processes the
  9845. ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
  9846. ** it should return some other SQLite error code. In this case processing
  9847. ** is immediately abandoned and the streaming API function returns a copy
  9848. ** of the xOutput error code to the application.
  9849. **
  9850. ** The sessions module never invokes an xOutput callback with the third
  9851. ** parameter set to a value less than or equal to zero. Other than this,
  9852. ** no guarantees are made as to the size of the chunks of data returned.
  9853. */
  9854. SQLITE_API int sqlite3changeset_apply_strm(
  9855. sqlite3 *db, /* Apply change to "main" db of this handle */
  9856. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  9857. void *pIn, /* First arg for xInput */
  9858. int(*xFilter)(
  9859. void *pCtx, /* Copy of sixth arg to _apply() */
  9860. const char *zTab /* Table name */
  9861. ),
  9862. int(*xConflict)(
  9863. void *pCtx, /* Copy of sixth arg to _apply() */
  9864. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  9865. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  9866. ),
  9867. void *pCtx /* First argument passed to xConflict */
  9868. );
  9869. SQLITE_API int sqlite3changeset_concat_strm(
  9870. int (*xInputA)(void *pIn, void *pData, int *pnData),
  9871. void *pInA,
  9872. int (*xInputB)(void *pIn, void *pData, int *pnData),
  9873. void *pInB,
  9874. int (*xOutput)(void *pOut, const void *pData, int nData),
  9875. void *pOut
  9876. );
  9877. SQLITE_API int sqlite3changeset_invert_strm(
  9878. int (*xInput)(void *pIn, void *pData, int *pnData),
  9879. void *pIn,
  9880. int (*xOutput)(void *pOut, const void *pData, int nData),
  9881. void *pOut
  9882. );
  9883. SQLITE_API int sqlite3changeset_start_strm(
  9884. sqlite3_changeset_iter **pp,
  9885. int (*xInput)(void *pIn, void *pData, int *pnData),
  9886. void *pIn
  9887. );
  9888. SQLITE_API int sqlite3session_changeset_strm(
  9889. sqlite3_session *pSession,
  9890. int (*xOutput)(void *pOut, const void *pData, int nData),
  9891. void *pOut
  9892. );
  9893. SQLITE_API int sqlite3session_patchset_strm(
  9894. sqlite3_session *pSession,
  9895. int (*xOutput)(void *pOut, const void *pData, int nData),
  9896. void *pOut
  9897. );
  9898. SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
  9899. int (*xInput)(void *pIn, void *pData, int *pnData),
  9900. void *pIn
  9901. );
  9902. SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
  9903. int (*xOutput)(void *pOut, const void *pData, int nData),
  9904. void *pOut
  9905. );
  9906. /*
  9907. ** Make sure we can call this stuff from C++.
  9908. */
  9909. #if 0
  9910. }
  9911. #endif
  9912. #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
  9913. /******** End of sqlite3session.h *********/
  9914. /******** Begin file fts5.h *********/
  9915. /*
  9916. ** 2014 May 31
  9917. **
  9918. ** The author disclaims copyright to this source code. In place of
  9919. ** a legal notice, here is a blessing:
  9920. **
  9921. ** May you do good and not evil.
  9922. ** May you find forgiveness for yourself and forgive others.
  9923. ** May you share freely, never taking more than you give.
  9924. **
  9925. ******************************************************************************
  9926. **
  9927. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  9928. ** FTS5 may be extended with:
  9929. **
  9930. ** * custom tokenizers, and
  9931. ** * custom auxiliary functions.
  9932. */
  9933. #ifndef _FTS5_H
  9934. #define _FTS5_H
  9935. #if 0
  9936. extern "C" {
  9937. #endif
  9938. /*************************************************************************
  9939. ** CUSTOM AUXILIARY FUNCTIONS
  9940. **
  9941. ** Virtual table implementations may overload SQL functions by implementing
  9942. ** the sqlite3_module.xFindFunction() method.
  9943. */
  9944. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  9945. typedef struct Fts5Context Fts5Context;
  9946. typedef struct Fts5PhraseIter Fts5PhraseIter;
  9947. typedef void (*fts5_extension_function)(
  9948. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  9949. Fts5Context *pFts, /* First arg to pass to pApi functions */
  9950. sqlite3_context *pCtx, /* Context for returning result/error */
  9951. int nVal, /* Number of values in apVal[] array */
  9952. sqlite3_value **apVal /* Array of trailing arguments */
  9953. );
  9954. struct Fts5PhraseIter {
  9955. const unsigned char *a;
  9956. const unsigned char *b;
  9957. };
  9958. /*
  9959. ** EXTENSION API FUNCTIONS
  9960. **
  9961. ** xUserData(pFts):
  9962. ** Return a copy of the context pointer the extension function was
  9963. ** registered with.
  9964. **
  9965. ** xColumnTotalSize(pFts, iCol, pnToken):
  9966. ** If parameter iCol is less than zero, set output variable *pnToken
  9967. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  9968. ** non-negative but less than the number of columns in the table, return
  9969. ** the total number of tokens in column iCol, considering all rows in
  9970. ** the FTS5 table.
  9971. **
  9972. ** If parameter iCol is greater than or equal to the number of columns
  9973. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  9974. ** an OOM condition or IO error), an appropriate SQLite error code is
  9975. ** returned.
  9976. **
  9977. ** xColumnCount(pFts):
  9978. ** Return the number of columns in the table.
  9979. **
  9980. ** xColumnSize(pFts, iCol, pnToken):
  9981. ** If parameter iCol is less than zero, set output variable *pnToken
  9982. ** to the total number of tokens in the current row. Or, if iCol is
  9983. ** non-negative but less than the number of columns in the table, set
  9984. ** *pnToken to the number of tokens in column iCol of the current row.
  9985. **
  9986. ** If parameter iCol is greater than or equal to the number of columns
  9987. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  9988. ** an OOM condition or IO error), an appropriate SQLite error code is
  9989. ** returned.
  9990. **
  9991. ** This function may be quite inefficient if used with an FTS5 table
  9992. ** created with the "columnsize=0" option.
  9993. **
  9994. ** xColumnText:
  9995. ** This function attempts to retrieve the text of column iCol of the
  9996. ** current document. If successful, (*pz) is set to point to a buffer
  9997. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  9998. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  9999. ** if an error occurs, an SQLite error code is returned and the final values
  10000. ** of (*pz) and (*pn) are undefined.
  10001. **
  10002. ** xPhraseCount:
  10003. ** Returns the number of phrases in the current query expression.
  10004. **
  10005. ** xPhraseSize:
  10006. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  10007. ** are numbered starting from zero.
  10008. **
  10009. ** xInstCount:
  10010. ** Set *pnInst to the total number of occurrences of all phrases within
  10011. ** the query within the current row. Return SQLITE_OK if successful, or
  10012. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  10013. **
  10014. ** This API can be quite slow if used with an FTS5 table created with the
  10015. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  10016. ** with either "detail=none" or "detail=column" and "content=" option
  10017. ** (i.e. if it is a contentless table), then this API always returns 0.
  10018. **
  10019. ** xInst:
  10020. ** Query for the details of phrase match iIdx within the current row.
  10021. ** Phrase matches are numbered starting from zero, so the iIdx argument
  10022. ** should be greater than or equal to zero and smaller than the value
  10023. ** output by xInstCount().
  10024. **
  10025. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  10026. ** to the column in which it occurs and *piOff the token offset of the
  10027. ** first token of the phrase. The exception is if the table was created
  10028. ** with the offsets=0 option specified. In this case *piOff is always
  10029. ** set to -1.
  10030. **
  10031. ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
  10032. ** if an error occurs.
  10033. **
  10034. ** This API can be quite slow if used with an FTS5 table created with the
  10035. ** "detail=none" or "detail=column" option.
  10036. **
  10037. ** xRowid:
  10038. ** Returns the rowid of the current row.
  10039. **
  10040. ** xTokenize:
  10041. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  10042. **
  10043. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  10044. ** This API function is used to query the FTS table for phrase iPhrase
  10045. ** of the current query. Specifically, a query equivalent to:
  10046. **
  10047. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  10048. **
  10049. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  10050. ** current query is executed. Any column filter that applies to
  10051. ** phrase iPhrase of the current query is included in $p. For each
  10052. ** row visited, the callback function passed as the fourth argument
  10053. ** is invoked. The context and API objects passed to the callback
  10054. ** function may be used to access the properties of each matched row.
  10055. ** Invoking Api.xUserData() returns a copy of the pointer passed as
  10056. ** the third argument to pUserData.
  10057. **
  10058. ** If the callback function returns any value other than SQLITE_OK, the
  10059. ** query is abandoned and the xQueryPhrase function returns immediately.
  10060. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  10061. ** Otherwise, the error code is propagated upwards.
  10062. **
  10063. ** If the query runs to completion without incident, SQLITE_OK is returned.
  10064. ** Or, if some error occurs before the query completes or is aborted by
  10065. ** the callback, an SQLite error code is returned.
  10066. **
  10067. **
  10068. ** xSetAuxdata(pFts5, pAux, xDelete)
  10069. **
  10070. ** Save the pointer passed as the second argument as the extension functions
  10071. ** "auxiliary data". The pointer may then be retrieved by the current or any
  10072. ** future invocation of the same fts5 extension function made as part of
  10073. ** of the same MATCH query using the xGetAuxdata() API.
  10074. **
  10075. ** Each extension function is allocated a single auxiliary data slot for
  10076. ** each FTS query (MATCH expression). If the extension function is invoked
  10077. ** more than once for a single FTS query, then all invocations share a
  10078. ** single auxiliary data context.
  10079. **
  10080. ** If there is already an auxiliary data pointer when this function is
  10081. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  10082. ** was specified along with the original pointer, it is invoked at this
  10083. ** point.
  10084. **
  10085. ** The xDelete callback, if one is specified, is also invoked on the
  10086. ** auxiliary data pointer after the FTS5 query has finished.
  10087. **
  10088. ** If an error (e.g. an OOM condition) occurs within this function, an
  10089. ** the auxiliary data is set to NULL and an error code returned. If the
  10090. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  10091. ** pointer before returning.
  10092. **
  10093. **
  10094. ** xGetAuxdata(pFts5, bClear)
  10095. **
  10096. ** Returns the current auxiliary data pointer for the fts5 extension
  10097. ** function. See the xSetAuxdata() method for details.
  10098. **
  10099. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  10100. ** (set to NULL) before this function returns. In this case the xDelete,
  10101. ** if any, is not invoked.
  10102. **
  10103. **
  10104. ** xRowCount(pFts5, pnRow)
  10105. **
  10106. ** This function is used to retrieve the total number of rows in the table.
  10107. ** In other words, the same value that would be returned by:
  10108. **
  10109. ** SELECT count(*) FROM ftstable;
  10110. **
  10111. ** xPhraseFirst()
  10112. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  10113. ** method, to iterate through all instances of a single query phrase within
  10114. ** the current row. This is the same information as is accessible via the
  10115. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  10116. ** to use, this API may be faster under some circumstances. To iterate
  10117. ** through instances of phrase iPhrase, use the following code:
  10118. **
  10119. ** Fts5PhraseIter iter;
  10120. ** int iCol, iOff;
  10121. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  10122. ** iCol>=0;
  10123. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  10124. ** ){
  10125. ** // An instance of phrase iPhrase at offset iOff of column iCol
  10126. ** }
  10127. **
  10128. ** The Fts5PhraseIter structure is defined above. Applications should not
  10129. ** modify this structure directly - it should only be used as shown above
  10130. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  10131. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  10132. **
  10133. ** This API can be quite slow if used with an FTS5 table created with the
  10134. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  10135. ** with either "detail=none" or "detail=column" and "content=" option
  10136. ** (i.e. if it is a contentless table), then this API always iterates
  10137. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  10138. **
  10139. ** xPhraseNext()
  10140. ** See xPhraseFirst above.
  10141. **
  10142. ** xPhraseFirstColumn()
  10143. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  10144. ** and xPhraseNext() APIs described above. The difference is that instead
  10145. ** of iterating through all instances of a phrase in the current row, these
  10146. ** APIs are used to iterate through the set of columns in the current row
  10147. ** that contain one or more instances of a specified phrase. For example:
  10148. **
  10149. ** Fts5PhraseIter iter;
  10150. ** int iCol;
  10151. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  10152. ** iCol>=0;
  10153. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  10154. ** ){
  10155. ** // Column iCol contains at least one instance of phrase iPhrase
  10156. ** }
  10157. **
  10158. ** This API can be quite slow if used with an FTS5 table created with the
  10159. ** "detail=none" option. If the FTS5 table is created with either
  10160. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  10161. ** then this API always iterates through an empty set (all calls to
  10162. ** xPhraseFirstColumn() set iCol to -1).
  10163. **
  10164. ** The information accessed using this API and its companion
  10165. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  10166. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  10167. ** significantly more efficient than those alternatives when used with
  10168. ** "detail=column" tables.
  10169. **
  10170. ** xPhraseNextColumn()
  10171. ** See xPhraseFirstColumn above.
  10172. */
  10173. struct Fts5ExtensionApi {
  10174. int iVersion; /* Currently always set to 3 */
  10175. void *(*xUserData)(Fts5Context*);
  10176. int (*xColumnCount)(Fts5Context*);
  10177. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  10178. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  10179. int (*xTokenize)(Fts5Context*,
  10180. const char *pText, int nText, /* Text to tokenize */
  10181. void *pCtx, /* Context passed to xToken() */
  10182. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  10183. );
  10184. int (*xPhraseCount)(Fts5Context*);
  10185. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  10186. int (*xInstCount)(Fts5Context*, int *pnInst);
  10187. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  10188. sqlite3_int64 (*xRowid)(Fts5Context*);
  10189. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  10190. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  10191. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  10192. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  10193. );
  10194. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  10195. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  10196. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  10197. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  10198. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  10199. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  10200. };
  10201. /*
  10202. ** CUSTOM AUXILIARY FUNCTIONS
  10203. *************************************************************************/
  10204. /*************************************************************************
  10205. ** CUSTOM TOKENIZERS
  10206. **
  10207. ** Applications may also register custom tokenizer types. A tokenizer
  10208. ** is registered by providing fts5 with a populated instance of the
  10209. ** following structure. All structure methods must be defined, setting
  10210. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  10211. ** behaviour. The structure methods are expected to function as follows:
  10212. **
  10213. ** xCreate:
  10214. ** This function is used to allocate and initialize a tokenizer instance.
  10215. ** A tokenizer instance is required to actually tokenize text.
  10216. **
  10217. ** The first argument passed to this function is a copy of the (void*)
  10218. ** pointer provided by the application when the fts5_tokenizer object
  10219. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  10220. ** The second and third arguments are an array of nul-terminated strings
  10221. ** containing the tokenizer arguments, if any, specified following the
  10222. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  10223. ** to create the FTS5 table.
  10224. **
  10225. ** The final argument is an output variable. If successful, (*ppOut)
  10226. ** should be set to point to the new tokenizer handle and SQLITE_OK
  10227. ** returned. If an error occurs, some value other than SQLITE_OK should
  10228. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  10229. ** is undefined.
  10230. **
  10231. ** xDelete:
  10232. ** This function is invoked to delete a tokenizer handle previously
  10233. ** allocated using xCreate(). Fts5 guarantees that this function will
  10234. ** be invoked exactly once for each successful call to xCreate().
  10235. **
  10236. ** xTokenize:
  10237. ** This function is expected to tokenize the nText byte string indicated
  10238. ** by argument pText. pText may or may not be nul-terminated. The first
  10239. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  10240. ** returned by an earlier call to xCreate().
  10241. **
  10242. ** The second argument indicates the reason that FTS5 is requesting
  10243. ** tokenization of the supplied text. This is always one of the following
  10244. ** four values:
  10245. **
  10246. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  10247. ** or removed from the FTS table. The tokenizer is being invoked to
  10248. ** determine the set of tokens to add to (or delete from) the
  10249. ** FTS index.
  10250. **
  10251. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  10252. ** against the FTS index. The tokenizer is being called to tokenize
  10253. ** a bareword or quoted string specified as part of the query.
  10254. **
  10255. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  10256. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  10257. ** followed by a "*" character, indicating that the last token
  10258. ** returned by the tokenizer will be treated as a token prefix.
  10259. **
  10260. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  10261. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  10262. ** function. Or an fts5_api.xColumnSize() request made by the same
  10263. ** on a columnsize=0 database.
  10264. ** </ul>
  10265. **
  10266. ** For each token in the input string, the supplied callback xToken() must
  10267. ** be invoked. The first argument to it should be a copy of the pointer
  10268. ** passed as the second argument to xTokenize(). The third and fourth
  10269. ** arguments are a pointer to a buffer containing the token text, and the
  10270. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  10271. ** of the first byte of and first byte immediately following the text from
  10272. ** which the token is derived within the input.
  10273. **
  10274. ** The second argument passed to the xToken() callback ("tflags") should
  10275. ** normally be set to 0. The exception is if the tokenizer supports
  10276. ** synonyms. In this case see the discussion below for details.
  10277. **
  10278. ** FTS5 assumes the xToken() callback is invoked for each token in the
  10279. ** order that they occur within the input text.
  10280. **
  10281. ** If an xToken() callback returns any value other than SQLITE_OK, then
  10282. ** the tokenization should be abandoned and the xTokenize() method should
  10283. ** immediately return a copy of the xToken() return value. Or, if the
  10284. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  10285. ** if an error occurs with the xTokenize() implementation itself, it
  10286. ** may abandon the tokenization and return any error code other than
  10287. ** SQLITE_OK or SQLITE_DONE.
  10288. **
  10289. ** SYNONYM SUPPORT
  10290. **
  10291. ** Custom tokenizers may also support synonyms. Consider a case in which a
  10292. ** user wishes to query for a phrase such as "first place". Using the
  10293. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  10294. ** of "first place" within the document set, but not alternative forms
  10295. ** such as "1st place". In some applications, it would be better to match
  10296. ** all instances of "first place" or "1st place" regardless of which form
  10297. ** the user specified in the MATCH query text.
  10298. **
  10299. ** There are several ways to approach this in FTS5:
  10300. **
  10301. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  10302. ** In the above example, this means that the tokenizer returns the
  10303. ** same token for inputs "first" and "1st". Say that token is in
  10304. ** fact "first", so that when the user inserts the document "I won
  10305. ** 1st place" entries are added to the index for tokens "i", "won",
  10306. ** "first" and "place". If the user then queries for '1st + place',
  10307. ** the tokenizer substitutes "first" for "1st" and the query works
  10308. ** as expected.
  10309. **
  10310. ** <li> By adding multiple synonyms for a single term to the FTS index.
  10311. ** In this case, when tokenizing query text, the tokenizer may
  10312. ** provide multiple synonyms for a single term within the document.
  10313. ** FTS5 then queries the index for each synonym individually. For
  10314. ** example, faced with the query:
  10315. **
  10316. ** <codeblock>
  10317. ** ... MATCH 'first place'</codeblock>
  10318. **
  10319. ** the tokenizer offers both "1st" and "first" as synonyms for the
  10320. ** first token in the MATCH query and FTS5 effectively runs a query
  10321. ** similar to:
  10322. **
  10323. ** <codeblock>
  10324. ** ... MATCH '(first OR 1st) place'</codeblock>
  10325. **
  10326. ** except that, for the purposes of auxiliary functions, the query
  10327. ** still appears to contain just two phrases - "(first OR 1st)"
  10328. ** being treated as a single phrase.
  10329. **
  10330. ** <li> By adding multiple synonyms for a single term to the FTS index.
  10331. ** Using this method, when tokenizing document text, the tokenizer
  10332. ** provides multiple synonyms for each token. So that when a
  10333. ** document such as "I won first place" is tokenized, entries are
  10334. ** added to the FTS index for "i", "won", "first", "1st" and
  10335. ** "place".
  10336. **
  10337. ** This way, even if the tokenizer does not provide synonyms
  10338. ** when tokenizing query text (it should not - to do would be
  10339. ** inefficient), it doesn't matter if the user queries for
  10340. ** 'first + place' or '1st + place', as there are entires in the
  10341. ** FTS index corresponding to both forms of the first token.
  10342. ** </ol>
  10343. **
  10344. ** Whether it is parsing document or query text, any call to xToken that
  10345. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  10346. ** is considered to supply a synonym for the previous token. For example,
  10347. ** when parsing the document "I won first place", a tokenizer that supports
  10348. ** synonyms would call xToken() 5 times, as follows:
  10349. **
  10350. ** <codeblock>
  10351. ** xToken(pCtx, 0, "i", 1, 0, 1);
  10352. ** xToken(pCtx, 0, "won", 3, 2, 5);
  10353. ** xToken(pCtx, 0, "first", 5, 6, 11);
  10354. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  10355. ** xToken(pCtx, 0, "place", 5, 12, 17);
  10356. **</codeblock>
  10357. **
  10358. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  10359. ** xToken() is called. Multiple synonyms may be specified for a single token
  10360. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  10361. ** There is no limit to the number of synonyms that may be provided for a
  10362. ** single token.
  10363. **
  10364. ** In many cases, method (1) above is the best approach. It does not add
  10365. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  10366. ** so it is efficient in terms of disk space and query speed. However, it
  10367. ** does not support prefix queries very well. If, as suggested above, the
  10368. ** token "first" is subsituted for "1st" by the tokenizer, then the query:
  10369. **
  10370. ** <codeblock>
  10371. ** ... MATCH '1s*'</codeblock>
  10372. **
  10373. ** will not match documents that contain the token "1st" (as the tokenizer
  10374. ** will probably not map "1s" to any prefix of "first").
  10375. **
  10376. ** For full prefix support, method (3) may be preferred. In this case,
  10377. ** because the index contains entries for both "first" and "1st", prefix
  10378. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  10379. ** extra entries are added to the FTS index, this method uses more space
  10380. ** within the database.
  10381. **
  10382. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  10383. ** a query such as '1s*' will match documents that contain the literal
  10384. ** token "1st", but not "first" (assuming the tokenizer is not able to
  10385. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  10386. ** will match against "1st" and "first". This method does not require
  10387. ** extra disk space, as no extra entries are added to the FTS index.
  10388. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  10389. ** as separate queries of the FTS index are required for each synonym.
  10390. **
  10391. ** When using methods (2) or (3), it is important that the tokenizer only
  10392. ** provide synonyms when tokenizing document text (method (2)) or query
  10393. ** text (method (3)), not both. Doing so will not cause any errors, but is
  10394. ** inefficient.
  10395. */
  10396. typedef struct Fts5Tokenizer Fts5Tokenizer;
  10397. typedef struct fts5_tokenizer fts5_tokenizer;
  10398. struct fts5_tokenizer {
  10399. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  10400. void (*xDelete)(Fts5Tokenizer*);
  10401. int (*xTokenize)(Fts5Tokenizer*,
  10402. void *pCtx,
  10403. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  10404. const char *pText, int nText,
  10405. int (*xToken)(
  10406. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  10407. int tflags, /* Mask of FTS5_TOKEN_* flags */
  10408. const char *pToken, /* Pointer to buffer containing token */
  10409. int nToken, /* Size of token in bytes */
  10410. int iStart, /* Byte offset of token within input text */
  10411. int iEnd /* Byte offset of end of token within input text */
  10412. )
  10413. );
  10414. };
  10415. /* Flags that may be passed as the third argument to xTokenize() */
  10416. #define FTS5_TOKENIZE_QUERY 0x0001
  10417. #define FTS5_TOKENIZE_PREFIX 0x0002
  10418. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  10419. #define FTS5_TOKENIZE_AUX 0x0008
  10420. /* Flags that may be passed by the tokenizer implementation back to FTS5
  10421. ** as the third argument to the supplied xToken callback. */
  10422. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  10423. /*
  10424. ** END OF CUSTOM TOKENIZERS
  10425. *************************************************************************/
  10426. /*************************************************************************
  10427. ** FTS5 EXTENSION REGISTRATION API
  10428. */
  10429. typedef struct fts5_api fts5_api;
  10430. struct fts5_api {
  10431. int iVersion; /* Currently always set to 2 */
  10432. /* Create a new tokenizer */
  10433. int (*xCreateTokenizer)(
  10434. fts5_api *pApi,
  10435. const char *zName,
  10436. void *pContext,
  10437. fts5_tokenizer *pTokenizer,
  10438. void (*xDestroy)(void*)
  10439. );
  10440. /* Find an existing tokenizer */
  10441. int (*xFindTokenizer)(
  10442. fts5_api *pApi,
  10443. const char *zName,
  10444. void **ppContext,
  10445. fts5_tokenizer *pTokenizer
  10446. );
  10447. /* Create a new auxiliary function */
  10448. int (*xCreateFunction)(
  10449. fts5_api *pApi,
  10450. const char *zName,
  10451. void *pContext,
  10452. fts5_extension_function xFunction,
  10453. void (*xDestroy)(void*)
  10454. );
  10455. };
  10456. /*
  10457. ** END OF REGISTRATION API
  10458. *************************************************************************/
  10459. #if 0
  10460. } /* end of the 'extern "C"' block */
  10461. #endif
  10462. #endif /* _FTS5_H */
  10463. /******** End of fts5.h *********/
  10464. /************** End of sqlite3.h *********************************************/
  10465. /************** Continuing where we left off in sqliteInt.h ******************/
  10466. /*
  10467. ** Include the configuration header output by 'configure' if we're using the
  10468. ** autoconf-based build
  10469. */
  10470. #ifdef _HAVE_SQLITE_CONFIG_H
  10471. #include "config.h"
  10472. #endif
  10473. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  10474. /************** Begin file sqliteLimit.h *************************************/
  10475. /*
  10476. ** 2007 May 7
  10477. **
  10478. ** The author disclaims copyright to this source code. In place of
  10479. ** a legal notice, here is a blessing:
  10480. **
  10481. ** May you do good and not evil.
  10482. ** May you find forgiveness for yourself and forgive others.
  10483. ** May you share freely, never taking more than you give.
  10484. **
  10485. *************************************************************************
  10486. **
  10487. ** This file defines various limits of what SQLite can process.
  10488. */
  10489. /*
  10490. ** The maximum length of a TEXT or BLOB in bytes. This also
  10491. ** limits the size of a row in a table or index.
  10492. **
  10493. ** The hard limit is the ability of a 32-bit signed integer
  10494. ** to count the size: 2^31-1 or 2147483647.
  10495. */
  10496. #ifndef SQLITE_MAX_LENGTH
  10497. # define SQLITE_MAX_LENGTH 1000000000
  10498. #endif
  10499. /*
  10500. ** This is the maximum number of
  10501. **
  10502. ** * Columns in a table
  10503. ** * Columns in an index
  10504. ** * Columns in a view
  10505. ** * Terms in the SET clause of an UPDATE statement
  10506. ** * Terms in the result set of a SELECT statement
  10507. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  10508. ** * Terms in the VALUES clause of an INSERT statement
  10509. **
  10510. ** The hard upper limit here is 32676. Most database people will
  10511. ** tell you that in a well-normalized database, you usually should
  10512. ** not have more than a dozen or so columns in any table. And if
  10513. ** that is the case, there is no point in having more than a few
  10514. ** dozen values in any of the other situations described above.
  10515. */
  10516. #ifndef SQLITE_MAX_COLUMN
  10517. # define SQLITE_MAX_COLUMN 2000
  10518. #endif
  10519. /*
  10520. ** The maximum length of a single SQL statement in bytes.
  10521. **
  10522. ** It used to be the case that setting this value to zero would
  10523. ** turn the limit off. That is no longer true. It is not possible
  10524. ** to turn this limit off.
  10525. */
  10526. #ifndef SQLITE_MAX_SQL_LENGTH
  10527. # define SQLITE_MAX_SQL_LENGTH 1000000000
  10528. #endif
  10529. /*
  10530. ** The maximum depth of an expression tree. This is limited to
  10531. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  10532. ** want to place more severe limits on the complexity of an
  10533. ** expression.
  10534. **
  10535. ** A value of 0 used to mean that the limit was not enforced.
  10536. ** But that is no longer true. The limit is now strictly enforced
  10537. ** at all times.
  10538. */
  10539. #ifndef SQLITE_MAX_EXPR_DEPTH
  10540. # define SQLITE_MAX_EXPR_DEPTH 1000
  10541. #endif
  10542. /*
  10543. ** The maximum number of terms in a compound SELECT statement.
  10544. ** The code generator for compound SELECT statements does one
  10545. ** level of recursion for each term. A stack overflow can result
  10546. ** if the number of terms is too large. In practice, most SQL
  10547. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  10548. ** any limit on the number of terms in a compount SELECT.
  10549. */
  10550. #ifndef SQLITE_MAX_COMPOUND_SELECT
  10551. # define SQLITE_MAX_COMPOUND_SELECT 500
  10552. #endif
  10553. /*
  10554. ** The maximum number of opcodes in a VDBE program.
  10555. ** Not currently enforced.
  10556. */
  10557. #ifndef SQLITE_MAX_VDBE_OP
  10558. # define SQLITE_MAX_VDBE_OP 250000000
  10559. #endif
  10560. /*
  10561. ** The maximum number of arguments to an SQL function.
  10562. */
  10563. #ifndef SQLITE_MAX_FUNCTION_ARG
  10564. # define SQLITE_MAX_FUNCTION_ARG 127
  10565. #endif
  10566. /*
  10567. ** The suggested maximum number of in-memory pages to use for
  10568. ** the main database table and for temporary tables.
  10569. **
  10570. ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
  10571. ** which means the cache size is limited to 2048000 bytes of memory.
  10572. ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
  10573. ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
  10574. */
  10575. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  10576. # define SQLITE_DEFAULT_CACHE_SIZE -2000
  10577. #endif
  10578. /*
  10579. ** The default number of frames to accumulate in the log file before
  10580. ** checkpointing the database in WAL mode.
  10581. */
  10582. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  10583. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  10584. #endif
  10585. /*
  10586. ** The maximum number of attached databases. This must be between 0
  10587. ** and 125. The upper bound of 125 is because the attached databases are
  10588. ** counted using a signed 8-bit integer which has a maximum value of 127
  10589. ** and we have to allow 2 extra counts for the "main" and "temp" databases.
  10590. */
  10591. #ifndef SQLITE_MAX_ATTACHED
  10592. # define SQLITE_MAX_ATTACHED 10
  10593. #endif
  10594. /*
  10595. ** The maximum value of a ?nnn wildcard that the parser will accept.
  10596. */
  10597. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  10598. # define SQLITE_MAX_VARIABLE_NUMBER 999
  10599. #endif
  10600. /* Maximum page size. The upper bound on this value is 65536. This a limit
  10601. ** imposed by the use of 16-bit offsets within each page.
  10602. **
  10603. ** Earlier versions of SQLite allowed the user to change this value at
  10604. ** compile time. This is no longer permitted, on the grounds that it creates
  10605. ** a library that is technically incompatible with an SQLite library
  10606. ** compiled with a different limit. If a process operating on a database
  10607. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  10608. ** compiled with the default page-size limit will not be able to rollback
  10609. ** the aborted transaction. This could lead to database corruption.
  10610. */
  10611. #ifdef SQLITE_MAX_PAGE_SIZE
  10612. # undef SQLITE_MAX_PAGE_SIZE
  10613. #endif
  10614. #define SQLITE_MAX_PAGE_SIZE 65536
  10615. /*
  10616. ** The default size of a database page.
  10617. */
  10618. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  10619. # define SQLITE_DEFAULT_PAGE_SIZE 4096
  10620. #endif
  10621. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  10622. # undef SQLITE_DEFAULT_PAGE_SIZE
  10623. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  10624. #endif
  10625. /*
  10626. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  10627. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  10628. ** device characteristics (sector-size and atomic write() support),
  10629. ** SQLite may choose a larger value. This constant is the maximum value
  10630. ** SQLite will choose on its own.
  10631. */
  10632. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  10633. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  10634. #endif
  10635. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  10636. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  10637. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  10638. #endif
  10639. /*
  10640. ** Maximum number of pages in one database file.
  10641. **
  10642. ** This is really just the default value for the max_page_count pragma.
  10643. ** This value can be lowered (or raised) at run-time using that the
  10644. ** max_page_count macro.
  10645. */
  10646. #ifndef SQLITE_MAX_PAGE_COUNT
  10647. # define SQLITE_MAX_PAGE_COUNT 1073741823
  10648. #endif
  10649. /*
  10650. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  10651. ** operator.
  10652. */
  10653. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  10654. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  10655. #endif
  10656. /*
  10657. ** Maximum depth of recursion for triggers.
  10658. **
  10659. ** A value of 1 means that a trigger program will not be able to itself
  10660. ** fire any triggers. A value of 0 means that no trigger programs at all
  10661. ** may be executed.
  10662. */
  10663. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  10664. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  10665. #endif
  10666. /************** End of sqliteLimit.h *****************************************/
  10667. /************** Continuing where we left off in sqliteInt.h ******************/
  10668. /* Disable nuisance warnings on Borland compilers */
  10669. #if defined(__BORLANDC__)
  10670. #pragma warn -rch /* unreachable code */
  10671. #pragma warn -ccc /* Condition is always true or false */
  10672. #pragma warn -aus /* Assigned value is never used */
  10673. #pragma warn -csu /* Comparing signed and unsigned */
  10674. #pragma warn -spa /* Suspicious pointer arithmetic */
  10675. #endif
  10676. /*
  10677. ** Include standard header files as necessary
  10678. */
  10679. #ifdef HAVE_STDINT_H
  10680. #include <stdint.h>
  10681. #endif
  10682. #ifdef HAVE_INTTYPES_H
  10683. #include <inttypes.h>
  10684. #endif
  10685. /*
  10686. ** The following macros are used to cast pointers to integers and
  10687. ** integers to pointers. The way you do this varies from one compiler
  10688. ** to the next, so we have developed the following set of #if statements
  10689. ** to generate appropriate macros for a wide range of compilers.
  10690. **
  10691. ** The correct "ANSI" way to do this is to use the intptr_t type.
  10692. ** Unfortunately, that typedef is not available on all compilers, or
  10693. ** if it is available, it requires an #include of specific headers
  10694. ** that vary from one machine to the next.
  10695. **
  10696. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  10697. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  10698. ** So we have to define the macros in different ways depending on the
  10699. ** compiler.
  10700. */
  10701. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  10702. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  10703. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  10704. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  10705. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  10706. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  10707. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  10708. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  10709. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  10710. #else /* Generates a warning - but it always works */
  10711. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  10712. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  10713. #endif
  10714. /*
  10715. ** A macro to hint to the compiler that a function should not be
  10716. ** inlined.
  10717. */
  10718. #if defined(__GNUC__)
  10719. # define SQLITE_NOINLINE __attribute__((noinline))
  10720. #elif defined(_MSC_VER) && _MSC_VER>=1310
  10721. # define SQLITE_NOINLINE __declspec(noinline)
  10722. #else
  10723. # define SQLITE_NOINLINE
  10724. #endif
  10725. /*
  10726. ** Make sure that the compiler intrinsics we desire are enabled when
  10727. ** compiling with an appropriate version of MSVC unless prevented by
  10728. ** the SQLITE_DISABLE_INTRINSIC define.
  10729. */
  10730. #if !defined(SQLITE_DISABLE_INTRINSIC)
  10731. # if defined(_MSC_VER) && _MSC_VER>=1400
  10732. # if !defined(_WIN32_WCE)
  10733. # include <intrin.h>
  10734. # pragma intrinsic(_byteswap_ushort)
  10735. # pragma intrinsic(_byteswap_ulong)
  10736. # pragma intrinsic(_byteswap_uint64)
  10737. # pragma intrinsic(_ReadWriteBarrier)
  10738. # else
  10739. # include <cmnintrin.h>
  10740. # endif
  10741. # endif
  10742. #endif
  10743. /*
  10744. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  10745. ** 0 means mutexes are permanently disable and the library is never
  10746. ** threadsafe. 1 means the library is serialized which is the highest
  10747. ** level of threadsafety. 2 means the library is multithreaded - multiple
  10748. ** threads can use SQLite as long as no two threads try to use the same
  10749. ** database connection at the same time.
  10750. **
  10751. ** Older versions of SQLite used an optional THREADSAFE macro.
  10752. ** We support that for legacy.
  10753. */
  10754. #if !defined(SQLITE_THREADSAFE)
  10755. # if defined(THREADSAFE)
  10756. # define SQLITE_THREADSAFE THREADSAFE
  10757. # else
  10758. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  10759. # endif
  10760. #endif
  10761. /*
  10762. ** Powersafe overwrite is on by default. But can be turned off using
  10763. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  10764. */
  10765. #ifndef SQLITE_POWERSAFE_OVERWRITE
  10766. # define SQLITE_POWERSAFE_OVERWRITE 1
  10767. #endif
  10768. /*
  10769. ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
  10770. ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
  10771. ** which case memory allocation statistics are disabled by default.
  10772. */
  10773. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  10774. # define SQLITE_DEFAULT_MEMSTATUS 1
  10775. #endif
  10776. /*
  10777. ** Exactly one of the following macros must be defined in order to
  10778. ** specify which memory allocation subsystem to use.
  10779. **
  10780. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  10781. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  10782. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  10783. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  10784. **
  10785. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  10786. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  10787. ** will cause HeapValidate to be called. If heap validation should fail, an
  10788. ** assertion will be triggered.
  10789. **
  10790. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  10791. ** the default.
  10792. */
  10793. #if defined(SQLITE_SYSTEM_MALLOC) \
  10794. + defined(SQLITE_WIN32_MALLOC) \
  10795. + defined(SQLITE_ZERO_MALLOC) \
  10796. + defined(SQLITE_MEMDEBUG)>1
  10797. # error "Two or more of the following compile-time configuration options\
  10798. are defined but at most one is allowed:\
  10799. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  10800. SQLITE_ZERO_MALLOC"
  10801. #endif
  10802. #if defined(SQLITE_SYSTEM_MALLOC) \
  10803. + defined(SQLITE_WIN32_MALLOC) \
  10804. + defined(SQLITE_ZERO_MALLOC) \
  10805. + defined(SQLITE_MEMDEBUG)==0
  10806. # define SQLITE_SYSTEM_MALLOC 1
  10807. #endif
  10808. /*
  10809. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  10810. ** sizes of memory allocations below this value where possible.
  10811. */
  10812. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  10813. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  10814. #endif
  10815. /*
  10816. ** We need to define _XOPEN_SOURCE as follows in order to enable
  10817. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  10818. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  10819. ** it.
  10820. */
  10821. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  10822. # define _XOPEN_SOURCE 600
  10823. #endif
  10824. /*
  10825. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  10826. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  10827. ** make it true by defining or undefining NDEBUG.
  10828. **
  10829. ** Setting NDEBUG makes the code smaller and faster by disabling the
  10830. ** assert() statements in the code. So we want the default action
  10831. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  10832. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  10833. ** feature.
  10834. */
  10835. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  10836. # define NDEBUG 1
  10837. #endif
  10838. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  10839. # undef NDEBUG
  10840. #endif
  10841. /*
  10842. ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
  10843. */
  10844. #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
  10845. # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
  10846. #endif
  10847. /*
  10848. ** The testcase() macro is used to aid in coverage testing. When
  10849. ** doing coverage testing, the condition inside the argument to
  10850. ** testcase() must be evaluated both true and false in order to
  10851. ** get full branch coverage. The testcase() macro is inserted
  10852. ** to help ensure adequate test coverage in places where simple
  10853. ** condition/decision coverage is inadequate. For example, testcase()
  10854. ** can be used to make sure boundary values are tested. For
  10855. ** bitmask tests, testcase() can be used to make sure each bit
  10856. ** is significant and used at least once. On switch statements
  10857. ** where multiple cases go to the same block of code, testcase()
  10858. ** can insure that all cases are evaluated.
  10859. **
  10860. */
  10861. #ifdef SQLITE_COVERAGE_TEST
  10862. SQLITE_PRIVATE void sqlite3Coverage(int);
  10863. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  10864. #else
  10865. # define testcase(X)
  10866. #endif
  10867. /*
  10868. ** The TESTONLY macro is used to enclose variable declarations or
  10869. ** other bits of code that are needed to support the arguments
  10870. ** within testcase() and assert() macros.
  10871. */
  10872. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  10873. # define TESTONLY(X) X
  10874. #else
  10875. # define TESTONLY(X)
  10876. #endif
  10877. /*
  10878. ** Sometimes we need a small amount of code such as a variable initialization
  10879. ** to setup for a later assert() statement. We do not want this code to
  10880. ** appear when assert() is disabled. The following macro is therefore
  10881. ** used to contain that setup code. The "VVA" acronym stands for
  10882. ** "Verification, Validation, and Accreditation". In other words, the
  10883. ** code within VVA_ONLY() will only run during verification processes.
  10884. */
  10885. #ifndef NDEBUG
  10886. # define VVA_ONLY(X) X
  10887. #else
  10888. # define VVA_ONLY(X)
  10889. #endif
  10890. /*
  10891. ** The ALWAYS and NEVER macros surround boolean expressions which
  10892. ** are intended to always be true or false, respectively. Such
  10893. ** expressions could be omitted from the code completely. But they
  10894. ** are included in a few cases in order to enhance the resilience
  10895. ** of SQLite to unexpected behavior - to make the code "self-healing"
  10896. ** or "ductile" rather than being "brittle" and crashing at the first
  10897. ** hint of unplanned behavior.
  10898. **
  10899. ** In other words, ALWAYS and NEVER are added for defensive code.
  10900. **
  10901. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  10902. ** be true and false so that the unreachable code they specify will
  10903. ** not be counted as untested code.
  10904. */
  10905. #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
  10906. # define ALWAYS(X) (1)
  10907. # define NEVER(X) (0)
  10908. #elif !defined(NDEBUG)
  10909. # define ALWAYS(X) ((X)?1:(assert(0),0))
  10910. # define NEVER(X) ((X)?(assert(0),1):0)
  10911. #else
  10912. # define ALWAYS(X) (X)
  10913. # define NEVER(X) (X)
  10914. #endif
  10915. /*
  10916. ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
  10917. ** defined. We need to defend against those failures when testing with
  10918. ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
  10919. ** during a normal build. The following macro can be used to disable tests
  10920. ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
  10921. */
  10922. #if defined(SQLITE_TEST_REALLOC_STRESS)
  10923. # define ONLY_IF_REALLOC_STRESS(X) (X)
  10924. #elif !defined(NDEBUG)
  10925. # define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
  10926. #else
  10927. # define ONLY_IF_REALLOC_STRESS(X) (0)
  10928. #endif
  10929. /*
  10930. ** Declarations used for tracing the operating system interfaces.
  10931. */
  10932. #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
  10933. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  10934. extern int sqlite3OSTrace;
  10935. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  10936. # define SQLITE_HAVE_OS_TRACE
  10937. #else
  10938. # define OSTRACE(X)
  10939. # undef SQLITE_HAVE_OS_TRACE
  10940. #endif
  10941. /*
  10942. ** Is the sqlite3ErrName() function needed in the build? Currently,
  10943. ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
  10944. ** OSTRACE is enabled), and by several "test*.c" files (which are
  10945. ** compiled using SQLITE_TEST).
  10946. */
  10947. #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
  10948. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  10949. # define SQLITE_NEED_ERR_NAME
  10950. #else
  10951. # undef SQLITE_NEED_ERR_NAME
  10952. #endif
  10953. /*
  10954. ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
  10955. */
  10956. #ifdef SQLITE_OMIT_EXPLAIN
  10957. # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
  10958. #endif
  10959. /*
  10960. ** Return true (non-zero) if the input is an integer that is too large
  10961. ** to fit in 32-bits. This macro is used inside of various testcase()
  10962. ** macros to verify that we have tested SQLite for large-file support.
  10963. */
  10964. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  10965. /*
  10966. ** The macro unlikely() is a hint that surrounds a boolean
  10967. ** expression that is usually false. Macro likely() surrounds
  10968. ** a boolean expression that is usually true. These hints could,
  10969. ** in theory, be used by the compiler to generate better code, but
  10970. ** currently they are just comments for human readers.
  10971. */
  10972. #define likely(X) (X)
  10973. #define unlikely(X) (X)
  10974. /************** Include hash.h in the middle of sqliteInt.h ******************/
  10975. /************** Begin file hash.h ********************************************/
  10976. /*
  10977. ** 2001 September 22
  10978. **
  10979. ** The author disclaims copyright to this source code. In place of
  10980. ** a legal notice, here is a blessing:
  10981. **
  10982. ** May you do good and not evil.
  10983. ** May you find forgiveness for yourself and forgive others.
  10984. ** May you share freely, never taking more than you give.
  10985. **
  10986. *************************************************************************
  10987. ** This is the header file for the generic hash-table implementation
  10988. ** used in SQLite.
  10989. */
  10990. #ifndef SQLITE_HASH_H
  10991. #define SQLITE_HASH_H
  10992. /* Forward declarations of structures. */
  10993. typedef struct Hash Hash;
  10994. typedef struct HashElem HashElem;
  10995. /* A complete hash table is an instance of the following structure.
  10996. ** The internals of this structure are intended to be opaque -- client
  10997. ** code should not attempt to access or modify the fields of this structure
  10998. ** directly. Change this structure only by using the routines below.
  10999. ** However, some of the "procedures" and "functions" for modifying and
  11000. ** accessing this structure are really macros, so we can't really make
  11001. ** this structure opaque.
  11002. **
  11003. ** All elements of the hash table are on a single doubly-linked list.
  11004. ** Hash.first points to the head of this list.
  11005. **
  11006. ** There are Hash.htsize buckets. Each bucket points to a spot in
  11007. ** the global doubly-linked list. The contents of the bucket are the
  11008. ** element pointed to plus the next _ht.count-1 elements in the list.
  11009. **
  11010. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  11011. ** by a linear search of the global list. For small tables, the
  11012. ** Hash.ht table is never allocated because if there are few elements
  11013. ** in the table, it is faster to do a linear search than to manage
  11014. ** the hash table.
  11015. */
  11016. struct Hash {
  11017. unsigned int htsize; /* Number of buckets in the hash table */
  11018. unsigned int count; /* Number of entries in this table */
  11019. HashElem *first; /* The first element of the array */
  11020. struct _ht { /* the hash table */
  11021. int count; /* Number of entries with this hash */
  11022. HashElem *chain; /* Pointer to first entry with this hash */
  11023. } *ht;
  11024. };
  11025. /* Each element in the hash table is an instance of the following
  11026. ** structure. All elements are stored on a single doubly-linked list.
  11027. **
  11028. ** Again, this structure is intended to be opaque, but it can't really
  11029. ** be opaque because it is used by macros.
  11030. */
  11031. struct HashElem {
  11032. HashElem *next, *prev; /* Next and previous elements in the table */
  11033. void *data; /* Data associated with this element */
  11034. const char *pKey; /* Key associated with this element */
  11035. };
  11036. /*
  11037. ** Access routines. To delete, insert a NULL pointer.
  11038. */
  11039. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  11040. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
  11041. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
  11042. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  11043. /*
  11044. ** Macros for looping over all elements of a hash table. The idiom is
  11045. ** like this:
  11046. **
  11047. ** Hash h;
  11048. ** HashElem *p;
  11049. ** ...
  11050. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  11051. ** SomeStructure *pData = sqliteHashData(p);
  11052. ** // do something with pData
  11053. ** }
  11054. */
  11055. #define sqliteHashFirst(H) ((H)->first)
  11056. #define sqliteHashNext(E) ((E)->next)
  11057. #define sqliteHashData(E) ((E)->data)
  11058. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  11059. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  11060. /*
  11061. ** Number of entries in a hash table
  11062. */
  11063. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  11064. #endif /* SQLITE_HASH_H */
  11065. /************** End of hash.h ************************************************/
  11066. /************** Continuing where we left off in sqliteInt.h ******************/
  11067. /************** Include parse.h in the middle of sqliteInt.h *****************/
  11068. /************** Begin file parse.h *******************************************/
  11069. #define TK_SEMI 1
  11070. #define TK_EXPLAIN 2
  11071. #define TK_QUERY 3
  11072. #define TK_PLAN 4
  11073. #define TK_BEGIN 5
  11074. #define TK_TRANSACTION 6
  11075. #define TK_DEFERRED 7
  11076. #define TK_IMMEDIATE 8
  11077. #define TK_EXCLUSIVE 9
  11078. #define TK_COMMIT 10
  11079. #define TK_END 11
  11080. #define TK_ROLLBACK 12
  11081. #define TK_SAVEPOINT 13
  11082. #define TK_RELEASE 14
  11083. #define TK_TO 15
  11084. #define TK_TABLE 16
  11085. #define TK_CREATE 17
  11086. #define TK_IF 18
  11087. #define TK_NOT 19
  11088. #define TK_EXISTS 20
  11089. #define TK_TEMP 21
  11090. #define TK_LP 22
  11091. #define TK_RP 23
  11092. #define TK_AS 24
  11093. #define TK_WITHOUT 25
  11094. #define TK_COMMA 26
  11095. #define TK_ID 27
  11096. #define TK_ABORT 28
  11097. #define TK_ACTION 29
  11098. #define TK_AFTER 30
  11099. #define TK_ANALYZE 31
  11100. #define TK_ASC 32
  11101. #define TK_ATTACH 33
  11102. #define TK_BEFORE 34
  11103. #define TK_BY 35
  11104. #define TK_CASCADE 36
  11105. #define TK_CAST 37
  11106. #define TK_COLUMNKW 38
  11107. #define TK_CONFLICT 39
  11108. #define TK_DATABASE 40
  11109. #define TK_DESC 41
  11110. #define TK_DETACH 42
  11111. #define TK_EACH 43
  11112. #define TK_FAIL 44
  11113. #define TK_FOR 45
  11114. #define TK_IGNORE 46
  11115. #define TK_INITIALLY 47
  11116. #define TK_INSTEAD 48
  11117. #define TK_LIKE_KW 49
  11118. #define TK_MATCH 50
  11119. #define TK_NO 51
  11120. #define TK_KEY 52
  11121. #define TK_OF 53
  11122. #define TK_OFFSET 54
  11123. #define TK_PRAGMA 55
  11124. #define TK_RAISE 56
  11125. #define TK_RECURSIVE 57
  11126. #define TK_REPLACE 58
  11127. #define TK_RESTRICT 59
  11128. #define TK_ROW 60
  11129. #define TK_TRIGGER 61
  11130. #define TK_VACUUM 62
  11131. #define TK_VIEW 63
  11132. #define TK_VIRTUAL 64
  11133. #define TK_WITH 65
  11134. #define TK_REINDEX 66
  11135. #define TK_RENAME 67
  11136. #define TK_CTIME_KW 68
  11137. #define TK_ANY 69
  11138. #define TK_OR 70
  11139. #define TK_AND 71
  11140. #define TK_IS 72
  11141. #define TK_BETWEEN 73
  11142. #define TK_IN 74
  11143. #define TK_ISNULL 75
  11144. #define TK_NOTNULL 76
  11145. #define TK_NE 77
  11146. #define TK_EQ 78
  11147. #define TK_GT 79
  11148. #define TK_LE 80
  11149. #define TK_LT 81
  11150. #define TK_GE 82
  11151. #define TK_ESCAPE 83
  11152. #define TK_BITAND 84
  11153. #define TK_BITOR 85
  11154. #define TK_LSHIFT 86
  11155. #define TK_RSHIFT 87
  11156. #define TK_PLUS 88
  11157. #define TK_MINUS 89
  11158. #define TK_STAR 90
  11159. #define TK_SLASH 91
  11160. #define TK_REM 92
  11161. #define TK_CONCAT 93
  11162. #define TK_COLLATE 94
  11163. #define TK_BITNOT 95
  11164. #define TK_INDEXED 96
  11165. #define TK_STRING 97
  11166. #define TK_JOIN_KW 98
  11167. #define TK_CONSTRAINT 99
  11168. #define TK_DEFAULT 100
  11169. #define TK_NULL 101
  11170. #define TK_PRIMARY 102
  11171. #define TK_UNIQUE 103
  11172. #define TK_CHECK 104
  11173. #define TK_REFERENCES 105
  11174. #define TK_AUTOINCR 106
  11175. #define TK_ON 107
  11176. #define TK_INSERT 108
  11177. #define TK_DELETE 109
  11178. #define TK_UPDATE 110
  11179. #define TK_SET 111
  11180. #define TK_DEFERRABLE 112
  11181. #define TK_FOREIGN 113
  11182. #define TK_DROP 114
  11183. #define TK_UNION 115
  11184. #define TK_ALL 116
  11185. #define TK_EXCEPT 117
  11186. #define TK_INTERSECT 118
  11187. #define TK_SELECT 119
  11188. #define TK_VALUES 120
  11189. #define TK_DISTINCT 121
  11190. #define TK_DOT 122
  11191. #define TK_FROM 123
  11192. #define TK_JOIN 124
  11193. #define TK_USING 125
  11194. #define TK_ORDER 126
  11195. #define TK_GROUP 127
  11196. #define TK_HAVING 128
  11197. #define TK_LIMIT 129
  11198. #define TK_WHERE 130
  11199. #define TK_INTO 131
  11200. #define TK_FLOAT 132
  11201. #define TK_BLOB 133
  11202. #define TK_INTEGER 134
  11203. #define TK_VARIABLE 135
  11204. #define TK_CASE 136
  11205. #define TK_WHEN 137
  11206. #define TK_THEN 138
  11207. #define TK_ELSE 139
  11208. #define TK_INDEX 140
  11209. #define TK_ALTER 141
  11210. #define TK_ADD 142
  11211. #define TK_TO_TEXT 143
  11212. #define TK_TO_BLOB 144
  11213. #define TK_TO_NUMERIC 145
  11214. #define TK_TO_INT 146
  11215. #define TK_TO_REAL 147
  11216. #define TK_ISNOT 148
  11217. #define TK_END_OF_FILE 149
  11218. #define TK_UNCLOSED_STRING 150
  11219. #define TK_FUNCTION 151
  11220. #define TK_COLUMN 152
  11221. #define TK_AGG_FUNCTION 153
  11222. #define TK_AGG_COLUMN 154
  11223. #define TK_UMINUS 155
  11224. #define TK_UPLUS 156
  11225. #define TK_REGISTER 157
  11226. #define TK_VECTOR 158
  11227. #define TK_SELECT_COLUMN 159
  11228. #define TK_IF_NULL_ROW 160
  11229. #define TK_ASTERISK 161
  11230. #define TK_SPAN 162
  11231. #define TK_SPACE 163
  11232. #define TK_ILLEGAL 164
  11233. /* The token codes above must all fit in 8 bits */
  11234. #define TKFLG_MASK 0xff
  11235. /* Flags that can be added to a token code when it is not
  11236. ** being stored in a u8: */
  11237. #define TKFLG_DONTFOLD 0x100 /* Omit constant folding optimizations */
  11238. /************** End of parse.h ***********************************************/
  11239. /************** Continuing where we left off in sqliteInt.h ******************/
  11240. #include <stdio.h>
  11241. #include <stdlib.h>
  11242. #include <string.h>
  11243. #include <assert.h>
  11244. #include <stddef.h>
  11245. /*
  11246. ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
  11247. ** This allows better measurements of where memcpy() is used when running
  11248. ** cachegrind. But this macro version of memcpy() is very slow so it
  11249. ** should not be used in production. This is a performance measurement
  11250. ** hack only.
  11251. */
  11252. #ifdef SQLITE_INLINE_MEMCPY
  11253. # define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
  11254. int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
  11255. #endif
  11256. /*
  11257. ** If compiling for a processor that lacks floating point support,
  11258. ** substitute integer for floating-point
  11259. */
  11260. #ifdef SQLITE_OMIT_FLOATING_POINT
  11261. # define double sqlite_int64
  11262. # define float sqlite_int64
  11263. # define LONGDOUBLE_TYPE sqlite_int64
  11264. # ifndef SQLITE_BIG_DBL
  11265. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  11266. # endif
  11267. # define SQLITE_OMIT_DATETIME_FUNCS 1
  11268. # define SQLITE_OMIT_TRACE 1
  11269. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  11270. # undef SQLITE_HAVE_ISNAN
  11271. #endif
  11272. #ifndef SQLITE_BIG_DBL
  11273. # define SQLITE_BIG_DBL (1e99)
  11274. #endif
  11275. /*
  11276. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  11277. ** afterward. Having this macro allows us to cause the C compiler
  11278. ** to omit code used by TEMP tables without messy #ifndef statements.
  11279. */
  11280. #ifdef SQLITE_OMIT_TEMPDB
  11281. #define OMIT_TEMPDB 1
  11282. #else
  11283. #define OMIT_TEMPDB 0
  11284. #endif
  11285. /*
  11286. ** The "file format" number is an integer that is incremented whenever
  11287. ** the VDBE-level file format changes. The following macros define the
  11288. ** the default file format for new databases and the maximum file format
  11289. ** that the library can read.
  11290. */
  11291. #define SQLITE_MAX_FILE_FORMAT 4
  11292. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  11293. # define SQLITE_DEFAULT_FILE_FORMAT 4
  11294. #endif
  11295. /*
  11296. ** Determine whether triggers are recursive by default. This can be
  11297. ** changed at run-time using a pragma.
  11298. */
  11299. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  11300. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  11301. #endif
  11302. /*
  11303. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  11304. ** on the command-line
  11305. */
  11306. #ifndef SQLITE_TEMP_STORE
  11307. # define SQLITE_TEMP_STORE 1
  11308. # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
  11309. #endif
  11310. /*
  11311. ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
  11312. ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
  11313. ** to zero.
  11314. */
  11315. #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
  11316. # undef SQLITE_MAX_WORKER_THREADS
  11317. # define SQLITE_MAX_WORKER_THREADS 0
  11318. #endif
  11319. #ifndef SQLITE_MAX_WORKER_THREADS
  11320. # define SQLITE_MAX_WORKER_THREADS 8
  11321. #endif
  11322. #ifndef SQLITE_DEFAULT_WORKER_THREADS
  11323. # define SQLITE_DEFAULT_WORKER_THREADS 0
  11324. #endif
  11325. #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
  11326. # undef SQLITE_MAX_WORKER_THREADS
  11327. # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
  11328. #endif
  11329. /*
  11330. ** The default initial allocation for the pagecache when using separate
  11331. ** pagecaches for each database connection. A positive number is the
  11332. ** number of pages. A negative number N translations means that a buffer
  11333. ** of -1024*N bytes is allocated and used for as many pages as it will hold.
  11334. **
  11335. ** The default value of "20" was choosen to minimize the run-time of the
  11336. ** speedtest1 test program with options: --shrink-memory --reprepare
  11337. */
  11338. #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
  11339. # define SQLITE_DEFAULT_PCACHE_INITSZ 20
  11340. #endif
  11341. /*
  11342. ** GCC does not define the offsetof() macro so we'll have to do it
  11343. ** ourselves.
  11344. */
  11345. #ifndef offsetof
  11346. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  11347. #endif
  11348. /*
  11349. ** Macros to compute minimum and maximum of two numbers.
  11350. */
  11351. #ifndef MIN
  11352. # define MIN(A,B) ((A)<(B)?(A):(B))
  11353. #endif
  11354. #ifndef MAX
  11355. # define MAX(A,B) ((A)>(B)?(A):(B))
  11356. #endif
  11357. /*
  11358. ** Swap two objects of type TYPE.
  11359. */
  11360. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  11361. /*
  11362. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  11363. ** not, there are still machines out there that use EBCDIC.)
  11364. */
  11365. #if 'A' == '\301'
  11366. # define SQLITE_EBCDIC 1
  11367. #else
  11368. # define SQLITE_ASCII 1
  11369. #endif
  11370. /*
  11371. ** Integers of known sizes. These typedefs might change for architectures
  11372. ** where the sizes very. Preprocessor macros are available so that the
  11373. ** types can be conveniently redefined at compile-type. Like this:
  11374. **
  11375. ** cc '-DUINTPTR_TYPE=long long int' ...
  11376. */
  11377. #ifndef UINT32_TYPE
  11378. # ifdef HAVE_UINT32_T
  11379. # define UINT32_TYPE uint32_t
  11380. # else
  11381. # define UINT32_TYPE unsigned int
  11382. # endif
  11383. #endif
  11384. #ifndef UINT16_TYPE
  11385. # ifdef HAVE_UINT16_T
  11386. # define UINT16_TYPE uint16_t
  11387. # else
  11388. # define UINT16_TYPE unsigned short int
  11389. # endif
  11390. #endif
  11391. #ifndef INT16_TYPE
  11392. # ifdef HAVE_INT16_T
  11393. # define INT16_TYPE int16_t
  11394. # else
  11395. # define INT16_TYPE short int
  11396. # endif
  11397. #endif
  11398. #ifndef UINT8_TYPE
  11399. # ifdef HAVE_UINT8_T
  11400. # define UINT8_TYPE uint8_t
  11401. # else
  11402. # define UINT8_TYPE unsigned char
  11403. # endif
  11404. #endif
  11405. #ifndef INT8_TYPE
  11406. # ifdef HAVE_INT8_T
  11407. # define INT8_TYPE int8_t
  11408. # else
  11409. # define INT8_TYPE signed char
  11410. # endif
  11411. #endif
  11412. #ifndef LONGDOUBLE_TYPE
  11413. # define LONGDOUBLE_TYPE long double
  11414. #endif
  11415. typedef sqlite_int64 i64; /* 8-byte signed integer */
  11416. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  11417. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  11418. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  11419. typedef INT16_TYPE i16; /* 2-byte signed integer */
  11420. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  11421. typedef INT8_TYPE i8; /* 1-byte signed integer */
  11422. /*
  11423. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  11424. ** that can be stored in a u32 without loss of data. The value
  11425. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  11426. ** have to specify the value in the less intuitive manner shown:
  11427. */
  11428. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  11429. /*
  11430. ** The datatype used to store estimates of the number of rows in a
  11431. ** table or index. This is an unsigned integer type. For 99.9% of
  11432. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  11433. ** can be used at compile-time if desired.
  11434. */
  11435. #ifdef SQLITE_64BIT_STATS
  11436. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  11437. #else
  11438. typedef u32 tRowcnt; /* 32-bit is the default */
  11439. #endif
  11440. /*
  11441. ** Estimated quantities used for query planning are stored as 16-bit
  11442. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  11443. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  11444. ** But the allowed values are "grainy". Not every value is representable.
  11445. ** For example, quantities 16 and 17 are both represented by a LogEst
  11446. ** of 40. However, since LogEst quantities are suppose to be estimates,
  11447. ** not exact values, this imprecision is not a problem.
  11448. **
  11449. ** "LogEst" is short for "Logarithmic Estimate".
  11450. **
  11451. ** Examples:
  11452. ** 1 -> 0 20 -> 43 10000 -> 132
  11453. ** 2 -> 10 25 -> 46 25000 -> 146
  11454. ** 3 -> 16 100 -> 66 1000000 -> 199
  11455. ** 4 -> 20 1000 -> 99 1048576 -> 200
  11456. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  11457. **
  11458. ** The LogEst can be negative to indicate fractional values.
  11459. ** Examples:
  11460. **
  11461. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  11462. */
  11463. typedef INT16_TYPE LogEst;
  11464. /*
  11465. ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
  11466. */
  11467. #ifndef SQLITE_PTRSIZE
  11468. # if defined(__SIZEOF_POINTER__)
  11469. # define SQLITE_PTRSIZE __SIZEOF_POINTER__
  11470. # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  11471. defined(_M_ARM) || defined(__arm__) || defined(__x86)
  11472. # define SQLITE_PTRSIZE 4
  11473. # else
  11474. # define SQLITE_PTRSIZE 8
  11475. # endif
  11476. #endif
  11477. /* The uptr type is an unsigned integer large enough to hold a pointer
  11478. */
  11479. #if defined(HAVE_STDINT_H)
  11480. typedef uintptr_t uptr;
  11481. #elif SQLITE_PTRSIZE==4
  11482. typedef u32 uptr;
  11483. #else
  11484. typedef u64 uptr;
  11485. #endif
  11486. /*
  11487. ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
  11488. ** something between S (inclusive) and E (exclusive).
  11489. **
  11490. ** In other words, S is a buffer and E is a pointer to the first byte after
  11491. ** the end of buffer S. This macro returns true if P points to something
  11492. ** contained within the buffer S.
  11493. */
  11494. #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
  11495. /*
  11496. ** Macros to determine whether the machine is big or little endian,
  11497. ** and whether or not that determination is run-time or compile-time.
  11498. **
  11499. ** For best performance, an attempt is made to guess at the byte-order
  11500. ** using C-preprocessor macros. If that is unsuccessful, or if
  11501. ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
  11502. ** at run-time.
  11503. */
  11504. #ifndef SQLITE_BYTEORDER
  11505. # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  11506. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  11507. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  11508. defined(__arm__)
  11509. # define SQLITE_BYTEORDER 1234
  11510. # elif defined(sparc) || defined(__ppc__)
  11511. # define SQLITE_BYTEORDER 4321
  11512. # else
  11513. # define SQLITE_BYTEORDER 0
  11514. # endif
  11515. #endif
  11516. #if SQLITE_BYTEORDER==4321
  11517. # define SQLITE_BIGENDIAN 1
  11518. # define SQLITE_LITTLEENDIAN 0
  11519. # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
  11520. #elif SQLITE_BYTEORDER==1234
  11521. # define SQLITE_BIGENDIAN 0
  11522. # define SQLITE_LITTLEENDIAN 1
  11523. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  11524. #else
  11525. # ifdef SQLITE_AMALGAMATION
  11526. const int sqlite3one = 1;
  11527. # else
  11528. extern const int sqlite3one;
  11529. # endif
  11530. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  11531. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  11532. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  11533. #endif
  11534. /*
  11535. ** Constants for the largest and smallest possible 64-bit signed integers.
  11536. ** These macros are designed to work correctly on both 32-bit and 64-bit
  11537. ** compilers.
  11538. */
  11539. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  11540. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  11541. /*
  11542. ** Round up a number to the next larger multiple of 8. This is used
  11543. ** to force 8-byte alignment on 64-bit architectures.
  11544. */
  11545. #define ROUND8(x) (((x)+7)&~7)
  11546. /*
  11547. ** Round down to the nearest multiple of 8
  11548. */
  11549. #define ROUNDDOWN8(x) ((x)&~7)
  11550. /*
  11551. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  11552. ** macro is used only within assert() to verify that the code gets
  11553. ** all alignment restrictions correct.
  11554. **
  11555. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  11556. ** underlying malloc() implementation might return us 4-byte aligned
  11557. ** pointers. In that case, only verify 4-byte alignment.
  11558. */
  11559. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  11560. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  11561. #else
  11562. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  11563. #endif
  11564. /*
  11565. ** Disable MMAP on platforms where it is known to not work
  11566. */
  11567. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  11568. # undef SQLITE_MAX_MMAP_SIZE
  11569. # define SQLITE_MAX_MMAP_SIZE 0
  11570. #endif
  11571. /*
  11572. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  11573. */
  11574. #ifdef __APPLE__
  11575. # include <TargetConditionals.h>
  11576. #endif
  11577. #ifndef SQLITE_MAX_MMAP_SIZE
  11578. # if defined(__linux__) \
  11579. || defined(_WIN32) \
  11580. || (defined(__APPLE__) && defined(__MACH__)) \
  11581. || defined(__sun) \
  11582. || defined(__FreeBSD__) \
  11583. || defined(__DragonFly__)
  11584. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  11585. # else
  11586. # define SQLITE_MAX_MMAP_SIZE 0
  11587. # endif
  11588. # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
  11589. #endif
  11590. /*
  11591. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  11592. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  11593. ** not exceed the maximum mmap size.
  11594. */
  11595. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  11596. # define SQLITE_DEFAULT_MMAP_SIZE 0
  11597. # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
  11598. #endif
  11599. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  11600. # undef SQLITE_DEFAULT_MMAP_SIZE
  11601. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  11602. #endif
  11603. /*
  11604. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  11605. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  11606. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  11607. */
  11608. #ifdef SQLITE_ENABLE_STAT4
  11609. # undef SQLITE_ENABLE_STAT3
  11610. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  11611. #elif SQLITE_ENABLE_STAT3
  11612. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  11613. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  11614. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  11615. #endif
  11616. /*
  11617. ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
  11618. ** the Select query generator tracing logic is turned on.
  11619. */
  11620. #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
  11621. # define SELECTTRACE_ENABLED 1
  11622. #else
  11623. # define SELECTTRACE_ENABLED 0
  11624. #endif
  11625. /*
  11626. ** An instance of the following structure is used to store the busy-handler
  11627. ** callback for a given sqlite handle.
  11628. **
  11629. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  11630. ** callback for the database handle. Each pager opened via the sqlite
  11631. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  11632. ** callback is currently invoked only from within pager.c.
  11633. */
  11634. typedef struct BusyHandler BusyHandler;
  11635. struct BusyHandler {
  11636. int (*xFunc)(void *,int); /* The busy callback */
  11637. void *pArg; /* First arg to busy callback */
  11638. int nBusy; /* Incremented with each busy call */
  11639. };
  11640. /*
  11641. ** Name of the master database table. The master database table
  11642. ** is a special table that holds the names and attributes of all
  11643. ** user tables and indices.
  11644. */
  11645. #define MASTER_NAME "sqlite_master"
  11646. #define TEMP_MASTER_NAME "sqlite_temp_master"
  11647. /*
  11648. ** The root-page of the master database table.
  11649. */
  11650. #define MASTER_ROOT 1
  11651. /*
  11652. ** The name of the schema table.
  11653. */
  11654. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  11655. /*
  11656. ** A convenience macro that returns the number of elements in
  11657. ** an array.
  11658. */
  11659. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  11660. /*
  11661. ** Determine if the argument is a power of two
  11662. */
  11663. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  11664. /*
  11665. ** The following value as a destructor means to use sqlite3DbFree().
  11666. ** The sqlite3DbFree() routine requires two parameters instead of the
  11667. ** one parameter that destructors normally want. So we have to introduce
  11668. ** this magic value that the code knows to handle differently. Any
  11669. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  11670. ** and SQLITE_TRANSIENT.
  11671. */
  11672. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  11673. /*
  11674. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  11675. ** not support Writable Static Data (WSD) such as global and static variables.
  11676. ** All variables must either be on the stack or dynamically allocated from
  11677. ** the heap. When WSD is unsupported, the variable declarations scattered
  11678. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  11679. ** macro is used for this purpose. And instead of referencing the variable
  11680. ** directly, we use its constant as a key to lookup the run-time allocated
  11681. ** buffer that holds real variable. The constant is also the initializer
  11682. ** for the run-time allocated buffer.
  11683. **
  11684. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  11685. ** macros become no-ops and have zero performance impact.
  11686. */
  11687. #ifdef SQLITE_OMIT_WSD
  11688. #define SQLITE_WSD const
  11689. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  11690. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  11691. SQLITE_API int sqlite3_wsd_init(int N, int J);
  11692. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  11693. #else
  11694. #define SQLITE_WSD
  11695. #define GLOBAL(t,v) v
  11696. #define sqlite3GlobalConfig sqlite3Config
  11697. #endif
  11698. /*
  11699. ** The following macros are used to suppress compiler warnings and to
  11700. ** make it clear to human readers when a function parameter is deliberately
  11701. ** left unused within the body of a function. This usually happens when
  11702. ** a function is called via a function pointer. For example the
  11703. ** implementation of an SQL aggregate step callback may not use the
  11704. ** parameter indicating the number of arguments passed to the aggregate,
  11705. ** if it knows that this is enforced elsewhere.
  11706. **
  11707. ** When a function parameter is not used at all within the body of a function,
  11708. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  11709. ** However, these macros may also be used to suppress warnings related to
  11710. ** parameters that may or may not be used depending on compilation options.
  11711. ** For example those parameters only used in assert() statements. In these
  11712. ** cases the parameters are named as per the usual conventions.
  11713. */
  11714. #define UNUSED_PARAMETER(x) (void)(x)
  11715. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  11716. /*
  11717. ** Forward references to structures
  11718. */
  11719. typedef struct AggInfo AggInfo;
  11720. typedef struct AuthContext AuthContext;
  11721. typedef struct AutoincInfo AutoincInfo;
  11722. typedef struct Bitvec Bitvec;
  11723. typedef struct CollSeq CollSeq;
  11724. typedef struct Column Column;
  11725. typedef struct Db Db;
  11726. typedef struct Schema Schema;
  11727. typedef struct Expr Expr;
  11728. typedef struct ExprList ExprList;
  11729. typedef struct ExprSpan ExprSpan;
  11730. typedef struct FKey FKey;
  11731. typedef struct FuncDestructor FuncDestructor;
  11732. typedef struct FuncDef FuncDef;
  11733. typedef struct FuncDefHash FuncDefHash;
  11734. typedef struct IdList IdList;
  11735. typedef struct Index Index;
  11736. typedef struct IndexSample IndexSample;
  11737. typedef struct KeyClass KeyClass;
  11738. typedef struct KeyInfo KeyInfo;
  11739. typedef struct Lookaside Lookaside;
  11740. typedef struct LookasideSlot LookasideSlot;
  11741. typedef struct Module Module;
  11742. typedef struct NameContext NameContext;
  11743. typedef struct Parse Parse;
  11744. typedef struct PreUpdate PreUpdate;
  11745. typedef struct PrintfArguments PrintfArguments;
  11746. typedef struct RowSet RowSet;
  11747. typedef struct Savepoint Savepoint;
  11748. typedef struct Select Select;
  11749. typedef struct SQLiteThread SQLiteThread;
  11750. typedef struct SelectDest SelectDest;
  11751. typedef struct SrcList SrcList;
  11752. typedef struct StrAccum StrAccum;
  11753. typedef struct Table Table;
  11754. typedef struct TableLock TableLock;
  11755. typedef struct Token Token;
  11756. typedef struct TreeView TreeView;
  11757. typedef struct Trigger Trigger;
  11758. typedef struct TriggerPrg TriggerPrg;
  11759. typedef struct TriggerStep TriggerStep;
  11760. typedef struct UnpackedRecord UnpackedRecord;
  11761. typedef struct VTable VTable;
  11762. typedef struct VtabCtx VtabCtx;
  11763. typedef struct Walker Walker;
  11764. typedef struct WhereInfo WhereInfo;
  11765. typedef struct With With;
  11766. /* A VList object records a mapping between parameters/variables/wildcards
  11767. ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
  11768. ** variable number associated with that parameter. See the format description
  11769. ** on the sqlite3VListAdd() routine for more information. A VList is really
  11770. ** just an array of integers.
  11771. */
  11772. typedef int VList;
  11773. /*
  11774. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  11775. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  11776. ** pointer types (i.e. FuncDef) defined above.
  11777. */
  11778. /************** Include btree.h in the middle of sqliteInt.h *****************/
  11779. /************** Begin file btree.h *******************************************/
  11780. /*
  11781. ** 2001 September 15
  11782. **
  11783. ** The author disclaims copyright to this source code. In place of
  11784. ** a legal notice, here is a blessing:
  11785. **
  11786. ** May you do good and not evil.
  11787. ** May you find forgiveness for yourself and forgive others.
  11788. ** May you share freely, never taking more than you give.
  11789. **
  11790. *************************************************************************
  11791. ** This header file defines the interface that the sqlite B-Tree file
  11792. ** subsystem. See comments in the source code for a detailed description
  11793. ** of what each interface routine does.
  11794. */
  11795. #ifndef SQLITE_BTREE_H
  11796. #define SQLITE_BTREE_H
  11797. /* TODO: This definition is just included so other modules compile. It
  11798. ** needs to be revisited.
  11799. */
  11800. #define SQLITE_N_BTREE_META 16
  11801. /*
  11802. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  11803. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  11804. */
  11805. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  11806. #define SQLITE_DEFAULT_AUTOVACUUM 0
  11807. #endif
  11808. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  11809. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  11810. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  11811. /*
  11812. ** Forward declarations of structure
  11813. */
  11814. typedef struct Btree Btree;
  11815. typedef struct BtCursor BtCursor;
  11816. typedef struct BtShared BtShared;
  11817. typedef struct BtreePayload BtreePayload;
  11818. SQLITE_PRIVATE int sqlite3BtreeOpen(
  11819. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  11820. const char *zFilename, /* Name of database file to open */
  11821. sqlite3 *db, /* Associated database connection */
  11822. Btree **ppBtree, /* Return open Btree* here */
  11823. int flags, /* Flags */
  11824. int vfsFlags /* Flags passed through to VFS open */
  11825. );
  11826. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  11827. ** following values.
  11828. **
  11829. ** NOTE: These values must match the corresponding PAGER_ values in
  11830. ** pager.h.
  11831. */
  11832. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  11833. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  11834. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  11835. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  11836. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  11837. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  11838. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
  11839. #if SQLITE_MAX_MMAP_SIZE>0
  11840. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  11841. #endif
  11842. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  11843. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  11844. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  11845. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  11846. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  11847. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  11848. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
  11849. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  11850. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  11851. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  11852. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  11853. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  11854. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  11855. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  11856. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
  11857. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  11858. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  11859. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  11860. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  11861. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  11862. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  11863. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  11864. #ifndef SQLITE_OMIT_SHARED_CACHE
  11865. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  11866. #endif
  11867. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  11868. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  11869. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  11870. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  11871. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  11872. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  11873. ** of the flags shown below.
  11874. **
  11875. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  11876. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  11877. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  11878. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  11879. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  11880. ** indices.)
  11881. */
  11882. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  11883. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  11884. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  11885. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  11886. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
  11887. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
  11888. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  11889. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  11890. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  11891. /*
  11892. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  11893. ** should be one of the following values. The integer values are assigned
  11894. ** to constants so that the offset of the corresponding field in an
  11895. ** SQLite database header may be found using the following formula:
  11896. **
  11897. ** offset = 36 + (idx * 4)
  11898. **
  11899. ** For example, the free-page-count field is located at byte offset 36 of
  11900. ** the database file header. The incr-vacuum-flag field is located at
  11901. ** byte offset 64 (== 36+4*7).
  11902. **
  11903. ** The BTREE_DATA_VERSION value is not really a value stored in the header.
  11904. ** It is a read-only number computed by the pager. But we merge it with
  11905. ** the header value access routines since its access pattern is the same.
  11906. ** Call it a "virtual meta value".
  11907. */
  11908. #define BTREE_FREE_PAGE_COUNT 0
  11909. #define BTREE_SCHEMA_VERSION 1
  11910. #define BTREE_FILE_FORMAT 2
  11911. #define BTREE_DEFAULT_CACHE_SIZE 3
  11912. #define BTREE_LARGEST_ROOT_PAGE 4
  11913. #define BTREE_TEXT_ENCODING 5
  11914. #define BTREE_USER_VERSION 6
  11915. #define BTREE_INCR_VACUUM 7
  11916. #define BTREE_APPLICATION_ID 8
  11917. #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
  11918. /*
  11919. ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
  11920. ** interface.
  11921. **
  11922. ** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
  11923. **
  11924. ** The first argument is an Expr* (which is guaranteed to be constant for
  11925. ** the lifetime of the cursor) that defines constraints on which rows
  11926. ** might be fetched with this cursor. The Expr* tree may contain
  11927. ** TK_REGISTER nodes that refer to values stored in the array of registers
  11928. ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
  11929. ** then the value of the node is the value in Mem[pExpr.iTable]. Any
  11930. ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
  11931. ** column of the b-tree of the cursor. The Expr tree will not contain
  11932. ** any function calls nor subqueries nor references to b-trees other than
  11933. ** the cursor being hinted.
  11934. **
  11935. ** The design of the _RANGE hint is aid b-tree implementations that try
  11936. ** to prefetch content from remote machines - to provide those
  11937. ** implementations with limits on what needs to be prefetched and thereby
  11938. ** reduce network bandwidth.
  11939. **
  11940. ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
  11941. ** standard SQLite. The other hints are provided for extentions that use
  11942. ** the SQLite parser and code generator but substitute their own storage
  11943. ** engine.
  11944. */
  11945. #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
  11946. /*
  11947. ** Values that may be OR'd together to form the argument to the
  11948. ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
  11949. **
  11950. ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
  11951. ** to be filled with content that is already in sorted order.
  11952. **
  11953. ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
  11954. ** OP_SeekLE opcodes for a range search, but where the range of entries
  11955. ** selected will all have the same key. In other words, the cursor will
  11956. ** be used only for equality key searches.
  11957. **
  11958. */
  11959. #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
  11960. #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
  11961. /*
  11962. ** Flags passed as the third argument to sqlite3BtreeCursor().
  11963. **
  11964. ** For read-only cursors the wrFlag argument is always zero. For read-write
  11965. ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
  11966. ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
  11967. ** only be used by SQLite for the following:
  11968. **
  11969. ** * to seek to and then delete specific entries, and/or
  11970. **
  11971. ** * to read values that will be used to create keys that other
  11972. ** BTREE_FORDELETE cursors will seek to and delete.
  11973. **
  11974. ** The BTREE_FORDELETE flag is an optimization hint. It is not used by
  11975. ** by this, the native b-tree engine of SQLite, but it is available to
  11976. ** alternative storage engines that might be substituted in place of this
  11977. ** b-tree system. For alternative storage engines in which a delete of
  11978. ** the main table row automatically deletes corresponding index rows,
  11979. ** the FORDELETE flag hint allows those alternative storage engines to
  11980. ** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
  11981. ** and DELETE operations as no-ops, and any READ operation against a
  11982. ** FORDELETE cursor may return a null row: 0x01 0x00.
  11983. */
  11984. #define BTREE_WRCSR 0x00000004 /* read-write cursor */
  11985. #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
  11986. SQLITE_PRIVATE int sqlite3BtreeCursor(
  11987. Btree*, /* BTree containing table to open */
  11988. int iTable, /* Index of root page */
  11989. int wrFlag, /* 1 for writing. 0 for read-only */
  11990. struct KeyInfo*, /* First argument to compare function */
  11991. BtCursor *pCursor /* Space to write cursor structure */
  11992. );
  11993. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  11994. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  11995. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
  11996. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  11997. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
  11998. #endif
  11999. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  12000. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  12001. BtCursor*,
  12002. UnpackedRecord *pUnKey,
  12003. i64 intKey,
  12004. int bias,
  12005. int *pRes
  12006. );
  12007. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
  12008. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
  12009. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
  12010. /* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
  12011. #define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */
  12012. #define BTREE_AUXDELETE 0x04 /* not the primary delete operation */
  12013. #define BTREE_APPEND 0x08 /* Insert is likely an append */
  12014. /* An instance of the BtreePayload object describes the content of a single
  12015. ** entry in either an index or table btree.
  12016. **
  12017. ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
  12018. ** an arbitrary key and no data. These btrees have pKey,nKey set to their
  12019. ** key and pData,nData,nZero set to zero.
  12020. **
  12021. ** Table btrees (used for rowid tables) contain an integer rowid used as
  12022. ** the key and passed in the nKey field. The pKey field is zero.
  12023. ** pData,nData hold the content of the new entry. nZero extra zero bytes
  12024. ** are appended to the end of the content when constructing the entry.
  12025. **
  12026. ** This object is used to pass information into sqlite3BtreeInsert(). The
  12027. ** same information used to be passed as five separate parameters. But placing
  12028. ** the information into this object helps to keep the interface more
  12029. ** organized and understandable, and it also helps the resulting code to
  12030. ** run a little faster by using fewer registers for parameter passing.
  12031. */
  12032. struct BtreePayload {
  12033. const void *pKey; /* Key content for indexes. NULL for tables */
  12034. sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */
  12035. const void *pData; /* Data for tables. NULL for indexes */
  12036. sqlite3_value *aMem; /* First of nMem value in the unpacked pKey */
  12037. u16 nMem; /* Number of aMem[] value. Might be zero */
  12038. int nData; /* Size of pData. 0 if none. */
  12039. int nZero; /* Extra zero data appended after pData,nData */
  12040. };
  12041. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
  12042. int flags, int seekResult);
  12043. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  12044. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  12045. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  12046. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  12047. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  12048. SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
  12049. SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
  12050. SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
  12051. SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
  12052. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  12053. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  12054. SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
  12055. #ifndef SQLITE_OMIT_INCRBLOB
  12056. SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
  12057. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  12058. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
  12059. #endif
  12060. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  12061. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  12062. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
  12063. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
  12064. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
  12065. #ifndef NDEBUG
  12066. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  12067. #endif
  12068. SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
  12069. #ifndef SQLITE_OMIT_BTREECOUNT
  12070. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  12071. #endif
  12072. #ifdef SQLITE_TEST
  12073. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  12074. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  12075. #endif
  12076. #ifndef SQLITE_OMIT_WAL
  12077. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  12078. #endif
  12079. /*
  12080. ** If we are not using shared cache, then there is no need to
  12081. ** use mutexes to access the BtShared structures. So make the
  12082. ** Enter and Leave procedures no-ops.
  12083. */
  12084. #ifndef SQLITE_OMIT_SHARED_CACHE
  12085. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  12086. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  12087. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  12088. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  12089. SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*);
  12090. #else
  12091. # define sqlite3BtreeEnter(X)
  12092. # define sqlite3BtreeEnterAll(X)
  12093. # define sqlite3BtreeSharable(X) 0
  12094. # define sqlite3BtreeEnterCursor(X)
  12095. # define sqlite3BtreeConnectionCount(X) 1
  12096. #endif
  12097. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  12098. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  12099. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  12100. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  12101. #ifndef NDEBUG
  12102. /* These routines are used inside assert() statements only. */
  12103. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  12104. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  12105. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  12106. #endif
  12107. #else
  12108. # define sqlite3BtreeLeave(X)
  12109. # define sqlite3BtreeLeaveCursor(X)
  12110. # define sqlite3BtreeLeaveAll(X)
  12111. # define sqlite3BtreeHoldsMutex(X) 1
  12112. # define sqlite3BtreeHoldsAllMutexes(X) 1
  12113. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  12114. #endif
  12115. #endif /* SQLITE_BTREE_H */
  12116. /************** End of btree.h ***********************************************/
  12117. /************** Continuing where we left off in sqliteInt.h ******************/
  12118. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  12119. /************** Begin file vdbe.h ********************************************/
  12120. /*
  12121. ** 2001 September 15
  12122. **
  12123. ** The author disclaims copyright to this source code. In place of
  12124. ** a legal notice, here is a blessing:
  12125. **
  12126. ** May you do good and not evil.
  12127. ** May you find forgiveness for yourself and forgive others.
  12128. ** May you share freely, never taking more than you give.
  12129. **
  12130. *************************************************************************
  12131. ** Header file for the Virtual DataBase Engine (VDBE)
  12132. **
  12133. ** This header defines the interface to the virtual database engine
  12134. ** or VDBE. The VDBE implements an abstract machine that runs a
  12135. ** simple program to access and modify the underlying database.
  12136. */
  12137. #ifndef SQLITE_VDBE_H
  12138. #define SQLITE_VDBE_H
  12139. /* #include <stdio.h> */
  12140. /*
  12141. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  12142. ** in the source file sqliteVdbe.c are allowed to see the insides
  12143. ** of this structure.
  12144. */
  12145. typedef struct Vdbe Vdbe;
  12146. /*
  12147. ** The names of the following types declared in vdbeInt.h are required
  12148. ** for the VdbeOp definition.
  12149. */
  12150. typedef struct sqlite3_value Mem;
  12151. typedef struct SubProgram SubProgram;
  12152. /*
  12153. ** A single instruction of the virtual machine has an opcode
  12154. ** and as many as three operands. The instruction is recorded
  12155. ** as an instance of the following structure:
  12156. */
  12157. struct VdbeOp {
  12158. u8 opcode; /* What operation to perform */
  12159. signed char p4type; /* One of the P4_xxx constants for p4 */
  12160. u16 p5; /* Fifth parameter is an unsigned 16-bit integer */
  12161. int p1; /* First operand */
  12162. int p2; /* Second parameter (often the jump destination) */
  12163. int p3; /* The third parameter */
  12164. union p4union { /* fourth parameter */
  12165. int i; /* Integer value if p4type==P4_INT32 */
  12166. void *p; /* Generic pointer */
  12167. char *z; /* Pointer to data for string (char array) types */
  12168. i64 *pI64; /* Used when p4type is P4_INT64 */
  12169. double *pReal; /* Used when p4type is P4_REAL */
  12170. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  12171. sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
  12172. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  12173. Mem *pMem; /* Used when p4type is P4_MEM */
  12174. VTable *pVtab; /* Used when p4type is P4_VTAB */
  12175. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  12176. int *ai; /* Used when p4type is P4_INTARRAY */
  12177. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  12178. Table *pTab; /* Used when p4type is P4_TABLE */
  12179. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  12180. Expr *pExpr; /* Used when p4type is P4_EXPR */
  12181. #endif
  12182. int (*xAdvance)(BtCursor *, int *);
  12183. } p4;
  12184. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  12185. char *zComment; /* Comment to improve readability */
  12186. #endif
  12187. #ifdef VDBE_PROFILE
  12188. u32 cnt; /* Number of times this instruction was executed */
  12189. u64 cycles; /* Total time spent executing this instruction */
  12190. #endif
  12191. #ifdef SQLITE_VDBE_COVERAGE
  12192. int iSrcLine; /* Source-code line that generated this opcode */
  12193. #endif
  12194. };
  12195. typedef struct VdbeOp VdbeOp;
  12196. /*
  12197. ** A sub-routine used to implement a trigger program.
  12198. */
  12199. struct SubProgram {
  12200. VdbeOp *aOp; /* Array of opcodes for sub-program */
  12201. int nOp; /* Elements in aOp[] */
  12202. int nMem; /* Number of memory cells required */
  12203. int nCsr; /* Number of cursors required */
  12204. u8 *aOnce; /* Array of OP_Once flags */
  12205. void *token; /* id that may be used to recursive triggers */
  12206. SubProgram *pNext; /* Next sub-program already visited */
  12207. };
  12208. /*
  12209. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  12210. ** it takes up less space.
  12211. */
  12212. struct VdbeOpList {
  12213. u8 opcode; /* What operation to perform */
  12214. signed char p1; /* First operand */
  12215. signed char p2; /* Second parameter (often the jump destination) */
  12216. signed char p3; /* Third parameter */
  12217. };
  12218. typedef struct VdbeOpList VdbeOpList;
  12219. /*
  12220. ** Allowed values of VdbeOp.p4type
  12221. */
  12222. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  12223. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  12224. #define P4_STATIC (-2) /* Pointer to a static string */
  12225. #define P4_COLLSEQ (-3) /* P4 is a pointer to a CollSeq structure */
  12226. #define P4_FUNCDEF (-4) /* P4 is a pointer to a FuncDef structure */
  12227. #define P4_KEYINFO (-5) /* P4 is a pointer to a KeyInfo structure */
  12228. #define P4_EXPR (-6) /* P4 is a pointer to an Expr tree */
  12229. #define P4_MEM (-7) /* P4 is a pointer to a Mem* structure */
  12230. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  12231. #define P4_VTAB (-8) /* P4 is a pointer to an sqlite3_vtab structure */
  12232. #define P4_REAL (-9) /* P4 is a 64-bit floating point value */
  12233. #define P4_INT64 (-10) /* P4 is a 64-bit signed integer */
  12234. #define P4_INT32 (-11) /* P4 is a 32-bit signed integer */
  12235. #define P4_INTARRAY (-12) /* P4 is a vector of 32-bit integers */
  12236. #define P4_SUBPROGRAM (-13) /* P4 is a pointer to a SubProgram structure */
  12237. #define P4_ADVANCE (-14) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  12238. #define P4_TABLE (-15) /* P4 is a pointer to a Table structure */
  12239. #define P4_FUNCCTX (-16) /* P4 is a pointer to an sqlite3_context object */
  12240. /* Error message codes for OP_Halt */
  12241. #define P5_ConstraintNotNull 1
  12242. #define P5_ConstraintUnique 2
  12243. #define P5_ConstraintCheck 3
  12244. #define P5_ConstraintFK 4
  12245. /*
  12246. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  12247. ** number of columns of data returned by the statement.
  12248. */
  12249. #define COLNAME_NAME 0
  12250. #define COLNAME_DECLTYPE 1
  12251. #define COLNAME_DATABASE 2
  12252. #define COLNAME_TABLE 3
  12253. #define COLNAME_COLUMN 4
  12254. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  12255. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  12256. #else
  12257. # ifdef SQLITE_OMIT_DECLTYPE
  12258. # define COLNAME_N 1 /* Store only the name */
  12259. # else
  12260. # define COLNAME_N 2 /* Store the name and decltype */
  12261. # endif
  12262. #endif
  12263. /*
  12264. ** The following macro converts a relative address in the p2 field
  12265. ** of a VdbeOp structure into a negative number so that
  12266. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  12267. ** the macro again restores the address.
  12268. */
  12269. #define ADDR(X) (-1-(X))
  12270. /*
  12271. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  12272. ** header file that defines a number for each opcode used by the VDBE.
  12273. */
  12274. /************** Include opcodes.h in the middle of vdbe.h ********************/
  12275. /************** Begin file opcodes.h *****************************************/
  12276. /* Automatically generated. Do not edit */
  12277. /* See the tool/mkopcodeh.tcl script for details */
  12278. #define OP_Savepoint 0
  12279. #define OP_AutoCommit 1
  12280. #define OP_Transaction 2
  12281. #define OP_SorterNext 3
  12282. #define OP_PrevIfOpen 4
  12283. #define OP_NextIfOpen 5
  12284. #define OP_Prev 6
  12285. #define OP_Next 7
  12286. #define OP_Checkpoint 8
  12287. #define OP_JournalMode 9
  12288. #define OP_Vacuum 10
  12289. #define OP_VFilter 11 /* synopsis: iplan=r[P3] zplan='P4' */
  12290. #define OP_VUpdate 12 /* synopsis: data=r[P3@P2] */
  12291. #define OP_Goto 13
  12292. #define OP_Gosub 14
  12293. #define OP_InitCoroutine 15
  12294. #define OP_Yield 16
  12295. #define OP_MustBeInt 17
  12296. #define OP_Jump 18
  12297. #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
  12298. #define OP_Once 20
  12299. #define OP_If 21
  12300. #define OP_IfNot 22
  12301. #define OP_IfNullRow 23 /* synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
  12302. #define OP_SeekLT 24 /* synopsis: key=r[P3@P4] */
  12303. #define OP_SeekLE 25 /* synopsis: key=r[P3@P4] */
  12304. #define OP_SeekGE 26 /* synopsis: key=r[P3@P4] */
  12305. #define OP_SeekGT 27 /* synopsis: key=r[P3@P4] */
  12306. #define OP_NoConflict 28 /* synopsis: key=r[P3@P4] */
  12307. #define OP_NotFound 29 /* synopsis: key=r[P3@P4] */
  12308. #define OP_Found 30 /* synopsis: key=r[P3@P4] */
  12309. #define OP_SeekRowid 31 /* synopsis: intkey=r[P3] */
  12310. #define OP_NotExists 32 /* synopsis: intkey=r[P3] */
  12311. #define OP_Last 33
  12312. #define OP_IfSmaller 34
  12313. #define OP_SorterSort 35
  12314. #define OP_Sort 36
  12315. #define OP_Rewind 37
  12316. #define OP_IdxLE 38 /* synopsis: key=r[P3@P4] */
  12317. #define OP_IdxGT 39 /* synopsis: key=r[P3@P4] */
  12318. #define OP_IdxLT 40 /* synopsis: key=r[P3@P4] */
  12319. #define OP_IdxGE 41 /* synopsis: key=r[P3@P4] */
  12320. #define OP_RowSetRead 42 /* synopsis: r[P3]=rowset(P1) */
  12321. #define OP_RowSetTest 43 /* synopsis: if r[P3] in rowset(P1) goto P2 */
  12322. #define OP_Program 44
  12323. #define OP_FkIfZero 45 /* synopsis: if fkctr[P1]==0 goto P2 */
  12324. #define OP_IfPos 46 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
  12325. #define OP_IfNotZero 47 /* synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
  12326. #define OP_DecrJumpZero 48 /* synopsis: if (--r[P1])==0 goto P2 */
  12327. #define OP_IncrVacuum 49
  12328. #define OP_VNext 50
  12329. #define OP_Init 51 /* synopsis: Start at P2 */
  12330. #define OP_Return 52
  12331. #define OP_EndCoroutine 53
  12332. #define OP_HaltIfNull 54 /* synopsis: if r[P3]=null halt */
  12333. #define OP_Halt 55
  12334. #define OP_Integer 56 /* synopsis: r[P2]=P1 */
  12335. #define OP_Int64 57 /* synopsis: r[P2]=P4 */
  12336. #define OP_String 58 /* synopsis: r[P2]='P4' (len=P1) */
  12337. #define OP_Null 59 /* synopsis: r[P2..P3]=NULL */
  12338. #define OP_SoftNull 60 /* synopsis: r[P1]=NULL */
  12339. #define OP_Blob 61 /* synopsis: r[P2]=P4 (len=P1) */
  12340. #define OP_Variable 62 /* synopsis: r[P2]=parameter(P1,P4) */
  12341. #define OP_Move 63 /* synopsis: r[P2@P3]=r[P1@P3] */
  12342. #define OP_Copy 64 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
  12343. #define OP_SCopy 65 /* synopsis: r[P2]=r[P1] */
  12344. #define OP_IntCopy 66 /* synopsis: r[P2]=r[P1] */
  12345. #define OP_ResultRow 67 /* synopsis: output=r[P1@P2] */
  12346. #define OP_CollSeq 68
  12347. #define OP_Function0 69 /* synopsis: r[P3]=func(r[P2@P5]) */
  12348. #define OP_Or 70 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
  12349. #define OP_And 71 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
  12350. #define OP_Function 72 /* synopsis: r[P3]=func(r[P2@P5]) */
  12351. #define OP_AddImm 73 /* synopsis: r[P1]=r[P1]+P2 */
  12352. #define OP_RealAffinity 74
  12353. #define OP_IsNull 75 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
  12354. #define OP_NotNull 76 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
  12355. #define OP_Ne 77 /* same as TK_NE, synopsis: IF r[P3]!=r[P1] */
  12356. #define OP_Eq 78 /* same as TK_EQ, synopsis: IF r[P3]==r[P1] */
  12357. #define OP_Gt 79 /* same as TK_GT, synopsis: IF r[P3]>r[P1] */
  12358. #define OP_Le 80 /* same as TK_LE, synopsis: IF r[P3]<=r[P1] */
  12359. #define OP_Lt 81 /* same as TK_LT, synopsis: IF r[P3]<r[P1] */
  12360. #define OP_Ge 82 /* same as TK_GE, synopsis: IF r[P3]>=r[P1] */
  12361. #define OP_ElseNotEq 83 /* same as TK_ESCAPE */
  12362. #define OP_BitAnd 84 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
  12363. #define OP_BitOr 85 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
  12364. #define OP_ShiftLeft 86 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
  12365. #define OP_ShiftRight 87 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
  12366. #define OP_Add 88 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
  12367. #define OP_Subtract 89 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
  12368. #define OP_Multiply 90 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
  12369. #define OP_Divide 91 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
  12370. #define OP_Remainder 92 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
  12371. #define OP_Concat 93 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
  12372. #define OP_Cast 94 /* synopsis: affinity(r[P1]) */
  12373. #define OP_BitNot 95 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
  12374. #define OP_Permutation 96
  12375. #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
  12376. #define OP_Compare 98 /* synopsis: r[P1@P3] <-> r[P2@P3] */
  12377. #define OP_Column 99 /* synopsis: r[P3]=PX */
  12378. #define OP_Affinity 100 /* synopsis: affinity(r[P1@P2]) */
  12379. #define OP_MakeRecord 101 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
  12380. #define OP_Count 102 /* synopsis: r[P2]=count() */
  12381. #define OP_ReadCookie 103
  12382. #define OP_SetCookie 104
  12383. #define OP_ReopenIdx 105 /* synopsis: root=P2 iDb=P3 */
  12384. #define OP_OpenRead 106 /* synopsis: root=P2 iDb=P3 */
  12385. #define OP_OpenWrite 107 /* synopsis: root=P2 iDb=P3 */
  12386. #define OP_OpenDup 108
  12387. #define OP_OpenAutoindex 109 /* synopsis: nColumn=P2 */
  12388. #define OP_OpenEphemeral 110 /* synopsis: nColumn=P2 */
  12389. #define OP_SorterOpen 111
  12390. #define OP_SequenceTest 112 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
  12391. #define OP_OpenPseudo 113 /* synopsis: P3 columns in r[P2] */
  12392. #define OP_Close 114
  12393. #define OP_ColumnsUsed 115
  12394. #define OP_Sequence 116 /* synopsis: r[P2]=cursor[P1].ctr++ */
  12395. #define OP_NewRowid 117 /* synopsis: r[P2]=rowid */
  12396. #define OP_Insert 118 /* synopsis: intkey=r[P3] data=r[P2] */
  12397. #define OP_InsertInt 119 /* synopsis: intkey=P3 data=r[P2] */
  12398. #define OP_Delete 120
  12399. #define OP_ResetCount 121
  12400. #define OP_SorterCompare 122 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
  12401. #define OP_SorterData 123 /* synopsis: r[P2]=data */
  12402. #define OP_RowData 124 /* synopsis: r[P2]=data */
  12403. #define OP_Rowid 125 /* synopsis: r[P2]=rowid */
  12404. #define OP_NullRow 126
  12405. #define OP_SorterInsert 127 /* synopsis: key=r[P2] */
  12406. #define OP_IdxInsert 128 /* synopsis: key=r[P2] */
  12407. #define OP_IdxDelete 129 /* synopsis: key=r[P2@P3] */
  12408. #define OP_Seek 130 /* synopsis: Move P3 to P1.rowid */
  12409. #define OP_IdxRowid 131 /* synopsis: r[P2]=rowid */
  12410. #define OP_Real 132 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
  12411. #define OP_Destroy 133
  12412. #define OP_Clear 134
  12413. #define OP_ResetSorter 135
  12414. #define OP_CreateIndex 136 /* synopsis: r[P2]=root iDb=P1 */
  12415. #define OP_CreateTable 137 /* synopsis: r[P2]=root iDb=P1 */
  12416. #define OP_SqlExec 138
  12417. #define OP_ParseSchema 139
  12418. #define OP_LoadAnalysis 140
  12419. #define OP_DropTable 141
  12420. #define OP_DropIndex 142
  12421. #define OP_DropTrigger 143
  12422. #define OP_IntegrityCk 144
  12423. #define OP_RowSetAdd 145 /* synopsis: rowset(P1)=r[P2] */
  12424. #define OP_Param 146
  12425. #define OP_FkCounter 147 /* synopsis: fkctr[P1]+=P2 */
  12426. #define OP_MemMax 148 /* synopsis: r[P1]=max(r[P1],r[P2]) */
  12427. #define OP_OffsetLimit 149 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
  12428. #define OP_AggStep0 150 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  12429. #define OP_AggStep 151 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  12430. #define OP_AggFinal 152 /* synopsis: accum=r[P1] N=P2 */
  12431. #define OP_Expire 153
  12432. #define OP_TableLock 154 /* synopsis: iDb=P1 root=P2 write=P3 */
  12433. #define OP_VBegin 155
  12434. #define OP_VCreate 156
  12435. #define OP_VDestroy 157
  12436. #define OP_VOpen 158
  12437. #define OP_VColumn 159 /* synopsis: r[P3]=vcolumn(P2) */
  12438. #define OP_VRename 160
  12439. #define OP_Pagecount 161
  12440. #define OP_MaxPgcnt 162
  12441. #define OP_CursorHint 163
  12442. #define OP_Noop 164
  12443. #define OP_Explain 165
  12444. /* Properties such as "out2" or "jump" that are specified in
  12445. ** comments following the "case" for each opcode in the vdbe.c
  12446. ** are encoded into bitvectors as follows:
  12447. */
  12448. #define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */
  12449. #define OPFLG_IN1 0x02 /* in1: P1 is an input */
  12450. #define OPFLG_IN2 0x04 /* in2: P2 is an input */
  12451. #define OPFLG_IN3 0x08 /* in3: P3 is an input */
  12452. #define OPFLG_OUT2 0x10 /* out2: P2 is an output */
  12453. #define OPFLG_OUT3 0x20 /* out3: P3 is an output */
  12454. #define OPFLG_INITIALIZER {\
  12455. /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
  12456. /* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\
  12457. /* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x01,\
  12458. /* 24 */ 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,\
  12459. /* 32 */ 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
  12460. /* 40 */ 0x01, 0x01, 0x23, 0x0b, 0x01, 0x01, 0x03, 0x03,\
  12461. /* 48 */ 0x03, 0x01, 0x01, 0x01, 0x02, 0x02, 0x08, 0x00,\
  12462. /* 56 */ 0x10, 0x10, 0x10, 0x10, 0x00, 0x10, 0x10, 0x00,\
  12463. /* 64 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x26, 0x26,\
  12464. /* 72 */ 0x00, 0x02, 0x02, 0x03, 0x03, 0x0b, 0x0b, 0x0b,\
  12465. /* 80 */ 0x0b, 0x0b, 0x0b, 0x01, 0x26, 0x26, 0x26, 0x26,\
  12466. /* 88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x02, 0x12,\
  12467. /* 96 */ 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10,\
  12468. /* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  12469. /* 112 */ 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
  12470. /* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x04,\
  12471. /* 128 */ 0x04, 0x00, 0x00, 0x10, 0x10, 0x10, 0x00, 0x00,\
  12472. /* 136 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  12473. /* 144 */ 0x00, 0x06, 0x10, 0x00, 0x04, 0x1a, 0x00, 0x00,\
  12474. /* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  12475. /* 160 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00,}
  12476. /* The sqlite3P2Values() routine is able to run faster if it knows
  12477. ** the value of the largest JUMP opcode. The smaller the maximum
  12478. ** JUMP opcode the better, so the mkopcodeh.tcl script that
  12479. ** generated this include file strives to group all JUMP opcodes
  12480. ** together near the beginning of the list.
  12481. */
  12482. #define SQLITE_MX_JUMP_OPCODE 83 /* Maximum JUMP opcode */
  12483. /************** End of opcodes.h *********************************************/
  12484. /************** Continuing where we left off in vdbe.h ***********************/
  12485. /*
  12486. ** Prototypes for the VDBE interface. See comments on the implementation
  12487. ** for a description of what each of these routines does.
  12488. */
  12489. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
  12490. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  12491. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  12492. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  12493. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
  12494. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
  12495. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
  12496. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  12497. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  12498. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
  12499. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  12500. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
  12501. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  12502. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
  12503. SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
  12504. #else
  12505. # define sqlite3VdbeVerifyNoMallocRequired(A,B)
  12506. # define sqlite3VdbeVerifyNoResultRow(A)
  12507. #endif
  12508. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
  12509. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  12510. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
  12511. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  12512. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  12513. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  12514. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
  12515. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  12516. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  12517. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
  12518. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  12519. SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
  12520. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
  12521. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  12522. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  12523. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  12524. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  12525. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
  12526. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  12527. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  12528. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  12529. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  12530. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  12531. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  12532. #ifdef SQLITE_DEBUG
  12533. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  12534. #endif
  12535. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  12536. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  12537. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  12538. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  12539. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  12540. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  12541. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  12542. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  12543. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  12544. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  12545. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  12546. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  12547. #ifndef SQLITE_OMIT_TRACE
  12548. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  12549. #endif
  12550. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  12551. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  12552. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  12553. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
  12554. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
  12555. typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
  12556. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
  12557. #ifndef SQLITE_OMIT_TRIGGER
  12558. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  12559. #endif
  12560. /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
  12561. ** each VDBE opcode.
  12562. **
  12563. ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
  12564. ** comments in VDBE programs that show key decision points in the code
  12565. ** generator.
  12566. */
  12567. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  12568. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  12569. # define VdbeComment(X) sqlite3VdbeComment X
  12570. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  12571. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  12572. # ifdef SQLITE_ENABLE_MODULE_COMMENTS
  12573. # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
  12574. # else
  12575. # define VdbeModuleComment(X)
  12576. # endif
  12577. #else
  12578. # define VdbeComment(X)
  12579. # define VdbeNoopComment(X)
  12580. # define VdbeModuleComment(X)
  12581. #endif
  12582. /*
  12583. ** The VdbeCoverage macros are used to set a coverage testing point
  12584. ** for VDBE branch instructions. The coverage testing points are line
  12585. ** numbers in the sqlite3.c source file. VDBE branch coverage testing
  12586. ** only works with an amalagmation build. That's ok since a VDBE branch
  12587. ** coverage build designed for testing the test suite only. No application
  12588. ** should ever ship with VDBE branch coverage measuring turned on.
  12589. **
  12590. ** VdbeCoverage(v) // Mark the previously coded instruction
  12591. ** // as a branch
  12592. **
  12593. ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
  12594. **
  12595. ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
  12596. **
  12597. ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
  12598. **
  12599. ** Every VDBE branch operation must be tagged with one of the macros above.
  12600. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
  12601. ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
  12602. ** routine in vdbe.c, alerting the developer to the missed tag.
  12603. */
  12604. #ifdef SQLITE_VDBE_COVERAGE
  12605. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
  12606. # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
  12607. # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
  12608. # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
  12609. # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
  12610. # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
  12611. #else
  12612. # define VdbeCoverage(v)
  12613. # define VdbeCoverageIf(v,x)
  12614. # define VdbeCoverageAlwaysTaken(v)
  12615. # define VdbeCoverageNeverTaken(v)
  12616. # define VDBE_OFFSET_LINENO(x) 0
  12617. #endif
  12618. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  12619. SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
  12620. #else
  12621. # define sqlite3VdbeScanStatus(a,b,c,d,e)
  12622. #endif
  12623. #endif /* SQLITE_VDBE_H */
  12624. /************** End of vdbe.h ************************************************/
  12625. /************** Continuing where we left off in sqliteInt.h ******************/
  12626. /************** Include pager.h in the middle of sqliteInt.h *****************/
  12627. /************** Begin file pager.h *******************************************/
  12628. /*
  12629. ** 2001 September 15
  12630. **
  12631. ** The author disclaims copyright to this source code. In place of
  12632. ** a legal notice, here is a blessing:
  12633. **
  12634. ** May you do good and not evil.
  12635. ** May you find forgiveness for yourself and forgive others.
  12636. ** May you share freely, never taking more than you give.
  12637. **
  12638. *************************************************************************
  12639. ** This header file defines the interface that the sqlite page cache
  12640. ** subsystem. The page cache subsystem reads and writes a file a page
  12641. ** at a time and provides a journal for rollback.
  12642. */
  12643. #ifndef SQLITE_PAGER_H
  12644. #define SQLITE_PAGER_H
  12645. /*
  12646. ** Default maximum size for persistent journal files. A negative
  12647. ** value means no limit. This value may be overridden using the
  12648. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  12649. */
  12650. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  12651. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  12652. #endif
  12653. /*
  12654. ** The type used to represent a page number. The first page in a file
  12655. ** is called page 1. 0 is used to represent "not a page".
  12656. */
  12657. typedef u32 Pgno;
  12658. /*
  12659. ** Each open file is managed by a separate instance of the "Pager" structure.
  12660. */
  12661. typedef struct Pager Pager;
  12662. /*
  12663. ** Handle type for pages.
  12664. */
  12665. typedef struct PgHdr DbPage;
  12666. /*
  12667. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  12668. ** reserved for working around a windows/posix incompatibility). It is
  12669. ** used in the journal to signify that the remainder of the journal file
  12670. ** is devoted to storing a master journal name - there are no more pages to
  12671. ** roll back. See comments for function writeMasterJournal() in pager.c
  12672. ** for details.
  12673. */
  12674. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  12675. /*
  12676. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  12677. **
  12678. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  12679. */
  12680. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  12681. #define PAGER_MEMORY 0x0002 /* In-memory database */
  12682. /*
  12683. ** Valid values for the second argument to sqlite3PagerLockingMode().
  12684. */
  12685. #define PAGER_LOCKINGMODE_QUERY -1
  12686. #define PAGER_LOCKINGMODE_NORMAL 0
  12687. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  12688. /*
  12689. ** Numeric constants that encode the journalmode.
  12690. **
  12691. ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
  12692. ** are exposed in the API via the "PRAGMA journal_mode" command and
  12693. ** therefore cannot be changed without a compatibility break.
  12694. */
  12695. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  12696. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  12697. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  12698. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  12699. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  12700. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  12701. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  12702. /*
  12703. ** Flags that make up the mask passed to sqlite3PagerGet().
  12704. */
  12705. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  12706. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  12707. /*
  12708. ** Flags for sqlite3PagerSetFlags()
  12709. **
  12710. ** Value constraints (enforced via assert()):
  12711. ** PAGER_FULLFSYNC == SQLITE_FullFSync
  12712. ** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
  12713. ** PAGER_CACHE_SPILL == SQLITE_CacheSpill
  12714. */
  12715. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  12716. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  12717. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  12718. #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
  12719. #define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */
  12720. #define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */
  12721. #define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */
  12722. #define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */
  12723. #define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */
  12724. /*
  12725. ** The remainder of this file contains the declarations of the functions
  12726. ** that make up the Pager sub-system API. See source code comments for
  12727. ** a detailed description of each routine.
  12728. */
  12729. /* Open and close a Pager connection. */
  12730. SQLITE_PRIVATE int sqlite3PagerOpen(
  12731. sqlite3_vfs*,
  12732. Pager **ppPager,
  12733. const char*,
  12734. int,
  12735. int,
  12736. int,
  12737. void(*)(DbPage*)
  12738. );
  12739. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
  12740. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  12741. /* Functions used to configure a Pager object. */
  12742. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  12743. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  12744. #ifdef SQLITE_HAS_CODEC
  12745. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
  12746. #endif
  12747. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  12748. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  12749. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
  12750. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  12751. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  12752. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  12753. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  12754. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  12755. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  12756. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  12757. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  12758. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  12759. SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
  12760. /* Functions used to obtain and release page references. */
  12761. SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  12762. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  12763. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  12764. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  12765. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
  12766. /* Operations on page references. */
  12767. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  12768. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  12769. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  12770. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  12771. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  12772. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  12773. /* Functions used to manage pager transactions and savepoints. */
  12774. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  12775. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  12776. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  12777. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  12778. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
  12779. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  12780. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  12781. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  12782. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  12783. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  12784. #ifndef SQLITE_OMIT_WAL
  12785. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
  12786. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  12787. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  12788. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  12789. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
  12790. # ifdef SQLITE_DIRECT_OVERFLOW_READ
  12791. SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno);
  12792. # endif
  12793. # ifdef SQLITE_ENABLE_SNAPSHOT
  12794. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
  12795. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
  12796. SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager);
  12797. # endif
  12798. #else
  12799. # define sqlite3PagerUseWal(x,y) 0
  12800. #endif
  12801. #ifdef SQLITE_ENABLE_ZIPVFS
  12802. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  12803. #endif
  12804. /* Functions used to query pager state and configuration. */
  12805. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  12806. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
  12807. #ifdef SQLITE_DEBUG
  12808. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  12809. #endif
  12810. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  12811. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  12812. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
  12813. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  12814. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
  12815. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  12816. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  12817. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  12818. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  12819. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
  12820. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  12821. /* Functions used to truncate the database file. */
  12822. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  12823. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
  12824. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  12825. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  12826. #endif
  12827. /* Functions to support testing and debugging. */
  12828. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  12829. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  12830. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  12831. #endif
  12832. #ifdef SQLITE_TEST
  12833. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  12834. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  12835. void disable_simulated_io_errors(void);
  12836. void enable_simulated_io_errors(void);
  12837. #else
  12838. # define disable_simulated_io_errors()
  12839. # define enable_simulated_io_errors()
  12840. #endif
  12841. #endif /* SQLITE_PAGER_H */
  12842. /************** End of pager.h ***********************************************/
  12843. /************** Continuing where we left off in sqliteInt.h ******************/
  12844. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  12845. /************** Begin file pcache.h ******************************************/
  12846. /*
  12847. ** 2008 August 05
  12848. **
  12849. ** The author disclaims copyright to this source code. In place of
  12850. ** a legal notice, here is a blessing:
  12851. **
  12852. ** May you do good and not evil.
  12853. ** May you find forgiveness for yourself and forgive others.
  12854. ** May you share freely, never taking more than you give.
  12855. **
  12856. *************************************************************************
  12857. ** This header file defines the interface that the sqlite page cache
  12858. ** subsystem.
  12859. */
  12860. #ifndef _PCACHE_H_
  12861. typedef struct PgHdr PgHdr;
  12862. typedef struct PCache PCache;
  12863. /*
  12864. ** Every page in the cache is controlled by an instance of the following
  12865. ** structure.
  12866. */
  12867. struct PgHdr {
  12868. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  12869. void *pData; /* Page data */
  12870. void *pExtra; /* Extra content */
  12871. PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
  12872. Pager *pPager; /* The pager this page is part of */
  12873. Pgno pgno; /* Page number for this page */
  12874. #ifdef SQLITE_CHECK_PAGES
  12875. u32 pageHash; /* Hash of page content */
  12876. #endif
  12877. u16 flags; /* PGHDR flags defined below */
  12878. /**********************************************************************
  12879. ** Elements above are public. All that follows is private to pcache.c
  12880. ** and should not be accessed by other modules.
  12881. */
  12882. i16 nRef; /* Number of users of this page */
  12883. PCache *pCache; /* Cache that owns this page */
  12884. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  12885. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  12886. };
  12887. /* Bit values for PgHdr.flags */
  12888. #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
  12889. #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
  12890. #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
  12891. #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
  12892. ** writing this page to the database */
  12893. #define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
  12894. #define PGHDR_MMAP 0x020 /* This is an mmap page object */
  12895. #define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
  12896. /* Initialize and shutdown the page cache subsystem */
  12897. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  12898. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  12899. /* Page cache buffer management:
  12900. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  12901. */
  12902. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  12903. /* Create a new pager cache.
  12904. ** Under memory stress, invoke xStress to try to make pages clean.
  12905. ** Only clean and unpinned pages can be reclaimed.
  12906. */
  12907. SQLITE_PRIVATE int sqlite3PcacheOpen(
  12908. int szPage, /* Size of every page */
  12909. int szExtra, /* Extra space associated with each page */
  12910. int bPurgeable, /* True if pages are on backing store */
  12911. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  12912. void *pStress, /* Argument to xStress */
  12913. PCache *pToInit /* Preallocated space for the PCache */
  12914. );
  12915. /* Modify the page-size after the cache has been created. */
  12916. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
  12917. /* Return the size in bytes of a PCache object. Used to preallocate
  12918. ** storage space.
  12919. */
  12920. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  12921. /* One release per successful fetch. Page is pinned until released.
  12922. ** Reference counted.
  12923. */
  12924. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
  12925. SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
  12926. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
  12927. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  12928. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  12929. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  12930. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  12931. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  12932. SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
  12933. /* Change a page number. Used by incr-vacuum. */
  12934. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  12935. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  12936. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  12937. /* Get a list of all dirty pages in the cache, sorted by page number */
  12938. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  12939. /* Reset and close the cache object */
  12940. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  12941. /* Clear flags from pages of the page cache */
  12942. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  12943. /* Discard the contents of the cache */
  12944. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  12945. /* Return the total number of outstanding page references */
  12946. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  12947. /* Increment the reference count of an existing page */
  12948. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  12949. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  12950. /* Return the total number of pages stored in the cache */
  12951. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  12952. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  12953. /* Iterate through all dirty pages currently stored in the cache. This
  12954. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  12955. ** library is built.
  12956. */
  12957. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  12958. #endif
  12959. #if defined(SQLITE_DEBUG)
  12960. /* Check invariants on a PgHdr object */
  12961. SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
  12962. #endif
  12963. /* Set and get the suggested cache-size for the specified pager-cache.
  12964. **
  12965. ** If no global maximum is configured, then the system attempts to limit
  12966. ** the total number of pages cached by purgeable pager-caches to the sum
  12967. ** of the suggested cache-sizes.
  12968. */
  12969. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  12970. #ifdef SQLITE_TEST
  12971. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  12972. #endif
  12973. /* Set or get the suggested spill-size for the specified pager-cache.
  12974. **
  12975. ** The spill-size is the minimum number of pages in cache before the cache
  12976. ** will attempt to spill dirty pages by calling xStress.
  12977. */
  12978. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
  12979. /* Free up as much memory as possible from the page cache */
  12980. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  12981. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  12982. /* Try to return memory used by the pcache module to the main memory heap */
  12983. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  12984. #endif
  12985. #ifdef SQLITE_TEST
  12986. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  12987. #endif
  12988. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  12989. /* Return the header size */
  12990. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
  12991. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
  12992. /* Number of dirty pages as a percentage of the configured cache size */
  12993. SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
  12994. #endif /* _PCACHE_H_ */
  12995. /************** End of pcache.h **********************************************/
  12996. /************** Continuing where we left off in sqliteInt.h ******************/
  12997. /************** Include os.h in the middle of sqliteInt.h ********************/
  12998. /************** Begin file os.h **********************************************/
  12999. /*
  13000. ** 2001 September 16
  13001. **
  13002. ** The author disclaims copyright to this source code. In place of
  13003. ** a legal notice, here is a blessing:
  13004. **
  13005. ** May you do good and not evil.
  13006. ** May you find forgiveness for yourself and forgive others.
  13007. ** May you share freely, never taking more than you give.
  13008. **
  13009. ******************************************************************************
  13010. **
  13011. ** This header file (together with is companion C source-code file
  13012. ** "os.c") attempt to abstract the underlying operating system so that
  13013. ** the SQLite library will work on both POSIX and windows systems.
  13014. **
  13015. ** This header file is #include-ed by sqliteInt.h and thus ends up
  13016. ** being included by every source file.
  13017. */
  13018. #ifndef _SQLITE_OS_H_
  13019. #define _SQLITE_OS_H_
  13020. /*
  13021. ** Attempt to automatically detect the operating system and setup the
  13022. ** necessary pre-processor macros for it.
  13023. */
  13024. /************** Include os_setup.h in the middle of os.h *********************/
  13025. /************** Begin file os_setup.h ****************************************/
  13026. /*
  13027. ** 2013 November 25
  13028. **
  13029. ** The author disclaims copyright to this source code. In place of
  13030. ** a legal notice, here is a blessing:
  13031. **
  13032. ** May you do good and not evil.
  13033. ** May you find forgiveness for yourself and forgive others.
  13034. ** May you share freely, never taking more than you give.
  13035. **
  13036. ******************************************************************************
  13037. **
  13038. ** This file contains pre-processor directives related to operating system
  13039. ** detection and/or setup.
  13040. */
  13041. #ifndef SQLITE_OS_SETUP_H
  13042. #define SQLITE_OS_SETUP_H
  13043. /*
  13044. ** Figure out if we are dealing with Unix, Windows, or some other operating
  13045. ** system.
  13046. **
  13047. ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
  13048. ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
  13049. ** the three will be 1. The other two will be 0.
  13050. */
  13051. #if defined(SQLITE_OS_OTHER)
  13052. # if SQLITE_OS_OTHER==1
  13053. # undef SQLITE_OS_UNIX
  13054. # define SQLITE_OS_UNIX 0
  13055. # undef SQLITE_OS_WIN
  13056. # define SQLITE_OS_WIN 0
  13057. # define SQLITE_OS_RTTHREAD 1
  13058. # else
  13059. # undef SQLITE_OS_OTHER
  13060. # endif
  13061. #endif
  13062. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  13063. # define SQLITE_OS_OTHER 0
  13064. # ifndef SQLITE_OS_WIN
  13065. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
  13066. defined(__MINGW32__) || defined(__BORLANDC__)
  13067. # define SQLITE_OS_WIN 1
  13068. # define SQLITE_OS_UNIX 0
  13069. # else
  13070. # define SQLITE_OS_WIN 0
  13071. # define SQLITE_OS_UNIX 1
  13072. # endif
  13073. # else
  13074. # define SQLITE_OS_UNIX 0
  13075. # endif
  13076. #else
  13077. # ifndef SQLITE_OS_WIN
  13078. # define SQLITE_OS_WIN 0
  13079. # endif
  13080. #endif
  13081. #endif /* SQLITE_OS_SETUP_H */
  13082. /************** End of os_setup.h ********************************************/
  13083. /************** Continuing where we left off in os.h *************************/
  13084. /* If the SET_FULLSYNC macro is not defined above, then make it
  13085. ** a no-op
  13086. */
  13087. #ifndef SET_FULLSYNC
  13088. # define SET_FULLSYNC(x,y)
  13089. #endif
  13090. /*
  13091. ** The default size of a disk sector
  13092. */
  13093. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  13094. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  13095. #endif
  13096. /*
  13097. ** Temporary files are named starting with this prefix followed by 16 random
  13098. ** alphanumeric characters, and no file extension. They are stored in the
  13099. ** OS's standard temporary file directory, and are deleted prior to exit.
  13100. ** If sqlite is being embedded in another program, you may wish to change the
  13101. ** prefix to reflect your program's name, so that if your program exits
  13102. ** prematurely, old temporary files can be easily identified. This can be done
  13103. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  13104. **
  13105. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  13106. ** Mcafee started using SQLite in their anti-virus product and it
  13107. ** started putting files with the "sqlite" name in the c:/temp folder.
  13108. ** This annoyed many windows users. Those users would then do a
  13109. ** Google search for "sqlite", find the telephone numbers of the
  13110. ** developers and call to wake them up at night and complain.
  13111. ** For this reason, the default name prefix is changed to be "sqlite"
  13112. ** spelled backwards. So the temp files are still identified, but
  13113. ** anybody smart enough to figure out the code is also likely smart
  13114. ** enough to know that calling the developer will not help get rid
  13115. ** of the file.
  13116. */
  13117. #ifndef SQLITE_TEMP_FILE_PREFIX
  13118. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  13119. #endif
  13120. /*
  13121. ** The following values may be passed as the second argument to
  13122. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  13123. **
  13124. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  13125. ** RESERVED: A single process may hold a RESERVED lock on a file at
  13126. ** any time. Other processes may hold and obtain new SHARED locks.
  13127. ** PENDING: A single process may hold a PENDING lock on a file at
  13128. ** any one time. Existing SHARED locks may persist, but no new
  13129. ** SHARED locks may be obtained by other processes.
  13130. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  13131. **
  13132. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  13133. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  13134. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  13135. ** sqlite3OsLock().
  13136. */
  13137. #define NO_LOCK 0
  13138. #define SHARED_LOCK 1
  13139. #define RESERVED_LOCK 2
  13140. #define PENDING_LOCK 3
  13141. #define EXCLUSIVE_LOCK 4
  13142. /*
  13143. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  13144. **
  13145. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  13146. ** those functions are not available. So we use only LockFile() and
  13147. ** UnlockFile().
  13148. **
  13149. ** LockFile() prevents not just writing but also reading by other processes.
  13150. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  13151. ** byte out of a specific range of bytes. The lock byte is obtained at
  13152. ** random so two separate readers can probably access the file at the
  13153. ** same time, unless they are unlucky and choose the same lock byte.
  13154. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  13155. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  13156. ** a single byte of the file that is designated as the reserved lock byte.
  13157. ** A PENDING_LOCK is obtained by locking a designated byte different from
  13158. ** the RESERVED_LOCK byte.
  13159. **
  13160. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  13161. ** which means we can use reader/writer locks. When reader/writer locks
  13162. ** are used, the lock is placed on the same range of bytes that is used
  13163. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  13164. ** will support two or more Win95 readers or two or more WinNT readers.
  13165. ** But a single Win95 reader will lock out all WinNT readers and a single
  13166. ** WinNT reader will lock out all other Win95 readers.
  13167. **
  13168. ** The following #defines specify the range of bytes used for locking.
  13169. ** SHARED_SIZE is the number of bytes available in the pool from which
  13170. ** a random byte is selected for a shared lock. The pool of bytes for
  13171. ** shared locks begins at SHARED_FIRST.
  13172. **
  13173. ** The same locking strategy and
  13174. ** byte ranges are used for Unix. This leaves open the possibility of having
  13175. ** clients on win95, winNT, and unix all talking to the same shared file
  13176. ** and all locking correctly. To do so would require that samba (or whatever
  13177. ** tool is being used for file sharing) implements locks correctly between
  13178. ** windows and unix. I'm guessing that isn't likely to happen, but by
  13179. ** using the same locking range we are at least open to the possibility.
  13180. **
  13181. ** Locking in windows is manditory. For this reason, we cannot store
  13182. ** actual data in the bytes used for locking. The pager never allocates
  13183. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  13184. ** that all locks will fit on a single page even at the minimum page size.
  13185. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  13186. ** is set high so that we don't have to allocate an unused page except
  13187. ** for very large databases. But one should test the page skipping logic
  13188. ** by setting PENDING_BYTE low and running the entire regression suite.
  13189. **
  13190. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  13191. ** file format. Depending on how it is changed, you might not notice
  13192. ** the incompatibility right away, even running a full regression test.
  13193. ** The default location of PENDING_BYTE is the first byte past the
  13194. ** 1GB boundary.
  13195. **
  13196. */
  13197. #ifdef SQLITE_OMIT_WSD
  13198. # define PENDING_BYTE (0x40000000)
  13199. #else
  13200. # define PENDING_BYTE sqlite3PendingByte
  13201. #endif
  13202. #define RESERVED_BYTE (PENDING_BYTE+1)
  13203. #define SHARED_FIRST (PENDING_BYTE+2)
  13204. #define SHARED_SIZE 510
  13205. /*
  13206. ** Wrapper around OS specific sqlite3_os_init() function.
  13207. */
  13208. SQLITE_PRIVATE int sqlite3OsInit(void);
  13209. /*
  13210. ** Functions for accessing sqlite3_file methods
  13211. */
  13212. SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
  13213. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  13214. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  13215. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  13216. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  13217. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  13218. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  13219. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  13220. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  13221. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  13222. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  13223. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  13224. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  13225. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  13226. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  13227. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  13228. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  13229. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  13230. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  13231. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  13232. /*
  13233. ** Functions for accessing sqlite3_vfs methods
  13234. */
  13235. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  13236. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  13237. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  13238. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  13239. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  13240. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  13241. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  13242. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  13243. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  13244. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  13245. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  13246. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  13247. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
  13248. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  13249. /*
  13250. ** Convenience functions for opening and closing files using
  13251. ** sqlite3_malloc() to obtain space for the file-handle structure.
  13252. */
  13253. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  13254. SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
  13255. #endif /* _SQLITE_OS_H_ */
  13256. /************** End of os.h **************************************************/
  13257. /************** Continuing where we left off in sqliteInt.h ******************/
  13258. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  13259. /************** Begin file mutex.h *******************************************/
  13260. /*
  13261. ** 2007 August 28
  13262. **
  13263. ** The author disclaims copyright to this source code. In place of
  13264. ** a legal notice, here is a blessing:
  13265. **
  13266. ** May you do good and not evil.
  13267. ** May you find forgiveness for yourself and forgive others.
  13268. ** May you share freely, never taking more than you give.
  13269. **
  13270. *************************************************************************
  13271. **
  13272. ** This file contains the common header for all mutex implementations.
  13273. ** The sqliteInt.h header #includes this file so that it is available
  13274. ** to all source files. We break it out in an effort to keep the code
  13275. ** better organized.
  13276. **
  13277. ** NOTE: source files should *not* #include this header file directly.
  13278. ** Source files should #include the sqliteInt.h file and let that file
  13279. ** include this one indirectly.
  13280. */
  13281. /*
  13282. ** Figure out what version of the code to use. The choices are
  13283. **
  13284. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  13285. ** mutexes implementation cannot be overridden
  13286. ** at start-time.
  13287. **
  13288. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  13289. ** mutual exclusion is provided. But this
  13290. ** implementation can be overridden at
  13291. ** start-time.
  13292. **
  13293. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  13294. **
  13295. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  13296. */
  13297. #if !SQLITE_THREADSAFE
  13298. # define SQLITE_MUTEX_OMIT
  13299. #endif
  13300. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  13301. # if SQLITE_OS_UNIX
  13302. # define SQLITE_MUTEX_PTHREADS
  13303. # elif SQLITE_OS_WIN
  13304. # define SQLITE_MUTEX_W32
  13305. # elif SQLITE_OS_RTTHREAD
  13306. # define SQLITE_MUTEX_RTTHREAD
  13307. # else
  13308. # define SQLITE_MUTEX_NOOP
  13309. # endif
  13310. #endif
  13311. #ifdef SQLITE_MUTEX_OMIT
  13312. /*
  13313. ** If this is a no-op implementation, implement everything as macros.
  13314. */
  13315. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  13316. #define sqlite3_mutex_free(X)
  13317. #define sqlite3_mutex_enter(X)
  13318. #define sqlite3_mutex_try(X) SQLITE_OK
  13319. #define sqlite3_mutex_leave(X)
  13320. #define sqlite3_mutex_held(X) ((void)(X),1)
  13321. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  13322. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  13323. #define sqlite3MutexInit() SQLITE_OK
  13324. #define sqlite3MutexEnd()
  13325. #define MUTEX_LOGIC(X)
  13326. #else
  13327. #define MUTEX_LOGIC(X) X
  13328. #endif /* defined(SQLITE_MUTEX_OMIT) */
  13329. /************** End of mutex.h ***********************************************/
  13330. /************** Continuing where we left off in sqliteInt.h ******************/
  13331. /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
  13332. ** synchronous setting to EXTRA. It is no longer supported.
  13333. */
  13334. #ifdef SQLITE_EXTRA_DURABLE
  13335. # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
  13336. # define SQLITE_DEFAULT_SYNCHRONOUS 3
  13337. #endif
  13338. /*
  13339. ** Default synchronous levels.
  13340. **
  13341. ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
  13342. ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
  13343. **
  13344. ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
  13345. ** OFF 1 0
  13346. ** NORMAL 2 1
  13347. ** FULL 3 2
  13348. ** EXTRA 4 3
  13349. **
  13350. ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
  13351. ** In other words, the zero-based numbers are used for all external interfaces
  13352. ** and the one-based values are used internally.
  13353. */
  13354. #ifndef SQLITE_DEFAULT_SYNCHRONOUS
  13355. # define SQLITE_DEFAULT_SYNCHRONOUS 2
  13356. #endif
  13357. #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
  13358. # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
  13359. #endif
  13360. /*
  13361. ** Each database file to be accessed by the system is an instance
  13362. ** of the following structure. There are normally two of these structures
  13363. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  13364. ** aDb[1] is the database file used to hold temporary tables. Additional
  13365. ** databases may be attached.
  13366. */
  13367. struct Db {
  13368. char *zDbSName; /* Name of this database. (schema name, not filename) */
  13369. Btree *pBt; /* The B*Tree structure for this database file */
  13370. u8 safety_level; /* How aggressive at syncing data to disk */
  13371. u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
  13372. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  13373. };
  13374. /*
  13375. ** An instance of the following structure stores a database schema.
  13376. **
  13377. ** Most Schema objects are associated with a Btree. The exception is
  13378. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  13379. ** In shared cache mode, a single Schema object can be shared by multiple
  13380. ** Btrees that refer to the same underlying BtShared object.
  13381. **
  13382. ** Schema objects are automatically deallocated when the last Btree that
  13383. ** references them is destroyed. The TEMP Schema is manually freed by
  13384. ** sqlite3_close().
  13385. *
  13386. ** A thread must be holding a mutex on the corresponding Btree in order
  13387. ** to access Schema content. This implies that the thread must also be
  13388. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  13389. ** For a TEMP Schema, only the connection mutex is required.
  13390. */
  13391. struct Schema {
  13392. int schema_cookie; /* Database schema version number for this file */
  13393. int iGeneration; /* Generation counter. Incremented with each change */
  13394. Hash tblHash; /* All tables indexed by name */
  13395. Hash idxHash; /* All (named) indices indexed by name */
  13396. Hash trigHash; /* All triggers indexed by name */
  13397. Hash fkeyHash; /* All foreign keys by referenced table name */
  13398. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  13399. u8 file_format; /* Schema format version for this file */
  13400. u8 enc; /* Text encoding used by this database */
  13401. u16 schemaFlags; /* Flags associated with this schema */
  13402. int cache_size; /* Number of pages to use in the cache */
  13403. };
  13404. /*
  13405. ** These macros can be used to test, set, or clear bits in the
  13406. ** Db.pSchema->flags field.
  13407. */
  13408. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
  13409. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
  13410. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
  13411. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
  13412. /*
  13413. ** Allowed values for the DB.pSchema->flags field.
  13414. **
  13415. ** The DB_SchemaLoaded flag is set after the database schema has been
  13416. ** read into internal hash tables.
  13417. **
  13418. ** DB_UnresetViews means that one or more views have column names that
  13419. ** have been filled out. If the schema changes, these column names might
  13420. ** changes and so the view will need to be reset.
  13421. */
  13422. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  13423. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  13424. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  13425. /*
  13426. ** The number of different kinds of things that can be limited
  13427. ** using the sqlite3_limit() interface.
  13428. */
  13429. #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
  13430. /*
  13431. ** Lookaside malloc is a set of fixed-size buffers that can be used
  13432. ** to satisfy small transient memory allocation requests for objects
  13433. ** associated with a particular database connection. The use of
  13434. ** lookaside malloc provides a significant performance enhancement
  13435. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  13436. ** SQL statements.
  13437. **
  13438. ** The Lookaside structure holds configuration information about the
  13439. ** lookaside malloc subsystem. Each available memory allocation in
  13440. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  13441. ** objects.
  13442. **
  13443. ** Lookaside allocations are only allowed for objects that are associated
  13444. ** with a particular database connection. Hence, schema information cannot
  13445. ** be stored in lookaside because in shared cache mode the schema information
  13446. ** is shared by multiple database connections. Therefore, while parsing
  13447. ** schema information, the Lookaside.bEnabled flag is cleared so that
  13448. ** lookaside allocations are not used to construct the schema objects.
  13449. */
  13450. struct Lookaside {
  13451. u32 bDisable; /* Only operate the lookaside when zero */
  13452. u16 sz; /* Size of each buffer in bytes */
  13453. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  13454. int nOut; /* Number of buffers currently checked out */
  13455. int mxOut; /* Highwater mark for nOut */
  13456. int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  13457. LookasideSlot *pFree; /* List of available buffers */
  13458. void *pStart; /* First byte of available memory space */
  13459. void *pEnd; /* First byte past end of available space */
  13460. };
  13461. struct LookasideSlot {
  13462. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  13463. };
  13464. /*
  13465. ** A hash table for built-in function definitions. (Application-defined
  13466. ** functions use a regular table table from hash.h.)
  13467. **
  13468. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  13469. ** Collisions are on the FuncDef.u.pHash chain.
  13470. */
  13471. #define SQLITE_FUNC_HASH_SZ 23
  13472. struct FuncDefHash {
  13473. FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
  13474. };
  13475. #ifdef SQLITE_USER_AUTHENTICATION
  13476. /*
  13477. ** Information held in the "sqlite3" database connection object and used
  13478. ** to manage user authentication.
  13479. */
  13480. typedef struct sqlite3_userauth sqlite3_userauth;
  13481. struct sqlite3_userauth {
  13482. u8 authLevel; /* Current authentication level */
  13483. int nAuthPW; /* Size of the zAuthPW in bytes */
  13484. char *zAuthPW; /* Password used to authenticate */
  13485. char *zAuthUser; /* User name used to authenticate */
  13486. };
  13487. /* Allowed values for sqlite3_userauth.authLevel */
  13488. #define UAUTH_Unknown 0 /* Authentication not yet checked */
  13489. #define UAUTH_Fail 1 /* User authentication failed */
  13490. #define UAUTH_User 2 /* Authenticated as a normal user */
  13491. #define UAUTH_Admin 3 /* Authenticated as an administrator */
  13492. /* Functions used only by user authorization logic */
  13493. SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
  13494. SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
  13495. SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
  13496. SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
  13497. #endif /* SQLITE_USER_AUTHENTICATION */
  13498. /*
  13499. ** typedef for the authorization callback function.
  13500. */
  13501. #ifdef SQLITE_USER_AUTHENTICATION
  13502. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  13503. const char*, const char*);
  13504. #else
  13505. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  13506. const char*);
  13507. #endif
  13508. #ifndef SQLITE_OMIT_DEPRECATED
  13509. /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
  13510. ** in the style of sqlite3_trace()
  13511. */
  13512. #define SQLITE_TRACE_LEGACY 0x80
  13513. #else
  13514. #define SQLITE_TRACE_LEGACY 0
  13515. #endif /* SQLITE_OMIT_DEPRECATED */
  13516. /*
  13517. ** Each database connection is an instance of the following structure.
  13518. */
  13519. struct sqlite3 {
  13520. sqlite3_vfs *pVfs; /* OS Interface */
  13521. struct Vdbe *pVdbe; /* List of active virtual machines */
  13522. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  13523. sqlite3_mutex *mutex; /* Connection mutex */
  13524. Db *aDb; /* All backends */
  13525. int nDb; /* Number of backends currently in use */
  13526. int flags; /* Miscellaneous flags. See below */
  13527. i64 lastRowid; /* ROWID of most recent insert (see above) */
  13528. i64 szMmap; /* Default mmap_size setting */
  13529. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  13530. int errCode; /* Most recent error code (SQLITE_*) */
  13531. int errMask; /* & result codes with this before returning */
  13532. int iSysErrno; /* Errno value from last system error */
  13533. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  13534. u8 enc; /* Text encoding */
  13535. u8 autoCommit; /* The auto-commit flag. */
  13536. u8 temp_store; /* 1: file 2: memory 0: default */
  13537. u8 mallocFailed; /* True if we have seen a malloc failure */
  13538. u8 bBenignMalloc; /* Do not require OOMs if true */
  13539. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  13540. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  13541. u8 suppressErr; /* Do not issue error messages if true */
  13542. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  13543. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  13544. u8 mTrace; /* zero or more SQLITE_TRACE flags */
  13545. u8 skipBtreeMutex; /* True if no shared-cache backends */
  13546. u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */
  13547. int nextPagesize; /* Pagesize after VACUUM if >0 */
  13548. u32 magic; /* Magic number for detect library misuse */
  13549. int nChange; /* Value returned by sqlite3_changes() */
  13550. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  13551. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  13552. int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
  13553. struct sqlite3InitInfo { /* Information used during initialization */
  13554. int newTnum; /* Rootpage of table being initialized */
  13555. u8 iDb; /* Which db file is being initialized */
  13556. u8 busy; /* TRUE if currently initializing */
  13557. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  13558. u8 imposterTable; /* Building an imposter table */
  13559. } init;
  13560. int nVdbeActive; /* Number of VDBEs currently running */
  13561. int nVdbeRead; /* Number of active VDBEs that read or write */
  13562. int nVdbeWrite; /* Number of active VDBEs that read and write */
  13563. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  13564. int nVDestroy; /* Number of active OP_VDestroy operations */
  13565. int nExtension; /* Number of loaded extensions */
  13566. void **aExtension; /* Array of shared library handles */
  13567. int (*xTrace)(u32,void*,void*,void*); /* Trace function */
  13568. void *pTraceArg; /* Argument to the trace function */
  13569. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  13570. void *pProfileArg; /* Argument to profile function */
  13571. void *pCommitArg; /* Argument to xCommitCallback() */
  13572. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  13573. void *pRollbackArg; /* Argument to xRollbackCallback() */
  13574. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  13575. void *pUpdateArg;
  13576. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  13577. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  13578. void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
  13579. void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
  13580. void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
  13581. );
  13582. PreUpdate *pPreUpdate; /* Context for active pre-update callback */
  13583. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  13584. #ifndef SQLITE_OMIT_WAL
  13585. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  13586. void *pWalArg;
  13587. #endif
  13588. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  13589. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  13590. void *pCollNeededArg;
  13591. sqlite3_value *pErr; /* Most recent error message */
  13592. union {
  13593. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  13594. double notUsed1; /* Spacer */
  13595. } u1;
  13596. Lookaside lookaside; /* Lookaside malloc configuration */
  13597. #ifndef SQLITE_OMIT_AUTHORIZATION
  13598. sqlite3_xauth xAuth; /* Access authorization function */
  13599. void *pAuthArg; /* 1st argument to the access auth function */
  13600. #endif
  13601. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  13602. int (*xProgress)(void *); /* The progress callback */
  13603. void *pProgressArg; /* Argument to the progress callback */
  13604. unsigned nProgressOps; /* Number of opcodes for progress callback */
  13605. #endif
  13606. #ifndef SQLITE_OMIT_VIRTUALTABLE
  13607. int nVTrans; /* Allocated size of aVTrans */
  13608. Hash aModule; /* populated by sqlite3_create_module() */
  13609. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  13610. VTable **aVTrans; /* Virtual tables with open transactions */
  13611. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  13612. #endif
  13613. Hash aFunc; /* Hash table of connection functions */
  13614. Hash aCollSeq; /* All collating sequences */
  13615. BusyHandler busyHandler; /* Busy callback */
  13616. Db aDbStatic[2]; /* Static space for the 2 default backends */
  13617. Savepoint *pSavepoint; /* List of active savepoints */
  13618. int busyTimeout; /* Busy handler timeout, in msec */
  13619. int nSavepoint; /* Number of non-transaction savepoints */
  13620. int nStatement; /* Number of nested statement-transactions */
  13621. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  13622. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  13623. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  13624. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  13625. /* The following variables are all protected by the STATIC_MASTER
  13626. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  13627. **
  13628. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  13629. ** unlock so that it can proceed.
  13630. **
  13631. ** When X.pBlockingConnection==Y, that means that something that X tried
  13632. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  13633. ** held by Y.
  13634. */
  13635. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  13636. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  13637. void *pUnlockArg; /* Argument to xUnlockNotify */
  13638. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  13639. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  13640. #endif
  13641. #ifdef SQLITE_USER_AUTHENTICATION
  13642. sqlite3_userauth auth; /* User authentication information */
  13643. #endif
  13644. };
  13645. /*
  13646. ** A macro to discover the encoding of a database.
  13647. */
  13648. #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
  13649. #define ENC(db) ((db)->enc)
  13650. /*
  13651. ** Possible values for the sqlite3.flags.
  13652. **
  13653. ** Value constraints (enforced via assert()):
  13654. ** SQLITE_FullFSync == PAGER_FULLFSYNC
  13655. ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
  13656. ** SQLITE_CacheSpill == PAGER_CACHE_SPILL
  13657. */
  13658. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  13659. #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
  13660. #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
  13661. #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
  13662. #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
  13663. #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
  13664. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  13665. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  13666. /* DELETE, or UPDATE and return */
  13667. /* the count using a callback. */
  13668. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  13669. /* result set is empty */
  13670. #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
  13671. #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
  13672. #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
  13673. #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
  13674. #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
  13675. #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
  13676. #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
  13677. #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
  13678. #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
  13679. #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
  13680. #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
  13681. #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
  13682. #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
  13683. #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
  13684. #define SQLITE_LoadExtFunc 0x00800000 /* Enable load_extension() SQL func */
  13685. #define SQLITE_EnableTrigger 0x01000000 /* True to enable triggers */
  13686. #define SQLITE_DeferFKs 0x02000000 /* Defer all FK constraints */
  13687. #define SQLITE_QueryOnly 0x04000000 /* Disable database changes */
  13688. #define SQLITE_VdbeEQP 0x08000000 /* Debug EXPLAIN QUERY PLAN */
  13689. #define SQLITE_Vacuum 0x10000000 /* Currently in a VACUUM */
  13690. #define SQLITE_CellSizeCk 0x20000000 /* Check btree cell sizes on load */
  13691. #define SQLITE_Fts3Tokenizer 0x40000000 /* Enable fts3_tokenizer(2) */
  13692. #define SQLITE_NoCkptOnClose 0x80000000 /* No checkpoint on close()/DETACH */
  13693. /*
  13694. ** Bits of the sqlite3.dbOptFlags field that are used by the
  13695. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  13696. ** selectively disable various optimizations.
  13697. */
  13698. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  13699. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  13700. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  13701. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  13702. /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */
  13703. #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
  13704. #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
  13705. #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
  13706. #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
  13707. #define SQLITE_Transitive 0x0200 /* Transitive constraints */
  13708. #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
  13709. #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
  13710. #define SQLITE_CursorHints 0x2000 /* Add OP_CursorHint opcodes */
  13711. #define SQLITE_AllOpts 0xffff /* All optimizations */
  13712. /*
  13713. ** Macros for testing whether or not optimizations are enabled or disabled.
  13714. */
  13715. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  13716. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  13717. /*
  13718. ** Return true if it OK to factor constant expressions into the initialization
  13719. ** code. The argument is a Parse object for the code generator.
  13720. */
  13721. #define ConstFactorOk(P) ((P)->okConstFactor)
  13722. /*
  13723. ** Possible values for the sqlite.magic field.
  13724. ** The numbers are obtained at random and have no special meaning, other
  13725. ** than being distinct from one another.
  13726. */
  13727. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  13728. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  13729. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  13730. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  13731. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  13732. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  13733. /*
  13734. ** Each SQL function is defined by an instance of the following
  13735. ** structure. For global built-in functions (ex: substr(), max(), count())
  13736. ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
  13737. ** For per-connection application-defined functions, a pointer to this
  13738. ** structure is held in the db->aHash hash table.
  13739. **
  13740. ** The u.pHash field is used by the global built-ins. The u.pDestructor
  13741. ** field is used by per-connection app-def functions.
  13742. */
  13743. struct FuncDef {
  13744. i8 nArg; /* Number of arguments. -1 means unlimited */
  13745. u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
  13746. void *pUserData; /* User data parameter */
  13747. FuncDef *pNext; /* Next function with same name */
  13748. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
  13749. void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
  13750. const char *zName; /* SQL name of the function. */
  13751. union {
  13752. FuncDef *pHash; /* Next with a different name but the same hash */
  13753. FuncDestructor *pDestructor; /* Reference counted destructor function */
  13754. } u;
  13755. };
  13756. /*
  13757. ** This structure encapsulates a user-function destructor callback (as
  13758. ** configured using create_function_v2()) and a reference counter. When
  13759. ** create_function_v2() is called to create a function with a destructor,
  13760. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  13761. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  13762. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  13763. ** member of each of the new FuncDef objects is set to point to the allocated
  13764. ** FuncDestructor.
  13765. **
  13766. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  13767. ** count on this object is decremented. When it reaches 0, the destructor
  13768. ** is invoked and the FuncDestructor structure freed.
  13769. */
  13770. struct FuncDestructor {
  13771. int nRef;
  13772. void (*xDestroy)(void *);
  13773. void *pUserData;
  13774. };
  13775. /*
  13776. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  13777. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
  13778. ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
  13779. ** are assert() statements in the code to verify this.
  13780. **
  13781. ** Value constraints (enforced via assert()):
  13782. ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
  13783. ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
  13784. ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
  13785. ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
  13786. ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
  13787. */
  13788. #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  13789. #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
  13790. #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
  13791. #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
  13792. #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
  13793. #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
  13794. #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
  13795. #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
  13796. #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
  13797. #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
  13798. #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
  13799. #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
  13800. #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
  13801. ** single query - might change over time */
  13802. #define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */
  13803. /*
  13804. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  13805. ** used to create the initializers for the FuncDef structures.
  13806. **
  13807. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  13808. ** Used to create a scalar function definition of a function zName
  13809. ** implemented by C function xFunc that accepts nArg arguments. The
  13810. ** value passed as iArg is cast to a (void*) and made available
  13811. ** as the user-data (sqlite3_user_data()) for the function. If
  13812. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  13813. **
  13814. ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
  13815. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
  13816. **
  13817. ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
  13818. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
  13819. ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
  13820. ** and functions like sqlite_version() that can change, but not during
  13821. ** a single query.
  13822. **
  13823. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  13824. ** Used to create an aggregate function definition implemented by
  13825. ** the C functions xStep and xFinal. The first four parameters
  13826. ** are interpreted in the same way as the first 4 parameters to
  13827. ** FUNCTION().
  13828. **
  13829. ** LIKEFUNC(zName, nArg, pArg, flags)
  13830. ** Used to create a scalar function definition of a function zName
  13831. ** that accepts nArg arguments and is implemented by a call to C
  13832. ** function likeFunc. Argument pArg is cast to a (void *) and made
  13833. ** available as the function user-data (sqlite3_user_data()). The
  13834. ** FuncDef.flags variable is set to the value passed as the flags
  13835. ** parameter.
  13836. */
  13837. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  13838. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  13839. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  13840. #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  13841. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  13842. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  13843. #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  13844. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  13845. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  13846. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  13847. {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
  13848. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  13849. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  13850. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  13851. pArg, 0, xFunc, 0, #zName, }
  13852. #define LIKEFUNC(zName, nArg, arg, flags) \
  13853. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
  13854. (void *)arg, 0, likeFunc, 0, #zName, {0} }
  13855. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  13856. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  13857. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
  13858. #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
  13859. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  13860. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
  13861. /*
  13862. ** All current savepoints are stored in a linked list starting at
  13863. ** sqlite3.pSavepoint. The first element in the list is the most recently
  13864. ** opened savepoint. Savepoints are added to the list by the vdbe
  13865. ** OP_Savepoint instruction.
  13866. */
  13867. struct Savepoint {
  13868. char *zName; /* Savepoint name (nul-terminated) */
  13869. i64 nDeferredCons; /* Number of deferred fk violations */
  13870. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  13871. Savepoint *pNext; /* Parent savepoint (if any) */
  13872. };
  13873. /*
  13874. ** The following are used as the second parameter to sqlite3Savepoint(),
  13875. ** and as the P1 argument to the OP_Savepoint instruction.
  13876. */
  13877. #define SAVEPOINT_BEGIN 0
  13878. #define SAVEPOINT_RELEASE 1
  13879. #define SAVEPOINT_ROLLBACK 2
  13880. /*
  13881. ** Each SQLite module (virtual table definition) is defined by an
  13882. ** instance of the following structure, stored in the sqlite3.aModule
  13883. ** hash table.
  13884. */
  13885. struct Module {
  13886. const sqlite3_module *pModule; /* Callback pointers */
  13887. const char *zName; /* Name passed to create_module() */
  13888. void *pAux; /* pAux passed to create_module() */
  13889. void (*xDestroy)(void *); /* Module destructor function */
  13890. Table *pEpoTab; /* Eponymous table for this module */
  13891. };
  13892. /*
  13893. ** information about each column of an SQL table is held in an instance
  13894. ** of this structure.
  13895. */
  13896. struct Column {
  13897. char *zName; /* Name of this column, \000, then the type */
  13898. Expr *pDflt; /* Default value of this column */
  13899. char *zColl; /* Collating sequence. If NULL, use the default */
  13900. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  13901. char affinity; /* One of the SQLITE_AFF_... values */
  13902. u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
  13903. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  13904. };
  13905. /* Allowed values for Column.colFlags:
  13906. */
  13907. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  13908. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  13909. #define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
  13910. /*
  13911. ** A "Collating Sequence" is defined by an instance of the following
  13912. ** structure. Conceptually, a collating sequence consists of a name and
  13913. ** a comparison routine that defines the order of that sequence.
  13914. **
  13915. ** If CollSeq.xCmp is NULL, it means that the
  13916. ** collating sequence is undefined. Indices built on an undefined
  13917. ** collating sequence may not be read or written.
  13918. */
  13919. struct CollSeq {
  13920. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  13921. u8 enc; /* Text encoding handled by xCmp() */
  13922. void *pUser; /* First argument to xCmp() */
  13923. int (*xCmp)(void*,int, const void*, int, const void*);
  13924. void (*xDel)(void*); /* Destructor for pUser */
  13925. };
  13926. /*
  13927. ** A sort order can be either ASC or DESC.
  13928. */
  13929. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  13930. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  13931. #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
  13932. /*
  13933. ** Column affinity types.
  13934. **
  13935. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  13936. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  13937. ** the speed a little by numbering the values consecutively.
  13938. **
  13939. ** But rather than start with 0 or 1, we begin with 'A'. That way,
  13940. ** when multiple affinity types are concatenated into a string and
  13941. ** used as the P4 operand, they will be more readable.
  13942. **
  13943. ** Note also that the numeric types are grouped together so that testing
  13944. ** for a numeric type is a single comparison. And the BLOB type is first.
  13945. */
  13946. #define SQLITE_AFF_BLOB 'A'
  13947. #define SQLITE_AFF_TEXT 'B'
  13948. #define SQLITE_AFF_NUMERIC 'C'
  13949. #define SQLITE_AFF_INTEGER 'D'
  13950. #define SQLITE_AFF_REAL 'E'
  13951. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  13952. /*
  13953. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  13954. ** affinity value.
  13955. */
  13956. #define SQLITE_AFF_MASK 0x47
  13957. /*
  13958. ** Additional bit values that can be ORed with an affinity without
  13959. ** changing the affinity.
  13960. **
  13961. ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
  13962. ** It causes an assert() to fire if either operand to a comparison
  13963. ** operator is NULL. It is added to certain comparison operators to
  13964. ** prove that the operands are always NOT NULL.
  13965. */
  13966. #define SQLITE_KEEPNULL 0x08 /* Used by vector == or <> */
  13967. #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
  13968. #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
  13969. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  13970. #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
  13971. /*
  13972. ** An object of this type is created for each virtual table present in
  13973. ** the database schema.
  13974. **
  13975. ** If the database schema is shared, then there is one instance of this
  13976. ** structure for each database connection (sqlite3*) that uses the shared
  13977. ** schema. This is because each database connection requires its own unique
  13978. ** instance of the sqlite3_vtab* handle used to access the virtual table
  13979. ** implementation. sqlite3_vtab* handles can not be shared between
  13980. ** database connections, even when the rest of the in-memory database
  13981. ** schema is shared, as the implementation often stores the database
  13982. ** connection handle passed to it via the xConnect() or xCreate() method
  13983. ** during initialization internally. This database connection handle may
  13984. ** then be used by the virtual table implementation to access real tables
  13985. ** within the database. So that they appear as part of the callers
  13986. ** transaction, these accesses need to be made via the same database
  13987. ** connection as that used to execute SQL operations on the virtual table.
  13988. **
  13989. ** All VTable objects that correspond to a single table in a shared
  13990. ** database schema are initially stored in a linked-list pointed to by
  13991. ** the Table.pVTable member variable of the corresponding Table object.
  13992. ** When an sqlite3_prepare() operation is required to access the virtual
  13993. ** table, it searches the list for the VTable that corresponds to the
  13994. ** database connection doing the preparing so as to use the correct
  13995. ** sqlite3_vtab* handle in the compiled query.
  13996. **
  13997. ** When an in-memory Table object is deleted (for example when the
  13998. ** schema is being reloaded for some reason), the VTable objects are not
  13999. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  14000. ** immediately. Instead, they are moved from the Table.pVTable list to
  14001. ** another linked list headed by the sqlite3.pDisconnect member of the
  14002. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  14003. ** next time a statement is prepared using said sqlite3*. This is done
  14004. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  14005. ** Refer to comments above function sqlite3VtabUnlockList() for an
  14006. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  14007. ** list without holding the corresponding sqlite3.mutex mutex.
  14008. **
  14009. ** The memory for objects of this type is always allocated by
  14010. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  14011. ** the first argument.
  14012. */
  14013. struct VTable {
  14014. sqlite3 *db; /* Database connection associated with this table */
  14015. Module *pMod; /* Pointer to module implementation */
  14016. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  14017. int nRef; /* Number of pointers to this structure */
  14018. u8 bConstraint; /* True if constraints are supported */
  14019. int iSavepoint; /* Depth of the SAVEPOINT stack */
  14020. VTable *pNext; /* Next in linked list (see above) */
  14021. };
  14022. /*
  14023. ** The schema for each SQL table and view is represented in memory
  14024. ** by an instance of the following structure.
  14025. */
  14026. struct Table {
  14027. char *zName; /* Name of the table or view */
  14028. Column *aCol; /* Information about each column */
  14029. Index *pIndex; /* List of SQL indexes on this table. */
  14030. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  14031. FKey *pFKey; /* Linked list of all foreign keys in this table */
  14032. char *zColAff; /* String defining the affinity of each column */
  14033. ExprList *pCheck; /* All CHECK constraints */
  14034. /* ... also used as column name list in a VIEW */
  14035. int tnum; /* Root BTree page for this table */
  14036. u32 nTabRef; /* Number of pointers to this Table */
  14037. u32 tabFlags; /* Mask of TF_* values */
  14038. i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
  14039. i16 nCol; /* Number of columns in this table */
  14040. LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
  14041. LogEst szTabRow; /* Estimated size of each table row in bytes */
  14042. #ifdef SQLITE_ENABLE_COSTMULT
  14043. LogEst costMult; /* Cost multiplier for using this table */
  14044. #endif
  14045. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  14046. #ifndef SQLITE_OMIT_ALTERTABLE
  14047. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  14048. #endif
  14049. #ifndef SQLITE_OMIT_VIRTUALTABLE
  14050. int nModuleArg; /* Number of arguments to the module */
  14051. char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
  14052. VTable *pVTable; /* List of VTable objects. */
  14053. #endif
  14054. Trigger *pTrigger; /* List of triggers stored in pSchema */
  14055. Schema *pSchema; /* Schema that contains this table */
  14056. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  14057. };
  14058. /*
  14059. ** Allowed values for Table.tabFlags.
  14060. **
  14061. ** TF_OOOHidden applies to tables or view that have hidden columns that are
  14062. ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
  14063. ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
  14064. ** the TF_OOOHidden attribute would apply in this case. Such tables require
  14065. ** special handling during INSERT processing.
  14066. */
  14067. #define TF_Readonly 0x0001 /* Read-only system table */
  14068. #define TF_Ephemeral 0x0002 /* An ephemeral table */
  14069. #define TF_HasPrimaryKey 0x0004 /* Table has a primary key */
  14070. #define TF_Autoincrement 0x0008 /* Integer primary key is autoincrement */
  14071. #define TF_HasStat1 0x0010 /* nRowLogEst set from sqlite_stat1 */
  14072. #define TF_WithoutRowid 0x0020 /* No rowid. PRIMARY KEY is the key */
  14073. #define TF_NoVisibleRowid 0x0040 /* No user-visible "rowid" column */
  14074. #define TF_OOOHidden 0x0080 /* Out-of-Order hidden columns */
  14075. #define TF_StatsUsed 0x0100 /* Query planner decisions affected by
  14076. ** Index.aiRowLogEst[] values */
  14077. #define TF_HasNotNull 0x0200 /* Contains NOT NULL constraints */
  14078. /*
  14079. ** Test to see whether or not a table is a virtual table. This is
  14080. ** done as a macro so that it will be optimized out when virtual
  14081. ** table support is omitted from the build.
  14082. */
  14083. #ifndef SQLITE_OMIT_VIRTUALTABLE
  14084. # define IsVirtual(X) ((X)->nModuleArg)
  14085. #else
  14086. # define IsVirtual(X) 0
  14087. #endif
  14088. /*
  14089. ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
  14090. ** only works for non-virtual tables (ordinary tables and views) and is
  14091. ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
  14092. ** IsHiddenColumn() macro is general purpose.
  14093. */
  14094. #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
  14095. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  14096. # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  14097. #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
  14098. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  14099. # define IsOrdinaryHiddenColumn(X) 0
  14100. #else
  14101. # define IsHiddenColumn(X) 0
  14102. # define IsOrdinaryHiddenColumn(X) 0
  14103. #endif
  14104. /* Does the table have a rowid */
  14105. #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
  14106. #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
  14107. /*
  14108. ** Each foreign key constraint is an instance of the following structure.
  14109. **
  14110. ** A foreign key is associated with two tables. The "from" table is
  14111. ** the table that contains the REFERENCES clause that creates the foreign
  14112. ** key. The "to" table is the table that is named in the REFERENCES clause.
  14113. ** Consider this example:
  14114. **
  14115. ** CREATE TABLE ex1(
  14116. ** a INTEGER PRIMARY KEY,
  14117. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  14118. ** );
  14119. **
  14120. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  14121. ** Equivalent names:
  14122. **
  14123. ** from-table == child-table
  14124. ** to-table == parent-table
  14125. **
  14126. ** Each REFERENCES clause generates an instance of the following structure
  14127. ** which is attached to the from-table. The to-table need not exist when
  14128. ** the from-table is created. The existence of the to-table is not checked.
  14129. **
  14130. ** The list of all parents for child Table X is held at X.pFKey.
  14131. **
  14132. ** A list of all children for a table named Z (which might not even exist)
  14133. ** is held in Schema.fkeyHash with a hash key of Z.
  14134. */
  14135. struct FKey {
  14136. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  14137. FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
  14138. char *zTo; /* Name of table that the key points to (aka: Parent) */
  14139. FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
  14140. FKey *pPrevTo; /* Previous with the same zTo */
  14141. int nCol; /* Number of columns in this key */
  14142. /* EV: R-30323-21917 */
  14143. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  14144. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  14145. Trigger *apTrigger[2];/* Triggers for aAction[] actions */
  14146. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  14147. int iFrom; /* Index of column in pFrom */
  14148. char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
  14149. } aCol[1]; /* One entry for each of nCol columns */
  14150. };
  14151. /*
  14152. ** SQLite supports many different ways to resolve a constraint
  14153. ** error. ROLLBACK processing means that a constraint violation
  14154. ** causes the operation in process to fail and for the current transaction
  14155. ** to be rolled back. ABORT processing means the operation in process
  14156. ** fails and any prior changes from that one operation are backed out,
  14157. ** but the transaction is not rolled back. FAIL processing means that
  14158. ** the operation in progress stops and returns an error code. But prior
  14159. ** changes due to the same operation are not backed out and no rollback
  14160. ** occurs. IGNORE means that the particular row that caused the constraint
  14161. ** error is not inserted or updated. Processing continues and no error
  14162. ** is returned. REPLACE means that preexisting database rows that caused
  14163. ** a UNIQUE constraint violation are removed so that the new insert or
  14164. ** update can proceed. Processing continues and no error is reported.
  14165. **
  14166. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  14167. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  14168. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  14169. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  14170. ** referenced table row is propagated into the row that holds the
  14171. ** foreign key.
  14172. **
  14173. ** The following symbolic values are used to record which type
  14174. ** of action to take.
  14175. */
  14176. #define OE_None 0 /* There is no constraint to check */
  14177. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  14178. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  14179. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  14180. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  14181. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  14182. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  14183. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  14184. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  14185. #define OE_Cascade 9 /* Cascade the changes */
  14186. #define OE_Default 10 /* Do whatever the default action is */
  14187. /*
  14188. ** An instance of the following structure is passed as the first
  14189. ** argument to sqlite3VdbeKeyCompare and is used to control the
  14190. ** comparison of the two index keys.
  14191. **
  14192. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  14193. ** are nField slots for the columns of an index then one extra slot
  14194. ** for the rowid at the end.
  14195. */
  14196. struct KeyInfo {
  14197. u32 nRef; /* Number of references to this KeyInfo object */
  14198. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  14199. u16 nField; /* Number of key columns in the index */
  14200. u16 nXField; /* Number of columns beyond the key columns */
  14201. sqlite3 *db; /* The database connection */
  14202. u8 *aSortOrder; /* Sort order for each column. */
  14203. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  14204. };
  14205. /*
  14206. ** This object holds a record which has been parsed out into individual
  14207. ** fields, for the purposes of doing a comparison.
  14208. **
  14209. ** A record is an object that contains one or more fields of data.
  14210. ** Records are used to store the content of a table row and to store
  14211. ** the key of an index. A blob encoding of a record is created by
  14212. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  14213. ** OP_Column opcode.
  14214. **
  14215. ** An instance of this object serves as a "key" for doing a search on
  14216. ** an index b+tree. The goal of the search is to find the entry that
  14217. ** is closed to the key described by this object. This object might hold
  14218. ** just a prefix of the key. The number of fields is given by
  14219. ** pKeyInfo->nField.
  14220. **
  14221. ** The r1 and r2 fields are the values to return if this key is less than
  14222. ** or greater than a key in the btree, respectively. These are normally
  14223. ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
  14224. ** is in DESC order.
  14225. **
  14226. ** The key comparison functions actually return default_rc when they find
  14227. ** an equals comparison. default_rc can be -1, 0, or +1. If there are
  14228. ** multiple entries in the b-tree with the same key (when only looking
  14229. ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
  14230. ** cause the search to find the last match, or +1 to cause the search to
  14231. ** find the first match.
  14232. **
  14233. ** The key comparison functions will set eqSeen to true if they ever
  14234. ** get and equal results when comparing this structure to a b-tree record.
  14235. ** When default_rc!=0, the search might end up on the record immediately
  14236. ** before the first match or immediately after the last match. The
  14237. ** eqSeen field will indicate whether or not an exact match exists in the
  14238. ** b-tree.
  14239. */
  14240. struct UnpackedRecord {
  14241. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  14242. Mem *aMem; /* Values */
  14243. u16 nField; /* Number of entries in apMem[] */
  14244. i8 default_rc; /* Comparison result if keys are equal */
  14245. u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
  14246. i8 r1; /* Value to return if (lhs > rhs) */
  14247. i8 r2; /* Value to return if (rhs < lhs) */
  14248. u8 eqSeen; /* True if an equality comparison has been seen */
  14249. };
  14250. /*
  14251. ** Each SQL index is represented in memory by an
  14252. ** instance of the following structure.
  14253. **
  14254. ** The columns of the table that are to be indexed are described
  14255. ** by the aiColumn[] field of this structure. For example, suppose
  14256. ** we have the following table and index:
  14257. **
  14258. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  14259. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  14260. **
  14261. ** In the Table structure describing Ex1, nCol==3 because there are
  14262. ** three columns in the table. In the Index structure describing
  14263. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  14264. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  14265. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  14266. ** The second column to be indexed (c1) has an index of 0 in
  14267. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  14268. **
  14269. ** The Index.onError field determines whether or not the indexed columns
  14270. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  14271. ** it means this is not a unique index. Otherwise it is a unique index
  14272. ** and the value of Index.onError indicate the which conflict resolution
  14273. ** algorithm to employ whenever an attempt is made to insert a non-unique
  14274. ** element.
  14275. **
  14276. ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
  14277. ** generate VDBE code (as opposed to parsing one read from an sqlite_master
  14278. ** table as part of parsing an existing database schema), transient instances
  14279. ** of this structure may be created. In this case the Index.tnum variable is
  14280. ** used to store the address of a VDBE instruction, not a database page
  14281. ** number (it cannot - the database page is not allocated until the VDBE
  14282. ** program is executed). See convertToWithoutRowidTable() for details.
  14283. */
  14284. struct Index {
  14285. char *zName; /* Name of this index */
  14286. i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
  14287. LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
  14288. Table *pTable; /* The SQL table being indexed */
  14289. char *zColAff; /* String defining the affinity of each column */
  14290. Index *pNext; /* The next index associated with the same table */
  14291. Schema *pSchema; /* Schema containing this index */
  14292. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  14293. const char **azColl; /* Array of collation sequence names for index */
  14294. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  14295. ExprList *aColExpr; /* Column expressions */
  14296. int tnum; /* DB Page containing root of this index */
  14297. LogEst szIdxRow; /* Estimated average row size in bytes */
  14298. u16 nKeyCol; /* Number of columns forming the key */
  14299. u16 nColumn; /* Number of columns stored in the index */
  14300. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  14301. unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  14302. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  14303. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  14304. unsigned isResized:1; /* True if resizeIndexObject() has been called */
  14305. unsigned isCovering:1; /* True if this is a covering index */
  14306. unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
  14307. unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */
  14308. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  14309. int nSample; /* Number of elements in aSample[] */
  14310. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  14311. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  14312. IndexSample *aSample; /* Samples of the left-most key */
  14313. tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
  14314. tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
  14315. #endif
  14316. };
  14317. /*
  14318. ** Allowed values for Index.idxType
  14319. */
  14320. #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
  14321. #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
  14322. #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
  14323. /* Return true if index X is a PRIMARY KEY index */
  14324. #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  14325. /* Return true if index X is a UNIQUE index */
  14326. #define IsUniqueIndex(X) ((X)->onError!=OE_None)
  14327. /* The Index.aiColumn[] values are normally positive integer. But
  14328. ** there are some negative values that have special meaning:
  14329. */
  14330. #define XN_ROWID (-1) /* Indexed column is the rowid */
  14331. #define XN_EXPR (-2) /* Indexed column is an expression */
  14332. /*
  14333. ** Each sample stored in the sqlite_stat3 table is represented in memory
  14334. ** using a structure of this type. See documentation at the top of the
  14335. ** analyze.c source file for additional information.
  14336. */
  14337. struct IndexSample {
  14338. void *p; /* Pointer to sampled record */
  14339. int n; /* Size of record in bytes */
  14340. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  14341. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  14342. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  14343. };
  14344. /*
  14345. ** Each token coming out of the lexer is an instance of
  14346. ** this structure. Tokens are also used as part of an expression.
  14347. **
  14348. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  14349. ** may contain random values. Do not make any assumptions about Token.dyn
  14350. ** and Token.n when Token.z==0.
  14351. */
  14352. struct Token {
  14353. const char *z; /* Text of the token. Not NULL-terminated! */
  14354. unsigned int n; /* Number of characters in this token */
  14355. };
  14356. /*
  14357. ** An instance of this structure contains information needed to generate
  14358. ** code for a SELECT that contains aggregate functions.
  14359. **
  14360. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  14361. ** pointer to this structure. The Expr.iColumn field is the index in
  14362. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  14363. ** code for that node.
  14364. **
  14365. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  14366. ** original Select structure that describes the SELECT statement. These
  14367. ** fields do not need to be freed when deallocating the AggInfo structure.
  14368. */
  14369. struct AggInfo {
  14370. u8 directMode; /* Direct rendering mode means take data directly
  14371. ** from source tables rather than from accumulators */
  14372. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  14373. ** than the source table */
  14374. int sortingIdx; /* Cursor number of the sorting index */
  14375. int sortingIdxPTab; /* Cursor number of pseudo-table */
  14376. int nSortingColumn; /* Number of columns in the sorting index */
  14377. int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
  14378. ExprList *pGroupBy; /* The group by clause */
  14379. struct AggInfo_col { /* For each column used in source tables */
  14380. Table *pTab; /* Source table */
  14381. int iTable; /* Cursor number of the source table */
  14382. int iColumn; /* Column number within the source table */
  14383. int iSorterColumn; /* Column number in the sorting index */
  14384. int iMem; /* Memory location that acts as accumulator */
  14385. Expr *pExpr; /* The original expression */
  14386. } *aCol;
  14387. int nColumn; /* Number of used entries in aCol[] */
  14388. int nAccumulator; /* Number of columns that show through to the output.
  14389. ** Additional columns are used only as parameters to
  14390. ** aggregate functions */
  14391. struct AggInfo_func { /* For each aggregate function */
  14392. Expr *pExpr; /* Expression encoding the function */
  14393. FuncDef *pFunc; /* The aggregate function implementation */
  14394. int iMem; /* Memory location that acts as accumulator */
  14395. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  14396. } *aFunc;
  14397. int nFunc; /* Number of entries in aFunc[] */
  14398. };
  14399. /*
  14400. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  14401. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  14402. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  14403. ** it uses less memory in the Expr object, which is a big memory user
  14404. ** in systems with lots of prepared statements. And few applications
  14405. ** need more than about 10 or 20 variables. But some extreme users want
  14406. ** to have prepared statements with over 32767 variables, and for them
  14407. ** the option is available (at compile-time).
  14408. */
  14409. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  14410. typedef i16 ynVar;
  14411. #else
  14412. typedef int ynVar;
  14413. #endif
  14414. /*
  14415. ** Each node of an expression in the parse tree is an instance
  14416. ** of this structure.
  14417. **
  14418. ** Expr.op is the opcode. The integer parser token codes are reused
  14419. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  14420. ** code representing the ">=" operator. This same integer code is reused
  14421. ** to represent the greater-than-or-equal-to operator in the expression
  14422. ** tree.
  14423. **
  14424. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  14425. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  14426. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  14427. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  14428. ** then Expr.token contains the name of the function.
  14429. **
  14430. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  14431. ** binary operator. Either or both may be NULL.
  14432. **
  14433. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  14434. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  14435. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  14436. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  14437. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  14438. ** valid.
  14439. **
  14440. ** An expression of the form ID or ID.ID refers to a column in a table.
  14441. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  14442. ** the integer cursor number of a VDBE cursor pointing to that table and
  14443. ** Expr.iColumn is the column number for the specific column. If the
  14444. ** expression is used as a result in an aggregate SELECT, then the
  14445. ** value is also stored in the Expr.iAgg column in the aggregate so that
  14446. ** it can be accessed after all aggregates are computed.
  14447. **
  14448. ** If the expression is an unbound variable marker (a question mark
  14449. ** character '?' in the original SQL) then the Expr.iTable holds the index
  14450. ** number for that variable.
  14451. **
  14452. ** If the expression is a subquery then Expr.iColumn holds an integer
  14453. ** register number containing the result of the subquery. If the
  14454. ** subquery gives a constant result, then iTable is -1. If the subquery
  14455. ** gives a different answer at different times during statement processing
  14456. ** then iTable is the address of a subroutine that computes the subquery.
  14457. **
  14458. ** If the Expr is of type OP_Column, and the table it is selecting from
  14459. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  14460. ** corresponding table definition.
  14461. **
  14462. ** ALLOCATION NOTES:
  14463. **
  14464. ** Expr objects can use a lot of memory space in database schema. To
  14465. ** help reduce memory requirements, sometimes an Expr object will be
  14466. ** truncated. And to reduce the number of memory allocations, sometimes
  14467. ** two or more Expr objects will be stored in a single memory allocation,
  14468. ** together with Expr.zToken strings.
  14469. **
  14470. ** If the EP_Reduced and EP_TokenOnly flags are set when
  14471. ** an Expr object is truncated. When EP_Reduced is set, then all
  14472. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  14473. ** are contained within the same memory allocation. Note, however, that
  14474. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  14475. ** allocated, regardless of whether or not EP_Reduced is set.
  14476. */
  14477. struct Expr {
  14478. u8 op; /* Operation performed by this node */
  14479. char affinity; /* The affinity of the column or 0 if not a column */
  14480. u32 flags; /* Various flags. EP_* See below */
  14481. union {
  14482. char *zToken; /* Token value. Zero terminated and dequoted */
  14483. int iValue; /* Non-negative integer value if EP_IntValue */
  14484. } u;
  14485. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  14486. ** space is allocated for the fields below this point. An attempt to
  14487. ** access them will result in a segfault or malfunction.
  14488. *********************************************************************/
  14489. Expr *pLeft; /* Left subnode */
  14490. Expr *pRight; /* Right subnode */
  14491. union {
  14492. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  14493. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  14494. } x;
  14495. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  14496. ** space is allocated for the fields below this point. An attempt to
  14497. ** access them will result in a segfault or malfunction.
  14498. *********************************************************************/
  14499. #if SQLITE_MAX_EXPR_DEPTH>0
  14500. int nHeight; /* Height of the tree headed by this node */
  14501. #endif
  14502. int iTable; /* TK_COLUMN: cursor number of table holding column
  14503. ** TK_REGISTER: register number
  14504. ** TK_TRIGGER: 1 -> new, 0 -> old
  14505. ** EP_Unlikely: 134217728 times likelihood
  14506. ** TK_SELECT: 1st register of result vector */
  14507. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  14508. ** TK_VARIABLE: variable number (always >= 1).
  14509. ** TK_SELECT_COLUMN: column of the result vector */
  14510. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  14511. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  14512. u8 op2; /* TK_REGISTER: original value of Expr.op
  14513. ** TK_COLUMN: the value of p5 for OP_Column
  14514. ** TK_AGG_FUNCTION: nesting depth */
  14515. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  14516. Table *pTab; /* Table for TK_COLUMN expressions. */
  14517. };
  14518. /*
  14519. ** The following are the meanings of bits in the Expr.flags field.
  14520. */
  14521. #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
  14522. #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
  14523. #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
  14524. #define EP_Error 0x000008 /* Expression contains one or more errors */
  14525. #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
  14526. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  14527. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  14528. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  14529. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
  14530. #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
  14531. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  14532. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  14533. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  14534. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  14535. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  14536. #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
  14537. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  14538. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  14539. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  14540. #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
  14541. #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
  14542. #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
  14543. #define EP_Alias 0x400000 /* Is an alias for a result set column */
  14544. #define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
  14545. /*
  14546. ** Combinations of two or more EP_* flags
  14547. */
  14548. #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
  14549. /*
  14550. ** These macros can be used to test, set, or clear bits in the
  14551. ** Expr.flags field.
  14552. */
  14553. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  14554. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  14555. #define ExprSetProperty(E,P) (E)->flags|=(P)
  14556. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  14557. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  14558. ** and Accreditation only. It works like ExprSetProperty() during VVA
  14559. ** processes but is a no-op for delivery.
  14560. */
  14561. #ifdef SQLITE_DEBUG
  14562. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  14563. #else
  14564. # define ExprSetVVAProperty(E,P)
  14565. #endif
  14566. /*
  14567. ** Macros to determine the number of bytes required by a normal Expr
  14568. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  14569. ** and an Expr struct with the EP_TokenOnly flag set.
  14570. */
  14571. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  14572. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  14573. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  14574. /*
  14575. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  14576. ** above sqlite3ExprDup() for details.
  14577. */
  14578. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  14579. /*
  14580. ** A list of expressions. Each expression may optionally have a
  14581. ** name. An expr/name combination can be used in several ways, such
  14582. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  14583. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  14584. ** also be used as the argument to a function, in which case the a.zName
  14585. ** field is not used.
  14586. **
  14587. ** By default the Expr.zSpan field holds a human-readable description of
  14588. ** the expression that is used in the generation of error messages and
  14589. ** column labels. In this case, Expr.zSpan is typically the text of a
  14590. ** column expression as it exists in a SELECT statement. However, if
  14591. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  14592. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  14593. ** form is used for name resolution with nested FROM clauses.
  14594. */
  14595. struct ExprList {
  14596. int nExpr; /* Number of expressions on the list */
  14597. int nAlloc; /* Number of a[] slots allocated */
  14598. struct ExprList_item { /* For each expression in the list */
  14599. Expr *pExpr; /* The parse tree for this expression */
  14600. char *zName; /* Token associated with this expression */
  14601. char *zSpan; /* Original text of the expression */
  14602. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  14603. unsigned done :1; /* A flag to indicate when processing is finished */
  14604. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  14605. unsigned reusable :1; /* Constant expression is reusable */
  14606. union {
  14607. struct {
  14608. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  14609. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  14610. } x;
  14611. int iConstExprReg; /* Register in which Expr value is cached */
  14612. } u;
  14613. } a[1]; /* One slot for each expression in the list */
  14614. };
  14615. /*
  14616. ** An instance of this structure is used by the parser to record both
  14617. ** the parse tree for an expression and the span of input text for an
  14618. ** expression.
  14619. */
  14620. struct ExprSpan {
  14621. Expr *pExpr; /* The expression parse tree */
  14622. const char *zStart; /* First character of input text */
  14623. const char *zEnd; /* One character past the end of input text */
  14624. };
  14625. /*
  14626. ** An instance of this structure can hold a simple list of identifiers,
  14627. ** such as the list "a,b,c" in the following statements:
  14628. **
  14629. ** INSERT INTO t(a,b,c) VALUES ...;
  14630. ** CREATE INDEX idx ON t(a,b,c);
  14631. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  14632. **
  14633. ** The IdList.a.idx field is used when the IdList represents the list of
  14634. ** column names after a table name in an INSERT statement. In the statement
  14635. **
  14636. ** INSERT INTO t(a,b,c) ...
  14637. **
  14638. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  14639. */
  14640. struct IdList {
  14641. struct IdList_item {
  14642. char *zName; /* Name of the identifier */
  14643. int idx; /* Index in some Table.aCol[] of a column named zName */
  14644. } *a;
  14645. int nId; /* Number of identifiers on the list */
  14646. };
  14647. /*
  14648. ** The bitmask datatype defined below is used for various optimizations.
  14649. **
  14650. ** Changing this from a 64-bit to a 32-bit type limits the number of
  14651. ** tables in a join to 32 instead of 64. But it also reduces the size
  14652. ** of the library by 738 bytes on ix86.
  14653. */
  14654. #ifdef SQLITE_BITMASK_TYPE
  14655. typedef SQLITE_BITMASK_TYPE Bitmask;
  14656. #else
  14657. typedef u64 Bitmask;
  14658. #endif
  14659. /*
  14660. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  14661. */
  14662. #define BMS ((int)(sizeof(Bitmask)*8))
  14663. /*
  14664. ** A bit in a Bitmask
  14665. */
  14666. #define MASKBIT(n) (((Bitmask)1)<<(n))
  14667. #define MASKBIT32(n) (((unsigned int)1)<<(n))
  14668. #define ALLBITS ((Bitmask)-1)
  14669. /*
  14670. ** The following structure describes the FROM clause of a SELECT statement.
  14671. ** Each table or subquery in the FROM clause is a separate element of
  14672. ** the SrcList.a[] array.
  14673. **
  14674. ** With the addition of multiple database support, the following structure
  14675. ** can also be used to describe a particular table such as the table that
  14676. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  14677. ** such a table must be a simple name: ID. But in SQLite, the table can
  14678. ** now be identified by a database name, a dot, then the table name: ID.ID.
  14679. **
  14680. ** The jointype starts out showing the join type between the current table
  14681. ** and the next table on the list. The parser builds the list this way.
  14682. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  14683. ** jointype expresses the join between the table and the previous table.
  14684. **
  14685. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  14686. ** contains more than 63 columns and the 64-th or later column is used.
  14687. */
  14688. struct SrcList {
  14689. int nSrc; /* Number of tables or subqueries in the FROM clause */
  14690. u32 nAlloc; /* Number of entries allocated in a[] below */
  14691. struct SrcList_item {
  14692. Schema *pSchema; /* Schema to which this item is fixed */
  14693. char *zDatabase; /* Name of database holding this table */
  14694. char *zName; /* Name of the table */
  14695. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  14696. Table *pTab; /* An SQL table corresponding to zName */
  14697. Select *pSelect; /* A SELECT statement used in place of a table name */
  14698. int addrFillSub; /* Address of subroutine to manifest a subquery */
  14699. int regReturn; /* Register holding return address of addrFillSub */
  14700. int regResult; /* Registers holding results of a co-routine */
  14701. struct {
  14702. u8 jointype; /* Type of join between this table and the previous */
  14703. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  14704. unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
  14705. unsigned isTabFunc :1; /* True if table-valued-function syntax */
  14706. unsigned isCorrelated :1; /* True if sub-query is correlated */
  14707. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  14708. unsigned isRecursive :1; /* True for recursive reference in WITH */
  14709. } fg;
  14710. #ifndef SQLITE_OMIT_EXPLAIN
  14711. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  14712. #endif
  14713. int iCursor; /* The VDBE cursor number used to access this table */
  14714. Expr *pOn; /* The ON clause of a join */
  14715. IdList *pUsing; /* The USING clause of a join */
  14716. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  14717. union {
  14718. char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
  14719. ExprList *pFuncArg; /* Arguments to table-valued-function */
  14720. } u1;
  14721. Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
  14722. } a[1]; /* One entry for each identifier on the list */
  14723. };
  14724. /*
  14725. ** Permitted values of the SrcList.a.jointype field
  14726. */
  14727. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  14728. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  14729. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  14730. #define JT_LEFT 0x0008 /* Left outer join */
  14731. #define JT_RIGHT 0x0010 /* Right outer join */
  14732. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  14733. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  14734. /*
  14735. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  14736. ** and the WhereInfo.wctrlFlags member.
  14737. **
  14738. ** Value constraints (enforced via assert()):
  14739. ** WHERE_USE_LIMIT == SF_FixedLimit
  14740. */
  14741. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  14742. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  14743. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  14744. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  14745. #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
  14746. #define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */
  14747. #define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
  14748. ** the OR optimization */
  14749. #define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */
  14750. #define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */
  14751. #define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */
  14752. #define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */
  14753. #define WHERE_SEEK_TABLE 0x0400 /* Do not defer seeks on main table */
  14754. #define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */
  14755. #define WHERE_SEEK_UNIQ_TABLE 0x1000 /* Do not defer seeks if unique */
  14756. /* 0x2000 not currently used */
  14757. #define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */
  14758. /* 0x8000 not currently used */
  14759. /* Allowed return values from sqlite3WhereIsDistinct()
  14760. */
  14761. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  14762. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  14763. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  14764. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  14765. /*
  14766. ** A NameContext defines a context in which to resolve table and column
  14767. ** names. The context consists of a list of tables (the pSrcList) field and
  14768. ** a list of named expression (pEList). The named expression list may
  14769. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  14770. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  14771. ** pEList corresponds to the result set of a SELECT and is NULL for
  14772. ** other statements.
  14773. **
  14774. ** NameContexts can be nested. When resolving names, the inner-most
  14775. ** context is searched first. If no match is found, the next outer
  14776. ** context is checked. If there is still no match, the next context
  14777. ** is checked. This process continues until either a match is found
  14778. ** or all contexts are check. When a match is found, the nRef member of
  14779. ** the context containing the match is incremented.
  14780. **
  14781. ** Each subquery gets a new NameContext. The pNext field points to the
  14782. ** NameContext in the parent query. Thus the process of scanning the
  14783. ** NameContext list corresponds to searching through successively outer
  14784. ** subqueries looking for a match.
  14785. */
  14786. struct NameContext {
  14787. Parse *pParse; /* The parser */
  14788. SrcList *pSrcList; /* One or more tables used to resolve names */
  14789. ExprList *pEList; /* Optional list of result-set columns */
  14790. AggInfo *pAggInfo; /* Information about aggregates at this level */
  14791. NameContext *pNext; /* Next outer name context. NULL for outermost */
  14792. int nRef; /* Number of names resolved by this context */
  14793. int nErr; /* Number of errors encountered while resolving names */
  14794. u16 ncFlags; /* Zero or more NC_* flags defined below */
  14795. };
  14796. /*
  14797. ** Allowed values for the NameContext, ncFlags field.
  14798. **
  14799. ** Value constraints (all checked via assert()):
  14800. ** NC_HasAgg == SF_HasAgg
  14801. ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
  14802. **
  14803. */
  14804. #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
  14805. #define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */
  14806. #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
  14807. #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
  14808. #define NC_HasAgg 0x0010 /* One or more aggregate functions seen */
  14809. #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
  14810. #define NC_VarSelect 0x0040 /* A correlated subquery has been seen */
  14811. #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
  14812. /*
  14813. ** An instance of the following structure contains all information
  14814. ** needed to generate code for a single SELECT statement.
  14815. **
  14816. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  14817. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  14818. ** limit and nOffset to the value of the offset (or 0 if there is not
  14819. ** offset). But later on, nLimit and nOffset become the memory locations
  14820. ** in the VDBE that record the limit and offset counters.
  14821. **
  14822. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  14823. ** These addresses must be stored so that we can go back and fill in
  14824. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  14825. ** the number of columns in P2 can be computed at the same time
  14826. ** as the OP_OpenEphm instruction is coded because not
  14827. ** enough information about the compound query is known at that point.
  14828. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  14829. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  14830. ** sequences for the ORDER BY clause.
  14831. */
  14832. struct Select {
  14833. ExprList *pEList; /* The fields of the result */
  14834. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  14835. LogEst nSelectRow; /* Estimated number of result rows */
  14836. u32 selFlags; /* Various SF_* values */
  14837. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  14838. #if SELECTTRACE_ENABLED
  14839. char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
  14840. #endif
  14841. int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
  14842. SrcList *pSrc; /* The FROM clause */
  14843. Expr *pWhere; /* The WHERE clause */
  14844. ExprList *pGroupBy; /* The GROUP BY clause */
  14845. Expr *pHaving; /* The HAVING clause */
  14846. ExprList *pOrderBy; /* The ORDER BY clause */
  14847. Select *pPrior; /* Prior select in a compound select statement */
  14848. Select *pNext; /* Next select to the left in a compound */
  14849. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  14850. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  14851. With *pWith; /* WITH clause attached to this select. Or NULL. */
  14852. };
  14853. /*
  14854. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  14855. ** "Select Flag".
  14856. **
  14857. ** Value constraints (all checked via assert())
  14858. ** SF_HasAgg == NC_HasAgg
  14859. ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
  14860. ** SF_FixedLimit == WHERE_USE_LIMIT
  14861. */
  14862. #define SF_Distinct 0x00001 /* Output should be DISTINCT */
  14863. #define SF_All 0x00002 /* Includes the ALL keyword */
  14864. #define SF_Resolved 0x00004 /* Identifiers have been resolved */
  14865. #define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */
  14866. #define SF_HasAgg 0x00010 /* Contains aggregate functions */
  14867. #define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */
  14868. #define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */
  14869. #define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */
  14870. #define SF_Compound 0x00100 /* Part of a compound query */
  14871. #define SF_Values 0x00200 /* Synthesized from VALUES clause */
  14872. #define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */
  14873. #define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */
  14874. #define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */
  14875. #define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */
  14876. #define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */
  14877. #define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */
  14878. #define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */
  14879. #define SF_IncludeHidden 0x20000 /* Include hidden columns in output */
  14880. /*
  14881. ** The results of a SELECT can be distributed in several ways, as defined
  14882. ** by one of the following macros. The "SRT" prefix means "SELECT Result
  14883. ** Type".
  14884. **
  14885. ** SRT_Union Store results as a key in a temporary index
  14886. ** identified by pDest->iSDParm.
  14887. **
  14888. ** SRT_Except Remove results from the temporary index pDest->iSDParm.
  14889. **
  14890. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  14891. ** set is not empty.
  14892. **
  14893. ** SRT_Discard Throw the results away. This is used by SELECT
  14894. ** statements within triggers whose only purpose is
  14895. ** the side-effects of functions.
  14896. **
  14897. ** All of the above are free to ignore their ORDER BY clause. Those that
  14898. ** follow must honor the ORDER BY clause.
  14899. **
  14900. ** SRT_Output Generate a row of output (using the OP_ResultRow
  14901. ** opcode) for each row in the result set.
  14902. **
  14903. ** SRT_Mem Only valid if the result is a single column.
  14904. ** Store the first column of the first result row
  14905. ** in register pDest->iSDParm then abandon the rest
  14906. ** of the query. This destination implies "LIMIT 1".
  14907. **
  14908. ** SRT_Set The result must be a single column. Store each
  14909. ** row of result as the key in table pDest->iSDParm.
  14910. ** Apply the affinity pDest->affSdst before storing
  14911. ** results. Used to implement "IN (SELECT ...)".
  14912. **
  14913. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  14914. ** the result there. The cursor is left open after
  14915. ** returning. This is like SRT_Table except that
  14916. ** this destination uses OP_OpenEphemeral to create
  14917. ** the table first.
  14918. **
  14919. ** SRT_Coroutine Generate a co-routine that returns a new row of
  14920. ** results each time it is invoked. The entry point
  14921. ** of the co-routine is stored in register pDest->iSDParm
  14922. ** and the result row is stored in pDest->nDest registers
  14923. ** starting with pDest->iSdst.
  14924. **
  14925. ** SRT_Table Store results in temporary table pDest->iSDParm.
  14926. ** SRT_Fifo This is like SRT_EphemTab except that the table
  14927. ** is assumed to already be open. SRT_Fifo has
  14928. ** the additional property of being able to ignore
  14929. ** the ORDER BY clause.
  14930. **
  14931. ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
  14932. ** But also use temporary table pDest->iSDParm+1 as
  14933. ** a record of all prior results and ignore any duplicate
  14934. ** rows. Name means: "Distinct Fifo".
  14935. **
  14936. ** SRT_Queue Store results in priority queue pDest->iSDParm (really
  14937. ** an index). Append a sequence number so that all entries
  14938. ** are distinct.
  14939. **
  14940. ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
  14941. ** the same record has never been stored before. The
  14942. ** index at pDest->iSDParm+1 hold all prior stores.
  14943. */
  14944. #define SRT_Union 1 /* Store result as keys in an index */
  14945. #define SRT_Except 2 /* Remove result from a UNION index */
  14946. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  14947. #define SRT_Discard 4 /* Do not save the results anywhere */
  14948. #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
  14949. #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
  14950. #define SRT_Queue 7 /* Store result in an queue */
  14951. #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
  14952. /* The ORDER BY clause is ignored for all of the above */
  14953. #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
  14954. #define SRT_Output 9 /* Output each row of result */
  14955. #define SRT_Mem 10 /* Store result in a memory cell */
  14956. #define SRT_Set 11 /* Store results as keys in an index */
  14957. #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
  14958. #define SRT_Coroutine 13 /* Generate a single row of result */
  14959. #define SRT_Table 14 /* Store result as data with an automatic rowid */
  14960. /*
  14961. ** An instance of this object describes where to put of the results of
  14962. ** a SELECT statement.
  14963. */
  14964. struct SelectDest {
  14965. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  14966. char *zAffSdst; /* Affinity used when eDest==SRT_Set */
  14967. int iSDParm; /* A parameter used by the eDest disposal method */
  14968. int iSdst; /* Base register where results are written */
  14969. int nSdst; /* Number of registers allocated */
  14970. ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
  14971. };
  14972. /*
  14973. ** During code generation of statements that do inserts into AUTOINCREMENT
  14974. ** tables, the following information is attached to the Table.u.autoInc.p
  14975. ** pointer of each autoincrement table to record some side information that
  14976. ** the code generator needs. We have to keep per-table autoincrement
  14977. ** information in case inserts are done within triggers. Triggers do not
  14978. ** normally coordinate their activities, but we do need to coordinate the
  14979. ** loading and saving of autoincrement information.
  14980. */
  14981. struct AutoincInfo {
  14982. AutoincInfo *pNext; /* Next info block in a list of them all */
  14983. Table *pTab; /* Table this info block refers to */
  14984. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  14985. int regCtr; /* Memory register holding the rowid counter */
  14986. };
  14987. /*
  14988. ** Size of the column cache
  14989. */
  14990. #ifndef SQLITE_N_COLCACHE
  14991. # define SQLITE_N_COLCACHE 10
  14992. #endif
  14993. /*
  14994. ** At least one instance of the following structure is created for each
  14995. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  14996. ** statement. All such objects are stored in the linked list headed at
  14997. ** Parse.pTriggerPrg and deleted once statement compilation has been
  14998. ** completed.
  14999. **
  15000. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  15001. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  15002. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  15003. ** The Parse.pTriggerPrg list never contains two entries with the same
  15004. ** values for both pTrigger and orconf.
  15005. **
  15006. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  15007. ** accessed (or set to 0 for triggers fired as a result of INSERT
  15008. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  15009. ** a mask of new.* columns used by the program.
  15010. */
  15011. struct TriggerPrg {
  15012. Trigger *pTrigger; /* Trigger this program was coded from */
  15013. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  15014. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  15015. int orconf; /* Default ON CONFLICT policy */
  15016. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  15017. };
  15018. /*
  15019. ** The yDbMask datatype for the bitmask of all attached databases.
  15020. */
  15021. #if SQLITE_MAX_ATTACHED>30
  15022. typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
  15023. # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
  15024. # define DbMaskZero(M) memset((M),0,sizeof(M))
  15025. # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
  15026. # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
  15027. # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
  15028. #else
  15029. typedef unsigned int yDbMask;
  15030. # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
  15031. # define DbMaskZero(M) (M)=0
  15032. # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
  15033. # define DbMaskAllZero(M) (M)==0
  15034. # define DbMaskNonZero(M) (M)!=0
  15035. #endif
  15036. /*
  15037. ** An SQL parser context. A copy of this structure is passed through
  15038. ** the parser and down into all the parser action routine in order to
  15039. ** carry around information that is global to the entire parse.
  15040. **
  15041. ** The structure is divided into two parts. When the parser and code
  15042. ** generate call themselves recursively, the first part of the structure
  15043. ** is constant but the second part is reset at the beginning and end of
  15044. ** each recursion.
  15045. **
  15046. ** The nTableLock and aTableLock variables are only used if the shared-cache
  15047. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  15048. ** used to store the set of table-locks required by the statement being
  15049. ** compiled. Function sqlite3TableLock() is used to add entries to the
  15050. ** list.
  15051. */
  15052. struct Parse {
  15053. sqlite3 *db; /* The main database structure */
  15054. char *zErrMsg; /* An error message */
  15055. Vdbe *pVdbe; /* An engine for executing database bytecode */
  15056. int rc; /* Return code from execution */
  15057. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  15058. u8 checkSchema; /* Causes schema cookie check after an error */
  15059. u8 nested; /* Number of nested calls to the parser/code generator */
  15060. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  15061. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  15062. u8 mayAbort; /* True if statement may throw an ABORT exception */
  15063. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  15064. u8 okConstFactor; /* OK to factor out constants */
  15065. u8 disableLookaside; /* Number of times lookaside has been disabled */
  15066. u8 nColCache; /* Number of entries in aColCache[] */
  15067. int nRangeReg; /* Size of the temporary register block */
  15068. int iRangeReg; /* First register in temporary register block */
  15069. int nErr; /* Number of errors seen */
  15070. int nTab; /* Number of previously allocated VDBE cursors */
  15071. int nMem; /* Number of memory cells used so far */
  15072. int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
  15073. int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
  15074. int ckBase; /* Base register of data during check constraints */
  15075. int iSelfTab; /* Table of an index whose exprs are being coded */
  15076. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  15077. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  15078. int nLabel; /* Number of labels used */
  15079. int *aLabel; /* Space to hold the labels */
  15080. ExprList *pConstExpr;/* Constant expressions */
  15081. Token constraintName;/* Name of the constraint currently being parsed */
  15082. yDbMask writeMask; /* Start a write transaction on these databases */
  15083. yDbMask cookieMask; /* Bitmask of schema verified databases */
  15084. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  15085. int regRoot; /* Register holding root page number for new objects */
  15086. int nMaxArg; /* Max args passed to user function by sub-program */
  15087. #if SELECTTRACE_ENABLED
  15088. int nSelect; /* Number of SELECT statements seen */
  15089. int nSelectIndent; /* How far to indent SELECTTRACE() output */
  15090. #endif
  15091. #ifndef SQLITE_OMIT_SHARED_CACHE
  15092. int nTableLock; /* Number of locks in aTableLock */
  15093. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  15094. #endif
  15095. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  15096. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  15097. Table *pTriggerTab; /* Table triggers are being coded for */
  15098. int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */
  15099. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  15100. u32 oldmask; /* Mask of old.* columns referenced */
  15101. u32 newmask; /* Mask of new.* columns referenced */
  15102. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  15103. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  15104. u8 disableTriggers; /* True to disable triggers */
  15105. /**************************************************************************
  15106. ** Fields above must be initialized to zero. The fields that follow,
  15107. ** down to the beginning of the recursive section, do not need to be
  15108. ** initialized as they will be set before being used. The boundary is
  15109. ** determined by offsetof(Parse,aColCache).
  15110. **************************************************************************/
  15111. struct yColCache {
  15112. int iTable; /* Table cursor number */
  15113. i16 iColumn; /* Table column number */
  15114. u8 tempReg; /* iReg is a temp register that needs to be freed */
  15115. int iLevel; /* Nesting level */
  15116. int iReg; /* Reg with value of this column. 0 means none. */
  15117. int lru; /* Least recently used entry has the smallest value */
  15118. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  15119. int aTempReg[8]; /* Holding area for temporary registers */
  15120. Token sNameToken; /* Token with unqualified schema object name */
  15121. /************************************************************************
  15122. ** Above is constant between recursions. Below is reset before and after
  15123. ** each recursion. The boundary between these two regions is determined
  15124. ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
  15125. ** first field in the recursive region.
  15126. ************************************************************************/
  15127. Token sLastToken; /* The last token parsed */
  15128. ynVar nVar; /* Number of '?' variables seen in the SQL so far */
  15129. u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
  15130. u8 explain; /* True if the EXPLAIN flag is found on the query */
  15131. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15132. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  15133. int nVtabLock; /* Number of virtual tables to lock */
  15134. #endif
  15135. int nHeight; /* Expression tree height of current sub-select */
  15136. #ifndef SQLITE_OMIT_EXPLAIN
  15137. int iSelectId; /* ID of current select for EXPLAIN output */
  15138. int iNextSelectId; /* Next available select ID for EXPLAIN output */
  15139. #endif
  15140. VList *pVList; /* Mapping between variable names and numbers */
  15141. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  15142. const char *zTail; /* All SQL text past the last semicolon parsed */
  15143. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  15144. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  15145. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  15146. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15147. Token sArg; /* Complete text of a module argument */
  15148. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  15149. #endif
  15150. Table *pZombieTab; /* List of Table objects to delete after code gen */
  15151. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  15152. With *pWith; /* Current WITH clause, or NULL */
  15153. With *pWithToFree; /* Free this WITH object at the end of the parse */
  15154. };
  15155. /*
  15156. ** Sizes and pointers of various parts of the Parse object.
  15157. */
  15158. #define PARSE_HDR_SZ offsetof(Parse,aColCache) /* Recursive part w/o aColCache*/
  15159. #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken) /* Recursive part */
  15160. #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
  15161. #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */
  15162. /*
  15163. ** Return true if currently inside an sqlite3_declare_vtab() call.
  15164. */
  15165. #ifdef SQLITE_OMIT_VIRTUALTABLE
  15166. #define IN_DECLARE_VTAB 0
  15167. #else
  15168. #define IN_DECLARE_VTAB (pParse->declareVtab)
  15169. #endif
  15170. /*
  15171. ** An instance of the following structure can be declared on a stack and used
  15172. ** to save the Parse.zAuthContext value so that it can be restored later.
  15173. */
  15174. struct AuthContext {
  15175. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  15176. Parse *pParse; /* The Parse structure */
  15177. };
  15178. /*
  15179. ** Bitfield flags for P5 value in various opcodes.
  15180. **
  15181. ** Value constraints (enforced via assert()):
  15182. ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
  15183. ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
  15184. ** OPFLAG_BULKCSR == BTREE_BULKLOAD
  15185. ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
  15186. ** OPFLAG_FORDELETE == BTREE_FORDELETE
  15187. ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
  15188. ** OPFLAG_AUXDELETE == BTREE_AUXDELETE
  15189. */
  15190. #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
  15191. /* Also used in P2 (not P5) of OP_Delete */
  15192. #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
  15193. #define OPFLAG_LASTROWID 0x20 /* Set to update db->lastRowid */
  15194. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  15195. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  15196. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  15197. #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
  15198. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  15199. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  15200. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  15201. #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
  15202. #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
  15203. #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
  15204. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  15205. #define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete/Insert: save cursor pos */
  15206. #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
  15207. /*
  15208. * Each trigger present in the database schema is stored as an instance of
  15209. * struct Trigger.
  15210. *
  15211. * Pointers to instances of struct Trigger are stored in two ways.
  15212. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  15213. * database). This allows Trigger structures to be retrieved by name.
  15214. * 2. All triggers associated with a single table form a linked list, using the
  15215. * pNext member of struct Trigger. A pointer to the first element of the
  15216. * linked list is stored as the "pTrigger" member of the associated
  15217. * struct Table.
  15218. *
  15219. * The "step_list" member points to the first element of a linked list
  15220. * containing the SQL statements specified as the trigger program.
  15221. */
  15222. struct Trigger {
  15223. char *zName; /* The name of the trigger */
  15224. char *table; /* The table or view to which the trigger applies */
  15225. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  15226. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  15227. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  15228. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  15229. the <column-list> is stored here */
  15230. Schema *pSchema; /* Schema containing the trigger */
  15231. Schema *pTabSchema; /* Schema containing the table */
  15232. TriggerStep *step_list; /* Link list of trigger program steps */
  15233. Trigger *pNext; /* Next trigger associated with the table */
  15234. };
  15235. /*
  15236. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  15237. ** determine which.
  15238. **
  15239. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  15240. ** In that cases, the constants below can be ORed together.
  15241. */
  15242. #define TRIGGER_BEFORE 1
  15243. #define TRIGGER_AFTER 2
  15244. /*
  15245. * An instance of struct TriggerStep is used to store a single SQL statement
  15246. * that is a part of a trigger-program.
  15247. *
  15248. * Instances of struct TriggerStep are stored in a singly linked list (linked
  15249. * using the "pNext" member) referenced by the "step_list" member of the
  15250. * associated struct Trigger instance. The first element of the linked list is
  15251. * the first step of the trigger-program.
  15252. *
  15253. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  15254. * "SELECT" statement. The meanings of the other members is determined by the
  15255. * value of "op" as follows:
  15256. *
  15257. * (op == TK_INSERT)
  15258. * orconf -> stores the ON CONFLICT algorithm
  15259. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  15260. * this stores a pointer to the SELECT statement. Otherwise NULL.
  15261. * zTarget -> Dequoted name of the table to insert into.
  15262. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  15263. * this stores values to be inserted. Otherwise NULL.
  15264. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  15265. * statement, then this stores the column-names to be
  15266. * inserted into.
  15267. *
  15268. * (op == TK_DELETE)
  15269. * zTarget -> Dequoted name of the table to delete from.
  15270. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  15271. * Otherwise NULL.
  15272. *
  15273. * (op == TK_UPDATE)
  15274. * zTarget -> Dequoted name of the table to update.
  15275. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  15276. * Otherwise NULL.
  15277. * pExprList -> A list of the columns to update and the expressions to update
  15278. * them to. See sqlite3Update() documentation of "pChanges"
  15279. * argument.
  15280. *
  15281. */
  15282. struct TriggerStep {
  15283. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  15284. u8 orconf; /* OE_Rollback etc. */
  15285. Trigger *pTrig; /* The trigger that this step is a part of */
  15286. Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
  15287. char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
  15288. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  15289. ExprList *pExprList; /* SET clause for UPDATE. */
  15290. IdList *pIdList; /* Column names for INSERT */
  15291. TriggerStep *pNext; /* Next in the link-list */
  15292. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  15293. };
  15294. /*
  15295. ** The following structure contains information used by the sqliteFix...
  15296. ** routines as they walk the parse tree to make database references
  15297. ** explicit.
  15298. */
  15299. typedef struct DbFixer DbFixer;
  15300. struct DbFixer {
  15301. Parse *pParse; /* The parsing context. Error messages written here */
  15302. Schema *pSchema; /* Fix items to this schema */
  15303. int bVarOnly; /* Check for variable references only */
  15304. const char *zDb; /* Make sure all objects are contained in this database */
  15305. const char *zType; /* Type of the container - used for error messages */
  15306. const Token *pName; /* Name of the container - used for error messages */
  15307. };
  15308. /*
  15309. ** An objected used to accumulate the text of a string where we
  15310. ** do not necessarily know how big the string will be in the end.
  15311. */
  15312. struct StrAccum {
  15313. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  15314. char *zBase; /* A base allocation. Not from malloc. */
  15315. char *zText; /* The string collected so far */
  15316. u32 nChar; /* Length of the string so far */
  15317. u32 nAlloc; /* Amount of space allocated in zText */
  15318. u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
  15319. u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
  15320. u8 printfFlags; /* SQLITE_PRINTF flags below */
  15321. };
  15322. #define STRACCUM_NOMEM 1
  15323. #define STRACCUM_TOOBIG 2
  15324. #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
  15325. #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
  15326. #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
  15327. #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
  15328. /*
  15329. ** A pointer to this structure is used to communicate information
  15330. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  15331. */
  15332. typedef struct {
  15333. sqlite3 *db; /* The database being initialized */
  15334. char **pzErrMsg; /* Error message stored here */
  15335. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  15336. int rc; /* Result code stored here */
  15337. } InitData;
  15338. /*
  15339. ** Structure containing global configuration data for the SQLite library.
  15340. **
  15341. ** This structure also contains some state information.
  15342. */
  15343. struct Sqlite3Config {
  15344. int bMemstat; /* True to enable memory status */
  15345. int bCoreMutex; /* True to enable core mutexing */
  15346. int bFullMutex; /* True to enable full mutexing */
  15347. int bOpenUri; /* True to interpret filenames as URIs */
  15348. int bUseCis; /* Use covering indices for full-scans */
  15349. int mxStrlen; /* Maximum string length */
  15350. int neverCorrupt; /* Database is always well-formed */
  15351. int szLookaside; /* Default lookaside buffer size */
  15352. int nLookaside; /* Default lookaside buffer count */
  15353. int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
  15354. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  15355. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  15356. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  15357. void *pHeap; /* Heap storage space */
  15358. int nHeap; /* Size of pHeap[] */
  15359. int mnReq, mxReq; /* Min and max heap requests sizes */
  15360. sqlite3_int64 szMmap; /* mmap() space per open file */
  15361. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  15362. void *pScratch; /* Scratch memory */
  15363. int szScratch; /* Size of each scratch buffer */
  15364. int nScratch; /* Number of scratch buffers */
  15365. void *pPage; /* Page cache memory */
  15366. int szPage; /* Size of each page in pPage[] */
  15367. int nPage; /* Number of pages in pPage[] */
  15368. int mxParserStack; /* maximum depth of the parser stack */
  15369. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  15370. u32 szPma; /* Maximum Sorter PMA size */
  15371. /* The above might be initialized to non-zero. The following need to always
  15372. ** initially be zero, however. */
  15373. int isInit; /* True after initialization has finished */
  15374. int inProgress; /* True while initialization in progress */
  15375. int isMutexInit; /* True after mutexes are initialized */
  15376. int isMallocInit; /* True after malloc is initialized */
  15377. int isPCacheInit; /* True after malloc is initialized */
  15378. int nRefInitMutex; /* Number of users of pInitMutex */
  15379. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  15380. void (*xLog)(void*,int,const char*); /* Function for logging */
  15381. void *pLogArg; /* First argument to xLog() */
  15382. #ifdef SQLITE_ENABLE_SQLLOG
  15383. void(*xSqllog)(void*,sqlite3*,const char*, int);
  15384. void *pSqllogArg;
  15385. #endif
  15386. #ifdef SQLITE_VDBE_COVERAGE
  15387. /* The following callback (if not NULL) is invoked on every VDBE branch
  15388. ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
  15389. */
  15390. void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
  15391. void *pVdbeBranchArg; /* 1st argument */
  15392. #endif
  15393. #ifndef SQLITE_UNTESTABLE
  15394. int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
  15395. #endif
  15396. int bLocaltimeFault; /* True to fail localtime() calls */
  15397. int iOnceResetThreshold; /* When to reset OP_Once counters */
  15398. };
  15399. /*
  15400. ** This macro is used inside of assert() statements to indicate that
  15401. ** the assert is only valid on a well-formed database. Instead of:
  15402. **
  15403. ** assert( X );
  15404. **
  15405. ** One writes:
  15406. **
  15407. ** assert( X || CORRUPT_DB );
  15408. **
  15409. ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
  15410. ** that the database is definitely corrupt, only that it might be corrupt.
  15411. ** For most test cases, CORRUPT_DB is set to false using a special
  15412. ** sqlite3_test_control(). This enables assert() statements to prove
  15413. ** things that are always true for well-formed databases.
  15414. */
  15415. #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
  15416. /*
  15417. ** Context pointer passed down through the tree-walk.
  15418. */
  15419. struct Walker {
  15420. Parse *pParse; /* Parser context. */
  15421. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  15422. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  15423. void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
  15424. int walkerDepth; /* Number of subqueries */
  15425. u8 eCode; /* A small processing code */
  15426. union { /* Extra data for callback */
  15427. NameContext *pNC; /* Naming context */
  15428. int n; /* A counter */
  15429. int iCur; /* A cursor number */
  15430. SrcList *pSrcList; /* FROM clause */
  15431. struct SrcCount *pSrcCount; /* Counting column references */
  15432. struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
  15433. int *aiCol; /* array of column indexes */
  15434. struct IdxCover *pIdxCover; /* Check for index coverage */
  15435. struct IdxExprTrans *pIdxTrans; /* Convert indexed expr to column */
  15436. ExprList *pGroupBy; /* GROUP BY clause */
  15437. struct HavingToWhereCtx *pHavingCtx; /* HAVING to WHERE clause ctx */
  15438. } u;
  15439. };
  15440. /* Forward declarations */
  15441. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  15442. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  15443. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  15444. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  15445. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  15446. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
  15447. /*
  15448. ** Return code from the parse-tree walking primitives and their
  15449. ** callbacks.
  15450. */
  15451. #define WRC_Continue 0 /* Continue down into children */
  15452. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  15453. #define WRC_Abort 2 /* Abandon the tree walk */
  15454. /*
  15455. ** An instance of this structure represents a set of one or more CTEs
  15456. ** (common table expressions) created by a single WITH clause.
  15457. */
  15458. struct With {
  15459. int nCte; /* Number of CTEs in the WITH clause */
  15460. With *pOuter; /* Containing WITH clause, or NULL */
  15461. struct Cte { /* For each CTE in the WITH clause.... */
  15462. char *zName; /* Name of this CTE */
  15463. ExprList *pCols; /* List of explicit column names, or NULL */
  15464. Select *pSelect; /* The definition of this CTE */
  15465. const char *zCteErr; /* Error message for circular references */
  15466. } a[1];
  15467. };
  15468. #ifdef SQLITE_DEBUG
  15469. /*
  15470. ** An instance of the TreeView object is used for printing the content of
  15471. ** data structures on sqlite3DebugPrintf() using a tree-like view.
  15472. */
  15473. struct TreeView {
  15474. int iLevel; /* Which level of the tree we are on */
  15475. u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
  15476. };
  15477. #endif /* SQLITE_DEBUG */
  15478. /*
  15479. ** Assuming zIn points to the first byte of a UTF-8 character,
  15480. ** advance zIn to point to the first byte of the next UTF-8 character.
  15481. */
  15482. #define SQLITE_SKIP_UTF8(zIn) { \
  15483. if( (*(zIn++))>=0xc0 ){ \
  15484. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  15485. } \
  15486. }
  15487. /*
  15488. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  15489. ** the same name but without the _BKPT suffix. These macros invoke
  15490. ** routines that report the line-number on which the error originated
  15491. ** using sqlite3_log(). The routines also provide a convenient place
  15492. ** to set a debugger breakpoint.
  15493. */
  15494. SQLITE_PRIVATE int sqlite3CorruptError(int);
  15495. SQLITE_PRIVATE int sqlite3MisuseError(int);
  15496. SQLITE_PRIVATE int sqlite3CantopenError(int);
  15497. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  15498. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  15499. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  15500. #ifdef SQLITE_DEBUG
  15501. SQLITE_PRIVATE int sqlite3NomemError(int);
  15502. SQLITE_PRIVATE int sqlite3IoerrnomemError(int);
  15503. # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
  15504. # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
  15505. #else
  15506. # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
  15507. # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
  15508. #endif
  15509. /*
  15510. ** FTS3 and FTS4 both require virtual table support
  15511. */
  15512. #if defined(SQLITE_OMIT_VIRTUALTABLE)
  15513. # undef SQLITE_ENABLE_FTS3
  15514. # undef SQLITE_ENABLE_FTS4
  15515. #endif
  15516. /*
  15517. ** FTS4 is really an extension for FTS3. It is enabled using the
  15518. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
  15519. ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
  15520. */
  15521. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  15522. # define SQLITE_ENABLE_FTS3 1
  15523. #endif
  15524. /*
  15525. ** The ctype.h header is needed for non-ASCII systems. It is also
  15526. ** needed by FTS3 when FTS3 is included in the amalgamation.
  15527. */
  15528. #if !defined(SQLITE_ASCII) || \
  15529. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  15530. # include <ctype.h>
  15531. #endif
  15532. /*
  15533. ** The following macros mimic the standard library functions toupper(),
  15534. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  15535. ** sqlite versions only work for ASCII characters, regardless of locale.
  15536. */
  15537. #ifdef SQLITE_ASCII
  15538. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  15539. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  15540. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  15541. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  15542. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  15543. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  15544. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  15545. # define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
  15546. #else
  15547. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  15548. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  15549. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  15550. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  15551. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  15552. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  15553. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  15554. # define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
  15555. #endif
  15556. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  15557. SQLITE_PRIVATE int sqlite3IsIdChar(u8);
  15558. #endif
  15559. /*
  15560. ** Internal function prototypes
  15561. */
  15562. SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
  15563. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  15564. SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
  15565. #define sqlite3StrNICmp sqlite3_strnicmp
  15566. SQLITE_PRIVATE int sqlite3MallocInit(void);
  15567. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  15568. SQLITE_PRIVATE void *sqlite3Malloc(u64);
  15569. SQLITE_PRIVATE void *sqlite3MallocZero(u64);
  15570. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
  15571. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
  15572. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
  15573. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  15574. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
  15575. SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
  15576. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
  15577. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
  15578. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  15579. SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
  15580. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  15581. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  15582. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  15583. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  15584. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  15585. SQLITE_PRIVATE void sqlite3PageFree(void*);
  15586. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  15587. #ifndef SQLITE_UNTESTABLE
  15588. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  15589. #endif
  15590. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  15591. /*
  15592. ** On systems with ample stack space and that support alloca(), make
  15593. ** use of alloca() to obtain space for large automatic objects. By default,
  15594. ** obtain space from malloc().
  15595. **
  15596. ** The alloca() routine never returns NULL. This will cause code paths
  15597. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  15598. */
  15599. #ifdef SQLITE_USE_ALLOCA
  15600. # define sqlite3StackAllocRaw(D,N) alloca(N)
  15601. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  15602. # define sqlite3StackFree(D,P)
  15603. #else
  15604. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  15605. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  15606. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  15607. #endif
  15608. /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they
  15609. ** are, disable MEMSYS3
  15610. */
  15611. #ifdef SQLITE_ENABLE_MEMSYS5
  15612. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  15613. #undef SQLITE_ENABLE_MEMSYS3
  15614. #endif
  15615. #ifdef SQLITE_ENABLE_MEMSYS3
  15616. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  15617. #endif
  15618. #ifndef SQLITE_MUTEX_OMIT
  15619. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  15620. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  15621. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  15622. SQLITE_PRIVATE int sqlite3MutexInit(void);
  15623. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  15624. #endif
  15625. #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
  15626. SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
  15627. #else
  15628. # define sqlite3MemoryBarrier()
  15629. #endif
  15630. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
  15631. SQLITE_PRIVATE void sqlite3StatusUp(int, int);
  15632. SQLITE_PRIVATE void sqlite3StatusDown(int, int);
  15633. SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
  15634. /* Access to mutexes used by sqlite3_status() */
  15635. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
  15636. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
  15637. #ifndef SQLITE_OMIT_FLOATING_POINT
  15638. SQLITE_PRIVATE int sqlite3IsNaN(double);
  15639. #else
  15640. # define sqlite3IsNaN(X) 0
  15641. #endif
  15642. /*
  15643. ** An instance of the following structure holds information about SQL
  15644. ** functions arguments that are the parameters to the printf() function.
  15645. */
  15646. struct PrintfArguments {
  15647. int nArg; /* Total number of arguments */
  15648. int nUsed; /* Number of arguments used so far */
  15649. sqlite3_value **apArg; /* The argument values */
  15650. };
  15651. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list);
  15652. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
  15653. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  15654. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  15655. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  15656. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  15657. #endif
  15658. #if defined(SQLITE_TEST)
  15659. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  15660. #endif
  15661. #if defined(SQLITE_DEBUG)
  15662. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
  15663. SQLITE_PRIVATE void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
  15664. SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
  15665. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
  15666. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
  15667. #endif
  15668. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
  15669. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  15670. SQLITE_PRIVATE void sqlite3Dequote(char*);
  15671. SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
  15672. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  15673. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  15674. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  15675. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  15676. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  15677. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  15678. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  15679. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  15680. #ifdef SQLITE_DEBUG
  15681. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
  15682. #endif
  15683. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  15684. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  15685. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  15686. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
  15687. SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
  15688. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  15689. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  15690. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
  15691. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  15692. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  15693. SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
  15694. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
  15695. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  15696. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  15697. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  15698. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
  15699. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  15700. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  15701. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  15702. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15703. SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
  15704. #endif
  15705. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  15706. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  15707. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  15708. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  15709. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
  15710. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
  15711. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
  15712. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  15713. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  15714. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
  15715. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
  15716. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  15717. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  15718. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*);
  15719. #else
  15720. # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
  15721. #endif
  15722. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
  15723. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  15724. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  15725. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  15726. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  15727. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  15728. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
  15729. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  15730. sqlite3_vfs**,char**,char **);
  15731. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  15732. #ifdef SQLITE_UNTESTABLE
  15733. # define sqlite3FaultSim(X) SQLITE_OK
  15734. #else
  15735. SQLITE_PRIVATE int sqlite3FaultSim(int);
  15736. #endif
  15737. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  15738. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  15739. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
  15740. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  15741. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  15742. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  15743. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  15744. #ifndef SQLITE_UNTESTABLE
  15745. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  15746. #endif
  15747. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  15748. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  15749. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  15750. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
  15751. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  15752. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
  15753. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  15754. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  15755. #else
  15756. # define sqlite3ViewGetColumnNames(A,B) 0
  15757. #endif
  15758. #if SQLITE_MAX_ATTACHED>30
  15759. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
  15760. #endif
  15761. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  15762. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  15763. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  15764. #ifndef SQLITE_OMIT_AUTOINCREMENT
  15765. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  15766. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  15767. #else
  15768. # define sqlite3AutoincrementBegin(X)
  15769. # define sqlite3AutoincrementEnd(X)
  15770. #endif
  15771. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
  15772. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  15773. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  15774. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  15775. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  15776. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  15777. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  15778. Token*, Select*, Expr*, IdList*);
  15779. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  15780. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
  15781. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  15782. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  15783. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  15784. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  15785. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  15786. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
  15787. SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  15788. Expr*, int, int, u8);
  15789. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  15790. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  15791. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  15792. Expr*,ExprList*,u32,Expr*,Expr*);
  15793. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  15794. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  15795. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  15796. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  15797. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  15798. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
  15799. #endif
  15800. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  15801. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  15802. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  15803. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  15804. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
  15805. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  15806. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  15807. SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo*);
  15808. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
  15809. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  15810. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  15811. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
  15812. #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
  15813. #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
  15814. #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
  15815. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
  15816. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  15817. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int);
  15818. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  15819. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  15820. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  15821. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  15822. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
  15823. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  15824. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  15825. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  15826. SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
  15827. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
  15828. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
  15829. SQLITE_PRIVATE int sqlite3ExprCodeAtInit(Parse*, Expr*, int);
  15830. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  15831. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  15832. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  15833. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
  15834. #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
  15835. #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
  15836. #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
  15837. #define SQLITE_ECEL_OMITREF 0x08 /* Omit if ExprList.u.x.iOrderByCol */
  15838. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  15839. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  15840. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
  15841. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  15842. #define LOCATE_VIEW 0x01
  15843. #define LOCATE_NOERR 0x02
  15844. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
  15845. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
  15846. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  15847. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  15848. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  15849. SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*);
  15850. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int);
  15851. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  15852. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
  15853. SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
  15854. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  15855. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
  15856. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  15857. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  15858. SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
  15859. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  15860. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  15861. #ifndef SQLITE_UNTESTABLE
  15862. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  15863. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  15864. #endif
  15865. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  15866. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  15867. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  15868. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  15869. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  15870. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  15871. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  15872. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  15873. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  15874. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  15875. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  15876. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
  15877. SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
  15878. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
  15879. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  15880. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
  15881. #endif
  15882. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  15883. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  15884. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  15885. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  15886. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  15887. Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
  15888. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
  15889. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
  15890. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
  15891. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
  15892. u8,u8,int,int*,int*);
  15893. #ifdef SQLITE_ENABLE_NULL_TRIM
  15894. SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe*,Table*);
  15895. #else
  15896. # define sqlite3SetMakeRecordP5(A,B)
  15897. #endif
  15898. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
  15899. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
  15900. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  15901. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  15902. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  15903. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
  15904. SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
  15905. SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
  15906. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  15907. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  15908. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  15909. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  15910. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  15911. #if SELECTTRACE_ENABLED
  15912. SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
  15913. #else
  15914. # define sqlite3SelectSetName(A,B)
  15915. #endif
  15916. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
  15917. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
  15918. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
  15919. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  15920. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
  15921. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  15922. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  15923. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  15924. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  15925. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  15926. #endif
  15927. #ifndef SQLITE_OMIT_TRIGGER
  15928. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  15929. Expr*,int, int);
  15930. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  15931. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  15932. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  15933. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  15934. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  15935. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  15936. int, int, int);
  15937. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  15938. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  15939. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  15940. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  15941. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  15942. Select*,u8);
  15943. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  15944. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  15945. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  15946. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  15947. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  15948. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  15949. # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
  15950. #else
  15951. # define sqlite3TriggersExist(B,C,D,E,F) 0
  15952. # define sqlite3DeleteTrigger(A,B)
  15953. # define sqlite3DropTriggerPtr(A,B)
  15954. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  15955. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  15956. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  15957. # define sqlite3TriggerList(X, Y) 0
  15958. # define sqlite3ParseToplevel(p) p
  15959. # define sqlite3IsToplevel(p) 1
  15960. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  15961. #endif
  15962. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  15963. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  15964. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  15965. #ifndef SQLITE_OMIT_AUTHORIZATION
  15966. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  15967. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  15968. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  15969. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  15970. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  15971. #else
  15972. # define sqlite3AuthRead(a,b,c,d)
  15973. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  15974. # define sqlite3AuthContextPush(a,b,c)
  15975. # define sqlite3AuthContextPop(a) ((void)(a))
  15976. #endif
  15977. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  15978. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  15979. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  15980. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  15981. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  15982. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  15983. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  15984. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  15985. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  15986. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  15987. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  15988. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  15989. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  15990. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  15991. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  15992. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  15993. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15994. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  15995. #endif
  15996. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  15997. defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
  15998. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  15999. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  16000. #endif
  16001. SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
  16002. SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
  16003. SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
  16004. /*
  16005. ** Routines to read and write variable-length integers. These used to
  16006. ** be defined locally, but now we use the varint routines in the util.c
  16007. ** file.
  16008. */
  16009. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  16010. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  16011. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  16012. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  16013. /*
  16014. ** The common case is for a varint to be a single byte. They following
  16015. ** macros handle the common case without a procedure call, but then call
  16016. ** the procedure for larger varints.
  16017. */
  16018. #define getVarint32(A,B) \
  16019. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  16020. #define putVarint32(A,B) \
  16021. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  16022. sqlite3PutVarint((A),(B)))
  16023. #define getVarint sqlite3GetVarint
  16024. #define putVarint sqlite3PutVarint
  16025. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
  16026. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
  16027. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  16028. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  16029. SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
  16030. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  16031. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  16032. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
  16033. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
  16034. SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
  16035. SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
  16036. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  16037. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  16038. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  16039. #if defined(SQLITE_NEED_ERR_NAME)
  16040. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  16041. #endif
  16042. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  16043. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  16044. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  16045. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  16046. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  16047. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
  16048. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  16049. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  16050. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  16051. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  16052. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  16053. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  16054. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  16055. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  16056. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  16057. #ifdef SQLITE_ENABLE_8_3_NAMES
  16058. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  16059. #else
  16060. # define sqlite3FileSuffix3(X,Y)
  16061. #endif
  16062. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
  16063. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  16064. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  16065. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  16066. void(*)(void*));
  16067. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
  16068. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  16069. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  16070. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  16071. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  16072. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  16073. #ifndef SQLITE_AMALGAMATION
  16074. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  16075. SQLITE_PRIVATE const char sqlite3StrBINARY[];
  16076. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  16077. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  16078. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  16079. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  16080. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  16081. #ifndef SQLITE_OMIT_WSD
  16082. SQLITE_PRIVATE int sqlite3PendingByte;
  16083. #endif
  16084. #endif
  16085. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  16086. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  16087. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  16088. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  16089. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  16090. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  16091. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  16092. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr *, int, int);
  16093. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  16094. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
  16095. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  16096. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  16097. SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
  16098. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  16099. SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  16100. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  16101. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  16102. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  16103. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  16104. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  16105. SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
  16106. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  16107. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  16108. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  16109. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  16110. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  16111. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  16112. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  16113. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  16114. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  16115. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  16116. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  16117. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  16118. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
  16119. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
  16120. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
  16121. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
  16122. #ifdef SQLITE_DEBUG
  16123. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
  16124. #endif
  16125. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  16126. void (*)(sqlite3_context*,int,sqlite3_value **),
  16127. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  16128. FuncDestructor *pDestructor
  16129. );
  16130. SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
  16131. SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
  16132. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  16133. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  16134. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
  16135. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  16136. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
  16137. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
  16138. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  16139. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  16140. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  16141. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  16142. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  16143. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  16144. #ifndef SQLITE_OMIT_SUBQUERY
  16145. SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
  16146. #else
  16147. # define sqlite3ExprCheckIN(x,y) SQLITE_OK
  16148. #endif
  16149. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  16150. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  16151. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  16152. Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
  16153. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
  16154. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  16155. SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
  16156. SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
  16157. #endif
  16158. /*
  16159. ** The interface to the LEMON-generated parser
  16160. */
  16161. #ifndef SQLITE_AMALGAMATION
  16162. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
  16163. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  16164. #endif
  16165. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  16166. #ifdef YYTRACKMAXSTACKDEPTH
  16167. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  16168. #endif
  16169. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  16170. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  16171. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  16172. #else
  16173. # define sqlite3CloseExtensions(X)
  16174. #endif
  16175. #ifndef SQLITE_OMIT_SHARED_CACHE
  16176. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  16177. #else
  16178. #define sqlite3TableLock(v,w,x,y,z)
  16179. #endif
  16180. #ifdef SQLITE_TEST
  16181. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  16182. #endif
  16183. #ifdef SQLITE_OMIT_VIRTUALTABLE
  16184. # define sqlite3VtabClear(Y)
  16185. # define sqlite3VtabSync(X,Y) SQLITE_OK
  16186. # define sqlite3VtabRollback(X)
  16187. # define sqlite3VtabCommit(X)
  16188. # define sqlite3VtabInSync(db) 0
  16189. # define sqlite3VtabLock(X)
  16190. # define sqlite3VtabUnlock(X)
  16191. # define sqlite3VtabUnlockList(X)
  16192. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  16193. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  16194. #else
  16195. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  16196. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  16197. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  16198. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  16199. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  16200. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  16201. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  16202. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  16203. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  16204. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  16205. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  16206. SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
  16207. sqlite3*,
  16208. const char*,
  16209. const sqlite3_module*,
  16210. void*,
  16211. void(*)(void*)
  16212. );
  16213. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  16214. #endif
  16215. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
  16216. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
  16217. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  16218. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  16219. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  16220. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  16221. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  16222. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  16223. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  16224. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  16225. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  16226. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  16227. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  16228. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  16229. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  16230. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  16231. SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
  16232. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  16233. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  16234. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  16235. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  16236. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  16237. #ifndef SQLITE_OMIT_WAL
  16238. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  16239. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  16240. #endif
  16241. #ifndef SQLITE_OMIT_CTE
  16242. SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
  16243. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
  16244. SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
  16245. #else
  16246. #define sqlite3WithPush(x,y,z)
  16247. #define sqlite3WithDelete(x,y)
  16248. #endif
  16249. /* Declarations for functions in fkey.c. All of these are replaced by
  16250. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  16251. ** key functionality is available. If OMIT_TRIGGER is defined but
  16252. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  16253. ** this case foreign keys are parsed, but no other functionality is
  16254. ** provided (enforcement of FK constraints requires the triggers sub-system).
  16255. */
  16256. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  16257. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  16258. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  16259. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  16260. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  16261. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  16262. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  16263. #else
  16264. #define sqlite3FkActions(a,b,c,d,e,f)
  16265. #define sqlite3FkCheck(a,b,c,d,e,f)
  16266. #define sqlite3FkDropTable(a,b,c)
  16267. #define sqlite3FkOldmask(a,b) 0
  16268. #define sqlite3FkRequired(a,b,c,d) 0
  16269. #define sqlite3FkReferences(a) 0
  16270. #endif
  16271. #ifndef SQLITE_OMIT_FOREIGN_KEY
  16272. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  16273. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  16274. #else
  16275. #define sqlite3FkDelete(a,b)
  16276. #define sqlite3FkLocateIndex(a,b,c,d,e)
  16277. #endif
  16278. /*
  16279. ** Available fault injectors. Should be numbered beginning with 0.
  16280. */
  16281. #define SQLITE_FAULTINJECTOR_MALLOC 0
  16282. #define SQLITE_FAULTINJECTOR_COUNT 1
  16283. /*
  16284. ** The interface to the code in fault.c used for identifying "benign"
  16285. ** malloc failures. This is only present if SQLITE_UNTESTABLE
  16286. ** is not defined.
  16287. */
  16288. #ifndef SQLITE_UNTESTABLE
  16289. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  16290. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  16291. #else
  16292. #define sqlite3BeginBenignMalloc()
  16293. #define sqlite3EndBenignMalloc()
  16294. #endif
  16295. /*
  16296. ** Allowed return values from sqlite3FindInIndex()
  16297. */
  16298. #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
  16299. #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
  16300. #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
  16301. #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
  16302. #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
  16303. /*
  16304. ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
  16305. */
  16306. #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
  16307. #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
  16308. #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
  16309. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*);
  16310. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  16311. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  16312. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  16313. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  16314. #endif
  16315. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
  16316. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  16317. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
  16318. #if SQLITE_MAX_EXPR_DEPTH>0
  16319. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  16320. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  16321. #else
  16322. #define sqlite3SelectExprHeight(x) 0
  16323. #define sqlite3ExprCheckHeight(x,y)
  16324. #endif
  16325. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  16326. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  16327. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  16328. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  16329. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  16330. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  16331. #else
  16332. #define sqlite3ConnectionBlocked(x,y)
  16333. #define sqlite3ConnectionUnlocked(x)
  16334. #define sqlite3ConnectionClosed(x)
  16335. #endif
  16336. #ifdef SQLITE_DEBUG
  16337. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  16338. #endif
  16339. /*
  16340. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  16341. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  16342. ** print I/O tracing messages.
  16343. */
  16344. #ifdef SQLITE_ENABLE_IOTRACE
  16345. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  16346. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  16347. SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
  16348. #else
  16349. # define IOTRACE(A)
  16350. # define sqlite3VdbeIOTraceSql(X)
  16351. #endif
  16352. /*
  16353. ** These routines are available for the mem2.c debugging memory allocator
  16354. ** only. They are used to verify that different "types" of memory
  16355. ** allocations are properly tracked by the system.
  16356. **
  16357. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  16358. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  16359. ** a single bit set.
  16360. **
  16361. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  16362. ** argument match the type set by the previous sqlite3MemdebugSetType().
  16363. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  16364. **
  16365. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  16366. ** argument match the type set by the previous sqlite3MemdebugSetType().
  16367. **
  16368. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  16369. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  16370. ** it might have been allocated by lookaside, except the allocation was
  16371. ** too large or lookaside was already full. It is important to verify
  16372. ** that allocations that might have been satisfied by lookaside are not
  16373. ** passed back to non-lookaside free() routines. Asserts such as the
  16374. ** example above are placed on the non-lookaside free() routines to verify
  16375. ** this constraint.
  16376. **
  16377. ** All of this is no-op for a production build. It only comes into
  16378. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  16379. */
  16380. #ifdef SQLITE_MEMDEBUG
  16381. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  16382. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  16383. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  16384. #else
  16385. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  16386. # define sqlite3MemdebugHasType(X,Y) 1
  16387. # define sqlite3MemdebugNoType(X,Y) 1
  16388. #endif
  16389. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  16390. #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
  16391. #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
  16392. #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
  16393. /*
  16394. ** Threading interface
  16395. */
  16396. #if SQLITE_MAX_WORKER_THREADS>0
  16397. SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
  16398. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
  16399. #endif
  16400. #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
  16401. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
  16402. #endif
  16403. SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
  16404. SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
  16405. SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
  16406. SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
  16407. SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
  16408. #endif /* SQLITEINT_H */
  16409. /************** End of sqliteInt.h *******************************************/
  16410. /************** Begin file global.c ******************************************/
  16411. /*
  16412. ** 2008 June 13
  16413. **
  16414. ** The author disclaims copyright to this source code. In place of
  16415. ** a legal notice, here is a blessing:
  16416. **
  16417. ** May you do good and not evil.
  16418. ** May you find forgiveness for yourself and forgive others.
  16419. ** May you share freely, never taking more than you give.
  16420. **
  16421. *************************************************************************
  16422. **
  16423. ** This file contains definitions of global variables and constants.
  16424. */
  16425. /* #include "sqliteInt.h" */
  16426. /* An array to map all upper-case characters into their corresponding
  16427. ** lower-case character.
  16428. **
  16429. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  16430. ** handle case conversions for the UTF character set since the tables
  16431. ** involved are nearly as big or bigger than SQLite itself.
  16432. */
  16433. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  16434. #ifdef SQLITE_ASCII
  16435. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  16436. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  16437. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  16438. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  16439. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  16440. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  16441. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  16442. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  16443. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  16444. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  16445. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  16446. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  16447. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  16448. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  16449. 252,253,254,255
  16450. #endif
  16451. #ifdef SQLITE_EBCDIC
  16452. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  16453. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  16454. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  16455. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  16456. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  16457. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  16458. 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
  16459. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
  16460. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  16461. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
  16462. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  16463. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  16464. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  16465. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  16466. 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
  16467. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
  16468. #endif
  16469. };
  16470. /*
  16471. ** The following 256 byte lookup table is used to support SQLites built-in
  16472. ** equivalents to the following standard library functions:
  16473. **
  16474. ** isspace() 0x01
  16475. ** isalpha() 0x02
  16476. ** isdigit() 0x04
  16477. ** isalnum() 0x06
  16478. ** isxdigit() 0x08
  16479. ** toupper() 0x20
  16480. ** SQLite identifier character 0x40
  16481. ** Quote character 0x80
  16482. **
  16483. ** Bit 0x20 is set if the mapped character requires translation to upper
  16484. ** case. i.e. if the character is a lower-case ASCII character.
  16485. ** If x is a lower-case ASCII character, then its upper-case equivalent
  16486. ** is (x - 0x20). Therefore toupper() can be implemented as:
  16487. **
  16488. ** (x & ~(map[x]&0x20))
  16489. **
  16490. ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
  16491. ** array. tolower() is used more often than toupper() by SQLite.
  16492. **
  16493. ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
  16494. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  16495. ** non-ASCII UTF character. Hence the test for whether or not a character is
  16496. ** part of an identifier is 0x46.
  16497. */
  16498. #ifdef SQLITE_ASCII
  16499. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  16500. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  16501. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  16502. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  16503. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  16504. 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
  16505. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  16506. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  16507. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  16508. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  16509. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  16510. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  16511. 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  16512. 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  16513. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  16514. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  16515. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  16516. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  16517. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  16518. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  16519. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  16520. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  16521. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  16522. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  16523. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  16524. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  16525. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  16526. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  16527. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  16528. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  16529. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  16530. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  16531. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  16532. };
  16533. #endif
  16534. /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
  16535. ** compatibility for legacy applications, the URI filename capability is
  16536. ** disabled by default.
  16537. **
  16538. ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
  16539. ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
  16540. **
  16541. ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
  16542. ** disabled. The default value may be changed by compiling with the
  16543. ** SQLITE_USE_URI symbol defined.
  16544. **
  16545. ** URI filenames are enabled by default if SQLITE_HAS_CODEC is
  16546. ** enabled.
  16547. */
  16548. #ifndef SQLITE_USE_URI
  16549. # ifdef SQLITE_HAS_CODEC
  16550. # define SQLITE_USE_URI 1
  16551. # else
  16552. # define SQLITE_USE_URI 0
  16553. # endif
  16554. #endif
  16555. /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
  16556. ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
  16557. ** that compile-time option is omitted.
  16558. */
  16559. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  16560. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  16561. #endif
  16562. /* The minimum PMA size is set to this value multiplied by the database
  16563. ** page size in bytes.
  16564. */
  16565. #ifndef SQLITE_SORTER_PMASZ
  16566. # define SQLITE_SORTER_PMASZ 250
  16567. #endif
  16568. /* Statement journals spill to disk when their size exceeds the following
  16569. ** threshold (in bytes). 0 means that statement journals are created and
  16570. ** written to disk immediately (the default behavior for SQLite versions
  16571. ** before 3.12.0). -1 means always keep the entire statement journal in
  16572. ** memory. (The statement journal is also always held entirely in memory
  16573. ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
  16574. ** setting.)
  16575. */
  16576. #ifndef SQLITE_STMTJRNL_SPILL
  16577. # define SQLITE_STMTJRNL_SPILL (64*1024)
  16578. #endif
  16579. /*
  16580. ** The default lookaside-configuration, the format "SZ,N". SZ is the
  16581. ** number of bytes in each lookaside slot (should be a multiple of 8)
  16582. ** and N is the number of slots. The lookaside-configuration can be
  16583. ** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
  16584. ** or at run-time for an individual database connection using
  16585. ** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
  16586. */
  16587. #ifndef SQLITE_DEFAULT_LOOKASIDE
  16588. # define SQLITE_DEFAULT_LOOKASIDE 1200,100
  16589. #endif
  16590. /*
  16591. ** The following singleton contains the global configuration for
  16592. ** the SQLite library.
  16593. */
  16594. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  16595. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  16596. 1, /* bCoreMutex */
  16597. SQLITE_THREADSAFE==1, /* bFullMutex */
  16598. SQLITE_USE_URI, /* bOpenUri */
  16599. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  16600. 0x7ffffffe, /* mxStrlen */
  16601. 0, /* neverCorrupt */
  16602. SQLITE_DEFAULT_LOOKASIDE, /* szLookaside, nLookaside */
  16603. SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
  16604. {0,0,0,0,0,0,0,0}, /* m */
  16605. {0,0,0,0,0,0,0,0,0}, /* mutex */
  16606. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  16607. (void*)0, /* pHeap */
  16608. 0, /* nHeap */
  16609. 0, 0, /* mnHeap, mxHeap */
  16610. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  16611. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  16612. (void*)0, /* pScratch */
  16613. 0, /* szScratch */
  16614. 0, /* nScratch */
  16615. (void*)0, /* pPage */
  16616. 0, /* szPage */
  16617. SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
  16618. 0, /* mxParserStack */
  16619. 0, /* sharedCacheEnabled */
  16620. SQLITE_SORTER_PMASZ, /* szPma */
  16621. /* All the rest should always be initialized to zero */
  16622. 0, /* isInit */
  16623. 0, /* inProgress */
  16624. 0, /* isMutexInit */
  16625. 0, /* isMallocInit */
  16626. 0, /* isPCacheInit */
  16627. 0, /* nRefInitMutex */
  16628. 0, /* pInitMutex */
  16629. 0, /* xLog */
  16630. 0, /* pLogArg */
  16631. #ifdef SQLITE_ENABLE_SQLLOG
  16632. 0, /* xSqllog */
  16633. 0, /* pSqllogArg */
  16634. #endif
  16635. #ifdef SQLITE_VDBE_COVERAGE
  16636. 0, /* xVdbeBranch */
  16637. 0, /* pVbeBranchArg */
  16638. #endif
  16639. #ifndef SQLITE_UNTESTABLE
  16640. 0, /* xTestCallback */
  16641. #endif
  16642. 0, /* bLocaltimeFault */
  16643. 0x7ffffffe /* iOnceResetThreshold */
  16644. };
  16645. /*
  16646. ** Hash table for global functions - functions common to all
  16647. ** database connections. After initialization, this table is
  16648. ** read-only.
  16649. */
  16650. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  16651. /*
  16652. ** Constant tokens for values 0 and 1.
  16653. */
  16654. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  16655. { "0", 1 },
  16656. { "1", 1 }
  16657. };
  16658. /*
  16659. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  16660. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  16661. ** the database page that contains the pending byte. It never attempts
  16662. ** to read or write that page. The pending byte page is set aside
  16663. ** for use by the VFS layers as space for managing file locks.
  16664. **
  16665. ** During testing, it is often desirable to move the pending byte to
  16666. ** a different position in the file. This allows code that has to
  16667. ** deal with the pending byte to run on files that are much smaller
  16668. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  16669. ** move the pending byte.
  16670. **
  16671. ** IMPORTANT: Changing the pending byte to any value other than
  16672. ** 0x40000000 results in an incompatible database file format!
  16673. ** Changing the pending byte during operation will result in undefined
  16674. ** and incorrect behavior.
  16675. */
  16676. #ifndef SQLITE_OMIT_WSD
  16677. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  16678. #endif
  16679. /* #include "opcodes.h" */
  16680. /*
  16681. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  16682. ** created by mkopcodeh.awk during compilation. Data is obtained
  16683. ** from the comments following the "case OP_xxxx:" statements in
  16684. ** the vdbe.c file.
  16685. */
  16686. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  16687. /*
  16688. ** Name of the default collating sequence
  16689. */
  16690. SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
  16691. /************** End of global.c **********************************************/
  16692. /************** Begin file ctime.c *******************************************/
  16693. /*
  16694. ** 2010 February 23
  16695. **
  16696. ** The author disclaims copyright to this source code. In place of
  16697. ** a legal notice, here is a blessing:
  16698. **
  16699. ** May you do good and not evil.
  16700. ** May you find forgiveness for yourself and forgive others.
  16701. ** May you share freely, never taking more than you give.
  16702. **
  16703. *************************************************************************
  16704. **
  16705. ** This file implements routines used to report what compile-time options
  16706. ** SQLite was built with.
  16707. */
  16708. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  16709. /* #include "sqliteInt.h" */
  16710. /*
  16711. ** An array of names of all compile-time options. This array should
  16712. ** be sorted A-Z.
  16713. **
  16714. ** This array looks large, but in a typical installation actually uses
  16715. ** only a handful of compile-time options, so most times this array is usually
  16716. ** rather short and uses little memory space.
  16717. */
  16718. static const char * const azCompileOpt[] = {
  16719. /* These macros are provided to "stringify" the value of the define
  16720. ** for those options in which the value is meaningful. */
  16721. #define CTIMEOPT_VAL_(opt) #opt
  16722. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  16723. #if SQLITE_32BIT_ROWID
  16724. "32BIT_ROWID",
  16725. #endif
  16726. #if SQLITE_4_BYTE_ALIGNED_MALLOC
  16727. "4_BYTE_ALIGNED_MALLOC",
  16728. #endif
  16729. #if SQLITE_CASE_SENSITIVE_LIKE
  16730. "CASE_SENSITIVE_LIKE",
  16731. #endif
  16732. #if SQLITE_CHECK_PAGES
  16733. "CHECK_PAGES",
  16734. #endif
  16735. #if defined(__clang__) && defined(__clang_major__)
  16736. "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
  16737. CTIMEOPT_VAL(__clang_minor__) "."
  16738. CTIMEOPT_VAL(__clang_patchlevel__),
  16739. #elif defined(_MSC_VER)
  16740. "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
  16741. #elif defined(__GNUC__) && defined(__VERSION__)
  16742. "COMPILER=gcc-" __VERSION__,
  16743. #endif
  16744. #if SQLITE_COVERAGE_TEST
  16745. "COVERAGE_TEST",
  16746. #endif
  16747. #ifdef SQLITE_DEBUG
  16748. "DEBUG",
  16749. #endif
  16750. #if SQLITE_DEFAULT_LOCKING_MODE
  16751. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  16752. #endif
  16753. #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
  16754. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  16755. #endif
  16756. #if SQLITE_DEFAULT_SYNCHRONOUS
  16757. "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),
  16758. #endif
  16759. #if SQLITE_DEFAULT_WAL_SYNCHRONOUS
  16760. "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),
  16761. #endif
  16762. #if SQLITE_DIRECT_OVERFLOW_READ
  16763. "DIRECT_OVERFLOW_READ",
  16764. #endif
  16765. #if SQLITE_DISABLE_DIRSYNC
  16766. "DISABLE_DIRSYNC",
  16767. #endif
  16768. #if SQLITE_DISABLE_LFS
  16769. "DISABLE_LFS",
  16770. #endif
  16771. #if SQLITE_ENABLE_8_3_NAMES
  16772. "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
  16773. #endif
  16774. #if SQLITE_ENABLE_API_ARMOR
  16775. "ENABLE_API_ARMOR",
  16776. #endif
  16777. #if SQLITE_ENABLE_ATOMIC_WRITE
  16778. "ENABLE_ATOMIC_WRITE",
  16779. #endif
  16780. #if SQLITE_ENABLE_CEROD
  16781. "ENABLE_CEROD",
  16782. #endif
  16783. #if SQLITE_ENABLE_COLUMN_METADATA
  16784. "ENABLE_COLUMN_METADATA",
  16785. #endif
  16786. #if SQLITE_ENABLE_DBSTAT_VTAB
  16787. "ENABLE_DBSTAT_VTAB",
  16788. #endif
  16789. #if SQLITE_ENABLE_EXPENSIVE_ASSERT
  16790. "ENABLE_EXPENSIVE_ASSERT",
  16791. #endif
  16792. #if SQLITE_ENABLE_FTS1
  16793. "ENABLE_FTS1",
  16794. #endif
  16795. #if SQLITE_ENABLE_FTS2
  16796. "ENABLE_FTS2",
  16797. #endif
  16798. #if SQLITE_ENABLE_FTS3
  16799. "ENABLE_FTS3",
  16800. #endif
  16801. #if SQLITE_ENABLE_FTS3_PARENTHESIS
  16802. "ENABLE_FTS3_PARENTHESIS",
  16803. #endif
  16804. #if SQLITE_ENABLE_FTS4
  16805. "ENABLE_FTS4",
  16806. #endif
  16807. #if SQLITE_ENABLE_FTS5
  16808. "ENABLE_FTS5",
  16809. #endif
  16810. #if SQLITE_ENABLE_ICU
  16811. "ENABLE_ICU",
  16812. #endif
  16813. #if SQLITE_ENABLE_IOTRACE
  16814. "ENABLE_IOTRACE",
  16815. #endif
  16816. #if SQLITE_ENABLE_JSON1
  16817. "ENABLE_JSON1",
  16818. #endif
  16819. #if SQLITE_ENABLE_LOAD_EXTENSION
  16820. "ENABLE_LOAD_EXTENSION",
  16821. #endif
  16822. #if SQLITE_ENABLE_LOCKING_STYLE
  16823. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  16824. #endif
  16825. #if SQLITE_ENABLE_MEMORY_MANAGEMENT
  16826. "ENABLE_MEMORY_MANAGEMENT",
  16827. #endif
  16828. #if SQLITE_ENABLE_MEMSYS3
  16829. "ENABLE_MEMSYS3",
  16830. #endif
  16831. #if SQLITE_ENABLE_MEMSYS5
  16832. "ENABLE_MEMSYS5",
  16833. #endif
  16834. #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  16835. "ENABLE_OVERSIZE_CELL_CHECK",
  16836. #endif
  16837. #if SQLITE_ENABLE_RTREE
  16838. "ENABLE_RTREE",
  16839. #endif
  16840. #if defined(SQLITE_ENABLE_STAT4)
  16841. "ENABLE_STAT4",
  16842. #elif defined(SQLITE_ENABLE_STAT3)
  16843. "ENABLE_STAT3",
  16844. #endif
  16845. #if SQLITE_ENABLE_UNLOCK_NOTIFY
  16846. "ENABLE_UNLOCK_NOTIFY",
  16847. #endif
  16848. #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  16849. "ENABLE_UPDATE_DELETE_LIMIT",
  16850. #endif
  16851. #if defined(SQLITE_ENABLE_URI_00_ERROR)
  16852. "ENABLE_URI_00_ERROR",
  16853. #endif
  16854. #if SQLITE_HAS_CODEC
  16855. "HAS_CODEC",
  16856. #endif
  16857. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  16858. "HAVE_ISNAN",
  16859. #endif
  16860. #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  16861. "HOMEGROWN_RECURSIVE_MUTEX",
  16862. #endif
  16863. #if SQLITE_IGNORE_AFP_LOCK_ERRORS
  16864. "IGNORE_AFP_LOCK_ERRORS",
  16865. #endif
  16866. #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  16867. "IGNORE_FLOCK_LOCK_ERRORS",
  16868. #endif
  16869. #ifdef SQLITE_INT64_TYPE
  16870. "INT64_TYPE",
  16871. #endif
  16872. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  16873. "LIKE_DOESNT_MATCH_BLOBS",
  16874. #endif
  16875. #if SQLITE_LOCK_TRACE
  16876. "LOCK_TRACE",
  16877. #endif
  16878. #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
  16879. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  16880. #endif
  16881. #ifdef SQLITE_MAX_SCHEMA_RETRY
  16882. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  16883. #endif
  16884. #if SQLITE_MEMDEBUG
  16885. "MEMDEBUG",
  16886. #endif
  16887. #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  16888. "MIXED_ENDIAN_64BIT_FLOAT",
  16889. #endif
  16890. #if SQLITE_NO_SYNC
  16891. "NO_SYNC",
  16892. #endif
  16893. #if SQLITE_OMIT_ALTERTABLE
  16894. "OMIT_ALTERTABLE",
  16895. #endif
  16896. #if SQLITE_OMIT_ANALYZE
  16897. "OMIT_ANALYZE",
  16898. #endif
  16899. #if SQLITE_OMIT_ATTACH
  16900. "OMIT_ATTACH",
  16901. #endif
  16902. #if SQLITE_OMIT_AUTHORIZATION
  16903. "OMIT_AUTHORIZATION",
  16904. #endif
  16905. #if SQLITE_OMIT_AUTOINCREMENT
  16906. "OMIT_AUTOINCREMENT",
  16907. #endif
  16908. #if SQLITE_OMIT_AUTOINIT
  16909. "OMIT_AUTOINIT",
  16910. #endif
  16911. #if SQLITE_OMIT_AUTOMATIC_INDEX
  16912. "OMIT_AUTOMATIC_INDEX",
  16913. #endif
  16914. #if SQLITE_OMIT_AUTORESET
  16915. "OMIT_AUTORESET",
  16916. #endif
  16917. #if SQLITE_OMIT_AUTOVACUUM
  16918. "OMIT_AUTOVACUUM",
  16919. #endif
  16920. #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
  16921. "OMIT_BETWEEN_OPTIMIZATION",
  16922. #endif
  16923. #if SQLITE_OMIT_BLOB_LITERAL
  16924. "OMIT_BLOB_LITERAL",
  16925. #endif
  16926. #if SQLITE_OMIT_BTREECOUNT
  16927. "OMIT_BTREECOUNT",
  16928. #endif
  16929. #if SQLITE_OMIT_CAST
  16930. "OMIT_CAST",
  16931. #endif
  16932. #if SQLITE_OMIT_CHECK
  16933. "OMIT_CHECK",
  16934. #endif
  16935. #if SQLITE_OMIT_COMPLETE
  16936. "OMIT_COMPLETE",
  16937. #endif
  16938. #if SQLITE_OMIT_COMPOUND_SELECT
  16939. "OMIT_COMPOUND_SELECT",
  16940. #endif
  16941. #if SQLITE_OMIT_CTE
  16942. "OMIT_CTE",
  16943. #endif
  16944. #if SQLITE_OMIT_DATETIME_FUNCS
  16945. "OMIT_DATETIME_FUNCS",
  16946. #endif
  16947. #if SQLITE_OMIT_DECLTYPE
  16948. "OMIT_DECLTYPE",
  16949. #endif
  16950. #if SQLITE_OMIT_DEPRECATED
  16951. "OMIT_DEPRECATED",
  16952. #endif
  16953. #if SQLITE_OMIT_DISKIO
  16954. "OMIT_DISKIO",
  16955. #endif
  16956. #if SQLITE_OMIT_EXPLAIN
  16957. "OMIT_EXPLAIN",
  16958. #endif
  16959. #if SQLITE_OMIT_FLAG_PRAGMAS
  16960. "OMIT_FLAG_PRAGMAS",
  16961. #endif
  16962. #if SQLITE_OMIT_FLOATING_POINT
  16963. "OMIT_FLOATING_POINT",
  16964. #endif
  16965. #if SQLITE_OMIT_FOREIGN_KEY
  16966. "OMIT_FOREIGN_KEY",
  16967. #endif
  16968. #if SQLITE_OMIT_GET_TABLE
  16969. "OMIT_GET_TABLE",
  16970. #endif
  16971. #if SQLITE_OMIT_INCRBLOB
  16972. "OMIT_INCRBLOB",
  16973. #endif
  16974. #if SQLITE_OMIT_INTEGRITY_CHECK
  16975. "OMIT_INTEGRITY_CHECK",
  16976. #endif
  16977. #if SQLITE_OMIT_LIKE_OPTIMIZATION
  16978. "OMIT_LIKE_OPTIMIZATION",
  16979. #endif
  16980. #if SQLITE_OMIT_LOAD_EXTENSION
  16981. "OMIT_LOAD_EXTENSION",
  16982. #endif
  16983. #if SQLITE_OMIT_LOCALTIME
  16984. "OMIT_LOCALTIME",
  16985. #endif
  16986. #if SQLITE_OMIT_LOOKASIDE
  16987. "OMIT_LOOKASIDE",
  16988. #endif
  16989. #if SQLITE_OMIT_MEMORYDB
  16990. "OMIT_MEMORYDB",
  16991. #endif
  16992. #if SQLITE_OMIT_OR_OPTIMIZATION
  16993. "OMIT_OR_OPTIMIZATION",
  16994. #endif
  16995. #if SQLITE_OMIT_PAGER_PRAGMAS
  16996. "OMIT_PAGER_PRAGMAS",
  16997. #endif
  16998. #if SQLITE_OMIT_PRAGMA
  16999. "OMIT_PRAGMA",
  17000. #endif
  17001. #if SQLITE_OMIT_PROGRESS_CALLBACK
  17002. "OMIT_PROGRESS_CALLBACK",
  17003. #endif
  17004. #if SQLITE_OMIT_QUICKBALANCE
  17005. "OMIT_QUICKBALANCE",
  17006. #endif
  17007. #if SQLITE_OMIT_REINDEX
  17008. "OMIT_REINDEX",
  17009. #endif
  17010. #if SQLITE_OMIT_SCHEMA_PRAGMAS
  17011. "OMIT_SCHEMA_PRAGMAS",
  17012. #endif
  17013. #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  17014. "OMIT_SCHEMA_VERSION_PRAGMAS",
  17015. #endif
  17016. #if SQLITE_OMIT_SHARED_CACHE
  17017. "OMIT_SHARED_CACHE",
  17018. #endif
  17019. #if SQLITE_OMIT_SUBQUERY
  17020. "OMIT_SUBQUERY",
  17021. #endif
  17022. #if SQLITE_OMIT_TCL_VARIABLE
  17023. "OMIT_TCL_VARIABLE",
  17024. #endif
  17025. #if SQLITE_OMIT_TEMPDB
  17026. "OMIT_TEMPDB",
  17027. #endif
  17028. #if SQLITE_OMIT_TRACE
  17029. "OMIT_TRACE",
  17030. #endif
  17031. #if SQLITE_OMIT_TRIGGER
  17032. "OMIT_TRIGGER",
  17033. #endif
  17034. #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  17035. "OMIT_TRUNCATE_OPTIMIZATION",
  17036. #endif
  17037. #if SQLITE_OMIT_UTF16
  17038. "OMIT_UTF16",
  17039. #endif
  17040. #if SQLITE_OMIT_VACUUM
  17041. "OMIT_VACUUM",
  17042. #endif
  17043. #if SQLITE_OMIT_VIEW
  17044. "OMIT_VIEW",
  17045. #endif
  17046. #if SQLITE_OMIT_VIRTUALTABLE
  17047. "OMIT_VIRTUALTABLE",
  17048. #endif
  17049. #if SQLITE_OMIT_WAL
  17050. "OMIT_WAL",
  17051. #endif
  17052. #if SQLITE_OMIT_WSD
  17053. "OMIT_WSD",
  17054. #endif
  17055. #if SQLITE_OMIT_XFER_OPT
  17056. "OMIT_XFER_OPT",
  17057. #endif
  17058. #if SQLITE_PERFORMANCE_TRACE
  17059. "PERFORMANCE_TRACE",
  17060. #endif
  17061. #if SQLITE_PROXY_DEBUG
  17062. "PROXY_DEBUG",
  17063. #endif
  17064. #if SQLITE_RTREE_INT_ONLY
  17065. "RTREE_INT_ONLY",
  17066. #endif
  17067. #if SQLITE_SECURE_DELETE
  17068. "SECURE_DELETE",
  17069. #endif
  17070. #if SQLITE_SMALL_STACK
  17071. "SMALL_STACK",
  17072. #endif
  17073. #if SQLITE_SOUNDEX
  17074. "SOUNDEX",
  17075. #endif
  17076. #if SQLITE_SYSTEM_MALLOC
  17077. "SYSTEM_MALLOC",
  17078. #endif
  17079. #if SQLITE_TCL
  17080. "TCL",
  17081. #endif
  17082. #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
  17083. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  17084. #endif
  17085. #if SQLITE_TEST
  17086. "TEST",
  17087. #endif
  17088. #if defined(SQLITE_THREADSAFE)
  17089. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  17090. #endif
  17091. #if SQLITE_UNTESTABLE
  17092. "UNTESTABLE"
  17093. #endif
  17094. #if SQLITE_USE_ALLOCA
  17095. "USE_ALLOCA",
  17096. #endif
  17097. #if SQLITE_USER_AUTHENTICATION
  17098. "USER_AUTHENTICATION",
  17099. #endif
  17100. #if SQLITE_WIN32_MALLOC
  17101. "WIN32_MALLOC",
  17102. #endif
  17103. #if SQLITE_ZERO_MALLOC
  17104. "ZERO_MALLOC"
  17105. #endif
  17106. };
  17107. /*
  17108. ** Given the name of a compile-time option, return true if that option
  17109. ** was used and false if not.
  17110. **
  17111. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  17112. ** is not required for a match.
  17113. */
  17114. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  17115. int i, n;
  17116. #if SQLITE_ENABLE_API_ARMOR
  17117. if( zOptName==0 ){
  17118. (void)SQLITE_MISUSE_BKPT;
  17119. return 0;
  17120. }
  17121. #endif
  17122. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  17123. n = sqlite3Strlen30(zOptName);
  17124. /* Since ArraySize(azCompileOpt) is normally in single digits, a
  17125. ** linear search is adequate. No need for a binary search. */
  17126. for(i=0; i<ArraySize(azCompileOpt); i++){
  17127. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  17128. && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
  17129. ){
  17130. return 1;
  17131. }
  17132. }
  17133. return 0;
  17134. }
  17135. /*
  17136. ** Return the N-th compile-time option string. If N is out of range,
  17137. ** return a NULL pointer.
  17138. */
  17139. SQLITE_API const char *sqlite3_compileoption_get(int N){
  17140. if( N>=0 && N<ArraySize(azCompileOpt) ){
  17141. return azCompileOpt[N];
  17142. }
  17143. return 0;
  17144. }
  17145. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  17146. /************** End of ctime.c ***********************************************/
  17147. /************** Begin file status.c ******************************************/
  17148. /*
  17149. ** 2008 June 18
  17150. **
  17151. ** The author disclaims copyright to this source code. In place of
  17152. ** a legal notice, here is a blessing:
  17153. **
  17154. ** May you do good and not evil.
  17155. ** May you find forgiveness for yourself and forgive others.
  17156. ** May you share freely, never taking more than you give.
  17157. **
  17158. *************************************************************************
  17159. **
  17160. ** This module implements the sqlite3_status() interface and related
  17161. ** functionality.
  17162. */
  17163. /* #include "sqliteInt.h" */
  17164. /************** Include vdbeInt.h in the middle of status.c ******************/
  17165. /************** Begin file vdbeInt.h *****************************************/
  17166. /*
  17167. ** 2003 September 6
  17168. **
  17169. ** The author disclaims copyright to this source code. In place of
  17170. ** a legal notice, here is a blessing:
  17171. **
  17172. ** May you do good and not evil.
  17173. ** May you find forgiveness for yourself and forgive others.
  17174. ** May you share freely, never taking more than you give.
  17175. **
  17176. *************************************************************************
  17177. ** This is the header file for information that is private to the
  17178. ** VDBE. This information used to all be at the top of the single
  17179. ** source code file "vdbe.c". When that file became too big (over
  17180. ** 6000 lines long) it was split up into several smaller files and
  17181. ** this header information was factored out.
  17182. */
  17183. #ifndef SQLITE_VDBEINT_H
  17184. #define SQLITE_VDBEINT_H
  17185. /*
  17186. ** The maximum number of times that a statement will try to reparse
  17187. ** itself before giving up and returning SQLITE_SCHEMA.
  17188. */
  17189. #ifndef SQLITE_MAX_SCHEMA_RETRY
  17190. # define SQLITE_MAX_SCHEMA_RETRY 50
  17191. #endif
  17192. /*
  17193. ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
  17194. ** "explain" P4 display logic is enabled.
  17195. */
  17196. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  17197. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  17198. # define VDBE_DISPLAY_P4 1
  17199. #else
  17200. # define VDBE_DISPLAY_P4 0
  17201. #endif
  17202. /*
  17203. ** SQL is translated into a sequence of instructions to be
  17204. ** executed by a virtual machine. Each instruction is an instance
  17205. ** of the following structure.
  17206. */
  17207. typedef struct VdbeOp Op;
  17208. /*
  17209. ** Boolean values
  17210. */
  17211. typedef unsigned Bool;
  17212. /* Opaque type used by code in vdbesort.c */
  17213. typedef struct VdbeSorter VdbeSorter;
  17214. /* Elements of the linked list at Vdbe.pAuxData */
  17215. typedef struct AuxData AuxData;
  17216. /* Types of VDBE cursors */
  17217. #define CURTYPE_BTREE 0
  17218. #define CURTYPE_SORTER 1
  17219. #define CURTYPE_VTAB 2
  17220. #define CURTYPE_PSEUDO 3
  17221. /*
  17222. ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
  17223. **
  17224. ** * A b-tree cursor
  17225. ** - In the main database or in an ephemeral database
  17226. ** - On either an index or a table
  17227. ** * A sorter
  17228. ** * A virtual table
  17229. ** * A one-row "pseudotable" stored in a single register
  17230. */
  17231. typedef struct VdbeCursor VdbeCursor;
  17232. struct VdbeCursor {
  17233. u8 eCurType; /* One of the CURTYPE_* values above */
  17234. i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
  17235. u8 nullRow; /* True if pointing to a row with no data */
  17236. u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  17237. u8 isTable; /* True for rowid tables. False for indexes */
  17238. #ifdef SQLITE_DEBUG
  17239. u8 seekOp; /* Most recent seek operation on this cursor */
  17240. u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
  17241. #endif
  17242. Bool isEphemeral:1; /* True for an ephemeral table */
  17243. Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */
  17244. Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
  17245. Btree *pBtx; /* Separate file holding temporary table */
  17246. i64 seqCount; /* Sequence counter */
  17247. int *aAltMap; /* Mapping from table to index column numbers */
  17248. /* Cached OP_Column parse information is only valid if cacheStatus matches
  17249. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  17250. ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
  17251. ** the cache is out of date. */
  17252. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  17253. int seekResult; /* Result of previous sqlite3BtreeMoveto() or 0
  17254. ** if there have been no prior seeks on the cursor. */
  17255. /* NB: seekResult does not distinguish between "no seeks have ever occurred
  17256. ** on this cursor" and "the most recent seek was an exact match". */
  17257. /* When a new VdbeCursor is allocated, only the fields above are zeroed.
  17258. ** The fields that follow are uninitialized, and must be individually
  17259. ** initialized prior to first use. */
  17260. VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
  17261. union {
  17262. BtCursor *pCursor; /* CURTYPE_BTREE. Btree cursor */
  17263. sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
  17264. int pseudoTableReg; /* CURTYPE_PSEUDO. Reg holding content. */
  17265. VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
  17266. } uc;
  17267. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  17268. u32 iHdrOffset; /* Offset to next unparsed byte of the header */
  17269. Pgno pgnoRoot; /* Root page of the open btree cursor */
  17270. i16 nField; /* Number of fields in the header */
  17271. u16 nHdrParsed; /* Number of header fields parsed so far */
  17272. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  17273. u32 *aOffset; /* Pointer to aType[nField] */
  17274. const u8 *aRow; /* Data for the current row, if all on one page */
  17275. u32 payloadSize; /* Total number of bytes in the record */
  17276. u32 szRow; /* Byte available in aRow */
  17277. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  17278. u64 maskUsed; /* Mask of columns used by this cursor */
  17279. #endif
  17280. /* 2*nField extra array elements allocated for aType[], beyond the one
  17281. ** static element declared in the structure. nField total array slots for
  17282. ** aType[] and nField+1 array slots for aOffset[] */
  17283. u32 aType[1]; /* Type values record decode. MUST BE LAST */
  17284. };
  17285. /*
  17286. ** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
  17287. */
  17288. #define CACHE_STALE 0
  17289. /*
  17290. ** When a sub-program is executed (OP_Program), a structure of this type
  17291. ** is allocated to store the current value of the program counter, as
  17292. ** well as the current memory cell array and various other frame specific
  17293. ** values stored in the Vdbe struct. When the sub-program is finished,
  17294. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  17295. ** restoring the state of the VM to as it was before the sub-program
  17296. ** began executing.
  17297. **
  17298. ** The memory for a VdbeFrame object is allocated and managed by a memory
  17299. ** cell in the parent (calling) frame. When the memory cell is deleted or
  17300. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  17301. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  17302. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  17303. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  17304. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  17305. ** child frame are released.
  17306. **
  17307. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  17308. ** set to NULL if the currently executing frame is the main program.
  17309. */
  17310. typedef struct VdbeFrame VdbeFrame;
  17311. struct VdbeFrame {
  17312. Vdbe *v; /* VM this frame belongs to */
  17313. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  17314. Op *aOp; /* Program instructions for parent frame */
  17315. i64 *anExec; /* Event counters from parent frame */
  17316. Mem *aMem; /* Array of memory cells for parent frame */
  17317. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  17318. u8 *aOnce; /* Bitmask used by OP_Once */
  17319. void *token; /* Copy of SubProgram.token */
  17320. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  17321. AuxData *pAuxData; /* Linked list of auxdata allocations */
  17322. int nCursor; /* Number of entries in apCsr */
  17323. int pc; /* Program Counter in parent (calling) frame */
  17324. int nOp; /* Size of aOp array */
  17325. int nMem; /* Number of entries in aMem */
  17326. int nChildMem; /* Number of memory cells for child frame */
  17327. int nChildCsr; /* Number of cursors for child frame */
  17328. int nChange; /* Statement changes (Vdbe.nChange) */
  17329. int nDbChange; /* Value of db->nChange */
  17330. };
  17331. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  17332. /*
  17333. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  17334. ** structures. Each Mem struct may cache multiple representations (string,
  17335. ** integer etc.) of the same value.
  17336. */
  17337. struct sqlite3_value {
  17338. union MemValue {
  17339. double r; /* Real value used when MEM_Real is set in flags */
  17340. i64 i; /* Integer value used when MEM_Int is set in flags */
  17341. int nZero; /* Used when bit MEM_Zero is set in flags */
  17342. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  17343. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  17344. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  17345. } u;
  17346. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  17347. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  17348. u8 eSubtype; /* Subtype for this value */
  17349. int n; /* Number of characters in string value, excluding '\0' */
  17350. char *z; /* String or BLOB value */
  17351. /* ShallowCopy only needs to copy the information above */
  17352. char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
  17353. int szMalloc; /* Size of the zMalloc allocation */
  17354. u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
  17355. sqlite3 *db; /* The associated database connection */
  17356. void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
  17357. #ifdef SQLITE_DEBUG
  17358. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  17359. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  17360. #endif
  17361. };
  17362. /*
  17363. ** Size of struct Mem not including the Mem.zMalloc member or anything that
  17364. ** follows.
  17365. */
  17366. #define MEMCELLSIZE offsetof(Mem,zMalloc)
  17367. /* One or more of the following flags are set to indicate the validOK
  17368. ** representations of the value stored in the Mem struct.
  17369. **
  17370. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  17371. ** No other flags may be set in this case.
  17372. **
  17373. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  17374. ** Usually this is encoded in the same unicode encoding as the main
  17375. ** database (see below for exceptions). If the MEM_Term flag is also
  17376. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  17377. ** flags may coexist with the MEM_Str flag.
  17378. */
  17379. #define MEM_Null 0x0001 /* Value is NULL */
  17380. #define MEM_Str 0x0002 /* Value is a string */
  17381. #define MEM_Int 0x0004 /* Value is an integer */
  17382. #define MEM_Real 0x0008 /* Value is a real number */
  17383. #define MEM_Blob 0x0010 /* Value is a BLOB */
  17384. #define MEM_AffMask 0x001f /* Mask of affinity bits */
  17385. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  17386. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  17387. #define MEM_Undefined 0x0080 /* Value is undefined */
  17388. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  17389. #define MEM_TypeMask 0x81ff /* Mask of type bits */
  17390. /* Whenever Mem contains a valid string or blob representation, one of
  17391. ** the following flags must be set to determine the memory management
  17392. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  17393. ** string is \000 or \u0000 terminated
  17394. */
  17395. #define MEM_Term 0x0200 /* String rep is nul terminated */
  17396. #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
  17397. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  17398. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  17399. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  17400. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  17401. #define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */
  17402. #ifdef SQLITE_OMIT_INCRBLOB
  17403. #undef MEM_Zero
  17404. #define MEM_Zero 0x0000
  17405. #endif
  17406. /* Return TRUE if Mem X contains dynamically allocated content - anything
  17407. ** that needs to be deallocated to avoid a leak.
  17408. */
  17409. #define VdbeMemDynamic(X) \
  17410. (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
  17411. /*
  17412. ** Clear any existing type flags from a Mem and replace them with f
  17413. */
  17414. #define MemSetTypeFlag(p, f) \
  17415. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  17416. /*
  17417. ** Return true if a memory cell is not marked as invalid. This macro
  17418. ** is for use inside assert() statements only.
  17419. */
  17420. #ifdef SQLITE_DEBUG
  17421. #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
  17422. #endif
  17423. /*
  17424. ** Each auxiliary data pointer stored by a user defined function
  17425. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  17426. ** of this structure. All such structures associated with a single VM
  17427. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  17428. ** when the VM is halted (if not before).
  17429. */
  17430. struct AuxData {
  17431. int iAuxOp; /* Instruction number of OP_Function opcode */
  17432. int iAuxArg; /* Index of function argument. */
  17433. void *pAux; /* Aux data pointer */
  17434. void (*xDeleteAux)(void*); /* Destructor for the aux data */
  17435. AuxData *pNextAux; /* Next element in list */
  17436. };
  17437. /*
  17438. ** The "context" argument for an installable function. A pointer to an
  17439. ** instance of this structure is the first argument to the routines used
  17440. ** implement the SQL functions.
  17441. **
  17442. ** There is a typedef for this structure in sqlite.h. So all routines,
  17443. ** even the public interface to SQLite, can use a pointer to this structure.
  17444. ** But this file is the only place where the internal details of this
  17445. ** structure are known.
  17446. **
  17447. ** This structure is defined inside of vdbeInt.h because it uses substructures
  17448. ** (Mem) which are only defined there.
  17449. */
  17450. struct sqlite3_context {
  17451. Mem *pOut; /* The return value is stored here */
  17452. FuncDef *pFunc; /* Pointer to function information */
  17453. Mem *pMem; /* Memory cell used to store aggregate context */
  17454. Vdbe *pVdbe; /* The VM that owns this context */
  17455. int iOp; /* Instruction number of OP_Function */
  17456. int isError; /* Error code returned by the function. */
  17457. u8 skipFlag; /* Skip accumulator loading if true */
  17458. u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
  17459. u8 argc; /* Number of arguments */
  17460. sqlite3_value *argv[1]; /* Argument set */
  17461. };
  17462. /* A bitfield type for use inside of structures. Always follow with :N where
  17463. ** N is the number of bits.
  17464. */
  17465. typedef unsigned bft; /* Bit Field Type */
  17466. typedef struct ScanStatus ScanStatus;
  17467. struct ScanStatus {
  17468. int addrExplain; /* OP_Explain for loop */
  17469. int addrLoop; /* Address of "loops" counter */
  17470. int addrVisit; /* Address of "rows visited" counter */
  17471. int iSelectID; /* The "Select-ID" for this loop */
  17472. LogEst nEst; /* Estimated output rows per loop */
  17473. char *zName; /* Name of table or index */
  17474. };
  17475. /*
  17476. ** An instance of the virtual machine. This structure contains the complete
  17477. ** state of the virtual machine.
  17478. **
  17479. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  17480. ** is really a pointer to an instance of this structure.
  17481. */
  17482. struct Vdbe {
  17483. sqlite3 *db; /* The database connection that owns this statement */
  17484. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  17485. Parse *pParse; /* Parsing context used to create this Vdbe */
  17486. ynVar nVar; /* Number of entries in aVar[] */
  17487. u32 magic; /* Magic number for sanity checking */
  17488. int nMem; /* Number of memory locations currently allocated */
  17489. int nCursor; /* Number of slots in apCsr[] */
  17490. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  17491. int pc; /* The program counter */
  17492. int rc; /* Value to return */
  17493. int nChange; /* Number of db changes made since last reset */
  17494. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  17495. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  17496. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  17497. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  17498. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  17499. /* When allocating a new Vdbe object, all of the fields below should be
  17500. ** initialized to zero or NULL */
  17501. Op *aOp; /* Space to hold the virtual machine's program */
  17502. Mem *aMem; /* The memory locations */
  17503. Mem **apArg; /* Arguments to currently executing user function */
  17504. Mem *aColName; /* Column names to return */
  17505. Mem *pResultSet; /* Pointer to an array of results */
  17506. char *zErrMsg; /* Error message written here */
  17507. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  17508. Mem *aVar; /* Values for the OP_Variable opcode. */
  17509. VList *pVList; /* Name of variables */
  17510. #ifndef SQLITE_OMIT_TRACE
  17511. i64 startTime; /* Time when query started - used for profiling */
  17512. #endif
  17513. int nOp; /* Number of instructions in the program */
  17514. #ifdef SQLITE_DEBUG
  17515. int rcApp; /* errcode set by sqlite3_result_error_code() */
  17516. #endif
  17517. u16 nResColumn; /* Number of columns in one row of the result set */
  17518. u8 errorAction; /* Recovery action to do in case of an error */
  17519. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  17520. bft expired:1; /* True if the VM needs to be recompiled */
  17521. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  17522. bft explain:2; /* True if EXPLAIN present on SQL command */
  17523. bft changeCntOn:1; /* True to update the change-counter */
  17524. bft runOnlyOnce:1; /* Automatically expire on reset */
  17525. bft usesStmtJournal:1; /* True if uses a statement journal */
  17526. bft readOnly:1; /* True for statements that do not write */
  17527. bft bIsReader:1; /* True for statements that read */
  17528. bft isPrepareV2:1; /* True if prepared with prepare_v2() */
  17529. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  17530. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  17531. u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
  17532. char *zSql; /* Text of the SQL statement that generated this */
  17533. void *pFree; /* Free this when deleting the vdbe */
  17534. VdbeFrame *pFrame; /* Parent frame */
  17535. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  17536. int nFrame; /* Number of frames in pFrame list */
  17537. u32 expmask; /* Binding to these vars invalidates VM */
  17538. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  17539. AuxData *pAuxData; /* Linked list of auxdata allocations */
  17540. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  17541. i64 *anExec; /* Number of times each op has been executed */
  17542. int nScan; /* Entries in aScan[] */
  17543. ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
  17544. #endif
  17545. };
  17546. /*
  17547. ** The following are allowed values for Vdbe.magic
  17548. */
  17549. #define VDBE_MAGIC_INIT 0x16bceaa5 /* Building a VDBE program */
  17550. #define VDBE_MAGIC_RUN 0x2df20da3 /* VDBE is ready to execute */
  17551. #define VDBE_MAGIC_HALT 0x319c2973 /* VDBE has completed execution */
  17552. #define VDBE_MAGIC_RESET 0x48fa9f76 /* Reset and ready to run again */
  17553. #define VDBE_MAGIC_DEAD 0x5606c3c8 /* The VDBE has been deallocated */
  17554. /*
  17555. ** Structure used to store the context required by the
  17556. ** sqlite3_preupdate_*() API functions.
  17557. */
  17558. struct PreUpdate {
  17559. Vdbe *v;
  17560. VdbeCursor *pCsr; /* Cursor to read old values from */
  17561. int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
  17562. u8 *aRecord; /* old.* database record */
  17563. KeyInfo keyinfo;
  17564. UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
  17565. UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
  17566. int iNewReg; /* Register for new.* values */
  17567. i64 iKey1; /* First key value passed to hook */
  17568. i64 iKey2; /* Second key value passed to hook */
  17569. Mem *aNew; /* Array of new.* values */
  17570. Table *pTab; /* Schema object being upated */
  17571. Index *pPk; /* PK index if pTab is WITHOUT ROWID */
  17572. };
  17573. /*
  17574. ** Function prototypes
  17575. */
  17576. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
  17577. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  17578. void sqliteVdbePopStack(Vdbe*,int);
  17579. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
  17580. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
  17581. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  17582. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  17583. #endif
  17584. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  17585. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
  17586. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
  17587. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
  17588. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  17589. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
  17590. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  17591. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
  17592. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
  17593. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  17594. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  17595. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  17596. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  17597. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  17598. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  17599. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  17600. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  17601. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  17602. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  17603. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  17604. #ifdef SQLITE_OMIT_FLOATING_POINT
  17605. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  17606. #else
  17607. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  17608. #endif
  17609. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
  17610. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  17611. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  17612. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  17613. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  17614. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
  17615. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  17616. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  17617. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  17618. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  17619. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  17620. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  17621. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
  17622. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
  17623. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  17624. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  17625. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  17626. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  17627. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
  17628. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  17629. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  17630. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  17631. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  17632. SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
  17633. #endif
  17634. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  17635. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
  17636. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
  17637. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  17638. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  17639. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
  17640. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
  17641. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
  17642. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
  17643. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  17644. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  17645. #else
  17646. # define sqlite3VdbeEnter(X)
  17647. #endif
  17648. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  17649. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  17650. #else
  17651. # define sqlite3VdbeLeave(X)
  17652. #endif
  17653. #ifdef SQLITE_DEBUG
  17654. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  17655. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
  17656. #endif
  17657. #ifndef SQLITE_OMIT_FOREIGN_KEY
  17658. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  17659. #else
  17660. # define sqlite3VdbeCheckFk(p,i) 0
  17661. #endif
  17662. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  17663. #ifdef SQLITE_DEBUG
  17664. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  17665. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  17666. #endif
  17667. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  17668. #ifndef SQLITE_OMIT_INCRBLOB
  17669. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  17670. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  17671. #else
  17672. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  17673. #define ExpandBlob(P) SQLITE_OK
  17674. #endif
  17675. #endif /* !defined(SQLITE_VDBEINT_H) */
  17676. /************** End of vdbeInt.h *********************************************/
  17677. /************** Continuing where we left off in status.c *********************/
  17678. /*
  17679. ** Variables in which to record status information.
  17680. */
  17681. #if SQLITE_PTRSIZE>4
  17682. typedef sqlite3_int64 sqlite3StatValueType;
  17683. #else
  17684. typedef u32 sqlite3StatValueType;
  17685. #endif
  17686. typedef struct sqlite3StatType sqlite3StatType;
  17687. static SQLITE_WSD struct sqlite3StatType {
  17688. sqlite3StatValueType nowValue[10]; /* Current value */
  17689. sqlite3StatValueType mxValue[10]; /* Maximum value */
  17690. } sqlite3Stat = { {0,}, {0,} };
  17691. /*
  17692. ** Elements of sqlite3Stat[] are protected by either the memory allocator
  17693. ** mutex, or by the pcache1 mutex. The following array determines which.
  17694. */
  17695. static const char statMutex[] = {
  17696. 0, /* SQLITE_STATUS_MEMORY_USED */
  17697. 1, /* SQLITE_STATUS_PAGECACHE_USED */
  17698. 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
  17699. 0, /* SQLITE_STATUS_SCRATCH_USED */
  17700. 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
  17701. 0, /* SQLITE_STATUS_MALLOC_SIZE */
  17702. 0, /* SQLITE_STATUS_PARSER_STACK */
  17703. 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
  17704. 0, /* SQLITE_STATUS_SCRATCH_SIZE */
  17705. 0, /* SQLITE_STATUS_MALLOC_COUNT */
  17706. };
  17707. /* The "wsdStat" macro will resolve to the status information
  17708. ** state vector. If writable static data is unsupported on the target,
  17709. ** we have to locate the state vector at run-time. In the more common
  17710. ** case where writable static data is supported, wsdStat can refer directly
  17711. ** to the "sqlite3Stat" state vector declared above.
  17712. */
  17713. #ifdef SQLITE_OMIT_WSD
  17714. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  17715. # define wsdStat x[0]
  17716. #else
  17717. # define wsdStatInit
  17718. # define wsdStat sqlite3Stat
  17719. #endif
  17720. /*
  17721. ** Return the current value of a status parameter. The caller must
  17722. ** be holding the appropriate mutex.
  17723. */
  17724. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
  17725. wsdStatInit;
  17726. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  17727. assert( op>=0 && op<ArraySize(statMutex) );
  17728. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  17729. : sqlite3MallocMutex()) );
  17730. return wsdStat.nowValue[op];
  17731. }
  17732. /*
  17733. ** Add N to the value of a status record. The caller must hold the
  17734. ** appropriate mutex. (Locking is checked by assert()).
  17735. **
  17736. ** The StatusUp() routine can accept positive or negative values for N.
  17737. ** The value of N is added to the current status value and the high-water
  17738. ** mark is adjusted if necessary.
  17739. **
  17740. ** The StatusDown() routine lowers the current value by N. The highwater
  17741. ** mark is unchanged. N must be non-negative for StatusDown().
  17742. */
  17743. SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
  17744. wsdStatInit;
  17745. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  17746. assert( op>=0 && op<ArraySize(statMutex) );
  17747. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  17748. : sqlite3MallocMutex()) );
  17749. wsdStat.nowValue[op] += N;
  17750. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  17751. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  17752. }
  17753. }
  17754. SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
  17755. wsdStatInit;
  17756. assert( N>=0 );
  17757. assert( op>=0 && op<ArraySize(statMutex) );
  17758. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  17759. : sqlite3MallocMutex()) );
  17760. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  17761. wsdStat.nowValue[op] -= N;
  17762. }
  17763. /*
  17764. ** Adjust the highwater mark if necessary.
  17765. ** The caller must hold the appropriate mutex.
  17766. */
  17767. SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
  17768. sqlite3StatValueType newValue;
  17769. wsdStatInit;
  17770. assert( X>=0 );
  17771. newValue = (sqlite3StatValueType)X;
  17772. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  17773. assert( op>=0 && op<ArraySize(statMutex) );
  17774. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  17775. : sqlite3MallocMutex()) );
  17776. assert( op==SQLITE_STATUS_MALLOC_SIZE
  17777. || op==SQLITE_STATUS_PAGECACHE_SIZE
  17778. || op==SQLITE_STATUS_SCRATCH_SIZE
  17779. || op==SQLITE_STATUS_PARSER_STACK );
  17780. if( newValue>wsdStat.mxValue[op] ){
  17781. wsdStat.mxValue[op] = newValue;
  17782. }
  17783. }
  17784. /*
  17785. ** Query status information.
  17786. */
  17787. SQLITE_API int sqlite3_status64(
  17788. int op,
  17789. sqlite3_int64 *pCurrent,
  17790. sqlite3_int64 *pHighwater,
  17791. int resetFlag
  17792. ){
  17793. sqlite3_mutex *pMutex;
  17794. wsdStatInit;
  17795. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  17796. return SQLITE_MISUSE_BKPT;
  17797. }
  17798. #ifdef SQLITE_ENABLE_API_ARMOR
  17799. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  17800. #endif
  17801. pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
  17802. sqlite3_mutex_enter(pMutex);
  17803. *pCurrent = wsdStat.nowValue[op];
  17804. *pHighwater = wsdStat.mxValue[op];
  17805. if( resetFlag ){
  17806. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  17807. }
  17808. sqlite3_mutex_leave(pMutex);
  17809. (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
  17810. return SQLITE_OK;
  17811. }
  17812. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  17813. sqlite3_int64 iCur = 0, iHwtr = 0;
  17814. int rc;
  17815. #ifdef SQLITE_ENABLE_API_ARMOR
  17816. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  17817. #endif
  17818. rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
  17819. if( rc==0 ){
  17820. *pCurrent = (int)iCur;
  17821. *pHighwater = (int)iHwtr;
  17822. }
  17823. return rc;
  17824. }
  17825. /*
  17826. ** Query status information for a single database connection
  17827. */
  17828. SQLITE_API int sqlite3_db_status(
  17829. sqlite3 *db, /* The database connection whose status is desired */
  17830. int op, /* Status verb */
  17831. int *pCurrent, /* Write current value here */
  17832. int *pHighwater, /* Write high-water mark here */
  17833. int resetFlag /* Reset high-water mark if true */
  17834. ){
  17835. int rc = SQLITE_OK; /* Return code */
  17836. #ifdef SQLITE_ENABLE_API_ARMOR
  17837. if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
  17838. return SQLITE_MISUSE_BKPT;
  17839. }
  17840. #endif
  17841. sqlite3_mutex_enter(db->mutex);
  17842. switch( op ){
  17843. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  17844. *pCurrent = db->lookaside.nOut;
  17845. *pHighwater = db->lookaside.mxOut;
  17846. if( resetFlag ){
  17847. db->lookaside.mxOut = db->lookaside.nOut;
  17848. }
  17849. break;
  17850. }
  17851. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  17852. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  17853. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  17854. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  17855. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  17856. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  17857. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  17858. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  17859. *pCurrent = 0;
  17860. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  17861. if( resetFlag ){
  17862. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  17863. }
  17864. break;
  17865. }
  17866. /*
  17867. ** Return an approximation for the amount of memory currently used
  17868. ** by all pagers associated with the given database connection. The
  17869. ** highwater mark is meaningless and is returned as zero.
  17870. */
  17871. case SQLITE_DBSTATUS_CACHE_USED_SHARED:
  17872. case SQLITE_DBSTATUS_CACHE_USED: {
  17873. int totalUsed = 0;
  17874. int i;
  17875. sqlite3BtreeEnterAll(db);
  17876. for(i=0; i<db->nDb; i++){
  17877. Btree *pBt = db->aDb[i].pBt;
  17878. if( pBt ){
  17879. Pager *pPager = sqlite3BtreePager(pBt);
  17880. int nByte = sqlite3PagerMemUsed(pPager);
  17881. if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
  17882. nByte = nByte / sqlite3BtreeConnectionCount(pBt);
  17883. }
  17884. totalUsed += nByte;
  17885. }
  17886. }
  17887. sqlite3BtreeLeaveAll(db);
  17888. *pCurrent = totalUsed;
  17889. *pHighwater = 0;
  17890. break;
  17891. }
  17892. /*
  17893. ** *pCurrent gets an accurate estimate of the amount of memory used
  17894. ** to store the schema for all databases (main, temp, and any ATTACHed
  17895. ** databases. *pHighwater is set to zero.
  17896. */
  17897. case SQLITE_DBSTATUS_SCHEMA_USED: {
  17898. int i; /* Used to iterate through schemas */
  17899. int nByte = 0; /* Used to accumulate return value */
  17900. sqlite3BtreeEnterAll(db);
  17901. db->pnBytesFreed = &nByte;
  17902. for(i=0; i<db->nDb; i++){
  17903. Schema *pSchema = db->aDb[i].pSchema;
  17904. if( ALWAYS(pSchema!=0) ){
  17905. HashElem *p;
  17906. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  17907. pSchema->tblHash.count
  17908. + pSchema->trigHash.count
  17909. + pSchema->idxHash.count
  17910. + pSchema->fkeyHash.count
  17911. );
  17912. nByte += sqlite3_msize(pSchema->tblHash.ht);
  17913. nByte += sqlite3_msize(pSchema->trigHash.ht);
  17914. nByte += sqlite3_msize(pSchema->idxHash.ht);
  17915. nByte += sqlite3_msize(pSchema->fkeyHash.ht);
  17916. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  17917. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  17918. }
  17919. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  17920. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  17921. }
  17922. }
  17923. }
  17924. db->pnBytesFreed = 0;
  17925. sqlite3BtreeLeaveAll(db);
  17926. *pHighwater = 0;
  17927. *pCurrent = nByte;
  17928. break;
  17929. }
  17930. /*
  17931. ** *pCurrent gets an accurate estimate of the amount of memory used
  17932. ** to store all prepared statements.
  17933. ** *pHighwater is set to zero.
  17934. */
  17935. case SQLITE_DBSTATUS_STMT_USED: {
  17936. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  17937. int nByte = 0; /* Used to accumulate return value */
  17938. db->pnBytesFreed = &nByte;
  17939. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  17940. sqlite3VdbeClearObject(db, pVdbe);
  17941. sqlite3DbFree(db, pVdbe);
  17942. }
  17943. db->pnBytesFreed = 0;
  17944. *pHighwater = 0; /* IMP: R-64479-57858 */
  17945. *pCurrent = nByte;
  17946. break;
  17947. }
  17948. /*
  17949. ** Set *pCurrent to the total cache hits or misses encountered by all
  17950. ** pagers the database handle is connected to. *pHighwater is always set
  17951. ** to zero.
  17952. */
  17953. case SQLITE_DBSTATUS_CACHE_HIT:
  17954. case SQLITE_DBSTATUS_CACHE_MISS:
  17955. case SQLITE_DBSTATUS_CACHE_WRITE:{
  17956. int i;
  17957. int nRet = 0;
  17958. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  17959. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  17960. for(i=0; i<db->nDb; i++){
  17961. if( db->aDb[i].pBt ){
  17962. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  17963. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  17964. }
  17965. }
  17966. *pHighwater = 0; /* IMP: R-42420-56072 */
  17967. /* IMP: R-54100-20147 */
  17968. /* IMP: R-29431-39229 */
  17969. *pCurrent = nRet;
  17970. break;
  17971. }
  17972. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  17973. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  17974. ** have been satisfied. The *pHighwater is always set to zero.
  17975. */
  17976. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  17977. *pHighwater = 0; /* IMP: R-11967-56545 */
  17978. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  17979. break;
  17980. }
  17981. default: {
  17982. rc = SQLITE_ERROR;
  17983. }
  17984. }
  17985. sqlite3_mutex_leave(db->mutex);
  17986. return rc;
  17987. }
  17988. /************** End of status.c **********************************************/
  17989. /************** Begin file date.c ********************************************/
  17990. /*
  17991. ** 2003 October 31
  17992. **
  17993. ** The author disclaims copyright to this source code. In place of
  17994. ** a legal notice, here is a blessing:
  17995. **
  17996. ** May you do good and not evil.
  17997. ** May you find forgiveness for yourself and forgive others.
  17998. ** May you share freely, never taking more than you give.
  17999. **
  18000. *************************************************************************
  18001. ** This file contains the C functions that implement date and time
  18002. ** functions for SQLite.
  18003. **
  18004. ** There is only one exported symbol in this file - the function
  18005. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  18006. ** All other code has file scope.
  18007. **
  18008. ** SQLite processes all times and dates as julian day numbers. The
  18009. ** dates and times are stored as the number of days since noon
  18010. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  18011. ** calendar system.
  18012. **
  18013. ** 1970-01-01 00:00:00 is JD 2440587.5
  18014. ** 2000-01-01 00:00:00 is JD 2451544.5
  18015. **
  18016. ** This implementation requires years to be expressed as a 4-digit number
  18017. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  18018. ** be represented, even though julian day numbers allow a much wider
  18019. ** range of dates.
  18020. **
  18021. ** The Gregorian calendar system is used for all dates and times,
  18022. ** even those that predate the Gregorian calendar. Historians usually
  18023. ** use the julian calendar for dates prior to 1582-10-15 and for some
  18024. ** dates afterwards, depending on locale. Beware of this difference.
  18025. **
  18026. ** The conversion algorithms are implemented based on descriptions
  18027. ** in the following text:
  18028. **
  18029. ** Jean Meeus
  18030. ** Astronomical Algorithms, 2nd Edition, 1998
  18031. ** ISBM 0-943396-61-1
  18032. ** Willmann-Bell, Inc
  18033. ** Richmond, Virginia (USA)
  18034. */
  18035. /* #include "sqliteInt.h" */
  18036. /* #include <stdlib.h> */
  18037. /* #include <assert.h> */
  18038. #include <time.h>
  18039. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  18040. /*
  18041. ** The MSVC CRT on Windows CE may not have a localtime() function.
  18042. ** So declare a substitute. The substitute function itself is
  18043. ** defined in "os_win.c".
  18044. */
  18045. #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
  18046. (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
  18047. struct tm *__cdecl localtime(const time_t *);
  18048. #endif
  18049. /*
  18050. ** A structure for holding a single date and time.
  18051. */
  18052. typedef struct DateTime DateTime;
  18053. struct DateTime {
  18054. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  18055. int Y, M, D; /* Year, month, and day */
  18056. int h, m; /* Hour and minutes */
  18057. int tz; /* Timezone offset in minutes */
  18058. double s; /* Seconds */
  18059. char validJD; /* True (1) if iJD is valid */
  18060. char rawS; /* Raw numeric value stored in s */
  18061. char validYMD; /* True (1) if Y,M,D are valid */
  18062. char validHMS; /* True (1) if h,m,s are valid */
  18063. char validTZ; /* True (1) if tz is valid */
  18064. char tzSet; /* Timezone was set explicitly */
  18065. char isError; /* An overflow has occurred */
  18066. };
  18067. /*
  18068. ** Convert zDate into one or more integers according to the conversion
  18069. ** specifier zFormat.
  18070. **
  18071. ** zFormat[] contains 4 characters for each integer converted, except for
  18072. ** the last integer which is specified by three characters. The meaning
  18073. ** of a four-character format specifiers ABCD is:
  18074. **
  18075. ** A: number of digits to convert. Always "2" or "4".
  18076. ** B: minimum value. Always "0" or "1".
  18077. ** C: maximum value, decoded as:
  18078. ** a: 12
  18079. ** b: 14
  18080. ** c: 24
  18081. ** d: 31
  18082. ** e: 59
  18083. ** f: 9999
  18084. ** D: the separator character, or \000 to indicate this is the
  18085. ** last number to convert.
  18086. **
  18087. ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
  18088. ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
  18089. ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
  18090. ** the 2-digit day which is the last integer in the set.
  18091. **
  18092. ** The function returns the number of successful conversions.
  18093. */
  18094. static int getDigits(const char *zDate, const char *zFormat, ...){
  18095. /* The aMx[] array translates the 3rd character of each format
  18096. ** spec into a max size: a b c d e f */
  18097. static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
  18098. va_list ap;
  18099. int cnt = 0;
  18100. char nextC;
  18101. va_start(ap, zFormat);
  18102. do{
  18103. char N = zFormat[0] - '0';
  18104. char min = zFormat[1] - '0';
  18105. int val = 0;
  18106. u16 max;
  18107. assert( zFormat[2]>='a' && zFormat[2]<='f' );
  18108. max = aMx[zFormat[2] - 'a'];
  18109. nextC = zFormat[3];
  18110. val = 0;
  18111. while( N-- ){
  18112. if( !sqlite3Isdigit(*zDate) ){
  18113. goto end_getDigits;
  18114. }
  18115. val = val*10 + *zDate - '0';
  18116. zDate++;
  18117. }
  18118. if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
  18119. goto end_getDigits;
  18120. }
  18121. *va_arg(ap,int*) = val;
  18122. zDate++;
  18123. cnt++;
  18124. zFormat += 4;
  18125. }while( nextC );
  18126. end_getDigits:
  18127. va_end(ap);
  18128. return cnt;
  18129. }
  18130. /*
  18131. ** Parse a timezone extension on the end of a date-time.
  18132. ** The extension is of the form:
  18133. **
  18134. ** (+/-)HH:MM
  18135. **
  18136. ** Or the "zulu" notation:
  18137. **
  18138. ** Z
  18139. **
  18140. ** If the parse is successful, write the number of minutes
  18141. ** of change in p->tz and return 0. If a parser error occurs,
  18142. ** return non-zero.
  18143. **
  18144. ** A missing specifier is not considered an error.
  18145. */
  18146. static int parseTimezone(const char *zDate, DateTime *p){
  18147. int sgn = 0;
  18148. int nHr, nMn;
  18149. int c;
  18150. while( sqlite3Isspace(*zDate) ){ zDate++; }
  18151. p->tz = 0;
  18152. c = *zDate;
  18153. if( c=='-' ){
  18154. sgn = -1;
  18155. }else if( c=='+' ){
  18156. sgn = +1;
  18157. }else if( c=='Z' || c=='z' ){
  18158. zDate++;
  18159. goto zulu_time;
  18160. }else{
  18161. return c!=0;
  18162. }
  18163. zDate++;
  18164. if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
  18165. return 1;
  18166. }
  18167. zDate += 5;
  18168. p->tz = sgn*(nMn + nHr*60);
  18169. zulu_time:
  18170. while( sqlite3Isspace(*zDate) ){ zDate++; }
  18171. p->tzSet = 1;
  18172. return *zDate!=0;
  18173. }
  18174. /*
  18175. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  18176. ** The HH, MM, and SS must each be exactly 2 digits. The
  18177. ** fractional seconds FFFF can be one or more digits.
  18178. **
  18179. ** Return 1 if there is a parsing error and 0 on success.
  18180. */
  18181. static int parseHhMmSs(const char *zDate, DateTime *p){
  18182. int h, m, s;
  18183. double ms = 0.0;
  18184. if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
  18185. return 1;
  18186. }
  18187. zDate += 5;
  18188. if( *zDate==':' ){
  18189. zDate++;
  18190. if( getDigits(zDate, "20e", &s)!=1 ){
  18191. return 1;
  18192. }
  18193. zDate += 2;
  18194. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  18195. double rScale = 1.0;
  18196. zDate++;
  18197. while( sqlite3Isdigit(*zDate) ){
  18198. ms = ms*10.0 + *zDate - '0';
  18199. rScale *= 10.0;
  18200. zDate++;
  18201. }
  18202. ms /= rScale;
  18203. }
  18204. }else{
  18205. s = 0;
  18206. }
  18207. p->validJD = 0;
  18208. p->rawS = 0;
  18209. p->validHMS = 1;
  18210. p->h = h;
  18211. p->m = m;
  18212. p->s = s + ms;
  18213. if( parseTimezone(zDate, p) ) return 1;
  18214. p->validTZ = (p->tz!=0)?1:0;
  18215. return 0;
  18216. }
  18217. /*
  18218. ** Put the DateTime object into its error state.
  18219. */
  18220. static void datetimeError(DateTime *p){
  18221. memset(p, 0, sizeof(*p));
  18222. p->isError = 1;
  18223. }
  18224. /*
  18225. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  18226. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  18227. **
  18228. ** Reference: Meeus page 61
  18229. */
  18230. static void computeJD(DateTime *p){
  18231. int Y, M, D, A, B, X1, X2;
  18232. if( p->validJD ) return;
  18233. if( p->validYMD ){
  18234. Y = p->Y;
  18235. M = p->M;
  18236. D = p->D;
  18237. }else{
  18238. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  18239. M = 1;
  18240. D = 1;
  18241. }
  18242. if( Y<-4713 || Y>9999 || p->rawS ){
  18243. datetimeError(p);
  18244. return;
  18245. }
  18246. if( M<=2 ){
  18247. Y--;
  18248. M += 12;
  18249. }
  18250. A = Y/100;
  18251. B = 2 - A + (A/4);
  18252. X1 = 36525*(Y+4716)/100;
  18253. X2 = 306001*(M+1)/10000;
  18254. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  18255. p->validJD = 1;
  18256. if( p->validHMS ){
  18257. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  18258. if( p->validTZ ){
  18259. p->iJD -= p->tz*60000;
  18260. p->validYMD = 0;
  18261. p->validHMS = 0;
  18262. p->validTZ = 0;
  18263. }
  18264. }
  18265. }
  18266. /*
  18267. ** Parse dates of the form
  18268. **
  18269. ** YYYY-MM-DD HH:MM:SS.FFF
  18270. ** YYYY-MM-DD HH:MM:SS
  18271. ** YYYY-MM-DD HH:MM
  18272. ** YYYY-MM-DD
  18273. **
  18274. ** Write the result into the DateTime structure and return 0
  18275. ** on success and 1 if the input string is not a well-formed
  18276. ** date.
  18277. */
  18278. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  18279. int Y, M, D, neg;
  18280. if( zDate[0]=='-' ){
  18281. zDate++;
  18282. neg = 1;
  18283. }else{
  18284. neg = 0;
  18285. }
  18286. if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
  18287. return 1;
  18288. }
  18289. zDate += 10;
  18290. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  18291. if( parseHhMmSs(zDate, p)==0 ){
  18292. /* We got the time */
  18293. }else if( *zDate==0 ){
  18294. p->validHMS = 0;
  18295. }else{
  18296. return 1;
  18297. }
  18298. p->validJD = 0;
  18299. p->validYMD = 1;
  18300. p->Y = neg ? -Y : Y;
  18301. p->M = M;
  18302. p->D = D;
  18303. if( p->validTZ ){
  18304. computeJD(p);
  18305. }
  18306. return 0;
  18307. }
  18308. /*
  18309. ** Set the time to the current time reported by the VFS.
  18310. **
  18311. ** Return the number of errors.
  18312. */
  18313. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  18314. p->iJD = sqlite3StmtCurrentTime(context);
  18315. if( p->iJD>0 ){
  18316. p->validJD = 1;
  18317. return 0;
  18318. }else{
  18319. return 1;
  18320. }
  18321. }
  18322. /*
  18323. ** Input "r" is a numeric quantity which might be a julian day number,
  18324. ** or the number of seconds since 1970. If the value if r is within
  18325. ** range of a julian day number, install it as such and set validJD.
  18326. ** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
  18327. */
  18328. static void setRawDateNumber(DateTime *p, double r){
  18329. p->s = r;
  18330. p->rawS = 1;
  18331. if( r>=0.0 && r<5373484.5 ){
  18332. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  18333. p->validJD = 1;
  18334. }
  18335. }
  18336. /*
  18337. ** Attempt to parse the given string into a julian day number. Return
  18338. ** the number of errors.
  18339. **
  18340. ** The following are acceptable forms for the input string:
  18341. **
  18342. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  18343. ** DDDD.DD
  18344. ** now
  18345. **
  18346. ** In the first form, the +/-HH:MM is always optional. The fractional
  18347. ** seconds extension (the ".FFF") is optional. The seconds portion
  18348. ** (":SS.FFF") is option. The year and date can be omitted as long
  18349. ** as there is a time string. The time string can be omitted as long
  18350. ** as there is a year and date.
  18351. */
  18352. static int parseDateOrTime(
  18353. sqlite3_context *context,
  18354. const char *zDate,
  18355. DateTime *p
  18356. ){
  18357. double r;
  18358. if( parseYyyyMmDd(zDate,p)==0 ){
  18359. return 0;
  18360. }else if( parseHhMmSs(zDate, p)==0 ){
  18361. return 0;
  18362. }else if( sqlite3StrICmp(zDate,"now")==0){
  18363. return setDateTimeToCurrent(context, p);
  18364. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  18365. setRawDateNumber(p, r);
  18366. return 0;
  18367. }
  18368. return 1;
  18369. }
  18370. /* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
  18371. ** Multiplying this by 86400000 gives 464269060799999 as the maximum value
  18372. ** for DateTime.iJD.
  18373. **
  18374. ** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
  18375. ** such a large integer literal, so we have to encode it.
  18376. */
  18377. #define INT_464269060799999 ((((i64)0x1a640)<<32)|0x1072fdff)
  18378. /*
  18379. ** Return TRUE if the given julian day number is within range.
  18380. **
  18381. ** The input is the JulianDay times 86400000.
  18382. */
  18383. static int validJulianDay(sqlite3_int64 iJD){
  18384. return iJD>=0 && iJD<=INT_464269060799999;
  18385. }
  18386. /*
  18387. ** Compute the Year, Month, and Day from the julian day number.
  18388. */
  18389. static void computeYMD(DateTime *p){
  18390. int Z, A, B, C, D, E, X1;
  18391. if( p->validYMD ) return;
  18392. if( !p->validJD ){
  18393. p->Y = 2000;
  18394. p->M = 1;
  18395. p->D = 1;
  18396. }else if( !validJulianDay(p->iJD) ){
  18397. datetimeError(p);
  18398. return;
  18399. }else{
  18400. Z = (int)((p->iJD + 43200000)/86400000);
  18401. A = (int)((Z - 1867216.25)/36524.25);
  18402. A = Z + 1 + A - (A/4);
  18403. B = A + 1524;
  18404. C = (int)((B - 122.1)/365.25);
  18405. D = (36525*(C&32767))/100;
  18406. E = (int)((B-D)/30.6001);
  18407. X1 = (int)(30.6001*E);
  18408. p->D = B - D - X1;
  18409. p->M = E<14 ? E-1 : E-13;
  18410. p->Y = p->M>2 ? C - 4716 : C - 4715;
  18411. }
  18412. p->validYMD = 1;
  18413. }
  18414. /*
  18415. ** Compute the Hour, Minute, and Seconds from the julian day number.
  18416. */
  18417. static void computeHMS(DateTime *p){
  18418. int s;
  18419. if( p->validHMS ) return;
  18420. computeJD(p);
  18421. s = (int)((p->iJD + 43200000) % 86400000);
  18422. p->s = s/1000.0;
  18423. s = (int)p->s;
  18424. p->s -= s;
  18425. p->h = s/3600;
  18426. s -= p->h*3600;
  18427. p->m = s/60;
  18428. p->s += s - p->m*60;
  18429. p->rawS = 0;
  18430. p->validHMS = 1;
  18431. }
  18432. /*
  18433. ** Compute both YMD and HMS
  18434. */
  18435. static void computeYMD_HMS(DateTime *p){
  18436. computeYMD(p);
  18437. computeHMS(p);
  18438. }
  18439. /*
  18440. ** Clear the YMD and HMS and the TZ
  18441. */
  18442. static void clearYMD_HMS_TZ(DateTime *p){
  18443. p->validYMD = 0;
  18444. p->validHMS = 0;
  18445. p->validTZ = 0;
  18446. }
  18447. #ifndef SQLITE_OMIT_LOCALTIME
  18448. /*
  18449. ** On recent Windows platforms, the localtime_s() function is available
  18450. ** as part of the "Secure CRT". It is essentially equivalent to
  18451. ** localtime_r() available under most POSIX platforms, except that the
  18452. ** order of the parameters is reversed.
  18453. **
  18454. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  18455. **
  18456. ** If the user has not indicated to use localtime_r() or localtime_s()
  18457. ** already, check for an MSVC build environment that provides
  18458. ** localtime_s().
  18459. */
  18460. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
  18461. && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  18462. #undef HAVE_LOCALTIME_S
  18463. #define HAVE_LOCALTIME_S 1
  18464. #endif
  18465. /*
  18466. ** The following routine implements the rough equivalent of localtime_r()
  18467. ** using whatever operating-system specific localtime facility that
  18468. ** is available. This routine returns 0 on success and
  18469. ** non-zero on any kind of error.
  18470. **
  18471. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  18472. ** routine will always fail.
  18473. **
  18474. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  18475. ** library function localtime_r() is used to assist in the calculation of
  18476. ** local time.
  18477. */
  18478. static int osLocaltime(time_t *t, struct tm *pTm){
  18479. int rc;
  18480. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
  18481. struct tm *pX;
  18482. #if SQLITE_THREADSAFE>0
  18483. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  18484. #endif
  18485. sqlite3_mutex_enter(mutex);
  18486. pX = localtime(t);
  18487. #ifndef SQLITE_UNTESTABLE
  18488. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  18489. #endif
  18490. if( pX ) *pTm = *pX;
  18491. sqlite3_mutex_leave(mutex);
  18492. rc = pX==0;
  18493. #else
  18494. #ifndef SQLITE_UNTESTABLE
  18495. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  18496. #endif
  18497. #if HAVE_LOCALTIME_R
  18498. rc = localtime_r(t, pTm)==0;
  18499. #else
  18500. rc = localtime_s(pTm, t);
  18501. #endif /* HAVE_LOCALTIME_R */
  18502. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  18503. return rc;
  18504. }
  18505. #endif /* SQLITE_OMIT_LOCALTIME */
  18506. #ifndef SQLITE_OMIT_LOCALTIME
  18507. /*
  18508. ** Compute the difference (in milliseconds) between localtime and UTC
  18509. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  18510. ** return this value and set *pRc to SQLITE_OK.
  18511. **
  18512. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  18513. ** is undefined in this case.
  18514. */
  18515. static sqlite3_int64 localtimeOffset(
  18516. DateTime *p, /* Date at which to calculate offset */
  18517. sqlite3_context *pCtx, /* Write error here if one occurs */
  18518. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  18519. ){
  18520. DateTime x, y;
  18521. time_t t;
  18522. struct tm sLocal;
  18523. /* Initialize the contents of sLocal to avoid a compiler warning. */
  18524. memset(&sLocal, 0, sizeof(sLocal));
  18525. x = *p;
  18526. computeYMD_HMS(&x);
  18527. if( x.Y<1971 || x.Y>=2038 ){
  18528. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  18529. ** works for years between 1970 and 2037. For dates outside this range,
  18530. ** SQLite attempts to map the year into an equivalent year within this
  18531. ** range, do the calculation, then map the year back.
  18532. */
  18533. x.Y = 2000;
  18534. x.M = 1;
  18535. x.D = 1;
  18536. x.h = 0;
  18537. x.m = 0;
  18538. x.s = 0.0;
  18539. } else {
  18540. int s = (int)(x.s + 0.5);
  18541. x.s = s;
  18542. }
  18543. x.tz = 0;
  18544. x.validJD = 0;
  18545. computeJD(&x);
  18546. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  18547. if( osLocaltime(&t, &sLocal) ){
  18548. sqlite3_result_error(pCtx, "local time unavailable", -1);
  18549. *pRc = SQLITE_ERROR;
  18550. return 0;
  18551. }
  18552. y.Y = sLocal.tm_year + 1900;
  18553. y.M = sLocal.tm_mon + 1;
  18554. y.D = sLocal.tm_mday;
  18555. y.h = sLocal.tm_hour;
  18556. y.m = sLocal.tm_min;
  18557. y.s = sLocal.tm_sec;
  18558. y.validYMD = 1;
  18559. y.validHMS = 1;
  18560. y.validJD = 0;
  18561. y.rawS = 0;
  18562. y.validTZ = 0;
  18563. y.isError = 0;
  18564. computeJD(&y);
  18565. *pRc = SQLITE_OK;
  18566. return y.iJD - x.iJD;
  18567. }
  18568. #endif /* SQLITE_OMIT_LOCALTIME */
  18569. /*
  18570. ** The following table defines various date transformations of the form
  18571. **
  18572. ** 'NNN days'
  18573. **
  18574. ** Where NNN is an arbitrary floating-point number and "days" can be one
  18575. ** of several units of time.
  18576. */
  18577. static const struct {
  18578. u8 eType; /* Transformation type code */
  18579. u8 nName; /* Length of th name */
  18580. char *zName; /* Name of the transformation */
  18581. double rLimit; /* Maximum NNN value for this transform */
  18582. double rXform; /* Constant used for this transform */
  18583. } aXformType[] = {
  18584. { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) },
  18585. { 0, 6, "minute", 7737817680.0, 86400000.0/(24.0*60.0) },
  18586. { 0, 4, "hour", 128963628.0, 86400000.0/24.0 },
  18587. { 0, 3, "day", 5373485.0, 86400000.0 },
  18588. { 1, 5, "month", 176546.0, 30.0*86400000.0 },
  18589. { 2, 4, "year", 14713.0, 365.0*86400000.0 },
  18590. };
  18591. /*
  18592. ** Process a modifier to a date-time stamp. The modifiers are
  18593. ** as follows:
  18594. **
  18595. ** NNN days
  18596. ** NNN hours
  18597. ** NNN minutes
  18598. ** NNN.NNNN seconds
  18599. ** NNN months
  18600. ** NNN years
  18601. ** start of month
  18602. ** start of year
  18603. ** start of week
  18604. ** start of day
  18605. ** weekday N
  18606. ** unixepoch
  18607. ** localtime
  18608. ** utc
  18609. **
  18610. ** Return 0 on success and 1 if there is any kind of error. If the error
  18611. ** is in a system call (i.e. localtime()), then an error message is written
  18612. ** to context pCtx. If the error is an unrecognized modifier, no error is
  18613. ** written to pCtx.
  18614. */
  18615. static int parseModifier(
  18616. sqlite3_context *pCtx, /* Function context */
  18617. const char *z, /* The text of the modifier */
  18618. int n, /* Length of zMod in bytes */
  18619. DateTime *p /* The date/time value to be modified */
  18620. ){
  18621. int rc = 1;
  18622. double r;
  18623. switch(sqlite3UpperToLower[(u8)z[0]] ){
  18624. #ifndef SQLITE_OMIT_LOCALTIME
  18625. case 'l': {
  18626. /* localtime
  18627. **
  18628. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  18629. ** show local time.
  18630. */
  18631. if( sqlite3_stricmp(z, "localtime")==0 ){
  18632. computeJD(p);
  18633. p->iJD += localtimeOffset(p, pCtx, &rc);
  18634. clearYMD_HMS_TZ(p);
  18635. }
  18636. break;
  18637. }
  18638. #endif
  18639. case 'u': {
  18640. /*
  18641. ** unixepoch
  18642. **
  18643. ** Treat the current value of p->s as the number of
  18644. ** seconds since 1970. Convert to a real julian day number.
  18645. */
  18646. if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
  18647. r = p->s*1000.0 + 210866760000000.0;
  18648. if( r>=0.0 && r<464269060800000.0 ){
  18649. clearYMD_HMS_TZ(p);
  18650. p->iJD = (sqlite3_int64)r;
  18651. p->validJD = 1;
  18652. p->rawS = 0;
  18653. rc = 0;
  18654. }
  18655. }
  18656. #ifndef SQLITE_OMIT_LOCALTIME
  18657. else if( sqlite3_stricmp(z, "utc")==0 ){
  18658. if( p->tzSet==0 ){
  18659. sqlite3_int64 c1;
  18660. computeJD(p);
  18661. c1 = localtimeOffset(p, pCtx, &rc);
  18662. if( rc==SQLITE_OK ){
  18663. p->iJD -= c1;
  18664. clearYMD_HMS_TZ(p);
  18665. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  18666. }
  18667. p->tzSet = 1;
  18668. }else{
  18669. rc = SQLITE_OK;
  18670. }
  18671. }
  18672. #endif
  18673. break;
  18674. }
  18675. case 'w': {
  18676. /*
  18677. ** weekday N
  18678. **
  18679. ** Move the date to the same time on the next occurrence of
  18680. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  18681. ** date is already on the appropriate weekday, this is a no-op.
  18682. */
  18683. if( sqlite3_strnicmp(z, "weekday ", 8)==0
  18684. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  18685. && (n=(int)r)==r && n>=0 && r<7 ){
  18686. sqlite3_int64 Z;
  18687. computeYMD_HMS(p);
  18688. p->validTZ = 0;
  18689. p->validJD = 0;
  18690. computeJD(p);
  18691. Z = ((p->iJD + 129600000)/86400000) % 7;
  18692. if( Z>n ) Z -= 7;
  18693. p->iJD += (n - Z)*86400000;
  18694. clearYMD_HMS_TZ(p);
  18695. rc = 0;
  18696. }
  18697. break;
  18698. }
  18699. case 's': {
  18700. /*
  18701. ** start of TTTTT
  18702. **
  18703. ** Move the date backwards to the beginning of the current day,
  18704. ** or month or year.
  18705. */
  18706. if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
  18707. if( !p->validJD && !p->validYMD && !p->validHMS ) break;
  18708. z += 9;
  18709. computeYMD(p);
  18710. p->validHMS = 1;
  18711. p->h = p->m = 0;
  18712. p->s = 0.0;
  18713. p->rawS = 0;
  18714. p->validTZ = 0;
  18715. p->validJD = 0;
  18716. if( sqlite3_stricmp(z,"month")==0 ){
  18717. p->D = 1;
  18718. rc = 0;
  18719. }else if( sqlite3_stricmp(z,"year")==0 ){
  18720. p->M = 1;
  18721. p->D = 1;
  18722. rc = 0;
  18723. }else if( sqlite3_stricmp(z,"day")==0 ){
  18724. rc = 0;
  18725. }
  18726. break;
  18727. }
  18728. case '+':
  18729. case '-':
  18730. case '0':
  18731. case '1':
  18732. case '2':
  18733. case '3':
  18734. case '4':
  18735. case '5':
  18736. case '6':
  18737. case '7':
  18738. case '8':
  18739. case '9': {
  18740. double rRounder;
  18741. int i;
  18742. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  18743. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  18744. rc = 1;
  18745. break;
  18746. }
  18747. if( z[n]==':' ){
  18748. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  18749. ** specified number of hours, minutes, seconds, and fractional seconds
  18750. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  18751. ** omitted.
  18752. */
  18753. const char *z2 = z;
  18754. DateTime tx;
  18755. sqlite3_int64 day;
  18756. if( !sqlite3Isdigit(*z2) ) z2++;
  18757. memset(&tx, 0, sizeof(tx));
  18758. if( parseHhMmSs(z2, &tx) ) break;
  18759. computeJD(&tx);
  18760. tx.iJD -= 43200000;
  18761. day = tx.iJD/86400000;
  18762. tx.iJD -= day*86400000;
  18763. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  18764. computeJD(p);
  18765. clearYMD_HMS_TZ(p);
  18766. p->iJD += tx.iJD;
  18767. rc = 0;
  18768. break;
  18769. }
  18770. /* If control reaches this point, it means the transformation is
  18771. ** one of the forms like "+NNN days". */
  18772. z += n;
  18773. while( sqlite3Isspace(*z) ) z++;
  18774. n = sqlite3Strlen30(z);
  18775. if( n>10 || n<3 ) break;
  18776. if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
  18777. computeJD(p);
  18778. rc = 1;
  18779. rRounder = r<0 ? -0.5 : +0.5;
  18780. for(i=0; i<ArraySize(aXformType); i++){
  18781. if( aXformType[i].nName==n
  18782. && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
  18783. && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
  18784. ){
  18785. switch( aXformType[i].eType ){
  18786. case 1: { /* Special processing to add months */
  18787. int x;
  18788. computeYMD_HMS(p);
  18789. p->M += (int)r;
  18790. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  18791. p->Y += x;
  18792. p->M -= x*12;
  18793. p->validJD = 0;
  18794. r -= (int)r;
  18795. break;
  18796. }
  18797. case 2: { /* Special processing to add years */
  18798. int y = (int)r;
  18799. computeYMD_HMS(p);
  18800. p->Y += y;
  18801. p->validJD = 0;
  18802. r -= (int)r;
  18803. break;
  18804. }
  18805. }
  18806. computeJD(p);
  18807. p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
  18808. rc = 0;
  18809. break;
  18810. }
  18811. }
  18812. clearYMD_HMS_TZ(p);
  18813. break;
  18814. }
  18815. default: {
  18816. break;
  18817. }
  18818. }
  18819. return rc;
  18820. }
  18821. /*
  18822. ** Process time function arguments. argv[0] is a date-time stamp.
  18823. ** argv[1] and following are modifiers. Parse them all and write
  18824. ** the resulting time into the DateTime structure p. Return 0
  18825. ** on success and 1 if there are any errors.
  18826. **
  18827. ** If there are zero parameters (if even argv[0] is undefined)
  18828. ** then assume a default value of "now" for argv[0].
  18829. */
  18830. static int isDate(
  18831. sqlite3_context *context,
  18832. int argc,
  18833. sqlite3_value **argv,
  18834. DateTime *p
  18835. ){
  18836. int i, n;
  18837. const unsigned char *z;
  18838. int eType;
  18839. memset(p, 0, sizeof(*p));
  18840. if( argc==0 ){
  18841. return setDateTimeToCurrent(context, p);
  18842. }
  18843. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  18844. || eType==SQLITE_INTEGER ){
  18845. setRawDateNumber(p, sqlite3_value_double(argv[0]));
  18846. }else{
  18847. z = sqlite3_value_text(argv[0]);
  18848. if( !z || parseDateOrTime(context, (char*)z, p) ){
  18849. return 1;
  18850. }
  18851. }
  18852. for(i=1; i<argc; i++){
  18853. z = sqlite3_value_text(argv[i]);
  18854. n = sqlite3_value_bytes(argv[i]);
  18855. if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;
  18856. }
  18857. computeJD(p);
  18858. if( p->isError || !validJulianDay(p->iJD) ) return 1;
  18859. return 0;
  18860. }
  18861. /*
  18862. ** The following routines implement the various date and time functions
  18863. ** of SQLite.
  18864. */
  18865. /*
  18866. ** julianday( TIMESTRING, MOD, MOD, ...)
  18867. **
  18868. ** Return the julian day number of the date specified in the arguments
  18869. */
  18870. static void juliandayFunc(
  18871. sqlite3_context *context,
  18872. int argc,
  18873. sqlite3_value **argv
  18874. ){
  18875. DateTime x;
  18876. if( isDate(context, argc, argv, &x)==0 ){
  18877. computeJD(&x);
  18878. sqlite3_result_double(context, x.iJD/86400000.0);
  18879. }
  18880. }
  18881. /*
  18882. ** datetime( TIMESTRING, MOD, MOD, ...)
  18883. **
  18884. ** Return YYYY-MM-DD HH:MM:SS
  18885. */
  18886. static void datetimeFunc(
  18887. sqlite3_context *context,
  18888. int argc,
  18889. sqlite3_value **argv
  18890. ){
  18891. DateTime x;
  18892. if( isDate(context, argc, argv, &x)==0 ){
  18893. char zBuf[100];
  18894. computeYMD_HMS(&x);
  18895. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  18896. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  18897. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  18898. }
  18899. }
  18900. /*
  18901. ** time( TIMESTRING, MOD, MOD, ...)
  18902. **
  18903. ** Return HH:MM:SS
  18904. */
  18905. static void timeFunc(
  18906. sqlite3_context *context,
  18907. int argc,
  18908. sqlite3_value **argv
  18909. ){
  18910. DateTime x;
  18911. if( isDate(context, argc, argv, &x)==0 ){
  18912. char zBuf[100];
  18913. computeHMS(&x);
  18914. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  18915. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  18916. }
  18917. }
  18918. /*
  18919. ** date( TIMESTRING, MOD, MOD, ...)
  18920. **
  18921. ** Return YYYY-MM-DD
  18922. */
  18923. static void dateFunc(
  18924. sqlite3_context *context,
  18925. int argc,
  18926. sqlite3_value **argv
  18927. ){
  18928. DateTime x;
  18929. if( isDate(context, argc, argv, &x)==0 ){
  18930. char zBuf[100];
  18931. computeYMD(&x);
  18932. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  18933. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  18934. }
  18935. }
  18936. /*
  18937. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  18938. **
  18939. ** Return a string described by FORMAT. Conversions as follows:
  18940. **
  18941. ** %d day of month
  18942. ** %f ** fractional seconds SS.SSS
  18943. ** %H hour 00-24
  18944. ** %j day of year 000-366
  18945. ** %J ** julian day number
  18946. ** %m month 01-12
  18947. ** %M minute 00-59
  18948. ** %s seconds since 1970-01-01
  18949. ** %S seconds 00-59
  18950. ** %w day of week 0-6 sunday==0
  18951. ** %W week of year 00-53
  18952. ** %Y year 0000-9999
  18953. ** %% %
  18954. */
  18955. static void strftimeFunc(
  18956. sqlite3_context *context,
  18957. int argc,
  18958. sqlite3_value **argv
  18959. ){
  18960. DateTime x;
  18961. u64 n;
  18962. size_t i,j;
  18963. char *z;
  18964. sqlite3 *db;
  18965. const char *zFmt;
  18966. char zBuf[100];
  18967. if( argc==0 ) return;
  18968. zFmt = (const char*)sqlite3_value_text(argv[0]);
  18969. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  18970. db = sqlite3_context_db_handle(context);
  18971. for(i=0, n=1; zFmt[i]; i++, n++){
  18972. if( zFmt[i]=='%' ){
  18973. switch( zFmt[i+1] ){
  18974. case 'd':
  18975. case 'H':
  18976. case 'm':
  18977. case 'M':
  18978. case 'S':
  18979. case 'W':
  18980. n++;
  18981. /* fall thru */
  18982. case 'w':
  18983. case '%':
  18984. break;
  18985. case 'f':
  18986. n += 8;
  18987. break;
  18988. case 'j':
  18989. n += 3;
  18990. break;
  18991. case 'Y':
  18992. n += 8;
  18993. break;
  18994. case 's':
  18995. case 'J':
  18996. n += 50;
  18997. break;
  18998. default:
  18999. return; /* ERROR. return a NULL */
  19000. }
  19001. i++;
  19002. }
  19003. }
  19004. testcase( n==sizeof(zBuf)-1 );
  19005. testcase( n==sizeof(zBuf) );
  19006. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  19007. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  19008. if( n<sizeof(zBuf) ){
  19009. z = zBuf;
  19010. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  19011. sqlite3_result_error_toobig(context);
  19012. return;
  19013. }else{
  19014. z = sqlite3DbMallocRawNN(db, (int)n);
  19015. if( z==0 ){
  19016. sqlite3_result_error_nomem(context);
  19017. return;
  19018. }
  19019. }
  19020. computeJD(&x);
  19021. computeYMD_HMS(&x);
  19022. for(i=j=0; zFmt[i]; i++){
  19023. if( zFmt[i]!='%' ){
  19024. z[j++] = zFmt[i];
  19025. }else{
  19026. i++;
  19027. switch( zFmt[i] ){
  19028. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  19029. case 'f': {
  19030. double s = x.s;
  19031. if( s>59.999 ) s = 59.999;
  19032. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  19033. j += sqlite3Strlen30(&z[j]);
  19034. break;
  19035. }
  19036. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  19037. case 'W': /* Fall thru */
  19038. case 'j': {
  19039. int nDay; /* Number of days since 1st day of year */
  19040. DateTime y = x;
  19041. y.validJD = 0;
  19042. y.M = 1;
  19043. y.D = 1;
  19044. computeJD(&y);
  19045. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  19046. if( zFmt[i]=='W' ){
  19047. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  19048. wd = (int)(((x.iJD+43200000)/86400000)%7);
  19049. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  19050. j += 2;
  19051. }else{
  19052. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  19053. j += 3;
  19054. }
  19055. break;
  19056. }
  19057. case 'J': {
  19058. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  19059. j+=sqlite3Strlen30(&z[j]);
  19060. break;
  19061. }
  19062. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  19063. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  19064. case 's': {
  19065. sqlite3_snprintf(30,&z[j],"%lld",
  19066. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  19067. j += sqlite3Strlen30(&z[j]);
  19068. break;
  19069. }
  19070. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  19071. case 'w': {
  19072. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  19073. break;
  19074. }
  19075. case 'Y': {
  19076. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  19077. break;
  19078. }
  19079. default: z[j++] = '%'; break;
  19080. }
  19081. }
  19082. }
  19083. z[j] = 0;
  19084. sqlite3_result_text(context, z, -1,
  19085. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  19086. }
  19087. /*
  19088. ** current_time()
  19089. **
  19090. ** This function returns the same value as time('now').
  19091. */
  19092. static void ctimeFunc(
  19093. sqlite3_context *context,
  19094. int NotUsed,
  19095. sqlite3_value **NotUsed2
  19096. ){
  19097. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  19098. timeFunc(context, 0, 0);
  19099. }
  19100. /*
  19101. ** current_date()
  19102. **
  19103. ** This function returns the same value as date('now').
  19104. */
  19105. static void cdateFunc(
  19106. sqlite3_context *context,
  19107. int NotUsed,
  19108. sqlite3_value **NotUsed2
  19109. ){
  19110. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  19111. dateFunc(context, 0, 0);
  19112. }
  19113. /*
  19114. ** current_timestamp()
  19115. **
  19116. ** This function returns the same value as datetime('now').
  19117. */
  19118. static void ctimestampFunc(
  19119. sqlite3_context *context,
  19120. int NotUsed,
  19121. sqlite3_value **NotUsed2
  19122. ){
  19123. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  19124. datetimeFunc(context, 0, 0);
  19125. }
  19126. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  19127. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  19128. /*
  19129. ** If the library is compiled to omit the full-scale date and time
  19130. ** handling (to get a smaller binary), the following minimal version
  19131. ** of the functions current_time(), current_date() and current_timestamp()
  19132. ** are included instead. This is to support column declarations that
  19133. ** include "DEFAULT CURRENT_TIME" etc.
  19134. **
  19135. ** This function uses the C-library functions time(), gmtime()
  19136. ** and strftime(). The format string to pass to strftime() is supplied
  19137. ** as the user-data for the function.
  19138. */
  19139. static void currentTimeFunc(
  19140. sqlite3_context *context,
  19141. int argc,
  19142. sqlite3_value **argv
  19143. ){
  19144. time_t t;
  19145. char *zFormat = (char *)sqlite3_user_data(context);
  19146. sqlite3_int64 iT;
  19147. struct tm *pTm;
  19148. struct tm sNow;
  19149. char zBuf[20];
  19150. UNUSED_PARAMETER(argc);
  19151. UNUSED_PARAMETER(argv);
  19152. iT = sqlite3StmtCurrentTime(context);
  19153. if( iT<=0 ) return;
  19154. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  19155. #if HAVE_GMTIME_R
  19156. pTm = gmtime_r(&t, &sNow);
  19157. #else
  19158. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  19159. pTm = gmtime(&t);
  19160. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  19161. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  19162. #endif
  19163. if( pTm ){
  19164. strftime(zBuf, 20, zFormat, &sNow);
  19165. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  19166. }
  19167. }
  19168. #endif
  19169. /*
  19170. ** This function registered all of the above C functions as SQL
  19171. ** functions. This should be the only routine in this file with
  19172. ** external linkage.
  19173. */
  19174. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  19175. static FuncDef aDateTimeFuncs[] = {
  19176. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  19177. DFUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  19178. DFUNCTION(date, -1, 0, 0, dateFunc ),
  19179. DFUNCTION(time, -1, 0, 0, timeFunc ),
  19180. DFUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  19181. DFUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  19182. DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  19183. DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  19184. DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
  19185. #else
  19186. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  19187. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  19188. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  19189. #endif
  19190. };
  19191. sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
  19192. }
  19193. /************** End of date.c ************************************************/
  19194. /************** Begin file os.c **********************************************/
  19195. /*
  19196. ** 2005 November 29
  19197. **
  19198. ** The author disclaims copyright to this source code. In place of
  19199. ** a legal notice, here is a blessing:
  19200. **
  19201. ** May you do good and not evil.
  19202. ** May you find forgiveness for yourself and forgive others.
  19203. ** May you share freely, never taking more than you give.
  19204. **
  19205. ******************************************************************************
  19206. **
  19207. ** This file contains OS interface code that is common to all
  19208. ** architectures.
  19209. */
  19210. /* #include "sqliteInt.h" */
  19211. /*
  19212. ** If we compile with the SQLITE_TEST macro set, then the following block
  19213. ** of code will give us the ability to simulate a disk I/O error. This
  19214. ** is used for testing the I/O recovery logic.
  19215. */
  19216. #if defined(SQLITE_TEST)
  19217. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  19218. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  19219. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  19220. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  19221. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  19222. SQLITE_API int sqlite3_diskfull_pending = 0;
  19223. SQLITE_API int sqlite3_diskfull = 0;
  19224. #endif /* defined(SQLITE_TEST) */
  19225. /*
  19226. ** When testing, also keep a count of the number of open files.
  19227. */
  19228. #if defined(SQLITE_TEST)
  19229. SQLITE_API int sqlite3_open_file_count = 0;
  19230. #endif /* defined(SQLITE_TEST) */
  19231. /*
  19232. ** The default SQLite sqlite3_vfs implementations do not allocate
  19233. ** memory (actually, os_unix.c allocates a small amount of memory
  19234. ** from within OsOpen()), but some third-party implementations may.
  19235. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  19236. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  19237. **
  19238. ** The following functions are instrumented for malloc() failure
  19239. ** testing:
  19240. **
  19241. ** sqlite3OsRead()
  19242. ** sqlite3OsWrite()
  19243. ** sqlite3OsSync()
  19244. ** sqlite3OsFileSize()
  19245. ** sqlite3OsLock()
  19246. ** sqlite3OsCheckReservedLock()
  19247. ** sqlite3OsFileControl()
  19248. ** sqlite3OsShmMap()
  19249. ** sqlite3OsOpen()
  19250. ** sqlite3OsDelete()
  19251. ** sqlite3OsAccess()
  19252. ** sqlite3OsFullPathname()
  19253. **
  19254. */
  19255. #if defined(SQLITE_TEST)
  19256. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  19257. #define DO_OS_MALLOC_TEST(x) \
  19258. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
  19259. void *pTstAlloc = sqlite3Malloc(10); \
  19260. if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \
  19261. sqlite3_free(pTstAlloc); \
  19262. }
  19263. #else
  19264. #define DO_OS_MALLOC_TEST(x)
  19265. #endif
  19266. /*
  19267. ** The following routines are convenience wrappers around methods
  19268. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  19269. ** of this would be completely automatic if SQLite were coded using
  19270. ** C++ instead of plain old C.
  19271. */
  19272. SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
  19273. if( pId->pMethods ){
  19274. pId->pMethods->xClose(pId);
  19275. pId->pMethods = 0;
  19276. }
  19277. }
  19278. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  19279. DO_OS_MALLOC_TEST(id);
  19280. return id->pMethods->xRead(id, pBuf, amt, offset);
  19281. }
  19282. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  19283. DO_OS_MALLOC_TEST(id);
  19284. return id->pMethods->xWrite(id, pBuf, amt, offset);
  19285. }
  19286. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  19287. return id->pMethods->xTruncate(id, size);
  19288. }
  19289. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  19290. DO_OS_MALLOC_TEST(id);
  19291. return id->pMethods->xSync(id, flags);
  19292. }
  19293. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  19294. DO_OS_MALLOC_TEST(id);
  19295. return id->pMethods->xFileSize(id, pSize);
  19296. }
  19297. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  19298. DO_OS_MALLOC_TEST(id);
  19299. return id->pMethods->xLock(id, lockType);
  19300. }
  19301. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  19302. return id->pMethods->xUnlock(id, lockType);
  19303. }
  19304. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  19305. DO_OS_MALLOC_TEST(id);
  19306. return id->pMethods->xCheckReservedLock(id, pResOut);
  19307. }
  19308. /*
  19309. ** Use sqlite3OsFileControl() when we are doing something that might fail
  19310. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  19311. ** when simply tossing information over the wall to the VFS and we do not
  19312. ** really care if the VFS receives and understands the information since it
  19313. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  19314. ** routine has no return value since the return value would be meaningless.
  19315. */
  19316. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  19317. #ifdef SQLITE_TEST
  19318. if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
  19319. /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
  19320. ** is using a regular VFS, it is called after the corresponding
  19321. ** transaction has been committed. Injecting a fault at this point
  19322. ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
  19323. ** but the transaction is committed anyway.
  19324. **
  19325. ** The core must call OsFileControl() though, not OsFileControlHint(),
  19326. ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
  19327. ** means the commit really has failed and an error should be returned
  19328. ** to the user. */
  19329. DO_OS_MALLOC_TEST(id);
  19330. }
  19331. #endif
  19332. return id->pMethods->xFileControl(id, op, pArg);
  19333. }
  19334. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  19335. (void)id->pMethods->xFileControl(id, op, pArg);
  19336. }
  19337. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  19338. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  19339. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  19340. }
  19341. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  19342. return id->pMethods->xDeviceCharacteristics(id);
  19343. }
  19344. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  19345. return id->pMethods->xShmLock(id, offset, n, flags);
  19346. }
  19347. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  19348. id->pMethods->xShmBarrier(id);
  19349. }
  19350. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  19351. return id->pMethods->xShmUnmap(id, deleteFlag);
  19352. }
  19353. SQLITE_PRIVATE int sqlite3OsShmMap(
  19354. sqlite3_file *id, /* Database file handle */
  19355. int iPage,
  19356. int pgsz,
  19357. int bExtend, /* True to extend file if necessary */
  19358. void volatile **pp /* OUT: Pointer to mapping */
  19359. ){
  19360. DO_OS_MALLOC_TEST(id);
  19361. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  19362. }
  19363. #if SQLITE_MAX_MMAP_SIZE>0
  19364. /* The real implementation of xFetch and xUnfetch */
  19365. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  19366. DO_OS_MALLOC_TEST(id);
  19367. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  19368. }
  19369. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  19370. return id->pMethods->xUnfetch(id, iOff, p);
  19371. }
  19372. #else
  19373. /* No-op stubs to use when memory-mapped I/O is disabled */
  19374. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  19375. *pp = 0;
  19376. return SQLITE_OK;
  19377. }
  19378. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  19379. return SQLITE_OK;
  19380. }
  19381. #endif
  19382. /*
  19383. ** The next group of routines are convenience wrappers around the
  19384. ** VFS methods.
  19385. */
  19386. SQLITE_PRIVATE int sqlite3OsOpen(
  19387. sqlite3_vfs *pVfs,
  19388. const char *zPath,
  19389. sqlite3_file *pFile,
  19390. int flags,
  19391. int *pFlagsOut
  19392. ){
  19393. int rc;
  19394. DO_OS_MALLOC_TEST(0);
  19395. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  19396. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  19397. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  19398. ** reaching the VFS. */
  19399. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  19400. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  19401. return rc;
  19402. }
  19403. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  19404. DO_OS_MALLOC_TEST(0);
  19405. assert( dirSync==0 || dirSync==1 );
  19406. return pVfs->xDelete(pVfs, zPath, dirSync);
  19407. }
  19408. SQLITE_PRIVATE int sqlite3OsAccess(
  19409. sqlite3_vfs *pVfs,
  19410. const char *zPath,
  19411. int flags,
  19412. int *pResOut
  19413. ){
  19414. DO_OS_MALLOC_TEST(0);
  19415. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  19416. }
  19417. SQLITE_PRIVATE int sqlite3OsFullPathname(
  19418. sqlite3_vfs *pVfs,
  19419. const char *zPath,
  19420. int nPathOut,
  19421. char *zPathOut
  19422. ){
  19423. DO_OS_MALLOC_TEST(0);
  19424. zPathOut[0] = 0;
  19425. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  19426. }
  19427. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  19428. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  19429. return pVfs->xDlOpen(pVfs, zPath);
  19430. }
  19431. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  19432. pVfs->xDlError(pVfs, nByte, zBufOut);
  19433. }
  19434. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  19435. return pVfs->xDlSym(pVfs, pHdle, zSym);
  19436. }
  19437. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  19438. pVfs->xDlClose(pVfs, pHandle);
  19439. }
  19440. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  19441. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  19442. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  19443. }
  19444. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  19445. return pVfs->xSleep(pVfs, nMicro);
  19446. }
  19447. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
  19448. return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
  19449. }
  19450. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  19451. int rc;
  19452. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  19453. ** method to get the current date and time if that method is available
  19454. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  19455. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  19456. ** unavailable.
  19457. */
  19458. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  19459. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  19460. }else{
  19461. double r;
  19462. rc = pVfs->xCurrentTime(pVfs, &r);
  19463. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  19464. }
  19465. return rc;
  19466. }
  19467. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  19468. sqlite3_vfs *pVfs,
  19469. const char *zFile,
  19470. sqlite3_file **ppFile,
  19471. int flags,
  19472. int *pOutFlags
  19473. ){
  19474. int rc;
  19475. sqlite3_file *pFile;
  19476. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  19477. if( pFile ){
  19478. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  19479. if( rc!=SQLITE_OK ){
  19480. sqlite3_free(pFile);
  19481. }else{
  19482. *ppFile = pFile;
  19483. }
  19484. }else{
  19485. rc = SQLITE_NOMEM_BKPT;
  19486. }
  19487. return rc;
  19488. }
  19489. SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
  19490. assert( pFile );
  19491. sqlite3OsClose(pFile);
  19492. sqlite3_free(pFile);
  19493. }
  19494. /*
  19495. ** This function is a wrapper around the OS specific implementation of
  19496. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  19497. ** ability to simulate a malloc failure, so that the handling of an
  19498. ** error in sqlite3_os_init() by the upper layers can be tested.
  19499. */
  19500. SQLITE_PRIVATE int sqlite3OsInit(void){
  19501. void *p = sqlite3_malloc(10);
  19502. if( p==0 ) return SQLITE_NOMEM_BKPT;
  19503. sqlite3_free(p);
  19504. return sqlite3_os_init();
  19505. }
  19506. /*
  19507. ** The list of all registered VFS implementations.
  19508. */
  19509. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  19510. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  19511. /*
  19512. ** Locate a VFS by name. If no name is given, simply return the
  19513. ** first VFS on the list.
  19514. */
  19515. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  19516. sqlite3_vfs *pVfs = 0;
  19517. #if SQLITE_THREADSAFE
  19518. sqlite3_mutex *mutex;
  19519. #endif
  19520. #ifndef SQLITE_OMIT_AUTOINIT
  19521. int rc = sqlite3_initialize();
  19522. if( rc ) return 0;
  19523. #endif
  19524. #if SQLITE_THREADSAFE
  19525. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  19526. #endif
  19527. sqlite3_mutex_enter(mutex);
  19528. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  19529. if( zVfs==0 ) break;
  19530. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  19531. }
  19532. sqlite3_mutex_leave(mutex);
  19533. return pVfs;
  19534. }
  19535. /*
  19536. ** Unlink a VFS from the linked list
  19537. */
  19538. static void vfsUnlink(sqlite3_vfs *pVfs){
  19539. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  19540. if( pVfs==0 ){
  19541. /* No-op */
  19542. }else if( vfsList==pVfs ){
  19543. vfsList = pVfs->pNext;
  19544. }else if( vfsList ){
  19545. sqlite3_vfs *p = vfsList;
  19546. while( p->pNext && p->pNext!=pVfs ){
  19547. p = p->pNext;
  19548. }
  19549. if( p->pNext==pVfs ){
  19550. p->pNext = pVfs->pNext;
  19551. }
  19552. }
  19553. }
  19554. /*
  19555. ** Register a VFS with the system. It is harmless to register the same
  19556. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  19557. ** true.
  19558. */
  19559. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  19560. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  19561. #ifndef SQLITE_OMIT_AUTOINIT
  19562. int rc = sqlite3_initialize();
  19563. if( rc ) return rc;
  19564. #endif
  19565. #ifdef SQLITE_ENABLE_API_ARMOR
  19566. if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
  19567. #endif
  19568. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  19569. sqlite3_mutex_enter(mutex);
  19570. vfsUnlink(pVfs);
  19571. if( makeDflt || vfsList==0 ){
  19572. pVfs->pNext = vfsList;
  19573. vfsList = pVfs;
  19574. }else{
  19575. pVfs->pNext = vfsList->pNext;
  19576. vfsList->pNext = pVfs;
  19577. }
  19578. assert(vfsList);
  19579. sqlite3_mutex_leave(mutex);
  19580. return SQLITE_OK;
  19581. }
  19582. /*
  19583. ** Unregister a VFS so that it is no longer accessible.
  19584. */
  19585. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  19586. #if SQLITE_THREADSAFE
  19587. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  19588. #endif
  19589. sqlite3_mutex_enter(mutex);
  19590. vfsUnlink(pVfs);
  19591. sqlite3_mutex_leave(mutex);
  19592. return SQLITE_OK;
  19593. }
  19594. /************** End of os.c **************************************************/
  19595. /************** Begin file fault.c *******************************************/
  19596. /*
  19597. ** 2008 Jan 22
  19598. **
  19599. ** The author disclaims copyright to this source code. In place of
  19600. ** a legal notice, here is a blessing:
  19601. **
  19602. ** May you do good and not evil.
  19603. ** May you find forgiveness for yourself and forgive others.
  19604. ** May you share freely, never taking more than you give.
  19605. **
  19606. *************************************************************************
  19607. **
  19608. ** This file contains code to support the concept of "benign"
  19609. ** malloc failures (when the xMalloc() or xRealloc() method of the
  19610. ** sqlite3_mem_methods structure fails to allocate a block of memory
  19611. ** and returns 0).
  19612. **
  19613. ** Most malloc failures are non-benign. After they occur, SQLite
  19614. ** abandons the current operation and returns an error code (usually
  19615. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  19616. ** fatal. For example, if a malloc fails while resizing a hash table, this
  19617. ** is completely recoverable simply by not carrying out the resize. The
  19618. ** hash table will continue to function normally. So a malloc failure
  19619. ** during a hash table resize is a benign fault.
  19620. */
  19621. /* #include "sqliteInt.h" */
  19622. #ifndef SQLITE_UNTESTABLE
  19623. /*
  19624. ** Global variables.
  19625. */
  19626. typedef struct BenignMallocHooks BenignMallocHooks;
  19627. static SQLITE_WSD struct BenignMallocHooks {
  19628. void (*xBenignBegin)(void);
  19629. void (*xBenignEnd)(void);
  19630. } sqlite3Hooks = { 0, 0 };
  19631. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  19632. ** structure. If writable static data is unsupported on the target,
  19633. ** we have to locate the state vector at run-time. In the more common
  19634. ** case where writable static data is supported, wsdHooks can refer directly
  19635. ** to the "sqlite3Hooks" state vector declared above.
  19636. */
  19637. #ifdef SQLITE_OMIT_WSD
  19638. # define wsdHooksInit \
  19639. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  19640. # define wsdHooks x[0]
  19641. #else
  19642. # define wsdHooksInit
  19643. # define wsdHooks sqlite3Hooks
  19644. #endif
  19645. /*
  19646. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  19647. ** sqlite3EndBenignMalloc() are called, respectively.
  19648. */
  19649. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  19650. void (*xBenignBegin)(void),
  19651. void (*xBenignEnd)(void)
  19652. ){
  19653. wsdHooksInit;
  19654. wsdHooks.xBenignBegin = xBenignBegin;
  19655. wsdHooks.xBenignEnd = xBenignEnd;
  19656. }
  19657. /*
  19658. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  19659. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  19660. ** indicates that subsequent malloc failures are non-benign.
  19661. */
  19662. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  19663. wsdHooksInit;
  19664. if( wsdHooks.xBenignBegin ){
  19665. wsdHooks.xBenignBegin();
  19666. }
  19667. }
  19668. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  19669. wsdHooksInit;
  19670. if( wsdHooks.xBenignEnd ){
  19671. wsdHooks.xBenignEnd();
  19672. }
  19673. }
  19674. #endif /* #ifndef SQLITE_UNTESTABLE */
  19675. /************** End of fault.c ***********************************************/
  19676. /************** Begin file mem0.c ********************************************/
  19677. /*
  19678. ** 2008 October 28
  19679. **
  19680. ** The author disclaims copyright to this source code. In place of
  19681. ** a legal notice, here is a blessing:
  19682. **
  19683. ** May you do good and not evil.
  19684. ** May you find forgiveness for yourself and forgive others.
  19685. ** May you share freely, never taking more than you give.
  19686. **
  19687. *************************************************************************
  19688. **
  19689. ** This file contains a no-op memory allocation drivers for use when
  19690. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  19691. ** here always fail. SQLite will not operate with these drivers. These
  19692. ** are merely placeholders. Real drivers must be substituted using
  19693. ** sqlite3_config() before SQLite will operate.
  19694. */
  19695. /* #include "sqliteInt.h" */
  19696. /*
  19697. ** This version of the memory allocator is the default. It is
  19698. ** used when no other memory allocator is specified using compile-time
  19699. ** macros.
  19700. */
  19701. #ifdef SQLITE_ZERO_MALLOC
  19702. /*
  19703. ** No-op versions of all memory allocation routines
  19704. */
  19705. static void *sqlite3MemMalloc(int nByte){ return 0; }
  19706. static void sqlite3MemFree(void *pPrior){ return; }
  19707. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  19708. static int sqlite3MemSize(void *pPrior){ return 0; }
  19709. static int sqlite3MemRoundup(int n){ return n; }
  19710. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  19711. static void sqlite3MemShutdown(void *NotUsed){ return; }
  19712. /*
  19713. ** This routine is the only routine in this file with external linkage.
  19714. **
  19715. ** Populate the low-level memory allocation function pointers in
  19716. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  19717. */
  19718. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  19719. static const sqlite3_mem_methods defaultMethods = {
  19720. sqlite3MemMalloc,
  19721. sqlite3MemFree,
  19722. sqlite3MemRealloc,
  19723. sqlite3MemSize,
  19724. sqlite3MemRoundup,
  19725. sqlite3MemInit,
  19726. sqlite3MemShutdown,
  19727. 0
  19728. };
  19729. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  19730. }
  19731. #endif /* SQLITE_ZERO_MALLOC */
  19732. /************** End of mem0.c ************************************************/
  19733. /************** Begin file mem1.c ********************************************/
  19734. /*
  19735. ** 2007 August 14
  19736. **
  19737. ** The author disclaims copyright to this source code. In place of
  19738. ** a legal notice, here is a blessing:
  19739. **
  19740. ** May you do good and not evil.
  19741. ** May you find forgiveness for yourself and forgive others.
  19742. ** May you share freely, never taking more than you give.
  19743. **
  19744. *************************************************************************
  19745. **
  19746. ** This file contains low-level memory allocation drivers for when
  19747. ** SQLite will use the standard C-library malloc/realloc/free interface
  19748. ** to obtain the memory it needs.
  19749. **
  19750. ** This file contains implementations of the low-level memory allocation
  19751. ** routines specified in the sqlite3_mem_methods object. The content of
  19752. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  19753. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  19754. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  19755. ** default configuration is to use memory allocation routines in this
  19756. ** file.
  19757. **
  19758. ** C-preprocessor macro summary:
  19759. **
  19760. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  19761. ** the malloc_usable_size() interface exists
  19762. ** on the target platform. Or, this symbol
  19763. ** can be set manually, if desired.
  19764. ** If an equivalent interface exists by
  19765. ** a different name, using a separate -D
  19766. ** option to rename it.
  19767. **
  19768. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  19769. ** memory allocator. Set this symbol to enable
  19770. ** building on older macs.
  19771. **
  19772. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  19773. ** _msize() on windows systems. This might
  19774. ** be necessary when compiling for Delphi,
  19775. ** for example.
  19776. */
  19777. /* #include "sqliteInt.h" */
  19778. /*
  19779. ** This version of the memory allocator is the default. It is
  19780. ** used when no other memory allocator is specified using compile-time
  19781. ** macros.
  19782. */
  19783. #ifdef SQLITE_SYSTEM_MALLOC
  19784. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  19785. /*
  19786. ** Use the zone allocator available on apple products unless the
  19787. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  19788. */
  19789. #include <sys/sysctl.h>
  19790. #include <malloc/malloc.h>
  19791. #ifdef SQLITE_MIGHT_BE_SINGLE_CORE
  19792. #include <libkern/OSAtomic.h>
  19793. #endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
  19794. static malloc_zone_t* _sqliteZone_;
  19795. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  19796. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  19797. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  19798. #define SQLITE_MALLOCSIZE(x) \
  19799. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  19800. #elif defined(SQLITE_OS_RTTHREAD)
  19801. #include <rtthread.h>
  19802. /*
  19803. ** Use standard C library malloc and free on non-Apple systems.
  19804. ** Also used by rt-thread systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  19805. */
  19806. #define SQLITE_MALLOC(x) rt_malloc((rt_size_t)x)
  19807. #define SQLITE_FREE(x) rt_free(x)
  19808. #define SQLITE_REALLOC(x,y) rt_realloc((x),(rt_size_t)(y))
  19809. #if (!defined(SQLITE_WITHOUT_MSIZE)) \
  19810. && (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
  19811. #error "not have malloc_usable_size()"
  19812. #endif
  19813. #ifdef HAVE_MALLOC_USABLE_SIZE
  19814. #undef SQLITE_MALLOCSIZE
  19815. #endif
  19816. #ifdef SQLITE_USE_MSIZE
  19817. #rror "not have msize()"
  19818. #endif
  19819. #else /* if not __APPLE__ */
  19820. /*
  19821. ** Use standard C library malloc and free on non-Apple systems.
  19822. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  19823. */
  19824. #define SQLITE_MALLOC(x) malloc(x)
  19825. #define SQLITE_FREE(x) free(x)
  19826. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  19827. /*
  19828. ** The malloc.h header file is needed for malloc_usable_size() function
  19829. ** on some systems (e.g. Linux).
  19830. */
  19831. #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
  19832. # define SQLITE_USE_MALLOC_H 1
  19833. # define SQLITE_USE_MALLOC_USABLE_SIZE 1
  19834. /*
  19835. ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
  19836. ** use of _msize() is automatic, but can be disabled by compiling with
  19837. ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
  19838. ** the malloc.h header file.
  19839. */
  19840. #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  19841. # define SQLITE_USE_MALLOC_H
  19842. # define SQLITE_USE_MSIZE
  19843. #endif
  19844. /*
  19845. ** Include the malloc.h header file, if necessary. Also set define macro
  19846. ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
  19847. ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
  19848. ** The memory size function can always be overridden manually by defining
  19849. ** the macro SQLITE_MALLOCSIZE to the desired function name.
  19850. */
  19851. #if defined(SQLITE_USE_MALLOC_H)
  19852. # include <malloc.h>
  19853. # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
  19854. # if !defined(SQLITE_MALLOCSIZE)
  19855. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  19856. # endif
  19857. # elif defined(SQLITE_USE_MSIZE)
  19858. # if !defined(SQLITE_MALLOCSIZE)
  19859. # define SQLITE_MALLOCSIZE _msize
  19860. # endif
  19861. # endif
  19862. #endif /* defined(SQLITE_USE_MALLOC_H) */
  19863. #endif /* __APPLE__ or not __APPLE__ */
  19864. /*
  19865. ** Like malloc(), but remember the size of the allocation
  19866. ** so that we can find it later using sqlite3MemSize().
  19867. **
  19868. ** For this low-level routine, we are guaranteed that nByte>0 because
  19869. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  19870. ** routines.
  19871. */
  19872. static void *sqlite3MemMalloc(int nByte){
  19873. #ifdef SQLITE_MALLOCSIZE
  19874. void *p;
  19875. testcase( ROUND8(nByte)==nByte );
  19876. p = SQLITE_MALLOC( nByte );
  19877. if( p==0 ){
  19878. testcase( sqlite3GlobalConfig.xLog!=0 );
  19879. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  19880. }
  19881. return p;
  19882. #else
  19883. sqlite3_int64 *p;
  19884. assert( nByte>0 );
  19885. testcase( ROUND8(nByte)!=nByte );
  19886. p = SQLITE_MALLOC( nByte+8 );
  19887. if( p ){
  19888. p[0] = nByte;
  19889. p++;
  19890. }else{
  19891. testcase( sqlite3GlobalConfig.xLog!=0 );
  19892. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  19893. }
  19894. return (void *)p;
  19895. #endif
  19896. }
  19897. /*
  19898. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  19899. ** or sqlite3MemRealloc().
  19900. **
  19901. ** For this low-level routine, we already know that pPrior!=0 since
  19902. ** cases where pPrior==0 will have been intecepted and dealt with
  19903. ** by higher-level routines.
  19904. */
  19905. static void sqlite3MemFree(void *pPrior){
  19906. #ifdef SQLITE_MALLOCSIZE
  19907. SQLITE_FREE(pPrior);
  19908. #else
  19909. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  19910. assert( pPrior!=0 );
  19911. p--;
  19912. SQLITE_FREE(p);
  19913. #endif
  19914. }
  19915. /*
  19916. ** Report the allocated size of a prior return from xMalloc()
  19917. ** or xRealloc().
  19918. */
  19919. static int sqlite3MemSize(void *pPrior){
  19920. #ifdef SQLITE_MALLOCSIZE
  19921. assert( pPrior!=0 );
  19922. return (int)SQLITE_MALLOCSIZE(pPrior);
  19923. #else
  19924. sqlite3_int64 *p;
  19925. assert( pPrior!=0 );
  19926. p = (sqlite3_int64*)pPrior;
  19927. p--;
  19928. return (int)p[0];
  19929. #endif
  19930. }
  19931. /*
  19932. ** Like realloc(). Resize an allocation previously obtained from
  19933. ** sqlite3MemMalloc().
  19934. **
  19935. ** For this low-level interface, we know that pPrior!=0. Cases where
  19936. ** pPrior==0 while have been intercepted by higher-level routine and
  19937. ** redirected to xMalloc. Similarly, we know that nByte>0 because
  19938. ** cases where nByte<=0 will have been intercepted by higher-level
  19939. ** routines and redirected to xFree.
  19940. */
  19941. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  19942. #ifdef SQLITE_MALLOCSIZE
  19943. void *p = SQLITE_REALLOC(pPrior, nByte);
  19944. if( p==0 ){
  19945. testcase( sqlite3GlobalConfig.xLog!=0 );
  19946. sqlite3_log(SQLITE_NOMEM,
  19947. "failed memory resize %u to %u bytes",
  19948. SQLITE_MALLOCSIZE(pPrior), nByte);
  19949. }
  19950. return p;
  19951. #else
  19952. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  19953. assert( pPrior!=0 && nByte>0 );
  19954. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  19955. p--;
  19956. p = SQLITE_REALLOC(p, nByte+8 );
  19957. if( p ){
  19958. p[0] = nByte;
  19959. p++;
  19960. }else{
  19961. testcase( sqlite3GlobalConfig.xLog!=0 );
  19962. sqlite3_log(SQLITE_NOMEM,
  19963. "failed memory resize %u to %u bytes",
  19964. sqlite3MemSize(pPrior), nByte);
  19965. }
  19966. return (void*)p;
  19967. #endif
  19968. }
  19969. /*
  19970. ** Round up a request size to the next valid allocation size.
  19971. */
  19972. static int sqlite3MemRoundup(int n){
  19973. return ROUND8(n);
  19974. }
  19975. /*
  19976. ** Initialize this module.
  19977. */
  19978. static int sqlite3MemInit(void *NotUsed){
  19979. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  19980. int cpuCount;
  19981. size_t len;
  19982. if( _sqliteZone_ ){
  19983. return SQLITE_OK;
  19984. }
  19985. len = sizeof(cpuCount);
  19986. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  19987. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  19988. if( cpuCount>1 ){
  19989. /* defer MT decisions to system malloc */
  19990. _sqliteZone_ = malloc_default_zone();
  19991. }else{
  19992. /* only 1 core, use our own zone to contention over global locks,
  19993. ** e.g. we have our own dedicated locks */
  19994. _sqliteZone_ = malloc_create_zone(4096, 0);
  19995. malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
  19996. }
  19997. #endif /* defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
  19998. UNUSED_PARAMETER(NotUsed);
  19999. return SQLITE_OK;
  20000. }
  20001. /*
  20002. ** Deinitialize this module.
  20003. */
  20004. static void sqlite3MemShutdown(void *NotUsed){
  20005. UNUSED_PARAMETER(NotUsed);
  20006. return;
  20007. }
  20008. /*
  20009. ** This routine is the only routine in this file with external linkage.
  20010. **
  20011. ** Populate the low-level memory allocation function pointers in
  20012. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  20013. */
  20014. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  20015. static const sqlite3_mem_methods defaultMethods = {
  20016. sqlite3MemMalloc,
  20017. sqlite3MemFree,
  20018. sqlite3MemRealloc,
  20019. sqlite3MemSize,
  20020. sqlite3MemRoundup,
  20021. sqlite3MemInit,
  20022. sqlite3MemShutdown,
  20023. 0
  20024. };
  20025. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  20026. }
  20027. #endif /* SQLITE_SYSTEM_MALLOC */
  20028. /************** End of mem1.c ************************************************/
  20029. /************** Begin file mem2.c ********************************************/
  20030. /*
  20031. ** 2007 August 15
  20032. **
  20033. ** The author disclaims copyright to this source code. In place of
  20034. ** a legal notice, here is a blessing:
  20035. **
  20036. ** May you do good and not evil.
  20037. ** May you find forgiveness for yourself and forgive others.
  20038. ** May you share freely, never taking more than you give.
  20039. **
  20040. *************************************************************************
  20041. **
  20042. ** This file contains low-level memory allocation drivers for when
  20043. ** SQLite will use the standard C-library malloc/realloc/free interface
  20044. ** to obtain the memory it needs while adding lots of additional debugging
  20045. ** information to each allocation in order to help detect and fix memory
  20046. ** leaks and memory usage errors.
  20047. **
  20048. ** This file contains implementations of the low-level memory allocation
  20049. ** routines specified in the sqlite3_mem_methods object.
  20050. */
  20051. /* #include "sqliteInt.h" */
  20052. /*
  20053. ** This version of the memory allocator is used only if the
  20054. ** SQLITE_MEMDEBUG macro is defined
  20055. */
  20056. #ifdef SQLITE_MEMDEBUG
  20057. /*
  20058. ** The backtrace functionality is only available with GLIBC
  20059. */
  20060. #ifdef __GLIBC__
  20061. extern int backtrace(void**,int);
  20062. extern void backtrace_symbols_fd(void*const*,int,int);
  20063. #else
  20064. # define backtrace(A,B) 1
  20065. # define backtrace_symbols_fd(A,B,C)
  20066. #endif
  20067. /* #include <stdio.h> */
  20068. /*
  20069. ** Each memory allocation looks like this:
  20070. **
  20071. ** ------------------------------------------------------------------------
  20072. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  20073. ** ------------------------------------------------------------------------
  20074. **
  20075. ** The application code sees only a pointer to the allocation. We have
  20076. ** to back up from the allocation pointer to find the MemBlockHdr. The
  20077. ** MemBlockHdr tells us the size of the allocation and the number of
  20078. ** backtrace pointers. There is also a guard word at the end of the
  20079. ** MemBlockHdr.
  20080. */
  20081. struct MemBlockHdr {
  20082. i64 iSize; /* Size of this allocation */
  20083. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  20084. char nBacktrace; /* Number of backtraces on this alloc */
  20085. char nBacktraceSlots; /* Available backtrace slots */
  20086. u8 nTitle; /* Bytes of title; includes '\0' */
  20087. u8 eType; /* Allocation type code */
  20088. int iForeGuard; /* Guard word for sanity */
  20089. };
  20090. /*
  20091. ** Guard words
  20092. */
  20093. #define FOREGUARD 0x80F5E153
  20094. #define REARGUARD 0xE4676B53
  20095. /*
  20096. ** Number of malloc size increments to track.
  20097. */
  20098. #define NCSIZE 1000
  20099. /*
  20100. ** All of the static variables used by this module are collected
  20101. ** into a single structure named "mem". This is to keep the
  20102. ** static variables organized and to reduce namespace pollution
  20103. ** when this module is combined with other in the amalgamation.
  20104. */
  20105. static struct {
  20106. /*
  20107. ** Mutex to control access to the memory allocation subsystem.
  20108. */
  20109. sqlite3_mutex *mutex;
  20110. /*
  20111. ** Head and tail of a linked list of all outstanding allocations
  20112. */
  20113. struct MemBlockHdr *pFirst;
  20114. struct MemBlockHdr *pLast;
  20115. /*
  20116. ** The number of levels of backtrace to save in new allocations.
  20117. */
  20118. int nBacktrace;
  20119. void (*xBacktrace)(int, int, void **);
  20120. /*
  20121. ** Title text to insert in front of each block
  20122. */
  20123. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  20124. char zTitle[100]; /* The title text */
  20125. /*
  20126. ** sqlite3MallocDisallow() increments the following counter.
  20127. ** sqlite3MallocAllow() decrements it.
  20128. */
  20129. int disallow; /* Do not allow memory allocation */
  20130. /*
  20131. ** Gather statistics on the sizes of memory allocations.
  20132. ** nAlloc[i] is the number of allocation attempts of i*8
  20133. ** bytes. i==NCSIZE is the number of allocation attempts for
  20134. ** sizes more than NCSIZE*8 bytes.
  20135. */
  20136. int nAlloc[NCSIZE]; /* Total number of allocations */
  20137. int nCurrent[NCSIZE]; /* Current number of allocations */
  20138. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  20139. } mem;
  20140. /*
  20141. ** Adjust memory usage statistics
  20142. */
  20143. static void adjustStats(int iSize, int increment){
  20144. int i = ROUND8(iSize)/8;
  20145. if( i>NCSIZE-1 ){
  20146. i = NCSIZE - 1;
  20147. }
  20148. if( increment>0 ){
  20149. mem.nAlloc[i]++;
  20150. mem.nCurrent[i]++;
  20151. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  20152. mem.mxCurrent[i] = mem.nCurrent[i];
  20153. }
  20154. }else{
  20155. mem.nCurrent[i]--;
  20156. assert( mem.nCurrent[i]>=0 );
  20157. }
  20158. }
  20159. /*
  20160. ** Given an allocation, find the MemBlockHdr for that allocation.
  20161. **
  20162. ** This routine checks the guards at either end of the allocation and
  20163. ** if they are incorrect it asserts.
  20164. */
  20165. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  20166. struct MemBlockHdr *p;
  20167. int *pInt;
  20168. u8 *pU8;
  20169. int nReserve;
  20170. p = (struct MemBlockHdr*)pAllocation;
  20171. p--;
  20172. assert( p->iForeGuard==(int)FOREGUARD );
  20173. nReserve = ROUND8(p->iSize);
  20174. pInt = (int*)pAllocation;
  20175. pU8 = (u8*)pAllocation;
  20176. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  20177. /* This checks any of the "extra" bytes allocated due
  20178. ** to rounding up to an 8 byte boundary to ensure
  20179. ** they haven't been overwritten.
  20180. */
  20181. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  20182. return p;
  20183. }
  20184. /*
  20185. ** Return the number of bytes currently allocated at address p.
  20186. */
  20187. static int sqlite3MemSize(void *p){
  20188. struct MemBlockHdr *pHdr;
  20189. if( !p ){
  20190. return 0;
  20191. }
  20192. pHdr = sqlite3MemsysGetHeader(p);
  20193. return (int)pHdr->iSize;
  20194. }
  20195. /*
  20196. ** Initialize the memory allocation subsystem.
  20197. */
  20198. static int sqlite3MemInit(void *NotUsed){
  20199. UNUSED_PARAMETER(NotUsed);
  20200. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  20201. if( !sqlite3GlobalConfig.bMemstat ){
  20202. /* If memory status is enabled, then the malloc.c wrapper will already
  20203. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  20204. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  20205. }
  20206. return SQLITE_OK;
  20207. }
  20208. /*
  20209. ** Deinitialize the memory allocation subsystem.
  20210. */
  20211. static void sqlite3MemShutdown(void *NotUsed){
  20212. UNUSED_PARAMETER(NotUsed);
  20213. mem.mutex = 0;
  20214. }
  20215. /*
  20216. ** Round up a request size to the next valid allocation size.
  20217. */
  20218. static int sqlite3MemRoundup(int n){
  20219. return ROUND8(n);
  20220. }
  20221. /*
  20222. ** Fill a buffer with pseudo-random bytes. This is used to preset
  20223. ** the content of a new memory allocation to unpredictable values and
  20224. ** to clear the content of a freed allocation to unpredictable values.
  20225. */
  20226. static void randomFill(char *pBuf, int nByte){
  20227. unsigned int x, y, r;
  20228. x = SQLITE_PTR_TO_INT(pBuf);
  20229. y = nByte | 1;
  20230. while( nByte >= 4 ){
  20231. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  20232. y = y*1103515245 + 12345;
  20233. r = x ^ y;
  20234. *(int*)pBuf = r;
  20235. pBuf += 4;
  20236. nByte -= 4;
  20237. }
  20238. while( nByte-- > 0 ){
  20239. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  20240. y = y*1103515245 + 12345;
  20241. r = x ^ y;
  20242. *(pBuf++) = r & 0xff;
  20243. }
  20244. }
  20245. /*
  20246. ** Allocate nByte bytes of memory.
  20247. */
  20248. static void *sqlite3MemMalloc(int nByte){
  20249. struct MemBlockHdr *pHdr;
  20250. void **pBt;
  20251. char *z;
  20252. int *pInt;
  20253. void *p = 0;
  20254. int totalSize;
  20255. int nReserve;
  20256. sqlite3_mutex_enter(mem.mutex);
  20257. assert( mem.disallow==0 );
  20258. nReserve = ROUND8(nByte);
  20259. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  20260. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  20261. p = malloc(totalSize);
  20262. if( p ){
  20263. z = p;
  20264. pBt = (void**)&z[mem.nTitle];
  20265. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  20266. pHdr->pNext = 0;
  20267. pHdr->pPrev = mem.pLast;
  20268. if( mem.pLast ){
  20269. mem.pLast->pNext = pHdr;
  20270. }else{
  20271. mem.pFirst = pHdr;
  20272. }
  20273. mem.pLast = pHdr;
  20274. pHdr->iForeGuard = FOREGUARD;
  20275. pHdr->eType = MEMTYPE_HEAP;
  20276. pHdr->nBacktraceSlots = mem.nBacktrace;
  20277. pHdr->nTitle = mem.nTitle;
  20278. if( mem.nBacktrace ){
  20279. void *aAddr[40];
  20280. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  20281. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  20282. assert(pBt[0]);
  20283. if( mem.xBacktrace ){
  20284. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  20285. }
  20286. }else{
  20287. pHdr->nBacktrace = 0;
  20288. }
  20289. if( mem.nTitle ){
  20290. memcpy(z, mem.zTitle, mem.nTitle);
  20291. }
  20292. pHdr->iSize = nByte;
  20293. adjustStats(nByte, +1);
  20294. pInt = (int*)&pHdr[1];
  20295. pInt[nReserve/sizeof(int)] = REARGUARD;
  20296. randomFill((char*)pInt, nByte);
  20297. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  20298. p = (void*)pInt;
  20299. }
  20300. sqlite3_mutex_leave(mem.mutex);
  20301. return p;
  20302. }
  20303. /*
  20304. ** Free memory.
  20305. */
  20306. static void sqlite3MemFree(void *pPrior){
  20307. struct MemBlockHdr *pHdr;
  20308. void **pBt;
  20309. char *z;
  20310. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  20311. || mem.mutex!=0 );
  20312. pHdr = sqlite3MemsysGetHeader(pPrior);
  20313. pBt = (void**)pHdr;
  20314. pBt -= pHdr->nBacktraceSlots;
  20315. sqlite3_mutex_enter(mem.mutex);
  20316. if( pHdr->pPrev ){
  20317. assert( pHdr->pPrev->pNext==pHdr );
  20318. pHdr->pPrev->pNext = pHdr->pNext;
  20319. }else{
  20320. assert( mem.pFirst==pHdr );
  20321. mem.pFirst = pHdr->pNext;
  20322. }
  20323. if( pHdr->pNext ){
  20324. assert( pHdr->pNext->pPrev==pHdr );
  20325. pHdr->pNext->pPrev = pHdr->pPrev;
  20326. }else{
  20327. assert( mem.pLast==pHdr );
  20328. mem.pLast = pHdr->pPrev;
  20329. }
  20330. z = (char*)pBt;
  20331. z -= pHdr->nTitle;
  20332. adjustStats((int)pHdr->iSize, -1);
  20333. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  20334. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  20335. free(z);
  20336. sqlite3_mutex_leave(mem.mutex);
  20337. }
  20338. /*
  20339. ** Change the size of an existing memory allocation.
  20340. **
  20341. ** For this debugging implementation, we *always* make a copy of the
  20342. ** allocation into a new place in memory. In this way, if the
  20343. ** higher level code is using pointer to the old allocation, it is
  20344. ** much more likely to break and we are much more liking to find
  20345. ** the error.
  20346. */
  20347. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  20348. struct MemBlockHdr *pOldHdr;
  20349. void *pNew;
  20350. assert( mem.disallow==0 );
  20351. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  20352. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  20353. pNew = sqlite3MemMalloc(nByte);
  20354. if( pNew ){
  20355. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  20356. if( nByte>pOldHdr->iSize ){
  20357. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  20358. }
  20359. sqlite3MemFree(pPrior);
  20360. }
  20361. return pNew;
  20362. }
  20363. /*
  20364. ** Populate the low-level memory allocation function pointers in
  20365. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  20366. */
  20367. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  20368. static const sqlite3_mem_methods defaultMethods = {
  20369. sqlite3MemMalloc,
  20370. sqlite3MemFree,
  20371. sqlite3MemRealloc,
  20372. sqlite3MemSize,
  20373. sqlite3MemRoundup,
  20374. sqlite3MemInit,
  20375. sqlite3MemShutdown,
  20376. 0
  20377. };
  20378. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  20379. }
  20380. /*
  20381. ** Set the "type" of an allocation.
  20382. */
  20383. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  20384. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  20385. struct MemBlockHdr *pHdr;
  20386. pHdr = sqlite3MemsysGetHeader(p);
  20387. assert( pHdr->iForeGuard==FOREGUARD );
  20388. pHdr->eType = eType;
  20389. }
  20390. }
  20391. /*
  20392. ** Return TRUE if the mask of type in eType matches the type of the
  20393. ** allocation p. Also return true if p==NULL.
  20394. **
  20395. ** This routine is designed for use within an assert() statement, to
  20396. ** verify the type of an allocation. For example:
  20397. **
  20398. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  20399. */
  20400. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  20401. int rc = 1;
  20402. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  20403. struct MemBlockHdr *pHdr;
  20404. pHdr = sqlite3MemsysGetHeader(p);
  20405. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  20406. if( (pHdr->eType&eType)==0 ){
  20407. rc = 0;
  20408. }
  20409. }
  20410. return rc;
  20411. }
  20412. /*
  20413. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  20414. ** allocation p. Also return true if p==NULL.
  20415. **
  20416. ** This routine is designed for use within an assert() statement, to
  20417. ** verify the type of an allocation. For example:
  20418. **
  20419. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  20420. */
  20421. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  20422. int rc = 1;
  20423. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  20424. struct MemBlockHdr *pHdr;
  20425. pHdr = sqlite3MemsysGetHeader(p);
  20426. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  20427. if( (pHdr->eType&eType)!=0 ){
  20428. rc = 0;
  20429. }
  20430. }
  20431. return rc;
  20432. }
  20433. /*
  20434. ** Set the number of backtrace levels kept for each allocation.
  20435. ** A value of zero turns off backtracing. The number is always rounded
  20436. ** up to a multiple of 2.
  20437. */
  20438. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  20439. if( depth<0 ){ depth = 0; }
  20440. if( depth>20 ){ depth = 20; }
  20441. depth = (depth+1)&0xfe;
  20442. mem.nBacktrace = depth;
  20443. }
  20444. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  20445. mem.xBacktrace = xBacktrace;
  20446. }
  20447. /*
  20448. ** Set the title string for subsequent allocations.
  20449. */
  20450. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  20451. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  20452. sqlite3_mutex_enter(mem.mutex);
  20453. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  20454. memcpy(mem.zTitle, zTitle, n);
  20455. mem.zTitle[n] = 0;
  20456. mem.nTitle = ROUND8(n);
  20457. sqlite3_mutex_leave(mem.mutex);
  20458. }
  20459. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  20460. struct MemBlockHdr *pHdr;
  20461. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  20462. void **pBt = (void**)pHdr;
  20463. pBt -= pHdr->nBacktraceSlots;
  20464. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  20465. }
  20466. }
  20467. /*
  20468. ** Open the file indicated and write a log of all unfreed memory
  20469. ** allocations into that log.
  20470. */
  20471. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  20472. FILE *out;
  20473. struct MemBlockHdr *pHdr;
  20474. void **pBt;
  20475. int i;
  20476. out = fopen(zFilename, "w");
  20477. if( out==0 ){
  20478. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  20479. zFilename);
  20480. return;
  20481. }
  20482. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  20483. char *z = (char*)pHdr;
  20484. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  20485. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  20486. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  20487. if( pHdr->nBacktrace ){
  20488. fflush(out);
  20489. pBt = (void**)pHdr;
  20490. pBt -= pHdr->nBacktraceSlots;
  20491. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  20492. fprintf(out, "\n");
  20493. }
  20494. }
  20495. fprintf(out, "COUNTS:\n");
  20496. for(i=0; i<NCSIZE-1; i++){
  20497. if( mem.nAlloc[i] ){
  20498. fprintf(out, " %5d: %10d %10d %10d\n",
  20499. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  20500. }
  20501. }
  20502. if( mem.nAlloc[NCSIZE-1] ){
  20503. fprintf(out, " %5d: %10d %10d %10d\n",
  20504. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  20505. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  20506. }
  20507. fclose(out);
  20508. }
  20509. /*
  20510. ** Return the number of times sqlite3MemMalloc() has been called.
  20511. */
  20512. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  20513. int i;
  20514. int nTotal = 0;
  20515. for(i=0; i<NCSIZE; i++){
  20516. nTotal += mem.nAlloc[i];
  20517. }
  20518. return nTotal;
  20519. }
  20520. #endif /* SQLITE_MEMDEBUG */
  20521. /************** End of mem2.c ************************************************/
  20522. /************** Begin file mem3.c ********************************************/
  20523. /*
  20524. ** 2007 October 14
  20525. **
  20526. ** The author disclaims copyright to this source code. In place of
  20527. ** a legal notice, here is a blessing:
  20528. **
  20529. ** May you do good and not evil.
  20530. ** May you find forgiveness for yourself and forgive others.
  20531. ** May you share freely, never taking more than you give.
  20532. **
  20533. *************************************************************************
  20534. ** This file contains the C functions that implement a memory
  20535. ** allocation subsystem for use by SQLite.
  20536. **
  20537. ** This version of the memory allocation subsystem omits all
  20538. ** use of malloc(). The SQLite user supplies a block of memory
  20539. ** before calling sqlite3_initialize() from which allocations
  20540. ** are made and returned by the xMalloc() and xRealloc()
  20541. ** implementations. Once sqlite3_initialize() has been called,
  20542. ** the amount of memory available to SQLite is fixed and cannot
  20543. ** be changed.
  20544. **
  20545. ** This version of the memory allocation subsystem is included
  20546. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  20547. */
  20548. /* #include "sqliteInt.h" */
  20549. /*
  20550. ** This version of the memory allocator is only built into the library
  20551. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  20552. ** mean that the library will use a memory-pool by default, just that
  20553. ** it is available. The mempool allocator is activated by calling
  20554. ** sqlite3_config().
  20555. */
  20556. #ifdef SQLITE_ENABLE_MEMSYS3
  20557. /*
  20558. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  20559. */
  20560. #define MX_SMALL 10
  20561. /*
  20562. ** Number of freelist hash slots
  20563. */
  20564. #define N_HASH 61
  20565. /*
  20566. ** A memory allocation (also called a "chunk") consists of two or
  20567. ** more blocks where each block is 8 bytes. The first 8 bytes are
  20568. ** a header that is not returned to the user.
  20569. **
  20570. ** A chunk is two or more blocks that is either checked out or
  20571. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  20572. ** size of the allocation in blocks if the allocation is free.
  20573. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  20574. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  20575. ** is true if the previous chunk is checked out and false if the
  20576. ** previous chunk is free. The u.hdr.prevSize field is the size of
  20577. ** the previous chunk in blocks if the previous chunk is on the
  20578. ** freelist. If the previous chunk is checked out, then
  20579. ** u.hdr.prevSize can be part of the data for that chunk and should
  20580. ** not be read or written.
  20581. **
  20582. ** We often identify a chunk by its index in mem3.aPool[]. When
  20583. ** this is done, the chunk index refers to the second block of
  20584. ** the chunk. In this way, the first chunk has an index of 1.
  20585. ** A chunk index of 0 means "no such chunk" and is the equivalent
  20586. ** of a NULL pointer.
  20587. **
  20588. ** The second block of free chunks is of the form u.list. The
  20589. ** two fields form a double-linked list of chunks of related sizes.
  20590. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  20591. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  20592. **
  20593. ** The second block of a chunk is user data if the chunk is checked
  20594. ** out. If a chunk is checked out, the user data may extend into
  20595. ** the u.hdr.prevSize value of the following chunk.
  20596. */
  20597. typedef struct Mem3Block Mem3Block;
  20598. struct Mem3Block {
  20599. union {
  20600. struct {
  20601. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  20602. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  20603. } hdr;
  20604. struct {
  20605. u32 next; /* Index in mem3.aPool[] of next free chunk */
  20606. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  20607. } list;
  20608. } u;
  20609. };
  20610. /*
  20611. ** All of the static variables used by this module are collected
  20612. ** into a single structure named "mem3". This is to keep the
  20613. ** static variables organized and to reduce namespace pollution
  20614. ** when this module is combined with other in the amalgamation.
  20615. */
  20616. static SQLITE_WSD struct Mem3Global {
  20617. /*
  20618. ** Memory available for allocation. nPool is the size of the array
  20619. ** (in Mem3Blocks) pointed to by aPool less 2.
  20620. */
  20621. u32 nPool;
  20622. Mem3Block *aPool;
  20623. /*
  20624. ** True if we are evaluating an out-of-memory callback.
  20625. */
  20626. int alarmBusy;
  20627. /*
  20628. ** Mutex to control access to the memory allocation subsystem.
  20629. */
  20630. sqlite3_mutex *mutex;
  20631. /*
  20632. ** The minimum amount of free space that we have seen.
  20633. */
  20634. u32 mnMaster;
  20635. /*
  20636. ** iMaster is the index of the master chunk. Most new allocations
  20637. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  20638. ** of the current master. iMaster is 0 if there is not master chunk.
  20639. ** The master chunk is not in either the aiHash[] or aiSmall[].
  20640. */
  20641. u32 iMaster;
  20642. u32 szMaster;
  20643. /*
  20644. ** Array of lists of free blocks according to the block size
  20645. ** for smaller chunks, or a hash on the block size for larger
  20646. ** chunks.
  20647. */
  20648. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  20649. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  20650. } mem3 = { 97535575 };
  20651. #define mem3 GLOBAL(struct Mem3Global, mem3)
  20652. /*
  20653. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  20654. ** on. *pRoot is the list that i is a member of.
  20655. */
  20656. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  20657. u32 next = mem3.aPool[i].u.list.next;
  20658. u32 prev = mem3.aPool[i].u.list.prev;
  20659. assert( sqlite3_mutex_held(mem3.mutex) );
  20660. if( prev==0 ){
  20661. *pRoot = next;
  20662. }else{
  20663. mem3.aPool[prev].u.list.next = next;
  20664. }
  20665. if( next ){
  20666. mem3.aPool[next].u.list.prev = prev;
  20667. }
  20668. mem3.aPool[i].u.list.next = 0;
  20669. mem3.aPool[i].u.list.prev = 0;
  20670. }
  20671. /*
  20672. ** Unlink the chunk at index i from
  20673. ** whatever list is currently a member of.
  20674. */
  20675. static void memsys3Unlink(u32 i){
  20676. u32 size, hash;
  20677. assert( sqlite3_mutex_held(mem3.mutex) );
  20678. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  20679. assert( i>=1 );
  20680. size = mem3.aPool[i-1].u.hdr.size4x/4;
  20681. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  20682. assert( size>=2 );
  20683. if( size <= MX_SMALL ){
  20684. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  20685. }else{
  20686. hash = size % N_HASH;
  20687. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  20688. }
  20689. }
  20690. /*
  20691. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  20692. ** at *pRoot.
  20693. */
  20694. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  20695. assert( sqlite3_mutex_held(mem3.mutex) );
  20696. mem3.aPool[i].u.list.next = *pRoot;
  20697. mem3.aPool[i].u.list.prev = 0;
  20698. if( *pRoot ){
  20699. mem3.aPool[*pRoot].u.list.prev = i;
  20700. }
  20701. *pRoot = i;
  20702. }
  20703. /*
  20704. ** Link the chunk at index i into either the appropriate
  20705. ** small chunk list, or into the large chunk hash table.
  20706. */
  20707. static void memsys3Link(u32 i){
  20708. u32 size, hash;
  20709. assert( sqlite3_mutex_held(mem3.mutex) );
  20710. assert( i>=1 );
  20711. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  20712. size = mem3.aPool[i-1].u.hdr.size4x/4;
  20713. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  20714. assert( size>=2 );
  20715. if( size <= MX_SMALL ){
  20716. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  20717. }else{
  20718. hash = size % N_HASH;
  20719. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  20720. }
  20721. }
  20722. /*
  20723. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  20724. ** will already be held (obtained by code in malloc.c) if
  20725. ** sqlite3GlobalConfig.bMemStat is true.
  20726. */
  20727. static void memsys3Enter(void){
  20728. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  20729. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  20730. }
  20731. sqlite3_mutex_enter(mem3.mutex);
  20732. }
  20733. static void memsys3Leave(void){
  20734. sqlite3_mutex_leave(mem3.mutex);
  20735. }
  20736. /*
  20737. ** Called when we are unable to satisfy an allocation of nBytes.
  20738. */
  20739. static void memsys3OutOfMemory(int nByte){
  20740. if( !mem3.alarmBusy ){
  20741. mem3.alarmBusy = 1;
  20742. assert( sqlite3_mutex_held(mem3.mutex) );
  20743. sqlite3_mutex_leave(mem3.mutex);
  20744. sqlite3_release_memory(nByte);
  20745. sqlite3_mutex_enter(mem3.mutex);
  20746. mem3.alarmBusy = 0;
  20747. }
  20748. }
  20749. /*
  20750. ** Chunk i is a free chunk that has been unlinked. Adjust its
  20751. ** size parameters for check-out and return a pointer to the
  20752. ** user portion of the chunk.
  20753. */
  20754. static void *memsys3Checkout(u32 i, u32 nBlock){
  20755. u32 x;
  20756. assert( sqlite3_mutex_held(mem3.mutex) );
  20757. assert( i>=1 );
  20758. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  20759. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  20760. x = mem3.aPool[i-1].u.hdr.size4x;
  20761. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  20762. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  20763. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  20764. return &mem3.aPool[i];
  20765. }
  20766. /*
  20767. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  20768. ** Return a pointer to the new allocation. Or, if the master chunk
  20769. ** is not large enough, return 0.
  20770. */
  20771. static void *memsys3FromMaster(u32 nBlock){
  20772. assert( sqlite3_mutex_held(mem3.mutex) );
  20773. assert( mem3.szMaster>=nBlock );
  20774. if( nBlock>=mem3.szMaster-1 ){
  20775. /* Use the entire master */
  20776. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  20777. mem3.iMaster = 0;
  20778. mem3.szMaster = 0;
  20779. mem3.mnMaster = 0;
  20780. return p;
  20781. }else{
  20782. /* Split the master block. Return the tail. */
  20783. u32 newi, x;
  20784. newi = mem3.iMaster + mem3.szMaster - nBlock;
  20785. assert( newi > mem3.iMaster+1 );
  20786. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  20787. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  20788. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  20789. mem3.szMaster -= nBlock;
  20790. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  20791. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  20792. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  20793. if( mem3.szMaster < mem3.mnMaster ){
  20794. mem3.mnMaster = mem3.szMaster;
  20795. }
  20796. return (void*)&mem3.aPool[newi];
  20797. }
  20798. }
  20799. /*
  20800. ** *pRoot is the head of a list of free chunks of the same size
  20801. ** or same size hash. In other words, *pRoot is an entry in either
  20802. ** mem3.aiSmall[] or mem3.aiHash[].
  20803. **
  20804. ** This routine examines all entries on the given list and tries
  20805. ** to coalesce each entries with adjacent free chunks.
  20806. **
  20807. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  20808. ** the current mem3.iMaster with the new larger chunk. In order for
  20809. ** this mem3.iMaster replacement to work, the master chunk must be
  20810. ** linked into the hash tables. That is not the normal state of
  20811. ** affairs, of course. The calling routine must link the master
  20812. ** chunk before invoking this routine, then must unlink the (possibly
  20813. ** changed) master chunk once this routine has finished.
  20814. */
  20815. static void memsys3Merge(u32 *pRoot){
  20816. u32 iNext, prev, size, i, x;
  20817. assert( sqlite3_mutex_held(mem3.mutex) );
  20818. for(i=*pRoot; i>0; i=iNext){
  20819. iNext = mem3.aPool[i].u.list.next;
  20820. size = mem3.aPool[i-1].u.hdr.size4x;
  20821. assert( (size&1)==0 );
  20822. if( (size&2)==0 ){
  20823. memsys3UnlinkFromList(i, pRoot);
  20824. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  20825. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  20826. if( prev==iNext ){
  20827. iNext = mem3.aPool[prev].u.list.next;
  20828. }
  20829. memsys3Unlink(prev);
  20830. size = i + size/4 - prev;
  20831. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  20832. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  20833. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  20834. memsys3Link(prev);
  20835. i = prev;
  20836. }else{
  20837. size /= 4;
  20838. }
  20839. if( size>mem3.szMaster ){
  20840. mem3.iMaster = i;
  20841. mem3.szMaster = size;
  20842. }
  20843. }
  20844. }
  20845. /*
  20846. ** Return a block of memory of at least nBytes in size.
  20847. ** Return NULL if unable.
  20848. **
  20849. ** This function assumes that the necessary mutexes, if any, are
  20850. ** already held by the caller. Hence "Unsafe".
  20851. */
  20852. static void *memsys3MallocUnsafe(int nByte){
  20853. u32 i;
  20854. u32 nBlock;
  20855. u32 toFree;
  20856. assert( sqlite3_mutex_held(mem3.mutex) );
  20857. assert( sizeof(Mem3Block)==8 );
  20858. if( nByte<=12 ){
  20859. nBlock = 2;
  20860. }else{
  20861. nBlock = (nByte + 11)/8;
  20862. }
  20863. assert( nBlock>=2 );
  20864. /* STEP 1:
  20865. ** Look for an entry of the correct size in either the small
  20866. ** chunk table or in the large chunk hash table. This is
  20867. ** successful most of the time (about 9 times out of 10).
  20868. */
  20869. if( nBlock <= MX_SMALL ){
  20870. i = mem3.aiSmall[nBlock-2];
  20871. if( i>0 ){
  20872. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  20873. return memsys3Checkout(i, nBlock);
  20874. }
  20875. }else{
  20876. int hash = nBlock % N_HASH;
  20877. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  20878. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  20879. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  20880. return memsys3Checkout(i, nBlock);
  20881. }
  20882. }
  20883. }
  20884. /* STEP 2:
  20885. ** Try to satisfy the allocation by carving a piece off of the end
  20886. ** of the master chunk. This step usually works if step 1 fails.
  20887. */
  20888. if( mem3.szMaster>=nBlock ){
  20889. return memsys3FromMaster(nBlock);
  20890. }
  20891. /* STEP 3:
  20892. ** Loop through the entire memory pool. Coalesce adjacent free
  20893. ** chunks. Recompute the master chunk as the largest free chunk.
  20894. ** Then try again to satisfy the allocation by carving a piece off
  20895. ** of the end of the master chunk. This step happens very
  20896. ** rarely (we hope!)
  20897. */
  20898. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  20899. memsys3OutOfMemory(toFree);
  20900. if( mem3.iMaster ){
  20901. memsys3Link(mem3.iMaster);
  20902. mem3.iMaster = 0;
  20903. mem3.szMaster = 0;
  20904. }
  20905. for(i=0; i<N_HASH; i++){
  20906. memsys3Merge(&mem3.aiHash[i]);
  20907. }
  20908. for(i=0; i<MX_SMALL-1; i++){
  20909. memsys3Merge(&mem3.aiSmall[i]);
  20910. }
  20911. if( mem3.szMaster ){
  20912. memsys3Unlink(mem3.iMaster);
  20913. if( mem3.szMaster>=nBlock ){
  20914. return memsys3FromMaster(nBlock);
  20915. }
  20916. }
  20917. }
  20918. /* If none of the above worked, then we fail. */
  20919. return 0;
  20920. }
  20921. /*
  20922. ** Free an outstanding memory allocation.
  20923. **
  20924. ** This function assumes that the necessary mutexes, if any, are
  20925. ** already held by the caller. Hence "Unsafe".
  20926. */
  20927. static void memsys3FreeUnsafe(void *pOld){
  20928. Mem3Block *p = (Mem3Block*)pOld;
  20929. int i;
  20930. u32 size, x;
  20931. assert( sqlite3_mutex_held(mem3.mutex) );
  20932. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  20933. i = p - mem3.aPool;
  20934. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  20935. size = mem3.aPool[i-1].u.hdr.size4x/4;
  20936. assert( i+size<=mem3.nPool+1 );
  20937. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  20938. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  20939. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  20940. memsys3Link(i);
  20941. /* Try to expand the master using the newly freed chunk */
  20942. if( mem3.iMaster ){
  20943. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  20944. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  20945. mem3.iMaster -= size;
  20946. mem3.szMaster += size;
  20947. memsys3Unlink(mem3.iMaster);
  20948. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  20949. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  20950. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  20951. }
  20952. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  20953. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  20954. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  20955. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  20956. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  20957. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  20958. }
  20959. }
  20960. }
  20961. /*
  20962. ** Return the size of an outstanding allocation, in bytes. The
  20963. ** size returned omits the 8-byte header overhead. This only
  20964. ** works for chunks that are currently checked out.
  20965. */
  20966. static int memsys3Size(void *p){
  20967. Mem3Block *pBlock;
  20968. assert( p!=0 );
  20969. pBlock = (Mem3Block*)p;
  20970. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  20971. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  20972. }
  20973. /*
  20974. ** Round up a request size to the next valid allocation size.
  20975. */
  20976. static int memsys3Roundup(int n){
  20977. if( n<=12 ){
  20978. return 12;
  20979. }else{
  20980. return ((n+11)&~7) - 4;
  20981. }
  20982. }
  20983. /*
  20984. ** Allocate nBytes of memory.
  20985. */
  20986. static void *memsys3Malloc(int nBytes){
  20987. sqlite3_int64 *p;
  20988. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  20989. memsys3Enter();
  20990. p = memsys3MallocUnsafe(nBytes);
  20991. memsys3Leave();
  20992. return (void*)p;
  20993. }
  20994. /*
  20995. ** Free memory.
  20996. */
  20997. static void memsys3Free(void *pPrior){
  20998. assert( pPrior );
  20999. memsys3Enter();
  21000. memsys3FreeUnsafe(pPrior);
  21001. memsys3Leave();
  21002. }
  21003. /*
  21004. ** Change the size of an existing memory allocation
  21005. */
  21006. static void *memsys3Realloc(void *pPrior, int nBytes){
  21007. int nOld;
  21008. void *p;
  21009. if( pPrior==0 ){
  21010. return sqlite3_malloc(nBytes);
  21011. }
  21012. if( nBytes<=0 ){
  21013. sqlite3_free(pPrior);
  21014. return 0;
  21015. }
  21016. nOld = memsys3Size(pPrior);
  21017. if( nBytes<=nOld && nBytes>=nOld-128 ){
  21018. return pPrior;
  21019. }
  21020. memsys3Enter();
  21021. p = memsys3MallocUnsafe(nBytes);
  21022. if( p ){
  21023. if( nOld<nBytes ){
  21024. memcpy(p, pPrior, nOld);
  21025. }else{
  21026. memcpy(p, pPrior, nBytes);
  21027. }
  21028. memsys3FreeUnsafe(pPrior);
  21029. }
  21030. memsys3Leave();
  21031. return p;
  21032. }
  21033. /*
  21034. ** Initialize this module.
  21035. */
  21036. static int memsys3Init(void *NotUsed){
  21037. UNUSED_PARAMETER(NotUsed);
  21038. if( !sqlite3GlobalConfig.pHeap ){
  21039. return SQLITE_ERROR;
  21040. }
  21041. /* Store a pointer to the memory block in global structure mem3. */
  21042. assert( sizeof(Mem3Block)==8 );
  21043. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  21044. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  21045. /* Initialize the master block. */
  21046. mem3.szMaster = mem3.nPool;
  21047. mem3.mnMaster = mem3.szMaster;
  21048. mem3.iMaster = 1;
  21049. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  21050. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  21051. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  21052. return SQLITE_OK;
  21053. }
  21054. /*
  21055. ** Deinitialize this module.
  21056. */
  21057. static void memsys3Shutdown(void *NotUsed){
  21058. UNUSED_PARAMETER(NotUsed);
  21059. mem3.mutex = 0;
  21060. return;
  21061. }
  21062. /*
  21063. ** Open the file indicated and write a log of all unfreed memory
  21064. ** allocations into that log.
  21065. */
  21066. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  21067. #ifdef SQLITE_DEBUG
  21068. FILE *out;
  21069. u32 i, j;
  21070. u32 size;
  21071. if( zFilename==0 || zFilename[0]==0 ){
  21072. out = stdout;
  21073. }else{
  21074. out = fopen(zFilename, "w");
  21075. if( out==0 ){
  21076. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  21077. zFilename);
  21078. return;
  21079. }
  21080. }
  21081. memsys3Enter();
  21082. fprintf(out, "CHUNKS:\n");
  21083. for(i=1; i<=mem3.nPool; i+=size/4){
  21084. size = mem3.aPool[i-1].u.hdr.size4x;
  21085. if( size/4<=1 ){
  21086. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  21087. assert( 0 );
  21088. break;
  21089. }
  21090. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  21091. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  21092. assert( 0 );
  21093. break;
  21094. }
  21095. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  21096. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  21097. assert( 0 );
  21098. break;
  21099. }
  21100. if( size&1 ){
  21101. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  21102. }else{
  21103. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  21104. i==mem3.iMaster ? " **master**" : "");
  21105. }
  21106. }
  21107. for(i=0; i<MX_SMALL-1; i++){
  21108. if( mem3.aiSmall[i]==0 ) continue;
  21109. fprintf(out, "small(%2d):", i);
  21110. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  21111. fprintf(out, " %p(%d)", &mem3.aPool[j],
  21112. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  21113. }
  21114. fprintf(out, "\n");
  21115. }
  21116. for(i=0; i<N_HASH; i++){
  21117. if( mem3.aiHash[i]==0 ) continue;
  21118. fprintf(out, "hash(%2d):", i);
  21119. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  21120. fprintf(out, " %p(%d)", &mem3.aPool[j],
  21121. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  21122. }
  21123. fprintf(out, "\n");
  21124. }
  21125. fprintf(out, "master=%d\n", mem3.iMaster);
  21126. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  21127. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  21128. sqlite3_mutex_leave(mem3.mutex);
  21129. if( out==stdout ){
  21130. fflush(stdout);
  21131. }else{
  21132. fclose(out);
  21133. }
  21134. #else
  21135. UNUSED_PARAMETER(zFilename);
  21136. #endif
  21137. }
  21138. /*
  21139. ** This routine is the only routine in this file with external
  21140. ** linkage.
  21141. **
  21142. ** Populate the low-level memory allocation function pointers in
  21143. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  21144. ** arguments specify the block of memory to manage.
  21145. **
  21146. ** This routine is only called by sqlite3_config(), and therefore
  21147. ** is not required to be threadsafe (it is not).
  21148. */
  21149. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  21150. static const sqlite3_mem_methods mempoolMethods = {
  21151. memsys3Malloc,
  21152. memsys3Free,
  21153. memsys3Realloc,
  21154. memsys3Size,
  21155. memsys3Roundup,
  21156. memsys3Init,
  21157. memsys3Shutdown,
  21158. 0
  21159. };
  21160. return &mempoolMethods;
  21161. }
  21162. #endif /* SQLITE_ENABLE_MEMSYS3 */
  21163. /************** End of mem3.c ************************************************/
  21164. /************** Begin file mem5.c ********************************************/
  21165. /*
  21166. ** 2007 October 14
  21167. **
  21168. ** The author disclaims copyright to this source code. In place of
  21169. ** a legal notice, here is a blessing:
  21170. **
  21171. ** May you do good and not evil.
  21172. ** May you find forgiveness for yourself and forgive others.
  21173. ** May you share freely, never taking more than you give.
  21174. **
  21175. *************************************************************************
  21176. ** This file contains the C functions that implement a memory
  21177. ** allocation subsystem for use by SQLite.
  21178. **
  21179. ** This version of the memory allocation subsystem omits all
  21180. ** use of malloc(). The application gives SQLite a block of memory
  21181. ** before calling sqlite3_initialize() from which allocations
  21182. ** are made and returned by the xMalloc() and xRealloc()
  21183. ** implementations. Once sqlite3_initialize() has been called,
  21184. ** the amount of memory available to SQLite is fixed and cannot
  21185. ** be changed.
  21186. **
  21187. ** This version of the memory allocation subsystem is included
  21188. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  21189. **
  21190. ** This memory allocator uses the following algorithm:
  21191. **
  21192. ** 1. All memory allocation sizes are rounded up to a power of 2.
  21193. **
  21194. ** 2. If two adjacent free blocks are the halves of a larger block,
  21195. ** then the two blocks are coalesced into the single larger block.
  21196. **
  21197. ** 3. New memory is allocated from the first available free block.
  21198. **
  21199. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  21200. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  21201. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  21202. **
  21203. ** Let n be the size of the largest allocation divided by the minimum
  21204. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  21205. ** be the maximum amount of memory ever outstanding at one time. Let
  21206. ** N be the total amount of memory available for allocation. Robson
  21207. ** proved that this memory allocator will never breakdown due to
  21208. ** fragmentation as long as the following constraint holds:
  21209. **
  21210. ** N >= M*(1 + log2(n)/2) - n + 1
  21211. **
  21212. ** The sqlite3_status() logic tracks the maximum values of n and M so
  21213. ** that an application can, at any time, verify this constraint.
  21214. */
  21215. /* #include "sqliteInt.h" */
  21216. /*
  21217. ** This version of the memory allocator is used only when
  21218. ** SQLITE_ENABLE_MEMSYS5 is defined.
  21219. */
  21220. #ifdef SQLITE_ENABLE_MEMSYS5
  21221. /*
  21222. ** A minimum allocation is an instance of the following structure.
  21223. ** Larger allocations are an array of these structures where the
  21224. ** size of the array is a power of 2.
  21225. **
  21226. ** The size of this object must be a power of two. That fact is
  21227. ** verified in memsys5Init().
  21228. */
  21229. typedef struct Mem5Link Mem5Link;
  21230. struct Mem5Link {
  21231. int next; /* Index of next free chunk */
  21232. int prev; /* Index of previous free chunk */
  21233. };
  21234. /*
  21235. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  21236. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  21237. ** it is not actually possible to reach this limit.
  21238. */
  21239. #define LOGMAX 30
  21240. /*
  21241. ** Masks used for mem5.aCtrl[] elements.
  21242. */
  21243. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  21244. #define CTRL_FREE 0x20 /* True if not checked out */
  21245. /*
  21246. ** All of the static variables used by this module are collected
  21247. ** into a single structure named "mem5". This is to keep the
  21248. ** static variables organized and to reduce namespace pollution
  21249. ** when this module is combined with other in the amalgamation.
  21250. */
  21251. static SQLITE_WSD struct Mem5Global {
  21252. /*
  21253. ** Memory available for allocation
  21254. */
  21255. int szAtom; /* Smallest possible allocation in bytes */
  21256. int nBlock; /* Number of szAtom sized blocks in zPool */
  21257. u8 *zPool; /* Memory available to be allocated */
  21258. /*
  21259. ** Mutex to control access to the memory allocation subsystem.
  21260. */
  21261. sqlite3_mutex *mutex;
  21262. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  21263. /*
  21264. ** Performance statistics
  21265. */
  21266. u64 nAlloc; /* Total number of calls to malloc */
  21267. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  21268. u64 totalExcess; /* Total internal fragmentation */
  21269. u32 currentOut; /* Current checkout, including internal fragmentation */
  21270. u32 currentCount; /* Current number of distinct checkouts */
  21271. u32 maxOut; /* Maximum instantaneous currentOut */
  21272. u32 maxCount; /* Maximum instantaneous currentCount */
  21273. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  21274. #endif
  21275. /*
  21276. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  21277. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  21278. ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
  21279. */
  21280. int aiFreelist[LOGMAX+1];
  21281. /*
  21282. ** Space for tracking which blocks are checked out and the size
  21283. ** of each block. One byte per block.
  21284. */
  21285. u8 *aCtrl;
  21286. } mem5;
  21287. /*
  21288. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  21289. */
  21290. #define mem5 GLOBAL(struct Mem5Global, mem5)
  21291. /*
  21292. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  21293. ** structures, return a pointer to the idx-th such link.
  21294. */
  21295. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  21296. /*
  21297. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  21298. ** on. It should be found on mem5.aiFreelist[iLogsize].
  21299. */
  21300. static void memsys5Unlink(int i, int iLogsize){
  21301. int next, prev;
  21302. assert( i>=0 && i<mem5.nBlock );
  21303. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  21304. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  21305. next = MEM5LINK(i)->next;
  21306. prev = MEM5LINK(i)->prev;
  21307. if( prev<0 ){
  21308. mem5.aiFreelist[iLogsize] = next;
  21309. }else{
  21310. MEM5LINK(prev)->next = next;
  21311. }
  21312. if( next>=0 ){
  21313. MEM5LINK(next)->prev = prev;
  21314. }
  21315. }
  21316. /*
  21317. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  21318. ** free list.
  21319. */
  21320. static void memsys5Link(int i, int iLogsize){
  21321. int x;
  21322. assert( sqlite3_mutex_held(mem5.mutex) );
  21323. assert( i>=0 && i<mem5.nBlock );
  21324. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  21325. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  21326. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  21327. MEM5LINK(i)->prev = -1;
  21328. if( x>=0 ){
  21329. assert( x<mem5.nBlock );
  21330. MEM5LINK(x)->prev = i;
  21331. }
  21332. mem5.aiFreelist[iLogsize] = i;
  21333. }
  21334. /*
  21335. ** Obtain or release the mutex needed to access global data structures.
  21336. */
  21337. static void memsys5Enter(void){
  21338. sqlite3_mutex_enter(mem5.mutex);
  21339. }
  21340. static void memsys5Leave(void){
  21341. sqlite3_mutex_leave(mem5.mutex);
  21342. }
  21343. /*
  21344. ** Return the size of an outstanding allocation, in bytes.
  21345. ** This only works for chunks that are currently checked out.
  21346. */
  21347. static int memsys5Size(void *p){
  21348. int iSize, i;
  21349. assert( p!=0 );
  21350. i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
  21351. assert( i>=0 && i<mem5.nBlock );
  21352. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  21353. return iSize;
  21354. }
  21355. /*
  21356. ** Return a block of memory of at least nBytes in size.
  21357. ** Return NULL if unable. Return NULL if nBytes==0.
  21358. **
  21359. ** The caller guarantees that nByte is positive.
  21360. **
  21361. ** The caller has obtained a mutex prior to invoking this
  21362. ** routine so there is never any chance that two or more
  21363. ** threads can be in this routine at the same time.
  21364. */
  21365. static void *memsys5MallocUnsafe(int nByte){
  21366. int i; /* Index of a mem5.aPool[] slot */
  21367. int iBin; /* Index into mem5.aiFreelist[] */
  21368. int iFullSz; /* Size of allocation rounded up to power of 2 */
  21369. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  21370. /* nByte must be a positive */
  21371. assert( nByte>0 );
  21372. /* No more than 1GiB per allocation */
  21373. if( nByte > 0x40000000 ) return 0;
  21374. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  21375. /* Keep track of the maximum allocation request. Even unfulfilled
  21376. ** requests are counted */
  21377. if( (u32)nByte>mem5.maxRequest ){
  21378. mem5.maxRequest = nByte;
  21379. }
  21380. #endif
  21381. /* Round nByte up to the next valid power of two */
  21382. for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
  21383. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  21384. ** block. If not, then split a block of the next larger power of
  21385. ** two in order to create a new free block of size iLogsize.
  21386. */
  21387. for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
  21388. if( iBin>LOGMAX ){
  21389. testcase( sqlite3GlobalConfig.xLog!=0 );
  21390. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  21391. return 0;
  21392. }
  21393. i = mem5.aiFreelist[iBin];
  21394. memsys5Unlink(i, iBin);
  21395. while( iBin>iLogsize ){
  21396. int newSize;
  21397. iBin--;
  21398. newSize = 1 << iBin;
  21399. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  21400. memsys5Link(i+newSize, iBin);
  21401. }
  21402. mem5.aCtrl[i] = iLogsize;
  21403. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  21404. /* Update allocator performance statistics. */
  21405. mem5.nAlloc++;
  21406. mem5.totalAlloc += iFullSz;
  21407. mem5.totalExcess += iFullSz - nByte;
  21408. mem5.currentCount++;
  21409. mem5.currentOut += iFullSz;
  21410. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  21411. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  21412. #endif
  21413. #ifdef SQLITE_DEBUG
  21414. /* Make sure the allocated memory does not assume that it is set to zero
  21415. ** or retains a value from a previous allocation */
  21416. memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
  21417. #endif
  21418. /* Return a pointer to the allocated memory. */
  21419. return (void*)&mem5.zPool[i*mem5.szAtom];
  21420. }
  21421. /*
  21422. ** Free an outstanding memory allocation.
  21423. */
  21424. static void memsys5FreeUnsafe(void *pOld){
  21425. u32 size, iLogsize;
  21426. int iBlock;
  21427. /* Set iBlock to the index of the block pointed to by pOld in
  21428. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  21429. */
  21430. iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
  21431. /* Check that the pointer pOld points to a valid, non-free block. */
  21432. assert( iBlock>=0 && iBlock<mem5.nBlock );
  21433. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  21434. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  21435. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  21436. size = 1<<iLogsize;
  21437. assert( iBlock+size-1<(u32)mem5.nBlock );
  21438. mem5.aCtrl[iBlock] |= CTRL_FREE;
  21439. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  21440. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  21441. assert( mem5.currentCount>0 );
  21442. assert( mem5.currentOut>=(size*mem5.szAtom) );
  21443. mem5.currentCount--;
  21444. mem5.currentOut -= size*mem5.szAtom;
  21445. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  21446. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  21447. #endif
  21448. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  21449. while( ALWAYS(iLogsize<LOGMAX) ){
  21450. int iBuddy;
  21451. if( (iBlock>>iLogsize) & 1 ){
  21452. iBuddy = iBlock - size;
  21453. assert( iBuddy>=0 );
  21454. }else{
  21455. iBuddy = iBlock + size;
  21456. if( iBuddy>=mem5.nBlock ) break;
  21457. }
  21458. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  21459. memsys5Unlink(iBuddy, iLogsize);
  21460. iLogsize++;
  21461. if( iBuddy<iBlock ){
  21462. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  21463. mem5.aCtrl[iBlock] = 0;
  21464. iBlock = iBuddy;
  21465. }else{
  21466. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  21467. mem5.aCtrl[iBuddy] = 0;
  21468. }
  21469. size *= 2;
  21470. }
  21471. #ifdef SQLITE_DEBUG
  21472. /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
  21473. ** not used after being freed */
  21474. memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
  21475. #endif
  21476. memsys5Link(iBlock, iLogsize);
  21477. }
  21478. /*
  21479. ** Allocate nBytes of memory.
  21480. */
  21481. static void *memsys5Malloc(int nBytes){
  21482. sqlite3_int64 *p = 0;
  21483. if( nBytes>0 ){
  21484. memsys5Enter();
  21485. p = memsys5MallocUnsafe(nBytes);
  21486. memsys5Leave();
  21487. }
  21488. return (void*)p;
  21489. }
  21490. /*
  21491. ** Free memory.
  21492. **
  21493. ** The outer layer memory allocator prevents this routine from
  21494. ** being called with pPrior==0.
  21495. */
  21496. static void memsys5Free(void *pPrior){
  21497. assert( pPrior!=0 );
  21498. memsys5Enter();
  21499. memsys5FreeUnsafe(pPrior);
  21500. memsys5Leave();
  21501. }
  21502. /*
  21503. ** Change the size of an existing memory allocation.
  21504. **
  21505. ** The outer layer memory allocator prevents this routine from
  21506. ** being called with pPrior==0.
  21507. **
  21508. ** nBytes is always a value obtained from a prior call to
  21509. ** memsys5Round(). Hence nBytes is always a non-negative power
  21510. ** of two. If nBytes==0 that means that an oversize allocation
  21511. ** (an allocation larger than 0x40000000) was requested and this
  21512. ** routine should return 0 without freeing pPrior.
  21513. */
  21514. static void *memsys5Realloc(void *pPrior, int nBytes){
  21515. int nOld;
  21516. void *p;
  21517. assert( pPrior!=0 );
  21518. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  21519. assert( nBytes>=0 );
  21520. if( nBytes==0 ){
  21521. return 0;
  21522. }
  21523. nOld = memsys5Size(pPrior);
  21524. if( nBytes<=nOld ){
  21525. return pPrior;
  21526. }
  21527. p = memsys5Malloc(nBytes);
  21528. if( p ){
  21529. memcpy(p, pPrior, nOld);
  21530. memsys5Free(pPrior);
  21531. }
  21532. return p;
  21533. }
  21534. /*
  21535. ** Round up a request size to the next valid allocation size. If
  21536. ** the allocation is too large to be handled by this allocation system,
  21537. ** return 0.
  21538. **
  21539. ** All allocations must be a power of two and must be expressed by a
  21540. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  21541. ** or 1073741824 bytes.
  21542. */
  21543. static int memsys5Roundup(int n){
  21544. int iFullSz;
  21545. if( n > 0x40000000 ) return 0;
  21546. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  21547. return iFullSz;
  21548. }
  21549. /*
  21550. ** Return the ceiling of the logarithm base 2 of iValue.
  21551. **
  21552. ** Examples: memsys5Log(1) -> 0
  21553. ** memsys5Log(2) -> 1
  21554. ** memsys5Log(4) -> 2
  21555. ** memsys5Log(5) -> 3
  21556. ** memsys5Log(8) -> 3
  21557. ** memsys5Log(9) -> 4
  21558. */
  21559. static int memsys5Log(int iValue){
  21560. int iLog;
  21561. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  21562. return iLog;
  21563. }
  21564. /*
  21565. ** Initialize the memory allocator.
  21566. **
  21567. ** This routine is not threadsafe. The caller must be holding a mutex
  21568. ** to prevent multiple threads from entering at the same time.
  21569. */
  21570. static int memsys5Init(void *NotUsed){
  21571. int ii; /* Loop counter */
  21572. int nByte; /* Number of bytes of memory available to this allocator */
  21573. u8 *zByte; /* Memory usable by this allocator */
  21574. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  21575. int iOffset; /* An offset into mem5.aCtrl[] */
  21576. UNUSED_PARAMETER(NotUsed);
  21577. /* For the purposes of this routine, disable the mutex */
  21578. mem5.mutex = 0;
  21579. /* The size of a Mem5Link object must be a power of two. Verify that
  21580. ** this is case.
  21581. */
  21582. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  21583. nByte = sqlite3GlobalConfig.nHeap;
  21584. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  21585. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  21586. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  21587. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  21588. mem5.szAtom = (1<<nMinLog);
  21589. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  21590. mem5.szAtom = mem5.szAtom << 1;
  21591. }
  21592. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  21593. mem5.zPool = zByte;
  21594. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  21595. for(ii=0; ii<=LOGMAX; ii++){
  21596. mem5.aiFreelist[ii] = -1;
  21597. }
  21598. iOffset = 0;
  21599. for(ii=LOGMAX; ii>=0; ii--){
  21600. int nAlloc = (1<<ii);
  21601. if( (iOffset+nAlloc)<=mem5.nBlock ){
  21602. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  21603. memsys5Link(iOffset, ii);
  21604. iOffset += nAlloc;
  21605. }
  21606. assert((iOffset+nAlloc)>mem5.nBlock);
  21607. }
  21608. /* If a mutex is required for normal operation, allocate one */
  21609. if( sqlite3GlobalConfig.bMemstat==0 ){
  21610. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  21611. }
  21612. return SQLITE_OK;
  21613. }
  21614. /*
  21615. ** Deinitialize this module.
  21616. */
  21617. static void memsys5Shutdown(void *NotUsed){
  21618. UNUSED_PARAMETER(NotUsed);
  21619. mem5.mutex = 0;
  21620. return;
  21621. }
  21622. #ifdef SQLITE_TEST
  21623. /*
  21624. ** Open the file indicated and write a log of all unfreed memory
  21625. ** allocations into that log.
  21626. */
  21627. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  21628. FILE *out;
  21629. int i, j, n;
  21630. int nMinLog;
  21631. if( zFilename==0 || zFilename[0]==0 ){
  21632. out = stdout;
  21633. }else{
  21634. out = fopen(zFilename, "w");
  21635. if( out==0 ){
  21636. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  21637. zFilename);
  21638. return;
  21639. }
  21640. }
  21641. memsys5Enter();
  21642. nMinLog = memsys5Log(mem5.szAtom);
  21643. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  21644. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  21645. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  21646. }
  21647. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  21648. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  21649. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  21650. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  21651. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  21652. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  21653. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  21654. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  21655. memsys5Leave();
  21656. if( out==stdout ){
  21657. fflush(stdout);
  21658. }else{
  21659. fclose(out);
  21660. }
  21661. }
  21662. #endif
  21663. /*
  21664. ** This routine is the only routine in this file with external
  21665. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  21666. ** struct populated with the memsys5 methods.
  21667. */
  21668. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  21669. static const sqlite3_mem_methods memsys5Methods = {
  21670. memsys5Malloc,
  21671. memsys5Free,
  21672. memsys5Realloc,
  21673. memsys5Size,
  21674. memsys5Roundup,
  21675. memsys5Init,
  21676. memsys5Shutdown,
  21677. 0
  21678. };
  21679. return &memsys5Methods;
  21680. }
  21681. #endif /* SQLITE_ENABLE_MEMSYS5 */
  21682. /************** End of mem5.c ************************************************/
  21683. /************** Begin file mutex.c *******************************************/
  21684. /*
  21685. ** 2007 August 14
  21686. **
  21687. ** The author disclaims copyright to this source code. In place of
  21688. ** a legal notice, here is a blessing:
  21689. **
  21690. ** May you do good and not evil.
  21691. ** May you find forgiveness for yourself and forgive others.
  21692. ** May you share freely, never taking more than you give.
  21693. **
  21694. *************************************************************************
  21695. ** This file contains the C functions that implement mutexes.
  21696. **
  21697. ** This file contains code that is common across all mutex implementations.
  21698. */
  21699. /* #include "sqliteInt.h" */
  21700. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  21701. /*
  21702. ** For debugging purposes, record when the mutex subsystem is initialized
  21703. ** and uninitialized so that we can assert() if there is an attempt to
  21704. ** allocate a mutex while the system is uninitialized.
  21705. */
  21706. static SQLITE_WSD int mutexIsInit = 0;
  21707. #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
  21708. #ifndef SQLITE_MUTEX_OMIT
  21709. /*
  21710. ** Initialize the mutex system.
  21711. */
  21712. SQLITE_PRIVATE int sqlite3MutexInit(void){
  21713. int rc = SQLITE_OK;
  21714. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  21715. /* If the xMutexAlloc method has not been set, then the user did not
  21716. ** install a mutex implementation via sqlite3_config() prior to
  21717. ** sqlite3_initialize() being called. This block copies pointers to
  21718. ** the default implementation into the sqlite3GlobalConfig structure.
  21719. */
  21720. sqlite3_mutex_methods const *pFrom;
  21721. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  21722. if( sqlite3GlobalConfig.bCoreMutex ){
  21723. pFrom = sqlite3DefaultMutex();
  21724. }else{
  21725. pFrom = sqlite3NoopMutex();
  21726. }
  21727. pTo->xMutexInit = pFrom->xMutexInit;
  21728. pTo->xMutexEnd = pFrom->xMutexEnd;
  21729. pTo->xMutexFree = pFrom->xMutexFree;
  21730. pTo->xMutexEnter = pFrom->xMutexEnter;
  21731. pTo->xMutexTry = pFrom->xMutexTry;
  21732. pTo->xMutexLeave = pFrom->xMutexLeave;
  21733. pTo->xMutexHeld = pFrom->xMutexHeld;
  21734. pTo->xMutexNotheld = pFrom->xMutexNotheld;
  21735. sqlite3MemoryBarrier();
  21736. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  21737. }
  21738. assert( sqlite3GlobalConfig.mutex.xMutexInit );
  21739. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  21740. #ifdef SQLITE_DEBUG
  21741. GLOBAL(int, mutexIsInit) = 1;
  21742. #endif
  21743. return rc;
  21744. }
  21745. /*
  21746. ** Shutdown the mutex system. This call frees resources allocated by
  21747. ** sqlite3MutexInit().
  21748. */
  21749. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  21750. int rc = SQLITE_OK;
  21751. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  21752. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  21753. }
  21754. #ifdef SQLITE_DEBUG
  21755. GLOBAL(int, mutexIsInit) = 0;
  21756. #endif
  21757. return rc;
  21758. }
  21759. /*
  21760. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  21761. */
  21762. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  21763. #ifndef SQLITE_OMIT_AUTOINIT
  21764. if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
  21765. if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
  21766. #endif
  21767. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  21768. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  21769. }
  21770. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  21771. if( !sqlite3GlobalConfig.bCoreMutex ){
  21772. return 0;
  21773. }
  21774. assert( GLOBAL(int, mutexIsInit) );
  21775. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  21776. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  21777. }
  21778. /*
  21779. ** Free a dynamic mutex.
  21780. */
  21781. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  21782. if( p ){
  21783. assert( sqlite3GlobalConfig.mutex.xMutexFree );
  21784. sqlite3GlobalConfig.mutex.xMutexFree(p);
  21785. }
  21786. }
  21787. /*
  21788. ** Obtain the mutex p. If some other thread already has the mutex, block
  21789. ** until it can be obtained.
  21790. */
  21791. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  21792. if( p ){
  21793. assert( sqlite3GlobalConfig.mutex.xMutexEnter );
  21794. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  21795. }
  21796. }
  21797. /*
  21798. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  21799. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  21800. */
  21801. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  21802. int rc = SQLITE_OK;
  21803. if( p ){
  21804. assert( sqlite3GlobalConfig.mutex.xMutexTry );
  21805. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  21806. }
  21807. return rc;
  21808. }
  21809. /*
  21810. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  21811. ** entered by the same thread. The behavior is undefined if the mutex
  21812. ** is not currently entered. If a NULL pointer is passed as an argument
  21813. ** this function is a no-op.
  21814. */
  21815. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  21816. if( p ){
  21817. assert( sqlite3GlobalConfig.mutex.xMutexLeave );
  21818. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  21819. }
  21820. }
  21821. #ifndef NDEBUG
  21822. /*
  21823. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  21824. ** intended for use inside assert() statements.
  21825. */
  21826. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  21827. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
  21828. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  21829. }
  21830. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  21831. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
  21832. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  21833. }
  21834. #endif
  21835. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  21836. /************** End of mutex.c ***********************************************/
  21837. /************** Begin file mutex_noop.c **************************************/
  21838. /*
  21839. ** 2008 October 07
  21840. **
  21841. ** The author disclaims copyright to this source code. In place of
  21842. ** a legal notice, here is a blessing:
  21843. **
  21844. ** May you do good and not evil.
  21845. ** May you find forgiveness for yourself and forgive others.
  21846. ** May you share freely, never taking more than you give.
  21847. **
  21848. *************************************************************************
  21849. ** This file contains the C functions that implement mutexes.
  21850. **
  21851. ** This implementation in this file does not provide any mutual
  21852. ** exclusion and is thus suitable for use only in applications
  21853. ** that use SQLite in a single thread. The routines defined
  21854. ** here are place-holders. Applications can substitute working
  21855. ** mutex routines at start-time using the
  21856. **
  21857. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  21858. **
  21859. ** interface.
  21860. **
  21861. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  21862. ** that does error checking on mutexes to make sure they are being
  21863. ** called correctly.
  21864. */
  21865. /* #include "sqliteInt.h" */
  21866. #ifndef SQLITE_MUTEX_OMIT
  21867. #ifndef SQLITE_DEBUG
  21868. /*
  21869. ** Stub routines for all mutex methods.
  21870. **
  21871. ** This routines provide no mutual exclusion or error checking.
  21872. */
  21873. static int noopMutexInit(void){ return SQLITE_OK; }
  21874. static int noopMutexEnd(void){ return SQLITE_OK; }
  21875. static sqlite3_mutex *noopMutexAlloc(int id){
  21876. UNUSED_PARAMETER(id);
  21877. return (sqlite3_mutex*)8;
  21878. }
  21879. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  21880. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  21881. static int noopMutexTry(sqlite3_mutex *p){
  21882. UNUSED_PARAMETER(p);
  21883. return SQLITE_OK;
  21884. }
  21885. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  21886. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  21887. static const sqlite3_mutex_methods sMutex = {
  21888. noopMutexInit,
  21889. noopMutexEnd,
  21890. noopMutexAlloc,
  21891. noopMutexFree,
  21892. noopMutexEnter,
  21893. noopMutexTry,
  21894. noopMutexLeave,
  21895. 0,
  21896. 0,
  21897. };
  21898. return &sMutex;
  21899. }
  21900. #endif /* !SQLITE_DEBUG */
  21901. #ifdef SQLITE_DEBUG
  21902. /*
  21903. ** In this implementation, error checking is provided for testing
  21904. ** and debugging purposes. The mutexes still do not provide any
  21905. ** mutual exclusion.
  21906. */
  21907. /*
  21908. ** The mutex object
  21909. */
  21910. typedef struct sqlite3_debug_mutex {
  21911. int id; /* The mutex type */
  21912. int cnt; /* Number of entries without a matching leave */
  21913. } sqlite3_debug_mutex;
  21914. /*
  21915. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  21916. ** intended for use inside assert() statements.
  21917. */
  21918. static int debugMutexHeld(sqlite3_mutex *pX){
  21919. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  21920. return p==0 || p->cnt>0;
  21921. }
  21922. static int debugMutexNotheld(sqlite3_mutex *pX){
  21923. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  21924. return p==0 || p->cnt==0;
  21925. }
  21926. /*
  21927. ** Initialize and deinitialize the mutex subsystem.
  21928. */
  21929. static int debugMutexInit(void){ return SQLITE_OK; }
  21930. static int debugMutexEnd(void){ return SQLITE_OK; }
  21931. /*
  21932. ** The sqlite3_mutex_alloc() routine allocates a new
  21933. ** mutex and returns a pointer to it. If it returns NULL
  21934. ** that means that a mutex could not be allocated.
  21935. */
  21936. static sqlite3_mutex *debugMutexAlloc(int id){
  21937. static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
  21938. sqlite3_debug_mutex *pNew = 0;
  21939. switch( id ){
  21940. case SQLITE_MUTEX_FAST:
  21941. case SQLITE_MUTEX_RECURSIVE: {
  21942. pNew = sqlite3Malloc(sizeof(*pNew));
  21943. if( pNew ){
  21944. pNew->id = id;
  21945. pNew->cnt = 0;
  21946. }
  21947. break;
  21948. }
  21949. default: {
  21950. #ifdef SQLITE_ENABLE_API_ARMOR
  21951. if( id-2<0 || id-2>=ArraySize(aStatic) ){
  21952. (void)SQLITE_MISUSE_BKPT;
  21953. return 0;
  21954. }
  21955. #endif
  21956. pNew = &aStatic[id-2];
  21957. pNew->id = id;
  21958. break;
  21959. }
  21960. }
  21961. return (sqlite3_mutex*)pNew;
  21962. }
  21963. /*
  21964. ** This routine deallocates a previously allocated mutex.
  21965. */
  21966. static void debugMutexFree(sqlite3_mutex *pX){
  21967. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  21968. assert( p->cnt==0 );
  21969. if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
  21970. sqlite3_free(p);
  21971. }else{
  21972. #ifdef SQLITE_ENABLE_API_ARMOR
  21973. (void)SQLITE_MISUSE_BKPT;
  21974. #endif
  21975. }
  21976. }
  21977. /*
  21978. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  21979. ** to enter a mutex. If another thread is already within the mutex,
  21980. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  21981. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  21982. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  21983. ** be entered multiple times by the same thread. In such cases the,
  21984. ** mutex must be exited an equal number of times before another thread
  21985. ** can enter. If the same thread tries to enter any other kind of mutex
  21986. ** more than once, the behavior is undefined.
  21987. */
  21988. static void debugMutexEnter(sqlite3_mutex *pX){
  21989. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  21990. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  21991. p->cnt++;
  21992. }
  21993. static int debugMutexTry(sqlite3_mutex *pX){
  21994. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  21995. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  21996. p->cnt++;
  21997. return SQLITE_OK;
  21998. }
  21999. /*
  22000. ** The sqlite3_mutex_leave() routine exits a mutex that was
  22001. ** previously entered by the same thread. The behavior
  22002. ** is undefined if the mutex is not currently entered or
  22003. ** is not currently allocated. SQLite will never do either.
  22004. */
  22005. static void debugMutexLeave(sqlite3_mutex *pX){
  22006. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  22007. assert( debugMutexHeld(pX) );
  22008. p->cnt--;
  22009. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  22010. }
  22011. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  22012. static const sqlite3_mutex_methods sMutex = {
  22013. debugMutexInit,
  22014. debugMutexEnd,
  22015. debugMutexAlloc,
  22016. debugMutexFree,
  22017. debugMutexEnter,
  22018. debugMutexTry,
  22019. debugMutexLeave,
  22020. debugMutexHeld,
  22021. debugMutexNotheld
  22022. };
  22023. return &sMutex;
  22024. }
  22025. #endif /* SQLITE_DEBUG */
  22026. /*
  22027. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  22028. ** is used regardless of the run-time threadsafety setting.
  22029. */
  22030. #ifdef SQLITE_MUTEX_NOOP
  22031. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  22032. return sqlite3NoopMutex();
  22033. }
  22034. #endif /* defined(SQLITE_MUTEX_NOOP) */
  22035. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  22036. /************** End of mutex_noop.c ******************************************/
  22037. #include "rtthread_mutex.c"
  22038. /************** Begin file mutex_unix.c **************************************/
  22039. /*
  22040. ** 2007 August 28
  22041. **
  22042. ** The author disclaims copyright to this source code. In place of
  22043. ** a legal notice, here is a blessing:
  22044. **
  22045. ** May you do good and not evil.
  22046. ** May you find forgiveness for yourself and forgive others.
  22047. ** May you share freely, never taking more than you give.
  22048. **
  22049. *************************************************************************
  22050. ** This file contains the C functions that implement mutexes for pthreads
  22051. */
  22052. /* #include "sqliteInt.h" */
  22053. /*
  22054. ** The code in this file is only used if we are compiling threadsafe
  22055. ** under unix with pthreads.
  22056. **
  22057. ** Note that this implementation requires a version of pthreads that
  22058. ** supports recursive mutexes.
  22059. */
  22060. #ifdef SQLITE_MUTEX_PTHREADS
  22061. #include <pthread.h>
  22062. /*
  22063. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  22064. ** are necessary under two condidtions: (1) Debug builds and (2) using
  22065. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  22066. */
  22067. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  22068. # define SQLITE_MUTEX_NREF 1
  22069. #else
  22070. # define SQLITE_MUTEX_NREF 0
  22071. #endif
  22072. /*
  22073. ** Each recursive mutex is an instance of the following structure.
  22074. */
  22075. struct sqlite3_mutex {
  22076. pthread_mutex_t mutex; /* Mutex controlling the lock */
  22077. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  22078. int id; /* Mutex type */
  22079. #endif
  22080. #if SQLITE_MUTEX_NREF
  22081. volatile int nRef; /* Number of entrances */
  22082. volatile pthread_t owner; /* Thread that is within this mutex */
  22083. int trace; /* True to trace changes */
  22084. #endif
  22085. };
  22086. #if SQLITE_MUTEX_NREF
  22087. #define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0}
  22088. #elif defined(SQLITE_ENABLE_API_ARMOR)
  22089. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 }
  22090. #else
  22091. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
  22092. #endif
  22093. /*
  22094. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  22095. ** intended for use only inside assert() statements. On some platforms,
  22096. ** there might be race conditions that can cause these routines to
  22097. ** deliver incorrect results. In particular, if pthread_equal() is
  22098. ** not an atomic operation, then these routines might delivery
  22099. ** incorrect results. On most platforms, pthread_equal() is a
  22100. ** comparison of two integers and is therefore atomic. But we are
  22101. ** told that HPUX is not such a platform. If so, then these routines
  22102. ** will not always work correctly on HPUX.
  22103. **
  22104. ** On those platforms where pthread_equal() is not atomic, SQLite
  22105. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  22106. ** make sure no assert() statements are evaluated and hence these
  22107. ** routines are never called.
  22108. */
  22109. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  22110. static int pthreadMutexHeld(sqlite3_mutex *p){
  22111. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  22112. }
  22113. static int pthreadMutexNotheld(sqlite3_mutex *p){
  22114. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  22115. }
  22116. #endif
  22117. /*
  22118. ** Try to provide a memory barrier operation, needed for initialization
  22119. ** and also for the implementation of xShmBarrier in the VFS in cases
  22120. ** where SQLite is compiled without mutexes.
  22121. */
  22122. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  22123. #if defined(SQLITE_MEMORY_BARRIER)
  22124. SQLITE_MEMORY_BARRIER;
  22125. #elif defined(__GNUC__) && GCC_VERSION>=4001000
  22126. __sync_synchronize();
  22127. #endif
  22128. }
  22129. /*
  22130. ** Initialize and deinitialize the mutex subsystem.
  22131. */
  22132. static int pthreadMutexInit(void){ return SQLITE_OK; }
  22133. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  22134. /*
  22135. ** The sqlite3_mutex_alloc() routine allocates a new
  22136. ** mutex and returns a pointer to it. If it returns NULL
  22137. ** that means that a mutex could not be allocated. SQLite
  22138. ** will unwind its stack and return an error. The argument
  22139. ** to sqlite3_mutex_alloc() is one of these integer constants:
  22140. **
  22141. ** <ul>
  22142. ** <li> SQLITE_MUTEX_FAST
  22143. ** <li> SQLITE_MUTEX_RECURSIVE
  22144. ** <li> SQLITE_MUTEX_STATIC_MASTER
  22145. ** <li> SQLITE_MUTEX_STATIC_MEM
  22146. ** <li> SQLITE_MUTEX_STATIC_OPEN
  22147. ** <li> SQLITE_MUTEX_STATIC_PRNG
  22148. ** <li> SQLITE_MUTEX_STATIC_LRU
  22149. ** <li> SQLITE_MUTEX_STATIC_PMEM
  22150. ** <li> SQLITE_MUTEX_STATIC_APP1
  22151. ** <li> SQLITE_MUTEX_STATIC_APP2
  22152. ** <li> SQLITE_MUTEX_STATIC_APP3
  22153. ** <li> SQLITE_MUTEX_STATIC_VFS1
  22154. ** <li> SQLITE_MUTEX_STATIC_VFS2
  22155. ** <li> SQLITE_MUTEX_STATIC_VFS3
  22156. ** </ul>
  22157. **
  22158. ** The first two constants cause sqlite3_mutex_alloc() to create
  22159. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  22160. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  22161. ** The mutex implementation does not need to make a distinction
  22162. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  22163. ** not want to. But SQLite will only request a recursive mutex in
  22164. ** cases where it really needs one. If a faster non-recursive mutex
  22165. ** implementation is available on the host platform, the mutex subsystem
  22166. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  22167. **
  22168. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  22169. ** a pointer to a static preexisting mutex. Six static mutexes are
  22170. ** used by the current version of SQLite. Future versions of SQLite
  22171. ** may add additional static mutexes. Static mutexes are for internal
  22172. ** use by SQLite only. Applications that use SQLite mutexes should
  22173. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  22174. ** SQLITE_MUTEX_RECURSIVE.
  22175. **
  22176. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  22177. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  22178. ** returns a different mutex on every call. But for the static
  22179. ** mutex types, the same mutex is returned on every call that has
  22180. ** the same type number.
  22181. */
  22182. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  22183. static sqlite3_mutex staticMutexes[] = {
  22184. SQLITE3_MUTEX_INITIALIZER,
  22185. SQLITE3_MUTEX_INITIALIZER,
  22186. SQLITE3_MUTEX_INITIALIZER,
  22187. SQLITE3_MUTEX_INITIALIZER,
  22188. SQLITE3_MUTEX_INITIALIZER,
  22189. SQLITE3_MUTEX_INITIALIZER,
  22190. SQLITE3_MUTEX_INITIALIZER,
  22191. SQLITE3_MUTEX_INITIALIZER,
  22192. SQLITE3_MUTEX_INITIALIZER,
  22193. SQLITE3_MUTEX_INITIALIZER,
  22194. SQLITE3_MUTEX_INITIALIZER,
  22195. SQLITE3_MUTEX_INITIALIZER
  22196. };
  22197. sqlite3_mutex *p;
  22198. switch( iType ){
  22199. case SQLITE_MUTEX_RECURSIVE: {
  22200. p = sqlite3MallocZero( sizeof(*p) );
  22201. if( p ){
  22202. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  22203. /* If recursive mutexes are not available, we will have to
  22204. ** build our own. See below. */
  22205. pthread_mutex_init(&p->mutex, 0);
  22206. #else
  22207. /* Use a recursive mutex if it is available */
  22208. pthread_mutexattr_t recursiveAttr;
  22209. pthread_mutexattr_init(&recursiveAttr);
  22210. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  22211. pthread_mutex_init(&p->mutex, &recursiveAttr);
  22212. pthread_mutexattr_destroy(&recursiveAttr);
  22213. #endif
  22214. }
  22215. break;
  22216. }
  22217. case SQLITE_MUTEX_FAST: {
  22218. p = sqlite3MallocZero( sizeof(*p) );
  22219. if( p ){
  22220. pthread_mutex_init(&p->mutex, 0);
  22221. }
  22222. break;
  22223. }
  22224. default: {
  22225. #ifdef SQLITE_ENABLE_API_ARMOR
  22226. if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
  22227. (void)SQLITE_MISUSE_BKPT;
  22228. return 0;
  22229. }
  22230. #endif
  22231. p = &staticMutexes[iType-2];
  22232. break;
  22233. }
  22234. }
  22235. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  22236. if( p ) p->id = iType;
  22237. #endif
  22238. return p;
  22239. }
  22240. /*
  22241. ** This routine deallocates a previously
  22242. ** allocated mutex. SQLite is careful to deallocate every
  22243. ** mutex that it allocates.
  22244. */
  22245. static void pthreadMutexFree(sqlite3_mutex *p){
  22246. assert( p->nRef==0 );
  22247. #if SQLITE_ENABLE_API_ARMOR
  22248. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
  22249. #endif
  22250. {
  22251. pthread_mutex_destroy(&p->mutex);
  22252. sqlite3_free(p);
  22253. }
  22254. #ifdef SQLITE_ENABLE_API_ARMOR
  22255. else{
  22256. (void)SQLITE_MISUSE_BKPT;
  22257. }
  22258. #endif
  22259. }
  22260. /*
  22261. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  22262. ** to enter a mutex. If another thread is already within the mutex,
  22263. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  22264. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  22265. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  22266. ** be entered multiple times by the same thread. In such cases the,
  22267. ** mutex must be exited an equal number of times before another thread
  22268. ** can enter. If the same thread tries to enter any other kind of mutex
  22269. ** more than once, the behavior is undefined.
  22270. */
  22271. static void pthreadMutexEnter(sqlite3_mutex *p){
  22272. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  22273. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  22274. /* If recursive mutexes are not available, then we have to grow
  22275. ** our own. This implementation assumes that pthread_equal()
  22276. ** is atomic - that it cannot be deceived into thinking self
  22277. ** and p->owner are equal if p->owner changes between two values
  22278. ** that are not equal to self while the comparison is taking place.
  22279. ** This implementation also assumes a coherent cache - that
  22280. ** separate processes cannot read different values from the same
  22281. ** address at the same time. If either of these two conditions
  22282. ** are not met, then the mutexes will fail and problems will result.
  22283. */
  22284. {
  22285. pthread_t self = pthread_self();
  22286. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  22287. p->nRef++;
  22288. }else{
  22289. pthread_mutex_lock(&p->mutex);
  22290. assert( p->nRef==0 );
  22291. p->owner = self;
  22292. p->nRef = 1;
  22293. }
  22294. }
  22295. #else
  22296. /* Use the built-in recursive mutexes if they are available.
  22297. */
  22298. pthread_mutex_lock(&p->mutex);
  22299. #if SQLITE_MUTEX_NREF
  22300. assert( p->nRef>0 || p->owner==0 );
  22301. p->owner = pthread_self();
  22302. p->nRef++;
  22303. #endif
  22304. #endif
  22305. #ifdef SQLITE_DEBUG
  22306. if( p->trace ){
  22307. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  22308. }
  22309. #endif
  22310. }
  22311. static int pthreadMutexTry(sqlite3_mutex *p){
  22312. int rc;
  22313. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  22314. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  22315. /* If recursive mutexes are not available, then we have to grow
  22316. ** our own. This implementation assumes that pthread_equal()
  22317. ** is atomic - that it cannot be deceived into thinking self
  22318. ** and p->owner are equal if p->owner changes between two values
  22319. ** that are not equal to self while the comparison is taking place.
  22320. ** This implementation also assumes a coherent cache - that
  22321. ** separate processes cannot read different values from the same
  22322. ** address at the same time. If either of these two conditions
  22323. ** are not met, then the mutexes will fail and problems will result.
  22324. */
  22325. {
  22326. pthread_t self = pthread_self();
  22327. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  22328. p->nRef++;
  22329. rc = SQLITE_OK;
  22330. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  22331. assert( p->nRef==0 );
  22332. p->owner = self;
  22333. p->nRef = 1;
  22334. rc = SQLITE_OK;
  22335. }else{
  22336. rc = SQLITE_BUSY;
  22337. }
  22338. }
  22339. #else
  22340. /* Use the built-in recursive mutexes if they are available.
  22341. */
  22342. if( pthread_mutex_trylock(&p->mutex)==0 ){
  22343. #if SQLITE_MUTEX_NREF
  22344. p->owner = pthread_self();
  22345. p->nRef++;
  22346. #endif
  22347. rc = SQLITE_OK;
  22348. }else{
  22349. rc = SQLITE_BUSY;
  22350. }
  22351. #endif
  22352. #ifdef SQLITE_DEBUG
  22353. if( rc==SQLITE_OK && p->trace ){
  22354. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  22355. }
  22356. #endif
  22357. return rc;
  22358. }
  22359. /*
  22360. ** The sqlite3_mutex_leave() routine exits a mutex that was
  22361. ** previously entered by the same thread. The behavior
  22362. ** is undefined if the mutex is not currently entered or
  22363. ** is not currently allocated. SQLite will never do either.
  22364. */
  22365. static void pthreadMutexLeave(sqlite3_mutex *p){
  22366. assert( pthreadMutexHeld(p) );
  22367. #if SQLITE_MUTEX_NREF
  22368. p->nRef--;
  22369. if( p->nRef==0 ) p->owner = 0;
  22370. #endif
  22371. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  22372. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  22373. if( p->nRef==0 ){
  22374. pthread_mutex_unlock(&p->mutex);
  22375. }
  22376. #else
  22377. pthread_mutex_unlock(&p->mutex);
  22378. #endif
  22379. #ifdef SQLITE_DEBUG
  22380. if( p->trace ){
  22381. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  22382. }
  22383. #endif
  22384. }
  22385. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  22386. static const sqlite3_mutex_methods sMutex = {
  22387. pthreadMutexInit,
  22388. pthreadMutexEnd,
  22389. pthreadMutexAlloc,
  22390. pthreadMutexFree,
  22391. pthreadMutexEnter,
  22392. pthreadMutexTry,
  22393. pthreadMutexLeave,
  22394. #ifdef SQLITE_DEBUG
  22395. pthreadMutexHeld,
  22396. pthreadMutexNotheld
  22397. #else
  22398. 0,
  22399. 0
  22400. #endif
  22401. };
  22402. return &sMutex;
  22403. }
  22404. #endif /* SQLITE_MUTEX_PTHREADS */
  22405. /************** End of mutex_unix.c ******************************************/
  22406. /************** Begin file mutex_w32.c ***************************************/
  22407. /*
  22408. ** 2007 August 14
  22409. **
  22410. ** The author disclaims copyright to this source code. In place of
  22411. ** a legal notice, here is a blessing:
  22412. **
  22413. ** May you do good and not evil.
  22414. ** May you find forgiveness for yourself and forgive others.
  22415. ** May you share freely, never taking more than you give.
  22416. **
  22417. *************************************************************************
  22418. ** This file contains the C functions that implement mutexes for Win32.
  22419. */
  22420. /* #include "sqliteInt.h" */
  22421. #if SQLITE_OS_WIN
  22422. /*
  22423. ** Include code that is common to all os_*.c files
  22424. */
  22425. /************** Include os_common.h in the middle of mutex_w32.c *************/
  22426. /************** Begin file os_common.h ***************************************/
  22427. /*
  22428. ** 2004 May 22
  22429. **
  22430. ** The author disclaims copyright to this source code. In place of
  22431. ** a legal notice, here is a blessing:
  22432. **
  22433. ** May you do good and not evil.
  22434. ** May you find forgiveness for yourself and forgive others.
  22435. ** May you share freely, never taking more than you give.
  22436. **
  22437. ******************************************************************************
  22438. **
  22439. ** This file contains macros and a little bit of code that is common to
  22440. ** all of the platform-specific files (os_*.c) and is #included into those
  22441. ** files.
  22442. **
  22443. ** This file should be #included by the os_*.c files only. It is not a
  22444. ** general purpose header file.
  22445. */
  22446. #ifndef _OS_COMMON_H_
  22447. #define _OS_COMMON_H_
  22448. /*
  22449. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  22450. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  22451. ** switch. The following code should catch this problem at compile-time.
  22452. */
  22453. #ifdef MEMORY_DEBUG
  22454. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  22455. #endif
  22456. /*
  22457. ** Macros for performance tracing. Normally turned off. Only works
  22458. ** on i486 hardware.
  22459. */
  22460. #ifdef SQLITE_PERFORMANCE_TRACE
  22461. /*
  22462. ** hwtime.h contains inline assembler code for implementing
  22463. ** high-performance timing routines.
  22464. */
  22465. /************** Include hwtime.h in the middle of os_common.h ****************/
  22466. /************** Begin file hwtime.h ******************************************/
  22467. /*
  22468. ** 2008 May 27
  22469. **
  22470. ** The author disclaims copyright to this source code. In place of
  22471. ** a legal notice, here is a blessing:
  22472. **
  22473. ** May you do good and not evil.
  22474. ** May you find forgiveness for yourself and forgive others.
  22475. ** May you share freely, never taking more than you give.
  22476. **
  22477. ******************************************************************************
  22478. **
  22479. ** This file contains inline asm code for retrieving "high-performance"
  22480. ** counters for x86 class CPUs.
  22481. */
  22482. #ifndef SQLITE_HWTIME_H
  22483. #define SQLITE_HWTIME_H
  22484. /*
  22485. ** The following routine only works on pentium-class (or newer) processors.
  22486. ** It uses the RDTSC opcode to read the cycle count value out of the
  22487. ** processor and returns that value. This can be used for high-res
  22488. ** profiling.
  22489. */
  22490. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  22491. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  22492. #if defined(__GNUC__)
  22493. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22494. unsigned int lo, hi;
  22495. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  22496. return (sqlite_uint64)hi << 32 | lo;
  22497. }
  22498. #elif defined(_MSC_VER)
  22499. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  22500. __asm {
  22501. rdtsc
  22502. ret ; return value at EDX:EAX
  22503. }
  22504. }
  22505. #endif
  22506. #elif (defined(__GNUC__) && defined(__x86_64__))
  22507. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22508. unsigned long val;
  22509. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  22510. return val;
  22511. }
  22512. #elif (defined(__GNUC__) && defined(__ppc__))
  22513. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22514. unsigned long long retval;
  22515. unsigned long junk;
  22516. __asm__ __volatile__ ("\n\
  22517. 1: mftbu %1\n\
  22518. mftb %L0\n\
  22519. mftbu %0\n\
  22520. cmpw %0,%1\n\
  22521. bne 1b"
  22522. : "=r" (retval), "=r" (junk));
  22523. return retval;
  22524. }
  22525. #else
  22526. #error Need implementation of sqlite3Hwtime() for your platform.
  22527. /*
  22528. ** To compile without implementing sqlite3Hwtime() for your platform,
  22529. ** you can remove the above #error and use the following
  22530. ** stub function. You will lose timing support for many
  22531. ** of the debugging and testing utilities, but it should at
  22532. ** least compile and run.
  22533. */
  22534. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  22535. #endif
  22536. #endif /* !defined(SQLITE_HWTIME_H) */
  22537. /************** End of hwtime.h **********************************************/
  22538. /************** Continuing where we left off in os_common.h ******************/
  22539. static sqlite_uint64 g_start;
  22540. static sqlite_uint64 g_elapsed;
  22541. #define TIMER_START g_start=sqlite3Hwtime()
  22542. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  22543. #define TIMER_ELAPSED g_elapsed
  22544. #else
  22545. #define TIMER_START
  22546. #define TIMER_END
  22547. #define TIMER_ELAPSED ((sqlite_uint64)0)
  22548. #endif
  22549. /*
  22550. ** If we compile with the SQLITE_TEST macro set, then the following block
  22551. ** of code will give us the ability to simulate a disk I/O error. This
  22552. ** is used for testing the I/O recovery logic.
  22553. */
  22554. #if defined(SQLITE_TEST)
  22555. SQLITE_API extern int sqlite3_io_error_hit;
  22556. SQLITE_API extern int sqlite3_io_error_hardhit;
  22557. SQLITE_API extern int sqlite3_io_error_pending;
  22558. SQLITE_API extern int sqlite3_io_error_persist;
  22559. SQLITE_API extern int sqlite3_io_error_benign;
  22560. SQLITE_API extern int sqlite3_diskfull_pending;
  22561. SQLITE_API extern int sqlite3_diskfull;
  22562. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  22563. #define SimulateIOError(CODE) \
  22564. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  22565. || sqlite3_io_error_pending-- == 1 ) \
  22566. { local_ioerr(); CODE; }
  22567. static void local_ioerr(){
  22568. IOTRACE(("IOERR\n"));
  22569. sqlite3_io_error_hit++;
  22570. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  22571. }
  22572. #define SimulateDiskfullError(CODE) \
  22573. if( sqlite3_diskfull_pending ){ \
  22574. if( sqlite3_diskfull_pending == 1 ){ \
  22575. local_ioerr(); \
  22576. sqlite3_diskfull = 1; \
  22577. sqlite3_io_error_hit = 1; \
  22578. CODE; \
  22579. }else{ \
  22580. sqlite3_diskfull_pending--; \
  22581. } \
  22582. }
  22583. #else
  22584. #define SimulateIOErrorBenign(X)
  22585. #define SimulateIOError(A)
  22586. #define SimulateDiskfullError(A)
  22587. #endif /* defined(SQLITE_TEST) */
  22588. /*
  22589. ** When testing, keep a count of the number of open files.
  22590. */
  22591. #if defined(SQLITE_TEST)
  22592. SQLITE_API extern int sqlite3_open_file_count;
  22593. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  22594. #else
  22595. #define OpenCounter(X)
  22596. #endif /* defined(SQLITE_TEST) */
  22597. #endif /* !defined(_OS_COMMON_H_) */
  22598. /************** End of os_common.h *******************************************/
  22599. /************** Continuing where we left off in mutex_w32.c ******************/
  22600. /*
  22601. ** Include the header file for the Windows VFS.
  22602. */
  22603. /************** Include os_win.h in the middle of mutex_w32.c ****************/
  22604. /************** Begin file os_win.h ******************************************/
  22605. /*
  22606. ** 2013 November 25
  22607. **
  22608. ** The author disclaims copyright to this source code. In place of
  22609. ** a legal notice, here is a blessing:
  22610. **
  22611. ** May you do good and not evil.
  22612. ** May you find forgiveness for yourself and forgive others.
  22613. ** May you share freely, never taking more than you give.
  22614. **
  22615. ******************************************************************************
  22616. **
  22617. ** This file contains code that is specific to Windows.
  22618. */
  22619. #ifndef SQLITE_OS_WIN_H
  22620. #define SQLITE_OS_WIN_H
  22621. /*
  22622. ** Include the primary Windows SDK header file.
  22623. */
  22624. #include "windows.h"
  22625. #ifdef __CYGWIN__
  22626. # include <sys/cygwin.h>
  22627. # include <errno.h> /* amalgamator: dontcache */
  22628. #endif
  22629. /*
  22630. ** Determine if we are dealing with Windows NT.
  22631. **
  22632. ** We ought to be able to determine if we are compiling for Windows 9x or
  22633. ** Windows NT using the _WIN32_WINNT macro as follows:
  22634. **
  22635. ** #if defined(_WIN32_WINNT)
  22636. ** # define SQLITE_OS_WINNT 1
  22637. ** #else
  22638. ** # define SQLITE_OS_WINNT 0
  22639. ** #endif
  22640. **
  22641. ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
  22642. ** it ought to, so the above test does not work. We'll just assume that
  22643. ** everything is Windows NT unless the programmer explicitly says otherwise
  22644. ** by setting SQLITE_OS_WINNT to 0.
  22645. */
  22646. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  22647. # define SQLITE_OS_WINNT 1
  22648. #endif
  22649. /*
  22650. ** Determine if we are dealing with Windows CE - which has a much reduced
  22651. ** API.
  22652. */
  22653. #if defined(_WIN32_WCE)
  22654. # define SQLITE_OS_WINCE 1
  22655. #else
  22656. # define SQLITE_OS_WINCE 0
  22657. #endif
  22658. /*
  22659. ** Determine if we are dealing with WinRT, which provides only a subset of
  22660. ** the full Win32 API.
  22661. */
  22662. #if !defined(SQLITE_OS_WINRT)
  22663. # define SQLITE_OS_WINRT 0
  22664. #endif
  22665. /*
  22666. ** For WinCE, some API function parameters do not appear to be declared as
  22667. ** volatile.
  22668. */
  22669. #if SQLITE_OS_WINCE
  22670. # define SQLITE_WIN32_VOLATILE
  22671. #else
  22672. # define SQLITE_WIN32_VOLATILE volatile
  22673. #endif
  22674. /*
  22675. ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
  22676. ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
  22677. */
  22678. #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  22679. SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
  22680. # define SQLITE_OS_WIN_THREADS 1
  22681. #else
  22682. # define SQLITE_OS_WIN_THREADS 0
  22683. #endif
  22684. #endif /* SQLITE_OS_WIN_H */
  22685. /************** End of os_win.h **********************************************/
  22686. /************** Continuing where we left off in mutex_w32.c ******************/
  22687. #endif
  22688. /*
  22689. ** The code in this file is only used if we are compiling multithreaded
  22690. ** on a Win32 system.
  22691. */
  22692. #ifdef SQLITE_MUTEX_W32
  22693. /*
  22694. ** Each recursive mutex is an instance of the following structure.
  22695. */
  22696. struct sqlite3_mutex {
  22697. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  22698. int id; /* Mutex type */
  22699. #ifdef SQLITE_DEBUG
  22700. volatile int nRef; /* Number of enterances */
  22701. volatile DWORD owner; /* Thread holding this mutex */
  22702. volatile int trace; /* True to trace changes */
  22703. #endif
  22704. };
  22705. /*
  22706. ** These are the initializer values used when declaring a "static" mutex
  22707. ** on Win32. It should be noted that all mutexes require initialization
  22708. ** on the Win32 platform.
  22709. */
  22710. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  22711. #ifdef SQLITE_DEBUG
  22712. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
  22713. 0L, (DWORD)0, 0 }
  22714. #else
  22715. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
  22716. #endif
  22717. #ifdef SQLITE_DEBUG
  22718. /*
  22719. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  22720. ** intended for use only inside assert() statements.
  22721. */
  22722. static int winMutexHeld(sqlite3_mutex *p){
  22723. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  22724. }
  22725. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  22726. return p->nRef==0 || p->owner!=tid;
  22727. }
  22728. static int winMutexNotheld(sqlite3_mutex *p){
  22729. DWORD tid = GetCurrentThreadId();
  22730. return winMutexNotheld2(p, tid);
  22731. }
  22732. #endif
  22733. /*
  22734. ** Try to provide a memory barrier operation, needed for initialization
  22735. ** and also for the xShmBarrier method of the VFS in cases when SQLite is
  22736. ** compiled without mutexes (SQLITE_THREADSAFE=0).
  22737. */
  22738. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  22739. #if defined(SQLITE_MEMORY_BARRIER)
  22740. SQLITE_MEMORY_BARRIER;
  22741. #elif defined(__GNUC__)
  22742. __sync_synchronize();
  22743. #elif MSVC_VERSION>=1300
  22744. _ReadWriteBarrier();
  22745. #elif defined(MemoryBarrier)
  22746. MemoryBarrier();
  22747. #endif
  22748. }
  22749. /*
  22750. ** Initialize and deinitialize the mutex subsystem.
  22751. */
  22752. static sqlite3_mutex winMutex_staticMutexes[] = {
  22753. SQLITE3_MUTEX_INITIALIZER,
  22754. SQLITE3_MUTEX_INITIALIZER,
  22755. SQLITE3_MUTEX_INITIALIZER,
  22756. SQLITE3_MUTEX_INITIALIZER,
  22757. SQLITE3_MUTEX_INITIALIZER,
  22758. SQLITE3_MUTEX_INITIALIZER,
  22759. SQLITE3_MUTEX_INITIALIZER,
  22760. SQLITE3_MUTEX_INITIALIZER,
  22761. SQLITE3_MUTEX_INITIALIZER,
  22762. SQLITE3_MUTEX_INITIALIZER,
  22763. SQLITE3_MUTEX_INITIALIZER,
  22764. SQLITE3_MUTEX_INITIALIZER
  22765. };
  22766. static int winMutex_isInit = 0;
  22767. static int winMutex_isNt = -1; /* <0 means "need to query" */
  22768. /* As the winMutexInit() and winMutexEnd() functions are called as part
  22769. ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
  22770. ** "interlocked" magic used here is probably not strictly necessary.
  22771. */
  22772. static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
  22773. SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
  22774. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  22775. static int winMutexInit(void){
  22776. /* The first to increment to 1 does actual initialization */
  22777. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  22778. int i;
  22779. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  22780. #if SQLITE_OS_WINRT
  22781. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  22782. #else
  22783. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  22784. #endif
  22785. }
  22786. winMutex_isInit = 1;
  22787. }else{
  22788. /* Another thread is (in the process of) initializing the static
  22789. ** mutexes */
  22790. while( !winMutex_isInit ){
  22791. sqlite3_win32_sleep(1);
  22792. }
  22793. }
  22794. return SQLITE_OK;
  22795. }
  22796. static int winMutexEnd(void){
  22797. /* The first to decrement to 0 does actual shutdown
  22798. ** (which should be the last to shutdown.) */
  22799. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  22800. if( winMutex_isInit==1 ){
  22801. int i;
  22802. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  22803. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  22804. }
  22805. winMutex_isInit = 0;
  22806. }
  22807. }
  22808. return SQLITE_OK;
  22809. }
  22810. /*
  22811. ** The sqlite3_mutex_alloc() routine allocates a new
  22812. ** mutex and returns a pointer to it. If it returns NULL
  22813. ** that means that a mutex could not be allocated. SQLite
  22814. ** will unwind its stack and return an error. The argument
  22815. ** to sqlite3_mutex_alloc() is one of these integer constants:
  22816. **
  22817. ** <ul>
  22818. ** <li> SQLITE_MUTEX_FAST
  22819. ** <li> SQLITE_MUTEX_RECURSIVE
  22820. ** <li> SQLITE_MUTEX_STATIC_MASTER
  22821. ** <li> SQLITE_MUTEX_STATIC_MEM
  22822. ** <li> SQLITE_MUTEX_STATIC_OPEN
  22823. ** <li> SQLITE_MUTEX_STATIC_PRNG
  22824. ** <li> SQLITE_MUTEX_STATIC_LRU
  22825. ** <li> SQLITE_MUTEX_STATIC_PMEM
  22826. ** <li> SQLITE_MUTEX_STATIC_APP1
  22827. ** <li> SQLITE_MUTEX_STATIC_APP2
  22828. ** <li> SQLITE_MUTEX_STATIC_APP3
  22829. ** <li> SQLITE_MUTEX_STATIC_VFS1
  22830. ** <li> SQLITE_MUTEX_STATIC_VFS2
  22831. ** <li> SQLITE_MUTEX_STATIC_VFS3
  22832. ** </ul>
  22833. **
  22834. ** The first two constants cause sqlite3_mutex_alloc() to create
  22835. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  22836. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  22837. ** The mutex implementation does not need to make a distinction
  22838. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  22839. ** not want to. But SQLite will only request a recursive mutex in
  22840. ** cases where it really needs one. If a faster non-recursive mutex
  22841. ** implementation is available on the host platform, the mutex subsystem
  22842. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  22843. **
  22844. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  22845. ** a pointer to a static preexisting mutex. Six static mutexes are
  22846. ** used by the current version of SQLite. Future versions of SQLite
  22847. ** may add additional static mutexes. Static mutexes are for internal
  22848. ** use by SQLite only. Applications that use SQLite mutexes should
  22849. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  22850. ** SQLITE_MUTEX_RECURSIVE.
  22851. **
  22852. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  22853. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  22854. ** returns a different mutex on every call. But for the static
  22855. ** mutex types, the same mutex is returned on every call that has
  22856. ** the same type number.
  22857. */
  22858. static sqlite3_mutex *winMutexAlloc(int iType){
  22859. sqlite3_mutex *p;
  22860. switch( iType ){
  22861. case SQLITE_MUTEX_FAST:
  22862. case SQLITE_MUTEX_RECURSIVE: {
  22863. p = sqlite3MallocZero( sizeof(*p) );
  22864. if( p ){
  22865. p->id = iType;
  22866. #ifdef SQLITE_DEBUG
  22867. #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
  22868. p->trace = 1;
  22869. #endif
  22870. #endif
  22871. #if SQLITE_OS_WINRT
  22872. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  22873. #else
  22874. InitializeCriticalSection(&p->mutex);
  22875. #endif
  22876. }
  22877. break;
  22878. }
  22879. default: {
  22880. #ifdef SQLITE_ENABLE_API_ARMOR
  22881. if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
  22882. (void)SQLITE_MISUSE_BKPT;
  22883. return 0;
  22884. }
  22885. #endif
  22886. p = &winMutex_staticMutexes[iType-2];
  22887. p->id = iType;
  22888. #ifdef SQLITE_DEBUG
  22889. #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
  22890. p->trace = 1;
  22891. #endif
  22892. #endif
  22893. break;
  22894. }
  22895. }
  22896. return p;
  22897. }
  22898. /*
  22899. ** This routine deallocates a previously
  22900. ** allocated mutex. SQLite is careful to deallocate every
  22901. ** mutex that it allocates.
  22902. */
  22903. static void winMutexFree(sqlite3_mutex *p){
  22904. assert( p );
  22905. assert( p->nRef==0 && p->owner==0 );
  22906. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
  22907. DeleteCriticalSection(&p->mutex);
  22908. sqlite3_free(p);
  22909. }else{
  22910. #ifdef SQLITE_ENABLE_API_ARMOR
  22911. (void)SQLITE_MISUSE_BKPT;
  22912. #endif
  22913. }
  22914. }
  22915. /*
  22916. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  22917. ** to enter a mutex. If another thread is already within the mutex,
  22918. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  22919. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  22920. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  22921. ** be entered multiple times by the same thread. In such cases the,
  22922. ** mutex must be exited an equal number of times before another thread
  22923. ** can enter. If the same thread tries to enter any other kind of mutex
  22924. ** more than once, the behavior is undefined.
  22925. */
  22926. static void winMutexEnter(sqlite3_mutex *p){
  22927. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  22928. DWORD tid = GetCurrentThreadId();
  22929. #endif
  22930. #ifdef SQLITE_DEBUG
  22931. assert( p );
  22932. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  22933. #else
  22934. assert( p );
  22935. #endif
  22936. assert( winMutex_isInit==1 );
  22937. EnterCriticalSection(&p->mutex);
  22938. #ifdef SQLITE_DEBUG
  22939. assert( p->nRef>0 || p->owner==0 );
  22940. p->owner = tid;
  22941. p->nRef++;
  22942. if( p->trace ){
  22943. OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
  22944. tid, p->id, p, p->trace, p->nRef));
  22945. }
  22946. #endif
  22947. }
  22948. static int winMutexTry(sqlite3_mutex *p){
  22949. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  22950. DWORD tid = GetCurrentThreadId();
  22951. #endif
  22952. int rc = SQLITE_BUSY;
  22953. assert( p );
  22954. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  22955. /*
  22956. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  22957. ** is used it is merely an optimization. So it is OK for it to always
  22958. ** fail.
  22959. **
  22960. ** The TryEnterCriticalSection() interface is only available on WinNT.
  22961. ** And some windows compilers complain if you try to use it without
  22962. ** first doing some #defines that prevent SQLite from building on Win98.
  22963. ** For that reason, we will omit this optimization for now. See
  22964. ** ticket #2685.
  22965. */
  22966. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
  22967. assert( winMutex_isInit==1 );
  22968. assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
  22969. if( winMutex_isNt<0 ){
  22970. winMutex_isNt = sqlite3_win32_is_nt();
  22971. }
  22972. assert( winMutex_isNt==0 || winMutex_isNt==1 );
  22973. if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
  22974. #ifdef SQLITE_DEBUG
  22975. p->owner = tid;
  22976. p->nRef++;
  22977. #endif
  22978. rc = SQLITE_OK;
  22979. }
  22980. #else
  22981. UNUSED_PARAMETER(p);
  22982. #endif
  22983. #ifdef SQLITE_DEBUG
  22984. if( p->trace ){
  22985. OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
  22986. tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
  22987. }
  22988. #endif
  22989. return rc;
  22990. }
  22991. /*
  22992. ** The sqlite3_mutex_leave() routine exits a mutex that was
  22993. ** previously entered by the same thread. The behavior
  22994. ** is undefined if the mutex is not currently entered or
  22995. ** is not currently allocated. SQLite will never do either.
  22996. */
  22997. static void winMutexLeave(sqlite3_mutex *p){
  22998. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  22999. DWORD tid = GetCurrentThreadId();
  23000. #endif
  23001. assert( p );
  23002. #ifdef SQLITE_DEBUG
  23003. assert( p->nRef>0 );
  23004. assert( p->owner==tid );
  23005. p->nRef--;
  23006. if( p->nRef==0 ) p->owner = 0;
  23007. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  23008. #endif
  23009. assert( winMutex_isInit==1 );
  23010. LeaveCriticalSection(&p->mutex);
  23011. #ifdef SQLITE_DEBUG
  23012. if( p->trace ){
  23013. OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
  23014. tid, p->id, p, p->trace, p->nRef));
  23015. }
  23016. #endif
  23017. }
  23018. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  23019. static const sqlite3_mutex_methods sMutex = {
  23020. winMutexInit,
  23021. winMutexEnd,
  23022. winMutexAlloc,
  23023. winMutexFree,
  23024. winMutexEnter,
  23025. winMutexTry,
  23026. winMutexLeave,
  23027. #ifdef SQLITE_DEBUG
  23028. winMutexHeld,
  23029. winMutexNotheld
  23030. #else
  23031. 0,
  23032. 0
  23033. #endif
  23034. };
  23035. return &sMutex;
  23036. }
  23037. #endif /* SQLITE_MUTEX_W32 */
  23038. /************** End of mutex_w32.c *******************************************/
  23039. /************** Begin file malloc.c ******************************************/
  23040. /*
  23041. ** 2001 September 15
  23042. **
  23043. ** The author disclaims copyright to this source code. In place of
  23044. ** a legal notice, here is a blessing:
  23045. **
  23046. ** May you do good and not evil.
  23047. ** May you find forgiveness for yourself and forgive others.
  23048. ** May you share freely, never taking more than you give.
  23049. **
  23050. *************************************************************************
  23051. **
  23052. ** Memory allocation functions used throughout sqlite.
  23053. */
  23054. /* #include "sqliteInt.h" */
  23055. /* #include <stdarg.h> */
  23056. /*
  23057. ** Attempt to release up to n bytes of non-essential memory currently
  23058. ** held by SQLite. An example of non-essential memory is memory used to
  23059. ** cache database pages that are not currently in use.
  23060. */
  23061. SQLITE_API int sqlite3_release_memory(int n){
  23062. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  23063. return sqlite3PcacheReleaseMemory(n);
  23064. #else
  23065. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  23066. ** is a no-op returning zero if SQLite is not compiled with
  23067. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  23068. UNUSED_PARAMETER(n);
  23069. return 0;
  23070. #endif
  23071. }
  23072. /*
  23073. ** An instance of the following object records the location of
  23074. ** each unused scratch buffer.
  23075. */
  23076. typedef struct ScratchFreeslot {
  23077. struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
  23078. } ScratchFreeslot;
  23079. /*
  23080. ** State information local to the memory allocation subsystem.
  23081. */
  23082. static SQLITE_WSD struct Mem0Global {
  23083. sqlite3_mutex *mutex; /* Mutex to serialize access */
  23084. sqlite3_int64 alarmThreshold; /* The soft heap limit */
  23085. /*
  23086. ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
  23087. ** (so that a range test can be used to determine if an allocation
  23088. ** being freed came from pScratch) and a pointer to the list of
  23089. ** unused scratch allocations.
  23090. */
  23091. void *pScratchEnd;
  23092. ScratchFreeslot *pScratchFree;
  23093. u32 nScratchFree;
  23094. /*
  23095. ** True if heap is nearly "full" where "full" is defined by the
  23096. ** sqlite3_soft_heap_limit() setting.
  23097. */
  23098. int nearlyFull;
  23099. } mem0 = { 0, 0, 0, 0, 0, 0 };
  23100. #define mem0 GLOBAL(struct Mem0Global, mem0)
  23101. /*
  23102. ** Return the memory allocator mutex. sqlite3_status() needs it.
  23103. */
  23104. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
  23105. return mem0.mutex;
  23106. }
  23107. #ifndef SQLITE_OMIT_DEPRECATED
  23108. /*
  23109. ** Deprecated external interface. It used to set an alarm callback
  23110. ** that was invoked when memory usage grew too large. Now it is a
  23111. ** no-op.
  23112. */
  23113. SQLITE_API int sqlite3_memory_alarm(
  23114. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  23115. void *pArg,
  23116. sqlite3_int64 iThreshold
  23117. ){
  23118. (void)xCallback;
  23119. (void)pArg;
  23120. (void)iThreshold;
  23121. return SQLITE_OK;
  23122. }
  23123. #endif
  23124. /*
  23125. ** Set the soft heap-size limit for the library. Passing a zero or
  23126. ** negative value indicates no limit.
  23127. */
  23128. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  23129. sqlite3_int64 priorLimit;
  23130. sqlite3_int64 excess;
  23131. sqlite3_int64 nUsed;
  23132. #ifndef SQLITE_OMIT_AUTOINIT
  23133. int rc = sqlite3_initialize();
  23134. if( rc ) return -1;
  23135. #endif
  23136. sqlite3_mutex_enter(mem0.mutex);
  23137. priorLimit = mem0.alarmThreshold;
  23138. if( n<0 ){
  23139. sqlite3_mutex_leave(mem0.mutex);
  23140. return priorLimit;
  23141. }
  23142. mem0.alarmThreshold = n;
  23143. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  23144. mem0.nearlyFull = (n>0 && n<=nUsed);
  23145. sqlite3_mutex_leave(mem0.mutex);
  23146. excess = sqlite3_memory_used() - n;
  23147. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  23148. return priorLimit;
  23149. }
  23150. SQLITE_API void sqlite3_soft_heap_limit(int n){
  23151. if( n<0 ) n = 0;
  23152. sqlite3_soft_heap_limit64(n);
  23153. }
  23154. /*
  23155. ** Initialize the memory allocation subsystem.
  23156. */
  23157. SQLITE_PRIVATE int sqlite3MallocInit(void){
  23158. int rc;
  23159. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  23160. sqlite3MemSetDefault();
  23161. }
  23162. memset(&mem0, 0, sizeof(mem0));
  23163. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  23164. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  23165. && sqlite3GlobalConfig.nScratch>0 ){
  23166. int i, n, sz;
  23167. ScratchFreeslot *pSlot;
  23168. sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
  23169. sqlite3GlobalConfig.szScratch = sz;
  23170. pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
  23171. n = sqlite3GlobalConfig.nScratch;
  23172. mem0.pScratchFree = pSlot;
  23173. mem0.nScratchFree = n;
  23174. for(i=0; i<n-1; i++){
  23175. pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
  23176. pSlot = pSlot->pNext;
  23177. }
  23178. pSlot->pNext = 0;
  23179. mem0.pScratchEnd = (void*)&pSlot[1];
  23180. }else{
  23181. mem0.pScratchEnd = 0;
  23182. sqlite3GlobalConfig.pScratch = 0;
  23183. sqlite3GlobalConfig.szScratch = 0;
  23184. sqlite3GlobalConfig.nScratch = 0;
  23185. }
  23186. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  23187. || sqlite3GlobalConfig.nPage<=0 ){
  23188. sqlite3GlobalConfig.pPage = 0;
  23189. sqlite3GlobalConfig.szPage = 0;
  23190. }
  23191. rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  23192. if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
  23193. return rc;
  23194. }
  23195. /*
  23196. ** Return true if the heap is currently under memory pressure - in other
  23197. ** words if the amount of heap used is close to the limit set by
  23198. ** sqlite3_soft_heap_limit().
  23199. */
  23200. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  23201. return mem0.nearlyFull;
  23202. }
  23203. /*
  23204. ** Deinitialize the memory allocation subsystem.
  23205. */
  23206. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  23207. if( sqlite3GlobalConfig.m.xShutdown ){
  23208. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  23209. }
  23210. memset(&mem0, 0, sizeof(mem0));
  23211. }
  23212. /*
  23213. ** Return the amount of memory currently checked out.
  23214. */
  23215. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  23216. sqlite3_int64 res, mx;
  23217. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
  23218. return res;
  23219. }
  23220. /*
  23221. ** Return the maximum amount of memory that has ever been
  23222. ** checked out since either the beginning of this process
  23223. ** or since the most recent reset.
  23224. */
  23225. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  23226. sqlite3_int64 res, mx;
  23227. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
  23228. return mx;
  23229. }
  23230. /*
  23231. ** Trigger the alarm
  23232. */
  23233. static void sqlite3MallocAlarm(int nByte){
  23234. if( mem0.alarmThreshold<=0 ) return;
  23235. sqlite3_mutex_leave(mem0.mutex);
  23236. sqlite3_release_memory(nByte);
  23237. sqlite3_mutex_enter(mem0.mutex);
  23238. }
  23239. /*
  23240. ** Do a memory allocation with statistics and alarms. Assume the
  23241. ** lock is already held.
  23242. */
  23243. static void mallocWithAlarm(int n, void **pp){
  23244. void *p;
  23245. int nFull;
  23246. assert( sqlite3_mutex_held(mem0.mutex) );
  23247. assert( n>0 );
  23248. /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
  23249. ** implementation of malloc_good_size(), which must be called in debug
  23250. ** mode and specifically when the DMD "Dark Matter Detector" is enabled
  23251. ** or else a crash results. Hence, do not attempt to optimize out the
  23252. ** following xRoundup() call. */
  23253. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  23254. #ifdef SQLITE_MAX_MEMORY
  23255. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){
  23256. *pp = 0;
  23257. return;
  23258. }
  23259. #endif
  23260. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
  23261. if( mem0.alarmThreshold>0 ){
  23262. sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  23263. if( nUsed >= mem0.alarmThreshold - nFull ){
  23264. mem0.nearlyFull = 1;
  23265. sqlite3MallocAlarm(nFull);
  23266. }else{
  23267. mem0.nearlyFull = 0;
  23268. }
  23269. }
  23270. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  23271. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  23272. if( p==0 && mem0.alarmThreshold>0 ){
  23273. sqlite3MallocAlarm(nFull);
  23274. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  23275. }
  23276. #endif
  23277. if( p ){
  23278. nFull = sqlite3MallocSize(p);
  23279. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
  23280. sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
  23281. }
  23282. *pp = p;
  23283. }
  23284. /*
  23285. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  23286. ** assumes the memory subsystem has already been initialized.
  23287. */
  23288. SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
  23289. void *p;
  23290. if( n==0 || n>=0x7fffff00 ){
  23291. /* A memory allocation of a number of bytes which is near the maximum
  23292. ** signed integer value might cause an integer overflow inside of the
  23293. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  23294. ** 255 bytes of overhead. SQLite itself will never use anything near
  23295. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  23296. p = 0;
  23297. }else if( sqlite3GlobalConfig.bMemstat ){
  23298. sqlite3_mutex_enter(mem0.mutex);
  23299. mallocWithAlarm((int)n, &p);
  23300. sqlite3_mutex_leave(mem0.mutex);
  23301. }else{
  23302. p = sqlite3GlobalConfig.m.xMalloc((int)n);
  23303. }
  23304. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
  23305. return p;
  23306. }
  23307. /*
  23308. ** This version of the memory allocation is for use by the application.
  23309. ** First make sure the memory subsystem is initialized, then do the
  23310. ** allocation.
  23311. */
  23312. SQLITE_API void *sqlite3_malloc(int n){
  23313. #ifndef SQLITE_OMIT_AUTOINIT
  23314. if( sqlite3_initialize() ) return 0;
  23315. #endif
  23316. return n<=0 ? 0 : sqlite3Malloc(n);
  23317. }
  23318. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
  23319. #ifndef SQLITE_OMIT_AUTOINIT
  23320. if( sqlite3_initialize() ) return 0;
  23321. #endif
  23322. return sqlite3Malloc(n);
  23323. }
  23324. /*
  23325. ** Each thread may only have a single outstanding allocation from
  23326. ** xScratchMalloc(). We verify this constraint in the single-threaded
  23327. ** case by setting scratchAllocOut to 1 when an allocation
  23328. ** is outstanding clearing it when the allocation is freed.
  23329. */
  23330. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  23331. static int scratchAllocOut = 0;
  23332. #endif
  23333. /*
  23334. ** Allocate memory that is to be used and released right away.
  23335. ** This routine is similar to alloca() in that it is not intended
  23336. ** for situations where the memory might be held long-term. This
  23337. ** routine is intended to get memory to old large transient data
  23338. ** structures that would not normally fit on the stack of an
  23339. ** embedded processor.
  23340. */
  23341. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  23342. void *p;
  23343. assert( n>0 );
  23344. sqlite3_mutex_enter(mem0.mutex);
  23345. sqlite3StatusHighwater(SQLITE_STATUS_SCRATCH_SIZE, n);
  23346. if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
  23347. p = mem0.pScratchFree;
  23348. mem0.pScratchFree = mem0.pScratchFree->pNext;
  23349. mem0.nScratchFree--;
  23350. sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
  23351. sqlite3_mutex_leave(mem0.mutex);
  23352. }else{
  23353. sqlite3_mutex_leave(mem0.mutex);
  23354. p = sqlite3Malloc(n);
  23355. if( sqlite3GlobalConfig.bMemstat && p ){
  23356. sqlite3_mutex_enter(mem0.mutex);
  23357. sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
  23358. sqlite3_mutex_leave(mem0.mutex);
  23359. }
  23360. sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
  23361. }
  23362. assert( sqlite3_mutex_notheld(mem0.mutex) );
  23363. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  23364. /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
  23365. ** buffers per thread.
  23366. **
  23367. ** This can only be checked in single-threaded mode.
  23368. */
  23369. assert( scratchAllocOut==0 );
  23370. if( p ) scratchAllocOut++;
  23371. #endif
  23372. return p;
  23373. }
  23374. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  23375. if( p ){
  23376. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  23377. /* Verify that no more than two scratch allocation per thread
  23378. ** is outstanding at one time. (This is only checked in the
  23379. ** single-threaded case since checking in the multi-threaded case
  23380. ** would be much more complicated.) */
  23381. assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
  23382. scratchAllocOut--;
  23383. #endif
  23384. if( SQLITE_WITHIN(p, sqlite3GlobalConfig.pScratch, mem0.pScratchEnd) ){
  23385. /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
  23386. ScratchFreeslot *pSlot;
  23387. pSlot = (ScratchFreeslot*)p;
  23388. sqlite3_mutex_enter(mem0.mutex);
  23389. pSlot->pNext = mem0.pScratchFree;
  23390. mem0.pScratchFree = pSlot;
  23391. mem0.nScratchFree++;
  23392. assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
  23393. sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
  23394. sqlite3_mutex_leave(mem0.mutex);
  23395. }else{
  23396. /* Release memory back to the heap */
  23397. assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
  23398. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
  23399. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  23400. if( sqlite3GlobalConfig.bMemstat ){
  23401. int iSize = sqlite3MallocSize(p);
  23402. sqlite3_mutex_enter(mem0.mutex);
  23403. sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
  23404. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
  23405. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  23406. sqlite3GlobalConfig.m.xFree(p);
  23407. sqlite3_mutex_leave(mem0.mutex);
  23408. }else{
  23409. sqlite3GlobalConfig.m.xFree(p);
  23410. }
  23411. }
  23412. }
  23413. }
  23414. /*
  23415. ** TRUE if p is a lookaside memory allocation from db
  23416. */
  23417. #ifndef SQLITE_OMIT_LOOKASIDE
  23418. static int isLookaside(sqlite3 *db, void *p){
  23419. return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
  23420. }
  23421. #else
  23422. #define isLookaside(A,B) 0
  23423. #endif
  23424. /*
  23425. ** Return the size of a memory allocation previously obtained from
  23426. ** sqlite3Malloc() or sqlite3_malloc().
  23427. */
  23428. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  23429. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  23430. return sqlite3GlobalConfig.m.xSize(p);
  23431. }
  23432. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  23433. assert( p!=0 );
  23434. if( db==0 || !isLookaside(db,p) ){
  23435. #ifdef SQLITE_DEBUG
  23436. if( db==0 ){
  23437. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  23438. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  23439. }else{
  23440. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  23441. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  23442. }
  23443. #endif
  23444. return sqlite3GlobalConfig.m.xSize(p);
  23445. }else{
  23446. assert( sqlite3_mutex_held(db->mutex) );
  23447. return db->lookaside.sz;
  23448. }
  23449. }
  23450. SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
  23451. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  23452. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  23453. return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
  23454. }
  23455. /*
  23456. ** Free memory previously obtained from sqlite3Malloc().
  23457. */
  23458. SQLITE_API void sqlite3_free(void *p){
  23459. if( p==0 ) return; /* IMP: R-49053-54554 */
  23460. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  23461. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  23462. if( sqlite3GlobalConfig.bMemstat ){
  23463. sqlite3_mutex_enter(mem0.mutex);
  23464. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
  23465. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  23466. sqlite3GlobalConfig.m.xFree(p);
  23467. sqlite3_mutex_leave(mem0.mutex);
  23468. }else{
  23469. sqlite3GlobalConfig.m.xFree(p);
  23470. }
  23471. }
  23472. /*
  23473. ** Add the size of memory allocation "p" to the count in
  23474. ** *db->pnBytesFreed.
  23475. */
  23476. static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
  23477. *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
  23478. }
  23479. /*
  23480. ** Free memory that might be associated with a particular database
  23481. ** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
  23482. ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
  23483. */
  23484. SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
  23485. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  23486. assert( p!=0 );
  23487. if( db ){
  23488. if( db->pnBytesFreed ){
  23489. measureAllocationSize(db, p);
  23490. return;
  23491. }
  23492. if( isLookaside(db, p) ){
  23493. LookasideSlot *pBuf = (LookasideSlot*)p;
  23494. #ifdef SQLITE_DEBUG
  23495. /* Trash all content in the buffer being freed */
  23496. memset(p, 0xaa, db->lookaside.sz);
  23497. #endif
  23498. pBuf->pNext = db->lookaside.pFree;
  23499. db->lookaside.pFree = pBuf;
  23500. db->lookaside.nOut--;
  23501. return;
  23502. }
  23503. }
  23504. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  23505. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  23506. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  23507. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  23508. sqlite3_free(p);
  23509. }
  23510. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  23511. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  23512. if( p ) sqlite3DbFreeNN(db, p);
  23513. }
  23514. /*
  23515. ** Change the size of an existing memory allocation
  23516. */
  23517. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
  23518. int nOld, nNew, nDiff;
  23519. void *pNew;
  23520. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  23521. assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
  23522. if( pOld==0 ){
  23523. return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
  23524. }
  23525. if( nBytes==0 ){
  23526. sqlite3_free(pOld); /* IMP: R-26507-47431 */
  23527. return 0;
  23528. }
  23529. if( nBytes>=0x7fffff00 ){
  23530. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  23531. return 0;
  23532. }
  23533. nOld = sqlite3MallocSize(pOld);
  23534. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  23535. ** argument to xRealloc is always a value returned by a prior call to
  23536. ** xRoundup. */
  23537. nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
  23538. if( nOld==nNew ){
  23539. pNew = pOld;
  23540. }else if( sqlite3GlobalConfig.bMemstat ){
  23541. sqlite3_mutex_enter(mem0.mutex);
  23542. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
  23543. nDiff = nNew - nOld;
  23544. if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  23545. mem0.alarmThreshold-nDiff ){
  23546. sqlite3MallocAlarm(nDiff);
  23547. }
  23548. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  23549. if( pNew==0 && mem0.alarmThreshold>0 ){
  23550. sqlite3MallocAlarm((int)nBytes);
  23551. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  23552. }
  23553. if( pNew ){
  23554. nNew = sqlite3MallocSize(pNew);
  23555. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  23556. }
  23557. sqlite3_mutex_leave(mem0.mutex);
  23558. }else{
  23559. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  23560. }
  23561. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
  23562. return pNew;
  23563. }
  23564. /*
  23565. ** The public interface to sqlite3Realloc. Make sure that the memory
  23566. ** subsystem is initialized prior to invoking sqliteRealloc.
  23567. */
  23568. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  23569. #ifndef SQLITE_OMIT_AUTOINIT
  23570. if( sqlite3_initialize() ) return 0;
  23571. #endif
  23572. if( n<0 ) n = 0; /* IMP: R-26507-47431 */
  23573. return sqlite3Realloc(pOld, n);
  23574. }
  23575. SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
  23576. #ifndef SQLITE_OMIT_AUTOINIT
  23577. if( sqlite3_initialize() ) return 0;
  23578. #endif
  23579. return sqlite3Realloc(pOld, n);
  23580. }
  23581. /*
  23582. ** Allocate and zero memory.
  23583. */
  23584. SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
  23585. void *p = sqlite3Malloc(n);
  23586. if( p ){
  23587. memset(p, 0, (size_t)n);
  23588. }
  23589. return p;
  23590. }
  23591. /*
  23592. ** Allocate and zero memory. If the allocation fails, make
  23593. ** the mallocFailed flag in the connection pointer.
  23594. */
  23595. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
  23596. void *p;
  23597. testcase( db==0 );
  23598. p = sqlite3DbMallocRaw(db, n);
  23599. if( p ) memset(p, 0, (size_t)n);
  23600. return p;
  23601. }
  23602. /* Finish the work of sqlite3DbMallocRawNN for the unusual and
  23603. ** slower case when the allocation cannot be fulfilled using lookaside.
  23604. */
  23605. static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
  23606. void *p;
  23607. assert( db!=0 );
  23608. p = sqlite3Malloc(n);
  23609. if( !p ) sqlite3OomFault(db);
  23610. sqlite3MemdebugSetType(p,
  23611. (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
  23612. return p;
  23613. }
  23614. /*
  23615. ** Allocate memory, either lookaside (if possible) or heap.
  23616. ** If the allocation fails, set the mallocFailed flag in
  23617. ** the connection pointer.
  23618. **
  23619. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  23620. ** failure on the same database connection) then always return 0.
  23621. ** Hence for a particular database connection, once malloc starts
  23622. ** failing, it fails consistently until mallocFailed is reset.
  23623. ** This is an important assumption. There are many places in the
  23624. ** code that do things like this:
  23625. **
  23626. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  23627. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  23628. ** if( b ) a[10] = 9;
  23629. **
  23630. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  23631. ** that all prior mallocs (ex: "a") worked too.
  23632. **
  23633. ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
  23634. ** not a NULL pointer.
  23635. */
  23636. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
  23637. void *p;
  23638. if( db ) return sqlite3DbMallocRawNN(db, n);
  23639. p = sqlite3Malloc(n);
  23640. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  23641. return p;
  23642. }
  23643. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
  23644. #ifndef SQLITE_OMIT_LOOKASIDE
  23645. LookasideSlot *pBuf;
  23646. assert( db!=0 );
  23647. assert( sqlite3_mutex_held(db->mutex) );
  23648. assert( db->pnBytesFreed==0 );
  23649. if( db->lookaside.bDisable==0 ){
  23650. assert( db->mallocFailed==0 );
  23651. if( n>db->lookaside.sz ){
  23652. db->lookaside.anStat[1]++;
  23653. }else if( (pBuf = db->lookaside.pFree)==0 ){
  23654. db->lookaside.anStat[2]++;
  23655. }else{
  23656. db->lookaside.pFree = pBuf->pNext;
  23657. db->lookaside.nOut++;
  23658. db->lookaside.anStat[0]++;
  23659. if( db->lookaside.nOut>db->lookaside.mxOut ){
  23660. db->lookaside.mxOut = db->lookaside.nOut;
  23661. }
  23662. return (void*)pBuf;
  23663. }
  23664. }else if( db->mallocFailed ){
  23665. return 0;
  23666. }
  23667. #else
  23668. assert( db!=0 );
  23669. assert( sqlite3_mutex_held(db->mutex) );
  23670. assert( db->pnBytesFreed==0 );
  23671. if( db->mallocFailed ){
  23672. return 0;
  23673. }
  23674. #endif
  23675. return dbMallocRawFinish(db, n);
  23676. }
  23677. /* Forward declaration */
  23678. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
  23679. /*
  23680. ** Resize the block of memory pointed to by p to n bytes. If the
  23681. ** resize fails, set the mallocFailed flag in the connection object.
  23682. */
  23683. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
  23684. assert( db!=0 );
  23685. if( p==0 ) return sqlite3DbMallocRawNN(db, n);
  23686. assert( sqlite3_mutex_held(db->mutex) );
  23687. if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
  23688. return dbReallocFinish(db, p, n);
  23689. }
  23690. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
  23691. void *pNew = 0;
  23692. assert( db!=0 );
  23693. assert( p!=0 );
  23694. if( db->mallocFailed==0 ){
  23695. if( isLookaside(db, p) ){
  23696. pNew = sqlite3DbMallocRawNN(db, n);
  23697. if( pNew ){
  23698. memcpy(pNew, p, db->lookaside.sz);
  23699. sqlite3DbFree(db, p);
  23700. }
  23701. }else{
  23702. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  23703. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  23704. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  23705. pNew = sqlite3_realloc64(p, n);
  23706. if( !pNew ){
  23707. sqlite3OomFault(db);
  23708. }
  23709. sqlite3MemdebugSetType(pNew,
  23710. (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  23711. }
  23712. }
  23713. return pNew;
  23714. }
  23715. /*
  23716. ** Attempt to reallocate p. If the reallocation fails, then free p
  23717. ** and set the mallocFailed flag in the database connection.
  23718. */
  23719. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
  23720. void *pNew;
  23721. pNew = sqlite3DbRealloc(db, p, n);
  23722. if( !pNew ){
  23723. sqlite3DbFree(db, p);
  23724. }
  23725. return pNew;
  23726. }
  23727. /*
  23728. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  23729. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  23730. ** is because when memory debugging is turned on, these two functions are
  23731. ** called via macros that record the current file and line number in the
  23732. ** ThreadData structure.
  23733. */
  23734. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  23735. char *zNew;
  23736. size_t n;
  23737. if( z==0 ){
  23738. return 0;
  23739. }
  23740. n = strlen(z) + 1;
  23741. zNew = sqlite3DbMallocRaw(db, n);
  23742. if( zNew ){
  23743. memcpy(zNew, z, n);
  23744. }
  23745. return zNew;
  23746. }
  23747. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
  23748. char *zNew;
  23749. assert( db!=0 );
  23750. if( z==0 ){
  23751. return 0;
  23752. }
  23753. assert( (n&0x7fffffff)==n );
  23754. zNew = sqlite3DbMallocRawNN(db, n+1);
  23755. if( zNew ){
  23756. memcpy(zNew, z, (size_t)n);
  23757. zNew[n] = 0;
  23758. }
  23759. return zNew;
  23760. }
  23761. /*
  23762. ** Free any prior content in *pz and replace it with a copy of zNew.
  23763. */
  23764. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
  23765. sqlite3DbFree(db, *pz);
  23766. *pz = sqlite3DbStrDup(db, zNew);
  23767. }
  23768. /*
  23769. ** Call this routine to record the fact that an OOM (out-of-memory) error
  23770. ** has happened. This routine will set db->mallocFailed, and also
  23771. ** temporarily disable the lookaside memory allocator and interrupt
  23772. ** any running VDBEs.
  23773. */
  23774. SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
  23775. if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
  23776. db->mallocFailed = 1;
  23777. if( db->nVdbeExec>0 ){
  23778. db->u1.isInterrupted = 1;
  23779. }
  23780. db->lookaside.bDisable++;
  23781. }
  23782. }
  23783. /*
  23784. ** This routine reactivates the memory allocator and clears the
  23785. ** db->mallocFailed flag as necessary.
  23786. **
  23787. ** The memory allocator is not restarted if there are running
  23788. ** VDBEs.
  23789. */
  23790. SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
  23791. if( db->mallocFailed && db->nVdbeExec==0 ){
  23792. db->mallocFailed = 0;
  23793. db->u1.isInterrupted = 0;
  23794. assert( db->lookaside.bDisable>0 );
  23795. db->lookaside.bDisable--;
  23796. }
  23797. }
  23798. /*
  23799. ** Take actions at the end of an API call to indicate an OOM error
  23800. */
  23801. static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
  23802. sqlite3OomClear(db);
  23803. sqlite3Error(db, SQLITE_NOMEM);
  23804. return SQLITE_NOMEM_BKPT;
  23805. }
  23806. /*
  23807. ** This function must be called before exiting any API function (i.e.
  23808. ** returning control to the user) that has called sqlite3_malloc or
  23809. ** sqlite3_realloc.
  23810. **
  23811. ** The returned value is normally a copy of the second argument to this
  23812. ** function. However, if a malloc() failure has occurred since the previous
  23813. ** invocation SQLITE_NOMEM is returned instead.
  23814. **
  23815. ** If an OOM as occurred, then the connection error-code (the value
  23816. ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
  23817. */
  23818. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  23819. /* If the db handle must hold the connection handle mutex here.
  23820. ** Otherwise the read (and possible write) of db->mallocFailed
  23821. ** is unsafe, as is the call to sqlite3Error().
  23822. */
  23823. assert( db!=0 );
  23824. assert( sqlite3_mutex_held(db->mutex) );
  23825. if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
  23826. return apiOomError(db);
  23827. }
  23828. return rc & db->errMask;
  23829. }
  23830. /************** End of malloc.c **********************************************/
  23831. /************** Begin file printf.c ******************************************/
  23832. /*
  23833. ** The "printf" code that follows dates from the 1980's. It is in
  23834. ** the public domain.
  23835. **
  23836. **************************************************************************
  23837. **
  23838. ** This file contains code for a set of "printf"-like routines. These
  23839. ** routines format strings much like the printf() from the standard C
  23840. ** library, though the implementation here has enhancements to support
  23841. ** SQLite.
  23842. */
  23843. /* #include "sqliteInt.h" */
  23844. /*
  23845. ** Conversion types fall into various categories as defined by the
  23846. ** following enumeration.
  23847. */
  23848. #define etRADIX 0 /* non-decimal integer types. %x %o */
  23849. #define etFLOAT 1 /* Floating point. %f */
  23850. #define etEXP 2 /* Exponentional notation. %e and %E */
  23851. #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
  23852. #define etSIZE 4 /* Return number of characters processed so far. %n */
  23853. #define etSTRING 5 /* Strings. %s */
  23854. #define etDYNSTRING 6 /* Dynamically allocated strings. %z */
  23855. #define etPERCENT 7 /* Percent symbol. %% */
  23856. #define etCHARX 8 /* Characters. %c */
  23857. /* The rest are extensions, not normally found in printf() */
  23858. #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
  23859. #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
  23860. NULL pointers replaced by SQL NULL. %Q */
  23861. #define etTOKEN 11 /* a pointer to a Token structure */
  23862. #define etSRCLIST 12 /* a pointer to a SrcList */
  23863. #define etPOINTER 13 /* The %p conversion */
  23864. #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
  23865. #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  23866. #define etDECIMAL 16 /* %d or %u, but not %x, %o */
  23867. #define etINVALID 17 /* Any unrecognized conversion type */
  23868. /*
  23869. ** An "etByte" is an 8-bit unsigned value.
  23870. */
  23871. typedef unsigned char etByte;
  23872. /*
  23873. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  23874. ** by an instance of the following structure
  23875. */
  23876. typedef struct et_info { /* Information about each format field */
  23877. char fmttype; /* The format field code letter */
  23878. etByte base; /* The base for radix conversion */
  23879. etByte flags; /* One or more of FLAG_ constants below */
  23880. etByte type; /* Conversion paradigm */
  23881. etByte charset; /* Offset into aDigits[] of the digits string */
  23882. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  23883. } et_info;
  23884. /*
  23885. ** Allowed values for et_info.flags
  23886. */
  23887. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  23888. #define FLAG_STRING 4 /* Allow infinite precision */
  23889. /*
  23890. ** The following table is searched linearly, so it is good to put the
  23891. ** most frequently used conversion types first.
  23892. */
  23893. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  23894. static const char aPrefix[] = "-x0\000X0";
  23895. static const et_info fmtinfo[] = {
  23896. { 'd', 10, 1, etDECIMAL, 0, 0 },
  23897. { 's', 0, 4, etSTRING, 0, 0 },
  23898. { 'g', 0, 1, etGENERIC, 30, 0 },
  23899. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  23900. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  23901. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  23902. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  23903. { 'c', 0, 0, etCHARX, 0, 0 },
  23904. { 'o', 8, 0, etRADIX, 0, 2 },
  23905. { 'u', 10, 0, etDECIMAL, 0, 0 },
  23906. { 'x', 16, 0, etRADIX, 16, 1 },
  23907. { 'X', 16, 0, etRADIX, 0, 4 },
  23908. #ifndef SQLITE_OMIT_FLOATING_POINT
  23909. { 'f', 0, 1, etFLOAT, 0, 0 },
  23910. { 'e', 0, 1, etEXP, 30, 0 },
  23911. { 'E', 0, 1, etEXP, 14, 0 },
  23912. { 'G', 0, 1, etGENERIC, 14, 0 },
  23913. #endif
  23914. { 'i', 10, 1, etDECIMAL, 0, 0 },
  23915. { 'n', 0, 0, etSIZE, 0, 0 },
  23916. { '%', 0, 0, etPERCENT, 0, 0 },
  23917. { 'p', 16, 0, etPOINTER, 0, 1 },
  23918. /* All the rest are undocumented and are for internal use only */
  23919. { 'T', 0, 0, etTOKEN, 0, 0 },
  23920. { 'S', 0, 0, etSRCLIST, 0, 0 },
  23921. { 'r', 10, 1, etORDINAL, 0, 0 },
  23922. };
  23923. /*
  23924. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  23925. ** conversions will work.
  23926. */
  23927. #ifndef SQLITE_OMIT_FLOATING_POINT
  23928. /*
  23929. ** "*val" is a double such that 0.1 <= *val < 10.0
  23930. ** Return the ascii code for the leading digit of *val, then
  23931. ** multiply "*val" by 10.0 to renormalize.
  23932. **
  23933. ** Example:
  23934. ** input: *val = 3.14159
  23935. ** output: *val = 1.4159 function return = '3'
  23936. **
  23937. ** The counter *cnt is incremented each time. After counter exceeds
  23938. ** 16 (the number of significant digits in a 64-bit float) '0' is
  23939. ** always returned.
  23940. */
  23941. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  23942. int digit;
  23943. LONGDOUBLE_TYPE d;
  23944. if( (*cnt)<=0 ) return '0';
  23945. (*cnt)--;
  23946. digit = (int)*val;
  23947. d = digit;
  23948. digit += '0';
  23949. *val = (*val - d)*10.0;
  23950. return (char)digit;
  23951. }
  23952. #endif /* SQLITE_OMIT_FLOATING_POINT */
  23953. /*
  23954. ** Set the StrAccum object to an error mode.
  23955. */
  23956. static void setStrAccumError(StrAccum *p, u8 eError){
  23957. assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
  23958. p->accError = eError;
  23959. p->nAlloc = 0;
  23960. }
  23961. /*
  23962. ** Extra argument values from a PrintfArguments object
  23963. */
  23964. static sqlite3_int64 getIntArg(PrintfArguments *p){
  23965. if( p->nArg<=p->nUsed ) return 0;
  23966. return sqlite3_value_int64(p->apArg[p->nUsed++]);
  23967. }
  23968. static double getDoubleArg(PrintfArguments *p){
  23969. if( p->nArg<=p->nUsed ) return 0.0;
  23970. return sqlite3_value_double(p->apArg[p->nUsed++]);
  23971. }
  23972. static char *getTextArg(PrintfArguments *p){
  23973. if( p->nArg<=p->nUsed ) return 0;
  23974. return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
  23975. }
  23976. /*
  23977. ** On machines with a small stack size, you can redefine the
  23978. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  23979. */
  23980. #ifndef SQLITE_PRINT_BUF_SIZE
  23981. # define SQLITE_PRINT_BUF_SIZE 70
  23982. #endif
  23983. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  23984. /*
  23985. ** Render a string given by "fmt" into the StrAccum object.
  23986. */
  23987. SQLITE_PRIVATE void sqlite3VXPrintf(
  23988. StrAccum *pAccum, /* Accumulate results here */
  23989. const char *fmt, /* Format string */
  23990. va_list ap /* arguments */
  23991. ){
  23992. int c; /* Next character in the format string */
  23993. char *bufpt; /* Pointer to the conversion buffer */
  23994. int precision; /* Precision of the current field */
  23995. int length; /* Length of the field */
  23996. int idx; /* A general purpose loop counter */
  23997. int width; /* Width of the current field */
  23998. etByte flag_leftjustify; /* True if "-" flag is present */
  23999. etByte flag_prefix; /* '+' or ' ' or 0 for prefix */
  24000. etByte flag_alternateform; /* True if "#" flag is present */
  24001. etByte flag_altform2; /* True if "!" flag is present */
  24002. etByte flag_zeropad; /* True if field width constant starts with zero */
  24003. etByte flag_long; /* 1 for the "l" flag, 2 for "ll", 0 by default */
  24004. etByte done; /* Loop termination flag */
  24005. etByte cThousand; /* Thousands separator for %d and %u */
  24006. etByte xtype = etINVALID; /* Conversion paradigm */
  24007. u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
  24008. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  24009. sqlite_uint64 longvalue; /* Value for integer types */
  24010. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  24011. const et_info *infop; /* Pointer to the appropriate info structure */
  24012. char *zOut; /* Rendering buffer */
  24013. int nOut; /* Size of the rendering buffer */
  24014. char *zExtra = 0; /* Malloced memory used by some conversion */
  24015. #ifndef SQLITE_OMIT_FLOATING_POINT
  24016. int exp, e2; /* exponent of real numbers */
  24017. int nsd; /* Number of significant digits returned */
  24018. double rounder; /* Used for rounding floating point values */
  24019. etByte flag_dp; /* True if decimal point should be shown */
  24020. etByte flag_rtz; /* True if trailing zeros should be removed */
  24021. #endif
  24022. PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
  24023. char buf[etBUFSIZE]; /* Conversion buffer */
  24024. bufpt = 0;
  24025. if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
  24026. pArgList = va_arg(ap, PrintfArguments*);
  24027. bArgList = 1;
  24028. }else{
  24029. bArgList = 0;
  24030. }
  24031. for(; (c=(*fmt))!=0; ++fmt){
  24032. if( c!='%' ){
  24033. bufpt = (char *)fmt;
  24034. #if HAVE_STRCHRNUL
  24035. fmt = strchrnul(fmt, '%');
  24036. #else
  24037. do{ fmt++; }while( *fmt && *fmt != '%' );
  24038. #endif
  24039. sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
  24040. if( *fmt==0 ) break;
  24041. }
  24042. if( (c=(*++fmt))==0 ){
  24043. sqlite3StrAccumAppend(pAccum, "%", 1);
  24044. break;
  24045. }
  24046. /* Find out what flags are present */
  24047. flag_leftjustify = flag_prefix = cThousand =
  24048. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  24049. done = 0;
  24050. do{
  24051. switch( c ){
  24052. case '-': flag_leftjustify = 1; break;
  24053. case '+': flag_prefix = '+'; break;
  24054. case ' ': flag_prefix = ' '; break;
  24055. case '#': flag_alternateform = 1; break;
  24056. case '!': flag_altform2 = 1; break;
  24057. case '0': flag_zeropad = 1; break;
  24058. case ',': cThousand = ','; break;
  24059. default: done = 1; break;
  24060. }
  24061. }while( !done && (c=(*++fmt))!=0 );
  24062. /* Get the field width */
  24063. if( c=='*' ){
  24064. if( bArgList ){
  24065. width = (int)getIntArg(pArgList);
  24066. }else{
  24067. width = va_arg(ap,int);
  24068. }
  24069. if( width<0 ){
  24070. flag_leftjustify = 1;
  24071. width = width >= -2147483647 ? -width : 0;
  24072. }
  24073. c = *++fmt;
  24074. }else{
  24075. unsigned wx = 0;
  24076. while( c>='0' && c<='9' ){
  24077. wx = wx*10 + c - '0';
  24078. c = *++fmt;
  24079. }
  24080. testcase( wx>0x7fffffff );
  24081. width = wx & 0x7fffffff;
  24082. }
  24083. assert( width>=0 );
  24084. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  24085. if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
  24086. width = SQLITE_PRINTF_PRECISION_LIMIT;
  24087. }
  24088. #endif
  24089. /* Get the precision */
  24090. if( c=='.' ){
  24091. c = *++fmt;
  24092. if( c=='*' ){
  24093. if( bArgList ){
  24094. precision = (int)getIntArg(pArgList);
  24095. }else{
  24096. precision = va_arg(ap,int);
  24097. }
  24098. c = *++fmt;
  24099. if( precision<0 ){
  24100. precision = precision >= -2147483647 ? -precision : -1;
  24101. }
  24102. }else{
  24103. unsigned px = 0;
  24104. while( c>='0' && c<='9' ){
  24105. px = px*10 + c - '0';
  24106. c = *++fmt;
  24107. }
  24108. testcase( px>0x7fffffff );
  24109. precision = px & 0x7fffffff;
  24110. }
  24111. }else{
  24112. precision = -1;
  24113. }
  24114. assert( precision>=(-1) );
  24115. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  24116. if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
  24117. precision = SQLITE_PRINTF_PRECISION_LIMIT;
  24118. }
  24119. #endif
  24120. /* Get the conversion type modifier */
  24121. if( c=='l' ){
  24122. flag_long = 1;
  24123. c = *++fmt;
  24124. if( c=='l' ){
  24125. flag_long = 2;
  24126. c = *++fmt;
  24127. }
  24128. }else{
  24129. flag_long = 0;
  24130. }
  24131. /* Fetch the info entry for the field */
  24132. infop = &fmtinfo[0];
  24133. xtype = etINVALID;
  24134. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  24135. if( c==fmtinfo[idx].fmttype ){
  24136. infop = &fmtinfo[idx];
  24137. xtype = infop->type;
  24138. break;
  24139. }
  24140. }
  24141. /*
  24142. ** At this point, variables are initialized as follows:
  24143. **
  24144. ** flag_alternateform TRUE if a '#' is present.
  24145. ** flag_altform2 TRUE if a '!' is present.
  24146. ** flag_prefix '+' or ' ' or zero
  24147. ** flag_leftjustify TRUE if a '-' is present or if the
  24148. ** field width was negative.
  24149. ** flag_zeropad TRUE if the width began with 0.
  24150. ** flag_long 1 for "l", 2 for "ll"
  24151. ** width The specified field width. This is
  24152. ** always non-negative. Zero is the default.
  24153. ** precision The specified precision. The default
  24154. ** is -1.
  24155. ** xtype The class of the conversion.
  24156. ** infop Pointer to the appropriate info struct.
  24157. */
  24158. switch( xtype ){
  24159. case etPOINTER:
  24160. flag_long = sizeof(char*)==sizeof(i64) ? 2 :
  24161. sizeof(char*)==sizeof(long int) ? 1 : 0;
  24162. /* Fall through into the next case */
  24163. case etORDINAL:
  24164. case etRADIX:
  24165. cThousand = 0;
  24166. /* Fall through into the next case */
  24167. case etDECIMAL:
  24168. if( infop->flags & FLAG_SIGNED ){
  24169. i64 v;
  24170. if( bArgList ){
  24171. v = getIntArg(pArgList);
  24172. }else if( flag_long ){
  24173. if( flag_long==2 ){
  24174. v = va_arg(ap,i64) ;
  24175. }else{
  24176. v = va_arg(ap,long int);
  24177. }
  24178. }else{
  24179. v = va_arg(ap,int);
  24180. }
  24181. if( v<0 ){
  24182. if( v==SMALLEST_INT64 ){
  24183. longvalue = ((u64)1)<<63;
  24184. }else{
  24185. longvalue = -v;
  24186. }
  24187. prefix = '-';
  24188. }else{
  24189. longvalue = v;
  24190. prefix = flag_prefix;
  24191. }
  24192. }else{
  24193. if( bArgList ){
  24194. longvalue = (u64)getIntArg(pArgList);
  24195. }else if( flag_long ){
  24196. if( flag_long==2 ){
  24197. longvalue = va_arg(ap,u64);
  24198. }else{
  24199. longvalue = va_arg(ap,unsigned long int);
  24200. }
  24201. }else{
  24202. longvalue = va_arg(ap,unsigned int);
  24203. }
  24204. prefix = 0;
  24205. }
  24206. if( longvalue==0 ) flag_alternateform = 0;
  24207. if( flag_zeropad && precision<width-(prefix!=0) ){
  24208. precision = width-(prefix!=0);
  24209. }
  24210. if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
  24211. nOut = etBUFSIZE;
  24212. zOut = buf;
  24213. }else{
  24214. u64 n = (u64)precision + 10 + precision/3;
  24215. zOut = zExtra = sqlite3Malloc( n );
  24216. if( zOut==0 ){
  24217. setStrAccumError(pAccum, STRACCUM_NOMEM);
  24218. return;
  24219. }
  24220. nOut = (int)n;
  24221. }
  24222. bufpt = &zOut[nOut-1];
  24223. if( xtype==etORDINAL ){
  24224. static const char zOrd[] = "thstndrd";
  24225. int x = (int)(longvalue % 10);
  24226. if( x>=4 || (longvalue/10)%10==1 ){
  24227. x = 0;
  24228. }
  24229. *(--bufpt) = zOrd[x*2+1];
  24230. *(--bufpt) = zOrd[x*2];
  24231. }
  24232. {
  24233. const char *cset = &aDigits[infop->charset];
  24234. u8 base = infop->base;
  24235. do{ /* Convert to ascii */
  24236. *(--bufpt) = cset[longvalue%base];
  24237. longvalue = longvalue/base;
  24238. }while( longvalue>0 );
  24239. }
  24240. length = (int)(&zOut[nOut-1]-bufpt);
  24241. while( precision>length ){
  24242. *(--bufpt) = '0'; /* Zero pad */
  24243. length++;
  24244. }
  24245. if( cThousand ){
  24246. int nn = (length - 1)/3; /* Number of "," to insert */
  24247. int ix = (length - 1)%3 + 1;
  24248. bufpt -= nn;
  24249. for(idx=0; nn>0; idx++){
  24250. bufpt[idx] = bufpt[idx+nn];
  24251. ix--;
  24252. if( ix==0 ){
  24253. bufpt[++idx] = cThousand;
  24254. nn--;
  24255. ix = 3;
  24256. }
  24257. }
  24258. }
  24259. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  24260. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  24261. const char *pre;
  24262. char x;
  24263. pre = &aPrefix[infop->prefix];
  24264. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  24265. }
  24266. length = (int)(&zOut[nOut-1]-bufpt);
  24267. break;
  24268. case etFLOAT:
  24269. case etEXP:
  24270. case etGENERIC:
  24271. if( bArgList ){
  24272. realvalue = getDoubleArg(pArgList);
  24273. }else{
  24274. realvalue = va_arg(ap,double);
  24275. }
  24276. #ifdef SQLITE_OMIT_FLOATING_POINT
  24277. length = 0;
  24278. #else
  24279. if( precision<0 ) precision = 6; /* Set default precision */
  24280. if( realvalue<0.0 ){
  24281. realvalue = -realvalue;
  24282. prefix = '-';
  24283. }else{
  24284. prefix = flag_prefix;
  24285. }
  24286. if( xtype==etGENERIC && precision>0 ) precision--;
  24287. testcase( precision>0xfff );
  24288. for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  24289. if( xtype==etFLOAT ) realvalue += rounder;
  24290. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  24291. exp = 0;
  24292. if( sqlite3IsNaN((double)realvalue) ){
  24293. bufpt = "NaN";
  24294. length = 3;
  24295. break;
  24296. }
  24297. if( realvalue>0.0 ){
  24298. LONGDOUBLE_TYPE scale = 1.0;
  24299. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  24300. while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
  24301. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  24302. realvalue /= scale;
  24303. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  24304. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  24305. if( exp>350 ){
  24306. bufpt = buf;
  24307. buf[0] = prefix;
  24308. memcpy(buf+(prefix!=0),"Inf",4);
  24309. length = 3+(prefix!=0);
  24310. break;
  24311. }
  24312. }
  24313. bufpt = buf;
  24314. /*
  24315. ** If the field type is etGENERIC, then convert to either etEXP
  24316. ** or etFLOAT, as appropriate.
  24317. */
  24318. if( xtype!=etFLOAT ){
  24319. realvalue += rounder;
  24320. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  24321. }
  24322. if( xtype==etGENERIC ){
  24323. flag_rtz = !flag_alternateform;
  24324. if( exp<-4 || exp>precision ){
  24325. xtype = etEXP;
  24326. }else{
  24327. precision = precision - exp;
  24328. xtype = etFLOAT;
  24329. }
  24330. }else{
  24331. flag_rtz = flag_altform2;
  24332. }
  24333. if( xtype==etEXP ){
  24334. e2 = 0;
  24335. }else{
  24336. e2 = exp;
  24337. }
  24338. if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
  24339. bufpt = zExtra
  24340. = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
  24341. if( bufpt==0 ){
  24342. setStrAccumError(pAccum, STRACCUM_NOMEM);
  24343. return;
  24344. }
  24345. }
  24346. zOut = bufpt;
  24347. nsd = 16 + flag_altform2*10;
  24348. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  24349. /* The sign in front of the number */
  24350. if( prefix ){
  24351. *(bufpt++) = prefix;
  24352. }
  24353. /* Digits prior to the decimal point */
  24354. if( e2<0 ){
  24355. *(bufpt++) = '0';
  24356. }else{
  24357. for(; e2>=0; e2--){
  24358. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  24359. }
  24360. }
  24361. /* The decimal point */
  24362. if( flag_dp ){
  24363. *(bufpt++) = '.';
  24364. }
  24365. /* "0" digits after the decimal point but before the first
  24366. ** significant digit of the number */
  24367. for(e2++; e2<0; precision--, e2++){
  24368. assert( precision>0 );
  24369. *(bufpt++) = '0';
  24370. }
  24371. /* Significant digits after the decimal point */
  24372. while( (precision--)>0 ){
  24373. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  24374. }
  24375. /* Remove trailing zeros and the "." if no digits follow the "." */
  24376. if( flag_rtz && flag_dp ){
  24377. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  24378. assert( bufpt>zOut );
  24379. if( bufpt[-1]=='.' ){
  24380. if( flag_altform2 ){
  24381. *(bufpt++) = '0';
  24382. }else{
  24383. *(--bufpt) = 0;
  24384. }
  24385. }
  24386. }
  24387. /* Add the "eNNN" suffix */
  24388. if( xtype==etEXP ){
  24389. *(bufpt++) = aDigits[infop->charset];
  24390. if( exp<0 ){
  24391. *(bufpt++) = '-'; exp = -exp;
  24392. }else{
  24393. *(bufpt++) = '+';
  24394. }
  24395. if( exp>=100 ){
  24396. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  24397. exp %= 100;
  24398. }
  24399. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  24400. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  24401. }
  24402. *bufpt = 0;
  24403. /* The converted number is in buf[] and zero terminated. Output it.
  24404. ** Note that the number is in the usual order, not reversed as with
  24405. ** integer conversions. */
  24406. length = (int)(bufpt-zOut);
  24407. bufpt = zOut;
  24408. /* Special case: Add leading zeros if the flag_zeropad flag is
  24409. ** set and we are not left justified */
  24410. if( flag_zeropad && !flag_leftjustify && length < width){
  24411. int i;
  24412. int nPad = width - length;
  24413. for(i=width; i>=nPad; i--){
  24414. bufpt[i] = bufpt[i-nPad];
  24415. }
  24416. i = prefix!=0;
  24417. while( nPad-- ) bufpt[i++] = '0';
  24418. length = width;
  24419. }
  24420. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  24421. break;
  24422. case etSIZE:
  24423. if( !bArgList ){
  24424. *(va_arg(ap,int*)) = pAccum->nChar;
  24425. }
  24426. length = width = 0;
  24427. break;
  24428. case etPERCENT:
  24429. buf[0] = '%';
  24430. bufpt = buf;
  24431. length = 1;
  24432. break;
  24433. case etCHARX:
  24434. if( bArgList ){
  24435. bufpt = getTextArg(pArgList);
  24436. c = bufpt ? bufpt[0] : 0;
  24437. }else{
  24438. c = va_arg(ap,int);
  24439. }
  24440. if( precision>1 ){
  24441. width -= precision-1;
  24442. if( width>1 && !flag_leftjustify ){
  24443. sqlite3AppendChar(pAccum, width-1, ' ');
  24444. width = 0;
  24445. }
  24446. sqlite3AppendChar(pAccum, precision-1, c);
  24447. }
  24448. length = 1;
  24449. buf[0] = c;
  24450. bufpt = buf;
  24451. break;
  24452. case etSTRING:
  24453. case etDYNSTRING:
  24454. if( bArgList ){
  24455. bufpt = getTextArg(pArgList);
  24456. xtype = etSTRING;
  24457. }else{
  24458. bufpt = va_arg(ap,char*);
  24459. }
  24460. if( bufpt==0 ){
  24461. bufpt = "";
  24462. }else if( xtype==etDYNSTRING ){
  24463. zExtra = bufpt;
  24464. }
  24465. if( precision>=0 ){
  24466. for(length=0; length<precision && bufpt[length]; length++){}
  24467. }else{
  24468. length = sqlite3Strlen30(bufpt);
  24469. }
  24470. break;
  24471. case etSQLESCAPE: /* Escape ' characters */
  24472. case etSQLESCAPE2: /* Escape ' and enclose in '...' */
  24473. case etSQLESCAPE3: { /* Escape " characters */
  24474. int i, j, k, n, isnull;
  24475. int needQuote;
  24476. char ch;
  24477. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  24478. char *escarg;
  24479. if( bArgList ){
  24480. escarg = getTextArg(pArgList);
  24481. }else{
  24482. escarg = va_arg(ap,char*);
  24483. }
  24484. isnull = escarg==0;
  24485. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  24486. k = precision;
  24487. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  24488. if( ch==q ) n++;
  24489. }
  24490. needQuote = !isnull && xtype==etSQLESCAPE2;
  24491. n += i + 3;
  24492. if( n>etBUFSIZE ){
  24493. bufpt = zExtra = sqlite3Malloc( n );
  24494. if( bufpt==0 ){
  24495. setStrAccumError(pAccum, STRACCUM_NOMEM);
  24496. return;
  24497. }
  24498. }else{
  24499. bufpt = buf;
  24500. }
  24501. j = 0;
  24502. if( needQuote ) bufpt[j++] = q;
  24503. k = i;
  24504. for(i=0; i<k; i++){
  24505. bufpt[j++] = ch = escarg[i];
  24506. if( ch==q ) bufpt[j++] = ch;
  24507. }
  24508. if( needQuote ) bufpt[j++] = q;
  24509. bufpt[j] = 0;
  24510. length = j;
  24511. /* The precision in %q and %Q means how many input characters to
  24512. ** consume, not the length of the output...
  24513. ** if( precision>=0 && precision<length ) length = precision; */
  24514. break;
  24515. }
  24516. case etTOKEN: {
  24517. Token *pToken;
  24518. if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
  24519. pToken = va_arg(ap, Token*);
  24520. assert( bArgList==0 );
  24521. if( pToken && pToken->n ){
  24522. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  24523. }
  24524. length = width = 0;
  24525. break;
  24526. }
  24527. case etSRCLIST: {
  24528. SrcList *pSrc;
  24529. int k;
  24530. struct SrcList_item *pItem;
  24531. if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
  24532. pSrc = va_arg(ap, SrcList*);
  24533. k = va_arg(ap, int);
  24534. pItem = &pSrc->a[k];
  24535. assert( bArgList==0 );
  24536. assert( k>=0 && k<pSrc->nSrc );
  24537. if( pItem->zDatabase ){
  24538. sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
  24539. sqlite3StrAccumAppend(pAccum, ".", 1);
  24540. }
  24541. sqlite3StrAccumAppendAll(pAccum, pItem->zName);
  24542. length = width = 0;
  24543. break;
  24544. }
  24545. default: {
  24546. assert( xtype==etINVALID );
  24547. return;
  24548. }
  24549. }/* End switch over the format type */
  24550. /*
  24551. ** The text of the conversion is pointed to by "bufpt" and is
  24552. ** "length" characters long. The field width is "width". Do
  24553. ** the output.
  24554. */
  24555. width -= length;
  24556. if( width>0 ){
  24557. if( !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  24558. sqlite3StrAccumAppend(pAccum, bufpt, length);
  24559. if( flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  24560. }else{
  24561. sqlite3StrAccumAppend(pAccum, bufpt, length);
  24562. }
  24563. if( zExtra ){
  24564. sqlite3DbFree(pAccum->db, zExtra);
  24565. zExtra = 0;
  24566. }
  24567. }/* End for loop over the format string */
  24568. } /* End of function */
  24569. /*
  24570. ** Enlarge the memory allocation on a StrAccum object so that it is
  24571. ** able to accept at least N more bytes of text.
  24572. **
  24573. ** Return the number of bytes of text that StrAccum is able to accept
  24574. ** after the attempted enlargement. The value returned might be zero.
  24575. */
  24576. static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
  24577. char *zNew;
  24578. assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
  24579. if( p->accError ){
  24580. testcase(p->accError==STRACCUM_TOOBIG);
  24581. testcase(p->accError==STRACCUM_NOMEM);
  24582. return 0;
  24583. }
  24584. if( p->mxAlloc==0 ){
  24585. N = p->nAlloc - p->nChar - 1;
  24586. setStrAccumError(p, STRACCUM_TOOBIG);
  24587. return N;
  24588. }else{
  24589. char *zOld = isMalloced(p) ? p->zText : 0;
  24590. i64 szNew = p->nChar;
  24591. assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
  24592. szNew += N + 1;
  24593. if( szNew+p->nChar<=p->mxAlloc ){
  24594. /* Force exponential buffer size growth as long as it does not overflow,
  24595. ** to avoid having to call this routine too often */
  24596. szNew += p->nChar;
  24597. }
  24598. if( szNew > p->mxAlloc ){
  24599. sqlite3StrAccumReset(p);
  24600. setStrAccumError(p, STRACCUM_TOOBIG);
  24601. return 0;
  24602. }else{
  24603. p->nAlloc = (int)szNew;
  24604. }
  24605. if( p->db ){
  24606. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  24607. }else{
  24608. zNew = sqlite3_realloc64(zOld, p->nAlloc);
  24609. }
  24610. if( zNew ){
  24611. assert( p->zText!=0 || p->nChar==0 );
  24612. if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  24613. p->zText = zNew;
  24614. p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
  24615. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  24616. }else{
  24617. sqlite3StrAccumReset(p);
  24618. setStrAccumError(p, STRACCUM_NOMEM);
  24619. return 0;
  24620. }
  24621. }
  24622. return N;
  24623. }
  24624. /*
  24625. ** Append N copies of character c to the given string buffer.
  24626. */
  24627. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
  24628. testcase( p->nChar + (i64)N > 0x7fffffff );
  24629. if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
  24630. return;
  24631. }
  24632. assert( (p->zText==p->zBase)==!isMalloced(p) );
  24633. while( (N--)>0 ) p->zText[p->nChar++] = c;
  24634. }
  24635. /*
  24636. ** The StrAccum "p" is not large enough to accept N new bytes of z[].
  24637. ** So enlarge if first, then do the append.
  24638. **
  24639. ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
  24640. ** work (enlarging the buffer) using tail recursion, so that the
  24641. ** sqlite3StrAccumAppend() routine can use fast calling semantics.
  24642. */
  24643. static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
  24644. N = sqlite3StrAccumEnlarge(p, N);
  24645. if( N>0 ){
  24646. memcpy(&p->zText[p->nChar], z, N);
  24647. p->nChar += N;
  24648. }
  24649. assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
  24650. }
  24651. /*
  24652. ** Append N bytes of text from z to the StrAccum object. Increase the
  24653. ** size of the memory allocation for StrAccum if necessary.
  24654. */
  24655. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  24656. assert( z!=0 || N==0 );
  24657. assert( p->zText!=0 || p->nChar==0 || p->accError );
  24658. assert( N>=0 );
  24659. assert( p->accError==0 || p->nAlloc==0 );
  24660. if( p->nChar+N >= p->nAlloc ){
  24661. enlargeAndAppend(p,z,N);
  24662. }else if( N ){
  24663. assert( p->zText );
  24664. p->nChar += N;
  24665. memcpy(&p->zText[p->nChar-N], z, N);
  24666. }
  24667. }
  24668. /*
  24669. ** Append the complete text of zero-terminated string z[] to the p string.
  24670. */
  24671. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
  24672. sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
  24673. }
  24674. /*
  24675. ** Finish off a string by making sure it is zero-terminated.
  24676. ** Return a pointer to the resulting string. Return a NULL
  24677. ** pointer if any kind of error was encountered.
  24678. */
  24679. static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
  24680. assert( p->mxAlloc>0 && !isMalloced(p) );
  24681. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  24682. if( p->zText ){
  24683. memcpy(p->zText, p->zBase, p->nChar+1);
  24684. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  24685. }else{
  24686. setStrAccumError(p, STRACCUM_NOMEM);
  24687. }
  24688. return p->zText;
  24689. }
  24690. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  24691. if( p->zText ){
  24692. assert( (p->zText==p->zBase)==!isMalloced(p) );
  24693. p->zText[p->nChar] = 0;
  24694. if( p->mxAlloc>0 && !isMalloced(p) ){
  24695. return strAccumFinishRealloc(p);
  24696. }
  24697. }
  24698. return p->zText;
  24699. }
  24700. /*
  24701. ** Reset an StrAccum string. Reclaim all malloced memory.
  24702. */
  24703. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  24704. assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
  24705. if( isMalloced(p) ){
  24706. sqlite3DbFree(p->db, p->zText);
  24707. p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
  24708. }
  24709. p->zText = 0;
  24710. }
  24711. /*
  24712. ** Initialize a string accumulator.
  24713. **
  24714. ** p: The accumulator to be initialized.
  24715. ** db: Pointer to a database connection. May be NULL. Lookaside
  24716. ** memory is used if not NULL. db->mallocFailed is set appropriately
  24717. ** when not NULL.
  24718. ** zBase: An initial buffer. May be NULL in which case the initial buffer
  24719. ** is malloced.
  24720. ** n: Size of zBase in bytes. If total space requirements never exceed
  24721. ** n then no memory allocations ever occur.
  24722. ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
  24723. ** allocations will ever occur.
  24724. */
  24725. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
  24726. p->zText = p->zBase = zBase;
  24727. p->db = db;
  24728. p->nChar = 0;
  24729. p->nAlloc = n;
  24730. p->mxAlloc = mx;
  24731. p->accError = 0;
  24732. p->printfFlags = 0;
  24733. }
  24734. /*
  24735. ** Print into memory obtained from sqliteMalloc(). Use the internal
  24736. ** %-conversion extensions.
  24737. */
  24738. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  24739. char *z;
  24740. char zBase[SQLITE_PRINT_BUF_SIZE];
  24741. StrAccum acc;
  24742. assert( db!=0 );
  24743. sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
  24744. db->aLimit[SQLITE_LIMIT_LENGTH]);
  24745. acc.printfFlags = SQLITE_PRINTF_INTERNAL;
  24746. sqlite3VXPrintf(&acc, zFormat, ap);
  24747. z = sqlite3StrAccumFinish(&acc);
  24748. if( acc.accError==STRACCUM_NOMEM ){
  24749. sqlite3OomFault(db);
  24750. }
  24751. return z;
  24752. }
  24753. /*
  24754. ** Print into memory obtained from sqliteMalloc(). Use the internal
  24755. ** %-conversion extensions.
  24756. */
  24757. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  24758. va_list ap;
  24759. char *z;
  24760. va_start(ap, zFormat);
  24761. z = sqlite3VMPrintf(db, zFormat, ap);
  24762. va_end(ap);
  24763. return z;
  24764. }
  24765. /*
  24766. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  24767. ** %-conversion extensions.
  24768. */
  24769. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  24770. char *z;
  24771. char zBase[SQLITE_PRINT_BUF_SIZE];
  24772. StrAccum acc;
  24773. #ifdef SQLITE_ENABLE_API_ARMOR
  24774. if( zFormat==0 ){
  24775. (void)SQLITE_MISUSE_BKPT;
  24776. return 0;
  24777. }
  24778. #endif
  24779. #ifndef SQLITE_OMIT_AUTOINIT
  24780. if( sqlite3_initialize() ) return 0;
  24781. #endif
  24782. sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  24783. sqlite3VXPrintf(&acc, zFormat, ap);
  24784. z = sqlite3StrAccumFinish(&acc);
  24785. return z;
  24786. }
  24787. /*
  24788. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  24789. ** %-conversion extensions.
  24790. */
  24791. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  24792. va_list ap;
  24793. char *z;
  24794. #ifndef SQLITE_OMIT_AUTOINIT
  24795. if( sqlite3_initialize() ) return 0;
  24796. #endif
  24797. va_start(ap, zFormat);
  24798. z = sqlite3_vmprintf(zFormat, ap);
  24799. va_end(ap);
  24800. return z;
  24801. }
  24802. /*
  24803. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  24804. ** current locale settings. This is important for SQLite because we
  24805. ** are not able to use a "," as the decimal point in place of "." as
  24806. ** specified by some locales.
  24807. **
  24808. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  24809. ** from the snprintf() standard. Unfortunately, it is too late to change
  24810. ** this without breaking compatibility, so we just have to live with the
  24811. ** mistake.
  24812. **
  24813. ** sqlite3_vsnprintf() is the varargs version.
  24814. */
  24815. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  24816. StrAccum acc;
  24817. if( n<=0 ) return zBuf;
  24818. #ifdef SQLITE_ENABLE_API_ARMOR
  24819. if( zBuf==0 || zFormat==0 ) {
  24820. (void)SQLITE_MISUSE_BKPT;
  24821. if( zBuf ) zBuf[0] = 0;
  24822. return zBuf;
  24823. }
  24824. #endif
  24825. sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
  24826. sqlite3VXPrintf(&acc, zFormat, ap);
  24827. zBuf[acc.nChar] = 0;
  24828. return zBuf;
  24829. }
  24830. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  24831. char *z;
  24832. va_list ap;
  24833. va_start(ap,zFormat);
  24834. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  24835. va_end(ap);
  24836. return z;
  24837. }
  24838. /*
  24839. ** This is the routine that actually formats the sqlite3_log() message.
  24840. ** We house it in a separate routine from sqlite3_log() to avoid using
  24841. ** stack space on small-stack systems when logging is disabled.
  24842. **
  24843. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  24844. ** allocate memory because it might be called while the memory allocator
  24845. ** mutex is held.
  24846. **
  24847. ** sqlite3VXPrintf() might ask for *temporary* memory allocations for
  24848. ** certain format characters (%q) or for very large precisions or widths.
  24849. ** Care must be taken that any sqlite3_log() calls that occur while the
  24850. ** memory mutex is held do not use these mechanisms.
  24851. */
  24852. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  24853. StrAccum acc; /* String accumulator */
  24854. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  24855. sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
  24856. sqlite3VXPrintf(&acc, zFormat, ap);
  24857. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  24858. sqlite3StrAccumFinish(&acc));
  24859. }
  24860. /*
  24861. ** Format and write a message to the log if logging is enabled.
  24862. */
  24863. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  24864. va_list ap; /* Vararg list */
  24865. if( sqlite3GlobalConfig.xLog ){
  24866. va_start(ap, zFormat);
  24867. renderLogMsg(iErrCode, zFormat, ap);
  24868. va_end(ap);
  24869. }
  24870. }
  24871. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  24872. /*
  24873. ** A version of printf() that understands %lld. Used for debugging.
  24874. ** The printf() built into some versions of windows does not understand %lld
  24875. ** and segfaults if you give it a long long int.
  24876. */
  24877. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  24878. va_list ap;
  24879. StrAccum acc;
  24880. char zBuf[500];
  24881. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  24882. va_start(ap,zFormat);
  24883. sqlite3VXPrintf(&acc, zFormat, ap);
  24884. va_end(ap);
  24885. sqlite3StrAccumFinish(&acc);
  24886. fprintf(stdout,"%s", zBuf);
  24887. fflush(stdout);
  24888. }
  24889. #endif
  24890. /*
  24891. ** variable-argument wrapper around sqlite3VXPrintf(). The bFlags argument
  24892. ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
  24893. */
  24894. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
  24895. va_list ap;
  24896. va_start(ap,zFormat);
  24897. sqlite3VXPrintf(p, zFormat, ap);
  24898. va_end(ap);
  24899. }
  24900. /************** End of printf.c **********************************************/
  24901. /************** Begin file treeview.c ****************************************/
  24902. /*
  24903. ** 2015-06-08
  24904. **
  24905. ** The author disclaims copyright to this source code. In place of
  24906. ** a legal notice, here is a blessing:
  24907. **
  24908. ** May you do good and not evil.
  24909. ** May you find forgiveness for yourself and forgive others.
  24910. ** May you share freely, never taking more than you give.
  24911. **
  24912. *************************************************************************
  24913. **
  24914. ** This file contains C code to implement the TreeView debugging routines.
  24915. ** These routines print a parse tree to standard output for debugging and
  24916. ** analysis.
  24917. **
  24918. ** The interfaces in this file is only available when compiling
  24919. ** with SQLITE_DEBUG.
  24920. */
  24921. /* #include "sqliteInt.h" */
  24922. #ifdef SQLITE_DEBUG
  24923. /*
  24924. ** Add a new subitem to the tree. The moreToFollow flag indicates that this
  24925. ** is not the last item in the tree.
  24926. */
  24927. static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
  24928. if( p==0 ){
  24929. p = sqlite3_malloc64( sizeof(*p) );
  24930. if( p==0 ) return 0;
  24931. memset(p, 0, sizeof(*p));
  24932. }else{
  24933. p->iLevel++;
  24934. }
  24935. assert( moreToFollow==0 || moreToFollow==1 );
  24936. if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
  24937. return p;
  24938. }
  24939. /*
  24940. ** Finished with one layer of the tree
  24941. */
  24942. static void sqlite3TreeViewPop(TreeView *p){
  24943. if( p==0 ) return;
  24944. p->iLevel--;
  24945. if( p->iLevel<0 ) sqlite3_free(p);
  24946. }
  24947. /*
  24948. ** Generate a single line of output for the tree, with a prefix that contains
  24949. ** all the appropriate tree lines
  24950. */
  24951. static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
  24952. va_list ap;
  24953. int i;
  24954. StrAccum acc;
  24955. char zBuf[500];
  24956. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  24957. if( p ){
  24958. for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
  24959. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
  24960. }
  24961. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
  24962. }
  24963. va_start(ap, zFormat);
  24964. sqlite3VXPrintf(&acc, zFormat, ap);
  24965. va_end(ap);
  24966. assert( acc.nChar>0 );
  24967. if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
  24968. sqlite3StrAccumFinish(&acc);
  24969. fprintf(stdout,"%s", zBuf);
  24970. fflush(stdout);
  24971. }
  24972. /*
  24973. ** Shorthand for starting a new tree item that consists of a single label
  24974. */
  24975. static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
  24976. p = sqlite3TreeViewPush(p, moreFollows);
  24977. sqlite3TreeViewLine(p, "%s", zLabel);
  24978. }
  24979. /*
  24980. ** Generate a human-readable description of a WITH clause.
  24981. */
  24982. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
  24983. int i;
  24984. if( pWith==0 ) return;
  24985. if( pWith->nCte==0 ) return;
  24986. if( pWith->pOuter ){
  24987. sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
  24988. }else{
  24989. sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
  24990. }
  24991. if( pWith->nCte>0 ){
  24992. pView = sqlite3TreeViewPush(pView, 1);
  24993. for(i=0; i<pWith->nCte; i++){
  24994. StrAccum x;
  24995. char zLine[1000];
  24996. const struct Cte *pCte = &pWith->a[i];
  24997. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  24998. sqlite3XPrintf(&x, "%s", pCte->zName);
  24999. if( pCte->pCols && pCte->pCols->nExpr>0 ){
  25000. char cSep = '(';
  25001. int j;
  25002. for(j=0; j<pCte->pCols->nExpr; j++){
  25003. sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
  25004. cSep = ',';
  25005. }
  25006. sqlite3XPrintf(&x, ")");
  25007. }
  25008. sqlite3XPrintf(&x, " AS");
  25009. sqlite3StrAccumFinish(&x);
  25010. sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
  25011. sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
  25012. sqlite3TreeViewPop(pView);
  25013. }
  25014. sqlite3TreeViewPop(pView);
  25015. }
  25016. }
  25017. /*
  25018. ** Generate a human-readable description of a Select object.
  25019. */
  25020. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
  25021. int n = 0;
  25022. int cnt = 0;
  25023. if( p==0 ){
  25024. sqlite3TreeViewLine(pView, "nil-SELECT");
  25025. return;
  25026. }
  25027. pView = sqlite3TreeViewPush(pView, moreToFollow);
  25028. if( p->pWith ){
  25029. sqlite3TreeViewWith(pView, p->pWith, 1);
  25030. cnt = 1;
  25031. sqlite3TreeViewPush(pView, 1);
  25032. }
  25033. do{
  25034. sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
  25035. ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
  25036. ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
  25037. (int)p->nSelectRow
  25038. );
  25039. if( cnt++ ) sqlite3TreeViewPop(pView);
  25040. if( p->pPrior ){
  25041. n = 1000;
  25042. }else{
  25043. n = 0;
  25044. if( p->pSrc && p->pSrc->nSrc ) n++;
  25045. if( p->pWhere ) n++;
  25046. if( p->pGroupBy ) n++;
  25047. if( p->pHaving ) n++;
  25048. if( p->pOrderBy ) n++;
  25049. if( p->pLimit ) n++;
  25050. if( p->pOffset ) n++;
  25051. }
  25052. sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
  25053. if( p->pSrc && p->pSrc->nSrc ){
  25054. int i;
  25055. pView = sqlite3TreeViewPush(pView, (n--)>0);
  25056. sqlite3TreeViewLine(pView, "FROM");
  25057. for(i=0; i<p->pSrc->nSrc; i++){
  25058. struct SrcList_item *pItem = &p->pSrc->a[i];
  25059. StrAccum x;
  25060. char zLine[100];
  25061. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  25062. sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor);
  25063. if( pItem->zDatabase ){
  25064. sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
  25065. }else if( pItem->zName ){
  25066. sqlite3XPrintf(&x, " %s", pItem->zName);
  25067. }
  25068. if( pItem->pTab ){
  25069. sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName);
  25070. }
  25071. if( pItem->zAlias ){
  25072. sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias);
  25073. }
  25074. if( pItem->fg.jointype & JT_LEFT ){
  25075. sqlite3XPrintf(&x, " LEFT-JOIN");
  25076. }
  25077. sqlite3StrAccumFinish(&x);
  25078. sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
  25079. if( pItem->pSelect ){
  25080. sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
  25081. }
  25082. if( pItem->fg.isTabFunc ){
  25083. sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
  25084. }
  25085. sqlite3TreeViewPop(pView);
  25086. }
  25087. sqlite3TreeViewPop(pView);
  25088. }
  25089. if( p->pWhere ){
  25090. sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
  25091. sqlite3TreeViewExpr(pView, p->pWhere, 0);
  25092. sqlite3TreeViewPop(pView);
  25093. }
  25094. if( p->pGroupBy ){
  25095. sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
  25096. }
  25097. if( p->pHaving ){
  25098. sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
  25099. sqlite3TreeViewExpr(pView, p->pHaving, 0);
  25100. sqlite3TreeViewPop(pView);
  25101. }
  25102. if( p->pOrderBy ){
  25103. sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
  25104. }
  25105. if( p->pLimit ){
  25106. sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
  25107. sqlite3TreeViewExpr(pView, p->pLimit, 0);
  25108. sqlite3TreeViewPop(pView);
  25109. }
  25110. if( p->pOffset ){
  25111. sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
  25112. sqlite3TreeViewExpr(pView, p->pOffset, 0);
  25113. sqlite3TreeViewPop(pView);
  25114. }
  25115. if( p->pPrior ){
  25116. const char *zOp = "UNION";
  25117. switch( p->op ){
  25118. case TK_ALL: zOp = "UNION ALL"; break;
  25119. case TK_INTERSECT: zOp = "INTERSECT"; break;
  25120. case TK_EXCEPT: zOp = "EXCEPT"; break;
  25121. }
  25122. sqlite3TreeViewItem(pView, zOp, 1);
  25123. }
  25124. p = p->pPrior;
  25125. }while( p!=0 );
  25126. sqlite3TreeViewPop(pView);
  25127. }
  25128. /*
  25129. ** Generate a human-readable explanation of an expression tree.
  25130. */
  25131. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
  25132. const char *zBinOp = 0; /* Binary operator */
  25133. const char *zUniOp = 0; /* Unary operator */
  25134. char zFlgs[60];
  25135. pView = sqlite3TreeViewPush(pView, moreToFollow);
  25136. if( pExpr==0 ){
  25137. sqlite3TreeViewLine(pView, "nil");
  25138. sqlite3TreeViewPop(pView);
  25139. return;
  25140. }
  25141. if( pExpr->flags ){
  25142. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  25143. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x iRJT=%d",
  25144. pExpr->flags, pExpr->iRightJoinTable);
  25145. }else{
  25146. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags);
  25147. }
  25148. }else{
  25149. zFlgs[0] = 0;
  25150. }
  25151. switch( pExpr->op ){
  25152. case TK_AGG_COLUMN: {
  25153. sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
  25154. pExpr->iTable, pExpr->iColumn, zFlgs);
  25155. break;
  25156. }
  25157. case TK_COLUMN: {
  25158. if( pExpr->iTable<0 ){
  25159. /* This only happens when coding check constraints */
  25160. sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
  25161. }else{
  25162. sqlite3TreeViewLine(pView, "{%d:%d}%s",
  25163. pExpr->iTable, pExpr->iColumn, zFlgs);
  25164. }
  25165. break;
  25166. }
  25167. case TK_INTEGER: {
  25168. if( pExpr->flags & EP_IntValue ){
  25169. sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
  25170. }else{
  25171. sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
  25172. }
  25173. break;
  25174. }
  25175. #ifndef SQLITE_OMIT_FLOATING_POINT
  25176. case TK_FLOAT: {
  25177. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  25178. break;
  25179. }
  25180. #endif
  25181. case TK_STRING: {
  25182. sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
  25183. break;
  25184. }
  25185. case TK_NULL: {
  25186. sqlite3TreeViewLine(pView,"NULL");
  25187. break;
  25188. }
  25189. #ifndef SQLITE_OMIT_BLOB_LITERAL
  25190. case TK_BLOB: {
  25191. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  25192. break;
  25193. }
  25194. #endif
  25195. case TK_VARIABLE: {
  25196. sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
  25197. pExpr->u.zToken, pExpr->iColumn);
  25198. break;
  25199. }
  25200. case TK_REGISTER: {
  25201. sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
  25202. break;
  25203. }
  25204. case TK_ID: {
  25205. sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
  25206. break;
  25207. }
  25208. #ifndef SQLITE_OMIT_CAST
  25209. case TK_CAST: {
  25210. /* Expressions of the form: CAST(pLeft AS token) */
  25211. sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
  25212. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  25213. break;
  25214. }
  25215. #endif /* SQLITE_OMIT_CAST */
  25216. case TK_LT: zBinOp = "LT"; break;
  25217. case TK_LE: zBinOp = "LE"; break;
  25218. case TK_GT: zBinOp = "GT"; break;
  25219. case TK_GE: zBinOp = "GE"; break;
  25220. case TK_NE: zBinOp = "NE"; break;
  25221. case TK_EQ: zBinOp = "EQ"; break;
  25222. case TK_IS: zBinOp = "IS"; break;
  25223. case TK_ISNOT: zBinOp = "ISNOT"; break;
  25224. case TK_AND: zBinOp = "AND"; break;
  25225. case TK_OR: zBinOp = "OR"; break;
  25226. case TK_PLUS: zBinOp = "ADD"; break;
  25227. case TK_STAR: zBinOp = "MUL"; break;
  25228. case TK_MINUS: zBinOp = "SUB"; break;
  25229. case TK_REM: zBinOp = "REM"; break;
  25230. case TK_BITAND: zBinOp = "BITAND"; break;
  25231. case TK_BITOR: zBinOp = "BITOR"; break;
  25232. case TK_SLASH: zBinOp = "DIV"; break;
  25233. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  25234. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  25235. case TK_CONCAT: zBinOp = "CONCAT"; break;
  25236. case TK_DOT: zBinOp = "DOT"; break;
  25237. case TK_UMINUS: zUniOp = "UMINUS"; break;
  25238. case TK_UPLUS: zUniOp = "UPLUS"; break;
  25239. case TK_BITNOT: zUniOp = "BITNOT"; break;
  25240. case TK_NOT: zUniOp = "NOT"; break;
  25241. case TK_ISNULL: zUniOp = "ISNULL"; break;
  25242. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  25243. case TK_SPAN: {
  25244. sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
  25245. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  25246. break;
  25247. }
  25248. case TK_COLLATE: {
  25249. sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
  25250. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  25251. break;
  25252. }
  25253. case TK_AGG_FUNCTION:
  25254. case TK_FUNCTION: {
  25255. ExprList *pFarg; /* List of function arguments */
  25256. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  25257. pFarg = 0;
  25258. }else{
  25259. pFarg = pExpr->x.pList;
  25260. }
  25261. if( pExpr->op==TK_AGG_FUNCTION ){
  25262. sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
  25263. pExpr->op2, pExpr->u.zToken);
  25264. }else{
  25265. sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
  25266. }
  25267. if( pFarg ){
  25268. sqlite3TreeViewExprList(pView, pFarg, 0, 0);
  25269. }
  25270. break;
  25271. }
  25272. #ifndef SQLITE_OMIT_SUBQUERY
  25273. case TK_EXISTS: {
  25274. sqlite3TreeViewLine(pView, "EXISTS-expr");
  25275. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  25276. break;
  25277. }
  25278. case TK_SELECT: {
  25279. sqlite3TreeViewLine(pView, "SELECT-expr");
  25280. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  25281. break;
  25282. }
  25283. case TK_IN: {
  25284. sqlite3TreeViewLine(pView, "IN");
  25285. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  25286. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  25287. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  25288. }else{
  25289. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  25290. }
  25291. break;
  25292. }
  25293. #endif /* SQLITE_OMIT_SUBQUERY */
  25294. /*
  25295. ** x BETWEEN y AND z
  25296. **
  25297. ** This is equivalent to
  25298. **
  25299. ** x>=y AND x<=z
  25300. **
  25301. ** X is stored in pExpr->pLeft.
  25302. ** Y is stored in pExpr->pList->a[0].pExpr.
  25303. ** Z is stored in pExpr->pList->a[1].pExpr.
  25304. */
  25305. case TK_BETWEEN: {
  25306. Expr *pX = pExpr->pLeft;
  25307. Expr *pY = pExpr->x.pList->a[0].pExpr;
  25308. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  25309. sqlite3TreeViewLine(pView, "BETWEEN");
  25310. sqlite3TreeViewExpr(pView, pX, 1);
  25311. sqlite3TreeViewExpr(pView, pY, 1);
  25312. sqlite3TreeViewExpr(pView, pZ, 0);
  25313. break;
  25314. }
  25315. case TK_TRIGGER: {
  25316. /* If the opcode is TK_TRIGGER, then the expression is a reference
  25317. ** to a column in the new.* or old.* pseudo-tables available to
  25318. ** trigger programs. In this case Expr.iTable is set to 1 for the
  25319. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  25320. ** is set to the column of the pseudo-table to read, or to -1 to
  25321. ** read the rowid field.
  25322. */
  25323. sqlite3TreeViewLine(pView, "%s(%d)",
  25324. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  25325. break;
  25326. }
  25327. case TK_CASE: {
  25328. sqlite3TreeViewLine(pView, "CASE");
  25329. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  25330. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  25331. break;
  25332. }
  25333. #ifndef SQLITE_OMIT_TRIGGER
  25334. case TK_RAISE: {
  25335. const char *zType = "unk";
  25336. switch( pExpr->affinity ){
  25337. case OE_Rollback: zType = "rollback"; break;
  25338. case OE_Abort: zType = "abort"; break;
  25339. case OE_Fail: zType = "fail"; break;
  25340. case OE_Ignore: zType = "ignore"; break;
  25341. }
  25342. sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
  25343. break;
  25344. }
  25345. #endif
  25346. case TK_MATCH: {
  25347. sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
  25348. pExpr->iTable, pExpr->iColumn, zFlgs);
  25349. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  25350. break;
  25351. }
  25352. case TK_VECTOR: {
  25353. sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR");
  25354. break;
  25355. }
  25356. case TK_SELECT_COLUMN: {
  25357. sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
  25358. sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
  25359. break;
  25360. }
  25361. case TK_IF_NULL_ROW: {
  25362. sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
  25363. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  25364. break;
  25365. }
  25366. default: {
  25367. sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
  25368. break;
  25369. }
  25370. }
  25371. if( zBinOp ){
  25372. sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
  25373. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  25374. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  25375. }else if( zUniOp ){
  25376. sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
  25377. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  25378. }
  25379. sqlite3TreeViewPop(pView);
  25380. }
  25381. /*
  25382. ** Generate a human-readable explanation of an expression list.
  25383. */
  25384. SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
  25385. TreeView *pView,
  25386. const ExprList *pList,
  25387. const char *zLabel
  25388. ){
  25389. if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
  25390. if( pList==0 ){
  25391. sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
  25392. }else{
  25393. int i;
  25394. sqlite3TreeViewLine(pView, "%s", zLabel);
  25395. for(i=0; i<pList->nExpr; i++){
  25396. int j = pList->a[i].u.x.iOrderByCol;
  25397. if( j ){
  25398. sqlite3TreeViewPush(pView, 0);
  25399. sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
  25400. }
  25401. sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
  25402. if( j ) sqlite3TreeViewPop(pView);
  25403. }
  25404. }
  25405. }
  25406. SQLITE_PRIVATE void sqlite3TreeViewExprList(
  25407. TreeView *pView,
  25408. const ExprList *pList,
  25409. u8 moreToFollow,
  25410. const char *zLabel
  25411. ){
  25412. pView = sqlite3TreeViewPush(pView, moreToFollow);
  25413. sqlite3TreeViewBareExprList(pView, pList, zLabel);
  25414. sqlite3TreeViewPop(pView);
  25415. }
  25416. #endif /* SQLITE_DEBUG */
  25417. /************** End of treeview.c ********************************************/
  25418. /************** Begin file random.c ******************************************/
  25419. /*
  25420. ** 2001 September 15
  25421. **
  25422. ** The author disclaims copyright to this source code. In place of
  25423. ** a legal notice, here is a blessing:
  25424. **
  25425. ** May you do good and not evil.
  25426. ** May you find forgiveness for yourself and forgive others.
  25427. ** May you share freely, never taking more than you give.
  25428. **
  25429. *************************************************************************
  25430. ** This file contains code to implement a pseudo-random number
  25431. ** generator (PRNG) for SQLite.
  25432. **
  25433. ** Random numbers are used by some of the database backends in order
  25434. ** to generate random integer keys for tables or random filenames.
  25435. */
  25436. /* #include "sqliteInt.h" */
  25437. /* All threads share a single random number generator.
  25438. ** This structure is the current state of the generator.
  25439. */
  25440. static SQLITE_WSD struct sqlite3PrngType {
  25441. unsigned char isInit; /* True if initialized */
  25442. unsigned char i, j; /* State variables */
  25443. unsigned char s[256]; /* State variables */
  25444. } sqlite3Prng;
  25445. /*
  25446. ** Return N random bytes.
  25447. */
  25448. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  25449. unsigned char t;
  25450. unsigned char *zBuf = pBuf;
  25451. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  25452. ** state vector. If writable static data is unsupported on the target,
  25453. ** we have to locate the state vector at run-time. In the more common
  25454. ** case where writable static data is supported, wsdPrng can refer directly
  25455. ** to the "sqlite3Prng" state vector declared above.
  25456. */
  25457. #ifdef SQLITE_OMIT_WSD
  25458. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  25459. # define wsdPrng p[0]
  25460. #else
  25461. # define wsdPrng sqlite3Prng
  25462. #endif
  25463. #if SQLITE_THREADSAFE
  25464. sqlite3_mutex *mutex;
  25465. #endif
  25466. #ifndef SQLITE_OMIT_AUTOINIT
  25467. if( sqlite3_initialize() ) return;
  25468. #endif
  25469. #if SQLITE_THREADSAFE
  25470. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  25471. #endif
  25472. sqlite3_mutex_enter(mutex);
  25473. if( N<=0 || pBuf==0 ){
  25474. wsdPrng.isInit = 0;
  25475. sqlite3_mutex_leave(mutex);
  25476. return;
  25477. }
  25478. /* Initialize the state of the random number generator once,
  25479. ** the first time this routine is called. The seed value does
  25480. ** not need to contain a lot of randomness since we are not
  25481. ** trying to do secure encryption or anything like that...
  25482. **
  25483. ** Nothing in this file or anywhere else in SQLite does any kind of
  25484. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  25485. ** number generator) not as an encryption device.
  25486. */
  25487. if( !wsdPrng.isInit ){
  25488. int i;
  25489. char k[256];
  25490. wsdPrng.j = 0;
  25491. wsdPrng.i = 0;
  25492. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  25493. for(i=0; i<256; i++){
  25494. wsdPrng.s[i] = (u8)i;
  25495. }
  25496. for(i=0; i<256; i++){
  25497. wsdPrng.j += wsdPrng.s[i] + k[i];
  25498. t = wsdPrng.s[wsdPrng.j];
  25499. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  25500. wsdPrng.s[i] = t;
  25501. }
  25502. wsdPrng.isInit = 1;
  25503. }
  25504. assert( N>0 );
  25505. do{
  25506. wsdPrng.i++;
  25507. t = wsdPrng.s[wsdPrng.i];
  25508. wsdPrng.j += t;
  25509. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  25510. wsdPrng.s[wsdPrng.j] = t;
  25511. t += wsdPrng.s[wsdPrng.i];
  25512. *(zBuf++) = wsdPrng.s[t];
  25513. }while( --N );
  25514. sqlite3_mutex_leave(mutex);
  25515. }
  25516. #ifndef SQLITE_UNTESTABLE
  25517. /*
  25518. ** For testing purposes, we sometimes want to preserve the state of
  25519. ** PRNG and restore the PRNG to its saved state at a later time, or
  25520. ** to reset the PRNG to its initial state. These routines accomplish
  25521. ** those tasks.
  25522. **
  25523. ** The sqlite3_test_control() interface calls these routines to
  25524. ** control the PRNG.
  25525. */
  25526. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  25527. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  25528. memcpy(
  25529. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  25530. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  25531. sizeof(sqlite3Prng)
  25532. );
  25533. }
  25534. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  25535. memcpy(
  25536. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  25537. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  25538. sizeof(sqlite3Prng)
  25539. );
  25540. }
  25541. #endif /* SQLITE_UNTESTABLE */
  25542. /************** End of random.c **********************************************/
  25543. /************** Begin file threads.c *****************************************/
  25544. /*
  25545. ** 2012 July 21
  25546. **
  25547. ** The author disclaims copyright to this source code. In place of
  25548. ** a legal notice, here is a blessing:
  25549. **
  25550. ** May you do good and not evil.
  25551. ** May you find forgiveness for yourself and forgive others.
  25552. ** May you share freely, never taking more than you give.
  25553. **
  25554. ******************************************************************************
  25555. **
  25556. ** This file presents a simple cross-platform threading interface for
  25557. ** use internally by SQLite.
  25558. **
  25559. ** A "thread" can be created using sqlite3ThreadCreate(). This thread
  25560. ** runs independently of its creator until it is joined using
  25561. ** sqlite3ThreadJoin(), at which point it terminates.
  25562. **
  25563. ** Threads do not have to be real. It could be that the work of the
  25564. ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
  25565. ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
  25566. ** single threaded systems. Nothing in SQLite requires multiple threads.
  25567. ** This interface exists so that applications that want to take advantage
  25568. ** of multiple cores can do so, while also allowing applications to stay
  25569. ** single-threaded if desired.
  25570. */
  25571. /* #include "sqliteInt.h" */
  25572. #if SQLITE_OS_WIN
  25573. /* # include "os_win.h" */
  25574. #endif
  25575. #if SQLITE_MAX_WORKER_THREADS>0
  25576. /********************************* Unix Pthreads ****************************/
  25577. #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
  25578. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  25579. /* #include <pthread.h> */
  25580. /* A running thread */
  25581. struct SQLiteThread {
  25582. pthread_t tid; /* Thread ID */
  25583. int done; /* Set to true when thread finishes */
  25584. void *pOut; /* Result returned by the thread */
  25585. void *(*xTask)(void*); /* The thread routine */
  25586. void *pIn; /* Argument to the thread */
  25587. };
  25588. /* Create a new thread */
  25589. SQLITE_PRIVATE int sqlite3ThreadCreate(
  25590. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  25591. void *(*xTask)(void*), /* Routine to run in a separate thread */
  25592. void *pIn /* Argument passed into xTask() */
  25593. ){
  25594. SQLiteThread *p;
  25595. int rc;
  25596. assert( ppThread!=0 );
  25597. assert( xTask!=0 );
  25598. /* This routine is never used in single-threaded mode */
  25599. assert( sqlite3GlobalConfig.bCoreMutex!=0 );
  25600. *ppThread = 0;
  25601. p = sqlite3Malloc(sizeof(*p));
  25602. if( p==0 ) return SQLITE_NOMEM_BKPT;
  25603. memset(p, 0, sizeof(*p));
  25604. p->xTask = xTask;
  25605. p->pIn = pIn;
  25606. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  25607. ** function that returns SQLITE_ERROR when passed the argument 200, that
  25608. ** forces worker threads to run sequentially and deterministically
  25609. ** for testing purposes. */
  25610. if( sqlite3FaultSim(200) ){
  25611. rc = 1;
  25612. }else{
  25613. rc = pthread_create(&p->tid, 0, xTask, pIn);
  25614. }
  25615. if( rc ){
  25616. p->done = 1;
  25617. p->pOut = xTask(pIn);
  25618. }
  25619. *ppThread = p;
  25620. return SQLITE_OK;
  25621. }
  25622. /* Get the results of the thread */
  25623. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  25624. int rc;
  25625. assert( ppOut!=0 );
  25626. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  25627. if( p->done ){
  25628. *ppOut = p->pOut;
  25629. rc = SQLITE_OK;
  25630. }else{
  25631. rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
  25632. }
  25633. sqlite3_free(p);
  25634. return rc;
  25635. }
  25636. #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
  25637. /******************************** End Unix Pthreads *************************/
  25638. /********************************* Win32 Threads ****************************/
  25639. #if SQLITE_OS_WIN_THREADS
  25640. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  25641. #include <process.h>
  25642. /* A running thread */
  25643. struct SQLiteThread {
  25644. void *tid; /* The thread handle */
  25645. unsigned id; /* The thread identifier */
  25646. void *(*xTask)(void*); /* The routine to run as a thread */
  25647. void *pIn; /* Argument to xTask */
  25648. void *pResult; /* Result of xTask */
  25649. };
  25650. /* Thread procedure Win32 compatibility shim */
  25651. static unsigned __stdcall sqlite3ThreadProc(
  25652. void *pArg /* IN: Pointer to the SQLiteThread structure */
  25653. ){
  25654. SQLiteThread *p = (SQLiteThread *)pArg;
  25655. assert( p!=0 );
  25656. #if 0
  25657. /*
  25658. ** This assert appears to trigger spuriously on certain
  25659. ** versions of Windows, possibly due to _beginthreadex()
  25660. ** and/or CreateThread() not fully setting their thread
  25661. ** ID parameter before starting the thread.
  25662. */
  25663. assert( p->id==GetCurrentThreadId() );
  25664. #endif
  25665. assert( p->xTask!=0 );
  25666. p->pResult = p->xTask(p->pIn);
  25667. _endthreadex(0);
  25668. return 0; /* NOT REACHED */
  25669. }
  25670. /* Create a new thread */
  25671. SQLITE_PRIVATE int sqlite3ThreadCreate(
  25672. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  25673. void *(*xTask)(void*), /* Routine to run in a separate thread */
  25674. void *pIn /* Argument passed into xTask() */
  25675. ){
  25676. SQLiteThread *p;
  25677. assert( ppThread!=0 );
  25678. assert( xTask!=0 );
  25679. *ppThread = 0;
  25680. p = sqlite3Malloc(sizeof(*p));
  25681. if( p==0 ) return SQLITE_NOMEM_BKPT;
  25682. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  25683. ** function that returns SQLITE_ERROR when passed the argument 200, that
  25684. ** forces worker threads to run sequentially and deterministically
  25685. ** (via the sqlite3FaultSim() term of the conditional) for testing
  25686. ** purposes. */
  25687. if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
  25688. memset(p, 0, sizeof(*p));
  25689. }else{
  25690. p->xTask = xTask;
  25691. p->pIn = pIn;
  25692. p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
  25693. if( p->tid==0 ){
  25694. memset(p, 0, sizeof(*p));
  25695. }
  25696. }
  25697. if( p->xTask==0 ){
  25698. p->id = GetCurrentThreadId();
  25699. p->pResult = xTask(pIn);
  25700. }
  25701. *ppThread = p;
  25702. return SQLITE_OK;
  25703. }
  25704. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
  25705. /* Get the results of the thread */
  25706. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  25707. DWORD rc;
  25708. BOOL bRc;
  25709. assert( ppOut!=0 );
  25710. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  25711. if( p->xTask==0 ){
  25712. /* assert( p->id==GetCurrentThreadId() ); */
  25713. rc = WAIT_OBJECT_0;
  25714. assert( p->tid==0 );
  25715. }else{
  25716. assert( p->id!=0 && p->id!=GetCurrentThreadId() );
  25717. rc = sqlite3Win32Wait((HANDLE)p->tid);
  25718. assert( rc!=WAIT_IO_COMPLETION );
  25719. bRc = CloseHandle((HANDLE)p->tid);
  25720. assert( bRc );
  25721. }
  25722. if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
  25723. sqlite3_free(p);
  25724. return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
  25725. }
  25726. #endif /* SQLITE_OS_WIN_THREADS */
  25727. /******************************** End Win32 Threads *************************/
  25728. /********************************* Single-Threaded **************************/
  25729. #ifndef SQLITE_THREADS_IMPLEMENTED
  25730. /*
  25731. ** This implementation does not actually create a new thread. It does the
  25732. ** work of the thread in the main thread, when either the thread is created
  25733. ** or when it is joined
  25734. */
  25735. /* A running thread */
  25736. struct SQLiteThread {
  25737. void *(*xTask)(void*); /* The routine to run as a thread */
  25738. void *pIn; /* Argument to xTask */
  25739. void *pResult; /* Result of xTask */
  25740. };
  25741. /* Create a new thread */
  25742. SQLITE_PRIVATE int sqlite3ThreadCreate(
  25743. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  25744. void *(*xTask)(void*), /* Routine to run in a separate thread */
  25745. void *pIn /* Argument passed into xTask() */
  25746. ){
  25747. SQLiteThread *p;
  25748. assert( ppThread!=0 );
  25749. assert( xTask!=0 );
  25750. *ppThread = 0;
  25751. p = sqlite3Malloc(sizeof(*p));
  25752. if( p==0 ) return SQLITE_NOMEM_BKPT;
  25753. if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
  25754. p->xTask = xTask;
  25755. p->pIn = pIn;
  25756. }else{
  25757. p->xTask = 0;
  25758. p->pResult = xTask(pIn);
  25759. }
  25760. *ppThread = p;
  25761. return SQLITE_OK;
  25762. }
  25763. /* Get the results of the thread */
  25764. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  25765. assert( ppOut!=0 );
  25766. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  25767. if( p->xTask ){
  25768. *ppOut = p->xTask(p->pIn);
  25769. }else{
  25770. *ppOut = p->pResult;
  25771. }
  25772. sqlite3_free(p);
  25773. #if defined(SQLITE_TEST)
  25774. {
  25775. void *pTstAlloc = sqlite3Malloc(10);
  25776. if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
  25777. sqlite3_free(pTstAlloc);
  25778. }
  25779. #endif
  25780. return SQLITE_OK;
  25781. }
  25782. #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
  25783. /****************************** End Single-Threaded *************************/
  25784. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  25785. /************** End of threads.c *********************************************/
  25786. /************** Begin file utf.c *********************************************/
  25787. /*
  25788. ** 2004 April 13
  25789. **
  25790. ** The author disclaims copyright to this source code. In place of
  25791. ** a legal notice, here is a blessing:
  25792. **
  25793. ** May you do good and not evil.
  25794. ** May you find forgiveness for yourself and forgive others.
  25795. ** May you share freely, never taking more than you give.
  25796. **
  25797. *************************************************************************
  25798. ** This file contains routines used to translate between UTF-8,
  25799. ** UTF-16, UTF-16BE, and UTF-16LE.
  25800. **
  25801. ** Notes on UTF-8:
  25802. **
  25803. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  25804. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  25805. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  25806. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  25807. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  25808. **
  25809. **
  25810. ** Notes on UTF-16: (with wwww+1==uuuuu)
  25811. **
  25812. ** Word-0 Word-1 Value
  25813. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  25814. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  25815. **
  25816. **
  25817. ** BOM or Byte Order Mark:
  25818. ** 0xff 0xfe little-endian utf-16 follows
  25819. ** 0xfe 0xff big-endian utf-16 follows
  25820. **
  25821. */
  25822. /* #include "sqliteInt.h" */
  25823. /* #include <assert.h> */
  25824. /* #include "vdbeInt.h" */
  25825. #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
  25826. /*
  25827. ** The following constant value is used by the SQLITE_BIGENDIAN and
  25828. ** SQLITE_LITTLEENDIAN macros.
  25829. */
  25830. SQLITE_PRIVATE const int sqlite3one = 1;
  25831. #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
  25832. /*
  25833. ** This lookup table is used to help decode the first byte of
  25834. ** a multi-byte UTF8 character.
  25835. */
  25836. static const unsigned char sqlite3Utf8Trans1[] = {
  25837. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  25838. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  25839. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  25840. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  25841. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  25842. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  25843. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  25844. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  25845. };
  25846. #define WRITE_UTF8(zOut, c) { \
  25847. if( c<0x00080 ){ \
  25848. *zOut++ = (u8)(c&0xFF); \
  25849. } \
  25850. else if( c<0x00800 ){ \
  25851. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  25852. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  25853. } \
  25854. else if( c<0x10000 ){ \
  25855. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  25856. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  25857. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  25858. }else{ \
  25859. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  25860. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  25861. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  25862. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  25863. } \
  25864. }
  25865. #define WRITE_UTF16LE(zOut, c) { \
  25866. if( c<=0xFFFF ){ \
  25867. *zOut++ = (u8)(c&0x00FF); \
  25868. *zOut++ = (u8)((c>>8)&0x00FF); \
  25869. }else{ \
  25870. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  25871. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  25872. *zOut++ = (u8)(c&0x00FF); \
  25873. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  25874. } \
  25875. }
  25876. #define WRITE_UTF16BE(zOut, c) { \
  25877. if( c<=0xFFFF ){ \
  25878. *zOut++ = (u8)((c>>8)&0x00FF); \
  25879. *zOut++ = (u8)(c&0x00FF); \
  25880. }else{ \
  25881. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  25882. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  25883. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  25884. *zOut++ = (u8)(c&0x00FF); \
  25885. } \
  25886. }
  25887. #define READ_UTF16LE(zIn, TERM, c){ \
  25888. c = (*zIn++); \
  25889. c += ((*zIn++)<<8); \
  25890. if( c>=0xD800 && c<0xE000 && TERM ){ \
  25891. int c2 = (*zIn++); \
  25892. c2 += ((*zIn++)<<8); \
  25893. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  25894. } \
  25895. }
  25896. #define READ_UTF16BE(zIn, TERM, c){ \
  25897. c = ((*zIn++)<<8); \
  25898. c += (*zIn++); \
  25899. if( c>=0xD800 && c<0xE000 && TERM ){ \
  25900. int c2 = ((*zIn++)<<8); \
  25901. c2 += (*zIn++); \
  25902. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  25903. } \
  25904. }
  25905. /*
  25906. ** Translate a single UTF-8 character. Return the unicode value.
  25907. **
  25908. ** During translation, assume that the byte that zTerm points
  25909. ** is a 0x00.
  25910. **
  25911. ** Write a pointer to the next unread byte back into *pzNext.
  25912. **
  25913. ** Notes On Invalid UTF-8:
  25914. **
  25915. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  25916. ** be encoded as a multi-byte character. Any multi-byte character that
  25917. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  25918. **
  25919. ** * This routine never allows a UTF16 surrogate value to be encoded.
  25920. ** If a multi-byte character attempts to encode a value between
  25921. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  25922. **
  25923. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  25924. ** byte of a character are interpreted as single-byte characters
  25925. ** and rendered as themselves even though they are technically
  25926. ** invalid characters.
  25927. **
  25928. ** * This routine accepts over-length UTF8 encodings
  25929. ** for unicode values 0x80 and greater. It does not change over-length
  25930. ** encodings to 0xfffd as some systems recommend.
  25931. */
  25932. #define READ_UTF8(zIn, zTerm, c) \
  25933. c = *(zIn++); \
  25934. if( c>=0xc0 ){ \
  25935. c = sqlite3Utf8Trans1[c-0xc0]; \
  25936. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  25937. c = (c<<6) + (0x3f & *(zIn++)); \
  25938. } \
  25939. if( c<0x80 \
  25940. || (c&0xFFFFF800)==0xD800 \
  25941. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  25942. }
  25943. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  25944. const unsigned char **pz /* Pointer to string from which to read char */
  25945. ){
  25946. unsigned int c;
  25947. /* Same as READ_UTF8() above but without the zTerm parameter.
  25948. ** For this routine, we assume the UTF8 string is always zero-terminated.
  25949. */
  25950. c = *((*pz)++);
  25951. if( c>=0xc0 ){
  25952. c = sqlite3Utf8Trans1[c-0xc0];
  25953. while( (*(*pz) & 0xc0)==0x80 ){
  25954. c = (c<<6) + (0x3f & *((*pz)++));
  25955. }
  25956. if( c<0x80
  25957. || (c&0xFFFFF800)==0xD800
  25958. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  25959. }
  25960. return c;
  25961. }
  25962. /*
  25963. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  25964. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  25965. */
  25966. /* #define TRANSLATE_TRACE 1 */
  25967. #ifndef SQLITE_OMIT_UTF16
  25968. /*
  25969. ** This routine transforms the internal text encoding used by pMem to
  25970. ** desiredEnc. It is an error if the string is already of the desired
  25971. ** encoding, or if *pMem does not contain a string value.
  25972. */
  25973. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  25974. int len; /* Maximum length of output string in bytes */
  25975. unsigned char *zOut; /* Output buffer */
  25976. unsigned char *zIn; /* Input iterator */
  25977. unsigned char *zTerm; /* End of input */
  25978. unsigned char *z; /* Output iterator */
  25979. unsigned int c;
  25980. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  25981. assert( pMem->flags&MEM_Str );
  25982. assert( pMem->enc!=desiredEnc );
  25983. assert( pMem->enc!=0 );
  25984. assert( pMem->n>=0 );
  25985. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  25986. {
  25987. char zBuf[100];
  25988. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  25989. fprintf(stderr, "INPUT: %s\n", zBuf);
  25990. }
  25991. #endif
  25992. /* If the translation is between UTF-16 little and big endian, then
  25993. ** all that is required is to swap the byte order. This case is handled
  25994. ** differently from the others.
  25995. */
  25996. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  25997. u8 temp;
  25998. int rc;
  25999. rc = sqlite3VdbeMemMakeWriteable(pMem);
  26000. if( rc!=SQLITE_OK ){
  26001. assert( rc==SQLITE_NOMEM );
  26002. return SQLITE_NOMEM_BKPT;
  26003. }
  26004. zIn = (u8*)pMem->z;
  26005. zTerm = &zIn[pMem->n&~1];
  26006. while( zIn<zTerm ){
  26007. temp = *zIn;
  26008. *zIn = *(zIn+1);
  26009. zIn++;
  26010. *zIn++ = temp;
  26011. }
  26012. pMem->enc = desiredEnc;
  26013. goto translate_out;
  26014. }
  26015. /* Set len to the maximum number of bytes required in the output buffer. */
  26016. if( desiredEnc==SQLITE_UTF8 ){
  26017. /* When converting from UTF-16, the maximum growth results from
  26018. ** translating a 2-byte character to a 4-byte UTF-8 character.
  26019. ** A single byte is required for the output string
  26020. ** nul-terminator.
  26021. */
  26022. pMem->n &= ~1;
  26023. len = pMem->n * 2 + 1;
  26024. }else{
  26025. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  26026. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  26027. ** character. Two bytes are required in the output buffer for the
  26028. ** nul-terminator.
  26029. */
  26030. len = pMem->n * 2 + 2;
  26031. }
  26032. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  26033. ** byte past the end.
  26034. **
  26035. ** Variable zOut is set to point at the output buffer, space obtained
  26036. ** from sqlite3_malloc().
  26037. */
  26038. zIn = (u8*)pMem->z;
  26039. zTerm = &zIn[pMem->n];
  26040. zOut = sqlite3DbMallocRaw(pMem->db, len);
  26041. if( !zOut ){
  26042. return SQLITE_NOMEM_BKPT;
  26043. }
  26044. z = zOut;
  26045. if( pMem->enc==SQLITE_UTF8 ){
  26046. if( desiredEnc==SQLITE_UTF16LE ){
  26047. /* UTF-8 -> UTF-16 Little-endian */
  26048. while( zIn<zTerm ){
  26049. READ_UTF8(zIn, zTerm, c);
  26050. WRITE_UTF16LE(z, c);
  26051. }
  26052. }else{
  26053. assert( desiredEnc==SQLITE_UTF16BE );
  26054. /* UTF-8 -> UTF-16 Big-endian */
  26055. while( zIn<zTerm ){
  26056. READ_UTF8(zIn, zTerm, c);
  26057. WRITE_UTF16BE(z, c);
  26058. }
  26059. }
  26060. pMem->n = (int)(z - zOut);
  26061. *z++ = 0;
  26062. }else{
  26063. assert( desiredEnc==SQLITE_UTF8 );
  26064. if( pMem->enc==SQLITE_UTF16LE ){
  26065. /* UTF-16 Little-endian -> UTF-8 */
  26066. while( zIn<zTerm ){
  26067. READ_UTF16LE(zIn, zIn<zTerm, c);
  26068. WRITE_UTF8(z, c);
  26069. }
  26070. }else{
  26071. /* UTF-16 Big-endian -> UTF-8 */
  26072. while( zIn<zTerm ){
  26073. READ_UTF16BE(zIn, zIn<zTerm, c);
  26074. WRITE_UTF8(z, c);
  26075. }
  26076. }
  26077. pMem->n = (int)(z - zOut);
  26078. }
  26079. *z = 0;
  26080. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  26081. c = pMem->flags;
  26082. sqlite3VdbeMemRelease(pMem);
  26083. pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
  26084. pMem->enc = desiredEnc;
  26085. pMem->z = (char*)zOut;
  26086. pMem->zMalloc = pMem->z;
  26087. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
  26088. translate_out:
  26089. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  26090. {
  26091. char zBuf[100];
  26092. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  26093. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  26094. }
  26095. #endif
  26096. return SQLITE_OK;
  26097. }
  26098. /*
  26099. ** This routine checks for a byte-order mark at the beginning of the
  26100. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  26101. ** the encoding of the Mem adjusted. This routine does not do any
  26102. ** byte-swapping, it just sets Mem.enc appropriately.
  26103. **
  26104. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  26105. ** changed by this function.
  26106. */
  26107. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  26108. int rc = SQLITE_OK;
  26109. u8 bom = 0;
  26110. assert( pMem->n>=0 );
  26111. if( pMem->n>1 ){
  26112. u8 b1 = *(u8 *)pMem->z;
  26113. u8 b2 = *(((u8 *)pMem->z) + 1);
  26114. if( b1==0xFE && b2==0xFF ){
  26115. bom = SQLITE_UTF16BE;
  26116. }
  26117. if( b1==0xFF && b2==0xFE ){
  26118. bom = SQLITE_UTF16LE;
  26119. }
  26120. }
  26121. if( bom ){
  26122. rc = sqlite3VdbeMemMakeWriteable(pMem);
  26123. if( rc==SQLITE_OK ){
  26124. pMem->n -= 2;
  26125. memmove(pMem->z, &pMem->z[2], pMem->n);
  26126. pMem->z[pMem->n] = '\0';
  26127. pMem->z[pMem->n+1] = '\0';
  26128. pMem->flags |= MEM_Term;
  26129. pMem->enc = bom;
  26130. }
  26131. }
  26132. return rc;
  26133. }
  26134. #endif /* SQLITE_OMIT_UTF16 */
  26135. /*
  26136. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  26137. ** return the number of unicode characters in pZ up to (but not including)
  26138. ** the first 0x00 byte. If nByte is not less than zero, return the
  26139. ** number of unicode characters in the first nByte of pZ (or up to
  26140. ** the first 0x00, whichever comes first).
  26141. */
  26142. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  26143. int r = 0;
  26144. const u8 *z = (const u8*)zIn;
  26145. const u8 *zTerm;
  26146. if( nByte>=0 ){
  26147. zTerm = &z[nByte];
  26148. }else{
  26149. zTerm = (const u8*)(-1);
  26150. }
  26151. assert( z<=zTerm );
  26152. while( *z!=0 && z<zTerm ){
  26153. SQLITE_SKIP_UTF8(z);
  26154. r++;
  26155. }
  26156. return r;
  26157. }
  26158. /* This test function is not currently used by the automated test-suite.
  26159. ** Hence it is only available in debug builds.
  26160. */
  26161. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  26162. /*
  26163. ** Translate UTF-8 to UTF-8.
  26164. **
  26165. ** This has the effect of making sure that the string is well-formed
  26166. ** UTF-8. Miscoded characters are removed.
  26167. **
  26168. ** The translation is done in-place and aborted if the output
  26169. ** overruns the input.
  26170. */
  26171. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  26172. unsigned char *zOut = zIn;
  26173. unsigned char *zStart = zIn;
  26174. u32 c;
  26175. while( zIn[0] && zOut<=zIn ){
  26176. c = sqlite3Utf8Read((const u8**)&zIn);
  26177. if( c!=0xfffd ){
  26178. WRITE_UTF8(zOut, c);
  26179. }
  26180. }
  26181. *zOut = 0;
  26182. return (int)(zOut - zStart);
  26183. }
  26184. #endif
  26185. #ifndef SQLITE_OMIT_UTF16
  26186. /*
  26187. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  26188. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  26189. ** be freed by the calling function.
  26190. **
  26191. ** NULL is returned if there is an allocation error.
  26192. */
  26193. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  26194. Mem m;
  26195. memset(&m, 0, sizeof(m));
  26196. m.db = db;
  26197. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  26198. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  26199. if( db->mallocFailed ){
  26200. sqlite3VdbeMemRelease(&m);
  26201. m.z = 0;
  26202. }
  26203. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  26204. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  26205. assert( m.z || db->mallocFailed );
  26206. return m.z;
  26207. }
  26208. /*
  26209. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  26210. ** Return the number of bytes in the first nChar unicode characters
  26211. ** in pZ. nChar must be non-negative.
  26212. */
  26213. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  26214. int c;
  26215. unsigned char const *z = zIn;
  26216. int n = 0;
  26217. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  26218. while( n<nChar ){
  26219. READ_UTF16BE(z, 1, c);
  26220. n++;
  26221. }
  26222. }else{
  26223. while( n<nChar ){
  26224. READ_UTF16LE(z, 1, c);
  26225. n++;
  26226. }
  26227. }
  26228. return (int)(z-(unsigned char const *)zIn);
  26229. }
  26230. #if defined(SQLITE_TEST)
  26231. /*
  26232. ** This routine is called from the TCL test function "translate_selftest".
  26233. ** It checks that the primitives for serializing and deserializing
  26234. ** characters in each encoding are inverses of each other.
  26235. */
  26236. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  26237. unsigned int i, t;
  26238. unsigned char zBuf[20];
  26239. unsigned char *z;
  26240. int n;
  26241. unsigned int c;
  26242. for(i=0; i<0x00110000; i++){
  26243. z = zBuf;
  26244. WRITE_UTF8(z, i);
  26245. n = (int)(z-zBuf);
  26246. assert( n>0 && n<=4 );
  26247. z[0] = 0;
  26248. z = zBuf;
  26249. c = sqlite3Utf8Read((const u8**)&z);
  26250. t = i;
  26251. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  26252. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  26253. assert( c==t );
  26254. assert( (z-zBuf)==n );
  26255. }
  26256. for(i=0; i<0x00110000; i++){
  26257. if( i>=0xD800 && i<0xE000 ) continue;
  26258. z = zBuf;
  26259. WRITE_UTF16LE(z, i);
  26260. n = (int)(z-zBuf);
  26261. assert( n>0 && n<=4 );
  26262. z[0] = 0;
  26263. z = zBuf;
  26264. READ_UTF16LE(z, 1, c);
  26265. assert( c==i );
  26266. assert( (z-zBuf)==n );
  26267. }
  26268. for(i=0; i<0x00110000; i++){
  26269. if( i>=0xD800 && i<0xE000 ) continue;
  26270. z = zBuf;
  26271. WRITE_UTF16BE(z, i);
  26272. n = (int)(z-zBuf);
  26273. assert( n>0 && n<=4 );
  26274. z[0] = 0;
  26275. z = zBuf;
  26276. READ_UTF16BE(z, 1, c);
  26277. assert( c==i );
  26278. assert( (z-zBuf)==n );
  26279. }
  26280. }
  26281. #endif /* SQLITE_TEST */
  26282. #endif /* SQLITE_OMIT_UTF16 */
  26283. /************** End of utf.c *************************************************/
  26284. /************** Begin file util.c ********************************************/
  26285. /*
  26286. ** 2001 September 15
  26287. **
  26288. ** The author disclaims copyright to this source code. In place of
  26289. ** a legal notice, here is a blessing:
  26290. **
  26291. ** May you do good and not evil.
  26292. ** May you find forgiveness for yourself and forgive others.
  26293. ** May you share freely, never taking more than you give.
  26294. **
  26295. *************************************************************************
  26296. ** Utility functions used throughout sqlite.
  26297. **
  26298. ** This file contains functions for allocating memory, comparing
  26299. ** strings, and stuff like that.
  26300. **
  26301. */
  26302. /* #include "sqliteInt.h" */
  26303. /* #include <stdarg.h> */
  26304. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  26305. # include <math.h>
  26306. #endif
  26307. /*
  26308. ** Routine needed to support the testcase() macro.
  26309. */
  26310. #ifdef SQLITE_COVERAGE_TEST
  26311. SQLITE_PRIVATE void sqlite3Coverage(int x){
  26312. static unsigned dummy = 0;
  26313. dummy += (unsigned)x;
  26314. }
  26315. #endif
  26316. /*
  26317. ** Give a callback to the test harness that can be used to simulate faults
  26318. ** in places where it is difficult or expensive to do so purely by means
  26319. ** of inputs.
  26320. **
  26321. ** The intent of the integer argument is to let the fault simulator know
  26322. ** which of multiple sqlite3FaultSim() calls has been hit.
  26323. **
  26324. ** Return whatever integer value the test callback returns, or return
  26325. ** SQLITE_OK if no test callback is installed.
  26326. */
  26327. #ifndef SQLITE_UNTESTABLE
  26328. SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
  26329. int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
  26330. return xCallback ? xCallback(iTest) : SQLITE_OK;
  26331. }
  26332. #endif
  26333. #ifndef SQLITE_OMIT_FLOATING_POINT
  26334. /*
  26335. ** Return true if the floating point value is Not a Number (NaN).
  26336. **
  26337. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  26338. ** Otherwise, we have our own implementation that works on most systems.
  26339. */
  26340. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  26341. int rc; /* The value return */
  26342. #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
  26343. /*
  26344. ** Systems that support the isnan() library function should probably
  26345. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  26346. ** found that many systems do not have a working isnan() function so
  26347. ** this implementation is provided as an alternative.
  26348. **
  26349. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  26350. ** On the other hand, the use of -ffast-math comes with the following
  26351. ** warning:
  26352. **
  26353. ** This option [-ffast-math] should never be turned on by any
  26354. ** -O option since it can result in incorrect output for programs
  26355. ** which depend on an exact implementation of IEEE or ISO
  26356. ** rules/specifications for math functions.
  26357. **
  26358. ** Under MSVC, this NaN test may fail if compiled with a floating-
  26359. ** point precision mode other than /fp:precise. From the MSDN
  26360. ** documentation:
  26361. **
  26362. ** The compiler [with /fp:precise] will properly handle comparisons
  26363. ** involving NaN. For example, x != x evaluates to true if x is NaN
  26364. ** ...
  26365. */
  26366. #ifdef __FAST_MATH__
  26367. # error SQLite will not work correctly with the -ffast-math option of GCC.
  26368. #endif
  26369. volatile double y = x;
  26370. volatile double z = y;
  26371. rc = (y!=z);
  26372. #else /* if HAVE_ISNAN */
  26373. rc = isnan(x);
  26374. #endif /* HAVE_ISNAN */
  26375. testcase( rc );
  26376. return rc;
  26377. }
  26378. #endif /* SQLITE_OMIT_FLOATING_POINT */
  26379. /*
  26380. ** Compute a string length that is limited to what can be stored in
  26381. ** lower 30 bits of a 32-bit signed integer.
  26382. **
  26383. ** The value returned will never be negative. Nor will it ever be greater
  26384. ** than the actual length of the string. For very long strings (greater
  26385. ** than 1GiB) the value returned might be less than the true string length.
  26386. */
  26387. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  26388. if( z==0 ) return 0;
  26389. return 0x3fffffff & (int)strlen(z);
  26390. }
  26391. /*
  26392. ** Return the declared type of a column. Or return zDflt if the column
  26393. ** has no declared type.
  26394. **
  26395. ** The column type is an extra string stored after the zero-terminator on
  26396. ** the column name if and only if the COLFLAG_HASTYPE flag is set.
  26397. */
  26398. SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
  26399. if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
  26400. return pCol->zName + strlen(pCol->zName) + 1;
  26401. }
  26402. /*
  26403. ** Helper function for sqlite3Error() - called rarely. Broken out into
  26404. ** a separate routine to avoid unnecessary register saves on entry to
  26405. ** sqlite3Error().
  26406. */
  26407. static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
  26408. if( db->pErr ) sqlite3ValueSetNull(db->pErr);
  26409. sqlite3SystemError(db, err_code);
  26410. }
  26411. /*
  26412. ** Set the current error code to err_code and clear any prior error message.
  26413. ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
  26414. ** that would be appropriate.
  26415. */
  26416. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
  26417. assert( db!=0 );
  26418. db->errCode = err_code;
  26419. if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
  26420. }
  26421. /*
  26422. ** Load the sqlite3.iSysErrno field if that is an appropriate thing
  26423. ** to do based on the SQLite error code in rc.
  26424. */
  26425. SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
  26426. if( rc==SQLITE_IOERR_NOMEM ) return;
  26427. rc &= 0xff;
  26428. if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
  26429. db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
  26430. }
  26431. }
  26432. /*
  26433. ** Set the most recent error code and error string for the sqlite
  26434. ** handle "db". The error code is set to "err_code".
  26435. **
  26436. ** If it is not NULL, string zFormat specifies the format of the
  26437. ** error string in the style of the printf functions: The following
  26438. ** format characters are allowed:
  26439. **
  26440. ** %s Insert a string
  26441. ** %z A string that should be freed after use
  26442. ** %d Insert an integer
  26443. ** %T Insert a token
  26444. ** %S Insert the first element of a SrcList
  26445. **
  26446. ** zFormat and any string tokens that follow it are assumed to be
  26447. ** encoded in UTF-8.
  26448. **
  26449. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  26450. ** should be called with err_code set to SQLITE_OK and zFormat set
  26451. ** to NULL.
  26452. */
  26453. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
  26454. assert( db!=0 );
  26455. db->errCode = err_code;
  26456. sqlite3SystemError(db, err_code);
  26457. if( zFormat==0 ){
  26458. sqlite3Error(db, err_code);
  26459. }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
  26460. char *z;
  26461. va_list ap;
  26462. va_start(ap, zFormat);
  26463. z = sqlite3VMPrintf(db, zFormat, ap);
  26464. va_end(ap);
  26465. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  26466. }
  26467. }
  26468. /*
  26469. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  26470. ** The following formatting characters are allowed:
  26471. **
  26472. ** %s Insert a string
  26473. ** %z A string that should be freed after use
  26474. ** %d Insert an integer
  26475. ** %T Insert a token
  26476. ** %S Insert the first element of a SrcList
  26477. **
  26478. ** This function should be used to report any error that occurs while
  26479. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  26480. ** last thing the sqlite3_prepare() function does is copy the error
  26481. ** stored by this function into the database handle using sqlite3Error().
  26482. ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
  26483. ** during statement execution (sqlite3_step() etc.).
  26484. */
  26485. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  26486. char *zMsg;
  26487. va_list ap;
  26488. sqlite3 *db = pParse->db;
  26489. va_start(ap, zFormat);
  26490. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  26491. va_end(ap);
  26492. if( db->suppressErr ){
  26493. sqlite3DbFree(db, zMsg);
  26494. }else{
  26495. pParse->nErr++;
  26496. sqlite3DbFree(db, pParse->zErrMsg);
  26497. pParse->zErrMsg = zMsg;
  26498. pParse->rc = SQLITE_ERROR;
  26499. }
  26500. }
  26501. /*
  26502. ** Convert an SQL-style quoted string into a normal string by removing
  26503. ** the quote characters. The conversion is done in-place. If the
  26504. ** input does not begin with a quote character, then this routine
  26505. ** is a no-op.
  26506. **
  26507. ** The input string must be zero-terminated. A new zero-terminator
  26508. ** is added to the dequoted string.
  26509. **
  26510. ** The return value is -1 if no dequoting occurs or the length of the
  26511. ** dequoted string, exclusive of the zero terminator, if dequoting does
  26512. ** occur.
  26513. **
  26514. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  26515. ** brackets from around identifiers. For example: "[a-b-c]" becomes
  26516. ** "a-b-c".
  26517. */
  26518. SQLITE_PRIVATE void sqlite3Dequote(char *z){
  26519. char quote;
  26520. int i, j;
  26521. if( z==0 ) return;
  26522. quote = z[0];
  26523. if( !sqlite3Isquote(quote) ) return;
  26524. if( quote=='[' ) quote = ']';
  26525. for(i=1, j=0;; i++){
  26526. assert( z[i] );
  26527. if( z[i]==quote ){
  26528. if( z[i+1]==quote ){
  26529. z[j++] = quote;
  26530. i++;
  26531. }else{
  26532. break;
  26533. }
  26534. }else{
  26535. z[j++] = z[i];
  26536. }
  26537. }
  26538. z[j] = 0;
  26539. }
  26540. /*
  26541. ** Generate a Token object from a string
  26542. */
  26543. SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
  26544. p->z = z;
  26545. p->n = sqlite3Strlen30(z);
  26546. }
  26547. /* Convenient short-hand */
  26548. #define UpperToLower sqlite3UpperToLower
  26549. /*
  26550. ** Some systems have stricmp(). Others have strcasecmp(). Because
  26551. ** there is no consistency, we will define our own.
  26552. **
  26553. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  26554. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  26555. ** the contents of two buffers containing UTF-8 strings in a
  26556. ** case-independent fashion, using the same definition of "case
  26557. ** independence" that SQLite uses internally when comparing identifiers.
  26558. */
  26559. SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
  26560. if( zLeft==0 ){
  26561. return zRight ? -1 : 0;
  26562. }else if( zRight==0 ){
  26563. return 1;
  26564. }
  26565. return sqlite3StrICmp(zLeft, zRight);
  26566. }
  26567. SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
  26568. unsigned char *a, *b;
  26569. int c;
  26570. a = (unsigned char *)zLeft;
  26571. b = (unsigned char *)zRight;
  26572. for(;;){
  26573. c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
  26574. if( c || *a==0 ) break;
  26575. a++;
  26576. b++;
  26577. }
  26578. return c;
  26579. }
  26580. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  26581. register unsigned char *a, *b;
  26582. if( zLeft==0 ){
  26583. return zRight ? -1 : 0;
  26584. }else if( zRight==0 ){
  26585. return 1;
  26586. }
  26587. a = (unsigned char *)zLeft;
  26588. b = (unsigned char *)zRight;
  26589. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  26590. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  26591. }
  26592. /*
  26593. ** The string z[] is an text representation of a real number.
  26594. ** Convert this string to a double and write it into *pResult.
  26595. **
  26596. ** The string z[] is length bytes in length (bytes, not characters) and
  26597. ** uses the encoding enc. The string is not necessarily zero-terminated.
  26598. **
  26599. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  26600. ** if the string is empty or contains extraneous text. Valid numbers
  26601. ** are in one of these formats:
  26602. **
  26603. ** [+-]digits[E[+-]digits]
  26604. ** [+-]digits.[digits][E[+-]digits]
  26605. ** [+-].digits[E[+-]digits]
  26606. **
  26607. ** Leading and trailing whitespace is ignored for the purpose of determining
  26608. ** validity.
  26609. **
  26610. ** If some prefix of the input string is a valid number, this routine
  26611. ** returns FALSE but it still converts the prefix and writes the result
  26612. ** into *pResult.
  26613. */
  26614. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  26615. #ifndef SQLITE_OMIT_FLOATING_POINT
  26616. int incr;
  26617. const char *zEnd = z + length;
  26618. /* sign * significand * (10 ^ (esign * exponent)) */
  26619. int sign = 1; /* sign of significand */
  26620. i64 s = 0; /* significand */
  26621. int d = 0; /* adjust exponent for shifting decimal point */
  26622. int esign = 1; /* sign of exponent */
  26623. int e = 0; /* exponent */
  26624. int eValid = 1; /* True exponent is either not used or is well-formed */
  26625. double result;
  26626. int nDigits = 0;
  26627. int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
  26628. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  26629. *pResult = 0.0; /* Default return value, in case of an error */
  26630. if( enc==SQLITE_UTF8 ){
  26631. incr = 1;
  26632. }else{
  26633. int i;
  26634. incr = 2;
  26635. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  26636. for(i=3-enc; i<length && z[i]==0; i+=2){}
  26637. nonNum = i<length;
  26638. zEnd = &z[i^1];
  26639. z += (enc&1);
  26640. }
  26641. /* skip leading spaces */
  26642. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  26643. if( z>=zEnd ) return 0;
  26644. /* get sign of significand */
  26645. if( *z=='-' ){
  26646. sign = -1;
  26647. z+=incr;
  26648. }else if( *z=='+' ){
  26649. z+=incr;
  26650. }
  26651. /* copy max significant digits to significand */
  26652. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  26653. s = s*10 + (*z - '0');
  26654. z+=incr, nDigits++;
  26655. }
  26656. /* skip non-significant significand digits
  26657. ** (increase exponent by d to shift decimal left) */
  26658. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
  26659. if( z>=zEnd ) goto do_atof_calc;
  26660. /* if decimal point is present */
  26661. if( *z=='.' ){
  26662. z+=incr;
  26663. /* copy digits from after decimal to significand
  26664. ** (decrease exponent by d to shift decimal right) */
  26665. while( z<zEnd && sqlite3Isdigit(*z) ){
  26666. if( s<((LARGEST_INT64-9)/10) ){
  26667. s = s*10 + (*z - '0');
  26668. d--;
  26669. }
  26670. z+=incr, nDigits++;
  26671. }
  26672. }
  26673. if( z>=zEnd ) goto do_atof_calc;
  26674. /* if exponent is present */
  26675. if( *z=='e' || *z=='E' ){
  26676. z+=incr;
  26677. eValid = 0;
  26678. /* This branch is needed to avoid a (harmless) buffer overread. The
  26679. ** special comment alerts the mutation tester that the correct answer
  26680. ** is obtained even if the branch is omitted */
  26681. if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
  26682. /* get sign of exponent */
  26683. if( *z=='-' ){
  26684. esign = -1;
  26685. z+=incr;
  26686. }else if( *z=='+' ){
  26687. z+=incr;
  26688. }
  26689. /* copy digits to exponent */
  26690. while( z<zEnd && sqlite3Isdigit(*z) ){
  26691. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  26692. z+=incr;
  26693. eValid = 1;
  26694. }
  26695. }
  26696. /* skip trailing spaces */
  26697. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  26698. do_atof_calc:
  26699. /* adjust exponent by d, and update sign */
  26700. e = (e*esign) + d;
  26701. if( e<0 ) {
  26702. esign = -1;
  26703. e *= -1;
  26704. } else {
  26705. esign = 1;
  26706. }
  26707. if( s==0 ) {
  26708. /* In the IEEE 754 standard, zero is signed. */
  26709. result = sign<0 ? -(double)0 : (double)0;
  26710. } else {
  26711. /* Attempt to reduce exponent.
  26712. **
  26713. ** Branches that are not required for the correct answer but which only
  26714. ** help to obtain the correct answer faster are marked with special
  26715. ** comments, as a hint to the mutation tester.
  26716. */
  26717. while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
  26718. if( esign>0 ){
  26719. if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
  26720. s *= 10;
  26721. }else{
  26722. if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
  26723. s /= 10;
  26724. }
  26725. e--;
  26726. }
  26727. /* adjust the sign of significand */
  26728. s = sign<0 ? -s : s;
  26729. if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
  26730. result = (double)s;
  26731. }else{
  26732. LONGDOUBLE_TYPE scale = 1.0;
  26733. /* attempt to handle extremely small/large numbers better */
  26734. if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
  26735. if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
  26736. while( e%308 ) { scale *= 1.0e+1; e -= 1; }
  26737. if( esign<0 ){
  26738. result = s / scale;
  26739. result /= 1.0e+308;
  26740. }else{
  26741. result = s * scale;
  26742. result *= 1.0e+308;
  26743. }
  26744. }else{ assert( e>=342 );
  26745. if( esign<0 ){
  26746. result = 0.0*s;
  26747. }else{
  26748. result = 1e308*1e308*s; /* Infinity */
  26749. }
  26750. }
  26751. }else{
  26752. /* 1.0e+22 is the largest power of 10 than can be
  26753. ** represented exactly. */
  26754. while( e%22 ) { scale *= 1.0e+1; e -= 1; }
  26755. while( e>0 ) { scale *= 1.0e+22; e -= 22; }
  26756. if( esign<0 ){
  26757. result = s / scale;
  26758. }else{
  26759. result = s * scale;
  26760. }
  26761. }
  26762. }
  26763. }
  26764. /* store the result */
  26765. *pResult = result;
  26766. /* return true if number and no extra non-whitespace chracters after */
  26767. return z==zEnd && nDigits>0 && eValid && nonNum==0;
  26768. #else
  26769. return !sqlite3Atoi64(z, pResult, length, enc);
  26770. #endif /* SQLITE_OMIT_FLOATING_POINT */
  26771. }
  26772. /*
  26773. ** Compare the 19-character string zNum against the text representation
  26774. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  26775. ** if zNum is less than, equal to, or greater than the string.
  26776. ** Note that zNum must contain exactly 19 characters.
  26777. **
  26778. ** Unlike memcmp() this routine is guaranteed to return the difference
  26779. ** in the values of the last digit if the only difference is in the
  26780. ** last digit. So, for example,
  26781. **
  26782. ** compare2pow63("9223372036854775800", 1)
  26783. **
  26784. ** will return -8.
  26785. */
  26786. static int compare2pow63(const char *zNum, int incr){
  26787. int c = 0;
  26788. int i;
  26789. /* 012345678901234567 */
  26790. const char *pow63 = "922337203685477580";
  26791. for(i=0; c==0 && i<18; i++){
  26792. c = (zNum[i*incr]-pow63[i])*10;
  26793. }
  26794. if( c==0 ){
  26795. c = zNum[18*incr] - '8';
  26796. testcase( c==(-1) );
  26797. testcase( c==0 );
  26798. testcase( c==(+1) );
  26799. }
  26800. return c;
  26801. }
  26802. /*
  26803. ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
  26804. ** routine does *not* accept hexadecimal notation.
  26805. **
  26806. ** If the zNum value is representable as a 64-bit twos-complement
  26807. ** integer, then write that value into *pNum and return 0.
  26808. **
  26809. ** If zNum is exactly 9223372036854775808, return 2. This special
  26810. ** case is broken out because while 9223372036854775808 cannot be a
  26811. ** signed 64-bit integer, its negative -9223372036854775808 can be.
  26812. **
  26813. ** If zNum is too big for a 64-bit integer and is not
  26814. ** 9223372036854775808 or if zNum contains any non-numeric text,
  26815. ** then return 1.
  26816. **
  26817. ** length is the number of bytes in the string (bytes, not characters).
  26818. ** The string is not necessarily zero-terminated. The encoding is
  26819. ** given by enc.
  26820. */
  26821. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  26822. int incr;
  26823. u64 u = 0;
  26824. int neg = 0; /* assume positive */
  26825. int i;
  26826. int c = 0;
  26827. int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
  26828. const char *zStart;
  26829. const char *zEnd = zNum + length;
  26830. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  26831. if( enc==SQLITE_UTF8 ){
  26832. incr = 1;
  26833. }else{
  26834. incr = 2;
  26835. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  26836. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  26837. nonNum = i<length;
  26838. zEnd = &zNum[i^1];
  26839. zNum += (enc&1);
  26840. }
  26841. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  26842. if( zNum<zEnd ){
  26843. if( *zNum=='-' ){
  26844. neg = 1;
  26845. zNum+=incr;
  26846. }else if( *zNum=='+' ){
  26847. zNum+=incr;
  26848. }
  26849. }
  26850. zStart = zNum;
  26851. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  26852. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  26853. u = u*10 + c - '0';
  26854. }
  26855. if( u>LARGEST_INT64 ){
  26856. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  26857. }else if( neg ){
  26858. *pNum = -(i64)u;
  26859. }else{
  26860. *pNum = (i64)u;
  26861. }
  26862. testcase( i==18 );
  26863. testcase( i==19 );
  26864. testcase( i==20 );
  26865. if( &zNum[i]<zEnd /* Extra bytes at the end */
  26866. || (i==0 && zStart==zNum) /* No digits */
  26867. || i>19*incr /* Too many digits */
  26868. || nonNum /* UTF16 with high-order bytes non-zero */
  26869. ){
  26870. /* zNum is empty or contains non-numeric text or is longer
  26871. ** than 19 digits (thus guaranteeing that it is too large) */
  26872. return 1;
  26873. }else if( i<19*incr ){
  26874. /* Less than 19 digits, so we know that it fits in 64 bits */
  26875. assert( u<=LARGEST_INT64 );
  26876. return 0;
  26877. }else{
  26878. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  26879. c = compare2pow63(zNum, incr);
  26880. if( c<0 ){
  26881. /* zNum is less than 9223372036854775808 so it fits */
  26882. assert( u<=LARGEST_INT64 );
  26883. return 0;
  26884. }else if( c>0 ){
  26885. /* zNum is greater than 9223372036854775808 so it overflows */
  26886. return 1;
  26887. }else{
  26888. /* zNum is exactly 9223372036854775808. Fits if negative. The
  26889. ** special case 2 overflow if positive */
  26890. assert( u-1==LARGEST_INT64 );
  26891. return neg ? 0 : 2;
  26892. }
  26893. }
  26894. }
  26895. /*
  26896. ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
  26897. ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
  26898. ** whereas sqlite3Atoi64() does not.
  26899. **
  26900. ** Returns:
  26901. **
  26902. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  26903. ** 1 Integer too large for a 64-bit signed integer or is malformed
  26904. ** 2 Special case of 9223372036854775808
  26905. */
  26906. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
  26907. #ifndef SQLITE_OMIT_HEX_INTEGER
  26908. if( z[0]=='0'
  26909. && (z[1]=='x' || z[1]=='X')
  26910. ){
  26911. u64 u = 0;
  26912. int i, k;
  26913. for(i=2; z[i]=='0'; i++){}
  26914. for(k=i; sqlite3Isxdigit(z[k]); k++){
  26915. u = u*16 + sqlite3HexToInt(z[k]);
  26916. }
  26917. memcpy(pOut, &u, 8);
  26918. return (z[k]==0 && k-i<=16) ? 0 : 1;
  26919. }else
  26920. #endif /* SQLITE_OMIT_HEX_INTEGER */
  26921. {
  26922. return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
  26923. }
  26924. }
  26925. /*
  26926. ** If zNum represents an integer that will fit in 32-bits, then set
  26927. ** *pValue to that integer and return true. Otherwise return false.
  26928. **
  26929. ** This routine accepts both decimal and hexadecimal notation for integers.
  26930. **
  26931. ** Any non-numeric characters that following zNum are ignored.
  26932. ** This is different from sqlite3Atoi64() which requires the
  26933. ** input number to be zero-terminated.
  26934. */
  26935. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  26936. sqlite_int64 v = 0;
  26937. int i, c;
  26938. int neg = 0;
  26939. if( zNum[0]=='-' ){
  26940. neg = 1;
  26941. zNum++;
  26942. }else if( zNum[0]=='+' ){
  26943. zNum++;
  26944. }
  26945. #ifndef SQLITE_OMIT_HEX_INTEGER
  26946. else if( zNum[0]=='0'
  26947. && (zNum[1]=='x' || zNum[1]=='X')
  26948. && sqlite3Isxdigit(zNum[2])
  26949. ){
  26950. u32 u = 0;
  26951. zNum += 2;
  26952. while( zNum[0]=='0' ) zNum++;
  26953. for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
  26954. u = u*16 + sqlite3HexToInt(zNum[i]);
  26955. }
  26956. if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
  26957. memcpy(pValue, &u, 4);
  26958. return 1;
  26959. }else{
  26960. return 0;
  26961. }
  26962. }
  26963. #endif
  26964. if( !sqlite3Isdigit(zNum[0]) ) return 0;
  26965. while( zNum[0]=='0' ) zNum++;
  26966. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  26967. v = v*10 + c;
  26968. }
  26969. /* The longest decimal representation of a 32 bit integer is 10 digits:
  26970. **
  26971. ** 1234567890
  26972. ** 2^31 -> 2147483648
  26973. */
  26974. testcase( i==10 );
  26975. if( i>10 ){
  26976. return 0;
  26977. }
  26978. testcase( v-neg==2147483647 );
  26979. if( v-neg>2147483647 ){
  26980. return 0;
  26981. }
  26982. if( neg ){
  26983. v = -v;
  26984. }
  26985. *pValue = (int)v;
  26986. return 1;
  26987. }
  26988. /*
  26989. ** Return a 32-bit integer value extracted from a string. If the
  26990. ** string is not an integer, just return 0.
  26991. */
  26992. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  26993. int x = 0;
  26994. if( z ) sqlite3GetInt32(z, &x);
  26995. return x;
  26996. }
  26997. /*
  26998. ** The variable-length integer encoding is as follows:
  26999. **
  27000. ** KEY:
  27001. ** A = 0xxxxxxx 7 bits of data and one flag bit
  27002. ** B = 1xxxxxxx 7 bits of data and one flag bit
  27003. ** C = xxxxxxxx 8 bits of data
  27004. **
  27005. ** 7 bits - A
  27006. ** 14 bits - BA
  27007. ** 21 bits - BBA
  27008. ** 28 bits - BBBA
  27009. ** 35 bits - BBBBA
  27010. ** 42 bits - BBBBBA
  27011. ** 49 bits - BBBBBBA
  27012. ** 56 bits - BBBBBBBA
  27013. ** 64 bits - BBBBBBBBC
  27014. */
  27015. /*
  27016. ** Write a 64-bit variable-length integer to memory starting at p[0].
  27017. ** The length of data write will be between 1 and 9 bytes. The number
  27018. ** of bytes written is returned.
  27019. **
  27020. ** A variable-length integer consists of the lower 7 bits of each byte
  27021. ** for all bytes that have the 8th bit set and one byte with the 8th
  27022. ** bit clear. Except, if we get to the 9th byte, it stores the full
  27023. ** 8 bits and is the last byte.
  27024. */
  27025. static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
  27026. int i, j, n;
  27027. u8 buf[10];
  27028. if( v & (((u64)0xff000000)<<32) ){
  27029. p[8] = (u8)v;
  27030. v >>= 8;
  27031. for(i=7; i>=0; i--){
  27032. p[i] = (u8)((v & 0x7f) | 0x80);
  27033. v >>= 7;
  27034. }
  27035. return 9;
  27036. }
  27037. n = 0;
  27038. do{
  27039. buf[n++] = (u8)((v & 0x7f) | 0x80);
  27040. v >>= 7;
  27041. }while( v!=0 );
  27042. buf[0] &= 0x7f;
  27043. assert( n<=9 );
  27044. for(i=0, j=n-1; j>=0; j--, i++){
  27045. p[i] = buf[j];
  27046. }
  27047. return n;
  27048. }
  27049. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  27050. if( v<=0x7f ){
  27051. p[0] = v&0x7f;
  27052. return 1;
  27053. }
  27054. if( v<=0x3fff ){
  27055. p[0] = ((v>>7)&0x7f)|0x80;
  27056. p[1] = v&0x7f;
  27057. return 2;
  27058. }
  27059. return putVarint64(p,v);
  27060. }
  27061. /*
  27062. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  27063. ** are defined here rather than simply putting the constant expressions
  27064. ** inline in order to work around bugs in the RVT compiler.
  27065. **
  27066. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  27067. **
  27068. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  27069. */
  27070. #define SLOT_2_0 0x001fc07f
  27071. #define SLOT_4_2_0 0xf01fc07f
  27072. /*
  27073. ** Read a 64-bit variable-length integer from memory starting at p[0].
  27074. ** Return the number of bytes read. The value is stored in *v.
  27075. */
  27076. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  27077. u32 a,b,s;
  27078. a = *p;
  27079. /* a: p0 (unmasked) */
  27080. if (!(a&0x80))
  27081. {
  27082. *v = a;
  27083. return 1;
  27084. }
  27085. p++;
  27086. b = *p;
  27087. /* b: p1 (unmasked) */
  27088. if (!(b&0x80))
  27089. {
  27090. a &= 0x7f;
  27091. a = a<<7;
  27092. a |= b;
  27093. *v = a;
  27094. return 2;
  27095. }
  27096. /* Verify that constants are precomputed correctly */
  27097. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  27098. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  27099. p++;
  27100. a = a<<14;
  27101. a |= *p;
  27102. /* a: p0<<14 | p2 (unmasked) */
  27103. if (!(a&0x80))
  27104. {
  27105. a &= SLOT_2_0;
  27106. b &= 0x7f;
  27107. b = b<<7;
  27108. a |= b;
  27109. *v = a;
  27110. return 3;
  27111. }
  27112. /* CSE1 from below */
  27113. a &= SLOT_2_0;
  27114. p++;
  27115. b = b<<14;
  27116. b |= *p;
  27117. /* b: p1<<14 | p3 (unmasked) */
  27118. if (!(b&0x80))
  27119. {
  27120. b &= SLOT_2_0;
  27121. /* moved CSE1 up */
  27122. /* a &= (0x7f<<14)|(0x7f); */
  27123. a = a<<7;
  27124. a |= b;
  27125. *v = a;
  27126. return 4;
  27127. }
  27128. /* a: p0<<14 | p2 (masked) */
  27129. /* b: p1<<14 | p3 (unmasked) */
  27130. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  27131. /* moved CSE1 up */
  27132. /* a &= (0x7f<<14)|(0x7f); */
  27133. b &= SLOT_2_0;
  27134. s = a;
  27135. /* s: p0<<14 | p2 (masked) */
  27136. p++;
  27137. a = a<<14;
  27138. a |= *p;
  27139. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  27140. if (!(a&0x80))
  27141. {
  27142. /* we can skip these cause they were (effectively) done above
  27143. ** while calculating s */
  27144. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  27145. /* b &= (0x7f<<14)|(0x7f); */
  27146. b = b<<7;
  27147. a |= b;
  27148. s = s>>18;
  27149. *v = ((u64)s)<<32 | a;
  27150. return 5;
  27151. }
  27152. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  27153. s = s<<7;
  27154. s |= b;
  27155. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  27156. p++;
  27157. b = b<<14;
  27158. b |= *p;
  27159. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  27160. if (!(b&0x80))
  27161. {
  27162. /* we can skip this cause it was (effectively) done above in calc'ing s */
  27163. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  27164. a &= SLOT_2_0;
  27165. a = a<<7;
  27166. a |= b;
  27167. s = s>>18;
  27168. *v = ((u64)s)<<32 | a;
  27169. return 6;
  27170. }
  27171. p++;
  27172. a = a<<14;
  27173. a |= *p;
  27174. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  27175. if (!(a&0x80))
  27176. {
  27177. a &= SLOT_4_2_0;
  27178. b &= SLOT_2_0;
  27179. b = b<<7;
  27180. a |= b;
  27181. s = s>>11;
  27182. *v = ((u64)s)<<32 | a;
  27183. return 7;
  27184. }
  27185. /* CSE2 from below */
  27186. a &= SLOT_2_0;
  27187. p++;
  27188. b = b<<14;
  27189. b |= *p;
  27190. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  27191. if (!(b&0x80))
  27192. {
  27193. b &= SLOT_4_2_0;
  27194. /* moved CSE2 up */
  27195. /* a &= (0x7f<<14)|(0x7f); */
  27196. a = a<<7;
  27197. a |= b;
  27198. s = s>>4;
  27199. *v = ((u64)s)<<32 | a;
  27200. return 8;
  27201. }
  27202. p++;
  27203. a = a<<15;
  27204. a |= *p;
  27205. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  27206. /* moved CSE2 up */
  27207. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  27208. b &= SLOT_2_0;
  27209. b = b<<8;
  27210. a |= b;
  27211. s = s<<4;
  27212. b = p[-4];
  27213. b &= 0x7f;
  27214. b = b>>3;
  27215. s |= b;
  27216. *v = ((u64)s)<<32 | a;
  27217. return 9;
  27218. }
  27219. /*
  27220. ** Read a 32-bit variable-length integer from memory starting at p[0].
  27221. ** Return the number of bytes read. The value is stored in *v.
  27222. **
  27223. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  27224. ** integer, then set *v to 0xffffffff.
  27225. **
  27226. ** A MACRO version, getVarint32, is provided which inlines the
  27227. ** single-byte case. All code should use the MACRO version as
  27228. ** this function assumes the single-byte case has already been handled.
  27229. */
  27230. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  27231. u32 a,b;
  27232. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  27233. ** by the getVarin32() macro */
  27234. a = *p;
  27235. /* a: p0 (unmasked) */
  27236. #ifndef getVarint32
  27237. if (!(a&0x80))
  27238. {
  27239. /* Values between 0 and 127 */
  27240. *v = a;
  27241. return 1;
  27242. }
  27243. #endif
  27244. /* The 2-byte case */
  27245. p++;
  27246. b = *p;
  27247. /* b: p1 (unmasked) */
  27248. if (!(b&0x80))
  27249. {
  27250. /* Values between 128 and 16383 */
  27251. a &= 0x7f;
  27252. a = a<<7;
  27253. *v = a | b;
  27254. return 2;
  27255. }
  27256. /* The 3-byte case */
  27257. p++;
  27258. a = a<<14;
  27259. a |= *p;
  27260. /* a: p0<<14 | p2 (unmasked) */
  27261. if (!(a&0x80))
  27262. {
  27263. /* Values between 16384 and 2097151 */
  27264. a &= (0x7f<<14)|(0x7f);
  27265. b &= 0x7f;
  27266. b = b<<7;
  27267. *v = a | b;
  27268. return 3;
  27269. }
  27270. /* A 32-bit varint is used to store size information in btrees.
  27271. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  27272. ** A 3-byte varint is sufficient, for example, to record the size
  27273. ** of a 1048569-byte BLOB or string.
  27274. **
  27275. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  27276. ** rare larger cases can be handled by the slower 64-bit varint
  27277. ** routine.
  27278. */
  27279. #if 1
  27280. {
  27281. u64 v64;
  27282. u8 n;
  27283. p -= 2;
  27284. n = sqlite3GetVarint(p, &v64);
  27285. assert( n>3 && n<=9 );
  27286. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  27287. *v = 0xffffffff;
  27288. }else{
  27289. *v = (u32)v64;
  27290. }
  27291. return n;
  27292. }
  27293. #else
  27294. /* For following code (kept for historical record only) shows an
  27295. ** unrolling for the 3- and 4-byte varint cases. This code is
  27296. ** slightly faster, but it is also larger and much harder to test.
  27297. */
  27298. p++;
  27299. b = b<<14;
  27300. b |= *p;
  27301. /* b: p1<<14 | p3 (unmasked) */
  27302. if (!(b&0x80))
  27303. {
  27304. /* Values between 2097152 and 268435455 */
  27305. b &= (0x7f<<14)|(0x7f);
  27306. a &= (0x7f<<14)|(0x7f);
  27307. a = a<<7;
  27308. *v = a | b;
  27309. return 4;
  27310. }
  27311. p++;
  27312. a = a<<14;
  27313. a |= *p;
  27314. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  27315. if (!(a&0x80))
  27316. {
  27317. /* Values between 268435456 and 34359738367 */
  27318. a &= SLOT_4_2_0;
  27319. b &= SLOT_4_2_0;
  27320. b = b<<7;
  27321. *v = a | b;
  27322. return 5;
  27323. }
  27324. /* We can only reach this point when reading a corrupt database
  27325. ** file. In that case we are not in any hurry. Use the (relatively
  27326. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  27327. ** value. */
  27328. {
  27329. u64 v64;
  27330. u8 n;
  27331. p -= 4;
  27332. n = sqlite3GetVarint(p, &v64);
  27333. assert( n>5 && n<=9 );
  27334. *v = (u32)v64;
  27335. return n;
  27336. }
  27337. #endif
  27338. }
  27339. /*
  27340. ** Return the number of bytes that will be needed to store the given
  27341. ** 64-bit integer.
  27342. */
  27343. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  27344. int i;
  27345. for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
  27346. return i;
  27347. }
  27348. /*
  27349. ** Read or write a four-byte big-endian integer value.
  27350. */
  27351. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  27352. #if SQLITE_BYTEORDER==4321
  27353. u32 x;
  27354. memcpy(&x,p,4);
  27355. return x;
  27356. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  27357. u32 x;
  27358. memcpy(&x,p,4);
  27359. return __builtin_bswap32(x);
  27360. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  27361. u32 x;
  27362. memcpy(&x,p,4);
  27363. return _byteswap_ulong(x);
  27364. #else
  27365. testcase( p[0]&0x80 );
  27366. return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  27367. #endif
  27368. }
  27369. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  27370. #if SQLITE_BYTEORDER==4321
  27371. memcpy(p,&v,4);
  27372. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  27373. u32 x = __builtin_bswap32(v);
  27374. memcpy(p,&x,4);
  27375. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  27376. u32 x = _byteswap_ulong(v);
  27377. memcpy(p,&x,4);
  27378. #else
  27379. p[0] = (u8)(v>>24);
  27380. p[1] = (u8)(v>>16);
  27381. p[2] = (u8)(v>>8);
  27382. p[3] = (u8)v;
  27383. #endif
  27384. }
  27385. /*
  27386. ** Translate a single byte of Hex into an integer.
  27387. ** This routine only works if h really is a valid hexadecimal
  27388. ** character: 0..9a..fA..F
  27389. */
  27390. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  27391. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  27392. #ifdef SQLITE_ASCII
  27393. h += 9*(1&(h>>6));
  27394. #endif
  27395. #ifdef SQLITE_EBCDIC
  27396. h += 9*(1&~(h>>4));
  27397. #endif
  27398. return (u8)(h & 0xf);
  27399. }
  27400. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  27401. /*
  27402. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  27403. ** value. Return a pointer to its binary value. Space to hold the
  27404. ** binary value has been obtained from malloc and must be freed by
  27405. ** the calling routine.
  27406. */
  27407. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  27408. char *zBlob;
  27409. int i;
  27410. zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
  27411. n--;
  27412. if( zBlob ){
  27413. for(i=0; i<n; i+=2){
  27414. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  27415. }
  27416. zBlob[i/2] = 0;
  27417. }
  27418. return zBlob;
  27419. }
  27420. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  27421. /*
  27422. ** Log an error that is an API call on a connection pointer that should
  27423. ** not have been used. The "type" of connection pointer is given as the
  27424. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  27425. */
  27426. static void logBadConnection(const char *zType){
  27427. sqlite3_log(SQLITE_MISUSE,
  27428. "API call with %s database connection pointer",
  27429. zType
  27430. );
  27431. }
  27432. /*
  27433. ** Check to make sure we have a valid db pointer. This test is not
  27434. ** foolproof but it does provide some measure of protection against
  27435. ** misuse of the interface such as passing in db pointers that are
  27436. ** NULL or which have been previously closed. If this routine returns
  27437. ** 1 it means that the db pointer is valid and 0 if it should not be
  27438. ** dereferenced for any reason. The calling function should invoke
  27439. ** SQLITE_MISUSE immediately.
  27440. **
  27441. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  27442. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  27443. ** open properly and is not fit for general use but which can be
  27444. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  27445. */
  27446. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  27447. u32 magic;
  27448. if( db==0 ){
  27449. logBadConnection("NULL");
  27450. return 0;
  27451. }
  27452. magic = db->magic;
  27453. if( magic!=SQLITE_MAGIC_OPEN ){
  27454. if( sqlite3SafetyCheckSickOrOk(db) ){
  27455. testcase( sqlite3GlobalConfig.xLog!=0 );
  27456. logBadConnection("unopened");
  27457. }
  27458. return 0;
  27459. }else{
  27460. return 1;
  27461. }
  27462. }
  27463. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  27464. u32 magic;
  27465. magic = db->magic;
  27466. if( magic!=SQLITE_MAGIC_SICK &&
  27467. magic!=SQLITE_MAGIC_OPEN &&
  27468. magic!=SQLITE_MAGIC_BUSY ){
  27469. testcase( sqlite3GlobalConfig.xLog!=0 );
  27470. logBadConnection("invalid");
  27471. return 0;
  27472. }else{
  27473. return 1;
  27474. }
  27475. }
  27476. /*
  27477. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  27478. ** the other 64-bit signed integer at *pA and store the result in *pA.
  27479. ** Return 0 on success. Or if the operation would have resulted in an
  27480. ** overflow, leave *pA unchanged and return 1.
  27481. */
  27482. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  27483. #if GCC_VERSION>=5004000
  27484. return __builtin_add_overflow(*pA, iB, pA);
  27485. #else
  27486. i64 iA = *pA;
  27487. testcase( iA==0 ); testcase( iA==1 );
  27488. testcase( iB==-1 ); testcase( iB==0 );
  27489. if( iB>=0 ){
  27490. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  27491. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  27492. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  27493. }else{
  27494. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  27495. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  27496. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  27497. }
  27498. *pA += iB;
  27499. return 0;
  27500. #endif
  27501. }
  27502. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  27503. #if GCC_VERSION>=5004000
  27504. return __builtin_sub_overflow(*pA, iB, pA);
  27505. #else
  27506. testcase( iB==SMALLEST_INT64+1 );
  27507. if( iB==SMALLEST_INT64 ){
  27508. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  27509. if( (*pA)>=0 ) return 1;
  27510. *pA -= iB;
  27511. return 0;
  27512. }else{
  27513. return sqlite3AddInt64(pA, -iB);
  27514. }
  27515. #endif
  27516. }
  27517. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  27518. #if GCC_VERSION>=5004000
  27519. return __builtin_mul_overflow(*pA, iB, pA);
  27520. #else
  27521. i64 iA = *pA;
  27522. if( iB>0 ){
  27523. if( iA>LARGEST_INT64/iB ) return 1;
  27524. if( iA<SMALLEST_INT64/iB ) return 1;
  27525. }else if( iB<0 ){
  27526. if( iA>0 ){
  27527. if( iB<SMALLEST_INT64/iA ) return 1;
  27528. }else if( iA<0 ){
  27529. if( iB==SMALLEST_INT64 ) return 1;
  27530. if( iA==SMALLEST_INT64 ) return 1;
  27531. if( -iA>LARGEST_INT64/-iB ) return 1;
  27532. }
  27533. }
  27534. *pA = iA*iB;
  27535. return 0;
  27536. #endif
  27537. }
  27538. /*
  27539. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  27540. ** if the integer has a value of -2147483648, return +2147483647
  27541. */
  27542. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  27543. if( x>=0 ) return x;
  27544. if( x==(int)0x80000000 ) return 0x7fffffff;
  27545. return -x;
  27546. }
  27547. #ifdef SQLITE_ENABLE_8_3_NAMES
  27548. /*
  27549. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  27550. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  27551. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  27552. ** three characters, then shorten the suffix on z[] to be the last three
  27553. ** characters of the original suffix.
  27554. **
  27555. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  27556. ** do the suffix shortening regardless of URI parameter.
  27557. **
  27558. ** Examples:
  27559. **
  27560. ** test.db-journal => test.nal
  27561. ** test.db-wal => test.wal
  27562. ** test.db-shm => test.shm
  27563. ** test.db-mj7f3319fa => test.9fa
  27564. */
  27565. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  27566. #if SQLITE_ENABLE_8_3_NAMES<2
  27567. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  27568. #endif
  27569. {
  27570. int i, sz;
  27571. sz = sqlite3Strlen30(z);
  27572. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  27573. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  27574. }
  27575. }
  27576. #endif
  27577. /*
  27578. ** Find (an approximate) sum of two LogEst values. This computation is
  27579. ** not a simple "+" operator because LogEst is stored as a logarithmic
  27580. ** value.
  27581. **
  27582. */
  27583. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  27584. static const unsigned char x[] = {
  27585. 10, 10, /* 0,1 */
  27586. 9, 9, /* 2,3 */
  27587. 8, 8, /* 4,5 */
  27588. 7, 7, 7, /* 6,7,8 */
  27589. 6, 6, 6, /* 9,10,11 */
  27590. 5, 5, 5, /* 12-14 */
  27591. 4, 4, 4, 4, /* 15-18 */
  27592. 3, 3, 3, 3, 3, 3, /* 19-24 */
  27593. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  27594. };
  27595. if( a>=b ){
  27596. if( a>b+49 ) return a;
  27597. if( a>b+31 ) return a+1;
  27598. return a+x[a-b];
  27599. }else{
  27600. if( b>a+49 ) return b;
  27601. if( b>a+31 ) return b+1;
  27602. return b+x[b-a];
  27603. }
  27604. }
  27605. /*
  27606. ** Convert an integer into a LogEst. In other words, compute an
  27607. ** approximation for 10*log2(x).
  27608. */
  27609. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  27610. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  27611. LogEst y = 40;
  27612. if( x<8 ){
  27613. if( x<2 ) return 0;
  27614. while( x<8 ){ y -= 10; x <<= 1; }
  27615. }else{
  27616. while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
  27617. while( x>15 ){ y += 10; x >>= 1; }
  27618. }
  27619. return a[x&7] + y - 10;
  27620. }
  27621. #ifndef SQLITE_OMIT_VIRTUALTABLE
  27622. /*
  27623. ** Convert a double into a LogEst
  27624. ** In other words, compute an approximation for 10*log2(x).
  27625. */
  27626. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  27627. u64 a;
  27628. LogEst e;
  27629. assert( sizeof(x)==8 && sizeof(a)==8 );
  27630. if( x<=1 ) return 0;
  27631. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  27632. memcpy(&a, &x, 8);
  27633. e = (a>>52) - 1022;
  27634. return e*10;
  27635. }
  27636. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  27637. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  27638. defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
  27639. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  27640. /*
  27641. ** Convert a LogEst into an integer.
  27642. **
  27643. ** Note that this routine is only used when one or more of various
  27644. ** non-standard compile-time options is enabled.
  27645. */
  27646. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  27647. u64 n;
  27648. n = x%10;
  27649. x /= 10;
  27650. if( n>=5 ) n -= 2;
  27651. else if( n>=1 ) n -= 1;
  27652. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  27653. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  27654. if( x>60 ) return (u64)LARGEST_INT64;
  27655. #else
  27656. /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
  27657. ** possible to this routine is 310, resulting in a maximum x of 31 */
  27658. assert( x<=60 );
  27659. #endif
  27660. return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
  27661. }
  27662. #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
  27663. /*
  27664. ** Add a new name/number pair to a VList. This might require that the
  27665. ** VList object be reallocated, so return the new VList. If an OOM
  27666. ** error occurs, the original VList returned and the
  27667. ** db->mallocFailed flag is set.
  27668. **
  27669. ** A VList is really just an array of integers. To destroy a VList,
  27670. ** simply pass it to sqlite3DbFree().
  27671. **
  27672. ** The first integer is the number of integers allocated for the whole
  27673. ** VList. The second integer is the number of integers actually used.
  27674. ** Each name/number pair is encoded by subsequent groups of 3 or more
  27675. ** integers.
  27676. **
  27677. ** Each name/number pair starts with two integers which are the numeric
  27678. ** value for the pair and the size of the name/number pair, respectively.
  27679. ** The text name overlays one or more following integers. The text name
  27680. ** is always zero-terminated.
  27681. **
  27682. ** Conceptually:
  27683. **
  27684. ** struct VList {
  27685. ** int nAlloc; // Number of allocated slots
  27686. ** int nUsed; // Number of used slots
  27687. ** struct VListEntry {
  27688. ** int iValue; // Value for this entry
  27689. ** int nSlot; // Slots used by this entry
  27690. ** // ... variable name goes here
  27691. ** } a[0];
  27692. ** }
  27693. **
  27694. ** During code generation, pointers to the variable names within the
  27695. ** VList are taken. When that happens, nAlloc is set to zero as an
  27696. ** indication that the VList may never again be enlarged, since the
  27697. ** accompanying realloc() would invalidate the pointers.
  27698. */
  27699. SQLITE_PRIVATE VList *sqlite3VListAdd(
  27700. sqlite3 *db, /* The database connection used for malloc() */
  27701. VList *pIn, /* The input VList. Might be NULL */
  27702. const char *zName, /* Name of symbol to add */
  27703. int nName, /* Bytes of text in zName */
  27704. int iVal /* Value to associate with zName */
  27705. ){
  27706. int nInt; /* number of sizeof(int) objects needed for zName */
  27707. char *z; /* Pointer to where zName will be stored */
  27708. int i; /* Index in pIn[] where zName is stored */
  27709. nInt = nName/4 + 3;
  27710. assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */
  27711. if( pIn==0 || pIn[1]+nInt > pIn[0] ){
  27712. /* Enlarge the allocation */
  27713. int nAlloc = (pIn ? pIn[0]*2 : 10) + nInt;
  27714. VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
  27715. if( pOut==0 ) return pIn;
  27716. if( pIn==0 ) pOut[1] = 2;
  27717. pIn = pOut;
  27718. pIn[0] = nAlloc;
  27719. }
  27720. i = pIn[1];
  27721. pIn[i] = iVal;
  27722. pIn[i+1] = nInt;
  27723. z = (char*)&pIn[i+2];
  27724. pIn[1] = i+nInt;
  27725. assert( pIn[1]<=pIn[0] );
  27726. memcpy(z, zName, nName);
  27727. z[nName] = 0;
  27728. return pIn;
  27729. }
  27730. /*
  27731. ** Return a pointer to the name of a variable in the given VList that
  27732. ** has the value iVal. Or return a NULL if there is no such variable in
  27733. ** the list
  27734. */
  27735. SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
  27736. int i, mx;
  27737. if( pIn==0 ) return 0;
  27738. mx = pIn[1];
  27739. i = 2;
  27740. do{
  27741. if( pIn[i]==iVal ) return (char*)&pIn[i+2];
  27742. i += pIn[i+1];
  27743. }while( i<mx );
  27744. return 0;
  27745. }
  27746. /*
  27747. ** Return the number of the variable named zName, if it is in VList.
  27748. ** or return 0 if there is no such variable.
  27749. */
  27750. SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
  27751. int i, mx;
  27752. if( pIn==0 ) return 0;
  27753. mx = pIn[1];
  27754. i = 2;
  27755. do{
  27756. const char *z = (const char*)&pIn[i+2];
  27757. if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
  27758. i += pIn[i+1];
  27759. }while( i<mx );
  27760. return 0;
  27761. }
  27762. /************** End of util.c ************************************************/
  27763. /************** Begin file hash.c ********************************************/
  27764. /*
  27765. ** 2001 September 22
  27766. **
  27767. ** The author disclaims copyright to this source code. In place of
  27768. ** a legal notice, here is a blessing:
  27769. **
  27770. ** May you do good and not evil.
  27771. ** May you find forgiveness for yourself and forgive others.
  27772. ** May you share freely, never taking more than you give.
  27773. **
  27774. *************************************************************************
  27775. ** This is the implementation of generic hash-tables
  27776. ** used in SQLite.
  27777. */
  27778. /* #include "sqliteInt.h" */
  27779. /* #include <assert.h> */
  27780. /* Turn bulk memory into a hash table object by initializing the
  27781. ** fields of the Hash structure.
  27782. **
  27783. ** "pNew" is a pointer to the hash table that is to be initialized.
  27784. */
  27785. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  27786. assert( pNew!=0 );
  27787. pNew->first = 0;
  27788. pNew->count = 0;
  27789. pNew->htsize = 0;
  27790. pNew->ht = 0;
  27791. }
  27792. /* Remove all entries from a hash table. Reclaim all memory.
  27793. ** Call this routine to delete a hash table or to reset a hash table
  27794. ** to the empty state.
  27795. */
  27796. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  27797. HashElem *elem; /* For looping over all elements of the table */
  27798. assert( pH!=0 );
  27799. elem = pH->first;
  27800. pH->first = 0;
  27801. sqlite3_free(pH->ht);
  27802. pH->ht = 0;
  27803. pH->htsize = 0;
  27804. while( elem ){
  27805. HashElem *next_elem = elem->next;
  27806. sqlite3_free(elem);
  27807. elem = next_elem;
  27808. }
  27809. pH->count = 0;
  27810. }
  27811. /*
  27812. ** The hashing function.
  27813. */
  27814. static unsigned int strHash(const char *z){
  27815. unsigned int h = 0;
  27816. unsigned char c;
  27817. while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
  27818. /* Knuth multiplicative hashing. (Sorting & Searching, p. 510).
  27819. ** 0x9e3779b1 is 2654435761 which is the closest prime number to
  27820. ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
  27821. h += sqlite3UpperToLower[c];
  27822. h *= 0x9e3779b1;
  27823. }
  27824. return h;
  27825. }
  27826. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  27827. ** insert pNew into the pEntry hash bucket.
  27828. */
  27829. static void insertElement(
  27830. Hash *pH, /* The complete hash table */
  27831. struct _ht *pEntry, /* The entry into which pNew is inserted */
  27832. HashElem *pNew /* The element to be inserted */
  27833. ){
  27834. HashElem *pHead; /* First element already in pEntry */
  27835. if( pEntry ){
  27836. pHead = pEntry->count ? pEntry->chain : 0;
  27837. pEntry->count++;
  27838. pEntry->chain = pNew;
  27839. }else{
  27840. pHead = 0;
  27841. }
  27842. if( pHead ){
  27843. pNew->next = pHead;
  27844. pNew->prev = pHead->prev;
  27845. if( pHead->prev ){ pHead->prev->next = pNew; }
  27846. else { pH->first = pNew; }
  27847. pHead->prev = pNew;
  27848. }else{
  27849. pNew->next = pH->first;
  27850. if( pH->first ){ pH->first->prev = pNew; }
  27851. pNew->prev = 0;
  27852. pH->first = pNew;
  27853. }
  27854. }
  27855. /* Resize the hash table so that it cantains "new_size" buckets.
  27856. **
  27857. ** The hash table might fail to resize if sqlite3_malloc() fails or
  27858. ** if the new size is the same as the prior size.
  27859. ** Return TRUE if the resize occurs and false if not.
  27860. */
  27861. static int rehash(Hash *pH, unsigned int new_size){
  27862. struct _ht *new_ht; /* The new hash table */
  27863. HashElem *elem, *next_elem; /* For looping over existing elements */
  27864. #if SQLITE_MALLOC_SOFT_LIMIT>0
  27865. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  27866. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  27867. }
  27868. if( new_size==pH->htsize ) return 0;
  27869. #endif
  27870. /* The inability to allocates space for a larger hash table is
  27871. ** a performance hit but it is not a fatal error. So mark the
  27872. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  27873. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  27874. ** only zeroes the requested number of bytes whereas this module will
  27875. ** use the actual amount of space allocated for the hash table (which
  27876. ** may be larger than the requested amount).
  27877. */
  27878. sqlite3BeginBenignMalloc();
  27879. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  27880. sqlite3EndBenignMalloc();
  27881. if( new_ht==0 ) return 0;
  27882. sqlite3_free(pH->ht);
  27883. pH->ht = new_ht;
  27884. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  27885. memset(new_ht, 0, new_size*sizeof(struct _ht));
  27886. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  27887. unsigned int h = strHash(elem->pKey) % new_size;
  27888. next_elem = elem->next;
  27889. insertElement(pH, &new_ht[h], elem);
  27890. }
  27891. return 1;
  27892. }
  27893. /* This function (for internal use only) locates an element in an
  27894. ** hash table that matches the given key. The hash for this key is
  27895. ** also computed and returned in the *pH parameter.
  27896. */
  27897. static HashElem *findElementWithHash(
  27898. const Hash *pH, /* The pH to be searched */
  27899. const char *pKey, /* The key we are searching for */
  27900. unsigned int *pHash /* Write the hash value here */
  27901. ){
  27902. HashElem *elem; /* Used to loop thru the element list */
  27903. int count; /* Number of elements left to test */
  27904. unsigned int h; /* The computed hash */
  27905. if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
  27906. struct _ht *pEntry;
  27907. h = strHash(pKey) % pH->htsize;
  27908. pEntry = &pH->ht[h];
  27909. elem = pEntry->chain;
  27910. count = pEntry->count;
  27911. }else{
  27912. h = 0;
  27913. elem = pH->first;
  27914. count = pH->count;
  27915. }
  27916. *pHash = h;
  27917. while( count-- ){
  27918. assert( elem!=0 );
  27919. if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
  27920. return elem;
  27921. }
  27922. elem = elem->next;
  27923. }
  27924. return 0;
  27925. }
  27926. /* Remove a single entry from the hash table given a pointer to that
  27927. ** element and a hash on the element's key.
  27928. */
  27929. static void removeElementGivenHash(
  27930. Hash *pH, /* The pH containing "elem" */
  27931. HashElem* elem, /* The element to be removed from the pH */
  27932. unsigned int h /* Hash value for the element */
  27933. ){
  27934. struct _ht *pEntry;
  27935. if( elem->prev ){
  27936. elem->prev->next = elem->next;
  27937. }else{
  27938. pH->first = elem->next;
  27939. }
  27940. if( elem->next ){
  27941. elem->next->prev = elem->prev;
  27942. }
  27943. if( pH->ht ){
  27944. pEntry = &pH->ht[h];
  27945. if( pEntry->chain==elem ){
  27946. pEntry->chain = elem->next;
  27947. }
  27948. pEntry->count--;
  27949. assert( pEntry->count>=0 );
  27950. }
  27951. sqlite3_free( elem );
  27952. pH->count--;
  27953. if( pH->count==0 ){
  27954. assert( pH->first==0 );
  27955. assert( pH->count==0 );
  27956. sqlite3HashClear(pH);
  27957. }
  27958. }
  27959. /* Attempt to locate an element of the hash table pH with a key
  27960. ** that matches pKey. Return the data for this element if it is
  27961. ** found, or NULL if there is no match.
  27962. */
  27963. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
  27964. HashElem *elem; /* The element that matches key */
  27965. unsigned int h; /* A hash on key */
  27966. assert( pH!=0 );
  27967. assert( pKey!=0 );
  27968. elem = findElementWithHash(pH, pKey, &h);
  27969. return elem ? elem->data : 0;
  27970. }
  27971. /* Insert an element into the hash table pH. The key is pKey
  27972. ** and the data is "data".
  27973. **
  27974. ** If no element exists with a matching key, then a new
  27975. ** element is created and NULL is returned.
  27976. **
  27977. ** If another element already exists with the same key, then the
  27978. ** new data replaces the old data and the old data is returned.
  27979. ** The key is not copied in this instance. If a malloc fails, then
  27980. ** the new data is returned and the hash table is unchanged.
  27981. **
  27982. ** If the "data" parameter to this function is NULL, then the
  27983. ** element corresponding to "key" is removed from the hash table.
  27984. */
  27985. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
  27986. unsigned int h; /* the hash of the key modulo hash table size */
  27987. HashElem *elem; /* Used to loop thru the element list */
  27988. HashElem *new_elem; /* New element added to the pH */
  27989. assert( pH!=0 );
  27990. assert( pKey!=0 );
  27991. elem = findElementWithHash(pH,pKey,&h);
  27992. if( elem ){
  27993. void *old_data = elem->data;
  27994. if( data==0 ){
  27995. removeElementGivenHash(pH,elem,h);
  27996. }else{
  27997. elem->data = data;
  27998. elem->pKey = pKey;
  27999. }
  28000. return old_data;
  28001. }
  28002. if( data==0 ) return 0;
  28003. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  28004. if( new_elem==0 ) return data;
  28005. new_elem->pKey = pKey;
  28006. new_elem->data = data;
  28007. pH->count++;
  28008. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  28009. if( rehash(pH, pH->count*2) ){
  28010. assert( pH->htsize>0 );
  28011. h = strHash(pKey) % pH->htsize;
  28012. }
  28013. }
  28014. insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
  28015. return 0;
  28016. }
  28017. /************** End of hash.c ************************************************/
  28018. /************** Begin file opcodes.c *****************************************/
  28019. /* Automatically generated. Do not edit */
  28020. /* See the tool/mkopcodec.tcl script for details. */
  28021. #if !defined(SQLITE_OMIT_EXPLAIN) \
  28022. || defined(VDBE_PROFILE) \
  28023. || defined(SQLITE_DEBUG)
  28024. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
  28025. # define OpHelp(X) "\0" X
  28026. #else
  28027. # define OpHelp(X)
  28028. #endif
  28029. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  28030. static const char *const azName[] = {
  28031. /* 0 */ "Savepoint" OpHelp(""),
  28032. /* 1 */ "AutoCommit" OpHelp(""),
  28033. /* 2 */ "Transaction" OpHelp(""),
  28034. /* 3 */ "SorterNext" OpHelp(""),
  28035. /* 4 */ "PrevIfOpen" OpHelp(""),
  28036. /* 5 */ "NextIfOpen" OpHelp(""),
  28037. /* 6 */ "Prev" OpHelp(""),
  28038. /* 7 */ "Next" OpHelp(""),
  28039. /* 8 */ "Checkpoint" OpHelp(""),
  28040. /* 9 */ "JournalMode" OpHelp(""),
  28041. /* 10 */ "Vacuum" OpHelp(""),
  28042. /* 11 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
  28043. /* 12 */ "VUpdate" OpHelp("data=r[P3@P2]"),
  28044. /* 13 */ "Goto" OpHelp(""),
  28045. /* 14 */ "Gosub" OpHelp(""),
  28046. /* 15 */ "InitCoroutine" OpHelp(""),
  28047. /* 16 */ "Yield" OpHelp(""),
  28048. /* 17 */ "MustBeInt" OpHelp(""),
  28049. /* 18 */ "Jump" OpHelp(""),
  28050. /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
  28051. /* 20 */ "Once" OpHelp(""),
  28052. /* 21 */ "If" OpHelp(""),
  28053. /* 22 */ "IfNot" OpHelp(""),
  28054. /* 23 */ "IfNullRow" OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
  28055. /* 24 */ "SeekLT" OpHelp("key=r[P3@P4]"),
  28056. /* 25 */ "SeekLE" OpHelp("key=r[P3@P4]"),
  28057. /* 26 */ "SeekGE" OpHelp("key=r[P3@P4]"),
  28058. /* 27 */ "SeekGT" OpHelp("key=r[P3@P4]"),
  28059. /* 28 */ "NoConflict" OpHelp("key=r[P3@P4]"),
  28060. /* 29 */ "NotFound" OpHelp("key=r[P3@P4]"),
  28061. /* 30 */ "Found" OpHelp("key=r[P3@P4]"),
  28062. /* 31 */ "SeekRowid" OpHelp("intkey=r[P3]"),
  28063. /* 32 */ "NotExists" OpHelp("intkey=r[P3]"),
  28064. /* 33 */ "Last" OpHelp(""),
  28065. /* 34 */ "IfSmaller" OpHelp(""),
  28066. /* 35 */ "SorterSort" OpHelp(""),
  28067. /* 36 */ "Sort" OpHelp(""),
  28068. /* 37 */ "Rewind" OpHelp(""),
  28069. /* 38 */ "IdxLE" OpHelp("key=r[P3@P4]"),
  28070. /* 39 */ "IdxGT" OpHelp("key=r[P3@P4]"),
  28071. /* 40 */ "IdxLT" OpHelp("key=r[P3@P4]"),
  28072. /* 41 */ "IdxGE" OpHelp("key=r[P3@P4]"),
  28073. /* 42 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
  28074. /* 43 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
  28075. /* 44 */ "Program" OpHelp(""),
  28076. /* 45 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
  28077. /* 46 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
  28078. /* 47 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
  28079. /* 48 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
  28080. /* 49 */ "IncrVacuum" OpHelp(""),
  28081. /* 50 */ "VNext" OpHelp(""),
  28082. /* 51 */ "Init" OpHelp("Start at P2"),
  28083. /* 52 */ "Return" OpHelp(""),
  28084. /* 53 */ "EndCoroutine" OpHelp(""),
  28085. /* 54 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
  28086. /* 55 */ "Halt" OpHelp(""),
  28087. /* 56 */ "Integer" OpHelp("r[P2]=P1"),
  28088. /* 57 */ "Int64" OpHelp("r[P2]=P4"),
  28089. /* 58 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
  28090. /* 59 */ "Null" OpHelp("r[P2..P3]=NULL"),
  28091. /* 60 */ "SoftNull" OpHelp("r[P1]=NULL"),
  28092. /* 61 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
  28093. /* 62 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
  28094. /* 63 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
  28095. /* 64 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
  28096. /* 65 */ "SCopy" OpHelp("r[P2]=r[P1]"),
  28097. /* 66 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
  28098. /* 67 */ "ResultRow" OpHelp("output=r[P1@P2]"),
  28099. /* 68 */ "CollSeq" OpHelp(""),
  28100. /* 69 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
  28101. /* 70 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
  28102. /* 71 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
  28103. /* 72 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
  28104. /* 73 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
  28105. /* 74 */ "RealAffinity" OpHelp(""),
  28106. /* 75 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
  28107. /* 76 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
  28108. /* 77 */ "Ne" OpHelp("IF r[P3]!=r[P1]"),
  28109. /* 78 */ "Eq" OpHelp("IF r[P3]==r[P1]"),
  28110. /* 79 */ "Gt" OpHelp("IF r[P3]>r[P1]"),
  28111. /* 80 */ "Le" OpHelp("IF r[P3]<=r[P1]"),
  28112. /* 81 */ "Lt" OpHelp("IF r[P3]<r[P1]"),
  28113. /* 82 */ "Ge" OpHelp("IF r[P3]>=r[P1]"),
  28114. /* 83 */ "ElseNotEq" OpHelp(""),
  28115. /* 84 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
  28116. /* 85 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
  28117. /* 86 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
  28118. /* 87 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
  28119. /* 88 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
  28120. /* 89 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
  28121. /* 90 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
  28122. /* 91 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
  28123. /* 92 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
  28124. /* 93 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
  28125. /* 94 */ "Cast" OpHelp("affinity(r[P1])"),
  28126. /* 95 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
  28127. /* 96 */ "Permutation" OpHelp(""),
  28128. /* 97 */ "String8" OpHelp("r[P2]='P4'"),
  28129. /* 98 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
  28130. /* 99 */ "Column" OpHelp("r[P3]=PX"),
  28131. /* 100 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
  28132. /* 101 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
  28133. /* 102 */ "Count" OpHelp("r[P2]=count()"),
  28134. /* 103 */ "ReadCookie" OpHelp(""),
  28135. /* 104 */ "SetCookie" OpHelp(""),
  28136. /* 105 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
  28137. /* 106 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
  28138. /* 107 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
  28139. /* 108 */ "OpenDup" OpHelp(""),
  28140. /* 109 */ "OpenAutoindex" OpHelp("nColumn=P2"),
  28141. /* 110 */ "OpenEphemeral" OpHelp("nColumn=P2"),
  28142. /* 111 */ "SorterOpen" OpHelp(""),
  28143. /* 112 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
  28144. /* 113 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
  28145. /* 114 */ "Close" OpHelp(""),
  28146. /* 115 */ "ColumnsUsed" OpHelp(""),
  28147. /* 116 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
  28148. /* 117 */ "NewRowid" OpHelp("r[P2]=rowid"),
  28149. /* 118 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
  28150. /* 119 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
  28151. /* 120 */ "Delete" OpHelp(""),
  28152. /* 121 */ "ResetCount" OpHelp(""),
  28153. /* 122 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
  28154. /* 123 */ "SorterData" OpHelp("r[P2]=data"),
  28155. /* 124 */ "RowData" OpHelp("r[P2]=data"),
  28156. /* 125 */ "Rowid" OpHelp("r[P2]=rowid"),
  28157. /* 126 */ "NullRow" OpHelp(""),
  28158. /* 127 */ "SorterInsert" OpHelp("key=r[P2]"),
  28159. /* 128 */ "IdxInsert" OpHelp("key=r[P2]"),
  28160. /* 129 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
  28161. /* 130 */ "Seek" OpHelp("Move P3 to P1.rowid"),
  28162. /* 131 */ "IdxRowid" OpHelp("r[P2]=rowid"),
  28163. /* 132 */ "Real" OpHelp("r[P2]=P4"),
  28164. /* 133 */ "Destroy" OpHelp(""),
  28165. /* 134 */ "Clear" OpHelp(""),
  28166. /* 135 */ "ResetSorter" OpHelp(""),
  28167. /* 136 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
  28168. /* 137 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
  28169. /* 138 */ "SqlExec" OpHelp(""),
  28170. /* 139 */ "ParseSchema" OpHelp(""),
  28171. /* 140 */ "LoadAnalysis" OpHelp(""),
  28172. /* 141 */ "DropTable" OpHelp(""),
  28173. /* 142 */ "DropIndex" OpHelp(""),
  28174. /* 143 */ "DropTrigger" OpHelp(""),
  28175. /* 144 */ "IntegrityCk" OpHelp(""),
  28176. /* 145 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
  28177. /* 146 */ "Param" OpHelp(""),
  28178. /* 147 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
  28179. /* 148 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
  28180. /* 149 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
  28181. /* 150 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"),
  28182. /* 151 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
  28183. /* 152 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
  28184. /* 153 */ "Expire" OpHelp(""),
  28185. /* 154 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
  28186. /* 155 */ "VBegin" OpHelp(""),
  28187. /* 156 */ "VCreate" OpHelp(""),
  28188. /* 157 */ "VDestroy" OpHelp(""),
  28189. /* 158 */ "VOpen" OpHelp(""),
  28190. /* 159 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
  28191. /* 160 */ "VRename" OpHelp(""),
  28192. /* 161 */ "Pagecount" OpHelp(""),
  28193. /* 162 */ "MaxPgcnt" OpHelp(""),
  28194. /* 163 */ "CursorHint" OpHelp(""),
  28195. /* 164 */ "Noop" OpHelp(""),
  28196. /* 165 */ "Explain" OpHelp(""),
  28197. };
  28198. return azName[i];
  28199. }
  28200. #endif
  28201. /************** End of opcodes.c *********************************************/
  28202. #include "rtthread_vfs.c"
  28203. /************** Begin file os_unix.c *****************************************/
  28204. /*
  28205. ** 2004 May 22
  28206. **
  28207. ** The author disclaims copyright to this source code. In place of
  28208. ** a legal notice, here is a blessing:
  28209. **
  28210. ** May you do good and not evil.
  28211. ** May you find forgiveness for yourself and forgive others.
  28212. ** May you share freely, never taking more than you give.
  28213. **
  28214. ******************************************************************************
  28215. **
  28216. ** This file contains the VFS implementation for unix-like operating systems
  28217. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  28218. **
  28219. ** There are actually several different VFS implementations in this file.
  28220. ** The differences are in the way that file locking is done. The default
  28221. ** implementation uses Posix Advisory Locks. Alternative implementations
  28222. ** use flock(), dot-files, various proprietary locking schemas, or simply
  28223. ** skip locking all together.
  28224. **
  28225. ** This source file is organized into divisions where the logic for various
  28226. ** subfunctions is contained within the appropriate division. PLEASE
  28227. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  28228. ** in the correct division and should be clearly labeled.
  28229. **
  28230. ** The layout of divisions is as follows:
  28231. **
  28232. ** * General-purpose declarations and utility functions.
  28233. ** * Unique file ID logic used by VxWorks.
  28234. ** * Various locking primitive implementations (all except proxy locking):
  28235. ** + for Posix Advisory Locks
  28236. ** + for no-op locks
  28237. ** + for dot-file locks
  28238. ** + for flock() locking
  28239. ** + for named semaphore locks (VxWorks only)
  28240. ** + for AFP filesystem locks (MacOSX only)
  28241. ** * sqlite3_file methods not associated with locking.
  28242. ** * Definitions of sqlite3_io_methods objects for all locking
  28243. ** methods plus "finder" functions for each locking method.
  28244. ** * sqlite3_vfs method implementations.
  28245. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  28246. ** * Definitions of sqlite3_vfs objects for all locking methods
  28247. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  28248. */
  28249. /* #include "sqliteInt.h" */
  28250. #if SQLITE_OS_UNIX /* This file is used on unix only */
  28251. /*
  28252. ** There are various methods for file locking used for concurrency
  28253. ** control:
  28254. **
  28255. ** 1. POSIX locking (the default),
  28256. ** 2. No locking,
  28257. ** 3. Dot-file locking,
  28258. ** 4. flock() locking,
  28259. ** 5. AFP locking (OSX only),
  28260. ** 6. Named POSIX semaphores (VXWorks only),
  28261. ** 7. proxy locking. (OSX only)
  28262. **
  28263. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  28264. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  28265. ** selection of the appropriate locking style based on the filesystem
  28266. ** where the database is located.
  28267. */
  28268. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  28269. # if defined(__APPLE__)
  28270. # define SQLITE_ENABLE_LOCKING_STYLE 1
  28271. # else
  28272. # define SQLITE_ENABLE_LOCKING_STYLE 0
  28273. # endif
  28274. #endif
  28275. /* Use pread() and pwrite() if they are available */
  28276. #if defined(__APPLE__)
  28277. # define HAVE_PREAD 1
  28278. # define HAVE_PWRITE 1
  28279. #endif
  28280. #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
  28281. # undef USE_PREAD
  28282. # define USE_PREAD64 1
  28283. #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
  28284. # undef USE_PREAD64
  28285. # define USE_PREAD 1
  28286. #endif
  28287. /*
  28288. ** standard include files.
  28289. */
  28290. #include <sys/types.h>
  28291. #include <sys/stat.h>
  28292. #include <fcntl.h>
  28293. #include <unistd.h>
  28294. /* #include <time.h> */
  28295. #include <sys/time.h>
  28296. #include <errno.h>
  28297. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  28298. # include <sys/mman.h>
  28299. #endif
  28300. #if SQLITE_ENABLE_LOCKING_STYLE
  28301. # include <sys/ioctl.h>
  28302. # include <sys/file.h>
  28303. # include <sys/param.h>
  28304. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  28305. #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
  28306. (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
  28307. # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
  28308. && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
  28309. # define HAVE_GETHOSTUUID 1
  28310. # else
  28311. # warning "gethostuuid() is disabled."
  28312. # endif
  28313. #endif
  28314. #if OS_VXWORKS
  28315. /* # include <sys/ioctl.h> */
  28316. # include <semaphore.h>
  28317. # include <limits.h>
  28318. #endif /* OS_VXWORKS */
  28319. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  28320. # include <sys/mount.h>
  28321. #endif
  28322. #ifdef HAVE_UTIME
  28323. # include <utime.h>
  28324. #endif
  28325. /*
  28326. ** Allowed values of unixFile.fsFlags
  28327. */
  28328. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  28329. /*
  28330. ** If we are to be thread-safe, include the pthreads header and define
  28331. ** the SQLITE_UNIX_THREADS macro.
  28332. */
  28333. #if SQLITE_THREADSAFE
  28334. /* # include <pthread.h> */
  28335. # define SQLITE_UNIX_THREADS 1
  28336. #endif
  28337. /*
  28338. ** Default permissions when creating a new file
  28339. */
  28340. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  28341. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  28342. #endif
  28343. /*
  28344. ** Default permissions when creating auto proxy dir
  28345. */
  28346. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  28347. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  28348. #endif
  28349. /*
  28350. ** Maximum supported path-length.
  28351. */
  28352. #define MAX_PATHNAME 512
  28353. /*
  28354. ** Maximum supported symbolic links
  28355. */
  28356. #define SQLITE_MAX_SYMLINKS 100
  28357. /* Always cast the getpid() return type for compatibility with
  28358. ** kernel modules in VxWorks. */
  28359. #define osGetpid(X) (pid_t)getpid()
  28360. /*
  28361. ** Only set the lastErrno if the error code is a real error and not
  28362. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  28363. */
  28364. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  28365. /* Forward references */
  28366. typedef struct unixShm unixShm; /* Connection shared memory */
  28367. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  28368. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  28369. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  28370. /*
  28371. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  28372. ** cannot be closed immediately. In these cases, instances of the following
  28373. ** structure are used to store the file descriptor while waiting for an
  28374. ** opportunity to either close or reuse it.
  28375. */
  28376. struct UnixUnusedFd {
  28377. int fd; /* File descriptor to close */
  28378. int flags; /* Flags this file descriptor was opened with */
  28379. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  28380. };
  28381. /*
  28382. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  28383. ** VFS implementations.
  28384. */
  28385. typedef struct unixFile unixFile;
  28386. struct unixFile {
  28387. sqlite3_io_methods const *pMethod; /* Always the first entry */
  28388. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  28389. unixInodeInfo *pInode; /* Info about locks on this inode */
  28390. int h; /* The file descriptor */
  28391. unsigned char eFileLock; /* The type of lock held on this fd */
  28392. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  28393. int lastErrno; /* The unix errno from last I/O error */
  28394. void *lockingContext; /* Locking style specific state */
  28395. UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
  28396. const char *zPath; /* Name of the file */
  28397. unixShm *pShm; /* Shared memory segment information */
  28398. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  28399. #if SQLITE_MAX_MMAP_SIZE>0
  28400. int nFetchOut; /* Number of outstanding xFetch refs */
  28401. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  28402. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  28403. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  28404. void *pMapRegion; /* Memory mapped region */
  28405. #endif
  28406. #ifdef __QNXNTO__
  28407. int sectorSize; /* Device sector size */
  28408. int deviceCharacteristics; /* Precomputed device characteristics */
  28409. #endif
  28410. #if SQLITE_ENABLE_LOCKING_STYLE
  28411. int openFlags; /* The flags specified at open() */
  28412. #endif
  28413. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  28414. unsigned fsFlags; /* cached details from statfs() */
  28415. #endif
  28416. #if OS_VXWORKS
  28417. struct vxworksFileId *pId; /* Unique file ID */
  28418. #endif
  28419. #ifdef SQLITE_DEBUG
  28420. /* The next group of variables are used to track whether or not the
  28421. ** transaction counter in bytes 24-27 of database files are updated
  28422. ** whenever any part of the database changes. An assertion fault will
  28423. ** occur if a file is updated without also updating the transaction
  28424. ** counter. This test is made to avoid new problems similar to the
  28425. ** one described by ticket #3584.
  28426. */
  28427. unsigned char transCntrChng; /* True if the transaction counter changed */
  28428. unsigned char dbUpdate; /* True if any part of database file changed */
  28429. unsigned char inNormalWrite; /* True if in a normal write operation */
  28430. #endif
  28431. #ifdef SQLITE_TEST
  28432. /* In test mode, increase the size of this structure a bit so that
  28433. ** it is larger than the struct CrashFile defined in test6.c.
  28434. */
  28435. char aPadding[32];
  28436. #endif
  28437. };
  28438. /* This variable holds the process id (pid) from when the xRandomness()
  28439. ** method was called. If xOpen() is called from a different process id,
  28440. ** indicating that a fork() has occurred, the PRNG will be reset.
  28441. */
  28442. static pid_t randomnessPid = 0;
  28443. /*
  28444. ** Allowed values for the unixFile.ctrlFlags bitmask:
  28445. */
  28446. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  28447. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  28448. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  28449. #ifndef SQLITE_DISABLE_DIRSYNC
  28450. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  28451. #else
  28452. # define UNIXFILE_DIRSYNC 0x00
  28453. #endif
  28454. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  28455. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  28456. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  28457. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  28458. /*
  28459. ** Include code that is common to all os_*.c files
  28460. */
  28461. /************** Include os_common.h in the middle of os_unix.c ***************/
  28462. /************** Begin file os_common.h ***************************************/
  28463. /*
  28464. ** 2004 May 22
  28465. **
  28466. ** The author disclaims copyright to this source code. In place of
  28467. ** a legal notice, here is a blessing:
  28468. **
  28469. ** May you do good and not evil.
  28470. ** May you find forgiveness for yourself and forgive others.
  28471. ** May you share freely, never taking more than you give.
  28472. **
  28473. ******************************************************************************
  28474. **
  28475. ** This file contains macros and a little bit of code that is common to
  28476. ** all of the platform-specific files (os_*.c) and is #included into those
  28477. ** files.
  28478. **
  28479. ** This file should be #included by the os_*.c files only. It is not a
  28480. ** general purpose header file.
  28481. */
  28482. #ifndef _OS_COMMON_H_
  28483. #define _OS_COMMON_H_
  28484. /*
  28485. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  28486. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  28487. ** switch. The following code should catch this problem at compile-time.
  28488. */
  28489. #ifdef MEMORY_DEBUG
  28490. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  28491. #endif
  28492. /*
  28493. ** Macros for performance tracing. Normally turned off. Only works
  28494. ** on i486 hardware.
  28495. */
  28496. #ifdef SQLITE_PERFORMANCE_TRACE
  28497. /*
  28498. ** hwtime.h contains inline assembler code for implementing
  28499. ** high-performance timing routines.
  28500. */
  28501. /************** Include hwtime.h in the middle of os_common.h ****************/
  28502. /************** Begin file hwtime.h ******************************************/
  28503. /*
  28504. ** 2008 May 27
  28505. **
  28506. ** The author disclaims copyright to this source code. In place of
  28507. ** a legal notice, here is a blessing:
  28508. **
  28509. ** May you do good and not evil.
  28510. ** May you find forgiveness for yourself and forgive others.
  28511. ** May you share freely, never taking more than you give.
  28512. **
  28513. ******************************************************************************
  28514. **
  28515. ** This file contains inline asm code for retrieving "high-performance"
  28516. ** counters for x86 class CPUs.
  28517. */
  28518. #ifndef SQLITE_HWTIME_H
  28519. #define SQLITE_HWTIME_H
  28520. /*
  28521. ** The following routine only works on pentium-class (or newer) processors.
  28522. ** It uses the RDTSC opcode to read the cycle count value out of the
  28523. ** processor and returns that value. This can be used for high-res
  28524. ** profiling.
  28525. */
  28526. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  28527. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  28528. #if defined(__GNUC__)
  28529. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  28530. unsigned int lo, hi;
  28531. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  28532. return (sqlite_uint64)hi << 32 | lo;
  28533. }
  28534. #elif defined(_MSC_VER)
  28535. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  28536. __asm {
  28537. rdtsc
  28538. ret ; return value at EDX:EAX
  28539. }
  28540. }
  28541. #endif
  28542. #elif (defined(__GNUC__) && defined(__x86_64__))
  28543. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  28544. unsigned long val;
  28545. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  28546. return val;
  28547. }
  28548. #elif (defined(__GNUC__) && defined(__ppc__))
  28549. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  28550. unsigned long long retval;
  28551. unsigned long junk;
  28552. __asm__ __volatile__ ("\n\
  28553. 1: mftbu %1\n\
  28554. mftb %L0\n\
  28555. mftbu %0\n\
  28556. cmpw %0,%1\n\
  28557. bne 1b"
  28558. : "=r" (retval), "=r" (junk));
  28559. return retval;
  28560. }
  28561. #else
  28562. #error Need implementation of sqlite3Hwtime() for your platform.
  28563. /*
  28564. ** To compile without implementing sqlite3Hwtime() for your platform,
  28565. ** you can remove the above #error and use the following
  28566. ** stub function. You will lose timing support for many
  28567. ** of the debugging and testing utilities, but it should at
  28568. ** least compile and run.
  28569. */
  28570. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  28571. #endif
  28572. #endif /* !defined(SQLITE_HWTIME_H) */
  28573. /************** End of hwtime.h **********************************************/
  28574. /************** Continuing where we left off in os_common.h ******************/
  28575. static sqlite_uint64 g_start;
  28576. static sqlite_uint64 g_elapsed;
  28577. #define TIMER_START g_start=sqlite3Hwtime()
  28578. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  28579. #define TIMER_ELAPSED g_elapsed
  28580. #else
  28581. #define TIMER_START
  28582. #define TIMER_END
  28583. #define TIMER_ELAPSED ((sqlite_uint64)0)
  28584. #endif
  28585. /*
  28586. ** If we compile with the SQLITE_TEST macro set, then the following block
  28587. ** of code will give us the ability to simulate a disk I/O error. This
  28588. ** is used for testing the I/O recovery logic.
  28589. */
  28590. #if defined(SQLITE_TEST)
  28591. SQLITE_API extern int sqlite3_io_error_hit;
  28592. SQLITE_API extern int sqlite3_io_error_hardhit;
  28593. SQLITE_API extern int sqlite3_io_error_pending;
  28594. SQLITE_API extern int sqlite3_io_error_persist;
  28595. SQLITE_API extern int sqlite3_io_error_benign;
  28596. SQLITE_API extern int sqlite3_diskfull_pending;
  28597. SQLITE_API extern int sqlite3_diskfull;
  28598. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  28599. #define SimulateIOError(CODE) \
  28600. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  28601. || sqlite3_io_error_pending-- == 1 ) \
  28602. { local_ioerr(); CODE; }
  28603. static void local_ioerr(){
  28604. IOTRACE(("IOERR\n"));
  28605. sqlite3_io_error_hit++;
  28606. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  28607. }
  28608. #define SimulateDiskfullError(CODE) \
  28609. if( sqlite3_diskfull_pending ){ \
  28610. if( sqlite3_diskfull_pending == 1 ){ \
  28611. local_ioerr(); \
  28612. sqlite3_diskfull = 1; \
  28613. sqlite3_io_error_hit = 1; \
  28614. CODE; \
  28615. }else{ \
  28616. sqlite3_diskfull_pending--; \
  28617. } \
  28618. }
  28619. #else
  28620. #define SimulateIOErrorBenign(X)
  28621. #define SimulateIOError(A)
  28622. #define SimulateDiskfullError(A)
  28623. #endif /* defined(SQLITE_TEST) */
  28624. /*
  28625. ** When testing, keep a count of the number of open files.
  28626. */
  28627. #if defined(SQLITE_TEST)
  28628. SQLITE_API extern int sqlite3_open_file_count;
  28629. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  28630. #else
  28631. #define OpenCounter(X)
  28632. #endif /* defined(SQLITE_TEST) */
  28633. #endif /* !defined(_OS_COMMON_H_) */
  28634. /************** End of os_common.h *******************************************/
  28635. /************** Continuing where we left off in os_unix.c ********************/
  28636. /*
  28637. ** Define various macros that are missing from some systems.
  28638. */
  28639. #ifndef O_LARGEFILE
  28640. # define O_LARGEFILE 0
  28641. #endif
  28642. #ifdef SQLITE_DISABLE_LFS
  28643. # undef O_LARGEFILE
  28644. # define O_LARGEFILE 0
  28645. #endif
  28646. #ifndef O_NOFOLLOW
  28647. # define O_NOFOLLOW 0
  28648. #endif
  28649. #ifndef O_BINARY
  28650. # define O_BINARY 0
  28651. #endif
  28652. /*
  28653. ** The threadid macro resolves to the thread-id or to 0. Used for
  28654. ** testing and debugging only.
  28655. */
  28656. #if SQLITE_THREADSAFE
  28657. #define threadid pthread_self()
  28658. #else
  28659. #define threadid 0
  28660. #endif
  28661. /*
  28662. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  28663. */
  28664. #if !defined(HAVE_MREMAP)
  28665. # if defined(__linux__) && defined(_GNU_SOURCE)
  28666. # define HAVE_MREMAP 1
  28667. # else
  28668. # define HAVE_MREMAP 0
  28669. # endif
  28670. #endif
  28671. /*
  28672. ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
  28673. ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
  28674. */
  28675. #ifdef __ANDROID__
  28676. # define lseek lseek64
  28677. #endif
  28678. /*
  28679. ** Different Unix systems declare open() in different ways. Same use
  28680. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  28681. ** The difference is important when using a pointer to the function.
  28682. **
  28683. ** The safest way to deal with the problem is to always use this wrapper
  28684. ** which always has the same well-defined interface.
  28685. */
  28686. static int posixOpen(const char *zFile, int flags, int mode){
  28687. return open(zFile, flags, mode);
  28688. }
  28689. /* Forward reference */
  28690. static int openDirectory(const char*, int*);
  28691. static int unixGetpagesize(void);
  28692. /*
  28693. ** Many system calls are accessed through pointer-to-functions so that
  28694. ** they may be overridden at runtime to facilitate fault injection during
  28695. ** testing and sandboxing. The following array holds the names and pointers
  28696. ** to all overrideable system calls.
  28697. */
  28698. static struct unix_syscall {
  28699. const char *zName; /* Name of the system call */
  28700. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  28701. sqlite3_syscall_ptr pDefault; /* Default value */
  28702. } aSyscall[] = {
  28703. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  28704. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  28705. { "close", (sqlite3_syscall_ptr)close, 0 },
  28706. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  28707. { "access", (sqlite3_syscall_ptr)access, 0 },
  28708. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  28709. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  28710. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  28711. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  28712. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  28713. /*
  28714. ** The DJGPP compiler environment looks mostly like Unix, but it
  28715. ** lacks the fcntl() system call. So redefine fcntl() to be something
  28716. ** that always succeeds. This means that locking does not occur under
  28717. ** DJGPP. But it is DOS - what did you expect?
  28718. */
  28719. #ifdef __DJGPP__
  28720. { "fstat", 0, 0 },
  28721. #define osFstat(a,b,c) 0
  28722. #else
  28723. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  28724. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  28725. #endif
  28726. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  28727. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  28728. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  28729. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  28730. { "read", (sqlite3_syscall_ptr)read, 0 },
  28731. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  28732. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  28733. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  28734. #else
  28735. { "pread", (sqlite3_syscall_ptr)0, 0 },
  28736. #endif
  28737. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  28738. #if defined(USE_PREAD64)
  28739. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  28740. #else
  28741. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  28742. #endif
  28743. #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
  28744. { "write", (sqlite3_syscall_ptr)write, 0 },
  28745. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  28746. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  28747. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  28748. #else
  28749. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  28750. #endif
  28751. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  28752. aSyscall[12].pCurrent)
  28753. #if defined(USE_PREAD64)
  28754. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  28755. #else
  28756. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  28757. #endif
  28758. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
  28759. aSyscall[13].pCurrent)
  28760. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  28761. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  28762. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  28763. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  28764. #else
  28765. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  28766. #endif
  28767. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  28768. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  28769. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  28770. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  28771. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  28772. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  28773. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  28774. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  28775. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  28776. #if defined(HAVE_FCHOWN)
  28777. { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
  28778. #else
  28779. { "fchown", (sqlite3_syscall_ptr)0, 0 },
  28780. #endif
  28781. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  28782. { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
  28783. #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
  28784. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  28785. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  28786. #else
  28787. { "mmap", (sqlite3_syscall_ptr)0, 0 },
  28788. #endif
  28789. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
  28790. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  28791. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  28792. #else
  28793. { "munmap", (sqlite3_syscall_ptr)0, 0 },
  28794. #endif
  28795. #define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
  28796. #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  28797. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  28798. #else
  28799. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  28800. #endif
  28801. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
  28802. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  28803. { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
  28804. #else
  28805. { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
  28806. #endif
  28807. #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
  28808. #if defined(HAVE_READLINK)
  28809. { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
  28810. #else
  28811. { "readlink", (sqlite3_syscall_ptr)0, 0 },
  28812. #endif
  28813. #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
  28814. #if defined(HAVE_LSTAT)
  28815. { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
  28816. #else
  28817. { "lstat", (sqlite3_syscall_ptr)0, 0 },
  28818. #endif
  28819. #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
  28820. }; /* End of the overrideable system calls */
  28821. /*
  28822. ** On some systems, calls to fchown() will trigger a message in a security
  28823. ** log if they come from non-root processes. So avoid calling fchown() if
  28824. ** we are not running as root.
  28825. */
  28826. static int robustFchown(int fd, uid_t uid, gid_t gid){
  28827. #if defined(HAVE_FCHOWN)
  28828. return osGeteuid() ? 0 : osFchown(fd,uid,gid);
  28829. #else
  28830. return 0;
  28831. #endif
  28832. }
  28833. /*
  28834. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  28835. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  28836. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  28837. ** system call named zName.
  28838. */
  28839. static int unixSetSystemCall(
  28840. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  28841. const char *zName, /* Name of system call to override */
  28842. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  28843. ){
  28844. unsigned int i;
  28845. int rc = SQLITE_NOTFOUND;
  28846. UNUSED_PARAMETER(pNotUsed);
  28847. if( zName==0 ){
  28848. /* If no zName is given, restore all system calls to their default
  28849. ** settings and return NULL
  28850. */
  28851. rc = SQLITE_OK;
  28852. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  28853. if( aSyscall[i].pDefault ){
  28854. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  28855. }
  28856. }
  28857. }else{
  28858. /* If zName is specified, operate on only the one system call
  28859. ** specified.
  28860. */
  28861. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  28862. if( strcmp(zName, aSyscall[i].zName)==0 ){
  28863. if( aSyscall[i].pDefault==0 ){
  28864. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  28865. }
  28866. rc = SQLITE_OK;
  28867. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  28868. aSyscall[i].pCurrent = pNewFunc;
  28869. break;
  28870. }
  28871. }
  28872. }
  28873. return rc;
  28874. }
  28875. /*
  28876. ** Return the value of a system call. Return NULL if zName is not a
  28877. ** recognized system call name. NULL is also returned if the system call
  28878. ** is currently undefined.
  28879. */
  28880. static sqlite3_syscall_ptr unixGetSystemCall(
  28881. sqlite3_vfs *pNotUsed,
  28882. const char *zName
  28883. ){
  28884. unsigned int i;
  28885. UNUSED_PARAMETER(pNotUsed);
  28886. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  28887. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  28888. }
  28889. return 0;
  28890. }
  28891. /*
  28892. ** Return the name of the first system call after zName. If zName==NULL
  28893. ** then return the name of the first system call. Return NULL if zName
  28894. ** is the last system call or if zName is not the name of a valid
  28895. ** system call.
  28896. */
  28897. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  28898. int i = -1;
  28899. UNUSED_PARAMETER(p);
  28900. if( zName ){
  28901. for(i=0; i<ArraySize(aSyscall)-1; i++){
  28902. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  28903. }
  28904. }
  28905. for(i++; i<ArraySize(aSyscall); i++){
  28906. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  28907. }
  28908. return 0;
  28909. }
  28910. /*
  28911. ** Do not accept any file descriptor less than this value, in order to avoid
  28912. ** opening database file using file descriptors that are commonly used for
  28913. ** standard input, output, and error.
  28914. */
  28915. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  28916. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  28917. #endif
  28918. /*
  28919. ** Invoke open(). Do so multiple times, until it either succeeds or
  28920. ** fails for some reason other than EINTR.
  28921. **
  28922. ** If the file creation mode "m" is 0 then set it to the default for
  28923. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  28924. ** 0644) as modified by the system umask. If m is not 0, then
  28925. ** make the file creation mode be exactly m ignoring the umask.
  28926. **
  28927. ** The m parameter will be non-zero only when creating -wal, -journal,
  28928. ** and -shm files. We want those files to have *exactly* the same
  28929. ** permissions as their original database, unadulterated by the umask.
  28930. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  28931. ** transaction crashes and leaves behind hot journals, then any
  28932. ** process that is able to write to the database will also be able to
  28933. ** recover the hot journals.
  28934. */
  28935. static int robust_open(const char *z, int f, mode_t m){
  28936. int fd;
  28937. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  28938. while(1){
  28939. #if defined(O_CLOEXEC)
  28940. fd = osOpen(z,f|O_CLOEXEC,m2);
  28941. #else
  28942. fd = osOpen(z,f,m2);
  28943. #endif
  28944. if( fd<0 ){
  28945. if( errno==EINTR ) continue;
  28946. break;
  28947. }
  28948. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  28949. osClose(fd);
  28950. sqlite3_log(SQLITE_WARNING,
  28951. "attempt to open \"%s\" as file descriptor %d", z, fd);
  28952. fd = -1;
  28953. if( osOpen("/dev/null", f, m)<0 ) break;
  28954. }
  28955. if( fd>=0 ){
  28956. if( m!=0 ){
  28957. struct stat statbuf;
  28958. if( osFstat(fd, &statbuf)==0
  28959. && statbuf.st_size==0
  28960. && (statbuf.st_mode&0777)!=m
  28961. ){
  28962. osFchmod(fd, m);
  28963. }
  28964. }
  28965. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  28966. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  28967. #endif
  28968. }
  28969. return fd;
  28970. }
  28971. /*
  28972. ** Helper functions to obtain and relinquish the global mutex. The
  28973. ** global mutex is used to protect the unixInodeInfo and
  28974. ** vxworksFileId objects used by this file, all of which may be
  28975. ** shared by multiple threads.
  28976. **
  28977. ** Function unixMutexHeld() is used to assert() that the global mutex
  28978. ** is held when required. This function is only used as part of assert()
  28979. ** statements. e.g.
  28980. **
  28981. ** unixEnterMutex()
  28982. ** assert( unixMutexHeld() );
  28983. ** unixEnterLeave()
  28984. */
  28985. static void unixEnterMutex(void){
  28986. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  28987. }
  28988. static void unixLeaveMutex(void){
  28989. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  28990. }
  28991. #ifdef SQLITE_DEBUG
  28992. static int unixMutexHeld(void) {
  28993. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  28994. }
  28995. #endif
  28996. #ifdef SQLITE_HAVE_OS_TRACE
  28997. /*
  28998. ** Helper function for printing out trace information from debugging
  28999. ** binaries. This returns the string representation of the supplied
  29000. ** integer lock-type.
  29001. */
  29002. static const char *azFileLock(int eFileLock){
  29003. switch( eFileLock ){
  29004. case NO_LOCK: return "NONE";
  29005. case SHARED_LOCK: return "SHARED";
  29006. case RESERVED_LOCK: return "RESERVED";
  29007. case PENDING_LOCK: return "PENDING";
  29008. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  29009. }
  29010. return "ERROR";
  29011. }
  29012. #endif
  29013. #ifdef SQLITE_LOCK_TRACE
  29014. /*
  29015. ** Print out information about all locking operations.
  29016. **
  29017. ** This routine is used for troubleshooting locks on multithreaded
  29018. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  29019. ** command-line option on the compiler. This code is normally
  29020. ** turned off.
  29021. */
  29022. static int lockTrace(int fd, int op, struct flock *p){
  29023. char *zOpName, *zType;
  29024. int s;
  29025. int savedErrno;
  29026. if( op==F_GETLK ){
  29027. zOpName = "GETLK";
  29028. }else if( op==F_SETLK ){
  29029. zOpName = "SETLK";
  29030. }else{
  29031. s = osFcntl(fd, op, p);
  29032. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  29033. return s;
  29034. }
  29035. if( p->l_type==F_RDLCK ){
  29036. zType = "RDLCK";
  29037. }else if( p->l_type==F_WRLCK ){
  29038. zType = "WRLCK";
  29039. }else if( p->l_type==F_UNLCK ){
  29040. zType = "UNLCK";
  29041. }else{
  29042. assert( 0 );
  29043. }
  29044. assert( p->l_whence==SEEK_SET );
  29045. s = osFcntl(fd, op, p);
  29046. savedErrno = errno;
  29047. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  29048. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  29049. (int)p->l_pid, s);
  29050. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  29051. struct flock l2;
  29052. l2 = *p;
  29053. osFcntl(fd, F_GETLK, &l2);
  29054. if( l2.l_type==F_RDLCK ){
  29055. zType = "RDLCK";
  29056. }else if( l2.l_type==F_WRLCK ){
  29057. zType = "WRLCK";
  29058. }else if( l2.l_type==F_UNLCK ){
  29059. zType = "UNLCK";
  29060. }else{
  29061. assert( 0 );
  29062. }
  29063. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  29064. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  29065. }
  29066. errno = savedErrno;
  29067. return s;
  29068. }
  29069. #undef osFcntl
  29070. #define osFcntl lockTrace
  29071. #endif /* SQLITE_LOCK_TRACE */
  29072. /*
  29073. ** Retry ftruncate() calls that fail due to EINTR
  29074. **
  29075. ** All calls to ftruncate() within this file should be made through
  29076. ** this wrapper. On the Android platform, bypassing the logic below
  29077. ** could lead to a corrupt database.
  29078. */
  29079. static int robust_ftruncate(int h, sqlite3_int64 sz){
  29080. int rc;
  29081. #ifdef __ANDROID__
  29082. /* On Android, ftruncate() always uses 32-bit offsets, even if
  29083. ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
  29084. ** truncate a file to any size larger than 2GiB. Silently ignore any
  29085. ** such attempts. */
  29086. if( sz>(sqlite3_int64)0x7FFFFFFF ){
  29087. rc = SQLITE_OK;
  29088. }else
  29089. #endif
  29090. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  29091. return rc;
  29092. }
  29093. /*
  29094. ** This routine translates a standard POSIX errno code into something
  29095. ** useful to the clients of the sqlite3 functions. Specifically, it is
  29096. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  29097. ** and a variety of "please close the file descriptor NOW" errors into
  29098. ** SQLITE_IOERR
  29099. **
  29100. ** Errors during initialization of locks, or file system support for locks,
  29101. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  29102. */
  29103. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  29104. assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  29105. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  29106. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  29107. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
  29108. switch (posixError) {
  29109. case EACCES:
  29110. case EAGAIN:
  29111. case ETIMEDOUT:
  29112. case EBUSY:
  29113. case EINTR:
  29114. case ENOLCK:
  29115. /* random NFS retry error, unless during file system support
  29116. * introspection, in which it actually means what it says */
  29117. return SQLITE_BUSY;
  29118. case EPERM:
  29119. return SQLITE_PERM;
  29120. default:
  29121. return sqliteIOErr;
  29122. }
  29123. }
  29124. /******************************************************************************
  29125. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  29126. **
  29127. ** On most versions of unix, we can get a unique ID for a file by concatenating
  29128. ** the device number and the inode number. But this does not work on VxWorks.
  29129. ** On VxWorks, a unique file id must be based on the canonical filename.
  29130. **
  29131. ** A pointer to an instance of the following structure can be used as a
  29132. ** unique file ID in VxWorks. Each instance of this structure contains
  29133. ** a copy of the canonical filename. There is also a reference count.
  29134. ** The structure is reclaimed when the number of pointers to it drops to
  29135. ** zero.
  29136. **
  29137. ** There are never very many files open at one time and lookups are not
  29138. ** a performance-critical path, so it is sufficient to put these
  29139. ** structures on a linked list.
  29140. */
  29141. struct vxworksFileId {
  29142. struct vxworksFileId *pNext; /* Next in a list of them all */
  29143. int nRef; /* Number of references to this one */
  29144. int nName; /* Length of the zCanonicalName[] string */
  29145. char *zCanonicalName; /* Canonical filename */
  29146. };
  29147. #if OS_VXWORKS
  29148. /*
  29149. ** All unique filenames are held on a linked list headed by this
  29150. ** variable:
  29151. */
  29152. static struct vxworksFileId *vxworksFileList = 0;
  29153. /*
  29154. ** Simplify a filename into its canonical form
  29155. ** by making the following changes:
  29156. **
  29157. ** * removing any trailing and duplicate /
  29158. ** * convert /./ into just /
  29159. ** * convert /A/../ where A is any simple name into just /
  29160. **
  29161. ** Changes are made in-place. Return the new name length.
  29162. **
  29163. ** The original filename is in z[0..n-1]. Return the number of
  29164. ** characters in the simplified name.
  29165. */
  29166. static int vxworksSimplifyName(char *z, int n){
  29167. int i, j;
  29168. while( n>1 && z[n-1]=='/' ){ n--; }
  29169. for(i=j=0; i<n; i++){
  29170. if( z[i]=='/' ){
  29171. if( z[i+1]=='/' ) continue;
  29172. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  29173. i += 1;
  29174. continue;
  29175. }
  29176. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  29177. while( j>0 && z[j-1]!='/' ){ j--; }
  29178. if( j>0 ){ j--; }
  29179. i += 2;
  29180. continue;
  29181. }
  29182. }
  29183. z[j++] = z[i];
  29184. }
  29185. z[j] = 0;
  29186. return j;
  29187. }
  29188. /*
  29189. ** Find a unique file ID for the given absolute pathname. Return
  29190. ** a pointer to the vxworksFileId object. This pointer is the unique
  29191. ** file ID.
  29192. **
  29193. ** The nRef field of the vxworksFileId object is incremented before
  29194. ** the object is returned. A new vxworksFileId object is created
  29195. ** and added to the global list if necessary.
  29196. **
  29197. ** If a memory allocation error occurs, return NULL.
  29198. */
  29199. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  29200. struct vxworksFileId *pNew; /* search key and new file ID */
  29201. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  29202. int n; /* Length of zAbsoluteName string */
  29203. assert( zAbsoluteName[0]=='/' );
  29204. n = (int)strlen(zAbsoluteName);
  29205. pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
  29206. if( pNew==0 ) return 0;
  29207. pNew->zCanonicalName = (char*)&pNew[1];
  29208. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  29209. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  29210. /* Search for an existing entry that matching the canonical name.
  29211. ** If found, increment the reference count and return a pointer to
  29212. ** the existing file ID.
  29213. */
  29214. unixEnterMutex();
  29215. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  29216. if( pCandidate->nName==n
  29217. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  29218. ){
  29219. sqlite3_free(pNew);
  29220. pCandidate->nRef++;
  29221. unixLeaveMutex();
  29222. return pCandidate;
  29223. }
  29224. }
  29225. /* No match was found. We will make a new file ID */
  29226. pNew->nRef = 1;
  29227. pNew->nName = n;
  29228. pNew->pNext = vxworksFileList;
  29229. vxworksFileList = pNew;
  29230. unixLeaveMutex();
  29231. return pNew;
  29232. }
  29233. /*
  29234. ** Decrement the reference count on a vxworksFileId object. Free
  29235. ** the object when the reference count reaches zero.
  29236. */
  29237. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  29238. unixEnterMutex();
  29239. assert( pId->nRef>0 );
  29240. pId->nRef--;
  29241. if( pId->nRef==0 ){
  29242. struct vxworksFileId **pp;
  29243. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  29244. assert( *pp==pId );
  29245. *pp = pId->pNext;
  29246. sqlite3_free(pId);
  29247. }
  29248. unixLeaveMutex();
  29249. }
  29250. #endif /* OS_VXWORKS */
  29251. /*************** End of Unique File ID Utility Used By VxWorks ****************
  29252. ******************************************************************************/
  29253. /******************************************************************************
  29254. *************************** Posix Advisory Locking ****************************
  29255. **
  29256. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  29257. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  29258. ** sets or clears a lock, that operation overrides any prior locks set
  29259. ** by the same process. It does not explicitly say so, but this implies
  29260. ** that it overrides locks set by the same process using a different
  29261. ** file descriptor. Consider this test case:
  29262. **
  29263. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  29264. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  29265. **
  29266. ** Suppose ./file1 and ./file2 are really the same file (because
  29267. ** one is a hard or symbolic link to the other) then if you set
  29268. ** an exclusive lock on fd1, then try to get an exclusive lock
  29269. ** on fd2, it works. I would have expected the second lock to
  29270. ** fail since there was already a lock on the file due to fd1.
  29271. ** But not so. Since both locks came from the same process, the
  29272. ** second overrides the first, even though they were on different
  29273. ** file descriptors opened on different file names.
  29274. **
  29275. ** This means that we cannot use POSIX locks to synchronize file access
  29276. ** among competing threads of the same process. POSIX locks will work fine
  29277. ** to synchronize access for threads in separate processes, but not
  29278. ** threads within the same process.
  29279. **
  29280. ** To work around the problem, SQLite has to manage file locks internally
  29281. ** on its own. Whenever a new database is opened, we have to find the
  29282. ** specific inode of the database file (the inode is determined by the
  29283. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  29284. ** and check for locks already existing on that inode. When locks are
  29285. ** created or removed, we have to look at our own internal record of the
  29286. ** locks to see if another thread has previously set a lock on that same
  29287. ** inode.
  29288. **
  29289. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  29290. ** For VxWorks, we have to use the alternative unique ID system based on
  29291. ** canonical filename and implemented in the previous division.)
  29292. **
  29293. ** The sqlite3_file structure for POSIX is no longer just an integer file
  29294. ** descriptor. It is now a structure that holds the integer file
  29295. ** descriptor and a pointer to a structure that describes the internal
  29296. ** locks on the corresponding inode. There is one locking structure
  29297. ** per inode, so if the same inode is opened twice, both unixFile structures
  29298. ** point to the same locking structure. The locking structure keeps
  29299. ** a reference count (so we will know when to delete it) and a "cnt"
  29300. ** field that tells us its internal lock status. cnt==0 means the
  29301. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  29302. ** cnt>0 means there are cnt shared locks on the file.
  29303. **
  29304. ** Any attempt to lock or unlock a file first checks the locking
  29305. ** structure. The fcntl() system call is only invoked to set a
  29306. ** POSIX lock if the internal lock structure transitions between
  29307. ** a locked and an unlocked state.
  29308. **
  29309. ** But wait: there are yet more problems with POSIX advisory locks.
  29310. **
  29311. ** If you close a file descriptor that points to a file that has locks,
  29312. ** all locks on that file that are owned by the current process are
  29313. ** released. To work around this problem, each unixInodeInfo object
  29314. ** maintains a count of the number of pending locks on tha inode.
  29315. ** When an attempt is made to close an unixFile, if there are
  29316. ** other unixFile open on the same inode that are holding locks, the call
  29317. ** to close() the file descriptor is deferred until all of the locks clear.
  29318. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  29319. ** be closed and that list is walked (and cleared) when the last lock
  29320. ** clears.
  29321. **
  29322. ** Yet another problem: LinuxThreads do not play well with posix locks.
  29323. **
  29324. ** Many older versions of linux use the LinuxThreads library which is
  29325. ** not posix compliant. Under LinuxThreads, a lock created by thread
  29326. ** A cannot be modified or overridden by a different thread B.
  29327. ** Only thread A can modify the lock. Locking behavior is correct
  29328. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  29329. ** on linux - with NPTL a lock created by thread A can override locks
  29330. ** in thread B. But there is no way to know at compile-time which
  29331. ** threading library is being used. So there is no way to know at
  29332. ** compile-time whether or not thread A can override locks on thread B.
  29333. ** One has to do a run-time check to discover the behavior of the
  29334. ** current process.
  29335. **
  29336. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  29337. ** was dropped beginning with version 3.7.0. SQLite will still work with
  29338. ** LinuxThreads provided that (1) there is no more than one connection
  29339. ** per database file in the same process and (2) database connections
  29340. ** do not move across threads.
  29341. */
  29342. /*
  29343. ** An instance of the following structure serves as the key used
  29344. ** to locate a particular unixInodeInfo object.
  29345. */
  29346. struct unixFileId {
  29347. dev_t dev; /* Device number */
  29348. #if OS_VXWORKS
  29349. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  29350. #else
  29351. /* We are told that some versions of Android contain a bug that
  29352. ** sizes ino_t at only 32-bits instead of 64-bits. (See
  29353. ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
  29354. ** To work around this, always allocate 64-bits for the inode number.
  29355. ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
  29356. ** but that should not be a big deal. */
  29357. /* WAS: ino_t ino; */
  29358. u64 ino; /* Inode number */
  29359. #endif
  29360. };
  29361. /*
  29362. ** An instance of the following structure is allocated for each open
  29363. ** inode. Or, on LinuxThreads, there is one of these structures for
  29364. ** each inode opened by each thread.
  29365. **
  29366. ** A single inode can have multiple file descriptors, so each unixFile
  29367. ** structure contains a pointer to an instance of this object and this
  29368. ** object keeps a count of the number of unixFile pointing to it.
  29369. */
  29370. struct unixInodeInfo {
  29371. struct unixFileId fileId; /* The lookup key */
  29372. int nShared; /* Number of SHARED locks held */
  29373. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  29374. unsigned char bProcessLock; /* An exclusive process lock is held */
  29375. int nRef; /* Number of pointers to this structure */
  29376. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  29377. int nLock; /* Number of outstanding file locks */
  29378. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  29379. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  29380. unixInodeInfo *pPrev; /* .... doubly linked */
  29381. #if SQLITE_ENABLE_LOCKING_STYLE
  29382. unsigned long long sharedByte; /* for AFP simulated shared lock */
  29383. #endif
  29384. #if OS_VXWORKS
  29385. sem_t *pSem; /* Named POSIX semaphore */
  29386. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  29387. #endif
  29388. };
  29389. /*
  29390. ** A lists of all unixInodeInfo objects.
  29391. */
  29392. static unixInodeInfo *inodeList = 0;
  29393. /*
  29394. **
  29395. ** This function - unixLogErrorAtLine(), is only ever called via the macro
  29396. ** unixLogError().
  29397. **
  29398. ** It is invoked after an error occurs in an OS function and errno has been
  29399. ** set. It logs a message using sqlite3_log() containing the current value of
  29400. ** errno and, if possible, the human-readable equivalent from strerror() or
  29401. ** strerror_r().
  29402. **
  29403. ** The first argument passed to the macro should be the error code that
  29404. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  29405. ** The two subsequent arguments should be the name of the OS function that
  29406. ** failed (e.g. "unlink", "open") and the associated file-system path,
  29407. ** if any.
  29408. */
  29409. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  29410. static int unixLogErrorAtLine(
  29411. int errcode, /* SQLite error code */
  29412. const char *zFunc, /* Name of OS function that failed */
  29413. const char *zPath, /* File path associated with error */
  29414. int iLine /* Source line number where error occurred */
  29415. ){
  29416. char *zErr; /* Message from strerror() or equivalent */
  29417. int iErrno = errno; /* Saved syscall error number */
  29418. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  29419. ** the strerror() function to obtain the human-readable error message
  29420. ** equivalent to errno. Otherwise, use strerror_r().
  29421. */
  29422. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  29423. char aErr[80];
  29424. memset(aErr, 0, sizeof(aErr));
  29425. zErr = aErr;
  29426. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  29427. ** assume that the system provides the GNU version of strerror_r() that
  29428. ** returns a pointer to a buffer containing the error message. That pointer
  29429. ** may point to aErr[], or it may point to some static storage somewhere.
  29430. ** Otherwise, assume that the system provides the POSIX version of
  29431. ** strerror_r(), which always writes an error message into aErr[].
  29432. **
  29433. ** If the code incorrectly assumes that it is the POSIX version that is
  29434. ** available, the error message will often be an empty string. Not a
  29435. ** huge problem. Incorrectly concluding that the GNU version is available
  29436. ** could lead to a segfault though.
  29437. */
  29438. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  29439. zErr =
  29440. # endif
  29441. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  29442. #elif SQLITE_THREADSAFE
  29443. /* This is a threadsafe build, but strerror_r() is not available. */
  29444. zErr = "";
  29445. #else
  29446. /* Non-threadsafe build, use strerror(). */
  29447. zErr = strerror(iErrno);
  29448. #endif
  29449. if( zPath==0 ) zPath = "";
  29450. sqlite3_log(errcode,
  29451. "os_unix.c:%d: (%d) %s(%s) - %s",
  29452. iLine, iErrno, zFunc, zPath, zErr
  29453. );
  29454. return errcode;
  29455. }
  29456. /*
  29457. ** Close a file descriptor.
  29458. **
  29459. ** We assume that close() almost always works, since it is only in a
  29460. ** very sick application or on a very sick platform that it might fail.
  29461. ** If it does fail, simply leak the file descriptor, but do log the
  29462. ** error.
  29463. **
  29464. ** Note that it is not safe to retry close() after EINTR since the
  29465. ** file descriptor might have already been reused by another thread.
  29466. ** So we don't even try to recover from an EINTR. Just log the error
  29467. ** and move on.
  29468. */
  29469. static void robust_close(unixFile *pFile, int h, int lineno){
  29470. if( osClose(h) ){
  29471. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  29472. pFile ? pFile->zPath : 0, lineno);
  29473. }
  29474. }
  29475. /*
  29476. ** Set the pFile->lastErrno. Do this in a subroutine as that provides
  29477. ** a convenient place to set a breakpoint.
  29478. */
  29479. static void storeLastErrno(unixFile *pFile, int error){
  29480. pFile->lastErrno = error;
  29481. }
  29482. /*
  29483. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  29484. */
  29485. static void closePendingFds(unixFile *pFile){
  29486. unixInodeInfo *pInode = pFile->pInode;
  29487. UnixUnusedFd *p;
  29488. UnixUnusedFd *pNext;
  29489. for(p=pInode->pUnused; p; p=pNext){
  29490. pNext = p->pNext;
  29491. robust_close(pFile, p->fd, __LINE__);
  29492. sqlite3_free(p);
  29493. }
  29494. pInode->pUnused = 0;
  29495. }
  29496. /*
  29497. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  29498. **
  29499. ** The mutex entered using the unixEnterMutex() function must be held
  29500. ** when this function is called.
  29501. */
  29502. static void releaseInodeInfo(unixFile *pFile){
  29503. unixInodeInfo *pInode = pFile->pInode;
  29504. assert( unixMutexHeld() );
  29505. if( ALWAYS(pInode) ){
  29506. pInode->nRef--;
  29507. if( pInode->nRef==0 ){
  29508. assert( pInode->pShmNode==0 );
  29509. closePendingFds(pFile);
  29510. if( pInode->pPrev ){
  29511. assert( pInode->pPrev->pNext==pInode );
  29512. pInode->pPrev->pNext = pInode->pNext;
  29513. }else{
  29514. assert( inodeList==pInode );
  29515. inodeList = pInode->pNext;
  29516. }
  29517. if( pInode->pNext ){
  29518. assert( pInode->pNext->pPrev==pInode );
  29519. pInode->pNext->pPrev = pInode->pPrev;
  29520. }
  29521. sqlite3_free(pInode);
  29522. }
  29523. }
  29524. }
  29525. /*
  29526. ** Given a file descriptor, locate the unixInodeInfo object that
  29527. ** describes that file descriptor. Create a new one if necessary. The
  29528. ** return value might be uninitialized if an error occurs.
  29529. **
  29530. ** The mutex entered using the unixEnterMutex() function must be held
  29531. ** when this function is called.
  29532. **
  29533. ** Return an appropriate error code.
  29534. */
  29535. static int findInodeInfo(
  29536. unixFile *pFile, /* Unix file with file desc used in the key */
  29537. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  29538. ){
  29539. int rc; /* System call return code */
  29540. int fd; /* The file descriptor for pFile */
  29541. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  29542. struct stat statbuf; /* Low-level file information */
  29543. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  29544. assert( unixMutexHeld() );
  29545. /* Get low-level information about the file that we can used to
  29546. ** create a unique name for the file.
  29547. */
  29548. fd = pFile->h;
  29549. rc = osFstat(fd, &statbuf);
  29550. if( rc!=0 ){
  29551. storeLastErrno(pFile, errno);
  29552. #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
  29553. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  29554. #endif
  29555. return SQLITE_IOERR;
  29556. }
  29557. #ifdef __APPLE__
  29558. /* On OS X on an msdos filesystem, the inode number is reported
  29559. ** incorrectly for zero-size files. See ticket #3260. To work
  29560. ** around this problem (we consider it a bug in OS X, not SQLite)
  29561. ** we always increase the file size to 1 by writing a single byte
  29562. ** prior to accessing the inode number. The one byte written is
  29563. ** an ASCII 'S' character which also happens to be the first byte
  29564. ** in the header of every SQLite database. In this way, if there
  29565. ** is a race condition such that another thread has already populated
  29566. ** the first page of the database, no damage is done.
  29567. */
  29568. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  29569. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  29570. if( rc!=1 ){
  29571. storeLastErrno(pFile, errno);
  29572. return SQLITE_IOERR;
  29573. }
  29574. rc = osFstat(fd, &statbuf);
  29575. if( rc!=0 ){
  29576. storeLastErrno(pFile, errno);
  29577. return SQLITE_IOERR;
  29578. }
  29579. }
  29580. #endif
  29581. memset(&fileId, 0, sizeof(fileId));
  29582. fileId.dev = statbuf.st_dev;
  29583. #if OS_VXWORKS
  29584. fileId.pId = pFile->pId;
  29585. #else
  29586. fileId.ino = (u64)statbuf.st_ino;
  29587. #endif
  29588. pInode = inodeList;
  29589. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  29590. pInode = pInode->pNext;
  29591. }
  29592. if( pInode==0 ){
  29593. pInode = sqlite3_malloc64( sizeof(*pInode) );
  29594. if( pInode==0 ){
  29595. return SQLITE_NOMEM_BKPT;
  29596. }
  29597. memset(pInode, 0, sizeof(*pInode));
  29598. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  29599. pInode->nRef = 1;
  29600. pInode->pNext = inodeList;
  29601. pInode->pPrev = 0;
  29602. if( inodeList ) inodeList->pPrev = pInode;
  29603. inodeList = pInode;
  29604. }else{
  29605. pInode->nRef++;
  29606. }
  29607. *ppInode = pInode;
  29608. return SQLITE_OK;
  29609. }
  29610. /*
  29611. ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
  29612. */
  29613. static int fileHasMoved(unixFile *pFile){
  29614. #if OS_VXWORKS
  29615. return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
  29616. #else
  29617. struct stat buf;
  29618. return pFile->pInode!=0 &&
  29619. (osStat(pFile->zPath, &buf)!=0
  29620. || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
  29621. #endif
  29622. }
  29623. /*
  29624. ** Check a unixFile that is a database. Verify the following:
  29625. **
  29626. ** (1) There is exactly one hard link on the file
  29627. ** (2) The file is not a symbolic link
  29628. ** (3) The file has not been renamed or unlinked
  29629. **
  29630. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  29631. */
  29632. static void verifyDbFile(unixFile *pFile){
  29633. struct stat buf;
  29634. int rc;
  29635. /* These verifications occurs for the main database only */
  29636. if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
  29637. rc = osFstat(pFile->h, &buf);
  29638. if( rc!=0 ){
  29639. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  29640. return;
  29641. }
  29642. if( buf.st_nlink==0 ){
  29643. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  29644. return;
  29645. }
  29646. if( buf.st_nlink>1 ){
  29647. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  29648. return;
  29649. }
  29650. if( fileHasMoved(pFile) ){
  29651. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  29652. return;
  29653. }
  29654. }
  29655. /*
  29656. ** This routine checks if there is a RESERVED lock held on the specified
  29657. ** file by this or any other process. If such a lock is held, set *pResOut
  29658. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  29659. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  29660. */
  29661. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  29662. int rc = SQLITE_OK;
  29663. int reserved = 0;
  29664. unixFile *pFile = (unixFile*)id;
  29665. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  29666. assert( pFile );
  29667. assert( pFile->eFileLock<=SHARED_LOCK );
  29668. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  29669. /* Check if a thread in this process holds such a lock */
  29670. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  29671. reserved = 1;
  29672. }
  29673. /* Otherwise see if some other process holds it.
  29674. */
  29675. #ifndef __DJGPP__
  29676. if( !reserved && !pFile->pInode->bProcessLock ){
  29677. struct flock lock;
  29678. lock.l_whence = SEEK_SET;
  29679. lock.l_start = RESERVED_BYTE;
  29680. lock.l_len = 1;
  29681. lock.l_type = F_WRLCK;
  29682. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  29683. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  29684. storeLastErrno(pFile, errno);
  29685. } else if( lock.l_type!=F_UNLCK ){
  29686. reserved = 1;
  29687. }
  29688. }
  29689. #endif
  29690. unixLeaveMutex();
  29691. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  29692. *pResOut = reserved;
  29693. return rc;
  29694. }
  29695. /*
  29696. ** Attempt to set a system-lock on the file pFile. The lock is
  29697. ** described by pLock.
  29698. **
  29699. ** If the pFile was opened read/write from unix-excl, then the only lock
  29700. ** ever obtained is an exclusive lock, and it is obtained exactly once
  29701. ** the first time any lock is attempted. All subsequent system locking
  29702. ** operations become no-ops. Locking operations still happen internally,
  29703. ** in order to coordinate access between separate database connections
  29704. ** within this process, but all of that is handled in memory and the
  29705. ** operating system does not participate.
  29706. **
  29707. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  29708. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  29709. ** and is read-only.
  29710. **
  29711. ** Zero is returned if the call completes successfully, or -1 if a call
  29712. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  29713. */
  29714. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  29715. int rc;
  29716. unixInodeInfo *pInode = pFile->pInode;
  29717. assert( unixMutexHeld() );
  29718. assert( pInode!=0 );
  29719. if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
  29720. if( pInode->bProcessLock==0 ){
  29721. struct flock lock;
  29722. assert( pInode->nLock==0 );
  29723. lock.l_whence = SEEK_SET;
  29724. lock.l_start = SHARED_FIRST;
  29725. lock.l_len = SHARED_SIZE;
  29726. lock.l_type = F_WRLCK;
  29727. rc = osFcntl(pFile->h, F_SETLK, &lock);
  29728. if( rc<0 ) return rc;
  29729. pInode->bProcessLock = 1;
  29730. pInode->nLock++;
  29731. }else{
  29732. rc = 0;
  29733. }
  29734. }else{
  29735. rc = osFcntl(pFile->h, F_SETLK, pLock);
  29736. }
  29737. return rc;
  29738. }
  29739. /*
  29740. ** Lock the file with the lock specified by parameter eFileLock - one
  29741. ** of the following:
  29742. **
  29743. ** (1) SHARED_LOCK
  29744. ** (2) RESERVED_LOCK
  29745. ** (3) PENDING_LOCK
  29746. ** (4) EXCLUSIVE_LOCK
  29747. **
  29748. ** Sometimes when requesting one lock state, additional lock states
  29749. ** are inserted in between. The locking might fail on one of the later
  29750. ** transitions leaving the lock state different from what it started but
  29751. ** still short of its goal. The following chart shows the allowed
  29752. ** transitions and the inserted intermediate states:
  29753. **
  29754. ** UNLOCKED -> SHARED
  29755. ** SHARED -> RESERVED
  29756. ** SHARED -> (PENDING) -> EXCLUSIVE
  29757. ** RESERVED -> (PENDING) -> EXCLUSIVE
  29758. ** PENDING -> EXCLUSIVE
  29759. **
  29760. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  29761. ** routine to lower a locking level.
  29762. */
  29763. static int unixLock(sqlite3_file *id, int eFileLock){
  29764. /* The following describes the implementation of the various locks and
  29765. ** lock transitions in terms of the POSIX advisory shared and exclusive
  29766. ** lock primitives (called read-locks and write-locks below, to avoid
  29767. ** confusion with SQLite lock names). The algorithms are complicated
  29768. ** slightly in order to be compatible with Windows95 systems simultaneously
  29769. ** accessing the same database file, in case that is ever required.
  29770. **
  29771. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  29772. ** byte', each single bytes at well known offsets, and the 'shared byte
  29773. ** range', a range of 510 bytes at a well known offset.
  29774. **
  29775. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  29776. ** byte'. If this is successful, 'shared byte range' is read-locked
  29777. ** and the lock on the 'pending byte' released. (Legacy note: When
  29778. ** SQLite was first developed, Windows95 systems were still very common,
  29779. ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
  29780. ** single randomly selected by from the 'shared byte range' is locked.
  29781. ** Windows95 is now pretty much extinct, but this work-around for the
  29782. ** lack of shared-locks on Windows95 lives on, for backwards
  29783. ** compatibility.)
  29784. **
  29785. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  29786. ** A RESERVED lock is implemented by grabbing a write-lock on the
  29787. ** 'reserved byte'.
  29788. **
  29789. ** A process may only obtain a PENDING lock after it has obtained a
  29790. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  29791. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  29792. ** obtained, but existing SHARED locks are allowed to persist. A process
  29793. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  29794. ** This property is used by the algorithm for rolling back a journal file
  29795. ** after a crash.
  29796. **
  29797. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  29798. ** implemented by obtaining a write-lock on the entire 'shared byte
  29799. ** range'. Since all other locks require a read-lock on one of the bytes
  29800. ** within this range, this ensures that no other locks are held on the
  29801. ** database.
  29802. */
  29803. int rc = SQLITE_OK;
  29804. unixFile *pFile = (unixFile*)id;
  29805. unixInodeInfo *pInode;
  29806. struct flock lock;
  29807. int tErrno = 0;
  29808. assert( pFile );
  29809. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  29810. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  29811. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
  29812. osGetpid(0)));
  29813. /* If there is already a lock of this type or more restrictive on the
  29814. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  29815. ** unixEnterMutex() hasn't been called yet.
  29816. */
  29817. if( pFile->eFileLock>=eFileLock ){
  29818. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  29819. azFileLock(eFileLock)));
  29820. return SQLITE_OK;
  29821. }
  29822. /* Make sure the locking sequence is correct.
  29823. ** (1) We never move from unlocked to anything higher than shared lock.
  29824. ** (2) SQLite never explicitly requests a pendig lock.
  29825. ** (3) A shared lock is always held when a reserve lock is requested.
  29826. */
  29827. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  29828. assert( eFileLock!=PENDING_LOCK );
  29829. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  29830. /* This mutex is needed because pFile->pInode is shared across threads
  29831. */
  29832. unixEnterMutex();
  29833. pInode = pFile->pInode;
  29834. /* If some thread using this PID has a lock via a different unixFile*
  29835. ** handle that precludes the requested lock, return BUSY.
  29836. */
  29837. if( (pFile->eFileLock!=pInode->eFileLock &&
  29838. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  29839. ){
  29840. rc = SQLITE_BUSY;
  29841. goto end_lock;
  29842. }
  29843. /* If a SHARED lock is requested, and some thread using this PID already
  29844. ** has a SHARED or RESERVED lock, then increment reference counts and
  29845. ** return SQLITE_OK.
  29846. */
  29847. if( eFileLock==SHARED_LOCK &&
  29848. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  29849. assert( eFileLock==SHARED_LOCK );
  29850. assert( pFile->eFileLock==0 );
  29851. assert( pInode->nShared>0 );
  29852. pFile->eFileLock = SHARED_LOCK;
  29853. pInode->nShared++;
  29854. pInode->nLock++;
  29855. goto end_lock;
  29856. }
  29857. /* A PENDING lock is needed before acquiring a SHARED lock and before
  29858. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  29859. ** be released.
  29860. */
  29861. lock.l_len = 1L;
  29862. lock.l_whence = SEEK_SET;
  29863. if( eFileLock==SHARED_LOCK
  29864. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  29865. ){
  29866. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  29867. lock.l_start = PENDING_BYTE;
  29868. if( unixFileLock(pFile, &lock) ){
  29869. tErrno = errno;
  29870. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  29871. if( rc!=SQLITE_BUSY ){
  29872. storeLastErrno(pFile, tErrno);
  29873. }
  29874. goto end_lock;
  29875. }
  29876. }
  29877. /* If control gets to this point, then actually go ahead and make
  29878. ** operating system calls for the specified lock.
  29879. */
  29880. if( eFileLock==SHARED_LOCK ){
  29881. assert( pInode->nShared==0 );
  29882. assert( pInode->eFileLock==0 );
  29883. assert( rc==SQLITE_OK );
  29884. /* Now get the read-lock */
  29885. lock.l_start = SHARED_FIRST;
  29886. lock.l_len = SHARED_SIZE;
  29887. if( unixFileLock(pFile, &lock) ){
  29888. tErrno = errno;
  29889. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  29890. }
  29891. /* Drop the temporary PENDING lock */
  29892. lock.l_start = PENDING_BYTE;
  29893. lock.l_len = 1L;
  29894. lock.l_type = F_UNLCK;
  29895. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  29896. /* This could happen with a network mount */
  29897. tErrno = errno;
  29898. rc = SQLITE_IOERR_UNLOCK;
  29899. }
  29900. if( rc ){
  29901. if( rc!=SQLITE_BUSY ){
  29902. storeLastErrno(pFile, tErrno);
  29903. }
  29904. goto end_lock;
  29905. }else{
  29906. pFile->eFileLock = SHARED_LOCK;
  29907. pInode->nLock++;
  29908. pInode->nShared = 1;
  29909. }
  29910. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  29911. /* We are trying for an exclusive lock but another thread in this
  29912. ** same process is still holding a shared lock. */
  29913. rc = SQLITE_BUSY;
  29914. }else{
  29915. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  29916. ** assumed that there is a SHARED or greater lock on the file
  29917. ** already.
  29918. */
  29919. assert( 0!=pFile->eFileLock );
  29920. lock.l_type = F_WRLCK;
  29921. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  29922. if( eFileLock==RESERVED_LOCK ){
  29923. lock.l_start = RESERVED_BYTE;
  29924. lock.l_len = 1L;
  29925. }else{
  29926. lock.l_start = SHARED_FIRST;
  29927. lock.l_len = SHARED_SIZE;
  29928. }
  29929. if( unixFileLock(pFile, &lock) ){
  29930. tErrno = errno;
  29931. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  29932. if( rc!=SQLITE_BUSY ){
  29933. storeLastErrno(pFile, tErrno);
  29934. }
  29935. }
  29936. }
  29937. #ifdef SQLITE_DEBUG
  29938. /* Set up the transaction-counter change checking flags when
  29939. ** transitioning from a SHARED to a RESERVED lock. The change
  29940. ** from SHARED to RESERVED marks the beginning of a normal
  29941. ** write operation (not a hot journal rollback).
  29942. */
  29943. if( rc==SQLITE_OK
  29944. && pFile->eFileLock<=SHARED_LOCK
  29945. && eFileLock==RESERVED_LOCK
  29946. ){
  29947. pFile->transCntrChng = 0;
  29948. pFile->dbUpdate = 0;
  29949. pFile->inNormalWrite = 1;
  29950. }
  29951. #endif
  29952. if( rc==SQLITE_OK ){
  29953. pFile->eFileLock = eFileLock;
  29954. pInode->eFileLock = eFileLock;
  29955. }else if( eFileLock==EXCLUSIVE_LOCK ){
  29956. pFile->eFileLock = PENDING_LOCK;
  29957. pInode->eFileLock = PENDING_LOCK;
  29958. }
  29959. end_lock:
  29960. unixLeaveMutex();
  29961. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  29962. rc==SQLITE_OK ? "ok" : "failed"));
  29963. return rc;
  29964. }
  29965. /*
  29966. ** Add the file descriptor used by file handle pFile to the corresponding
  29967. ** pUnused list.
  29968. */
  29969. static void setPendingFd(unixFile *pFile){
  29970. unixInodeInfo *pInode = pFile->pInode;
  29971. UnixUnusedFd *p = pFile->pUnused;
  29972. p->pNext = pInode->pUnused;
  29973. pInode->pUnused = p;
  29974. pFile->h = -1;
  29975. pFile->pUnused = 0;
  29976. }
  29977. /*
  29978. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  29979. ** must be either NO_LOCK or SHARED_LOCK.
  29980. **
  29981. ** If the locking level of the file descriptor is already at or below
  29982. ** the requested locking level, this routine is a no-op.
  29983. **
  29984. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  29985. ** the byte range is divided into 2 parts and the first part is unlocked then
  29986. ** set to a read lock, then the other part is simply unlocked. This works
  29987. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  29988. ** remove the write lock on a region when a read lock is set.
  29989. */
  29990. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  29991. unixFile *pFile = (unixFile*)id;
  29992. unixInodeInfo *pInode;
  29993. struct flock lock;
  29994. int rc = SQLITE_OK;
  29995. assert( pFile );
  29996. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  29997. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  29998. osGetpid(0)));
  29999. assert( eFileLock<=SHARED_LOCK );
  30000. if( pFile->eFileLock<=eFileLock ){
  30001. return SQLITE_OK;
  30002. }
  30003. unixEnterMutex();
  30004. pInode = pFile->pInode;
  30005. assert( pInode->nShared!=0 );
  30006. if( pFile->eFileLock>SHARED_LOCK ){
  30007. assert( pInode->eFileLock==pFile->eFileLock );
  30008. #ifdef SQLITE_DEBUG
  30009. /* When reducing a lock such that other processes can start
  30010. ** reading the database file again, make sure that the
  30011. ** transaction counter was updated if any part of the database
  30012. ** file changed. If the transaction counter is not updated,
  30013. ** other connections to the same file might not realize that
  30014. ** the file has changed and hence might not know to flush their
  30015. ** cache. The use of a stale cache can lead to database corruption.
  30016. */
  30017. pFile->inNormalWrite = 0;
  30018. #endif
  30019. /* downgrading to a shared lock on NFS involves clearing the write lock
  30020. ** before establishing the readlock - to avoid a race condition we downgrade
  30021. ** the lock in 2 blocks, so that part of the range will be covered by a
  30022. ** write lock until the rest is covered by a read lock:
  30023. ** 1: [WWWWW]
  30024. ** 2: [....W]
  30025. ** 3: [RRRRW]
  30026. ** 4: [RRRR.]
  30027. */
  30028. if( eFileLock==SHARED_LOCK ){
  30029. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  30030. (void)handleNFSUnlock;
  30031. assert( handleNFSUnlock==0 );
  30032. #endif
  30033. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30034. if( handleNFSUnlock ){
  30035. int tErrno; /* Error code from system call errors */
  30036. off_t divSize = SHARED_SIZE - 1;
  30037. lock.l_type = F_UNLCK;
  30038. lock.l_whence = SEEK_SET;
  30039. lock.l_start = SHARED_FIRST;
  30040. lock.l_len = divSize;
  30041. if( unixFileLock(pFile, &lock)==(-1) ){
  30042. tErrno = errno;
  30043. rc = SQLITE_IOERR_UNLOCK;
  30044. storeLastErrno(pFile, tErrno);
  30045. goto end_unlock;
  30046. }
  30047. lock.l_type = F_RDLCK;
  30048. lock.l_whence = SEEK_SET;
  30049. lock.l_start = SHARED_FIRST;
  30050. lock.l_len = divSize;
  30051. if( unixFileLock(pFile, &lock)==(-1) ){
  30052. tErrno = errno;
  30053. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  30054. if( IS_LOCK_ERROR(rc) ){
  30055. storeLastErrno(pFile, tErrno);
  30056. }
  30057. goto end_unlock;
  30058. }
  30059. lock.l_type = F_UNLCK;
  30060. lock.l_whence = SEEK_SET;
  30061. lock.l_start = SHARED_FIRST+divSize;
  30062. lock.l_len = SHARED_SIZE-divSize;
  30063. if( unixFileLock(pFile, &lock)==(-1) ){
  30064. tErrno = errno;
  30065. rc = SQLITE_IOERR_UNLOCK;
  30066. storeLastErrno(pFile, tErrno);
  30067. goto end_unlock;
  30068. }
  30069. }else
  30070. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  30071. {
  30072. lock.l_type = F_RDLCK;
  30073. lock.l_whence = SEEK_SET;
  30074. lock.l_start = SHARED_FIRST;
  30075. lock.l_len = SHARED_SIZE;
  30076. if( unixFileLock(pFile, &lock) ){
  30077. /* In theory, the call to unixFileLock() cannot fail because another
  30078. ** process is holding an incompatible lock. If it does, this
  30079. ** indicates that the other process is not following the locking
  30080. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  30081. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  30082. ** an assert to fail). */
  30083. rc = SQLITE_IOERR_RDLOCK;
  30084. storeLastErrno(pFile, errno);
  30085. goto end_unlock;
  30086. }
  30087. }
  30088. }
  30089. lock.l_type = F_UNLCK;
  30090. lock.l_whence = SEEK_SET;
  30091. lock.l_start = PENDING_BYTE;
  30092. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  30093. if( unixFileLock(pFile, &lock)==0 ){
  30094. pInode->eFileLock = SHARED_LOCK;
  30095. }else{
  30096. rc = SQLITE_IOERR_UNLOCK;
  30097. storeLastErrno(pFile, errno);
  30098. goto end_unlock;
  30099. }
  30100. }
  30101. if( eFileLock==NO_LOCK ){
  30102. /* Decrement the shared lock counter. Release the lock using an
  30103. ** OS call only when all threads in this same process have released
  30104. ** the lock.
  30105. */
  30106. pInode->nShared--;
  30107. if( pInode->nShared==0 ){
  30108. lock.l_type = F_UNLCK;
  30109. lock.l_whence = SEEK_SET;
  30110. lock.l_start = lock.l_len = 0L;
  30111. if( unixFileLock(pFile, &lock)==0 ){
  30112. pInode->eFileLock = NO_LOCK;
  30113. }else{
  30114. rc = SQLITE_IOERR_UNLOCK;
  30115. storeLastErrno(pFile, errno);
  30116. pInode->eFileLock = NO_LOCK;
  30117. pFile->eFileLock = NO_LOCK;
  30118. }
  30119. }
  30120. /* Decrement the count of locks against this same file. When the
  30121. ** count reaches zero, close any other file descriptors whose close
  30122. ** was deferred because of outstanding locks.
  30123. */
  30124. pInode->nLock--;
  30125. assert( pInode->nLock>=0 );
  30126. if( pInode->nLock==0 ){
  30127. closePendingFds(pFile);
  30128. }
  30129. }
  30130. end_unlock:
  30131. unixLeaveMutex();
  30132. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  30133. return rc;
  30134. }
  30135. /*
  30136. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  30137. ** must be either NO_LOCK or SHARED_LOCK.
  30138. **
  30139. ** If the locking level of the file descriptor is already at or below
  30140. ** the requested locking level, this routine is a no-op.
  30141. */
  30142. static int unixUnlock(sqlite3_file *id, int eFileLock){
  30143. #if SQLITE_MAX_MMAP_SIZE>0
  30144. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  30145. #endif
  30146. return posixUnlock(id, eFileLock, 0);
  30147. }
  30148. #if SQLITE_MAX_MMAP_SIZE>0
  30149. static int unixMapfile(unixFile *pFd, i64 nByte);
  30150. static void unixUnmapfile(unixFile *pFd);
  30151. #endif
  30152. /*
  30153. ** This function performs the parts of the "close file" operation
  30154. ** common to all locking schemes. It closes the directory and file
  30155. ** handles, if they are valid, and sets all fields of the unixFile
  30156. ** structure to 0.
  30157. **
  30158. ** It is *not* necessary to hold the mutex when this routine is called,
  30159. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  30160. ** vxworksReleaseFileId() routine.
  30161. */
  30162. static int closeUnixFile(sqlite3_file *id){
  30163. unixFile *pFile = (unixFile*)id;
  30164. #if SQLITE_MAX_MMAP_SIZE>0
  30165. unixUnmapfile(pFile);
  30166. #endif
  30167. if( pFile->h>=0 ){
  30168. robust_close(pFile, pFile->h, __LINE__);
  30169. pFile->h = -1;
  30170. }
  30171. #if OS_VXWORKS
  30172. if( pFile->pId ){
  30173. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  30174. osUnlink(pFile->pId->zCanonicalName);
  30175. }
  30176. vxworksReleaseFileId(pFile->pId);
  30177. pFile->pId = 0;
  30178. }
  30179. #endif
  30180. #ifdef SQLITE_UNLINK_AFTER_CLOSE
  30181. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  30182. osUnlink(pFile->zPath);
  30183. sqlite3_free(*(char**)&pFile->zPath);
  30184. pFile->zPath = 0;
  30185. }
  30186. #endif
  30187. OSTRACE(("CLOSE %-3d\n", pFile->h));
  30188. OpenCounter(-1);
  30189. sqlite3_free(pFile->pUnused);
  30190. memset(pFile, 0, sizeof(unixFile));
  30191. return SQLITE_OK;
  30192. }
  30193. /*
  30194. ** Close a file.
  30195. */
  30196. static int unixClose(sqlite3_file *id){
  30197. int rc = SQLITE_OK;
  30198. unixFile *pFile = (unixFile *)id;
  30199. verifyDbFile(pFile);
  30200. unixUnlock(id, NO_LOCK);
  30201. unixEnterMutex();
  30202. /* unixFile.pInode is always valid here. Otherwise, a different close
  30203. ** routine (e.g. nolockClose()) would be called instead.
  30204. */
  30205. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  30206. if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
  30207. /* If there are outstanding locks, do not actually close the file just
  30208. ** yet because that would clear those locks. Instead, add the file
  30209. ** descriptor to pInode->pUnused list. It will be automatically closed
  30210. ** when the last lock is cleared.
  30211. */
  30212. setPendingFd(pFile);
  30213. }
  30214. releaseInodeInfo(pFile);
  30215. rc = closeUnixFile(id);
  30216. unixLeaveMutex();
  30217. return rc;
  30218. }
  30219. /************** End of the posix advisory lock implementation *****************
  30220. ******************************************************************************/
  30221. /******************************************************************************
  30222. ****************************** No-op Locking **********************************
  30223. **
  30224. ** Of the various locking implementations available, this is by far the
  30225. ** simplest: locking is ignored. No attempt is made to lock the database
  30226. ** file for reading or writing.
  30227. **
  30228. ** This locking mode is appropriate for use on read-only databases
  30229. ** (ex: databases that are burned into CD-ROM, for example.) It can
  30230. ** also be used if the application employs some external mechanism to
  30231. ** prevent simultaneous access of the same database by two or more
  30232. ** database connections. But there is a serious risk of database
  30233. ** corruption if this locking mode is used in situations where multiple
  30234. ** database connections are accessing the same database file at the same
  30235. ** time and one or more of those connections are writing.
  30236. */
  30237. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  30238. UNUSED_PARAMETER(NotUsed);
  30239. *pResOut = 0;
  30240. return SQLITE_OK;
  30241. }
  30242. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  30243. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  30244. return SQLITE_OK;
  30245. }
  30246. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  30247. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  30248. return SQLITE_OK;
  30249. }
  30250. /*
  30251. ** Close the file.
  30252. */
  30253. static int nolockClose(sqlite3_file *id) {
  30254. return closeUnixFile(id);
  30255. }
  30256. /******************* End of the no-op lock implementation *********************
  30257. ******************************************************************************/
  30258. /******************************************************************************
  30259. ************************* Begin dot-file Locking ******************************
  30260. **
  30261. ** The dotfile locking implementation uses the existence of separate lock
  30262. ** files (really a directory) to control access to the database. This works
  30263. ** on just about every filesystem imaginable. But there are serious downsides:
  30264. **
  30265. ** (1) There is zero concurrency. A single reader blocks all other
  30266. ** connections from reading or writing the database.
  30267. **
  30268. ** (2) An application crash or power loss can leave stale lock files
  30269. ** sitting around that need to be cleared manually.
  30270. **
  30271. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  30272. ** other locking strategy is available.
  30273. **
  30274. ** Dotfile locking works by creating a subdirectory in the same directory as
  30275. ** the database and with the same name but with a ".lock" extension added.
  30276. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  30277. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  30278. */
  30279. /*
  30280. ** The file suffix added to the data base filename in order to create the
  30281. ** lock directory.
  30282. */
  30283. #define DOTLOCK_SUFFIX ".lock"
  30284. /*
  30285. ** This routine checks if there is a RESERVED lock held on the specified
  30286. ** file by this or any other process. If such a lock is held, set *pResOut
  30287. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  30288. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  30289. **
  30290. ** In dotfile locking, either a lock exists or it does not. So in this
  30291. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  30292. ** is held on the file and false if the file is unlocked.
  30293. */
  30294. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  30295. int rc = SQLITE_OK;
  30296. int reserved = 0;
  30297. unixFile *pFile = (unixFile*)id;
  30298. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  30299. assert( pFile );
  30300. reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
  30301. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  30302. *pResOut = reserved;
  30303. return rc;
  30304. }
  30305. /*
  30306. ** Lock the file with the lock specified by parameter eFileLock - one
  30307. ** of the following:
  30308. **
  30309. ** (1) SHARED_LOCK
  30310. ** (2) RESERVED_LOCK
  30311. ** (3) PENDING_LOCK
  30312. ** (4) EXCLUSIVE_LOCK
  30313. **
  30314. ** Sometimes when requesting one lock state, additional lock states
  30315. ** are inserted in between. The locking might fail on one of the later
  30316. ** transitions leaving the lock state different from what it started but
  30317. ** still short of its goal. The following chart shows the allowed
  30318. ** transitions and the inserted intermediate states:
  30319. **
  30320. ** UNLOCKED -> SHARED
  30321. ** SHARED -> RESERVED
  30322. ** SHARED -> (PENDING) -> EXCLUSIVE
  30323. ** RESERVED -> (PENDING) -> EXCLUSIVE
  30324. ** PENDING -> EXCLUSIVE
  30325. **
  30326. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  30327. ** routine to lower a locking level.
  30328. **
  30329. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  30330. ** But we track the other locking levels internally.
  30331. */
  30332. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  30333. unixFile *pFile = (unixFile*)id;
  30334. char *zLockFile = (char *)pFile->lockingContext;
  30335. int rc = SQLITE_OK;
  30336. /* If we have any lock, then the lock file already exists. All we have
  30337. ** to do is adjust our internal record of the lock level.
  30338. */
  30339. if( pFile->eFileLock > NO_LOCK ){
  30340. pFile->eFileLock = eFileLock;
  30341. /* Always update the timestamp on the old file */
  30342. #ifdef HAVE_UTIME
  30343. utime(zLockFile, NULL);
  30344. #else
  30345. utimes(zLockFile, NULL);
  30346. #endif
  30347. return SQLITE_OK;
  30348. }
  30349. /* grab an exclusive lock */
  30350. rc = osMkdir(zLockFile, 0777);
  30351. if( rc<0 ){
  30352. /* failed to open/create the lock directory */
  30353. int tErrno = errno;
  30354. if( EEXIST == tErrno ){
  30355. rc = SQLITE_BUSY;
  30356. } else {
  30357. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  30358. if( rc!=SQLITE_BUSY ){
  30359. storeLastErrno(pFile, tErrno);
  30360. }
  30361. }
  30362. return rc;
  30363. }
  30364. /* got it, set the type and return ok */
  30365. pFile->eFileLock = eFileLock;
  30366. return rc;
  30367. }
  30368. /*
  30369. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  30370. ** must be either NO_LOCK or SHARED_LOCK.
  30371. **
  30372. ** If the locking level of the file descriptor is already at or below
  30373. ** the requested locking level, this routine is a no-op.
  30374. **
  30375. ** When the locking level reaches NO_LOCK, delete the lock file.
  30376. */
  30377. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  30378. unixFile *pFile = (unixFile*)id;
  30379. char *zLockFile = (char *)pFile->lockingContext;
  30380. int rc;
  30381. assert( pFile );
  30382. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  30383. pFile->eFileLock, osGetpid(0)));
  30384. assert( eFileLock<=SHARED_LOCK );
  30385. /* no-op if possible */
  30386. if( pFile->eFileLock==eFileLock ){
  30387. return SQLITE_OK;
  30388. }
  30389. /* To downgrade to shared, simply update our internal notion of the
  30390. ** lock state. No need to mess with the file on disk.
  30391. */
  30392. if( eFileLock==SHARED_LOCK ){
  30393. pFile->eFileLock = SHARED_LOCK;
  30394. return SQLITE_OK;
  30395. }
  30396. /* To fully unlock the database, delete the lock file */
  30397. assert( eFileLock==NO_LOCK );
  30398. rc = osRmdir(zLockFile);
  30399. if( rc<0 ){
  30400. int tErrno = errno;
  30401. if( tErrno==ENOENT ){
  30402. rc = SQLITE_OK;
  30403. }else{
  30404. rc = SQLITE_IOERR_UNLOCK;
  30405. storeLastErrno(pFile, tErrno);
  30406. }
  30407. return rc;
  30408. }
  30409. pFile->eFileLock = NO_LOCK;
  30410. return SQLITE_OK;
  30411. }
  30412. /*
  30413. ** Close a file. Make sure the lock has been released before closing.
  30414. */
  30415. static int dotlockClose(sqlite3_file *id) {
  30416. unixFile *pFile = (unixFile*)id;
  30417. assert( id!=0 );
  30418. dotlockUnlock(id, NO_LOCK);
  30419. sqlite3_free(pFile->lockingContext);
  30420. return closeUnixFile(id);
  30421. }
  30422. /****************** End of the dot-file lock implementation *******************
  30423. ******************************************************************************/
  30424. /******************************************************************************
  30425. ************************** Begin flock Locking ********************************
  30426. **
  30427. ** Use the flock() system call to do file locking.
  30428. **
  30429. ** flock() locking is like dot-file locking in that the various
  30430. ** fine-grain locking levels supported by SQLite are collapsed into
  30431. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  30432. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  30433. ** still works when you do this, but concurrency is reduced since
  30434. ** only a single process can be reading the database at a time.
  30435. **
  30436. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
  30437. */
  30438. #if SQLITE_ENABLE_LOCKING_STYLE
  30439. /*
  30440. ** Retry flock() calls that fail with EINTR
  30441. */
  30442. #ifdef EINTR
  30443. static int robust_flock(int fd, int op){
  30444. int rc;
  30445. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  30446. return rc;
  30447. }
  30448. #else
  30449. # define robust_flock(a,b) flock(a,b)
  30450. #endif
  30451. /*
  30452. ** This routine checks if there is a RESERVED lock held on the specified
  30453. ** file by this or any other process. If such a lock is held, set *pResOut
  30454. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  30455. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  30456. */
  30457. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  30458. int rc = SQLITE_OK;
  30459. int reserved = 0;
  30460. unixFile *pFile = (unixFile*)id;
  30461. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  30462. assert( pFile );
  30463. /* Check if a thread in this process holds such a lock */
  30464. if( pFile->eFileLock>SHARED_LOCK ){
  30465. reserved = 1;
  30466. }
  30467. /* Otherwise see if some other process holds it. */
  30468. if( !reserved ){
  30469. /* attempt to get the lock */
  30470. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  30471. if( !lrc ){
  30472. /* got the lock, unlock it */
  30473. lrc = robust_flock(pFile->h, LOCK_UN);
  30474. if ( lrc ) {
  30475. int tErrno = errno;
  30476. /* unlock failed with an error */
  30477. lrc = SQLITE_IOERR_UNLOCK;
  30478. storeLastErrno(pFile, tErrno);
  30479. rc = lrc;
  30480. }
  30481. } else {
  30482. int tErrno = errno;
  30483. reserved = 1;
  30484. /* someone else might have it reserved */
  30485. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  30486. if( IS_LOCK_ERROR(lrc) ){
  30487. storeLastErrno(pFile, tErrno);
  30488. rc = lrc;
  30489. }
  30490. }
  30491. }
  30492. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  30493. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  30494. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  30495. rc = SQLITE_OK;
  30496. reserved=1;
  30497. }
  30498. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  30499. *pResOut = reserved;
  30500. return rc;
  30501. }
  30502. /*
  30503. ** Lock the file with the lock specified by parameter eFileLock - one
  30504. ** of the following:
  30505. **
  30506. ** (1) SHARED_LOCK
  30507. ** (2) RESERVED_LOCK
  30508. ** (3) PENDING_LOCK
  30509. ** (4) EXCLUSIVE_LOCK
  30510. **
  30511. ** Sometimes when requesting one lock state, additional lock states
  30512. ** are inserted in between. The locking might fail on one of the later
  30513. ** transitions leaving the lock state different from what it started but
  30514. ** still short of its goal. The following chart shows the allowed
  30515. ** transitions and the inserted intermediate states:
  30516. **
  30517. ** UNLOCKED -> SHARED
  30518. ** SHARED -> RESERVED
  30519. ** SHARED -> (PENDING) -> EXCLUSIVE
  30520. ** RESERVED -> (PENDING) -> EXCLUSIVE
  30521. ** PENDING -> EXCLUSIVE
  30522. **
  30523. ** flock() only really support EXCLUSIVE locks. We track intermediate
  30524. ** lock states in the sqlite3_file structure, but all locks SHARED or
  30525. ** above are really EXCLUSIVE locks and exclude all other processes from
  30526. ** access the file.
  30527. **
  30528. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  30529. ** routine to lower a locking level.
  30530. */
  30531. static int flockLock(sqlite3_file *id, int eFileLock) {
  30532. int rc = SQLITE_OK;
  30533. unixFile *pFile = (unixFile*)id;
  30534. assert( pFile );
  30535. /* if we already have a lock, it is exclusive.
  30536. ** Just adjust level and punt on outta here. */
  30537. if (pFile->eFileLock > NO_LOCK) {
  30538. pFile->eFileLock = eFileLock;
  30539. return SQLITE_OK;
  30540. }
  30541. /* grab an exclusive lock */
  30542. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  30543. int tErrno = errno;
  30544. /* didn't get, must be busy */
  30545. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  30546. if( IS_LOCK_ERROR(rc) ){
  30547. storeLastErrno(pFile, tErrno);
  30548. }
  30549. } else {
  30550. /* got it, set the type and return ok */
  30551. pFile->eFileLock = eFileLock;
  30552. }
  30553. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  30554. rc==SQLITE_OK ? "ok" : "failed"));
  30555. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  30556. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  30557. rc = SQLITE_BUSY;
  30558. }
  30559. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  30560. return rc;
  30561. }
  30562. /*
  30563. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  30564. ** must be either NO_LOCK or SHARED_LOCK.
  30565. **
  30566. ** If the locking level of the file descriptor is already at or below
  30567. ** the requested locking level, this routine is a no-op.
  30568. */
  30569. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  30570. unixFile *pFile = (unixFile*)id;
  30571. assert( pFile );
  30572. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  30573. pFile->eFileLock, osGetpid(0)));
  30574. assert( eFileLock<=SHARED_LOCK );
  30575. /* no-op if possible */
  30576. if( pFile->eFileLock==eFileLock ){
  30577. return SQLITE_OK;
  30578. }
  30579. /* shared can just be set because we always have an exclusive */
  30580. if (eFileLock==SHARED_LOCK) {
  30581. pFile->eFileLock = eFileLock;
  30582. return SQLITE_OK;
  30583. }
  30584. /* no, really, unlock. */
  30585. if( robust_flock(pFile->h, LOCK_UN) ){
  30586. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  30587. return SQLITE_OK;
  30588. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  30589. return SQLITE_IOERR_UNLOCK;
  30590. }else{
  30591. pFile->eFileLock = NO_LOCK;
  30592. return SQLITE_OK;
  30593. }
  30594. }
  30595. /*
  30596. ** Close a file.
  30597. */
  30598. static int flockClose(sqlite3_file *id) {
  30599. assert( id!=0 );
  30600. flockUnlock(id, NO_LOCK);
  30601. return closeUnixFile(id);
  30602. }
  30603. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  30604. /******************* End of the flock lock implementation *********************
  30605. ******************************************************************************/
  30606. /******************************************************************************
  30607. ************************ Begin Named Semaphore Locking ************************
  30608. **
  30609. ** Named semaphore locking is only supported on VxWorks.
  30610. **
  30611. ** Semaphore locking is like dot-lock and flock in that it really only
  30612. ** supports EXCLUSIVE locking. Only a single process can read or write
  30613. ** the database file at a time. This reduces potential concurrency, but
  30614. ** makes the lock implementation much easier.
  30615. */
  30616. #if OS_VXWORKS
  30617. /*
  30618. ** This routine checks if there is a RESERVED lock held on the specified
  30619. ** file by this or any other process. If such a lock is held, set *pResOut
  30620. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  30621. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  30622. */
  30623. static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
  30624. int rc = SQLITE_OK;
  30625. int reserved = 0;
  30626. unixFile *pFile = (unixFile*)id;
  30627. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  30628. assert( pFile );
  30629. /* Check if a thread in this process holds such a lock */
  30630. if( pFile->eFileLock>SHARED_LOCK ){
  30631. reserved = 1;
  30632. }
  30633. /* Otherwise see if some other process holds it. */
  30634. if( !reserved ){
  30635. sem_t *pSem = pFile->pInode->pSem;
  30636. if( sem_trywait(pSem)==-1 ){
  30637. int tErrno = errno;
  30638. if( EAGAIN != tErrno ){
  30639. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  30640. storeLastErrno(pFile, tErrno);
  30641. } else {
  30642. /* someone else has the lock when we are in NO_LOCK */
  30643. reserved = (pFile->eFileLock < SHARED_LOCK);
  30644. }
  30645. }else{
  30646. /* we could have it if we want it */
  30647. sem_post(pSem);
  30648. }
  30649. }
  30650. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  30651. *pResOut = reserved;
  30652. return rc;
  30653. }
  30654. /*
  30655. ** Lock the file with the lock specified by parameter eFileLock - one
  30656. ** of the following:
  30657. **
  30658. ** (1) SHARED_LOCK
  30659. ** (2) RESERVED_LOCK
  30660. ** (3) PENDING_LOCK
  30661. ** (4) EXCLUSIVE_LOCK
  30662. **
  30663. ** Sometimes when requesting one lock state, additional lock states
  30664. ** are inserted in between. The locking might fail on one of the later
  30665. ** transitions leaving the lock state different from what it started but
  30666. ** still short of its goal. The following chart shows the allowed
  30667. ** transitions and the inserted intermediate states:
  30668. **
  30669. ** UNLOCKED -> SHARED
  30670. ** SHARED -> RESERVED
  30671. ** SHARED -> (PENDING) -> EXCLUSIVE
  30672. ** RESERVED -> (PENDING) -> EXCLUSIVE
  30673. ** PENDING -> EXCLUSIVE
  30674. **
  30675. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  30676. ** lock states in the sqlite3_file structure, but all locks SHARED or
  30677. ** above are really EXCLUSIVE locks and exclude all other processes from
  30678. ** access the file.
  30679. **
  30680. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  30681. ** routine to lower a locking level.
  30682. */
  30683. static int semXLock(sqlite3_file *id, int eFileLock) {
  30684. unixFile *pFile = (unixFile*)id;
  30685. sem_t *pSem = pFile->pInode->pSem;
  30686. int rc = SQLITE_OK;
  30687. /* if we already have a lock, it is exclusive.
  30688. ** Just adjust level and punt on outta here. */
  30689. if (pFile->eFileLock > NO_LOCK) {
  30690. pFile->eFileLock = eFileLock;
  30691. rc = SQLITE_OK;
  30692. goto sem_end_lock;
  30693. }
  30694. /* lock semaphore now but bail out when already locked. */
  30695. if( sem_trywait(pSem)==-1 ){
  30696. rc = SQLITE_BUSY;
  30697. goto sem_end_lock;
  30698. }
  30699. /* got it, set the type and return ok */
  30700. pFile->eFileLock = eFileLock;
  30701. sem_end_lock:
  30702. return rc;
  30703. }
  30704. /*
  30705. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  30706. ** must be either NO_LOCK or SHARED_LOCK.
  30707. **
  30708. ** If the locking level of the file descriptor is already at or below
  30709. ** the requested locking level, this routine is a no-op.
  30710. */
  30711. static int semXUnlock(sqlite3_file *id, int eFileLock) {
  30712. unixFile *pFile = (unixFile*)id;
  30713. sem_t *pSem = pFile->pInode->pSem;
  30714. assert( pFile );
  30715. assert( pSem );
  30716. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  30717. pFile->eFileLock, osGetpid(0)));
  30718. assert( eFileLock<=SHARED_LOCK );
  30719. /* no-op if possible */
  30720. if( pFile->eFileLock==eFileLock ){
  30721. return SQLITE_OK;
  30722. }
  30723. /* shared can just be set because we always have an exclusive */
  30724. if (eFileLock==SHARED_LOCK) {
  30725. pFile->eFileLock = eFileLock;
  30726. return SQLITE_OK;
  30727. }
  30728. /* no, really unlock. */
  30729. if ( sem_post(pSem)==-1 ) {
  30730. int rc, tErrno = errno;
  30731. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  30732. if( IS_LOCK_ERROR(rc) ){
  30733. storeLastErrno(pFile, tErrno);
  30734. }
  30735. return rc;
  30736. }
  30737. pFile->eFileLock = NO_LOCK;
  30738. return SQLITE_OK;
  30739. }
  30740. /*
  30741. ** Close a file.
  30742. */
  30743. static int semXClose(sqlite3_file *id) {
  30744. if( id ){
  30745. unixFile *pFile = (unixFile*)id;
  30746. semXUnlock(id, NO_LOCK);
  30747. assert( pFile );
  30748. unixEnterMutex();
  30749. releaseInodeInfo(pFile);
  30750. unixLeaveMutex();
  30751. closeUnixFile(id);
  30752. }
  30753. return SQLITE_OK;
  30754. }
  30755. #endif /* OS_VXWORKS */
  30756. /*
  30757. ** Named semaphore locking is only available on VxWorks.
  30758. **
  30759. *************** End of the named semaphore lock implementation ****************
  30760. ******************************************************************************/
  30761. /******************************************************************************
  30762. *************************** Begin AFP Locking *********************************
  30763. **
  30764. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  30765. ** on Apple Macintosh computers - both OS9 and OSX.
  30766. **
  30767. ** Third-party implementations of AFP are available. But this code here
  30768. ** only works on OSX.
  30769. */
  30770. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30771. /*
  30772. ** The afpLockingContext structure contains all afp lock specific state
  30773. */
  30774. typedef struct afpLockingContext afpLockingContext;
  30775. struct afpLockingContext {
  30776. int reserved;
  30777. const char *dbPath; /* Name of the open file */
  30778. };
  30779. struct ByteRangeLockPB2
  30780. {
  30781. unsigned long long offset; /* offset to first byte to lock */
  30782. unsigned long long length; /* nbr of bytes to lock */
  30783. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  30784. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  30785. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  30786. int fd; /* file desc to assoc this lock with */
  30787. };
  30788. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  30789. /*
  30790. ** This is a utility for setting or clearing a bit-range lock on an
  30791. ** AFP filesystem.
  30792. **
  30793. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  30794. */
  30795. static int afpSetLock(
  30796. const char *path, /* Name of the file to be locked or unlocked */
  30797. unixFile *pFile, /* Open file descriptor on path */
  30798. unsigned long long offset, /* First byte to be locked */
  30799. unsigned long long length, /* Number of bytes to lock */
  30800. int setLockFlag /* True to set lock. False to clear lock */
  30801. ){
  30802. struct ByteRangeLockPB2 pb;
  30803. int err;
  30804. pb.unLockFlag = setLockFlag ? 0 : 1;
  30805. pb.startEndFlag = 0;
  30806. pb.offset = offset;
  30807. pb.length = length;
  30808. pb.fd = pFile->h;
  30809. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  30810. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  30811. offset, length));
  30812. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  30813. if ( err==-1 ) {
  30814. int rc;
  30815. int tErrno = errno;
  30816. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  30817. path, tErrno, strerror(tErrno)));
  30818. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  30819. rc = SQLITE_BUSY;
  30820. #else
  30821. rc = sqliteErrorFromPosixError(tErrno,
  30822. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  30823. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  30824. if( IS_LOCK_ERROR(rc) ){
  30825. storeLastErrno(pFile, tErrno);
  30826. }
  30827. return rc;
  30828. } else {
  30829. return SQLITE_OK;
  30830. }
  30831. }
  30832. /*
  30833. ** This routine checks if there is a RESERVED lock held on the specified
  30834. ** file by this or any other process. If such a lock is held, set *pResOut
  30835. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  30836. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  30837. */
  30838. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  30839. int rc = SQLITE_OK;
  30840. int reserved = 0;
  30841. unixFile *pFile = (unixFile*)id;
  30842. afpLockingContext *context;
  30843. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  30844. assert( pFile );
  30845. context = (afpLockingContext *) pFile->lockingContext;
  30846. if( context->reserved ){
  30847. *pResOut = 1;
  30848. return SQLITE_OK;
  30849. }
  30850. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  30851. /* Check if a thread in this process holds such a lock */
  30852. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  30853. reserved = 1;
  30854. }
  30855. /* Otherwise see if some other process holds it.
  30856. */
  30857. if( !reserved ){
  30858. /* lock the RESERVED byte */
  30859. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  30860. if( SQLITE_OK==lrc ){
  30861. /* if we succeeded in taking the reserved lock, unlock it to restore
  30862. ** the original state */
  30863. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  30864. } else {
  30865. /* if we failed to get the lock then someone else must have it */
  30866. reserved = 1;
  30867. }
  30868. if( IS_LOCK_ERROR(lrc) ){
  30869. rc=lrc;
  30870. }
  30871. }
  30872. unixLeaveMutex();
  30873. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  30874. *pResOut = reserved;
  30875. return rc;
  30876. }
  30877. /*
  30878. ** Lock the file with the lock specified by parameter eFileLock - one
  30879. ** of the following:
  30880. **
  30881. ** (1) SHARED_LOCK
  30882. ** (2) RESERVED_LOCK
  30883. ** (3) PENDING_LOCK
  30884. ** (4) EXCLUSIVE_LOCK
  30885. **
  30886. ** Sometimes when requesting one lock state, additional lock states
  30887. ** are inserted in between. The locking might fail on one of the later
  30888. ** transitions leaving the lock state different from what it started but
  30889. ** still short of its goal. The following chart shows the allowed
  30890. ** transitions and the inserted intermediate states:
  30891. **
  30892. ** UNLOCKED -> SHARED
  30893. ** SHARED -> RESERVED
  30894. ** SHARED -> (PENDING) -> EXCLUSIVE
  30895. ** RESERVED -> (PENDING) -> EXCLUSIVE
  30896. ** PENDING -> EXCLUSIVE
  30897. **
  30898. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  30899. ** routine to lower a locking level.
  30900. */
  30901. static int afpLock(sqlite3_file *id, int eFileLock){
  30902. int rc = SQLITE_OK;
  30903. unixFile *pFile = (unixFile*)id;
  30904. unixInodeInfo *pInode = pFile->pInode;
  30905. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  30906. assert( pFile );
  30907. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  30908. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  30909. azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
  30910. /* If there is already a lock of this type or more restrictive on the
  30911. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  30912. ** unixEnterMutex() hasn't been called yet.
  30913. */
  30914. if( pFile->eFileLock>=eFileLock ){
  30915. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  30916. azFileLock(eFileLock)));
  30917. return SQLITE_OK;
  30918. }
  30919. /* Make sure the locking sequence is correct
  30920. ** (1) We never move from unlocked to anything higher than shared lock.
  30921. ** (2) SQLite never explicitly requests a pendig lock.
  30922. ** (3) A shared lock is always held when a reserve lock is requested.
  30923. */
  30924. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  30925. assert( eFileLock!=PENDING_LOCK );
  30926. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  30927. /* This mutex is needed because pFile->pInode is shared across threads
  30928. */
  30929. unixEnterMutex();
  30930. pInode = pFile->pInode;
  30931. /* If some thread using this PID has a lock via a different unixFile*
  30932. ** handle that precludes the requested lock, return BUSY.
  30933. */
  30934. if( (pFile->eFileLock!=pInode->eFileLock &&
  30935. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  30936. ){
  30937. rc = SQLITE_BUSY;
  30938. goto afp_end_lock;
  30939. }
  30940. /* If a SHARED lock is requested, and some thread using this PID already
  30941. ** has a SHARED or RESERVED lock, then increment reference counts and
  30942. ** return SQLITE_OK.
  30943. */
  30944. if( eFileLock==SHARED_LOCK &&
  30945. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  30946. assert( eFileLock==SHARED_LOCK );
  30947. assert( pFile->eFileLock==0 );
  30948. assert( pInode->nShared>0 );
  30949. pFile->eFileLock = SHARED_LOCK;
  30950. pInode->nShared++;
  30951. pInode->nLock++;
  30952. goto afp_end_lock;
  30953. }
  30954. /* A PENDING lock is needed before acquiring a SHARED lock and before
  30955. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  30956. ** be released.
  30957. */
  30958. if( eFileLock==SHARED_LOCK
  30959. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  30960. ){
  30961. int failed;
  30962. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  30963. if (failed) {
  30964. rc = failed;
  30965. goto afp_end_lock;
  30966. }
  30967. }
  30968. /* If control gets to this point, then actually go ahead and make
  30969. ** operating system calls for the specified lock.
  30970. */
  30971. if( eFileLock==SHARED_LOCK ){
  30972. int lrc1, lrc2, lrc1Errno = 0;
  30973. long lk, mask;
  30974. assert( pInode->nShared==0 );
  30975. assert( pInode->eFileLock==0 );
  30976. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  30977. /* Now get the read-lock SHARED_LOCK */
  30978. /* note that the quality of the randomness doesn't matter that much */
  30979. lk = random();
  30980. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  30981. lrc1 = afpSetLock(context->dbPath, pFile,
  30982. SHARED_FIRST+pInode->sharedByte, 1, 1);
  30983. if( IS_LOCK_ERROR(lrc1) ){
  30984. lrc1Errno = pFile->lastErrno;
  30985. }
  30986. /* Drop the temporary PENDING lock */
  30987. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  30988. if( IS_LOCK_ERROR(lrc1) ) {
  30989. storeLastErrno(pFile, lrc1Errno);
  30990. rc = lrc1;
  30991. goto afp_end_lock;
  30992. } else if( IS_LOCK_ERROR(lrc2) ){
  30993. rc = lrc2;
  30994. goto afp_end_lock;
  30995. } else if( lrc1 != SQLITE_OK ) {
  30996. rc = lrc1;
  30997. } else {
  30998. pFile->eFileLock = SHARED_LOCK;
  30999. pInode->nLock++;
  31000. pInode->nShared = 1;
  31001. }
  31002. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  31003. /* We are trying for an exclusive lock but another thread in this
  31004. ** same process is still holding a shared lock. */
  31005. rc = SQLITE_BUSY;
  31006. }else{
  31007. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  31008. ** assumed that there is a SHARED or greater lock on the file
  31009. ** already.
  31010. */
  31011. int failed = 0;
  31012. assert( 0!=pFile->eFileLock );
  31013. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  31014. /* Acquire a RESERVED lock */
  31015. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  31016. if( !failed ){
  31017. context->reserved = 1;
  31018. }
  31019. }
  31020. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  31021. /* Acquire an EXCLUSIVE lock */
  31022. /* Remove the shared lock before trying the range. we'll need to
  31023. ** reestablish the shared lock if we can't get the afpUnlock
  31024. */
  31025. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  31026. pInode->sharedByte, 1, 0)) ){
  31027. int failed2 = SQLITE_OK;
  31028. /* now attemmpt to get the exclusive lock range */
  31029. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  31030. SHARED_SIZE, 1);
  31031. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  31032. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  31033. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  31034. ** a critical I/O error
  31035. */
  31036. rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
  31037. SQLITE_IOERR_LOCK;
  31038. goto afp_end_lock;
  31039. }
  31040. }else{
  31041. rc = failed;
  31042. }
  31043. }
  31044. if( failed ){
  31045. rc = failed;
  31046. }
  31047. }
  31048. if( rc==SQLITE_OK ){
  31049. pFile->eFileLock = eFileLock;
  31050. pInode->eFileLock = eFileLock;
  31051. }else if( eFileLock==EXCLUSIVE_LOCK ){
  31052. pFile->eFileLock = PENDING_LOCK;
  31053. pInode->eFileLock = PENDING_LOCK;
  31054. }
  31055. afp_end_lock:
  31056. unixLeaveMutex();
  31057. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  31058. rc==SQLITE_OK ? "ok" : "failed"));
  31059. return rc;
  31060. }
  31061. /*
  31062. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  31063. ** must be either NO_LOCK or SHARED_LOCK.
  31064. **
  31065. ** If the locking level of the file descriptor is already at or below
  31066. ** the requested locking level, this routine is a no-op.
  31067. */
  31068. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  31069. int rc = SQLITE_OK;
  31070. unixFile *pFile = (unixFile*)id;
  31071. unixInodeInfo *pInode;
  31072. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  31073. int skipShared = 0;
  31074. #ifdef SQLITE_TEST
  31075. int h = pFile->h;
  31076. #endif
  31077. assert( pFile );
  31078. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  31079. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  31080. osGetpid(0)));
  31081. assert( eFileLock<=SHARED_LOCK );
  31082. if( pFile->eFileLock<=eFileLock ){
  31083. return SQLITE_OK;
  31084. }
  31085. unixEnterMutex();
  31086. pInode = pFile->pInode;
  31087. assert( pInode->nShared!=0 );
  31088. if( pFile->eFileLock>SHARED_LOCK ){
  31089. assert( pInode->eFileLock==pFile->eFileLock );
  31090. SimulateIOErrorBenign(1);
  31091. SimulateIOError( h=(-1) )
  31092. SimulateIOErrorBenign(0);
  31093. #ifdef SQLITE_DEBUG
  31094. /* When reducing a lock such that other processes can start
  31095. ** reading the database file again, make sure that the
  31096. ** transaction counter was updated if any part of the database
  31097. ** file changed. If the transaction counter is not updated,
  31098. ** other connections to the same file might not realize that
  31099. ** the file has changed and hence might not know to flush their
  31100. ** cache. The use of a stale cache can lead to database corruption.
  31101. */
  31102. assert( pFile->inNormalWrite==0
  31103. || pFile->dbUpdate==0
  31104. || pFile->transCntrChng==1 );
  31105. pFile->inNormalWrite = 0;
  31106. #endif
  31107. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  31108. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  31109. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  31110. /* only re-establish the shared lock if necessary */
  31111. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  31112. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  31113. } else {
  31114. skipShared = 1;
  31115. }
  31116. }
  31117. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  31118. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  31119. }
  31120. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  31121. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  31122. if( !rc ){
  31123. context->reserved = 0;
  31124. }
  31125. }
  31126. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  31127. pInode->eFileLock = SHARED_LOCK;
  31128. }
  31129. }
  31130. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  31131. /* Decrement the shared lock counter. Release the lock using an
  31132. ** OS call only when all threads in this same process have released
  31133. ** the lock.
  31134. */
  31135. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  31136. pInode->nShared--;
  31137. if( pInode->nShared==0 ){
  31138. SimulateIOErrorBenign(1);
  31139. SimulateIOError( h=(-1) )
  31140. SimulateIOErrorBenign(0);
  31141. if( !skipShared ){
  31142. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  31143. }
  31144. if( !rc ){
  31145. pInode->eFileLock = NO_LOCK;
  31146. pFile->eFileLock = NO_LOCK;
  31147. }
  31148. }
  31149. if( rc==SQLITE_OK ){
  31150. pInode->nLock--;
  31151. assert( pInode->nLock>=0 );
  31152. if( pInode->nLock==0 ){
  31153. closePendingFds(pFile);
  31154. }
  31155. }
  31156. }
  31157. unixLeaveMutex();
  31158. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  31159. return rc;
  31160. }
  31161. /*
  31162. ** Close a file & cleanup AFP specific locking context
  31163. */
  31164. static int afpClose(sqlite3_file *id) {
  31165. int rc = SQLITE_OK;
  31166. unixFile *pFile = (unixFile*)id;
  31167. assert( id!=0 );
  31168. afpUnlock(id, NO_LOCK);
  31169. unixEnterMutex();
  31170. if( pFile->pInode && pFile->pInode->nLock ){
  31171. /* If there are outstanding locks, do not actually close the file just
  31172. ** yet because that would clear those locks. Instead, add the file
  31173. ** descriptor to pInode->aPending. It will be automatically closed when
  31174. ** the last lock is cleared.
  31175. */
  31176. setPendingFd(pFile);
  31177. }
  31178. releaseInodeInfo(pFile);
  31179. sqlite3_free(pFile->lockingContext);
  31180. rc = closeUnixFile(id);
  31181. unixLeaveMutex();
  31182. return rc;
  31183. }
  31184. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  31185. /*
  31186. ** The code above is the AFP lock implementation. The code is specific
  31187. ** to MacOSX and does not work on other unix platforms. No alternative
  31188. ** is available. If you don't compile for a mac, then the "unix-afp"
  31189. ** VFS is not available.
  31190. **
  31191. ********************* End of the AFP lock implementation **********************
  31192. ******************************************************************************/
  31193. /******************************************************************************
  31194. *************************** Begin NFS Locking ********************************/
  31195. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  31196. /*
  31197. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  31198. ** must be either NO_LOCK or SHARED_LOCK.
  31199. **
  31200. ** If the locking level of the file descriptor is already at or below
  31201. ** the requested locking level, this routine is a no-op.
  31202. */
  31203. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  31204. return posixUnlock(id, eFileLock, 1);
  31205. }
  31206. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  31207. /*
  31208. ** The code above is the NFS lock implementation. The code is specific
  31209. ** to MacOSX and does not work on other unix platforms. No alternative
  31210. ** is available.
  31211. **
  31212. ********************* End of the NFS lock implementation **********************
  31213. ******************************************************************************/
  31214. /******************************************************************************
  31215. **************** Non-locking sqlite3_file methods *****************************
  31216. **
  31217. ** The next division contains implementations for all methods of the
  31218. ** sqlite3_file object other than the locking methods. The locking
  31219. ** methods were defined in divisions above (one locking method per
  31220. ** division). Those methods that are common to all locking modes
  31221. ** are gather together into this division.
  31222. */
  31223. /*
  31224. ** Seek to the offset passed as the second argument, then read cnt
  31225. ** bytes into pBuf. Return the number of bytes actually read.
  31226. **
  31227. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  31228. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  31229. ** one system to another. Since SQLite does not define USE_PREAD
  31230. ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
  31231. ** See tickets #2741 and #2681.
  31232. **
  31233. ** To avoid stomping the errno value on a failed read the lastErrno value
  31234. ** is set before returning.
  31235. */
  31236. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  31237. int got;
  31238. int prior = 0;
  31239. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  31240. i64 newOffset;
  31241. #endif
  31242. TIMER_START;
  31243. assert( cnt==(cnt&0x1ffff) );
  31244. assert( id->h>2 );
  31245. do{
  31246. #if defined(USE_PREAD)
  31247. got = osPread(id->h, pBuf, cnt, offset);
  31248. SimulateIOError( got = -1 );
  31249. #elif defined(USE_PREAD64)
  31250. got = osPread64(id->h, pBuf, cnt, offset);
  31251. SimulateIOError( got = -1 );
  31252. #else
  31253. newOffset = lseek(id->h, offset, SEEK_SET);
  31254. SimulateIOError( newOffset = -1 );
  31255. if( newOffset<0 ){
  31256. storeLastErrno((unixFile*)id, errno);
  31257. return -1;
  31258. }
  31259. got = osRead(id->h, pBuf, cnt);
  31260. #endif
  31261. if( got==cnt ) break;
  31262. if( got<0 ){
  31263. if( errno==EINTR ){ got = 1; continue; }
  31264. prior = 0;
  31265. storeLastErrno((unixFile*)id, errno);
  31266. break;
  31267. }else if( got>0 ){
  31268. cnt -= got;
  31269. offset += got;
  31270. prior += got;
  31271. pBuf = (void*)(got + (char*)pBuf);
  31272. }
  31273. }while( got>0 );
  31274. TIMER_END;
  31275. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  31276. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  31277. return got+prior;
  31278. }
  31279. /*
  31280. ** Read data from a file into a buffer. Return SQLITE_OK if all
  31281. ** bytes were read successfully and SQLITE_IOERR if anything goes
  31282. ** wrong.
  31283. */
  31284. static int unixRead(
  31285. sqlite3_file *id,
  31286. void *pBuf,
  31287. int amt,
  31288. sqlite3_int64 offset
  31289. ){
  31290. unixFile *pFile = (unixFile *)id;
  31291. int got;
  31292. assert( id );
  31293. assert( offset>=0 );
  31294. assert( amt>0 );
  31295. /* If this is a database file (not a journal, master-journal or temp
  31296. ** file), the bytes in the locking range should never be read or written. */
  31297. #if 0
  31298. assert( pFile->pUnused==0
  31299. || offset>=PENDING_BYTE+512
  31300. || offset+amt<=PENDING_BYTE
  31301. );
  31302. #endif
  31303. #if SQLITE_MAX_MMAP_SIZE>0
  31304. /* Deal with as much of this read request as possible by transfering
  31305. ** data from the memory mapping using memcpy(). */
  31306. if( offset<pFile->mmapSize ){
  31307. if( offset+amt <= pFile->mmapSize ){
  31308. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  31309. return SQLITE_OK;
  31310. }else{
  31311. int nCopy = pFile->mmapSize - offset;
  31312. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  31313. pBuf = &((u8 *)pBuf)[nCopy];
  31314. amt -= nCopy;
  31315. offset += nCopy;
  31316. }
  31317. }
  31318. #endif
  31319. got = seekAndRead(pFile, offset, pBuf, amt);
  31320. if( got==amt ){
  31321. return SQLITE_OK;
  31322. }else if( got<0 ){
  31323. /* lastErrno set by seekAndRead */
  31324. return SQLITE_IOERR_READ;
  31325. }else{
  31326. storeLastErrno(pFile, 0); /* not a system error */
  31327. /* Unread parts of the buffer must be zero-filled */
  31328. memset(&((char*)pBuf)[got], 0, amt-got);
  31329. return SQLITE_IOERR_SHORT_READ;
  31330. }
  31331. }
  31332. /*
  31333. ** Attempt to seek the file-descriptor passed as the first argument to
  31334. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  31335. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  31336. ** return the actual number of bytes written (which may be less than
  31337. ** nBuf).
  31338. */
  31339. static int seekAndWriteFd(
  31340. int fd, /* File descriptor to write to */
  31341. i64 iOff, /* File offset to begin writing at */
  31342. const void *pBuf, /* Copy data from this buffer to the file */
  31343. int nBuf, /* Size of buffer pBuf in bytes */
  31344. int *piErrno /* OUT: Error number if error occurs */
  31345. ){
  31346. int rc = 0; /* Value returned by system call */
  31347. assert( nBuf==(nBuf&0x1ffff) );
  31348. assert( fd>2 );
  31349. assert( piErrno!=0 );
  31350. nBuf &= 0x1ffff;
  31351. TIMER_START;
  31352. #if defined(USE_PREAD)
  31353. do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  31354. #elif defined(USE_PREAD64)
  31355. do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  31356. #else
  31357. do{
  31358. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  31359. SimulateIOError( iSeek = -1 );
  31360. if( iSeek<0 ){
  31361. rc = -1;
  31362. break;
  31363. }
  31364. rc = osWrite(fd, pBuf, nBuf);
  31365. }while( rc<0 && errno==EINTR );
  31366. #endif
  31367. TIMER_END;
  31368. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  31369. if( rc<0 ) *piErrno = errno;
  31370. return rc;
  31371. }
  31372. /*
  31373. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  31374. ** Return the number of bytes actually read. Update the offset.
  31375. **
  31376. ** To avoid stomping the errno value on a failed write the lastErrno value
  31377. ** is set before returning.
  31378. */
  31379. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  31380. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  31381. }
  31382. /*
  31383. ** Write data from a buffer into a file. Return SQLITE_OK on success
  31384. ** or some other error code on failure.
  31385. */
  31386. static int unixWrite(
  31387. sqlite3_file *id,
  31388. const void *pBuf,
  31389. int amt,
  31390. sqlite3_int64 offset
  31391. ){
  31392. unixFile *pFile = (unixFile*)id;
  31393. int wrote = 0;
  31394. assert( id );
  31395. assert( amt>0 );
  31396. /* If this is a database file (not a journal, master-journal or temp
  31397. ** file), the bytes in the locking range should never be read or written. */
  31398. #if 0
  31399. assert( pFile->pUnused==0
  31400. || offset>=PENDING_BYTE+512
  31401. || offset+amt<=PENDING_BYTE
  31402. );
  31403. #endif
  31404. #ifdef SQLITE_DEBUG
  31405. /* If we are doing a normal write to a database file (as opposed to
  31406. ** doing a hot-journal rollback or a write to some file other than a
  31407. ** normal database file) then record the fact that the database
  31408. ** has changed. If the transaction counter is modified, record that
  31409. ** fact too.
  31410. */
  31411. if( pFile->inNormalWrite ){
  31412. pFile->dbUpdate = 1; /* The database has been modified */
  31413. if( offset<=24 && offset+amt>=27 ){
  31414. int rc;
  31415. char oldCntr[4];
  31416. SimulateIOErrorBenign(1);
  31417. rc = seekAndRead(pFile, 24, oldCntr, 4);
  31418. SimulateIOErrorBenign(0);
  31419. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  31420. pFile->transCntrChng = 1; /* The transaction counter has changed */
  31421. }
  31422. }
  31423. }
  31424. #endif
  31425. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  31426. /* Deal with as much of this write request as possible by transfering
  31427. ** data from the memory mapping using memcpy(). */
  31428. if( offset<pFile->mmapSize ){
  31429. if( offset+amt <= pFile->mmapSize ){
  31430. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  31431. return SQLITE_OK;
  31432. }else{
  31433. int nCopy = pFile->mmapSize - offset;
  31434. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  31435. pBuf = &((u8 *)pBuf)[nCopy];
  31436. amt -= nCopy;
  31437. offset += nCopy;
  31438. }
  31439. }
  31440. #endif
  31441. while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
  31442. amt -= wrote;
  31443. offset += wrote;
  31444. pBuf = &((char*)pBuf)[wrote];
  31445. }
  31446. SimulateIOError(( wrote=(-1), amt=1 ));
  31447. SimulateDiskfullError(( wrote=0, amt=1 ));
  31448. if( amt>wrote ){
  31449. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  31450. /* lastErrno set by seekAndWrite */
  31451. return SQLITE_IOERR_WRITE;
  31452. }else{
  31453. storeLastErrno(pFile, 0); /* not a system error */
  31454. return SQLITE_FULL;
  31455. }
  31456. }
  31457. return SQLITE_OK;
  31458. }
  31459. #ifdef SQLITE_TEST
  31460. /*
  31461. ** Count the number of fullsyncs and normal syncs. This is used to test
  31462. ** that syncs and fullsyncs are occurring at the right times.
  31463. */
  31464. SQLITE_API int sqlite3_sync_count = 0;
  31465. SQLITE_API int sqlite3_fullsync_count = 0;
  31466. #endif
  31467. /*
  31468. ** We do not trust systems to provide a working fdatasync(). Some do.
  31469. ** Others do no. To be safe, we will stick with the (slightly slower)
  31470. ** fsync(). If you know that your system does support fdatasync() correctly,
  31471. ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
  31472. */
  31473. #if !defined(fdatasync) && !HAVE_FDATASYNC
  31474. # define fdatasync fsync
  31475. #endif
  31476. /*
  31477. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  31478. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  31479. ** only available on Mac OS X. But that could change.
  31480. */
  31481. #ifdef F_FULLFSYNC
  31482. # define HAVE_FULLFSYNC 1
  31483. #else
  31484. # define HAVE_FULLFSYNC 0
  31485. #endif
  31486. /*
  31487. ** The fsync() system call does not work as advertised on many
  31488. ** unix systems. The following procedure is an attempt to make
  31489. ** it work better.
  31490. **
  31491. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  31492. ** for testing when we want to run through the test suite quickly.
  31493. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  31494. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  31495. ** or power failure will likely corrupt the database file.
  31496. **
  31497. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  31498. ** The idea behind dataOnly is that it should only write the file content
  31499. ** to disk, not the inode. We only set dataOnly if the file size is
  31500. ** unchanged since the file size is part of the inode. However,
  31501. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  31502. ** file size has changed. The only real difference between fdatasync()
  31503. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  31504. ** inode if the mtime or owner or other inode attributes have changed.
  31505. ** We only care about the file size, not the other file attributes, so
  31506. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  31507. ** So, we always use fdatasync() if it is available, regardless of
  31508. ** the value of the dataOnly flag.
  31509. */
  31510. static int full_fsync(int fd, int fullSync, int dataOnly){
  31511. int rc;
  31512. /* The following "ifdef/elif/else/" block has the same structure as
  31513. ** the one below. It is replicated here solely to avoid cluttering
  31514. ** up the real code with the UNUSED_PARAMETER() macros.
  31515. */
  31516. #ifdef SQLITE_NO_SYNC
  31517. UNUSED_PARAMETER(fd);
  31518. UNUSED_PARAMETER(fullSync);
  31519. UNUSED_PARAMETER(dataOnly);
  31520. #elif HAVE_FULLFSYNC
  31521. UNUSED_PARAMETER(dataOnly);
  31522. #else
  31523. UNUSED_PARAMETER(fullSync);
  31524. UNUSED_PARAMETER(dataOnly);
  31525. #endif
  31526. /* Record the number of times that we do a normal fsync() and
  31527. ** FULLSYNC. This is used during testing to verify that this procedure
  31528. ** gets called with the correct arguments.
  31529. */
  31530. #ifdef SQLITE_TEST
  31531. if( fullSync ) sqlite3_fullsync_count++;
  31532. sqlite3_sync_count++;
  31533. #endif
  31534. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  31535. ** no-op. But go ahead and call fstat() to validate the file
  31536. ** descriptor as we need a method to provoke a failure during
  31537. ** coverate testing.
  31538. */
  31539. #ifdef SQLITE_NO_SYNC
  31540. {
  31541. struct stat buf;
  31542. rc = osFstat(fd, &buf);
  31543. }
  31544. #elif HAVE_FULLFSYNC
  31545. if( fullSync ){
  31546. rc = osFcntl(fd, F_FULLFSYNC, 0);
  31547. }else{
  31548. rc = 1;
  31549. }
  31550. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  31551. ** It shouldn't be possible for fullfsync to fail on the local
  31552. ** file system (on OSX), so failure indicates that FULLFSYNC
  31553. ** isn't supported for this file system. So, attempt an fsync
  31554. ** and (for now) ignore the overhead of a superfluous fcntl call.
  31555. ** It'd be better to detect fullfsync support once and avoid
  31556. ** the fcntl call every time sync is called.
  31557. */
  31558. if( rc ) rc = fsync(fd);
  31559. #elif defined(__APPLE__)
  31560. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  31561. ** so currently we default to the macro that redefines fdatasync to fsync
  31562. */
  31563. rc = fsync(fd);
  31564. #else
  31565. rc = fdatasync(fd);
  31566. #if OS_VXWORKS
  31567. if( rc==-1 && errno==ENOTSUP ){
  31568. rc = fsync(fd);
  31569. }
  31570. #endif /* OS_VXWORKS */
  31571. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  31572. if( OS_VXWORKS && rc!= -1 ){
  31573. rc = 0;
  31574. }
  31575. return rc;
  31576. }
  31577. /*
  31578. ** Open a file descriptor to the directory containing file zFilename.
  31579. ** If successful, *pFd is set to the opened file descriptor and
  31580. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  31581. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  31582. ** value.
  31583. **
  31584. ** The directory file descriptor is used for only one thing - to
  31585. ** fsync() a directory to make sure file creation and deletion events
  31586. ** are flushed to disk. Such fsyncs are not needed on newer
  31587. ** journaling filesystems, but are required on older filesystems.
  31588. **
  31589. ** This routine can be overridden using the xSetSysCall interface.
  31590. ** The ability to override this routine was added in support of the
  31591. ** chromium sandbox. Opening a directory is a security risk (we are
  31592. ** told) so making it overrideable allows the chromium sandbox to
  31593. ** replace this routine with a harmless no-op. To make this routine
  31594. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  31595. ** *pFd set to a negative number.
  31596. **
  31597. ** If SQLITE_OK is returned, the caller is responsible for closing
  31598. ** the file descriptor *pFd using close().
  31599. */
  31600. static int openDirectory(const char *zFilename, int *pFd){
  31601. int ii;
  31602. int fd = -1;
  31603. char zDirname[MAX_PATHNAME+1];
  31604. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  31605. for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
  31606. if( ii>0 ){
  31607. zDirname[ii] = '\0';
  31608. }else{
  31609. if( zDirname[0]!='/' ) zDirname[0] = '.';
  31610. zDirname[1] = 0;
  31611. }
  31612. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  31613. if( fd>=0 ){
  31614. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  31615. }
  31616. *pFd = fd;
  31617. if( fd>=0 ) return SQLITE_OK;
  31618. return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
  31619. }
  31620. /*
  31621. ** Make sure all writes to a particular file are committed to disk.
  31622. **
  31623. ** If dataOnly==0 then both the file itself and its metadata (file
  31624. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  31625. ** file data is synced.
  31626. **
  31627. ** Under Unix, also make sure that the directory entry for the file
  31628. ** has been created by fsync-ing the directory that contains the file.
  31629. ** If we do not do this and we encounter a power failure, the directory
  31630. ** entry for the journal might not exist after we reboot. The next
  31631. ** SQLite to access the file will not know that the journal exists (because
  31632. ** the directory entry for the journal was never created) and the transaction
  31633. ** will not roll back - possibly leading to database corruption.
  31634. */
  31635. static int unixSync(sqlite3_file *id, int flags){
  31636. int rc;
  31637. unixFile *pFile = (unixFile*)id;
  31638. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  31639. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  31640. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  31641. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  31642. || (flags&0x0F)==SQLITE_SYNC_FULL
  31643. );
  31644. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  31645. ** line is to test that doing so does not cause any problems.
  31646. */
  31647. SimulateDiskfullError( return SQLITE_FULL );
  31648. assert( pFile );
  31649. OSTRACE(("SYNC %-3d\n", pFile->h));
  31650. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  31651. SimulateIOError( rc=1 );
  31652. if( rc ){
  31653. storeLastErrno(pFile, errno);
  31654. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  31655. }
  31656. /* Also fsync the directory containing the file if the DIRSYNC flag
  31657. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  31658. ** are unable to fsync a directory, so ignore errors on the fsync.
  31659. */
  31660. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  31661. int dirfd;
  31662. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  31663. HAVE_FULLFSYNC, isFullsync));
  31664. rc = osOpenDirectory(pFile->zPath, &dirfd);
  31665. if( rc==SQLITE_OK ){
  31666. full_fsync(dirfd, 0, 0);
  31667. robust_close(pFile, dirfd, __LINE__);
  31668. }else{
  31669. assert( rc==SQLITE_CANTOPEN );
  31670. rc = SQLITE_OK;
  31671. }
  31672. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  31673. }
  31674. return rc;
  31675. }
  31676. /*
  31677. ** Truncate an open file to a specified size
  31678. */
  31679. static int unixTruncate(sqlite3_file *id, i64 nByte){
  31680. unixFile *pFile = (unixFile *)id;
  31681. int rc;
  31682. assert( pFile );
  31683. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  31684. /* If the user has configured a chunk-size for this file, truncate the
  31685. ** file so that it consists of an integer number of chunks (i.e. the
  31686. ** actual file size after the operation may be larger than the requested
  31687. ** size).
  31688. */
  31689. if( pFile->szChunk>0 ){
  31690. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  31691. }
  31692. rc = robust_ftruncate(pFile->h, nByte);
  31693. if( rc ){
  31694. storeLastErrno(pFile, errno);
  31695. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  31696. }else{
  31697. #ifdef SQLITE_DEBUG
  31698. /* If we are doing a normal write to a database file (as opposed to
  31699. ** doing a hot-journal rollback or a write to some file other than a
  31700. ** normal database file) and we truncate the file to zero length,
  31701. ** that effectively updates the change counter. This might happen
  31702. ** when restoring a database using the backup API from a zero-length
  31703. ** source.
  31704. */
  31705. if( pFile->inNormalWrite && nByte==0 ){
  31706. pFile->transCntrChng = 1;
  31707. }
  31708. #endif
  31709. #if SQLITE_MAX_MMAP_SIZE>0
  31710. /* If the file was just truncated to a size smaller than the currently
  31711. ** mapped region, reduce the effective mapping size as well. SQLite will
  31712. ** use read() and write() to access data beyond this point from now on.
  31713. */
  31714. if( nByte<pFile->mmapSize ){
  31715. pFile->mmapSize = nByte;
  31716. }
  31717. #endif
  31718. return SQLITE_OK;
  31719. }
  31720. }
  31721. /*
  31722. ** Determine the current size of a file in bytes
  31723. */
  31724. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  31725. int rc;
  31726. struct stat buf;
  31727. assert( id );
  31728. rc = osFstat(((unixFile*)id)->h, &buf);
  31729. SimulateIOError( rc=1 );
  31730. if( rc!=0 ){
  31731. storeLastErrno((unixFile*)id, errno);
  31732. return SQLITE_IOERR_FSTAT;
  31733. }
  31734. *pSize = buf.st_size;
  31735. /* When opening a zero-size database, the findInodeInfo() procedure
  31736. ** writes a single byte into that file in order to work around a bug
  31737. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  31738. ** layers, we need to report this file size as zero even though it is
  31739. ** really 1. Ticket #3260.
  31740. */
  31741. if( *pSize==1 ) *pSize = 0;
  31742. return SQLITE_OK;
  31743. }
  31744. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  31745. /*
  31746. ** Handler for proxy-locking file-control verbs. Defined below in the
  31747. ** proxying locking division.
  31748. */
  31749. static int proxyFileControl(sqlite3_file*,int,void*);
  31750. #endif
  31751. /*
  31752. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  31753. ** file-control operation. Enlarge the database to nBytes in size
  31754. ** (rounded up to the next chunk-size). If the database is already
  31755. ** nBytes or larger, this routine is a no-op.
  31756. */
  31757. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  31758. if( pFile->szChunk>0 ){
  31759. i64 nSize; /* Required file size */
  31760. struct stat buf; /* Used to hold return values of fstat() */
  31761. if( osFstat(pFile->h, &buf) ){
  31762. return SQLITE_IOERR_FSTAT;
  31763. }
  31764. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  31765. if( nSize>(i64)buf.st_size ){
  31766. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  31767. /* The code below is handling the return value of osFallocate()
  31768. ** correctly. posix_fallocate() is defined to "returns zero on success,
  31769. ** or an error number on failure". See the manpage for details. */
  31770. int err;
  31771. do{
  31772. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  31773. }while( err==EINTR );
  31774. if( err ) return SQLITE_IOERR_WRITE;
  31775. #else
  31776. /* If the OS does not have posix_fallocate(), fake it. Write a
  31777. ** single byte to the last byte in each block that falls entirely
  31778. ** within the extended region. Then, if required, a single byte
  31779. ** at offset (nSize-1), to set the size of the file correctly.
  31780. ** This is a similar technique to that used by glibc on systems
  31781. ** that do not have a real fallocate() call.
  31782. */
  31783. int nBlk = buf.st_blksize; /* File-system block size */
  31784. int nWrite = 0; /* Number of bytes written by seekAndWrite */
  31785. i64 iWrite; /* Next offset to write to */
  31786. iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
  31787. assert( iWrite>=buf.st_size );
  31788. assert( ((iWrite+1)%nBlk)==0 );
  31789. for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
  31790. if( iWrite>=nSize ) iWrite = nSize - 1;
  31791. nWrite = seekAndWrite(pFile, iWrite, "", 1);
  31792. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  31793. }
  31794. #endif
  31795. }
  31796. }
  31797. #if SQLITE_MAX_MMAP_SIZE>0
  31798. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  31799. int rc;
  31800. if( pFile->szChunk<=0 ){
  31801. if( robust_ftruncate(pFile->h, nByte) ){
  31802. storeLastErrno(pFile, errno);
  31803. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  31804. }
  31805. }
  31806. rc = unixMapfile(pFile, nByte);
  31807. return rc;
  31808. }
  31809. #endif
  31810. return SQLITE_OK;
  31811. }
  31812. /*
  31813. ** If *pArg is initially negative then this is a query. Set *pArg to
  31814. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  31815. **
  31816. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  31817. */
  31818. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  31819. if( *pArg<0 ){
  31820. *pArg = (pFile->ctrlFlags & mask)!=0;
  31821. }else if( (*pArg)==0 ){
  31822. pFile->ctrlFlags &= ~mask;
  31823. }else{
  31824. pFile->ctrlFlags |= mask;
  31825. }
  31826. }
  31827. /* Forward declaration */
  31828. static int unixGetTempname(int nBuf, char *zBuf);
  31829. /*
  31830. ** Information and control of an open file handle.
  31831. */
  31832. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  31833. unixFile *pFile = (unixFile*)id;
  31834. switch( op ){
  31835. case SQLITE_FCNTL_LOCKSTATE: {
  31836. *(int*)pArg = pFile->eFileLock;
  31837. return SQLITE_OK;
  31838. }
  31839. case SQLITE_FCNTL_LAST_ERRNO: {
  31840. *(int*)pArg = pFile->lastErrno;
  31841. return SQLITE_OK;
  31842. }
  31843. case SQLITE_FCNTL_CHUNK_SIZE: {
  31844. pFile->szChunk = *(int *)pArg;
  31845. return SQLITE_OK;
  31846. }
  31847. case SQLITE_FCNTL_SIZE_HINT: {
  31848. int rc;
  31849. SimulateIOErrorBenign(1);
  31850. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  31851. SimulateIOErrorBenign(0);
  31852. return rc;
  31853. }
  31854. case SQLITE_FCNTL_PERSIST_WAL: {
  31855. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  31856. return SQLITE_OK;
  31857. }
  31858. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  31859. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  31860. return SQLITE_OK;
  31861. }
  31862. case SQLITE_FCNTL_VFSNAME: {
  31863. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  31864. return SQLITE_OK;
  31865. }
  31866. case SQLITE_FCNTL_TEMPFILENAME: {
  31867. char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
  31868. if( zTFile ){
  31869. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  31870. *(char**)pArg = zTFile;
  31871. }
  31872. return SQLITE_OK;
  31873. }
  31874. case SQLITE_FCNTL_HAS_MOVED: {
  31875. *(int*)pArg = fileHasMoved(pFile);
  31876. return SQLITE_OK;
  31877. }
  31878. #if SQLITE_MAX_MMAP_SIZE>0
  31879. case SQLITE_FCNTL_MMAP_SIZE: {
  31880. i64 newLimit = *(i64*)pArg;
  31881. int rc = SQLITE_OK;
  31882. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  31883. newLimit = sqlite3GlobalConfig.mxMmap;
  31884. }
  31885. *(i64*)pArg = pFile->mmapSizeMax;
  31886. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  31887. pFile->mmapSizeMax = newLimit;
  31888. if( pFile->mmapSize>0 ){
  31889. unixUnmapfile(pFile);
  31890. rc = unixMapfile(pFile, -1);
  31891. }
  31892. }
  31893. return rc;
  31894. }
  31895. #endif
  31896. #ifdef SQLITE_DEBUG
  31897. /* The pager calls this method to signal that it has done
  31898. ** a rollback and that the database is therefore unchanged and
  31899. ** it hence it is OK for the transaction change counter to be
  31900. ** unchanged.
  31901. */
  31902. case SQLITE_FCNTL_DB_UNCHANGED: {
  31903. ((unixFile*)id)->dbUpdate = 0;
  31904. return SQLITE_OK;
  31905. }
  31906. #endif
  31907. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  31908. case SQLITE_FCNTL_SET_LOCKPROXYFILE:
  31909. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  31910. return proxyFileControl(id,op,pArg);
  31911. }
  31912. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  31913. }
  31914. return SQLITE_NOTFOUND;
  31915. }
  31916. /*
  31917. ** Return the sector size in bytes of the underlying block device for
  31918. ** the specified file. This is almost always 512 bytes, but may be
  31919. ** larger for some devices.
  31920. **
  31921. ** SQLite code assumes this function cannot fail. It also assumes that
  31922. ** if two files are created in the same file-system directory (i.e.
  31923. ** a database and its journal file) that the sector size will be the
  31924. ** same for both.
  31925. */
  31926. #ifndef __QNXNTO__
  31927. static int unixSectorSize(sqlite3_file *NotUsed){
  31928. UNUSED_PARAMETER(NotUsed);
  31929. return SQLITE_DEFAULT_SECTOR_SIZE;
  31930. }
  31931. #endif
  31932. /*
  31933. ** The following version of unixSectorSize() is optimized for QNX.
  31934. */
  31935. #ifdef __QNXNTO__
  31936. #include <sys/dcmd_blk.h>
  31937. #include <sys/statvfs.h>
  31938. static int unixSectorSize(sqlite3_file *id){
  31939. unixFile *pFile = (unixFile*)id;
  31940. if( pFile->sectorSize == 0 ){
  31941. struct statvfs fsInfo;
  31942. /* Set defaults for non-supported filesystems */
  31943. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  31944. pFile->deviceCharacteristics = 0;
  31945. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  31946. return pFile->sectorSize;
  31947. }
  31948. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  31949. pFile->sectorSize = fsInfo.f_bsize;
  31950. pFile->deviceCharacteristics =
  31951. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  31952. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  31953. ** the write succeeds */
  31954. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  31955. ** so it is ordered */
  31956. 0;
  31957. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  31958. pFile->sectorSize = fsInfo.f_bsize;
  31959. pFile->deviceCharacteristics =
  31960. /* etfs cluster size writes are atomic */
  31961. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  31962. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  31963. ** the write succeeds */
  31964. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  31965. ** so it is ordered */
  31966. 0;
  31967. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  31968. pFile->sectorSize = fsInfo.f_bsize;
  31969. pFile->deviceCharacteristics =
  31970. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  31971. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  31972. ** the write succeeds */
  31973. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  31974. ** so it is ordered */
  31975. 0;
  31976. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  31977. pFile->sectorSize = fsInfo.f_bsize;
  31978. pFile->deviceCharacteristics =
  31979. /* full bitset of atomics from max sector size and smaller */
  31980. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  31981. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  31982. ** so it is ordered */
  31983. 0;
  31984. }else if( strstr(fsInfo.f_basetype, "dos") ){
  31985. pFile->sectorSize = fsInfo.f_bsize;
  31986. pFile->deviceCharacteristics =
  31987. /* full bitset of atomics from max sector size and smaller */
  31988. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  31989. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  31990. ** so it is ordered */
  31991. 0;
  31992. }else{
  31993. pFile->deviceCharacteristics =
  31994. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  31995. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  31996. ** the write succeeds */
  31997. 0;
  31998. }
  31999. }
  32000. /* Last chance verification. If the sector size isn't a multiple of 512
  32001. ** then it isn't valid.*/
  32002. if( pFile->sectorSize % 512 != 0 ){
  32003. pFile->deviceCharacteristics = 0;
  32004. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  32005. }
  32006. return pFile->sectorSize;
  32007. }
  32008. #endif /* __QNXNTO__ */
  32009. /*
  32010. ** Return the device characteristics for the file.
  32011. **
  32012. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  32013. ** However, that choice is controversial since technically the underlying
  32014. ** file system does not always provide powersafe overwrites. (In other
  32015. ** words, after a power-loss event, parts of the file that were never
  32016. ** written might end up being altered.) However, non-PSOW behavior is very,
  32017. ** very rare. And asserting PSOW makes a large reduction in the amount
  32018. ** of required I/O for journaling, since a lot of padding is eliminated.
  32019. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  32020. ** available to turn it off and URI query parameter available to turn it off.
  32021. */
  32022. static int unixDeviceCharacteristics(sqlite3_file *id){
  32023. unixFile *p = (unixFile*)id;
  32024. int rc = 0;
  32025. #ifdef __QNXNTO__
  32026. if( p->sectorSize==0 ) unixSectorSize(id);
  32027. rc = p->deviceCharacteristics;
  32028. #endif
  32029. if( p->ctrlFlags & UNIXFILE_PSOW ){
  32030. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  32031. }
  32032. return rc;
  32033. }
  32034. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  32035. /*
  32036. ** Return the system page size.
  32037. **
  32038. ** This function should not be called directly by other code in this file.
  32039. ** Instead, it should be called via macro osGetpagesize().
  32040. */
  32041. static int unixGetpagesize(void){
  32042. #if OS_VXWORKS
  32043. return 1024;
  32044. #elif defined(_BSD_SOURCE)
  32045. return getpagesize();
  32046. #else
  32047. return (int)sysconf(_SC_PAGESIZE);
  32048. #endif
  32049. }
  32050. #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
  32051. #ifndef SQLITE_OMIT_WAL
  32052. /*
  32053. ** Object used to represent an shared memory buffer.
  32054. **
  32055. ** When multiple threads all reference the same wal-index, each thread
  32056. ** has its own unixShm object, but they all point to a single instance
  32057. ** of this unixShmNode object. In other words, each wal-index is opened
  32058. ** only once per process.
  32059. **
  32060. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  32061. ** We could coalesce this object into unixInodeInfo, but that would mean
  32062. ** every open file that does not use shared memory (in other words, most
  32063. ** open files) would have to carry around this extra information. So
  32064. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  32065. ** and the unixShmNode object is created only when needed.
  32066. **
  32067. ** unixMutexHeld() must be true when creating or destroying
  32068. ** this object or while reading or writing the following fields:
  32069. **
  32070. ** nRef
  32071. **
  32072. ** The following fields are read-only after the object is created:
  32073. **
  32074. ** fid
  32075. ** zFilename
  32076. **
  32077. ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
  32078. ** unixMutexHeld() is true when reading or writing any other field
  32079. ** in this structure.
  32080. */
  32081. struct unixShmNode {
  32082. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  32083. sqlite3_mutex *mutex; /* Mutex to access this object */
  32084. char *zFilename; /* Name of the mmapped file */
  32085. int h; /* Open file descriptor */
  32086. int szRegion; /* Size of shared-memory regions */
  32087. u16 nRegion; /* Size of array apRegion */
  32088. u8 isReadonly; /* True if read-only */
  32089. char **apRegion; /* Array of mapped shared-memory regions */
  32090. int nRef; /* Number of unixShm objects pointing to this */
  32091. unixShm *pFirst; /* All unixShm objects pointing to this */
  32092. #ifdef SQLITE_DEBUG
  32093. u8 exclMask; /* Mask of exclusive locks held */
  32094. u8 sharedMask; /* Mask of shared locks held */
  32095. u8 nextShmId; /* Next available unixShm.id value */
  32096. #endif
  32097. };
  32098. /*
  32099. ** Structure used internally by this VFS to record the state of an
  32100. ** open shared memory connection.
  32101. **
  32102. ** The following fields are initialized when this object is created and
  32103. ** are read-only thereafter:
  32104. **
  32105. ** unixShm.pFile
  32106. ** unixShm.id
  32107. **
  32108. ** All other fields are read/write. The unixShm.pFile->mutex must be held
  32109. ** while accessing any read/write fields.
  32110. */
  32111. struct unixShm {
  32112. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  32113. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  32114. u8 hasMutex; /* True if holding the unixShmNode mutex */
  32115. u8 id; /* Id of this connection within its unixShmNode */
  32116. u16 sharedMask; /* Mask of shared locks held */
  32117. u16 exclMask; /* Mask of exclusive locks held */
  32118. };
  32119. /*
  32120. ** Constants used for locking
  32121. */
  32122. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  32123. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  32124. /*
  32125. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  32126. **
  32127. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  32128. ** otherwise.
  32129. */
  32130. static int unixShmSystemLock(
  32131. unixFile *pFile, /* Open connection to the WAL file */
  32132. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  32133. int ofst, /* First byte of the locking range */
  32134. int n /* Number of bytes to lock */
  32135. ){
  32136. unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
  32137. struct flock f; /* The posix advisory locking structure */
  32138. int rc = SQLITE_OK; /* Result code form fcntl() */
  32139. /* Access to the unixShmNode object is serialized by the caller */
  32140. pShmNode = pFile->pInode->pShmNode;
  32141. assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
  32142. /* Shared locks never span more than one byte */
  32143. assert( n==1 || lockType!=F_RDLCK );
  32144. /* Locks are within range */
  32145. assert( n>=1 && n<=SQLITE_SHM_NLOCK );
  32146. if( pShmNode->h>=0 ){
  32147. /* Initialize the locking parameters */
  32148. memset(&f, 0, sizeof(f));
  32149. f.l_type = lockType;
  32150. f.l_whence = SEEK_SET;
  32151. f.l_start = ofst;
  32152. f.l_len = n;
  32153. rc = osFcntl(pShmNode->h, F_SETLK, &f);
  32154. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  32155. }
  32156. /* Update the global lock state and do debug tracing */
  32157. #ifdef SQLITE_DEBUG
  32158. { u16 mask;
  32159. OSTRACE(("SHM-LOCK "));
  32160. mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
  32161. if( rc==SQLITE_OK ){
  32162. if( lockType==F_UNLCK ){
  32163. OSTRACE(("unlock %d ok", ofst));
  32164. pShmNode->exclMask &= ~mask;
  32165. pShmNode->sharedMask &= ~mask;
  32166. }else if( lockType==F_RDLCK ){
  32167. OSTRACE(("read-lock %d ok", ofst));
  32168. pShmNode->exclMask &= ~mask;
  32169. pShmNode->sharedMask |= mask;
  32170. }else{
  32171. assert( lockType==F_WRLCK );
  32172. OSTRACE(("write-lock %d ok", ofst));
  32173. pShmNode->exclMask |= mask;
  32174. pShmNode->sharedMask &= ~mask;
  32175. }
  32176. }else{
  32177. if( lockType==F_UNLCK ){
  32178. OSTRACE(("unlock %d failed", ofst));
  32179. }else if( lockType==F_RDLCK ){
  32180. OSTRACE(("read-lock failed"));
  32181. }else{
  32182. assert( lockType==F_WRLCK );
  32183. OSTRACE(("write-lock %d failed", ofst));
  32184. }
  32185. }
  32186. OSTRACE((" - afterwards %03x,%03x\n",
  32187. pShmNode->sharedMask, pShmNode->exclMask));
  32188. }
  32189. #endif
  32190. return rc;
  32191. }
  32192. /*
  32193. ** Return the minimum number of 32KB shm regions that should be mapped at
  32194. ** a time, assuming that each mapping must be an integer multiple of the
  32195. ** current system page-size.
  32196. **
  32197. ** Usually, this is 1. The exception seems to be systems that are configured
  32198. ** to use 64KB pages - in this case each mapping must cover at least two
  32199. ** shm regions.
  32200. */
  32201. static int unixShmRegionPerMap(void){
  32202. int shmsz = 32*1024; /* SHM region size */
  32203. int pgsz = osGetpagesize(); /* System page size */
  32204. assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
  32205. if( pgsz<shmsz ) return 1;
  32206. return pgsz/shmsz;
  32207. }
  32208. /*
  32209. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  32210. **
  32211. ** This is not a VFS shared-memory method; it is a utility function called
  32212. ** by VFS shared-memory methods.
  32213. */
  32214. static void unixShmPurge(unixFile *pFd){
  32215. unixShmNode *p = pFd->pInode->pShmNode;
  32216. assert( unixMutexHeld() );
  32217. if( p && ALWAYS(p->nRef==0) ){
  32218. int nShmPerMap = unixShmRegionPerMap();
  32219. int i;
  32220. assert( p->pInode==pFd->pInode );
  32221. sqlite3_mutex_free(p->mutex);
  32222. for(i=0; i<p->nRegion; i+=nShmPerMap){
  32223. if( p->h>=0 ){
  32224. osMunmap(p->apRegion[i], p->szRegion);
  32225. }else{
  32226. sqlite3_free(p->apRegion[i]);
  32227. }
  32228. }
  32229. sqlite3_free(p->apRegion);
  32230. if( p->h>=0 ){
  32231. robust_close(pFd, p->h, __LINE__);
  32232. p->h = -1;
  32233. }
  32234. p->pInode->pShmNode = 0;
  32235. sqlite3_free(p);
  32236. }
  32237. }
  32238. /*
  32239. ** Open a shared-memory area associated with open database file pDbFd.
  32240. ** This particular implementation uses mmapped files.
  32241. **
  32242. ** The file used to implement shared-memory is in the same directory
  32243. ** as the open database file and has the same name as the open database
  32244. ** file with the "-shm" suffix added. For example, if the database file
  32245. ** is "/home/user1/config.db" then the file that is created and mmapped
  32246. ** for shared memory will be called "/home/user1/config.db-shm".
  32247. **
  32248. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  32249. ** some other tmpfs mount. But if a file in a different directory
  32250. ** from the database file is used, then differing access permissions
  32251. ** or a chroot() might cause two different processes on the same
  32252. ** database to end up using different files for shared memory -
  32253. ** meaning that their memory would not really be shared - resulting
  32254. ** in database corruption. Nevertheless, this tmpfs file usage
  32255. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  32256. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  32257. ** option results in an incompatible build of SQLite; builds of SQLite
  32258. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  32259. ** same database file at the same time, database corruption will likely
  32260. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  32261. ** "unsupported" and may go away in a future SQLite release.
  32262. **
  32263. ** When opening a new shared-memory file, if no other instances of that
  32264. ** file are currently open, in this process or in other processes, then
  32265. ** the file must be truncated to zero length or have its header cleared.
  32266. **
  32267. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  32268. ** that means that an exclusive lock is held on the database file and
  32269. ** that no other processes are able to read or write the database. In
  32270. ** that case, we do not really need shared memory. No shared memory
  32271. ** file is created. The shared memory will be simulated with heap memory.
  32272. */
  32273. static int unixOpenSharedMemory(unixFile *pDbFd){
  32274. struct unixShm *p = 0; /* The connection to be opened */
  32275. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  32276. int rc; /* Result code */
  32277. unixInodeInfo *pInode; /* The inode of fd */
  32278. char *zShmFilename; /* Name of the file used for SHM */
  32279. int nShmFilename; /* Size of the SHM filename in bytes */
  32280. /* Allocate space for the new unixShm object. */
  32281. p = sqlite3_malloc64( sizeof(*p) );
  32282. if( p==0 ) return SQLITE_NOMEM_BKPT;
  32283. memset(p, 0, sizeof(*p));
  32284. assert( pDbFd->pShm==0 );
  32285. /* Check to see if a unixShmNode object already exists. Reuse an existing
  32286. ** one if present. Create a new one if necessary.
  32287. */
  32288. unixEnterMutex();
  32289. pInode = pDbFd->pInode;
  32290. pShmNode = pInode->pShmNode;
  32291. if( pShmNode==0 ){
  32292. struct stat sStat; /* fstat() info for database file */
  32293. #ifndef SQLITE_SHM_DIRECTORY
  32294. const char *zBasePath = pDbFd->zPath;
  32295. #endif
  32296. /* Call fstat() to figure out the permissions on the database file. If
  32297. ** a new *-shm file is created, an attempt will be made to create it
  32298. ** with the same permissions.
  32299. */
  32300. if( osFstat(pDbFd->h, &sStat) ){
  32301. rc = SQLITE_IOERR_FSTAT;
  32302. goto shm_open_err;
  32303. }
  32304. #ifdef SQLITE_SHM_DIRECTORY
  32305. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  32306. #else
  32307. nShmFilename = 6 + (int)strlen(zBasePath);
  32308. #endif
  32309. pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
  32310. if( pShmNode==0 ){
  32311. rc = SQLITE_NOMEM_BKPT;
  32312. goto shm_open_err;
  32313. }
  32314. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  32315. zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
  32316. #ifdef SQLITE_SHM_DIRECTORY
  32317. sqlite3_snprintf(nShmFilename, zShmFilename,
  32318. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  32319. (u32)sStat.st_ino, (u32)sStat.st_dev);
  32320. #else
  32321. sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
  32322. sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
  32323. #endif
  32324. pShmNode->h = -1;
  32325. pDbFd->pInode->pShmNode = pShmNode;
  32326. pShmNode->pInode = pDbFd->pInode;
  32327. if( sqlite3GlobalConfig.bCoreMutex ){
  32328. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  32329. if( pShmNode->mutex==0 ){
  32330. rc = SQLITE_NOMEM_BKPT;
  32331. goto shm_open_err;
  32332. }
  32333. }
  32334. if( pInode->bProcessLock==0 ){
  32335. int openFlags = O_RDWR | O_CREAT;
  32336. if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  32337. openFlags = O_RDONLY;
  32338. pShmNode->isReadonly = 1;
  32339. }
  32340. pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
  32341. if( pShmNode->h<0 ){
  32342. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
  32343. goto shm_open_err;
  32344. }
  32345. /* If this process is running as root, make sure that the SHM file
  32346. ** is owned by the same user that owns the original database. Otherwise,
  32347. ** the original owner will not be able to connect.
  32348. */
  32349. robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
  32350. /* Check to see if another process is holding the dead-man switch.
  32351. ** If not, truncate the file to zero length.
  32352. */
  32353. rc = SQLITE_OK;
  32354. if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
  32355. if( robust_ftruncate(pShmNode->h, 0) ){
  32356. rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
  32357. }
  32358. }
  32359. if( rc==SQLITE_OK ){
  32360. rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
  32361. }
  32362. if( rc ) goto shm_open_err;
  32363. }
  32364. }
  32365. /* Make the new connection a child of the unixShmNode */
  32366. p->pShmNode = pShmNode;
  32367. #ifdef SQLITE_DEBUG
  32368. p->id = pShmNode->nextShmId++;
  32369. #endif
  32370. pShmNode->nRef++;
  32371. pDbFd->pShm = p;
  32372. unixLeaveMutex();
  32373. /* The reference count on pShmNode has already been incremented under
  32374. ** the cover of the unixEnterMutex() mutex and the pointer from the
  32375. ** new (struct unixShm) object to the pShmNode has been set. All that is
  32376. ** left to do is to link the new object into the linked list starting
  32377. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  32378. ** mutex.
  32379. */
  32380. sqlite3_mutex_enter(pShmNode->mutex);
  32381. p->pNext = pShmNode->pFirst;
  32382. pShmNode->pFirst = p;
  32383. sqlite3_mutex_leave(pShmNode->mutex);
  32384. return SQLITE_OK;
  32385. /* Jump here on any error */
  32386. shm_open_err:
  32387. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  32388. sqlite3_free(p);
  32389. unixLeaveMutex();
  32390. return rc;
  32391. }
  32392. /*
  32393. ** This function is called to obtain a pointer to region iRegion of the
  32394. ** shared-memory associated with the database file fd. Shared-memory regions
  32395. ** are numbered starting from zero. Each shared-memory region is szRegion
  32396. ** bytes in size.
  32397. **
  32398. ** If an error occurs, an error code is returned and *pp is set to NULL.
  32399. **
  32400. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  32401. ** region has not been allocated (by any client, including one running in a
  32402. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  32403. ** bExtend is non-zero and the requested shared-memory region has not yet
  32404. ** been allocated, it is allocated by this function.
  32405. **
  32406. ** If the shared-memory region has already been allocated or is allocated by
  32407. ** this call as described above, then it is mapped into this processes
  32408. ** address space (if it is not already), *pp is set to point to the mapped
  32409. ** memory and SQLITE_OK returned.
  32410. */
  32411. static int unixShmMap(
  32412. sqlite3_file *fd, /* Handle open on database file */
  32413. int iRegion, /* Region to retrieve */
  32414. int szRegion, /* Size of regions */
  32415. int bExtend, /* True to extend file if necessary */
  32416. void volatile **pp /* OUT: Mapped memory */
  32417. ){
  32418. unixFile *pDbFd = (unixFile*)fd;
  32419. unixShm *p;
  32420. unixShmNode *pShmNode;
  32421. int rc = SQLITE_OK;
  32422. int nShmPerMap = unixShmRegionPerMap();
  32423. int nReqRegion;
  32424. /* If the shared-memory file has not yet been opened, open it now. */
  32425. if( pDbFd->pShm==0 ){
  32426. rc = unixOpenSharedMemory(pDbFd);
  32427. if( rc!=SQLITE_OK ) return rc;
  32428. }
  32429. p = pDbFd->pShm;
  32430. pShmNode = p->pShmNode;
  32431. sqlite3_mutex_enter(pShmNode->mutex);
  32432. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  32433. assert( pShmNode->pInode==pDbFd->pInode );
  32434. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  32435. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  32436. /* Minimum number of regions required to be mapped. */
  32437. nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
  32438. if( pShmNode->nRegion<nReqRegion ){
  32439. char **apNew; /* New apRegion[] array */
  32440. int nByte = nReqRegion*szRegion; /* Minimum required file size */
  32441. struct stat sStat; /* Used by fstat() */
  32442. pShmNode->szRegion = szRegion;
  32443. if( pShmNode->h>=0 ){
  32444. /* The requested region is not mapped into this processes address space.
  32445. ** Check to see if it has been allocated (i.e. if the wal-index file is
  32446. ** large enough to contain the requested region).
  32447. */
  32448. if( osFstat(pShmNode->h, &sStat) ){
  32449. rc = SQLITE_IOERR_SHMSIZE;
  32450. goto shmpage_out;
  32451. }
  32452. if( sStat.st_size<nByte ){
  32453. /* The requested memory region does not exist. If bExtend is set to
  32454. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  32455. */
  32456. if( !bExtend ){
  32457. goto shmpage_out;
  32458. }
  32459. /* Alternatively, if bExtend is true, extend the file. Do this by
  32460. ** writing a single byte to the end of each (OS) page being
  32461. ** allocated or extended. Technically, we need only write to the
  32462. ** last page in order to extend the file. But writing to all new
  32463. ** pages forces the OS to allocate them immediately, which reduces
  32464. ** the chances of SIGBUS while accessing the mapped region later on.
  32465. */
  32466. else{
  32467. static const int pgsz = 4096;
  32468. int iPg;
  32469. /* Write to the last byte of each newly allocated or extended page */
  32470. assert( (nByte % pgsz)==0 );
  32471. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  32472. int x = 0;
  32473. if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
  32474. const char *zFile = pShmNode->zFilename;
  32475. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  32476. goto shmpage_out;
  32477. }
  32478. }
  32479. }
  32480. }
  32481. }
  32482. /* Map the requested memory region into this processes address space. */
  32483. apNew = (char **)sqlite3_realloc(
  32484. pShmNode->apRegion, nReqRegion*sizeof(char *)
  32485. );
  32486. if( !apNew ){
  32487. rc = SQLITE_IOERR_NOMEM_BKPT;
  32488. goto shmpage_out;
  32489. }
  32490. pShmNode->apRegion = apNew;
  32491. while( pShmNode->nRegion<nReqRegion ){
  32492. int nMap = szRegion*nShmPerMap;
  32493. int i;
  32494. void *pMem;
  32495. if( pShmNode->h>=0 ){
  32496. pMem = osMmap(0, nMap,
  32497. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  32498. MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
  32499. );
  32500. if( pMem==MAP_FAILED ){
  32501. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  32502. goto shmpage_out;
  32503. }
  32504. }else{
  32505. pMem = sqlite3_malloc64(szRegion);
  32506. if( pMem==0 ){
  32507. rc = SQLITE_NOMEM_BKPT;
  32508. goto shmpage_out;
  32509. }
  32510. memset(pMem, 0, szRegion);
  32511. }
  32512. for(i=0; i<nShmPerMap; i++){
  32513. pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
  32514. }
  32515. pShmNode->nRegion += nShmPerMap;
  32516. }
  32517. }
  32518. shmpage_out:
  32519. if( pShmNode->nRegion>iRegion ){
  32520. *pp = pShmNode->apRegion[iRegion];
  32521. }else{
  32522. *pp = 0;
  32523. }
  32524. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  32525. sqlite3_mutex_leave(pShmNode->mutex);
  32526. return rc;
  32527. }
  32528. /*
  32529. ** Change the lock state for a shared-memory segment.
  32530. **
  32531. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  32532. ** different here than in posix. In xShmLock(), one can go from unlocked
  32533. ** to shared and back or from unlocked to exclusive and back. But one may
  32534. ** not go from shared to exclusive or from exclusive to shared.
  32535. */
  32536. static int unixShmLock(
  32537. sqlite3_file *fd, /* Database file holding the shared memory */
  32538. int ofst, /* First lock to acquire or release */
  32539. int n, /* Number of locks to acquire or release */
  32540. int flags /* What to do with the lock */
  32541. ){
  32542. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  32543. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  32544. unixShm *pX; /* For looping over all siblings */
  32545. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  32546. int rc = SQLITE_OK; /* Result code */
  32547. u16 mask; /* Mask of locks to take or release */
  32548. assert( pShmNode==pDbFd->pInode->pShmNode );
  32549. assert( pShmNode->pInode==pDbFd->pInode );
  32550. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  32551. assert( n>=1 );
  32552. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  32553. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  32554. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  32555. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  32556. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  32557. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  32558. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  32559. mask = (1<<(ofst+n)) - (1<<ofst);
  32560. assert( n>1 || mask==(1<<ofst) );
  32561. sqlite3_mutex_enter(pShmNode->mutex);
  32562. if( flags & SQLITE_SHM_UNLOCK ){
  32563. u16 allMask = 0; /* Mask of locks held by siblings */
  32564. /* See if any siblings hold this same lock */
  32565. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  32566. if( pX==p ) continue;
  32567. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  32568. allMask |= pX->sharedMask;
  32569. }
  32570. /* Unlock the system-level locks */
  32571. if( (mask & allMask)==0 ){
  32572. rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  32573. }else{
  32574. rc = SQLITE_OK;
  32575. }
  32576. /* Undo the local locks */
  32577. if( rc==SQLITE_OK ){
  32578. p->exclMask &= ~mask;
  32579. p->sharedMask &= ~mask;
  32580. }
  32581. }else if( flags & SQLITE_SHM_SHARED ){
  32582. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  32583. /* Find out which shared locks are already held by sibling connections.
  32584. ** If any sibling already holds an exclusive lock, go ahead and return
  32585. ** SQLITE_BUSY.
  32586. */
  32587. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  32588. if( (pX->exclMask & mask)!=0 ){
  32589. rc = SQLITE_BUSY;
  32590. break;
  32591. }
  32592. allShared |= pX->sharedMask;
  32593. }
  32594. /* Get shared locks at the system level, if necessary */
  32595. if( rc==SQLITE_OK ){
  32596. if( (allShared & mask)==0 ){
  32597. rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  32598. }else{
  32599. rc = SQLITE_OK;
  32600. }
  32601. }
  32602. /* Get the local shared locks */
  32603. if( rc==SQLITE_OK ){
  32604. p->sharedMask |= mask;
  32605. }
  32606. }else{
  32607. /* Make sure no sibling connections hold locks that will block this
  32608. ** lock. If any do, return SQLITE_BUSY right away.
  32609. */
  32610. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  32611. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  32612. rc = SQLITE_BUSY;
  32613. break;
  32614. }
  32615. }
  32616. /* Get the exclusive locks at the system level. Then if successful
  32617. ** also mark the local connection as being locked.
  32618. */
  32619. if( rc==SQLITE_OK ){
  32620. rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  32621. if( rc==SQLITE_OK ){
  32622. assert( (p->sharedMask & mask)==0 );
  32623. p->exclMask |= mask;
  32624. }
  32625. }
  32626. }
  32627. sqlite3_mutex_leave(pShmNode->mutex);
  32628. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  32629. p->id, osGetpid(0), p->sharedMask, p->exclMask));
  32630. return rc;
  32631. }
  32632. /*
  32633. ** Implement a memory barrier or memory fence on shared memory.
  32634. **
  32635. ** All loads and stores begun before the barrier must complete before
  32636. ** any load or store begun after the barrier.
  32637. */
  32638. static void unixShmBarrier(
  32639. sqlite3_file *fd /* Database file holding the shared memory */
  32640. ){
  32641. UNUSED_PARAMETER(fd);
  32642. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  32643. unixEnterMutex(); /* Also mutex, for redundancy */
  32644. unixLeaveMutex();
  32645. }
  32646. /*
  32647. ** Close a connection to shared-memory. Delete the underlying
  32648. ** storage if deleteFlag is true.
  32649. **
  32650. ** If there is no shared memory associated with the connection then this
  32651. ** routine is a harmless no-op.
  32652. */
  32653. static int unixShmUnmap(
  32654. sqlite3_file *fd, /* The underlying database file */
  32655. int deleteFlag /* Delete shared-memory if true */
  32656. ){
  32657. unixShm *p; /* The connection to be closed */
  32658. unixShmNode *pShmNode; /* The underlying shared-memory file */
  32659. unixShm **pp; /* For looping over sibling connections */
  32660. unixFile *pDbFd; /* The underlying database file */
  32661. pDbFd = (unixFile*)fd;
  32662. p = pDbFd->pShm;
  32663. if( p==0 ) return SQLITE_OK;
  32664. pShmNode = p->pShmNode;
  32665. assert( pShmNode==pDbFd->pInode->pShmNode );
  32666. assert( pShmNode->pInode==pDbFd->pInode );
  32667. /* Remove connection p from the set of connections associated
  32668. ** with pShmNode */
  32669. sqlite3_mutex_enter(pShmNode->mutex);
  32670. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  32671. *pp = p->pNext;
  32672. /* Free the connection p */
  32673. sqlite3_free(p);
  32674. pDbFd->pShm = 0;
  32675. sqlite3_mutex_leave(pShmNode->mutex);
  32676. /* If pShmNode->nRef has reached 0, then close the underlying
  32677. ** shared-memory file, too */
  32678. unixEnterMutex();
  32679. assert( pShmNode->nRef>0 );
  32680. pShmNode->nRef--;
  32681. if( pShmNode->nRef==0 ){
  32682. if( deleteFlag && pShmNode->h>=0 ){
  32683. osUnlink(pShmNode->zFilename);
  32684. }
  32685. unixShmPurge(pDbFd);
  32686. }
  32687. unixLeaveMutex();
  32688. return SQLITE_OK;
  32689. }
  32690. #else
  32691. # define unixShmMap 0
  32692. # define unixShmLock 0
  32693. # define unixShmBarrier 0
  32694. # define unixShmUnmap 0
  32695. #endif /* #ifndef SQLITE_OMIT_WAL */
  32696. #if SQLITE_MAX_MMAP_SIZE>0
  32697. /*
  32698. ** If it is currently memory mapped, unmap file pFd.
  32699. */
  32700. static void unixUnmapfile(unixFile *pFd){
  32701. assert( pFd->nFetchOut==0 );
  32702. if( pFd->pMapRegion ){
  32703. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  32704. pFd->pMapRegion = 0;
  32705. pFd->mmapSize = 0;
  32706. pFd->mmapSizeActual = 0;
  32707. }
  32708. }
  32709. /*
  32710. ** Attempt to set the size of the memory mapping maintained by file
  32711. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  32712. **
  32713. ** If successful, this function sets the following variables:
  32714. **
  32715. ** unixFile.pMapRegion
  32716. ** unixFile.mmapSize
  32717. ** unixFile.mmapSizeActual
  32718. **
  32719. ** If unsuccessful, an error message is logged via sqlite3_log() and
  32720. ** the three variables above are zeroed. In this case SQLite should
  32721. ** continue accessing the database using the xRead() and xWrite()
  32722. ** methods.
  32723. */
  32724. static void unixRemapfile(
  32725. unixFile *pFd, /* File descriptor object */
  32726. i64 nNew /* Required mapping size */
  32727. ){
  32728. const char *zErr = "mmap";
  32729. int h = pFd->h; /* File descriptor open on db file */
  32730. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  32731. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  32732. u8 *pNew = 0; /* Location of new mapping */
  32733. int flags = PROT_READ; /* Flags to pass to mmap() */
  32734. assert( pFd->nFetchOut==0 );
  32735. assert( nNew>pFd->mmapSize );
  32736. assert( nNew<=pFd->mmapSizeMax );
  32737. assert( nNew>0 );
  32738. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  32739. assert( MAP_FAILED!=0 );
  32740. #ifdef SQLITE_MMAP_READWRITE
  32741. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  32742. #endif
  32743. if( pOrig ){
  32744. #if HAVE_MREMAP
  32745. i64 nReuse = pFd->mmapSize;
  32746. #else
  32747. const int szSyspage = osGetpagesize();
  32748. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  32749. #endif
  32750. u8 *pReq = &pOrig[nReuse];
  32751. /* Unmap any pages of the existing mapping that cannot be reused. */
  32752. if( nReuse!=nOrig ){
  32753. osMunmap(pReq, nOrig-nReuse);
  32754. }
  32755. #if HAVE_MREMAP
  32756. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  32757. zErr = "mremap";
  32758. #else
  32759. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  32760. if( pNew!=MAP_FAILED ){
  32761. if( pNew!=pReq ){
  32762. osMunmap(pNew, nNew - nReuse);
  32763. pNew = 0;
  32764. }else{
  32765. pNew = pOrig;
  32766. }
  32767. }
  32768. #endif
  32769. /* The attempt to extend the existing mapping failed. Free it. */
  32770. if( pNew==MAP_FAILED || pNew==0 ){
  32771. osMunmap(pOrig, nReuse);
  32772. }
  32773. }
  32774. /* If pNew is still NULL, try to create an entirely new mapping. */
  32775. if( pNew==0 ){
  32776. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  32777. }
  32778. if( pNew==MAP_FAILED ){
  32779. pNew = 0;
  32780. nNew = 0;
  32781. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  32782. /* If the mmap() above failed, assume that all subsequent mmap() calls
  32783. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  32784. ** in this case. */
  32785. pFd->mmapSizeMax = 0;
  32786. }
  32787. pFd->pMapRegion = (void *)pNew;
  32788. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  32789. }
  32790. /*
  32791. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  32792. ** is already mapped, the existing mapping is replaced by the new). Or, if
  32793. ** there already exists a mapping for this file, and there are still
  32794. ** outstanding xFetch() references to it, this function is a no-op.
  32795. **
  32796. ** If parameter nByte is non-negative, then it is the requested size of
  32797. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  32798. ** requested size is the size of the file on disk. The actual size of the
  32799. ** created mapping is either the requested size or the value configured
  32800. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  32801. **
  32802. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  32803. ** recreated as a result of outstanding references) or an SQLite error
  32804. ** code otherwise.
  32805. */
  32806. static int unixMapfile(unixFile *pFd, i64 nMap){
  32807. assert( nMap>=0 || pFd->nFetchOut==0 );
  32808. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  32809. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  32810. if( nMap<0 ){
  32811. struct stat statbuf; /* Low-level file information */
  32812. if( osFstat(pFd->h, &statbuf) ){
  32813. return SQLITE_IOERR_FSTAT;
  32814. }
  32815. nMap = statbuf.st_size;
  32816. }
  32817. if( nMap>pFd->mmapSizeMax ){
  32818. nMap = pFd->mmapSizeMax;
  32819. }
  32820. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  32821. if( nMap!=pFd->mmapSize ){
  32822. unixRemapfile(pFd, nMap);
  32823. }
  32824. return SQLITE_OK;
  32825. }
  32826. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  32827. /*
  32828. ** If possible, return a pointer to a mapping of file fd starting at offset
  32829. ** iOff. The mapping must be valid for at least nAmt bytes.
  32830. **
  32831. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  32832. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  32833. ** Finally, if an error does occur, return an SQLite error code. The final
  32834. ** value of *pp is undefined in this case.
  32835. **
  32836. ** If this function does return a pointer, the caller must eventually
  32837. ** release the reference by calling unixUnfetch().
  32838. */
  32839. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  32840. #if SQLITE_MAX_MMAP_SIZE>0
  32841. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  32842. #endif
  32843. *pp = 0;
  32844. #if SQLITE_MAX_MMAP_SIZE>0
  32845. if( pFd->mmapSizeMax>0 ){
  32846. if( pFd->pMapRegion==0 ){
  32847. int rc = unixMapfile(pFd, -1);
  32848. if( rc!=SQLITE_OK ) return rc;
  32849. }
  32850. if( pFd->mmapSize >= iOff+nAmt ){
  32851. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  32852. pFd->nFetchOut++;
  32853. }
  32854. }
  32855. #endif
  32856. return SQLITE_OK;
  32857. }
  32858. /*
  32859. ** If the third argument is non-NULL, then this function releases a
  32860. ** reference obtained by an earlier call to unixFetch(). The second
  32861. ** argument passed to this function must be the same as the corresponding
  32862. ** argument that was passed to the unixFetch() invocation.
  32863. **
  32864. ** Or, if the third argument is NULL, then this function is being called
  32865. ** to inform the VFS layer that, according to POSIX, any existing mapping
  32866. ** may now be invalid and should be unmapped.
  32867. */
  32868. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  32869. #if SQLITE_MAX_MMAP_SIZE>0
  32870. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  32871. UNUSED_PARAMETER(iOff);
  32872. /* If p==0 (unmap the entire file) then there must be no outstanding
  32873. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  32874. ** then there must be at least one outstanding. */
  32875. assert( (p==0)==(pFd->nFetchOut==0) );
  32876. /* If p!=0, it must match the iOff value. */
  32877. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  32878. if( p ){
  32879. pFd->nFetchOut--;
  32880. }else{
  32881. unixUnmapfile(pFd);
  32882. }
  32883. assert( pFd->nFetchOut>=0 );
  32884. #else
  32885. UNUSED_PARAMETER(fd);
  32886. UNUSED_PARAMETER(p);
  32887. UNUSED_PARAMETER(iOff);
  32888. #endif
  32889. return SQLITE_OK;
  32890. }
  32891. /*
  32892. ** Here ends the implementation of all sqlite3_file methods.
  32893. **
  32894. ********************** End sqlite3_file Methods *******************************
  32895. ******************************************************************************/
  32896. /*
  32897. ** This division contains definitions of sqlite3_io_methods objects that
  32898. ** implement various file locking strategies. It also contains definitions
  32899. ** of "finder" functions. A finder-function is used to locate the appropriate
  32900. ** sqlite3_io_methods object for a particular database file. The pAppData
  32901. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  32902. ** the correct finder-function for that VFS.
  32903. **
  32904. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  32905. ** object. The only interesting finder-function is autolockIoFinder, which
  32906. ** looks at the filesystem type and tries to guess the best locking
  32907. ** strategy from that.
  32908. **
  32909. ** For finder-function F, two objects are created:
  32910. **
  32911. ** (1) The real finder-function named "FImpt()".
  32912. **
  32913. ** (2) A constant pointer to this function named just "F".
  32914. **
  32915. **
  32916. ** A pointer to the F pointer is used as the pAppData value for VFS
  32917. ** objects. We have to do this instead of letting pAppData point
  32918. ** directly at the finder-function since C90 rules prevent a void*
  32919. ** from be cast into a function pointer.
  32920. **
  32921. **
  32922. ** Each instance of this macro generates two objects:
  32923. **
  32924. ** * A constant sqlite3_io_methods object call METHOD that has locking
  32925. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  32926. **
  32927. ** * An I/O method finder function called FINDER that returns a pointer
  32928. ** to the METHOD object in the previous bullet.
  32929. */
  32930. #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
  32931. static const sqlite3_io_methods METHOD = { \
  32932. VERSION, /* iVersion */ \
  32933. CLOSE, /* xClose */ \
  32934. unixRead, /* xRead */ \
  32935. unixWrite, /* xWrite */ \
  32936. unixTruncate, /* xTruncate */ \
  32937. unixSync, /* xSync */ \
  32938. unixFileSize, /* xFileSize */ \
  32939. LOCK, /* xLock */ \
  32940. UNLOCK, /* xUnlock */ \
  32941. CKLOCK, /* xCheckReservedLock */ \
  32942. unixFileControl, /* xFileControl */ \
  32943. unixSectorSize, /* xSectorSize */ \
  32944. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  32945. SHMMAP, /* xShmMap */ \
  32946. unixShmLock, /* xShmLock */ \
  32947. unixShmBarrier, /* xShmBarrier */ \
  32948. unixShmUnmap, /* xShmUnmap */ \
  32949. unixFetch, /* xFetch */ \
  32950. unixUnfetch, /* xUnfetch */ \
  32951. }; \
  32952. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  32953. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  32954. return &METHOD; \
  32955. } \
  32956. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  32957. = FINDER##Impl;
  32958. /*
  32959. ** Here are all of the sqlite3_io_methods objects for each of the
  32960. ** locking strategies. Functions that return pointers to these methods
  32961. ** are also created.
  32962. */
  32963. IOMETHODS(
  32964. posixIoFinder, /* Finder function name */
  32965. posixIoMethods, /* sqlite3_io_methods object name */
  32966. 3, /* shared memory and mmap are enabled */
  32967. unixClose, /* xClose method */
  32968. unixLock, /* xLock method */
  32969. unixUnlock, /* xUnlock method */
  32970. unixCheckReservedLock, /* xCheckReservedLock method */
  32971. unixShmMap /* xShmMap method */
  32972. )
  32973. IOMETHODS(
  32974. nolockIoFinder, /* Finder function name */
  32975. nolockIoMethods, /* sqlite3_io_methods object name */
  32976. 3, /* shared memory is disabled */
  32977. nolockClose, /* xClose method */
  32978. nolockLock, /* xLock method */
  32979. nolockUnlock, /* xUnlock method */
  32980. nolockCheckReservedLock, /* xCheckReservedLock method */
  32981. 0 /* xShmMap method */
  32982. )
  32983. IOMETHODS(
  32984. dotlockIoFinder, /* Finder function name */
  32985. dotlockIoMethods, /* sqlite3_io_methods object name */
  32986. 1, /* shared memory is disabled */
  32987. dotlockClose, /* xClose method */
  32988. dotlockLock, /* xLock method */
  32989. dotlockUnlock, /* xUnlock method */
  32990. dotlockCheckReservedLock, /* xCheckReservedLock method */
  32991. 0 /* xShmMap method */
  32992. )
  32993. #if SQLITE_ENABLE_LOCKING_STYLE
  32994. IOMETHODS(
  32995. flockIoFinder, /* Finder function name */
  32996. flockIoMethods, /* sqlite3_io_methods object name */
  32997. 1, /* shared memory is disabled */
  32998. flockClose, /* xClose method */
  32999. flockLock, /* xLock method */
  33000. flockUnlock, /* xUnlock method */
  33001. flockCheckReservedLock, /* xCheckReservedLock method */
  33002. 0 /* xShmMap method */
  33003. )
  33004. #endif
  33005. #if OS_VXWORKS
  33006. IOMETHODS(
  33007. semIoFinder, /* Finder function name */
  33008. semIoMethods, /* sqlite3_io_methods object name */
  33009. 1, /* shared memory is disabled */
  33010. semXClose, /* xClose method */
  33011. semXLock, /* xLock method */
  33012. semXUnlock, /* xUnlock method */
  33013. semXCheckReservedLock, /* xCheckReservedLock method */
  33014. 0 /* xShmMap method */
  33015. )
  33016. #endif
  33017. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33018. IOMETHODS(
  33019. afpIoFinder, /* Finder function name */
  33020. afpIoMethods, /* sqlite3_io_methods object name */
  33021. 1, /* shared memory is disabled */
  33022. afpClose, /* xClose method */
  33023. afpLock, /* xLock method */
  33024. afpUnlock, /* xUnlock method */
  33025. afpCheckReservedLock, /* xCheckReservedLock method */
  33026. 0 /* xShmMap method */
  33027. )
  33028. #endif
  33029. /*
  33030. ** The proxy locking method is a "super-method" in the sense that it
  33031. ** opens secondary file descriptors for the conch and lock files and
  33032. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  33033. ** secondary files. For this reason, the division that implements
  33034. ** proxy locking is located much further down in the file. But we need
  33035. ** to go ahead and define the sqlite3_io_methods and finder function
  33036. ** for proxy locking here. So we forward declare the I/O methods.
  33037. */
  33038. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33039. static int proxyClose(sqlite3_file*);
  33040. static int proxyLock(sqlite3_file*, int);
  33041. static int proxyUnlock(sqlite3_file*, int);
  33042. static int proxyCheckReservedLock(sqlite3_file*, int*);
  33043. IOMETHODS(
  33044. proxyIoFinder, /* Finder function name */
  33045. proxyIoMethods, /* sqlite3_io_methods object name */
  33046. 1, /* shared memory is disabled */
  33047. proxyClose, /* xClose method */
  33048. proxyLock, /* xLock method */
  33049. proxyUnlock, /* xUnlock method */
  33050. proxyCheckReservedLock, /* xCheckReservedLock method */
  33051. 0 /* xShmMap method */
  33052. )
  33053. #endif
  33054. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  33055. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33056. IOMETHODS(
  33057. nfsIoFinder, /* Finder function name */
  33058. nfsIoMethods, /* sqlite3_io_methods object name */
  33059. 1, /* shared memory is disabled */
  33060. unixClose, /* xClose method */
  33061. unixLock, /* xLock method */
  33062. nfsUnlock, /* xUnlock method */
  33063. unixCheckReservedLock, /* xCheckReservedLock method */
  33064. 0 /* xShmMap method */
  33065. )
  33066. #endif
  33067. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33068. /*
  33069. ** This "finder" function attempts to determine the best locking strategy
  33070. ** for the database file "filePath". It then returns the sqlite3_io_methods
  33071. ** object that implements that strategy.
  33072. **
  33073. ** This is for MacOSX only.
  33074. */
  33075. static const sqlite3_io_methods *autolockIoFinderImpl(
  33076. const char *filePath, /* name of the database file */
  33077. unixFile *pNew /* open file object for the database file */
  33078. ){
  33079. static const struct Mapping {
  33080. const char *zFilesystem; /* Filesystem type name */
  33081. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  33082. } aMap[] = {
  33083. { "hfs", &posixIoMethods },
  33084. { "ufs", &posixIoMethods },
  33085. { "afpfs", &afpIoMethods },
  33086. { "smbfs", &afpIoMethods },
  33087. { "webdav", &nolockIoMethods },
  33088. { 0, 0 }
  33089. };
  33090. int i;
  33091. struct statfs fsInfo;
  33092. struct flock lockInfo;
  33093. if( !filePath ){
  33094. /* If filePath==NULL that means we are dealing with a transient file
  33095. ** that does not need to be locked. */
  33096. return &nolockIoMethods;
  33097. }
  33098. if( statfs(filePath, &fsInfo) != -1 ){
  33099. if( fsInfo.f_flags & MNT_RDONLY ){
  33100. return &nolockIoMethods;
  33101. }
  33102. for(i=0; aMap[i].zFilesystem; i++){
  33103. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  33104. return aMap[i].pMethods;
  33105. }
  33106. }
  33107. }
  33108. /* Default case. Handles, amongst others, "nfs".
  33109. ** Test byte-range lock using fcntl(). If the call succeeds,
  33110. ** assume that the file-system supports POSIX style locks.
  33111. */
  33112. lockInfo.l_len = 1;
  33113. lockInfo.l_start = 0;
  33114. lockInfo.l_whence = SEEK_SET;
  33115. lockInfo.l_type = F_RDLCK;
  33116. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  33117. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  33118. return &nfsIoMethods;
  33119. } else {
  33120. return &posixIoMethods;
  33121. }
  33122. }else{
  33123. return &dotlockIoMethods;
  33124. }
  33125. }
  33126. static const sqlite3_io_methods
  33127. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  33128. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  33129. #if OS_VXWORKS
  33130. /*
  33131. ** This "finder" function for VxWorks checks to see if posix advisory
  33132. ** locking works. If it does, then that is what is used. If it does not
  33133. ** work, then fallback to named semaphore locking.
  33134. */
  33135. static const sqlite3_io_methods *vxworksIoFinderImpl(
  33136. const char *filePath, /* name of the database file */
  33137. unixFile *pNew /* the open file object */
  33138. ){
  33139. struct flock lockInfo;
  33140. if( !filePath ){
  33141. /* If filePath==NULL that means we are dealing with a transient file
  33142. ** that does not need to be locked. */
  33143. return &nolockIoMethods;
  33144. }
  33145. /* Test if fcntl() is supported and use POSIX style locks.
  33146. ** Otherwise fall back to the named semaphore method.
  33147. */
  33148. lockInfo.l_len = 1;
  33149. lockInfo.l_start = 0;
  33150. lockInfo.l_whence = SEEK_SET;
  33151. lockInfo.l_type = F_RDLCK;
  33152. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  33153. return &posixIoMethods;
  33154. }else{
  33155. return &semIoMethods;
  33156. }
  33157. }
  33158. static const sqlite3_io_methods
  33159. *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
  33160. #endif /* OS_VXWORKS */
  33161. /*
  33162. ** An abstract type for a pointer to an IO method finder function:
  33163. */
  33164. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  33165. /****************************************************************************
  33166. **************************** sqlite3_vfs methods ****************************
  33167. **
  33168. ** This division contains the implementation of methods on the
  33169. ** sqlite3_vfs object.
  33170. */
  33171. /*
  33172. ** Initialize the contents of the unixFile structure pointed to by pId.
  33173. */
  33174. static int fillInUnixFile(
  33175. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  33176. int h, /* Open file descriptor of file being opened */
  33177. sqlite3_file *pId, /* Write to the unixFile structure here */
  33178. const char *zFilename, /* Name of the file being opened */
  33179. int ctrlFlags /* Zero or more UNIXFILE_* values */
  33180. ){
  33181. const sqlite3_io_methods *pLockingStyle;
  33182. unixFile *pNew = (unixFile *)pId;
  33183. int rc = SQLITE_OK;
  33184. assert( pNew->pInode==NULL );
  33185. /* Usually the path zFilename should not be a relative pathname. The
  33186. ** exception is when opening the proxy "conch" file in builds that
  33187. ** include the special Apple locking styles.
  33188. */
  33189. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33190. assert( zFilename==0 || zFilename[0]=='/'
  33191. || pVfs->pAppData==(void*)&autolockIoFinder );
  33192. #else
  33193. assert( zFilename==0 || zFilename[0]=='/' );
  33194. #endif
  33195. /* No locking occurs in temporary files */
  33196. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  33197. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  33198. pNew->h = h;
  33199. pNew->pVfs = pVfs;
  33200. pNew->zPath = zFilename;
  33201. pNew->ctrlFlags = (u8)ctrlFlags;
  33202. #if SQLITE_MAX_MMAP_SIZE>0
  33203. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  33204. #endif
  33205. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  33206. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  33207. pNew->ctrlFlags |= UNIXFILE_PSOW;
  33208. }
  33209. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  33210. pNew->ctrlFlags |= UNIXFILE_EXCL;
  33211. }
  33212. #if OS_VXWORKS
  33213. pNew->pId = vxworksFindFileId(zFilename);
  33214. if( pNew->pId==0 ){
  33215. ctrlFlags |= UNIXFILE_NOLOCK;
  33216. rc = SQLITE_NOMEM_BKPT;
  33217. }
  33218. #endif
  33219. if( ctrlFlags & UNIXFILE_NOLOCK ){
  33220. pLockingStyle = &nolockIoMethods;
  33221. }else{
  33222. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  33223. #if SQLITE_ENABLE_LOCKING_STYLE
  33224. /* Cache zFilename in the locking context (AFP and dotlock override) for
  33225. ** proxyLock activation is possible (remote proxy is based on db name)
  33226. ** zFilename remains valid until file is closed, to support */
  33227. pNew->lockingContext = (void*)zFilename;
  33228. #endif
  33229. }
  33230. if( pLockingStyle == &posixIoMethods
  33231. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33232. || pLockingStyle == &nfsIoMethods
  33233. #endif
  33234. ){
  33235. unixEnterMutex();
  33236. rc = findInodeInfo(pNew, &pNew->pInode);
  33237. if( rc!=SQLITE_OK ){
  33238. /* If an error occurred in findInodeInfo(), close the file descriptor
  33239. ** immediately, before releasing the mutex. findInodeInfo() may fail
  33240. ** in two scenarios:
  33241. **
  33242. ** (a) A call to fstat() failed.
  33243. ** (b) A malloc failed.
  33244. **
  33245. ** Scenario (b) may only occur if the process is holding no other
  33246. ** file descriptors open on the same file. If there were other file
  33247. ** descriptors on this file, then no malloc would be required by
  33248. ** findInodeInfo(). If this is the case, it is quite safe to close
  33249. ** handle h - as it is guaranteed that no posix locks will be released
  33250. ** by doing so.
  33251. **
  33252. ** If scenario (a) caused the error then things are not so safe. The
  33253. ** implicit assumption here is that if fstat() fails, things are in
  33254. ** such bad shape that dropping a lock or two doesn't matter much.
  33255. */
  33256. robust_close(pNew, h, __LINE__);
  33257. h = -1;
  33258. }
  33259. unixLeaveMutex();
  33260. }
  33261. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  33262. else if( pLockingStyle == &afpIoMethods ){
  33263. /* AFP locking uses the file path so it needs to be included in
  33264. ** the afpLockingContext.
  33265. */
  33266. afpLockingContext *pCtx;
  33267. pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  33268. if( pCtx==0 ){
  33269. rc = SQLITE_NOMEM_BKPT;
  33270. }else{
  33271. /* NB: zFilename exists and remains valid until the file is closed
  33272. ** according to requirement F11141. So we do not need to make a
  33273. ** copy of the filename. */
  33274. pCtx->dbPath = zFilename;
  33275. pCtx->reserved = 0;
  33276. srandomdev();
  33277. unixEnterMutex();
  33278. rc = findInodeInfo(pNew, &pNew->pInode);
  33279. if( rc!=SQLITE_OK ){
  33280. sqlite3_free(pNew->lockingContext);
  33281. robust_close(pNew, h, __LINE__);
  33282. h = -1;
  33283. }
  33284. unixLeaveMutex();
  33285. }
  33286. }
  33287. #endif
  33288. else if( pLockingStyle == &dotlockIoMethods ){
  33289. /* Dotfile locking uses the file path so it needs to be included in
  33290. ** the dotlockLockingContext
  33291. */
  33292. char *zLockFile;
  33293. int nFilename;
  33294. assert( zFilename!=0 );
  33295. nFilename = (int)strlen(zFilename) + 6;
  33296. zLockFile = (char *)sqlite3_malloc64(nFilename);
  33297. if( zLockFile==0 ){
  33298. rc = SQLITE_NOMEM_BKPT;
  33299. }else{
  33300. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  33301. }
  33302. pNew->lockingContext = zLockFile;
  33303. }
  33304. #if OS_VXWORKS
  33305. else if( pLockingStyle == &semIoMethods ){
  33306. /* Named semaphore locking uses the file path so it needs to be
  33307. ** included in the semLockingContext
  33308. */
  33309. unixEnterMutex();
  33310. rc = findInodeInfo(pNew, &pNew->pInode);
  33311. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  33312. char *zSemName = pNew->pInode->aSemName;
  33313. int n;
  33314. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  33315. pNew->pId->zCanonicalName);
  33316. for( n=1; zSemName[n]; n++ )
  33317. if( zSemName[n]=='/' ) zSemName[n] = '_';
  33318. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  33319. if( pNew->pInode->pSem == SEM_FAILED ){
  33320. rc = SQLITE_NOMEM_BKPT;
  33321. pNew->pInode->aSemName[0] = '\0';
  33322. }
  33323. }
  33324. unixLeaveMutex();
  33325. }
  33326. #endif
  33327. storeLastErrno(pNew, 0);
  33328. #if OS_VXWORKS
  33329. if( rc!=SQLITE_OK ){
  33330. if( h>=0 ) robust_close(pNew, h, __LINE__);
  33331. h = -1;
  33332. osUnlink(zFilename);
  33333. pNew->ctrlFlags |= UNIXFILE_DELETE;
  33334. }
  33335. #endif
  33336. if( rc!=SQLITE_OK ){
  33337. if( h>=0 ) robust_close(pNew, h, __LINE__);
  33338. }else{
  33339. pNew->pMethod = pLockingStyle;
  33340. OpenCounter(+1);
  33341. verifyDbFile(pNew);
  33342. }
  33343. return rc;
  33344. }
  33345. /*
  33346. ** Return the name of a directory in which to put temporary files.
  33347. ** If no suitable temporary file directory can be found, return NULL.
  33348. */
  33349. static const char *unixTempFileDir(void){
  33350. static const char *azDirs[] = {
  33351. 0,
  33352. 0,
  33353. "/var/tmp",
  33354. "/usr/tmp",
  33355. "/tmp",
  33356. "."
  33357. };
  33358. unsigned int i = 0;
  33359. struct stat buf;
  33360. const char *zDir = sqlite3_temp_directory;
  33361. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  33362. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  33363. while(1){
  33364. if( zDir!=0
  33365. && osStat(zDir, &buf)==0
  33366. && S_ISDIR(buf.st_mode)
  33367. && osAccess(zDir, 03)==0
  33368. ){
  33369. return zDir;
  33370. }
  33371. if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
  33372. zDir = azDirs[i++];
  33373. }
  33374. return 0;
  33375. }
  33376. /*
  33377. ** Create a temporary file name in zBuf. zBuf must be allocated
  33378. ** by the calling process and must be big enough to hold at least
  33379. ** pVfs->mxPathname bytes.
  33380. */
  33381. static int unixGetTempname(int nBuf, char *zBuf){
  33382. const char *zDir;
  33383. int iLimit = 0;
  33384. /* It's odd to simulate an io-error here, but really this is just
  33385. ** using the io-error infrastructure to test that SQLite handles this
  33386. ** function failing.
  33387. */
  33388. zBuf[0] = 0;
  33389. SimulateIOError( return SQLITE_IOERR );
  33390. zDir = unixTempFileDir();
  33391. if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
  33392. do{
  33393. u64 r;
  33394. sqlite3_randomness(sizeof(r), &r);
  33395. assert( nBuf>2 );
  33396. zBuf[nBuf-2] = 0;
  33397. sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
  33398. zDir, r, 0);
  33399. if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
  33400. }while( osAccess(zBuf,0)==0 );
  33401. return SQLITE_OK;
  33402. }
  33403. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  33404. /*
  33405. ** Routine to transform a unixFile into a proxy-locking unixFile.
  33406. ** Implementation in the proxy-lock division, but used by unixOpen()
  33407. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  33408. */
  33409. static int proxyTransformUnixFile(unixFile*, const char*);
  33410. #endif
  33411. /*
  33412. ** Search for an unused file descriptor that was opened on the database
  33413. ** file (not a journal or master-journal file) identified by pathname
  33414. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  33415. ** argument to this function.
  33416. **
  33417. ** Such a file descriptor may exist if a database connection was closed
  33418. ** but the associated file descriptor could not be closed because some
  33419. ** other file descriptor open on the same file is holding a file-lock.
  33420. ** Refer to comments in the unixClose() function and the lengthy comment
  33421. ** describing "Posix Advisory Locking" at the start of this file for
  33422. ** further details. Also, ticket #4018.
  33423. **
  33424. ** If a suitable file descriptor is found, then it is returned. If no
  33425. ** such file descriptor is located, -1 is returned.
  33426. */
  33427. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  33428. UnixUnusedFd *pUnused = 0;
  33429. /* Do not search for an unused file descriptor on vxworks. Not because
  33430. ** vxworks would not benefit from the change (it might, we're not sure),
  33431. ** but because no way to test it is currently available. It is better
  33432. ** not to risk breaking vxworks support for the sake of such an obscure
  33433. ** feature. */
  33434. #if !OS_VXWORKS
  33435. struct stat sStat; /* Results of stat() call */
  33436. /* A stat() call may fail for various reasons. If this happens, it is
  33437. ** almost certain that an open() call on the same path will also fail.
  33438. ** For this reason, if an error occurs in the stat() call here, it is
  33439. ** ignored and -1 is returned. The caller will try to open a new file
  33440. ** descriptor on the same path, fail, and return an error to SQLite.
  33441. **
  33442. ** Even if a subsequent open() call does succeed, the consequences of
  33443. ** not searching for a reusable file descriptor are not dire. */
  33444. if( 0==osStat(zPath, &sStat) ){
  33445. unixInodeInfo *pInode;
  33446. unixEnterMutex();
  33447. pInode = inodeList;
  33448. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  33449. || pInode->fileId.ino!=(u64)sStat.st_ino) ){
  33450. pInode = pInode->pNext;
  33451. }
  33452. if( pInode ){
  33453. UnixUnusedFd **pp;
  33454. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  33455. pUnused = *pp;
  33456. if( pUnused ){
  33457. *pp = pUnused->pNext;
  33458. }
  33459. }
  33460. unixLeaveMutex();
  33461. }
  33462. #endif /* if !OS_VXWORKS */
  33463. return pUnused;
  33464. }
  33465. /*
  33466. ** Find the mode, uid and gid of file zFile.
  33467. */
  33468. static int getFileMode(
  33469. const char *zFile, /* File name */
  33470. mode_t *pMode, /* OUT: Permissions of zFile */
  33471. uid_t *pUid, /* OUT: uid of zFile. */
  33472. gid_t *pGid /* OUT: gid of zFile. */
  33473. ){
  33474. struct stat sStat; /* Output of stat() on database file */
  33475. int rc = SQLITE_OK;
  33476. if( 0==osStat(zFile, &sStat) ){
  33477. *pMode = sStat.st_mode & 0777;
  33478. *pUid = sStat.st_uid;
  33479. *pGid = sStat.st_gid;
  33480. }else{
  33481. rc = SQLITE_IOERR_FSTAT;
  33482. }
  33483. return rc;
  33484. }
  33485. /*
  33486. ** This function is called by unixOpen() to determine the unix permissions
  33487. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  33488. ** and a value suitable for passing as the third argument to open(2) is
  33489. ** written to *pMode. If an IO error occurs, an SQLite error code is
  33490. ** returned and the value of *pMode is not modified.
  33491. **
  33492. ** In most cases, this routine sets *pMode to 0, which will become
  33493. ** an indication to robust_open() to create the file using
  33494. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  33495. ** But if the file being opened is a WAL or regular journal file, then
  33496. ** this function queries the file-system for the permissions on the
  33497. ** corresponding database file and sets *pMode to this value. Whenever
  33498. ** possible, WAL and journal files are created using the same permissions
  33499. ** as the associated database file.
  33500. **
  33501. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  33502. ** original filename is unavailable. But 8_3_NAMES is only used for
  33503. ** FAT filesystems and permissions do not matter there, so just use
  33504. ** the default permissions.
  33505. */
  33506. static int findCreateFileMode(
  33507. const char *zPath, /* Path of file (possibly) being created */
  33508. int flags, /* Flags passed as 4th argument to xOpen() */
  33509. mode_t *pMode, /* OUT: Permissions to open file with */
  33510. uid_t *pUid, /* OUT: uid to set on the file */
  33511. gid_t *pGid /* OUT: gid to set on the file */
  33512. ){
  33513. int rc = SQLITE_OK; /* Return Code */
  33514. *pMode = 0;
  33515. *pUid = 0;
  33516. *pGid = 0;
  33517. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  33518. char zDb[MAX_PATHNAME+1]; /* Database file path */
  33519. int nDb; /* Number of valid bytes in zDb */
  33520. /* zPath is a path to a WAL or journal file. The following block derives
  33521. ** the path to the associated database file from zPath. This block handles
  33522. ** the following naming conventions:
  33523. **
  33524. ** "<path to db>-journal"
  33525. ** "<path to db>-wal"
  33526. ** "<path to db>-journalNN"
  33527. ** "<path to db>-walNN"
  33528. **
  33529. ** where NN is a decimal number. The NN naming schemes are
  33530. ** used by the test_multiplex.c module.
  33531. */
  33532. nDb = sqlite3Strlen30(zPath) - 1;
  33533. while( zPath[nDb]!='-' ){
  33534. #ifndef SQLITE_ENABLE_8_3_NAMES
  33535. /* In the normal case (8+3 filenames disabled) the journal filename
  33536. ** is guaranteed to contain a '-' character. */
  33537. assert( nDb>0 );
  33538. assert( sqlite3Isalnum(zPath[nDb]) );
  33539. #else
  33540. /* If 8+3 names are possible, then the journal file might not contain
  33541. ** a '-' character. So check for that case and return early. */
  33542. if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
  33543. #endif
  33544. nDb--;
  33545. }
  33546. memcpy(zDb, zPath, nDb);
  33547. zDb[nDb] = '\0';
  33548. rc = getFileMode(zDb, pMode, pUid, pGid);
  33549. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  33550. *pMode = 0600;
  33551. }else if( flags & SQLITE_OPEN_URI ){
  33552. /* If this is a main database file and the file was opened using a URI
  33553. ** filename, check for the "modeof" parameter. If present, interpret
  33554. ** its value as a filename and try to copy the mode, uid and gid from
  33555. ** that file. */
  33556. const char *z = sqlite3_uri_parameter(zPath, "modeof");
  33557. if( z ){
  33558. rc = getFileMode(z, pMode, pUid, pGid);
  33559. }
  33560. }
  33561. return rc;
  33562. }
  33563. /*
  33564. ** Open the file zPath.
  33565. **
  33566. ** Previously, the SQLite OS layer used three functions in place of this
  33567. ** one:
  33568. **
  33569. ** sqlite3OsOpenReadWrite();
  33570. ** sqlite3OsOpenReadOnly();
  33571. ** sqlite3OsOpenExclusive();
  33572. **
  33573. ** These calls correspond to the following combinations of flags:
  33574. **
  33575. ** ReadWrite() -> (READWRITE | CREATE)
  33576. ** ReadOnly() -> (READONLY)
  33577. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  33578. **
  33579. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  33580. ** true, the file was configured to be automatically deleted when the
  33581. ** file handle closed. To achieve the same effect using this new
  33582. ** interface, add the DELETEONCLOSE flag to those specified above for
  33583. ** OpenExclusive().
  33584. */
  33585. static int unixOpen(
  33586. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  33587. const char *zPath, /* Pathname of file to be opened */
  33588. sqlite3_file *pFile, /* The file descriptor to be filled in */
  33589. int flags, /* Input flags to control the opening */
  33590. int *pOutFlags /* Output flags returned to SQLite core */
  33591. ){
  33592. unixFile *p = (unixFile *)pFile;
  33593. int fd = -1; /* File descriptor returned by open() */
  33594. int openFlags = 0; /* Flags to pass to open() */
  33595. int eType = flags&0xFFFFFF00; /* Type of file to open */
  33596. int noLock; /* True to omit locking primitives */
  33597. int rc = SQLITE_OK; /* Function Return Code */
  33598. int ctrlFlags = 0; /* UNIXFILE_* flags */
  33599. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  33600. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  33601. int isCreate = (flags & SQLITE_OPEN_CREATE);
  33602. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  33603. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  33604. #if SQLITE_ENABLE_LOCKING_STYLE
  33605. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  33606. #endif
  33607. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  33608. struct statfs fsInfo;
  33609. #endif
  33610. /* If creating a master or main-file journal, this function will open
  33611. ** a file-descriptor on the directory too. The first time unixSync()
  33612. ** is called the directory file descriptor will be fsync()ed and close()d.
  33613. */
  33614. int syncDir = (isCreate && (
  33615. eType==SQLITE_OPEN_MASTER_JOURNAL
  33616. || eType==SQLITE_OPEN_MAIN_JOURNAL
  33617. || eType==SQLITE_OPEN_WAL
  33618. ));
  33619. /* If argument zPath is a NULL pointer, this function is required to open
  33620. ** a temporary file. Use this buffer to store the file name in.
  33621. */
  33622. char zTmpname[MAX_PATHNAME+2];
  33623. const char *zName = zPath;
  33624. /* Check the following statements are true:
  33625. **
  33626. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  33627. ** (b) if CREATE is set, then READWRITE must also be set, and
  33628. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  33629. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  33630. */
  33631. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  33632. assert(isCreate==0 || isReadWrite);
  33633. assert(isExclusive==0 || isCreate);
  33634. assert(isDelete==0 || isCreate);
  33635. /* The main DB, main journal, WAL file and master journal are never
  33636. ** automatically deleted. Nor are they ever temporary files. */
  33637. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  33638. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  33639. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  33640. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  33641. /* Assert that the upper layer has set one of the "file-type" flags. */
  33642. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  33643. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  33644. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  33645. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  33646. );
  33647. /* Detect a pid change and reset the PRNG. There is a race condition
  33648. ** here such that two or more threads all trying to open databases at
  33649. ** the same instant might all reset the PRNG. But multiple resets
  33650. ** are harmless.
  33651. */
  33652. if( randomnessPid!=osGetpid(0) ){
  33653. randomnessPid = osGetpid(0);
  33654. sqlite3_randomness(0,0);
  33655. }
  33656. memset(p, 0, sizeof(unixFile));
  33657. if( eType==SQLITE_OPEN_MAIN_DB ){
  33658. UnixUnusedFd *pUnused;
  33659. pUnused = findReusableFd(zName, flags);
  33660. if( pUnused ){
  33661. fd = pUnused->fd;
  33662. }else{
  33663. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  33664. if( !pUnused ){
  33665. return SQLITE_NOMEM_BKPT;
  33666. }
  33667. }
  33668. p->pUnused = pUnused;
  33669. /* Database filenames are double-zero terminated if they are not
  33670. ** URIs with parameters. Hence, they can always be passed into
  33671. ** sqlite3_uri_parameter(). */
  33672. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  33673. }else if( !zName ){
  33674. /* If zName is NULL, the upper layer is requesting a temp file. */
  33675. assert(isDelete && !syncDir);
  33676. rc = unixGetTempname(pVfs->mxPathname, zTmpname);
  33677. if( rc!=SQLITE_OK ){
  33678. return rc;
  33679. }
  33680. zName = zTmpname;
  33681. /* Generated temporary filenames are always double-zero terminated
  33682. ** for use by sqlite3_uri_parameter(). */
  33683. assert( zName[strlen(zName)+1]==0 );
  33684. }
  33685. /* Determine the value of the flags parameter passed to POSIX function
  33686. ** open(). These must be calculated even if open() is not called, as
  33687. ** they may be stored as part of the file handle and used by the
  33688. ** 'conch file' locking functions later on. */
  33689. if( isReadonly ) openFlags |= O_RDONLY;
  33690. if( isReadWrite ) openFlags |= O_RDWR;
  33691. if( isCreate ) openFlags |= O_CREAT;
  33692. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  33693. openFlags |= (O_LARGEFILE|O_BINARY);
  33694. if( fd<0 ){
  33695. mode_t openMode; /* Permissions to create file with */
  33696. uid_t uid; /* Userid for the file */
  33697. gid_t gid; /* Groupid for the file */
  33698. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  33699. if( rc!=SQLITE_OK ){
  33700. assert( !p->pUnused );
  33701. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  33702. return rc;
  33703. }
  33704. fd = robust_open(zName, openFlags, openMode);
  33705. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  33706. assert( !isExclusive || (openFlags & O_CREAT)!=0 );
  33707. if( fd<0 && errno!=EISDIR && isReadWrite ){
  33708. /* Failed to open the file for read/write access. Try read-only. */
  33709. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  33710. openFlags &= ~(O_RDWR|O_CREAT);
  33711. flags |= SQLITE_OPEN_READONLY;
  33712. openFlags |= O_RDONLY;
  33713. isReadonly = 1;
  33714. fd = robust_open(zName, openFlags, openMode);
  33715. }
  33716. if( fd<0 ){
  33717. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  33718. goto open_finished;
  33719. }
  33720. /* If this process is running as root and if creating a new rollback
  33721. ** journal or WAL file, set the ownership of the journal or WAL to be
  33722. ** the same as the original database.
  33723. */
  33724. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  33725. robustFchown(fd, uid, gid);
  33726. }
  33727. }
  33728. assert( fd>=0 );
  33729. if( pOutFlags ){
  33730. *pOutFlags = flags;
  33731. }
  33732. if( p->pUnused ){
  33733. p->pUnused->fd = fd;
  33734. p->pUnused->flags = flags;
  33735. }
  33736. if( isDelete ){
  33737. #if OS_VXWORKS
  33738. zPath = zName;
  33739. #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
  33740. zPath = sqlite3_mprintf("%s", zName);
  33741. if( zPath==0 ){
  33742. robust_close(p, fd, __LINE__);
  33743. return SQLITE_NOMEM_BKPT;
  33744. }
  33745. #else
  33746. osUnlink(zName);
  33747. #endif
  33748. }
  33749. #if SQLITE_ENABLE_LOCKING_STYLE
  33750. else{
  33751. p->openFlags = openFlags;
  33752. }
  33753. #endif
  33754. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  33755. if( fstatfs(fd, &fsInfo) == -1 ){
  33756. storeLastErrno(p, errno);
  33757. robust_close(p, fd, __LINE__);
  33758. return SQLITE_IOERR_ACCESS;
  33759. }
  33760. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  33761. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  33762. }
  33763. if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
  33764. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  33765. }
  33766. #endif
  33767. /* Set up appropriate ctrlFlags */
  33768. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  33769. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  33770. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  33771. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  33772. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  33773. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  33774. #if SQLITE_ENABLE_LOCKING_STYLE
  33775. #if SQLITE_PREFER_PROXY_LOCKING
  33776. isAutoProxy = 1;
  33777. #endif
  33778. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  33779. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  33780. int useProxy = 0;
  33781. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  33782. ** never use proxy, NULL means use proxy for non-local files only. */
  33783. if( envforce!=NULL ){
  33784. useProxy = atoi(envforce)>0;
  33785. }else{
  33786. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  33787. }
  33788. if( useProxy ){
  33789. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  33790. if( rc==SQLITE_OK ){
  33791. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  33792. if( rc!=SQLITE_OK ){
  33793. /* Use unixClose to clean up the resources added in fillInUnixFile
  33794. ** and clear all the structure's references. Specifically,
  33795. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  33796. */
  33797. unixClose(pFile);
  33798. return rc;
  33799. }
  33800. }
  33801. goto open_finished;
  33802. }
  33803. }
  33804. #endif
  33805. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  33806. open_finished:
  33807. if( rc!=SQLITE_OK ){
  33808. sqlite3_free(p->pUnused);
  33809. }
  33810. return rc;
  33811. }
  33812. /*
  33813. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  33814. ** the directory after deleting the file.
  33815. */
  33816. static int unixDelete(
  33817. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  33818. const char *zPath, /* Name of file to be deleted */
  33819. int dirSync /* If true, fsync() directory after deleting file */
  33820. ){
  33821. int rc = SQLITE_OK;
  33822. UNUSED_PARAMETER(NotUsed);
  33823. SimulateIOError(return SQLITE_IOERR_DELETE);
  33824. if( osUnlink(zPath)==(-1) ){
  33825. if( errno==ENOENT
  33826. #if OS_VXWORKS
  33827. || osAccess(zPath,0)!=0
  33828. #endif
  33829. ){
  33830. rc = SQLITE_IOERR_DELETE_NOENT;
  33831. }else{
  33832. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  33833. }
  33834. return rc;
  33835. }
  33836. #ifndef SQLITE_DISABLE_DIRSYNC
  33837. if( (dirSync & 1)!=0 ){
  33838. int fd;
  33839. rc = osOpenDirectory(zPath, &fd);
  33840. if( rc==SQLITE_OK ){
  33841. if( full_fsync(fd,0,0) ){
  33842. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  33843. }
  33844. robust_close(0, fd, __LINE__);
  33845. }else{
  33846. assert( rc==SQLITE_CANTOPEN );
  33847. rc = SQLITE_OK;
  33848. }
  33849. }
  33850. #endif
  33851. return rc;
  33852. }
  33853. /*
  33854. ** Test the existence of or access permissions of file zPath. The
  33855. ** test performed depends on the value of flags:
  33856. **
  33857. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  33858. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  33859. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  33860. **
  33861. ** Otherwise return 0.
  33862. */
  33863. static int unixAccess(
  33864. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  33865. const char *zPath, /* Path of the file to examine */
  33866. int flags, /* What do we want to learn about the zPath file? */
  33867. int *pResOut /* Write result boolean here */
  33868. ){
  33869. UNUSED_PARAMETER(NotUsed);
  33870. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  33871. assert( pResOut!=0 );
  33872. /* The spec says there are three possible values for flags. But only
  33873. ** two of them are actually used */
  33874. assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
  33875. if( flags==SQLITE_ACCESS_EXISTS ){
  33876. struct stat buf;
  33877. *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
  33878. }else{
  33879. *pResOut = osAccess(zPath, W_OK|R_OK)==0;
  33880. }
  33881. return SQLITE_OK;
  33882. }
  33883. /*
  33884. **
  33885. */
  33886. static int mkFullPathname(
  33887. const char *zPath, /* Input path */
  33888. char *zOut, /* Output buffer */
  33889. int nOut /* Allocated size of buffer zOut */
  33890. ){
  33891. int nPath = sqlite3Strlen30(zPath);
  33892. int iOff = 0;
  33893. if( zPath[0]!='/' ){
  33894. if( osGetcwd(zOut, nOut-2)==0 ){
  33895. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  33896. }
  33897. iOff = sqlite3Strlen30(zOut);
  33898. zOut[iOff++] = '/';
  33899. }
  33900. if( (iOff+nPath+1)>nOut ){
  33901. /* SQLite assumes that xFullPathname() nul-terminates the output buffer
  33902. ** even if it returns an error. */
  33903. zOut[iOff] = '\0';
  33904. return SQLITE_CANTOPEN_BKPT;
  33905. }
  33906. sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
  33907. return SQLITE_OK;
  33908. }
  33909. /*
  33910. ** Turn a relative pathname into a full pathname. The relative path
  33911. ** is stored as a nul-terminated string in the buffer pointed to by
  33912. ** zPath.
  33913. **
  33914. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  33915. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  33916. ** this buffer before returning.
  33917. */
  33918. static int unixFullPathname(
  33919. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  33920. const char *zPath, /* Possibly relative input path */
  33921. int nOut, /* Size of output buffer in bytes */
  33922. char *zOut /* Output buffer */
  33923. ){
  33924. #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
  33925. return mkFullPathname(zPath, zOut, nOut);
  33926. #else
  33927. int rc = SQLITE_OK;
  33928. int nByte;
  33929. int nLink = 1; /* Number of symbolic links followed so far */
  33930. const char *zIn = zPath; /* Input path for each iteration of loop */
  33931. char *zDel = 0;
  33932. assert( pVfs->mxPathname==MAX_PATHNAME );
  33933. UNUSED_PARAMETER(pVfs);
  33934. /* It's odd to simulate an io-error here, but really this is just
  33935. ** using the io-error infrastructure to test that SQLite handles this
  33936. ** function failing. This function could fail if, for example, the
  33937. ** current working directory has been unlinked.
  33938. */
  33939. SimulateIOError( return SQLITE_ERROR );
  33940. do {
  33941. /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
  33942. ** link, or false otherwise. */
  33943. int bLink = 0;
  33944. struct stat buf;
  33945. if( osLstat(zIn, &buf)!=0 ){
  33946. if( errno!=ENOENT ){
  33947. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
  33948. }
  33949. }else{
  33950. bLink = S_ISLNK(buf.st_mode);
  33951. }
  33952. if( bLink ){
  33953. if( zDel==0 ){
  33954. zDel = sqlite3_malloc(nOut);
  33955. if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
  33956. }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
  33957. rc = SQLITE_CANTOPEN_BKPT;
  33958. }
  33959. if( rc==SQLITE_OK ){
  33960. nByte = osReadlink(zIn, zDel, nOut-1);
  33961. if( nByte<0 ){
  33962. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
  33963. }else{
  33964. if( zDel[0]!='/' ){
  33965. int n;
  33966. for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
  33967. if( nByte+n+1>nOut ){
  33968. rc = SQLITE_CANTOPEN_BKPT;
  33969. }else{
  33970. memmove(&zDel[n], zDel, nByte+1);
  33971. memcpy(zDel, zIn, n);
  33972. nByte += n;
  33973. }
  33974. }
  33975. zDel[nByte] = '\0';
  33976. }
  33977. }
  33978. zIn = zDel;
  33979. }
  33980. assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
  33981. if( rc==SQLITE_OK && zIn!=zOut ){
  33982. rc = mkFullPathname(zIn, zOut, nOut);
  33983. }
  33984. if( bLink==0 ) break;
  33985. zIn = zOut;
  33986. }while( rc==SQLITE_OK );
  33987. sqlite3_free(zDel);
  33988. return rc;
  33989. #endif /* HAVE_READLINK && HAVE_LSTAT */
  33990. }
  33991. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  33992. /*
  33993. ** Interfaces for opening a shared library, finding entry points
  33994. ** within the shared library, and closing the shared library.
  33995. */
  33996. #include <dlfcn.h>
  33997. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  33998. UNUSED_PARAMETER(NotUsed);
  33999. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  34000. }
  34001. /*
  34002. ** SQLite calls this function immediately after a call to unixDlSym() or
  34003. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  34004. ** message is available, it is written to zBufOut. If no error message
  34005. ** is available, zBufOut is left unmodified and SQLite uses a default
  34006. ** error message.
  34007. */
  34008. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  34009. const char *zErr;
  34010. UNUSED_PARAMETER(NotUsed);
  34011. unixEnterMutex();
  34012. zErr = dlerror();
  34013. if( zErr ){
  34014. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  34015. }
  34016. unixLeaveMutex();
  34017. }
  34018. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  34019. /*
  34020. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  34021. ** cast into a pointer to a function. And yet the library dlsym() routine
  34022. ** returns a void* which is really a pointer to a function. So how do we
  34023. ** use dlsym() with -pedantic-errors?
  34024. **
  34025. ** Variable x below is defined to be a pointer to a function taking
  34026. ** parameters void* and const char* and returning a pointer to a function.
  34027. ** We initialize x by assigning it a pointer to the dlsym() function.
  34028. ** (That assignment requires a cast.) Then we call the function that
  34029. ** x points to.
  34030. **
  34031. ** This work-around is unlikely to work correctly on any system where
  34032. ** you really cannot cast a function pointer into void*. But then, on the
  34033. ** other hand, dlsym() will not work on such a system either, so we have
  34034. ** not really lost anything.
  34035. */
  34036. void (*(*x)(void*,const char*))(void);
  34037. UNUSED_PARAMETER(NotUsed);
  34038. x = (void(*(*)(void*,const char*))(void))dlsym;
  34039. return (*x)(p, zSym);
  34040. }
  34041. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  34042. UNUSED_PARAMETER(NotUsed);
  34043. dlclose(pHandle);
  34044. }
  34045. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  34046. #define unixDlOpen 0
  34047. #define unixDlError 0
  34048. #define unixDlSym 0
  34049. #define unixDlClose 0
  34050. #endif
  34051. /*
  34052. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  34053. */
  34054. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  34055. UNUSED_PARAMETER(NotUsed);
  34056. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  34057. /* We have to initialize zBuf to prevent valgrind from reporting
  34058. ** errors. The reports issued by valgrind are incorrect - we would
  34059. ** prefer that the randomness be increased by making use of the
  34060. ** uninitialized space in zBuf - but valgrind errors tend to worry
  34061. ** some users. Rather than argue, it seems easier just to initialize
  34062. ** the whole array and silence valgrind, even if that means less randomness
  34063. ** in the random seed.
  34064. **
  34065. ** When testing, initializing zBuf[] to zero is all we do. That means
  34066. ** that we always use the same random number sequence. This makes the
  34067. ** tests repeatable.
  34068. */
  34069. memset(zBuf, 0, nBuf);
  34070. randomnessPid = osGetpid(0);
  34071. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  34072. {
  34073. int fd, got;
  34074. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  34075. if( fd<0 ){
  34076. time_t t;
  34077. time(&t);
  34078. memcpy(zBuf, &t, sizeof(t));
  34079. memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
  34080. assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
  34081. nBuf = sizeof(t) + sizeof(randomnessPid);
  34082. }else{
  34083. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  34084. robust_close(0, fd, __LINE__);
  34085. }
  34086. }
  34087. #endif
  34088. return nBuf;
  34089. }
  34090. /*
  34091. ** Sleep for a little while. Return the amount of time slept.
  34092. ** The argument is the number of microseconds we want to sleep.
  34093. ** The return value is the number of microseconds of sleep actually
  34094. ** requested from the underlying operating system, a number which
  34095. ** might be greater than or equal to the argument, but not less
  34096. ** than the argument.
  34097. */
  34098. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  34099. #if OS_VXWORKS
  34100. struct timespec sp;
  34101. sp.tv_sec = microseconds / 1000000;
  34102. sp.tv_nsec = (microseconds % 1000000) * 1000;
  34103. nanosleep(&sp, NULL);
  34104. UNUSED_PARAMETER(NotUsed);
  34105. return microseconds;
  34106. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  34107. usleep(microseconds);
  34108. UNUSED_PARAMETER(NotUsed);
  34109. return microseconds;
  34110. #else
  34111. int seconds = (microseconds+999999)/1000000;
  34112. sleep(seconds);
  34113. UNUSED_PARAMETER(NotUsed);
  34114. return seconds*1000000;
  34115. #endif
  34116. }
  34117. /*
  34118. ** The following variable, if set to a non-zero value, is interpreted as
  34119. ** the number of seconds since 1970 and is used to set the result of
  34120. ** sqlite3OsCurrentTime() during testing.
  34121. */
  34122. #ifdef SQLITE_TEST
  34123. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  34124. #endif
  34125. /*
  34126. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  34127. ** the current time and date as a Julian Day number times 86_400_000. In
  34128. ** other words, write into *piNow the number of milliseconds since the Julian
  34129. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  34130. ** proleptic Gregorian calendar.
  34131. **
  34132. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  34133. ** cannot be found.
  34134. */
  34135. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  34136. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  34137. int rc = SQLITE_OK;
  34138. #if defined(NO_GETTOD)
  34139. time_t t;
  34140. time(&t);
  34141. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  34142. #elif OS_VXWORKS
  34143. struct timespec sNow;
  34144. clock_gettime(CLOCK_REALTIME, &sNow);
  34145. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  34146. #else
  34147. struct timeval sNow;
  34148. (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
  34149. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  34150. #endif
  34151. #ifdef SQLITE_TEST
  34152. if( sqlite3_current_time ){
  34153. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  34154. }
  34155. #endif
  34156. UNUSED_PARAMETER(NotUsed);
  34157. return rc;
  34158. }
  34159. #ifndef SQLITE_OMIT_DEPRECATED
  34160. /*
  34161. ** Find the current time (in Universal Coordinated Time). Write the
  34162. ** current time and date as a Julian Day number into *prNow and
  34163. ** return 0. Return 1 if the time and date cannot be found.
  34164. */
  34165. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  34166. sqlite3_int64 i = 0;
  34167. int rc;
  34168. UNUSED_PARAMETER(NotUsed);
  34169. rc = unixCurrentTimeInt64(0, &i);
  34170. *prNow = i/86400000.0;
  34171. return rc;
  34172. }
  34173. #else
  34174. # define unixCurrentTime 0
  34175. #endif
  34176. /*
  34177. ** The xGetLastError() method is designed to return a better
  34178. ** low-level error message when operating-system problems come up
  34179. ** during SQLite operation. Only the integer return code is currently
  34180. ** used.
  34181. */
  34182. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  34183. UNUSED_PARAMETER(NotUsed);
  34184. UNUSED_PARAMETER(NotUsed2);
  34185. UNUSED_PARAMETER(NotUsed3);
  34186. return errno;
  34187. }
  34188. /*
  34189. ************************ End of sqlite3_vfs methods ***************************
  34190. ******************************************************************************/
  34191. /******************************************************************************
  34192. ************************** Begin Proxy Locking ********************************
  34193. **
  34194. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  34195. ** other locking methods on secondary lock files. Proxy locking is a
  34196. ** meta-layer over top of the primitive locking implemented above. For
  34197. ** this reason, the division that implements of proxy locking is deferred
  34198. ** until late in the file (here) after all of the other I/O methods have
  34199. ** been defined - so that the primitive locking methods are available
  34200. ** as services to help with the implementation of proxy locking.
  34201. **
  34202. ****
  34203. **
  34204. ** The default locking schemes in SQLite use byte-range locks on the
  34205. ** database file to coordinate safe, concurrent access by multiple readers
  34206. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  34207. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  34208. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  34209. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  34210. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  34211. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  34212. ** address in the shared range is taken for a SHARED lock, the entire
  34213. ** shared range is taken for an EXCLUSIVE lock):
  34214. **
  34215. ** PENDING_BYTE 0x40000000
  34216. ** RESERVED_BYTE 0x40000001
  34217. ** SHARED_RANGE 0x40000002 -> 0x40000200
  34218. **
  34219. ** This works well on the local file system, but shows a nearly 100x
  34220. ** slowdown in read performance on AFP because the AFP client disables
  34221. ** the read cache when byte-range locks are present. Enabling the read
  34222. ** cache exposes a cache coherency problem that is present on all OS X
  34223. ** supported network file systems. NFS and AFP both observe the
  34224. ** close-to-open semantics for ensuring cache coherency
  34225. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  34226. ** address the requirements for concurrent database access by multiple
  34227. ** readers and writers
  34228. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  34229. **
  34230. ** To address the performance and cache coherency issues, proxy file locking
  34231. ** changes the way database access is controlled by limiting access to a
  34232. ** single host at a time and moving file locks off of the database file
  34233. ** and onto a proxy file on the local file system.
  34234. **
  34235. **
  34236. ** Using proxy locks
  34237. ** -----------------
  34238. **
  34239. ** C APIs
  34240. **
  34241. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
  34242. ** <proxy_path> | ":auto:");
  34243. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
  34244. ** &<proxy_path>);
  34245. **
  34246. **
  34247. ** SQL pragmas
  34248. **
  34249. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  34250. ** PRAGMA [database.]lock_proxy_file
  34251. **
  34252. ** Specifying ":auto:" means that if there is a conch file with a matching
  34253. ** host ID in it, the proxy path in the conch file will be used, otherwise
  34254. ** a proxy path based on the user's temp dir
  34255. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  34256. ** actual proxy file name is generated from the name and path of the
  34257. ** database file. For example:
  34258. **
  34259. ** For database path "/Users/me/foo.db"
  34260. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  34261. **
  34262. ** Once a lock proxy is configured for a database connection, it can not
  34263. ** be removed, however it may be switched to a different proxy path via
  34264. ** the above APIs (assuming the conch file is not being held by another
  34265. ** connection or process).
  34266. **
  34267. **
  34268. ** How proxy locking works
  34269. ** -----------------------
  34270. **
  34271. ** Proxy file locking relies primarily on two new supporting files:
  34272. **
  34273. ** * conch file to limit access to the database file to a single host
  34274. ** at a time
  34275. **
  34276. ** * proxy file to act as a proxy for the advisory locks normally
  34277. ** taken on the database
  34278. **
  34279. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  34280. ** by taking an sqlite-style shared lock on the conch file, reading the
  34281. ** contents and comparing the host's unique host ID (see below) and lock
  34282. ** proxy path against the values stored in the conch. The conch file is
  34283. ** stored in the same directory as the database file and the file name
  34284. ** is patterned after the database file name as ".<databasename>-conch".
  34285. ** If the conch file does not exist, or its contents do not match the
  34286. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  34287. ** lock and the conch file contents is updated with the host ID and proxy
  34288. ** path and the lock is downgraded to a shared lock again. If the conch
  34289. ** is held by another process (with a shared lock), the exclusive lock
  34290. ** will fail and SQLITE_BUSY is returned.
  34291. **
  34292. ** The proxy file - a single-byte file used for all advisory file locks
  34293. ** normally taken on the database file. This allows for safe sharing
  34294. ** of the database file for multiple readers and writers on the same
  34295. ** host (the conch ensures that they all use the same local lock file).
  34296. **
  34297. ** Requesting the lock proxy does not immediately take the conch, it is
  34298. ** only taken when the first request to lock database file is made.
  34299. ** This matches the semantics of the traditional locking behavior, where
  34300. ** opening a connection to a database file does not take a lock on it.
  34301. ** The shared lock and an open file descriptor are maintained until
  34302. ** the connection to the database is closed.
  34303. **
  34304. ** The proxy file and the lock file are never deleted so they only need
  34305. ** to be created the first time they are used.
  34306. **
  34307. ** Configuration options
  34308. ** ---------------------
  34309. **
  34310. ** SQLITE_PREFER_PROXY_LOCKING
  34311. **
  34312. ** Database files accessed on non-local file systems are
  34313. ** automatically configured for proxy locking, lock files are
  34314. ** named automatically using the same logic as
  34315. ** PRAGMA lock_proxy_file=":auto:"
  34316. **
  34317. ** SQLITE_PROXY_DEBUG
  34318. **
  34319. ** Enables the logging of error messages during host id file
  34320. ** retrieval and creation
  34321. **
  34322. ** LOCKPROXYDIR
  34323. **
  34324. ** Overrides the default directory used for lock proxy files that
  34325. ** are named automatically via the ":auto:" setting
  34326. **
  34327. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  34328. **
  34329. ** Permissions to use when creating a directory for storing the
  34330. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  34331. **
  34332. **
  34333. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  34334. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  34335. ** force proxy locking to be used for every database file opened, and 0
  34336. ** will force automatic proxy locking to be disabled for all database
  34337. ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
  34338. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  34339. */
  34340. /*
  34341. ** Proxy locking is only available on MacOSX
  34342. */
  34343. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  34344. /*
  34345. ** The proxyLockingContext has the path and file structures for the remote
  34346. ** and local proxy files in it
  34347. */
  34348. typedef struct proxyLockingContext proxyLockingContext;
  34349. struct proxyLockingContext {
  34350. unixFile *conchFile; /* Open conch file */
  34351. char *conchFilePath; /* Name of the conch file */
  34352. unixFile *lockProxy; /* Open proxy lock file */
  34353. char *lockProxyPath; /* Name of the proxy lock file */
  34354. char *dbPath; /* Name of the open file */
  34355. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  34356. int nFails; /* Number of conch taking failures */
  34357. void *oldLockingContext; /* Original lockingcontext to restore on close */
  34358. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  34359. };
  34360. /*
  34361. ** The proxy lock file path for the database at dbPath is written into lPath,
  34362. ** which must point to valid, writable memory large enough for a maxLen length
  34363. ** file path.
  34364. */
  34365. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  34366. int len;
  34367. int dbLen;
  34368. int i;
  34369. #ifdef LOCKPROXYDIR
  34370. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  34371. #else
  34372. # ifdef _CS_DARWIN_USER_TEMP_DIR
  34373. {
  34374. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  34375. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  34376. lPath, errno, osGetpid(0)));
  34377. return SQLITE_IOERR_LOCK;
  34378. }
  34379. len = strlcat(lPath, "sqliteplocks", maxLen);
  34380. }
  34381. # else
  34382. len = strlcpy(lPath, "/tmp/", maxLen);
  34383. # endif
  34384. #endif
  34385. if( lPath[len-1]!='/' ){
  34386. len = strlcat(lPath, "/", maxLen);
  34387. }
  34388. /* transform the db path to a unique cache name */
  34389. dbLen = (int)strlen(dbPath);
  34390. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  34391. char c = dbPath[i];
  34392. lPath[i+len] = (c=='/')?'_':c;
  34393. }
  34394. lPath[i+len]='\0';
  34395. strlcat(lPath, ":auto:", maxLen);
  34396. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
  34397. return SQLITE_OK;
  34398. }
  34399. /*
  34400. ** Creates the lock file and any missing directories in lockPath
  34401. */
  34402. static int proxyCreateLockPath(const char *lockPath){
  34403. int i, len;
  34404. char buf[MAXPATHLEN];
  34405. int start = 0;
  34406. assert(lockPath!=NULL);
  34407. /* try to create all the intermediate directories */
  34408. len = (int)strlen(lockPath);
  34409. buf[0] = lockPath[0];
  34410. for( i=1; i<len; i++ ){
  34411. if( lockPath[i] == '/' && (i - start > 0) ){
  34412. /* only mkdir if leaf dir != "." or "/" or ".." */
  34413. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  34414. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  34415. buf[i]='\0';
  34416. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  34417. int err=errno;
  34418. if( err!=EEXIST ) {
  34419. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  34420. "'%s' proxy lock path=%s pid=%d\n",
  34421. buf, strerror(err), lockPath, osGetpid(0)));
  34422. return err;
  34423. }
  34424. }
  34425. }
  34426. start=i+1;
  34427. }
  34428. buf[i] = lockPath[i];
  34429. }
  34430. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
  34431. return 0;
  34432. }
  34433. /*
  34434. ** Create a new VFS file descriptor (stored in memory obtained from
  34435. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  34436. **
  34437. ** The caller is responsible not only for closing the file descriptor
  34438. ** but also for freeing the memory associated with the file descriptor.
  34439. */
  34440. static int proxyCreateUnixFile(
  34441. const char *path, /* path for the new unixFile */
  34442. unixFile **ppFile, /* unixFile created and returned by ref */
  34443. int islockfile /* if non zero missing dirs will be created */
  34444. ) {
  34445. int fd = -1;
  34446. unixFile *pNew;
  34447. int rc = SQLITE_OK;
  34448. int openFlags = O_RDWR | O_CREAT;
  34449. sqlite3_vfs dummyVfs;
  34450. int terrno = 0;
  34451. UnixUnusedFd *pUnused = NULL;
  34452. /* 1. first try to open/create the file
  34453. ** 2. if that fails, and this is a lock file (not-conch), try creating
  34454. ** the parent directories and then try again.
  34455. ** 3. if that fails, try to open the file read-only
  34456. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  34457. */
  34458. pUnused = findReusableFd(path, openFlags);
  34459. if( pUnused ){
  34460. fd = pUnused->fd;
  34461. }else{
  34462. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  34463. if( !pUnused ){
  34464. return SQLITE_NOMEM_BKPT;
  34465. }
  34466. }
  34467. if( fd<0 ){
  34468. fd = robust_open(path, openFlags, 0);
  34469. terrno = errno;
  34470. if( fd<0 && errno==ENOENT && islockfile ){
  34471. if( proxyCreateLockPath(path) == SQLITE_OK ){
  34472. fd = robust_open(path, openFlags, 0);
  34473. }
  34474. }
  34475. }
  34476. if( fd<0 ){
  34477. openFlags = O_RDONLY;
  34478. fd = robust_open(path, openFlags, 0);
  34479. terrno = errno;
  34480. }
  34481. if( fd<0 ){
  34482. if( islockfile ){
  34483. return SQLITE_BUSY;
  34484. }
  34485. switch (terrno) {
  34486. case EACCES:
  34487. return SQLITE_PERM;
  34488. case EIO:
  34489. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  34490. default:
  34491. return SQLITE_CANTOPEN_BKPT;
  34492. }
  34493. }
  34494. pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
  34495. if( pNew==NULL ){
  34496. rc = SQLITE_NOMEM_BKPT;
  34497. goto end_create_proxy;
  34498. }
  34499. memset(pNew, 0, sizeof(unixFile));
  34500. pNew->openFlags = openFlags;
  34501. memset(&dummyVfs, 0, sizeof(dummyVfs));
  34502. dummyVfs.pAppData = (void*)&autolockIoFinder;
  34503. dummyVfs.zName = "dummy";
  34504. pUnused->fd = fd;
  34505. pUnused->flags = openFlags;
  34506. pNew->pUnused = pUnused;
  34507. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  34508. if( rc==SQLITE_OK ){
  34509. *ppFile = pNew;
  34510. return SQLITE_OK;
  34511. }
  34512. end_create_proxy:
  34513. robust_close(pNew, fd, __LINE__);
  34514. sqlite3_free(pNew);
  34515. sqlite3_free(pUnused);
  34516. return rc;
  34517. }
  34518. #ifdef SQLITE_TEST
  34519. /* simulate multiple hosts by creating unique hostid file paths */
  34520. SQLITE_API int sqlite3_hostid_num = 0;
  34521. #endif
  34522. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  34523. #ifdef HAVE_GETHOSTUUID
  34524. /* Not always defined in the headers as it ought to be */
  34525. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  34526. #endif
  34527. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  34528. ** bytes of writable memory.
  34529. */
  34530. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  34531. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  34532. memset(pHostID, 0, PROXY_HOSTIDLEN);
  34533. #ifdef HAVE_GETHOSTUUID
  34534. {
  34535. struct timespec timeout = {1, 0}; /* 1 sec timeout */
  34536. if( gethostuuid(pHostID, &timeout) ){
  34537. int err = errno;
  34538. if( pError ){
  34539. *pError = err;
  34540. }
  34541. return SQLITE_IOERR;
  34542. }
  34543. }
  34544. #else
  34545. UNUSED_PARAMETER(pError);
  34546. #endif
  34547. #ifdef SQLITE_TEST
  34548. /* simulate multiple hosts by creating unique hostid file paths */
  34549. if( sqlite3_hostid_num != 0){
  34550. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  34551. }
  34552. #endif
  34553. return SQLITE_OK;
  34554. }
  34555. /* The conch file contains the header, host id and lock file path
  34556. */
  34557. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  34558. #define PROXY_HEADERLEN 1 /* conch file header length */
  34559. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  34560. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  34561. /*
  34562. ** Takes an open conch file, copies the contents to a new path and then moves
  34563. ** it back. The newly created file's file descriptor is assigned to the
  34564. ** conch file structure and finally the original conch file descriptor is
  34565. ** closed. Returns zero if successful.
  34566. */
  34567. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  34568. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  34569. unixFile *conchFile = pCtx->conchFile;
  34570. char tPath[MAXPATHLEN];
  34571. char buf[PROXY_MAXCONCHLEN];
  34572. char *cPath = pCtx->conchFilePath;
  34573. size_t readLen = 0;
  34574. size_t pathLen = 0;
  34575. char errmsg[64] = "";
  34576. int fd = -1;
  34577. int rc = -1;
  34578. UNUSED_PARAMETER(myHostID);
  34579. /* create a new path by replace the trailing '-conch' with '-break' */
  34580. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  34581. if( pathLen>MAXPATHLEN || pathLen<6 ||
  34582. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  34583. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  34584. goto end_breaklock;
  34585. }
  34586. /* read the conch content */
  34587. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  34588. if( readLen<PROXY_PATHINDEX ){
  34589. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  34590. goto end_breaklock;
  34591. }
  34592. /* write it out to the temporary break file */
  34593. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  34594. if( fd<0 ){
  34595. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  34596. goto end_breaklock;
  34597. }
  34598. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  34599. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  34600. goto end_breaklock;
  34601. }
  34602. if( rename(tPath, cPath) ){
  34603. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  34604. goto end_breaklock;
  34605. }
  34606. rc = 0;
  34607. fprintf(stderr, "broke stale lock on %s\n", cPath);
  34608. robust_close(pFile, conchFile->h, __LINE__);
  34609. conchFile->h = fd;
  34610. conchFile->openFlags = O_RDWR | O_CREAT;
  34611. end_breaklock:
  34612. if( rc ){
  34613. if( fd>=0 ){
  34614. osUnlink(tPath);
  34615. robust_close(pFile, fd, __LINE__);
  34616. }
  34617. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  34618. }
  34619. return rc;
  34620. }
  34621. /* Take the requested lock on the conch file and break a stale lock if the
  34622. ** host id matches.
  34623. */
  34624. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  34625. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  34626. unixFile *conchFile = pCtx->conchFile;
  34627. int rc = SQLITE_OK;
  34628. int nTries = 0;
  34629. struct timespec conchModTime;
  34630. memset(&conchModTime, 0, sizeof(conchModTime));
  34631. do {
  34632. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  34633. nTries ++;
  34634. if( rc==SQLITE_BUSY ){
  34635. /* If the lock failed (busy):
  34636. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  34637. * 2nd try: fail if the mod time changed or host id is different, wait
  34638. * 10 sec and try again
  34639. * 3rd try: break the lock unless the mod time has changed.
  34640. */
  34641. struct stat buf;
  34642. if( osFstat(conchFile->h, &buf) ){
  34643. storeLastErrno(pFile, errno);
  34644. return SQLITE_IOERR_LOCK;
  34645. }
  34646. if( nTries==1 ){
  34647. conchModTime = buf.st_mtimespec;
  34648. usleep(500000); /* wait 0.5 sec and try the lock again*/
  34649. continue;
  34650. }
  34651. assert( nTries>1 );
  34652. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  34653. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  34654. return SQLITE_BUSY;
  34655. }
  34656. if( nTries==2 ){
  34657. char tBuf[PROXY_MAXCONCHLEN];
  34658. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  34659. if( len<0 ){
  34660. storeLastErrno(pFile, errno);
  34661. return SQLITE_IOERR_LOCK;
  34662. }
  34663. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  34664. /* don't break the lock if the host id doesn't match */
  34665. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  34666. return SQLITE_BUSY;
  34667. }
  34668. }else{
  34669. /* don't break the lock on short read or a version mismatch */
  34670. return SQLITE_BUSY;
  34671. }
  34672. usleep(10000000); /* wait 10 sec and try the lock again */
  34673. continue;
  34674. }
  34675. assert( nTries==3 );
  34676. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  34677. rc = SQLITE_OK;
  34678. if( lockType==EXCLUSIVE_LOCK ){
  34679. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  34680. }
  34681. if( !rc ){
  34682. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  34683. }
  34684. }
  34685. }
  34686. } while( rc==SQLITE_BUSY && nTries<3 );
  34687. return rc;
  34688. }
  34689. /* Takes the conch by taking a shared lock and read the contents conch, if
  34690. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  34691. ** lockPath means that the lockPath in the conch file will be used if the
  34692. ** host IDs match, or a new lock path will be generated automatically
  34693. ** and written to the conch file.
  34694. */
  34695. static int proxyTakeConch(unixFile *pFile){
  34696. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  34697. if( pCtx->conchHeld!=0 ){
  34698. return SQLITE_OK;
  34699. }else{
  34700. unixFile *conchFile = pCtx->conchFile;
  34701. uuid_t myHostID;
  34702. int pError = 0;
  34703. char readBuf[PROXY_MAXCONCHLEN];
  34704. char lockPath[MAXPATHLEN];
  34705. char *tempLockPath = NULL;
  34706. int rc = SQLITE_OK;
  34707. int createConch = 0;
  34708. int hostIdMatch = 0;
  34709. int readLen = 0;
  34710. int tryOldLockPath = 0;
  34711. int forceNewLockPath = 0;
  34712. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  34713. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  34714. osGetpid(0)));
  34715. rc = proxyGetHostID(myHostID, &pError);
  34716. if( (rc&0xff)==SQLITE_IOERR ){
  34717. storeLastErrno(pFile, pError);
  34718. goto end_takeconch;
  34719. }
  34720. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  34721. if( rc!=SQLITE_OK ){
  34722. goto end_takeconch;
  34723. }
  34724. /* read the existing conch file */
  34725. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  34726. if( readLen<0 ){
  34727. /* I/O error: lastErrno set by seekAndRead */
  34728. storeLastErrno(pFile, conchFile->lastErrno);
  34729. rc = SQLITE_IOERR_READ;
  34730. goto end_takeconch;
  34731. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  34732. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  34733. /* a short read or version format mismatch means we need to create a new
  34734. ** conch file.
  34735. */
  34736. createConch = 1;
  34737. }
  34738. /* if the host id matches and the lock path already exists in the conch
  34739. ** we'll try to use the path there, if we can't open that path, we'll
  34740. ** retry with a new auto-generated path
  34741. */
  34742. do { /* in case we need to try again for an :auto: named lock file */
  34743. if( !createConch && !forceNewLockPath ){
  34744. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  34745. PROXY_HOSTIDLEN);
  34746. /* if the conch has data compare the contents */
  34747. if( !pCtx->lockProxyPath ){
  34748. /* for auto-named local lock file, just check the host ID and we'll
  34749. ** use the local lock file path that's already in there
  34750. */
  34751. if( hostIdMatch ){
  34752. size_t pathLen = (readLen - PROXY_PATHINDEX);
  34753. if( pathLen>=MAXPATHLEN ){
  34754. pathLen=MAXPATHLEN-1;
  34755. }
  34756. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  34757. lockPath[pathLen] = 0;
  34758. tempLockPath = lockPath;
  34759. tryOldLockPath = 1;
  34760. /* create a copy of the lock path if the conch is taken */
  34761. goto end_takeconch;
  34762. }
  34763. }else if( hostIdMatch
  34764. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  34765. readLen-PROXY_PATHINDEX)
  34766. ){
  34767. /* conch host and lock path match */
  34768. goto end_takeconch;
  34769. }
  34770. }
  34771. /* if the conch isn't writable and doesn't match, we can't take it */
  34772. if( (conchFile->openFlags&O_RDWR) == 0 ){
  34773. rc = SQLITE_BUSY;
  34774. goto end_takeconch;
  34775. }
  34776. /* either the conch didn't match or we need to create a new one */
  34777. if( !pCtx->lockProxyPath ){
  34778. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  34779. tempLockPath = lockPath;
  34780. /* create a copy of the lock path _only_ if the conch is taken */
  34781. }
  34782. /* update conch with host and path (this will fail if other process
  34783. ** has a shared lock already), if the host id matches, use the big
  34784. ** stick.
  34785. */
  34786. futimes(conchFile->h, NULL);
  34787. if( hostIdMatch && !createConch ){
  34788. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  34789. /* We are trying for an exclusive lock but another thread in this
  34790. ** same process is still holding a shared lock. */
  34791. rc = SQLITE_BUSY;
  34792. } else {
  34793. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  34794. }
  34795. }else{
  34796. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  34797. }
  34798. if( rc==SQLITE_OK ){
  34799. char writeBuffer[PROXY_MAXCONCHLEN];
  34800. int writeSize = 0;
  34801. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  34802. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  34803. if( pCtx->lockProxyPath!=NULL ){
  34804. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
  34805. MAXPATHLEN);
  34806. }else{
  34807. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  34808. }
  34809. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  34810. robust_ftruncate(conchFile->h, writeSize);
  34811. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  34812. full_fsync(conchFile->h,0,0);
  34813. /* If we created a new conch file (not just updated the contents of a
  34814. ** valid conch file), try to match the permissions of the database
  34815. */
  34816. if( rc==SQLITE_OK && createConch ){
  34817. struct stat buf;
  34818. int err = osFstat(pFile->h, &buf);
  34819. if( err==0 ){
  34820. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  34821. S_IROTH|S_IWOTH);
  34822. /* try to match the database file R/W permissions, ignore failure */
  34823. #ifndef SQLITE_PROXY_DEBUG
  34824. osFchmod(conchFile->h, cmode);
  34825. #else
  34826. do{
  34827. rc = osFchmod(conchFile->h, cmode);
  34828. }while( rc==(-1) && errno==EINTR );
  34829. if( rc!=0 ){
  34830. int code = errno;
  34831. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  34832. cmode, code, strerror(code));
  34833. } else {
  34834. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  34835. }
  34836. }else{
  34837. int code = errno;
  34838. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  34839. err, code, strerror(code));
  34840. #endif
  34841. }
  34842. }
  34843. }
  34844. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  34845. end_takeconch:
  34846. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  34847. if( rc==SQLITE_OK && pFile->openFlags ){
  34848. int fd;
  34849. if( pFile->h>=0 ){
  34850. robust_close(pFile, pFile->h, __LINE__);
  34851. }
  34852. pFile->h = -1;
  34853. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  34854. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  34855. if( fd>=0 ){
  34856. pFile->h = fd;
  34857. }else{
  34858. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  34859. during locking */
  34860. }
  34861. }
  34862. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  34863. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  34864. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  34865. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  34866. /* we couldn't create the proxy lock file with the old lock file path
  34867. ** so try again via auto-naming
  34868. */
  34869. forceNewLockPath = 1;
  34870. tryOldLockPath = 0;
  34871. continue; /* go back to the do {} while start point, try again */
  34872. }
  34873. }
  34874. if( rc==SQLITE_OK ){
  34875. /* Need to make a copy of path if we extracted the value
  34876. ** from the conch file or the path was allocated on the stack
  34877. */
  34878. if( tempLockPath ){
  34879. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  34880. if( !pCtx->lockProxyPath ){
  34881. rc = SQLITE_NOMEM_BKPT;
  34882. }
  34883. }
  34884. }
  34885. if( rc==SQLITE_OK ){
  34886. pCtx->conchHeld = 1;
  34887. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  34888. afpLockingContext *afpCtx;
  34889. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  34890. afpCtx->dbPath = pCtx->lockProxyPath;
  34891. }
  34892. } else {
  34893. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  34894. }
  34895. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  34896. rc==SQLITE_OK?"ok":"failed"));
  34897. return rc;
  34898. } while (1); /* in case we need to retry the :auto: lock file -
  34899. ** we should never get here except via the 'continue' call. */
  34900. }
  34901. }
  34902. /*
  34903. ** If pFile holds a lock on a conch file, then release that lock.
  34904. */
  34905. static int proxyReleaseConch(unixFile *pFile){
  34906. int rc = SQLITE_OK; /* Subroutine return code */
  34907. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  34908. unixFile *conchFile; /* Name of the conch file */
  34909. pCtx = (proxyLockingContext *)pFile->lockingContext;
  34910. conchFile = pCtx->conchFile;
  34911. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  34912. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  34913. osGetpid(0)));
  34914. if( pCtx->conchHeld>0 ){
  34915. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  34916. }
  34917. pCtx->conchHeld = 0;
  34918. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  34919. (rc==SQLITE_OK ? "ok" : "failed")));
  34920. return rc;
  34921. }
  34922. /*
  34923. ** Given the name of a database file, compute the name of its conch file.
  34924. ** Store the conch filename in memory obtained from sqlite3_malloc64().
  34925. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  34926. ** or SQLITE_NOMEM if unable to obtain memory.
  34927. **
  34928. ** The caller is responsible for ensuring that the allocated memory
  34929. ** space is eventually freed.
  34930. **
  34931. ** *pConchPath is set to NULL if a memory allocation error occurs.
  34932. */
  34933. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  34934. int i; /* Loop counter */
  34935. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  34936. char *conchPath; /* buffer in which to construct conch name */
  34937. /* Allocate space for the conch filename and initialize the name to
  34938. ** the name of the original database file. */
  34939. *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
  34940. if( conchPath==0 ){
  34941. return SQLITE_NOMEM_BKPT;
  34942. }
  34943. memcpy(conchPath, dbPath, len+1);
  34944. /* now insert a "." before the last / character */
  34945. for( i=(len-1); i>=0; i-- ){
  34946. if( conchPath[i]=='/' ){
  34947. i++;
  34948. break;
  34949. }
  34950. }
  34951. conchPath[i]='.';
  34952. while ( i<len ){
  34953. conchPath[i+1]=dbPath[i];
  34954. i++;
  34955. }
  34956. /* append the "-conch" suffix to the file */
  34957. memcpy(&conchPath[i+1], "-conch", 7);
  34958. assert( (int)strlen(conchPath) == len+7 );
  34959. return SQLITE_OK;
  34960. }
  34961. /* Takes a fully configured proxy locking-style unix file and switches
  34962. ** the local lock file path
  34963. */
  34964. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  34965. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  34966. char *oldPath = pCtx->lockProxyPath;
  34967. int rc = SQLITE_OK;
  34968. if( pFile->eFileLock!=NO_LOCK ){
  34969. return SQLITE_BUSY;
  34970. }
  34971. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  34972. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  34973. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  34974. return SQLITE_OK;
  34975. }else{
  34976. unixFile *lockProxy = pCtx->lockProxy;
  34977. pCtx->lockProxy=NULL;
  34978. pCtx->conchHeld = 0;
  34979. if( lockProxy!=NULL ){
  34980. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  34981. if( rc ) return rc;
  34982. sqlite3_free(lockProxy);
  34983. }
  34984. sqlite3_free(oldPath);
  34985. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  34986. }
  34987. return rc;
  34988. }
  34989. /*
  34990. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  34991. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  34992. **
  34993. ** This routine find the filename associated with pFile and writes it
  34994. ** int dbPath.
  34995. */
  34996. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  34997. #if defined(__APPLE__)
  34998. if( pFile->pMethod == &afpIoMethods ){
  34999. /* afp style keeps a reference to the db path in the filePath field
  35000. ** of the struct */
  35001. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  35002. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
  35003. MAXPATHLEN);
  35004. } else
  35005. #endif
  35006. if( pFile->pMethod == &dotlockIoMethods ){
  35007. /* dot lock style uses the locking context to store the dot lock
  35008. ** file path */
  35009. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  35010. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  35011. }else{
  35012. /* all other styles use the locking context to store the db file path */
  35013. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  35014. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  35015. }
  35016. return SQLITE_OK;
  35017. }
  35018. /*
  35019. ** Takes an already filled in unix file and alters it so all file locking
  35020. ** will be performed on the local proxy lock file. The following fields
  35021. ** are preserved in the locking context so that they can be restored and
  35022. ** the unix structure properly cleaned up at close time:
  35023. ** ->lockingContext
  35024. ** ->pMethod
  35025. */
  35026. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  35027. proxyLockingContext *pCtx;
  35028. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  35029. char *lockPath=NULL;
  35030. int rc = SQLITE_OK;
  35031. if( pFile->eFileLock!=NO_LOCK ){
  35032. return SQLITE_BUSY;
  35033. }
  35034. proxyGetDbPathForUnixFile(pFile, dbPath);
  35035. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  35036. lockPath=NULL;
  35037. }else{
  35038. lockPath=(char *)path;
  35039. }
  35040. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  35041. (lockPath ? lockPath : ":auto:"), osGetpid(0)));
  35042. pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  35043. if( pCtx==0 ){
  35044. return SQLITE_NOMEM_BKPT;
  35045. }
  35046. memset(pCtx, 0, sizeof(*pCtx));
  35047. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  35048. if( rc==SQLITE_OK ){
  35049. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  35050. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  35051. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  35052. ** (c) the file system is read-only, then enable no-locking access.
  35053. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  35054. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  35055. */
  35056. struct statfs fsInfo;
  35057. struct stat conchInfo;
  35058. int goLockless = 0;
  35059. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  35060. int err = errno;
  35061. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  35062. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  35063. }
  35064. }
  35065. if( goLockless ){
  35066. pCtx->conchHeld = -1; /* read only FS/ lockless */
  35067. rc = SQLITE_OK;
  35068. }
  35069. }
  35070. }
  35071. if( rc==SQLITE_OK && lockPath ){
  35072. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  35073. }
  35074. if( rc==SQLITE_OK ){
  35075. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  35076. if( pCtx->dbPath==NULL ){
  35077. rc = SQLITE_NOMEM_BKPT;
  35078. }
  35079. }
  35080. if( rc==SQLITE_OK ){
  35081. /* all memory is allocated, proxys are created and assigned,
  35082. ** switch the locking context and pMethod then return.
  35083. */
  35084. pCtx->oldLockingContext = pFile->lockingContext;
  35085. pFile->lockingContext = pCtx;
  35086. pCtx->pOldMethod = pFile->pMethod;
  35087. pFile->pMethod = &proxyIoMethods;
  35088. }else{
  35089. if( pCtx->conchFile ){
  35090. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  35091. sqlite3_free(pCtx->conchFile);
  35092. }
  35093. sqlite3DbFree(0, pCtx->lockProxyPath);
  35094. sqlite3_free(pCtx->conchFilePath);
  35095. sqlite3_free(pCtx);
  35096. }
  35097. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  35098. (rc==SQLITE_OK ? "ok" : "failed")));
  35099. return rc;
  35100. }
  35101. /*
  35102. ** This routine handles sqlite3_file_control() calls that are specific
  35103. ** to proxy locking.
  35104. */
  35105. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  35106. switch( op ){
  35107. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  35108. unixFile *pFile = (unixFile*)id;
  35109. if( pFile->pMethod == &proxyIoMethods ){
  35110. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  35111. proxyTakeConch(pFile);
  35112. if( pCtx->lockProxyPath ){
  35113. *(const char **)pArg = pCtx->lockProxyPath;
  35114. }else{
  35115. *(const char **)pArg = ":auto: (not held)";
  35116. }
  35117. } else {
  35118. *(const char **)pArg = NULL;
  35119. }
  35120. return SQLITE_OK;
  35121. }
  35122. case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
  35123. unixFile *pFile = (unixFile*)id;
  35124. int rc = SQLITE_OK;
  35125. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  35126. if( pArg==NULL || (const char *)pArg==0 ){
  35127. if( isProxyStyle ){
  35128. /* turn off proxy locking - not supported. If support is added for
  35129. ** switching proxy locking mode off then it will need to fail if
  35130. ** the journal mode is WAL mode.
  35131. */
  35132. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  35133. }else{
  35134. /* turn off proxy locking - already off - NOOP */
  35135. rc = SQLITE_OK;
  35136. }
  35137. }else{
  35138. const char *proxyPath = (const char *)pArg;
  35139. if( isProxyStyle ){
  35140. proxyLockingContext *pCtx =
  35141. (proxyLockingContext*)pFile->lockingContext;
  35142. if( !strcmp(pArg, ":auto:")
  35143. || (pCtx->lockProxyPath &&
  35144. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  35145. ){
  35146. rc = SQLITE_OK;
  35147. }else{
  35148. rc = switchLockProxyPath(pFile, proxyPath);
  35149. }
  35150. }else{
  35151. /* turn on proxy file locking */
  35152. rc = proxyTransformUnixFile(pFile, proxyPath);
  35153. }
  35154. }
  35155. return rc;
  35156. }
  35157. default: {
  35158. assert( 0 ); /* The call assures that only valid opcodes are sent */
  35159. }
  35160. }
  35161. /*NOTREACHED*/
  35162. return SQLITE_ERROR;
  35163. }
  35164. /*
  35165. ** Within this division (the proxying locking implementation) the procedures
  35166. ** above this point are all utilities. The lock-related methods of the
  35167. ** proxy-locking sqlite3_io_method object follow.
  35168. */
  35169. /*
  35170. ** This routine checks if there is a RESERVED lock held on the specified
  35171. ** file by this or any other process. If such a lock is held, set *pResOut
  35172. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  35173. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  35174. */
  35175. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  35176. unixFile *pFile = (unixFile*)id;
  35177. int rc = proxyTakeConch(pFile);
  35178. if( rc==SQLITE_OK ){
  35179. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  35180. if( pCtx->conchHeld>0 ){
  35181. unixFile *proxy = pCtx->lockProxy;
  35182. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  35183. }else{ /* conchHeld < 0 is lockless */
  35184. pResOut=0;
  35185. }
  35186. }
  35187. return rc;
  35188. }
  35189. /*
  35190. ** Lock the file with the lock specified by parameter eFileLock - one
  35191. ** of the following:
  35192. **
  35193. ** (1) SHARED_LOCK
  35194. ** (2) RESERVED_LOCK
  35195. ** (3) PENDING_LOCK
  35196. ** (4) EXCLUSIVE_LOCK
  35197. **
  35198. ** Sometimes when requesting one lock state, additional lock states
  35199. ** are inserted in between. The locking might fail on one of the later
  35200. ** transitions leaving the lock state different from what it started but
  35201. ** still short of its goal. The following chart shows the allowed
  35202. ** transitions and the inserted intermediate states:
  35203. **
  35204. ** UNLOCKED -> SHARED
  35205. ** SHARED -> RESERVED
  35206. ** SHARED -> (PENDING) -> EXCLUSIVE
  35207. ** RESERVED -> (PENDING) -> EXCLUSIVE
  35208. ** PENDING -> EXCLUSIVE
  35209. **
  35210. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  35211. ** routine to lower a locking level.
  35212. */
  35213. static int proxyLock(sqlite3_file *id, int eFileLock) {
  35214. unixFile *pFile = (unixFile*)id;
  35215. int rc = proxyTakeConch(pFile);
  35216. if( rc==SQLITE_OK ){
  35217. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  35218. if( pCtx->conchHeld>0 ){
  35219. unixFile *proxy = pCtx->lockProxy;
  35220. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  35221. pFile->eFileLock = proxy->eFileLock;
  35222. }else{
  35223. /* conchHeld < 0 is lockless */
  35224. }
  35225. }
  35226. return rc;
  35227. }
  35228. /*
  35229. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  35230. ** must be either NO_LOCK or SHARED_LOCK.
  35231. **
  35232. ** If the locking level of the file descriptor is already at or below
  35233. ** the requested locking level, this routine is a no-op.
  35234. */
  35235. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  35236. unixFile *pFile = (unixFile*)id;
  35237. int rc = proxyTakeConch(pFile);
  35238. if( rc==SQLITE_OK ){
  35239. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  35240. if( pCtx->conchHeld>0 ){
  35241. unixFile *proxy = pCtx->lockProxy;
  35242. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  35243. pFile->eFileLock = proxy->eFileLock;
  35244. }else{
  35245. /* conchHeld < 0 is lockless */
  35246. }
  35247. }
  35248. return rc;
  35249. }
  35250. /*
  35251. ** Close a file that uses proxy locks.
  35252. */
  35253. static int proxyClose(sqlite3_file *id) {
  35254. if( ALWAYS(id) ){
  35255. unixFile *pFile = (unixFile*)id;
  35256. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  35257. unixFile *lockProxy = pCtx->lockProxy;
  35258. unixFile *conchFile = pCtx->conchFile;
  35259. int rc = SQLITE_OK;
  35260. if( lockProxy ){
  35261. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  35262. if( rc ) return rc;
  35263. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  35264. if( rc ) return rc;
  35265. sqlite3_free(lockProxy);
  35266. pCtx->lockProxy = 0;
  35267. }
  35268. if( conchFile ){
  35269. if( pCtx->conchHeld ){
  35270. rc = proxyReleaseConch(pFile);
  35271. if( rc ) return rc;
  35272. }
  35273. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  35274. if( rc ) return rc;
  35275. sqlite3_free(conchFile);
  35276. }
  35277. sqlite3DbFree(0, pCtx->lockProxyPath);
  35278. sqlite3_free(pCtx->conchFilePath);
  35279. sqlite3DbFree(0, pCtx->dbPath);
  35280. /* restore the original locking context and pMethod then close it */
  35281. pFile->lockingContext = pCtx->oldLockingContext;
  35282. pFile->pMethod = pCtx->pOldMethod;
  35283. sqlite3_free(pCtx);
  35284. return pFile->pMethod->xClose(id);
  35285. }
  35286. return SQLITE_OK;
  35287. }
  35288. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  35289. /*
  35290. ** The proxy locking style is intended for use with AFP filesystems.
  35291. ** And since AFP is only supported on MacOSX, the proxy locking is also
  35292. ** restricted to MacOSX.
  35293. **
  35294. **
  35295. ******************* End of the proxy lock implementation **********************
  35296. ******************************************************************************/
  35297. /*
  35298. ** Initialize the operating system interface.
  35299. **
  35300. ** This routine registers all VFS implementations for unix-like operating
  35301. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  35302. ** should be the only routines in this file that are visible from other
  35303. ** files.
  35304. **
  35305. ** This routine is called once during SQLite initialization and by a
  35306. ** single thread. The memory allocation and mutex subsystems have not
  35307. ** necessarily been initialized when this routine is called, and so they
  35308. ** should not be used.
  35309. */
  35310. SQLITE_API int sqlite3_os_init(void){
  35311. /*
  35312. ** The following macro defines an initializer for an sqlite3_vfs object.
  35313. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  35314. ** to the "finder" function. (pAppData is a pointer to a pointer because
  35315. ** silly C90 rules prohibit a void* from being cast to a function pointer
  35316. ** and so we have to go through the intermediate pointer to avoid problems
  35317. ** when compiling with -pedantic-errors on GCC.)
  35318. **
  35319. ** The FINDER parameter to this macro is the name of the pointer to the
  35320. ** finder-function. The finder-function returns a pointer to the
  35321. ** sqlite_io_methods object that implements the desired locking
  35322. ** behaviors. See the division above that contains the IOMETHODS
  35323. ** macro for addition information on finder-functions.
  35324. **
  35325. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  35326. ** object. But the "autolockIoFinder" available on MacOSX does a little
  35327. ** more than that; it looks at the filesystem type that hosts the
  35328. ** database file and tries to choose an locking method appropriate for
  35329. ** that filesystem time.
  35330. */
  35331. #define UNIXVFS(VFSNAME, FINDER) { \
  35332. 3, /* iVersion */ \
  35333. sizeof(unixFile), /* szOsFile */ \
  35334. MAX_PATHNAME, /* mxPathname */ \
  35335. 0, /* pNext */ \
  35336. VFSNAME, /* zName */ \
  35337. (void*)&FINDER, /* pAppData */ \
  35338. unixOpen, /* xOpen */ \
  35339. unixDelete, /* xDelete */ \
  35340. unixAccess, /* xAccess */ \
  35341. unixFullPathname, /* xFullPathname */ \
  35342. unixDlOpen, /* xDlOpen */ \
  35343. unixDlError, /* xDlError */ \
  35344. unixDlSym, /* xDlSym */ \
  35345. unixDlClose, /* xDlClose */ \
  35346. unixRandomness, /* xRandomness */ \
  35347. unixSleep, /* xSleep */ \
  35348. unixCurrentTime, /* xCurrentTime */ \
  35349. unixGetLastError, /* xGetLastError */ \
  35350. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  35351. unixSetSystemCall, /* xSetSystemCall */ \
  35352. unixGetSystemCall, /* xGetSystemCall */ \
  35353. unixNextSystemCall, /* xNextSystemCall */ \
  35354. }
  35355. /*
  35356. ** All default VFSes for unix are contained in the following array.
  35357. **
  35358. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  35359. ** by the SQLite core when the VFS is registered. So the following
  35360. ** array cannot be const.
  35361. */
  35362. static sqlite3_vfs aVfs[] = {
  35363. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  35364. UNIXVFS("unix", autolockIoFinder ),
  35365. #elif OS_VXWORKS
  35366. UNIXVFS("unix", vxworksIoFinder ),
  35367. #else
  35368. UNIXVFS("unix", posixIoFinder ),
  35369. #endif
  35370. UNIXVFS("unix-none", nolockIoFinder ),
  35371. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  35372. UNIXVFS("unix-excl", posixIoFinder ),
  35373. #if OS_VXWORKS
  35374. UNIXVFS("unix-namedsem", semIoFinder ),
  35375. #endif
  35376. #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
  35377. UNIXVFS("unix-posix", posixIoFinder ),
  35378. #endif
  35379. #if SQLITE_ENABLE_LOCKING_STYLE
  35380. UNIXVFS("unix-flock", flockIoFinder ),
  35381. #endif
  35382. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  35383. UNIXVFS("unix-afp", afpIoFinder ),
  35384. UNIXVFS("unix-nfs", nfsIoFinder ),
  35385. UNIXVFS("unix-proxy", proxyIoFinder ),
  35386. #endif
  35387. };
  35388. unsigned int i; /* Loop counter */
  35389. /* Double-check that the aSyscall[] array has been constructed
  35390. ** correctly. See ticket [bb3a86e890c8e96ab] */
  35391. assert( ArraySize(aSyscall)==28 );
  35392. /* Register all VFSes defined in the aVfs[] array */
  35393. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  35394. sqlite3_vfs_register(&aVfs[i], i==0);
  35395. }
  35396. return SQLITE_OK;
  35397. }
  35398. /*
  35399. ** Shutdown the operating system interface.
  35400. **
  35401. ** Some operating systems might need to do some cleanup in this routine,
  35402. ** to release dynamically allocated objects. But not on unix.
  35403. ** This routine is a no-op for unix.
  35404. */
  35405. SQLITE_API int sqlite3_os_end(void){
  35406. return SQLITE_OK;
  35407. }
  35408. #endif /* SQLITE_OS_UNIX */
  35409. /************** End of os_unix.c *********************************************/
  35410. /************** Begin file os_win.c ******************************************/
  35411. /*
  35412. ** 2004 May 22
  35413. **
  35414. ** The author disclaims copyright to this source code. In place of
  35415. ** a legal notice, here is a blessing:
  35416. **
  35417. ** May you do good and not evil.
  35418. ** May you find forgiveness for yourself and forgive others.
  35419. ** May you share freely, never taking more than you give.
  35420. **
  35421. ******************************************************************************
  35422. **
  35423. ** This file contains code that is specific to Windows.
  35424. */
  35425. /* #include "sqliteInt.h" */
  35426. #if SQLITE_OS_WIN /* This file is used for Windows only */
  35427. /*
  35428. ** Include code that is common to all os_*.c files
  35429. */
  35430. /************** Include os_common.h in the middle of os_win.c ****************/
  35431. /************** Begin file os_common.h ***************************************/
  35432. /*
  35433. ** 2004 May 22
  35434. **
  35435. ** The author disclaims copyright to this source code. In place of
  35436. ** a legal notice, here is a blessing:
  35437. **
  35438. ** May you do good and not evil.
  35439. ** May you find forgiveness for yourself and forgive others.
  35440. ** May you share freely, never taking more than you give.
  35441. **
  35442. ******************************************************************************
  35443. **
  35444. ** This file contains macros and a little bit of code that is common to
  35445. ** all of the platform-specific files (os_*.c) and is #included into those
  35446. ** files.
  35447. **
  35448. ** This file should be #included by the os_*.c files only. It is not a
  35449. ** general purpose header file.
  35450. */
  35451. #ifndef _OS_COMMON_H_
  35452. #define _OS_COMMON_H_
  35453. /*
  35454. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  35455. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  35456. ** switch. The following code should catch this problem at compile-time.
  35457. */
  35458. #ifdef MEMORY_DEBUG
  35459. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  35460. #endif
  35461. /*
  35462. ** Macros for performance tracing. Normally turned off. Only works
  35463. ** on i486 hardware.
  35464. */
  35465. #ifdef SQLITE_PERFORMANCE_TRACE
  35466. /*
  35467. ** hwtime.h contains inline assembler code for implementing
  35468. ** high-performance timing routines.
  35469. */
  35470. /************** Include hwtime.h in the middle of os_common.h ****************/
  35471. /************** Begin file hwtime.h ******************************************/
  35472. /*
  35473. ** 2008 May 27
  35474. **
  35475. ** The author disclaims copyright to this source code. In place of
  35476. ** a legal notice, here is a blessing:
  35477. **
  35478. ** May you do good and not evil.
  35479. ** May you find forgiveness for yourself and forgive others.
  35480. ** May you share freely, never taking more than you give.
  35481. **
  35482. ******************************************************************************
  35483. **
  35484. ** This file contains inline asm code for retrieving "high-performance"
  35485. ** counters for x86 class CPUs.
  35486. */
  35487. #ifndef SQLITE_HWTIME_H
  35488. #define SQLITE_HWTIME_H
  35489. /*
  35490. ** The following routine only works on pentium-class (or newer) processors.
  35491. ** It uses the RDTSC opcode to read the cycle count value out of the
  35492. ** processor and returns that value. This can be used for high-res
  35493. ** profiling.
  35494. */
  35495. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  35496. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  35497. #if defined(__GNUC__)
  35498. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  35499. unsigned int lo, hi;
  35500. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  35501. return (sqlite_uint64)hi << 32 | lo;
  35502. }
  35503. #elif defined(_MSC_VER)
  35504. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  35505. __asm {
  35506. rdtsc
  35507. ret ; return value at EDX:EAX
  35508. }
  35509. }
  35510. #endif
  35511. #elif (defined(__GNUC__) && defined(__x86_64__))
  35512. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  35513. unsigned long val;
  35514. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  35515. return val;
  35516. }
  35517. #elif (defined(__GNUC__) && defined(__ppc__))
  35518. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  35519. unsigned long long retval;
  35520. unsigned long junk;
  35521. __asm__ __volatile__ ("\n\
  35522. 1: mftbu %1\n\
  35523. mftb %L0\n\
  35524. mftbu %0\n\
  35525. cmpw %0,%1\n\
  35526. bne 1b"
  35527. : "=r" (retval), "=r" (junk));
  35528. return retval;
  35529. }
  35530. #else
  35531. #error Need implementation of sqlite3Hwtime() for your platform.
  35532. /*
  35533. ** To compile without implementing sqlite3Hwtime() for your platform,
  35534. ** you can remove the above #error and use the following
  35535. ** stub function. You will lose timing support for many
  35536. ** of the debugging and testing utilities, but it should at
  35537. ** least compile and run.
  35538. */
  35539. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  35540. #endif
  35541. #endif /* !defined(SQLITE_HWTIME_H) */
  35542. /************** End of hwtime.h **********************************************/
  35543. /************** Continuing where we left off in os_common.h ******************/
  35544. static sqlite_uint64 g_start;
  35545. static sqlite_uint64 g_elapsed;
  35546. #define TIMER_START g_start=sqlite3Hwtime()
  35547. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  35548. #define TIMER_ELAPSED g_elapsed
  35549. #else
  35550. #define TIMER_START
  35551. #define TIMER_END
  35552. #define TIMER_ELAPSED ((sqlite_uint64)0)
  35553. #endif
  35554. /*
  35555. ** If we compile with the SQLITE_TEST macro set, then the following block
  35556. ** of code will give us the ability to simulate a disk I/O error. This
  35557. ** is used for testing the I/O recovery logic.
  35558. */
  35559. #if defined(SQLITE_TEST)
  35560. SQLITE_API extern int sqlite3_io_error_hit;
  35561. SQLITE_API extern int sqlite3_io_error_hardhit;
  35562. SQLITE_API extern int sqlite3_io_error_pending;
  35563. SQLITE_API extern int sqlite3_io_error_persist;
  35564. SQLITE_API extern int sqlite3_io_error_benign;
  35565. SQLITE_API extern int sqlite3_diskfull_pending;
  35566. SQLITE_API extern int sqlite3_diskfull;
  35567. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  35568. #define SimulateIOError(CODE) \
  35569. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  35570. || sqlite3_io_error_pending-- == 1 ) \
  35571. { local_ioerr(); CODE; }
  35572. static void local_ioerr(){
  35573. IOTRACE(("IOERR\n"));
  35574. sqlite3_io_error_hit++;
  35575. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  35576. }
  35577. #define SimulateDiskfullError(CODE) \
  35578. if( sqlite3_diskfull_pending ){ \
  35579. if( sqlite3_diskfull_pending == 1 ){ \
  35580. local_ioerr(); \
  35581. sqlite3_diskfull = 1; \
  35582. sqlite3_io_error_hit = 1; \
  35583. CODE; \
  35584. }else{ \
  35585. sqlite3_diskfull_pending--; \
  35586. } \
  35587. }
  35588. #else
  35589. #define SimulateIOErrorBenign(X)
  35590. #define SimulateIOError(A)
  35591. #define SimulateDiskfullError(A)
  35592. #endif /* defined(SQLITE_TEST) */
  35593. /*
  35594. ** When testing, keep a count of the number of open files.
  35595. */
  35596. #if defined(SQLITE_TEST)
  35597. SQLITE_API extern int sqlite3_open_file_count;
  35598. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  35599. #else
  35600. #define OpenCounter(X)
  35601. #endif /* defined(SQLITE_TEST) */
  35602. #endif /* !defined(_OS_COMMON_H_) */
  35603. /************** End of os_common.h *******************************************/
  35604. /************** Continuing where we left off in os_win.c *********************/
  35605. /*
  35606. ** Include the header file for the Windows VFS.
  35607. */
  35608. /* #include "os_win.h" */
  35609. /*
  35610. ** Compiling and using WAL mode requires several APIs that are only
  35611. ** available in Windows platforms based on the NT kernel.
  35612. */
  35613. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  35614. # error "WAL mode requires support from the Windows NT kernel, compile\
  35615. with SQLITE_OMIT_WAL."
  35616. #endif
  35617. #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
  35618. # error "Memory mapped files require support from the Windows NT kernel,\
  35619. compile with SQLITE_MAX_MMAP_SIZE=0."
  35620. #endif
  35621. /*
  35622. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  35623. ** based on the sub-platform)?
  35624. */
  35625. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  35626. # define SQLITE_WIN32_HAS_ANSI
  35627. #endif
  35628. /*
  35629. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  35630. ** based on the sub-platform)?
  35631. */
  35632. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  35633. !defined(SQLITE_WIN32_NO_WIDE)
  35634. # define SQLITE_WIN32_HAS_WIDE
  35635. #endif
  35636. /*
  35637. ** Make sure at least one set of Win32 APIs is available.
  35638. */
  35639. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  35640. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  35641. must be defined."
  35642. #endif
  35643. /*
  35644. ** Define the required Windows SDK version constants if they are not
  35645. ** already available.
  35646. */
  35647. #ifndef NTDDI_WIN8
  35648. # define NTDDI_WIN8 0x06020000
  35649. #endif
  35650. #ifndef NTDDI_WINBLUE
  35651. # define NTDDI_WINBLUE 0x06030000
  35652. #endif
  35653. #ifndef NTDDI_WINTHRESHOLD
  35654. # define NTDDI_WINTHRESHOLD 0x06040000
  35655. #endif
  35656. /*
  35657. ** Check to see if the GetVersionEx[AW] functions are deprecated on the
  35658. ** target system. GetVersionEx was first deprecated in Win8.1.
  35659. */
  35660. #ifndef SQLITE_WIN32_GETVERSIONEX
  35661. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
  35662. # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
  35663. # else
  35664. # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
  35665. # endif
  35666. #endif
  35667. /*
  35668. ** Check to see if the CreateFileMappingA function is supported on the
  35669. ** target system. It is unavailable when using "mincore.lib" on Win10.
  35670. ** When compiling for Windows 10, always assume "mincore.lib" is in use.
  35671. */
  35672. #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
  35673. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
  35674. # define SQLITE_WIN32_CREATEFILEMAPPINGA 0
  35675. # else
  35676. # define SQLITE_WIN32_CREATEFILEMAPPINGA 1
  35677. # endif
  35678. #endif
  35679. /*
  35680. ** This constant should already be defined (in the "WinDef.h" SDK file).
  35681. */
  35682. #ifndef MAX_PATH
  35683. # define MAX_PATH (260)
  35684. #endif
  35685. /*
  35686. ** Maximum pathname length (in chars) for Win32. This should normally be
  35687. ** MAX_PATH.
  35688. */
  35689. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  35690. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  35691. #endif
  35692. /*
  35693. ** This constant should already be defined (in the "WinNT.h" SDK file).
  35694. */
  35695. #ifndef UNICODE_STRING_MAX_CHARS
  35696. # define UNICODE_STRING_MAX_CHARS (32767)
  35697. #endif
  35698. /*
  35699. ** Maximum pathname length (in chars) for WinNT. This should normally be
  35700. ** UNICODE_STRING_MAX_CHARS.
  35701. */
  35702. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  35703. # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
  35704. #endif
  35705. /*
  35706. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  35707. ** characters, so we allocate 4 bytes per character assuming worst-case of
  35708. ** 4-bytes-per-character for UTF8.
  35709. */
  35710. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  35711. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  35712. #endif
  35713. /*
  35714. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  35715. ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
  35716. */
  35717. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  35718. # define SQLITE_WINNT_MAX_PATH_BYTES \
  35719. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  35720. #endif
  35721. /*
  35722. ** Maximum error message length (in chars) for WinRT.
  35723. */
  35724. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  35725. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  35726. #endif
  35727. /*
  35728. ** Returns non-zero if the character should be treated as a directory
  35729. ** separator.
  35730. */
  35731. #ifndef winIsDirSep
  35732. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  35733. #endif
  35734. /*
  35735. ** This macro is used when a local variable is set to a value that is
  35736. ** [sometimes] not used by the code (e.g. via conditional compilation).
  35737. */
  35738. #ifndef UNUSED_VARIABLE_VALUE
  35739. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  35740. #endif
  35741. /*
  35742. ** Returns the character that should be used as the directory separator.
  35743. */
  35744. #ifndef winGetDirSep
  35745. # define winGetDirSep() '\\'
  35746. #endif
  35747. /*
  35748. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  35749. ** mode or memory mapped files (e.g. these APIs are available in the Windows
  35750. ** CE SDK; however, they are not present in the header file)?
  35751. */
  35752. #if SQLITE_WIN32_FILEMAPPING_API && \
  35753. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  35754. /*
  35755. ** Two of the file mapping APIs are different under WinRT. Figure out which
  35756. ** set we need.
  35757. */
  35758. #if SQLITE_OS_WINRT
  35759. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  35760. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  35761. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  35762. #else
  35763. #if defined(SQLITE_WIN32_HAS_ANSI)
  35764. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  35765. DWORD, DWORD, DWORD, LPCSTR);
  35766. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  35767. #if defined(SQLITE_WIN32_HAS_WIDE)
  35768. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  35769. DWORD, DWORD, DWORD, LPCWSTR);
  35770. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  35771. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  35772. #endif /* SQLITE_OS_WINRT */
  35773. /*
  35774. ** These file mapping APIs are common to both Win32 and WinRT.
  35775. */
  35776. WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
  35777. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  35778. #endif /* SQLITE_WIN32_FILEMAPPING_API */
  35779. /*
  35780. ** Some Microsoft compilers lack this definition.
  35781. */
  35782. #ifndef INVALID_FILE_ATTRIBUTES
  35783. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  35784. #endif
  35785. #ifndef FILE_FLAG_MASK
  35786. # define FILE_FLAG_MASK (0xFF3C0000)
  35787. #endif
  35788. #ifndef FILE_ATTRIBUTE_MASK
  35789. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  35790. #endif
  35791. #ifndef SQLITE_OMIT_WAL
  35792. /* Forward references to structures used for WAL */
  35793. typedef struct winShm winShm; /* A connection to shared-memory */
  35794. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  35795. #endif
  35796. /*
  35797. ** WinCE lacks native support for file locking so we have to fake it
  35798. ** with some code of our own.
  35799. */
  35800. #if SQLITE_OS_WINCE
  35801. typedef struct winceLock {
  35802. int nReaders; /* Number of reader locks obtained */
  35803. BOOL bPending; /* Indicates a pending lock has been obtained */
  35804. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  35805. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  35806. } winceLock;
  35807. #endif
  35808. /*
  35809. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  35810. ** portability layer.
  35811. */
  35812. typedef struct winFile winFile;
  35813. struct winFile {
  35814. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  35815. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  35816. HANDLE h; /* Handle for accessing the file */
  35817. u8 locktype; /* Type of lock currently held on this file */
  35818. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  35819. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  35820. DWORD lastErrno; /* The Windows errno from the last I/O error */
  35821. #ifndef SQLITE_OMIT_WAL
  35822. winShm *pShm; /* Instance of shared memory on this file */
  35823. #endif
  35824. const char *zPath; /* Full pathname of this file */
  35825. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  35826. #if SQLITE_OS_WINCE
  35827. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  35828. HANDLE hMutex; /* Mutex used to control access to shared lock */
  35829. HANDLE hShared; /* Shared memory segment used for locking */
  35830. winceLock local; /* Locks obtained by this instance of winFile */
  35831. winceLock *shared; /* Global shared lock memory for the file */
  35832. #endif
  35833. #if SQLITE_MAX_MMAP_SIZE>0
  35834. int nFetchOut; /* Number of outstanding xFetch references */
  35835. HANDLE hMap; /* Handle for accessing memory mapping */
  35836. void *pMapRegion; /* Area memory mapped */
  35837. sqlite3_int64 mmapSize; /* Usable size of mapped region */
  35838. sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
  35839. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  35840. #endif
  35841. };
  35842. /*
  35843. ** The winVfsAppData structure is used for the pAppData member for all of the
  35844. ** Win32 VFS variants.
  35845. */
  35846. typedef struct winVfsAppData winVfsAppData;
  35847. struct winVfsAppData {
  35848. const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
  35849. void *pAppData; /* The extra pAppData, if any. */
  35850. BOOL bNoLock; /* Non-zero if locking is disabled. */
  35851. };
  35852. /*
  35853. ** Allowed values for winFile.ctrlFlags
  35854. */
  35855. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  35856. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  35857. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  35858. /*
  35859. * The size of the buffer used by sqlite3_win32_write_debug().
  35860. */
  35861. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  35862. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  35863. #endif
  35864. /*
  35865. * The value used with sqlite3_win32_set_directory() to specify that
  35866. * the data directory should be changed.
  35867. */
  35868. #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
  35869. # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
  35870. #endif
  35871. /*
  35872. * The value used with sqlite3_win32_set_directory() to specify that
  35873. * the temporary directory should be changed.
  35874. */
  35875. #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  35876. # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
  35877. #endif
  35878. /*
  35879. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  35880. * various Win32 API heap functions instead of our own.
  35881. */
  35882. #ifdef SQLITE_WIN32_MALLOC
  35883. /*
  35884. * If this is non-zero, an isolated heap will be created by the native Win32
  35885. * allocator subsystem; otherwise, the default process heap will be used. This
  35886. * setting has no effect when compiling for WinRT. By default, this is enabled
  35887. * and an isolated heap will be created to store all allocated data.
  35888. *
  35889. ******************************************************************************
  35890. * WARNING: It is important to note that when this setting is non-zero and the
  35891. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  35892. * function), all data that was allocated using the isolated heap will
  35893. * be freed immediately and any attempt to access any of that freed
  35894. * data will almost certainly result in an immediate access violation.
  35895. ******************************************************************************
  35896. */
  35897. #ifndef SQLITE_WIN32_HEAP_CREATE
  35898. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  35899. #endif
  35900. /*
  35901. * This is the maximum possible initial size of the Win32-specific heap, in
  35902. * bytes.
  35903. */
  35904. #ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
  35905. # define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
  35906. #endif
  35907. /*
  35908. * This is the extra space for the initial size of the Win32-specific heap,
  35909. * in bytes. This value may be zero.
  35910. */
  35911. #ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
  35912. # define SQLITE_WIN32_HEAP_INIT_EXTRA (4194304)
  35913. #endif
  35914. /*
  35915. * Calculate the maximum legal cache size, in pages, based on the maximum
  35916. * possible initial heap size and the default page size, setting aside the
  35917. * needed extra space.
  35918. */
  35919. #ifndef SQLITE_WIN32_MAX_CACHE_SIZE
  35920. # define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
  35921. (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
  35922. (SQLITE_DEFAULT_PAGE_SIZE))
  35923. #endif
  35924. /*
  35925. * This is cache size used in the calculation of the initial size of the
  35926. * Win32-specific heap. It cannot be negative.
  35927. */
  35928. #ifndef SQLITE_WIN32_CACHE_SIZE
  35929. # if SQLITE_DEFAULT_CACHE_SIZE>=0
  35930. # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
  35931. # else
  35932. # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
  35933. # endif
  35934. #endif
  35935. /*
  35936. * Make sure that the calculated cache size, in pages, cannot cause the
  35937. * initial size of the Win32-specific heap to exceed the maximum amount
  35938. * of memory that can be specified in the call to HeapCreate.
  35939. */
  35940. #if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
  35941. # undef SQLITE_WIN32_CACHE_SIZE
  35942. # define SQLITE_WIN32_CACHE_SIZE (2000)
  35943. #endif
  35944. /*
  35945. * The initial size of the Win32-specific heap. This value may be zero.
  35946. */
  35947. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  35948. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
  35949. (SQLITE_DEFAULT_PAGE_SIZE) + \
  35950. (SQLITE_WIN32_HEAP_INIT_EXTRA))
  35951. #endif
  35952. /*
  35953. * The maximum size of the Win32-specific heap. This value may be zero.
  35954. */
  35955. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  35956. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  35957. #endif
  35958. /*
  35959. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  35960. * zero for the default behavior.
  35961. */
  35962. #ifndef SQLITE_WIN32_HEAP_FLAGS
  35963. # define SQLITE_WIN32_HEAP_FLAGS (0)
  35964. #endif
  35965. /*
  35966. ** The winMemData structure stores information required by the Win32-specific
  35967. ** sqlite3_mem_methods implementation.
  35968. */
  35969. typedef struct winMemData winMemData;
  35970. struct winMemData {
  35971. #ifndef NDEBUG
  35972. u32 magic1; /* Magic number to detect structure corruption. */
  35973. #endif
  35974. HANDLE hHeap; /* The handle to our heap. */
  35975. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  35976. #ifndef NDEBUG
  35977. u32 magic2; /* Magic number to detect structure corruption. */
  35978. #endif
  35979. };
  35980. #ifndef NDEBUG
  35981. #define WINMEM_MAGIC1 0x42b2830b
  35982. #define WINMEM_MAGIC2 0xbd4d7cf4
  35983. #endif
  35984. static struct winMemData win_mem_data = {
  35985. #ifndef NDEBUG
  35986. WINMEM_MAGIC1,
  35987. #endif
  35988. NULL, FALSE
  35989. #ifndef NDEBUG
  35990. ,WINMEM_MAGIC2
  35991. #endif
  35992. };
  35993. #ifndef NDEBUG
  35994. #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
  35995. #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
  35996. #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
  35997. #else
  35998. #define winMemAssertMagic()
  35999. #endif
  36000. #define winMemGetDataPtr() &win_mem_data
  36001. #define winMemGetHeap() win_mem_data.hHeap
  36002. #define winMemGetOwned() win_mem_data.bOwned
  36003. static void *winMemMalloc(int nBytes);
  36004. static void winMemFree(void *pPrior);
  36005. static void *winMemRealloc(void *pPrior, int nBytes);
  36006. static int winMemSize(void *p);
  36007. static int winMemRoundup(int n);
  36008. static int winMemInit(void *pAppData);
  36009. static void winMemShutdown(void *pAppData);
  36010. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  36011. #endif /* SQLITE_WIN32_MALLOC */
  36012. /*
  36013. ** The following variable is (normally) set once and never changes
  36014. ** thereafter. It records whether the operating system is Win9x
  36015. ** or WinNT.
  36016. **
  36017. ** 0: Operating system unknown.
  36018. ** 1: Operating system is Win9x.
  36019. ** 2: Operating system is WinNT.
  36020. **
  36021. ** In order to facilitate testing on a WinNT system, the test fixture
  36022. ** can manually set this value to 1 to emulate Win98 behavior.
  36023. */
  36024. #ifdef SQLITE_TEST
  36025. SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  36026. #else
  36027. static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  36028. #endif
  36029. #ifndef SYSCALL
  36030. # define SYSCALL sqlite3_syscall_ptr
  36031. #endif
  36032. /*
  36033. ** This function is not available on Windows CE or WinRT.
  36034. */
  36035. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  36036. # define osAreFileApisANSI() 1
  36037. #endif
  36038. /*
  36039. ** Many system calls are accessed through pointer-to-functions so that
  36040. ** they may be overridden at runtime to facilitate fault injection during
  36041. ** testing and sandboxing. The following array holds the names and pointers
  36042. ** to all overrideable system calls.
  36043. */
  36044. static struct win_syscall {
  36045. const char *zName; /* Name of the system call */
  36046. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  36047. sqlite3_syscall_ptr pDefault; /* Default value */
  36048. } aSyscall[] = {
  36049. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  36050. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  36051. #else
  36052. { "AreFileApisANSI", (SYSCALL)0, 0 },
  36053. #endif
  36054. #ifndef osAreFileApisANSI
  36055. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  36056. #endif
  36057. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  36058. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  36059. #else
  36060. { "CharLowerW", (SYSCALL)0, 0 },
  36061. #endif
  36062. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  36063. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  36064. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  36065. #else
  36066. { "CharUpperW", (SYSCALL)0, 0 },
  36067. #endif
  36068. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  36069. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  36070. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  36071. #if defined(SQLITE_WIN32_HAS_ANSI)
  36072. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  36073. #else
  36074. { "CreateFileA", (SYSCALL)0, 0 },
  36075. #endif
  36076. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  36077. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  36078. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  36079. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  36080. #else
  36081. { "CreateFileW", (SYSCALL)0, 0 },
  36082. #endif
  36083. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  36084. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  36085. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  36086. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
  36087. SQLITE_WIN32_CREATEFILEMAPPINGA
  36088. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  36089. #else
  36090. { "CreateFileMappingA", (SYSCALL)0, 0 },
  36091. #endif
  36092. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  36093. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  36094. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  36095. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  36096. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  36097. #else
  36098. { "CreateFileMappingW", (SYSCALL)0, 0 },
  36099. #endif
  36100. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  36101. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  36102. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  36103. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  36104. #else
  36105. { "CreateMutexW", (SYSCALL)0, 0 },
  36106. #endif
  36107. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  36108. LPCWSTR))aSyscall[8].pCurrent)
  36109. #if defined(SQLITE_WIN32_HAS_ANSI)
  36110. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  36111. #else
  36112. { "DeleteFileA", (SYSCALL)0, 0 },
  36113. #endif
  36114. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  36115. #if defined(SQLITE_WIN32_HAS_WIDE)
  36116. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  36117. #else
  36118. { "DeleteFileW", (SYSCALL)0, 0 },
  36119. #endif
  36120. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  36121. #if SQLITE_OS_WINCE
  36122. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  36123. #else
  36124. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  36125. #endif
  36126. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  36127. LPFILETIME))aSyscall[11].pCurrent)
  36128. #if SQLITE_OS_WINCE
  36129. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  36130. #else
  36131. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  36132. #endif
  36133. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  36134. LPSYSTEMTIME))aSyscall[12].pCurrent)
  36135. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  36136. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  36137. #if defined(SQLITE_WIN32_HAS_ANSI)
  36138. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  36139. #else
  36140. { "FormatMessageA", (SYSCALL)0, 0 },
  36141. #endif
  36142. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  36143. DWORD,va_list*))aSyscall[14].pCurrent)
  36144. #if defined(SQLITE_WIN32_HAS_WIDE)
  36145. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  36146. #else
  36147. { "FormatMessageW", (SYSCALL)0, 0 },
  36148. #endif
  36149. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  36150. DWORD,va_list*))aSyscall[15].pCurrent)
  36151. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  36152. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  36153. #else
  36154. { "FreeLibrary", (SYSCALL)0, 0 },
  36155. #endif
  36156. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  36157. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  36158. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  36159. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  36160. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  36161. #else
  36162. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  36163. #endif
  36164. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  36165. LPDWORD))aSyscall[18].pCurrent)
  36166. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  36167. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  36168. #else
  36169. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  36170. #endif
  36171. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  36172. LPDWORD))aSyscall[19].pCurrent)
  36173. #if defined(SQLITE_WIN32_HAS_ANSI)
  36174. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  36175. #else
  36176. { "GetFileAttributesA", (SYSCALL)0, 0 },
  36177. #endif
  36178. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  36179. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  36180. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  36181. #else
  36182. { "GetFileAttributesW", (SYSCALL)0, 0 },
  36183. #endif
  36184. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  36185. #if defined(SQLITE_WIN32_HAS_WIDE)
  36186. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  36187. #else
  36188. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  36189. #endif
  36190. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  36191. LPVOID))aSyscall[22].pCurrent)
  36192. #if !SQLITE_OS_WINRT
  36193. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  36194. #else
  36195. { "GetFileSize", (SYSCALL)0, 0 },
  36196. #endif
  36197. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  36198. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  36199. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  36200. #else
  36201. { "GetFullPathNameA", (SYSCALL)0, 0 },
  36202. #endif
  36203. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  36204. LPSTR*))aSyscall[24].pCurrent)
  36205. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  36206. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  36207. #else
  36208. { "GetFullPathNameW", (SYSCALL)0, 0 },
  36209. #endif
  36210. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  36211. LPWSTR*))aSyscall[25].pCurrent)
  36212. { "GetLastError", (SYSCALL)GetLastError, 0 },
  36213. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  36214. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  36215. #if SQLITE_OS_WINCE
  36216. /* The GetProcAddressA() routine is only available on Windows CE. */
  36217. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  36218. #else
  36219. /* All other Windows platforms expect GetProcAddress() to take
  36220. ** an ANSI string regardless of the _UNICODE setting */
  36221. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  36222. #endif
  36223. #else
  36224. { "GetProcAddressA", (SYSCALL)0, 0 },
  36225. #endif
  36226. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  36227. LPCSTR))aSyscall[27].pCurrent)
  36228. #if !SQLITE_OS_WINRT
  36229. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  36230. #else
  36231. { "GetSystemInfo", (SYSCALL)0, 0 },
  36232. #endif
  36233. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  36234. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  36235. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  36236. #if !SQLITE_OS_WINCE
  36237. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  36238. #else
  36239. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  36240. #endif
  36241. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  36242. LPFILETIME))aSyscall[30].pCurrent)
  36243. #if defined(SQLITE_WIN32_HAS_ANSI)
  36244. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  36245. #else
  36246. { "GetTempPathA", (SYSCALL)0, 0 },
  36247. #endif
  36248. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  36249. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  36250. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  36251. #else
  36252. { "GetTempPathW", (SYSCALL)0, 0 },
  36253. #endif
  36254. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  36255. #if !SQLITE_OS_WINRT
  36256. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  36257. #else
  36258. { "GetTickCount", (SYSCALL)0, 0 },
  36259. #endif
  36260. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  36261. #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
  36262. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  36263. #else
  36264. { "GetVersionExA", (SYSCALL)0, 0 },
  36265. #endif
  36266. #define osGetVersionExA ((BOOL(WINAPI*)( \
  36267. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  36268. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  36269. SQLITE_WIN32_GETVERSIONEX
  36270. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  36271. #else
  36272. { "GetVersionExW", (SYSCALL)0, 0 },
  36273. #endif
  36274. #define osGetVersionExW ((BOOL(WINAPI*)( \
  36275. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  36276. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  36277. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  36278. SIZE_T))aSyscall[36].pCurrent)
  36279. #if !SQLITE_OS_WINRT
  36280. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  36281. #else
  36282. { "HeapCreate", (SYSCALL)0, 0 },
  36283. #endif
  36284. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  36285. SIZE_T))aSyscall[37].pCurrent)
  36286. #if !SQLITE_OS_WINRT
  36287. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  36288. #else
  36289. { "HeapDestroy", (SYSCALL)0, 0 },
  36290. #endif
  36291. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  36292. { "HeapFree", (SYSCALL)HeapFree, 0 },
  36293. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  36294. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  36295. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  36296. SIZE_T))aSyscall[40].pCurrent)
  36297. { "HeapSize", (SYSCALL)HeapSize, 0 },
  36298. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  36299. LPCVOID))aSyscall[41].pCurrent)
  36300. #if !SQLITE_OS_WINRT
  36301. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  36302. #else
  36303. { "HeapValidate", (SYSCALL)0, 0 },
  36304. #endif
  36305. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  36306. LPCVOID))aSyscall[42].pCurrent)
  36307. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  36308. { "HeapCompact", (SYSCALL)HeapCompact, 0 },
  36309. #else
  36310. { "HeapCompact", (SYSCALL)0, 0 },
  36311. #endif
  36312. #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
  36313. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  36314. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  36315. #else
  36316. { "LoadLibraryA", (SYSCALL)0, 0 },
  36317. #endif
  36318. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
  36319. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  36320. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  36321. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  36322. #else
  36323. { "LoadLibraryW", (SYSCALL)0, 0 },
  36324. #endif
  36325. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
  36326. #if !SQLITE_OS_WINRT
  36327. { "LocalFree", (SYSCALL)LocalFree, 0 },
  36328. #else
  36329. { "LocalFree", (SYSCALL)0, 0 },
  36330. #endif
  36331. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
  36332. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  36333. { "LockFile", (SYSCALL)LockFile, 0 },
  36334. #else
  36335. { "LockFile", (SYSCALL)0, 0 },
  36336. #endif
  36337. #ifndef osLockFile
  36338. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  36339. DWORD))aSyscall[47].pCurrent)
  36340. #endif
  36341. #if !SQLITE_OS_WINCE
  36342. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  36343. #else
  36344. { "LockFileEx", (SYSCALL)0, 0 },
  36345. #endif
  36346. #ifndef osLockFileEx
  36347. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  36348. LPOVERLAPPED))aSyscall[48].pCurrent)
  36349. #endif
  36350. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
  36351. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  36352. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  36353. #else
  36354. { "MapViewOfFile", (SYSCALL)0, 0 },
  36355. #endif
  36356. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  36357. SIZE_T))aSyscall[49].pCurrent)
  36358. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  36359. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  36360. int))aSyscall[50].pCurrent)
  36361. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  36362. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  36363. LARGE_INTEGER*))aSyscall[51].pCurrent)
  36364. { "ReadFile", (SYSCALL)ReadFile, 0 },
  36365. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  36366. LPOVERLAPPED))aSyscall[52].pCurrent)
  36367. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  36368. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
  36369. #if !SQLITE_OS_WINRT
  36370. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  36371. #else
  36372. { "SetFilePointer", (SYSCALL)0, 0 },
  36373. #endif
  36374. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  36375. DWORD))aSyscall[54].pCurrent)
  36376. #if !SQLITE_OS_WINRT
  36377. { "Sleep", (SYSCALL)Sleep, 0 },
  36378. #else
  36379. { "Sleep", (SYSCALL)0, 0 },
  36380. #endif
  36381. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
  36382. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  36383. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  36384. LPFILETIME))aSyscall[56].pCurrent)
  36385. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  36386. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  36387. #else
  36388. { "UnlockFile", (SYSCALL)0, 0 },
  36389. #endif
  36390. #ifndef osUnlockFile
  36391. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  36392. DWORD))aSyscall[57].pCurrent)
  36393. #endif
  36394. #if !SQLITE_OS_WINCE
  36395. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  36396. #else
  36397. { "UnlockFileEx", (SYSCALL)0, 0 },
  36398. #endif
  36399. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  36400. LPOVERLAPPED))aSyscall[58].pCurrent)
  36401. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  36402. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  36403. #else
  36404. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  36405. #endif
  36406. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
  36407. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  36408. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  36409. LPCSTR,LPBOOL))aSyscall[60].pCurrent)
  36410. { "WriteFile", (SYSCALL)WriteFile, 0 },
  36411. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  36412. LPOVERLAPPED))aSyscall[61].pCurrent)
  36413. #if SQLITE_OS_WINRT
  36414. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  36415. #else
  36416. { "CreateEventExW", (SYSCALL)0, 0 },
  36417. #endif
  36418. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  36419. DWORD,DWORD))aSyscall[62].pCurrent)
  36420. #if !SQLITE_OS_WINRT
  36421. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  36422. #else
  36423. { "WaitForSingleObject", (SYSCALL)0, 0 },
  36424. #endif
  36425. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  36426. DWORD))aSyscall[63].pCurrent)
  36427. #if !SQLITE_OS_WINCE
  36428. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  36429. #else
  36430. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  36431. #endif
  36432. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  36433. BOOL))aSyscall[64].pCurrent)
  36434. #if SQLITE_OS_WINRT
  36435. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  36436. #else
  36437. { "SetFilePointerEx", (SYSCALL)0, 0 },
  36438. #endif
  36439. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  36440. PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
  36441. #if SQLITE_OS_WINRT
  36442. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  36443. #else
  36444. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  36445. #endif
  36446. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  36447. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
  36448. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  36449. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  36450. #else
  36451. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  36452. #endif
  36453. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  36454. SIZE_T))aSyscall[67].pCurrent)
  36455. #if SQLITE_OS_WINRT
  36456. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  36457. #else
  36458. { "CreateFile2", (SYSCALL)0, 0 },
  36459. #endif
  36460. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  36461. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
  36462. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  36463. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  36464. #else
  36465. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  36466. #endif
  36467. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  36468. DWORD))aSyscall[69].pCurrent)
  36469. #if SQLITE_OS_WINRT
  36470. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  36471. #else
  36472. { "GetTickCount64", (SYSCALL)0, 0 },
  36473. #endif
  36474. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
  36475. #if SQLITE_OS_WINRT
  36476. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  36477. #else
  36478. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  36479. #endif
  36480. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  36481. LPSYSTEM_INFO))aSyscall[71].pCurrent)
  36482. #if defined(SQLITE_WIN32_HAS_ANSI)
  36483. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  36484. #else
  36485. { "OutputDebugStringA", (SYSCALL)0, 0 },
  36486. #endif
  36487. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
  36488. #if defined(SQLITE_WIN32_HAS_WIDE)
  36489. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  36490. #else
  36491. { "OutputDebugStringW", (SYSCALL)0, 0 },
  36492. #endif
  36493. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
  36494. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  36495. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
  36496. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  36497. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  36498. #else
  36499. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  36500. #endif
  36501. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  36502. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
  36503. /*
  36504. ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
  36505. ** is really just a macro that uses a compiler intrinsic (e.g. x64).
  36506. ** So do not try to make this is into a redefinable interface.
  36507. */
  36508. #if defined(InterlockedCompareExchange)
  36509. { "InterlockedCompareExchange", (SYSCALL)0, 0 },
  36510. #define osInterlockedCompareExchange InterlockedCompareExchange
  36511. #else
  36512. { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
  36513. #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
  36514. SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
  36515. #endif /* defined(InterlockedCompareExchange) */
  36516. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  36517. { "UuidCreate", (SYSCALL)UuidCreate, 0 },
  36518. #else
  36519. { "UuidCreate", (SYSCALL)0, 0 },
  36520. #endif
  36521. #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
  36522. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  36523. { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
  36524. #else
  36525. { "UuidCreateSequential", (SYSCALL)0, 0 },
  36526. #endif
  36527. #define osUuidCreateSequential \
  36528. ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
  36529. #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
  36530. { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
  36531. #else
  36532. { "FlushViewOfFile", (SYSCALL)0, 0 },
  36533. #endif
  36534. #define osFlushViewOfFile \
  36535. ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
  36536. }; /* End of the overrideable system calls */
  36537. /*
  36538. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  36539. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  36540. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  36541. ** system call named zName.
  36542. */
  36543. static int winSetSystemCall(
  36544. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  36545. const char *zName, /* Name of system call to override */
  36546. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  36547. ){
  36548. unsigned int i;
  36549. int rc = SQLITE_NOTFOUND;
  36550. UNUSED_PARAMETER(pNotUsed);
  36551. if( zName==0 ){
  36552. /* If no zName is given, restore all system calls to their default
  36553. ** settings and return NULL
  36554. */
  36555. rc = SQLITE_OK;
  36556. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  36557. if( aSyscall[i].pDefault ){
  36558. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  36559. }
  36560. }
  36561. }else{
  36562. /* If zName is specified, operate on only the one system call
  36563. ** specified.
  36564. */
  36565. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  36566. if( strcmp(zName, aSyscall[i].zName)==0 ){
  36567. if( aSyscall[i].pDefault==0 ){
  36568. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  36569. }
  36570. rc = SQLITE_OK;
  36571. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  36572. aSyscall[i].pCurrent = pNewFunc;
  36573. break;
  36574. }
  36575. }
  36576. }
  36577. return rc;
  36578. }
  36579. /*
  36580. ** Return the value of a system call. Return NULL if zName is not a
  36581. ** recognized system call name. NULL is also returned if the system call
  36582. ** is currently undefined.
  36583. */
  36584. static sqlite3_syscall_ptr winGetSystemCall(
  36585. sqlite3_vfs *pNotUsed,
  36586. const char *zName
  36587. ){
  36588. unsigned int i;
  36589. UNUSED_PARAMETER(pNotUsed);
  36590. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  36591. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  36592. }
  36593. return 0;
  36594. }
  36595. /*
  36596. ** Return the name of the first system call after zName. If zName==NULL
  36597. ** then return the name of the first system call. Return NULL if zName
  36598. ** is the last system call or if zName is not the name of a valid
  36599. ** system call.
  36600. */
  36601. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  36602. int i = -1;
  36603. UNUSED_PARAMETER(p);
  36604. if( zName ){
  36605. for(i=0; i<ArraySize(aSyscall)-1; i++){
  36606. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  36607. }
  36608. }
  36609. for(i++; i<ArraySize(aSyscall); i++){
  36610. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  36611. }
  36612. return 0;
  36613. }
  36614. #ifdef SQLITE_WIN32_MALLOC
  36615. /*
  36616. ** If a Win32 native heap has been configured, this function will attempt to
  36617. ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
  36618. ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
  36619. ** "pnLargest" argument, if non-zero, will be used to return the size of the
  36620. ** largest committed free block in the heap, in bytes.
  36621. */
  36622. SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
  36623. int rc = SQLITE_OK;
  36624. UINT nLargest = 0;
  36625. HANDLE hHeap;
  36626. winMemAssertMagic();
  36627. hHeap = winMemGetHeap();
  36628. assert( hHeap!=0 );
  36629. assert( hHeap!=INVALID_HANDLE_VALUE );
  36630. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  36631. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  36632. #endif
  36633. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  36634. if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
  36635. DWORD lastErrno = osGetLastError();
  36636. if( lastErrno==NO_ERROR ){
  36637. sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
  36638. (void*)hHeap);
  36639. rc = SQLITE_NOMEM_BKPT;
  36640. }else{
  36641. sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
  36642. osGetLastError(), (void*)hHeap);
  36643. rc = SQLITE_ERROR;
  36644. }
  36645. }
  36646. #else
  36647. sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
  36648. (void*)hHeap);
  36649. rc = SQLITE_NOTFOUND;
  36650. #endif
  36651. if( pnLargest ) *pnLargest = nLargest;
  36652. return rc;
  36653. }
  36654. /*
  36655. ** If a Win32 native heap has been configured, this function will attempt to
  36656. ** destroy and recreate it. If the Win32 native heap is not isolated and/or
  36657. ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
  36658. ** be returned and no changes will be made to the Win32 native heap.
  36659. */
  36660. SQLITE_API int sqlite3_win32_reset_heap(){
  36661. int rc;
  36662. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  36663. MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
  36664. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  36665. MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
  36666. sqlite3_mutex_enter(pMaster);
  36667. sqlite3_mutex_enter(pMem);
  36668. winMemAssertMagic();
  36669. if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
  36670. /*
  36671. ** At this point, there should be no outstanding memory allocations on
  36672. ** the heap. Also, since both the master and memsys locks are currently
  36673. ** being held by us, no other function (i.e. from another thread) should
  36674. ** be able to even access the heap. Attempt to destroy and recreate our
  36675. ** isolated Win32 native heap now.
  36676. */
  36677. assert( winMemGetHeap()!=NULL );
  36678. assert( winMemGetOwned() );
  36679. assert( sqlite3_memory_used()==0 );
  36680. winMemShutdown(winMemGetDataPtr());
  36681. assert( winMemGetHeap()==NULL );
  36682. assert( !winMemGetOwned() );
  36683. assert( sqlite3_memory_used()==0 );
  36684. rc = winMemInit(winMemGetDataPtr());
  36685. assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
  36686. assert( rc!=SQLITE_OK || winMemGetOwned() );
  36687. assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
  36688. }else{
  36689. /*
  36690. ** The Win32 native heap cannot be modified because it may be in use.
  36691. */
  36692. rc = SQLITE_BUSY;
  36693. }
  36694. sqlite3_mutex_leave(pMem);
  36695. sqlite3_mutex_leave(pMaster);
  36696. return rc;
  36697. }
  36698. #endif /* SQLITE_WIN32_MALLOC */
  36699. /*
  36700. ** This function outputs the specified (ANSI) string to the Win32 debugger
  36701. ** (if available).
  36702. */
  36703. SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  36704. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  36705. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  36706. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  36707. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  36708. #ifdef SQLITE_ENABLE_API_ARMOR
  36709. if( !zBuf ){
  36710. (void)SQLITE_MISUSE_BKPT;
  36711. return;
  36712. }
  36713. #endif
  36714. #if defined(SQLITE_WIN32_HAS_ANSI)
  36715. if( nMin>0 ){
  36716. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  36717. memcpy(zDbgBuf, zBuf, nMin);
  36718. osOutputDebugStringA(zDbgBuf);
  36719. }else{
  36720. osOutputDebugStringA(zBuf);
  36721. }
  36722. #elif defined(SQLITE_WIN32_HAS_WIDE)
  36723. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  36724. if ( osMultiByteToWideChar(
  36725. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  36726. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  36727. return;
  36728. }
  36729. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  36730. #else
  36731. if( nMin>0 ){
  36732. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  36733. memcpy(zDbgBuf, zBuf, nMin);
  36734. fprintf(stderr, "%s", zDbgBuf);
  36735. }else{
  36736. fprintf(stderr, "%s", zBuf);
  36737. }
  36738. #endif
  36739. }
  36740. /*
  36741. ** The following routine suspends the current thread for at least ms
  36742. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  36743. */
  36744. #if SQLITE_OS_WINRT
  36745. static HANDLE sleepObj = NULL;
  36746. #endif
  36747. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
  36748. #if SQLITE_OS_WINRT
  36749. if ( sleepObj==NULL ){
  36750. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  36751. SYNCHRONIZE);
  36752. }
  36753. assert( sleepObj!=NULL );
  36754. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  36755. #else
  36756. osSleep(milliseconds);
  36757. #endif
  36758. }
  36759. #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  36760. SQLITE_THREADSAFE>0
  36761. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
  36762. DWORD rc;
  36763. while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
  36764. TRUE))==WAIT_IO_COMPLETION ){}
  36765. return rc;
  36766. }
  36767. #endif
  36768. /*
  36769. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  36770. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  36771. **
  36772. ** Here is an interesting observation: Win95, Win98, and WinME lack
  36773. ** the LockFileEx() API. But we can still statically link against that
  36774. ** API as long as we don't call it when running Win95/98/ME. A call to
  36775. ** this routine is used to determine if the host is Win95/98/ME or
  36776. ** WinNT/2K/XP so that we will know whether or not we can safely call
  36777. ** the LockFileEx() API.
  36778. */
  36779. #if !SQLITE_WIN32_GETVERSIONEX
  36780. # define osIsNT() (1)
  36781. #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  36782. # define osIsNT() (1)
  36783. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  36784. # define osIsNT() (0)
  36785. #else
  36786. # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
  36787. #endif
  36788. /*
  36789. ** This function determines if the machine is running a version of Windows
  36790. ** based on the NT kernel.
  36791. */
  36792. SQLITE_API int sqlite3_win32_is_nt(void){
  36793. #if SQLITE_OS_WINRT
  36794. /*
  36795. ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
  36796. ** kernel.
  36797. */
  36798. return 1;
  36799. #elif SQLITE_WIN32_GETVERSIONEX
  36800. if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
  36801. #if defined(SQLITE_WIN32_HAS_ANSI)
  36802. OSVERSIONINFOA sInfo;
  36803. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  36804. osGetVersionExA(&sInfo);
  36805. osInterlockedCompareExchange(&sqlite3_os_type,
  36806. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  36807. #elif defined(SQLITE_WIN32_HAS_WIDE)
  36808. OSVERSIONINFOW sInfo;
  36809. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  36810. osGetVersionExW(&sInfo);
  36811. osInterlockedCompareExchange(&sqlite3_os_type,
  36812. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  36813. #endif
  36814. }
  36815. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  36816. #elif SQLITE_TEST
  36817. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  36818. #else
  36819. /*
  36820. ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
  36821. ** deprecated are always assumed to be based on the NT kernel.
  36822. */
  36823. return 1;
  36824. #endif
  36825. }
  36826. #ifdef SQLITE_WIN32_MALLOC
  36827. /*
  36828. ** Allocate nBytes of memory.
  36829. */
  36830. static void *winMemMalloc(int nBytes){
  36831. HANDLE hHeap;
  36832. void *p;
  36833. winMemAssertMagic();
  36834. hHeap = winMemGetHeap();
  36835. assert( hHeap!=0 );
  36836. assert( hHeap!=INVALID_HANDLE_VALUE );
  36837. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  36838. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  36839. #endif
  36840. assert( nBytes>=0 );
  36841. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  36842. if( !p ){
  36843. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  36844. nBytes, osGetLastError(), (void*)hHeap);
  36845. }
  36846. return p;
  36847. }
  36848. /*
  36849. ** Free memory.
  36850. */
  36851. static void winMemFree(void *pPrior){
  36852. HANDLE hHeap;
  36853. winMemAssertMagic();
  36854. hHeap = winMemGetHeap();
  36855. assert( hHeap!=0 );
  36856. assert( hHeap!=INVALID_HANDLE_VALUE );
  36857. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  36858. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  36859. #endif
  36860. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  36861. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  36862. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  36863. pPrior, osGetLastError(), (void*)hHeap);
  36864. }
  36865. }
  36866. /*
  36867. ** Change the size of an existing memory allocation
  36868. */
  36869. static void *winMemRealloc(void *pPrior, int nBytes){
  36870. HANDLE hHeap;
  36871. void *p;
  36872. winMemAssertMagic();
  36873. hHeap = winMemGetHeap();
  36874. assert( hHeap!=0 );
  36875. assert( hHeap!=INVALID_HANDLE_VALUE );
  36876. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  36877. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  36878. #endif
  36879. assert( nBytes>=0 );
  36880. if( !pPrior ){
  36881. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  36882. }else{
  36883. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  36884. }
  36885. if( !p ){
  36886. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  36887. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  36888. (void*)hHeap);
  36889. }
  36890. return p;
  36891. }
  36892. /*
  36893. ** Return the size of an outstanding allocation, in bytes.
  36894. */
  36895. static int winMemSize(void *p){
  36896. HANDLE hHeap;
  36897. SIZE_T n;
  36898. winMemAssertMagic();
  36899. hHeap = winMemGetHeap();
  36900. assert( hHeap!=0 );
  36901. assert( hHeap!=INVALID_HANDLE_VALUE );
  36902. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  36903. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
  36904. #endif
  36905. if( !p ) return 0;
  36906. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  36907. if( n==(SIZE_T)-1 ){
  36908. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  36909. p, osGetLastError(), (void*)hHeap);
  36910. return 0;
  36911. }
  36912. return (int)n;
  36913. }
  36914. /*
  36915. ** Round up a request size to the next valid allocation size.
  36916. */
  36917. static int winMemRoundup(int n){
  36918. return n;
  36919. }
  36920. /*
  36921. ** Initialize this module.
  36922. */
  36923. static int winMemInit(void *pAppData){
  36924. winMemData *pWinMemData = (winMemData *)pAppData;
  36925. if( !pWinMemData ) return SQLITE_ERROR;
  36926. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  36927. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  36928. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  36929. if( !pWinMemData->hHeap ){
  36930. DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
  36931. DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
  36932. if( dwMaximumSize==0 ){
  36933. dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
  36934. }else if( dwInitialSize>dwMaximumSize ){
  36935. dwInitialSize = dwMaximumSize;
  36936. }
  36937. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  36938. dwInitialSize, dwMaximumSize);
  36939. if( !pWinMemData->hHeap ){
  36940. sqlite3_log(SQLITE_NOMEM,
  36941. "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
  36942. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
  36943. dwMaximumSize);
  36944. return SQLITE_NOMEM_BKPT;
  36945. }
  36946. pWinMemData->bOwned = TRUE;
  36947. assert( pWinMemData->bOwned );
  36948. }
  36949. #else
  36950. pWinMemData->hHeap = osGetProcessHeap();
  36951. if( !pWinMemData->hHeap ){
  36952. sqlite3_log(SQLITE_NOMEM,
  36953. "failed to GetProcessHeap (%lu)", osGetLastError());
  36954. return SQLITE_NOMEM_BKPT;
  36955. }
  36956. pWinMemData->bOwned = FALSE;
  36957. assert( !pWinMemData->bOwned );
  36958. #endif
  36959. assert( pWinMemData->hHeap!=0 );
  36960. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  36961. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  36962. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  36963. #endif
  36964. return SQLITE_OK;
  36965. }
  36966. /*
  36967. ** Deinitialize this module.
  36968. */
  36969. static void winMemShutdown(void *pAppData){
  36970. winMemData *pWinMemData = (winMemData *)pAppData;
  36971. if( !pWinMemData ) return;
  36972. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  36973. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  36974. if( pWinMemData->hHeap ){
  36975. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  36976. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  36977. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  36978. #endif
  36979. if( pWinMemData->bOwned ){
  36980. if( !osHeapDestroy(pWinMemData->hHeap) ){
  36981. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  36982. osGetLastError(), (void*)pWinMemData->hHeap);
  36983. }
  36984. pWinMemData->bOwned = FALSE;
  36985. }
  36986. pWinMemData->hHeap = NULL;
  36987. }
  36988. }
  36989. /*
  36990. ** Populate the low-level memory allocation function pointers in
  36991. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  36992. ** arguments specify the block of memory to manage.
  36993. **
  36994. ** This routine is only called by sqlite3_config(), and therefore
  36995. ** is not required to be threadsafe (it is not).
  36996. */
  36997. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  36998. static const sqlite3_mem_methods winMemMethods = {
  36999. winMemMalloc,
  37000. winMemFree,
  37001. winMemRealloc,
  37002. winMemSize,
  37003. winMemRoundup,
  37004. winMemInit,
  37005. winMemShutdown,
  37006. &win_mem_data
  37007. };
  37008. return &winMemMethods;
  37009. }
  37010. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  37011. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  37012. }
  37013. #endif /* SQLITE_WIN32_MALLOC */
  37014. /*
  37015. ** Convert a UTF-8 string to Microsoft Unicode.
  37016. **
  37017. ** Space to hold the returned string is obtained from sqlite3_malloc().
  37018. */
  37019. static LPWSTR winUtf8ToUnicode(const char *zText){
  37020. int nChar;
  37021. LPWSTR zWideText;
  37022. nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
  37023. if( nChar==0 ){
  37024. return 0;
  37025. }
  37026. zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
  37027. if( zWideText==0 ){
  37028. return 0;
  37029. }
  37030. nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
  37031. nChar);
  37032. if( nChar==0 ){
  37033. sqlite3_free(zWideText);
  37034. zWideText = 0;
  37035. }
  37036. return zWideText;
  37037. }
  37038. /*
  37039. ** Convert a Microsoft Unicode string to UTF-8.
  37040. **
  37041. ** Space to hold the returned string is obtained from sqlite3_malloc().
  37042. */
  37043. static char *winUnicodeToUtf8(LPCWSTR zWideText){
  37044. int nByte;
  37045. char *zText;
  37046. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
  37047. if( nByte == 0 ){
  37048. return 0;
  37049. }
  37050. zText = sqlite3MallocZero( nByte );
  37051. if( zText==0 ){
  37052. return 0;
  37053. }
  37054. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
  37055. 0, 0);
  37056. if( nByte == 0 ){
  37057. sqlite3_free(zText);
  37058. zText = 0;
  37059. }
  37060. return zText;
  37061. }
  37062. /*
  37063. ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
  37064. ** code page.
  37065. **
  37066. ** Space to hold the returned string is obtained from sqlite3_malloc().
  37067. */
  37068. static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
  37069. int nByte;
  37070. LPWSTR zMbcsText;
  37071. int codepage = useAnsi ? CP_ACP : CP_OEMCP;
  37072. nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
  37073. 0)*sizeof(WCHAR);
  37074. if( nByte==0 ){
  37075. return 0;
  37076. }
  37077. zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
  37078. if( zMbcsText==0 ){
  37079. return 0;
  37080. }
  37081. nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
  37082. nByte);
  37083. if( nByte==0 ){
  37084. sqlite3_free(zMbcsText);
  37085. zMbcsText = 0;
  37086. }
  37087. return zMbcsText;
  37088. }
  37089. /*
  37090. ** Convert a Microsoft Unicode string to a multi-byte character string,
  37091. ** using the ANSI or OEM code page.
  37092. **
  37093. ** Space to hold the returned string is obtained from sqlite3_malloc().
  37094. */
  37095. static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
  37096. int nByte;
  37097. char *zText;
  37098. int codepage = useAnsi ? CP_ACP : CP_OEMCP;
  37099. nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
  37100. if( nByte == 0 ){
  37101. return 0;
  37102. }
  37103. zText = sqlite3MallocZero( nByte );
  37104. if( zText==0 ){
  37105. return 0;
  37106. }
  37107. nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
  37108. nByte, 0, 0);
  37109. if( nByte == 0 ){
  37110. sqlite3_free(zText);
  37111. zText = 0;
  37112. }
  37113. return zText;
  37114. }
  37115. /*
  37116. ** Convert a multi-byte character string to UTF-8.
  37117. **
  37118. ** Space to hold the returned string is obtained from sqlite3_malloc().
  37119. */
  37120. static char *winMbcsToUtf8(const char *zText, int useAnsi){
  37121. char *zTextUtf8;
  37122. LPWSTR zTmpWide;
  37123. zTmpWide = winMbcsToUnicode(zText, useAnsi);
  37124. if( zTmpWide==0 ){
  37125. return 0;
  37126. }
  37127. zTextUtf8 = winUnicodeToUtf8(zTmpWide);
  37128. sqlite3_free(zTmpWide);
  37129. return zTextUtf8;
  37130. }
  37131. /*
  37132. ** Convert a UTF-8 string to a multi-byte character string.
  37133. **
  37134. ** Space to hold the returned string is obtained from sqlite3_malloc().
  37135. */
  37136. static char *winUtf8ToMbcs(const char *zText, int useAnsi){
  37137. char *zTextMbcs;
  37138. LPWSTR zTmpWide;
  37139. zTmpWide = winUtf8ToUnicode(zText);
  37140. if( zTmpWide==0 ){
  37141. return 0;
  37142. }
  37143. zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
  37144. sqlite3_free(zTmpWide);
  37145. return zTextMbcs;
  37146. }
  37147. /*
  37148. ** This is a public wrapper for the winUtf8ToUnicode() function.
  37149. */
  37150. SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
  37151. #ifdef SQLITE_ENABLE_API_ARMOR
  37152. if( !zText ){
  37153. (void)SQLITE_MISUSE_BKPT;
  37154. return 0;
  37155. }
  37156. #endif
  37157. #ifndef SQLITE_OMIT_AUTOINIT
  37158. if( sqlite3_initialize() ) return 0;
  37159. #endif
  37160. return winUtf8ToUnicode(zText);
  37161. }
  37162. /*
  37163. ** This is a public wrapper for the winUnicodeToUtf8() function.
  37164. */
  37165. SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
  37166. #ifdef SQLITE_ENABLE_API_ARMOR
  37167. if( !zWideText ){
  37168. (void)SQLITE_MISUSE_BKPT;
  37169. return 0;
  37170. }
  37171. #endif
  37172. #ifndef SQLITE_OMIT_AUTOINIT
  37173. if( sqlite3_initialize() ) return 0;
  37174. #endif
  37175. return winUnicodeToUtf8(zWideText);
  37176. }
  37177. /*
  37178. ** This is a public wrapper for the winMbcsToUtf8() function.
  37179. */
  37180. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
  37181. #ifdef SQLITE_ENABLE_API_ARMOR
  37182. if( !zText ){
  37183. (void)SQLITE_MISUSE_BKPT;
  37184. return 0;
  37185. }
  37186. #endif
  37187. #ifndef SQLITE_OMIT_AUTOINIT
  37188. if( sqlite3_initialize() ) return 0;
  37189. #endif
  37190. return winMbcsToUtf8(zText, osAreFileApisANSI());
  37191. }
  37192. /*
  37193. ** This is a public wrapper for the winMbcsToUtf8() function.
  37194. */
  37195. SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
  37196. #ifdef SQLITE_ENABLE_API_ARMOR
  37197. if( !zText ){
  37198. (void)SQLITE_MISUSE_BKPT;
  37199. return 0;
  37200. }
  37201. #endif
  37202. #ifndef SQLITE_OMIT_AUTOINIT
  37203. if( sqlite3_initialize() ) return 0;
  37204. #endif
  37205. return winMbcsToUtf8(zText, useAnsi);
  37206. }
  37207. /*
  37208. ** This is a public wrapper for the winUtf8ToMbcs() function.
  37209. */
  37210. SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
  37211. #ifdef SQLITE_ENABLE_API_ARMOR
  37212. if( !zText ){
  37213. (void)SQLITE_MISUSE_BKPT;
  37214. return 0;
  37215. }
  37216. #endif
  37217. #ifndef SQLITE_OMIT_AUTOINIT
  37218. if( sqlite3_initialize() ) return 0;
  37219. #endif
  37220. return winUtf8ToMbcs(zText, osAreFileApisANSI());
  37221. }
  37222. /*
  37223. ** This is a public wrapper for the winUtf8ToMbcs() function.
  37224. */
  37225. SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
  37226. #ifdef SQLITE_ENABLE_API_ARMOR
  37227. if( !zText ){
  37228. (void)SQLITE_MISUSE_BKPT;
  37229. return 0;
  37230. }
  37231. #endif
  37232. #ifndef SQLITE_OMIT_AUTOINIT
  37233. if( sqlite3_initialize() ) return 0;
  37234. #endif
  37235. return winUtf8ToMbcs(zText, useAnsi);
  37236. }
  37237. /*
  37238. ** This function sets the data directory or the temporary directory based on
  37239. ** the provided arguments. The type argument must be 1 in order to set the
  37240. ** data directory or 2 in order to set the temporary directory. The zValue
  37241. ** argument is the name of the directory to use. The return value will be
  37242. ** SQLITE_OK if successful.
  37243. */
  37244. SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
  37245. char **ppDirectory = 0;
  37246. #ifndef SQLITE_OMIT_AUTOINIT
  37247. int rc = sqlite3_initialize();
  37248. if( rc ) return rc;
  37249. #endif
  37250. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  37251. ppDirectory = &sqlite3_data_directory;
  37252. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  37253. ppDirectory = &sqlite3_temp_directory;
  37254. }
  37255. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  37256. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  37257. );
  37258. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  37259. if( ppDirectory ){
  37260. char *zValueUtf8 = 0;
  37261. if( zValue && zValue[0] ){
  37262. zValueUtf8 = winUnicodeToUtf8(zValue);
  37263. if ( zValueUtf8==0 ){
  37264. return SQLITE_NOMEM_BKPT;
  37265. }
  37266. }
  37267. sqlite3_free(*ppDirectory);
  37268. *ppDirectory = zValueUtf8;
  37269. return SQLITE_OK;
  37270. }
  37271. return SQLITE_ERROR;
  37272. }
  37273. /*
  37274. ** The return value of winGetLastErrorMsg
  37275. ** is zero if the error message fits in the buffer, or non-zero
  37276. ** otherwise (if the message was truncated).
  37277. */
  37278. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  37279. /* FormatMessage returns 0 on failure. Otherwise it
  37280. ** returns the number of TCHARs written to the output
  37281. ** buffer, excluding the terminating null char.
  37282. */
  37283. DWORD dwLen = 0;
  37284. char *zOut = 0;
  37285. if( osIsNT() ){
  37286. #if SQLITE_OS_WINRT
  37287. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  37288. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  37289. FORMAT_MESSAGE_IGNORE_INSERTS,
  37290. NULL,
  37291. lastErrno,
  37292. 0,
  37293. zTempWide,
  37294. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  37295. 0);
  37296. #else
  37297. LPWSTR zTempWide = NULL;
  37298. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  37299. FORMAT_MESSAGE_FROM_SYSTEM |
  37300. FORMAT_MESSAGE_IGNORE_INSERTS,
  37301. NULL,
  37302. lastErrno,
  37303. 0,
  37304. (LPWSTR) &zTempWide,
  37305. 0,
  37306. 0);
  37307. #endif
  37308. if( dwLen > 0 ){
  37309. /* allocate a buffer and convert to UTF8 */
  37310. sqlite3BeginBenignMalloc();
  37311. zOut = winUnicodeToUtf8(zTempWide);
  37312. sqlite3EndBenignMalloc();
  37313. #if !SQLITE_OS_WINRT
  37314. /* free the system buffer allocated by FormatMessage */
  37315. osLocalFree(zTempWide);
  37316. #endif
  37317. }
  37318. }
  37319. #ifdef SQLITE_WIN32_HAS_ANSI
  37320. else{
  37321. char *zTemp = NULL;
  37322. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  37323. FORMAT_MESSAGE_FROM_SYSTEM |
  37324. FORMAT_MESSAGE_IGNORE_INSERTS,
  37325. NULL,
  37326. lastErrno,
  37327. 0,
  37328. (LPSTR) &zTemp,
  37329. 0,
  37330. 0);
  37331. if( dwLen > 0 ){
  37332. /* allocate a buffer and convert to UTF8 */
  37333. sqlite3BeginBenignMalloc();
  37334. zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
  37335. sqlite3EndBenignMalloc();
  37336. /* free the system buffer allocated by FormatMessage */
  37337. osLocalFree(zTemp);
  37338. }
  37339. }
  37340. #endif
  37341. if( 0 == dwLen ){
  37342. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  37343. }else{
  37344. /* copy a maximum of nBuf chars to output buffer */
  37345. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  37346. /* free the UTF8 buffer */
  37347. sqlite3_free(zOut);
  37348. }
  37349. return 0;
  37350. }
  37351. /*
  37352. **
  37353. ** This function - winLogErrorAtLine() - is only ever called via the macro
  37354. ** winLogError().
  37355. **
  37356. ** This routine is invoked after an error occurs in an OS function.
  37357. ** It logs a message using sqlite3_log() containing the current value of
  37358. ** error code and, if possible, the human-readable equivalent from
  37359. ** FormatMessage.
  37360. **
  37361. ** The first argument passed to the macro should be the error code that
  37362. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  37363. ** The two subsequent arguments should be the name of the OS function that
  37364. ** failed and the associated file-system path, if any.
  37365. */
  37366. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  37367. static int winLogErrorAtLine(
  37368. int errcode, /* SQLite error code */
  37369. DWORD lastErrno, /* Win32 last error */
  37370. const char *zFunc, /* Name of OS function that failed */
  37371. const char *zPath, /* File path associated with error */
  37372. int iLine /* Source line number where error occurred */
  37373. ){
  37374. char zMsg[500]; /* Human readable error text */
  37375. int i; /* Loop counter */
  37376. zMsg[0] = 0;
  37377. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  37378. assert( errcode!=SQLITE_OK );
  37379. if( zPath==0 ) zPath = "";
  37380. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  37381. zMsg[i] = 0;
  37382. sqlite3_log(errcode,
  37383. "os_win.c:%d: (%lu) %s(%s) - %s",
  37384. iLine, lastErrno, zFunc, zPath, zMsg
  37385. );
  37386. return errcode;
  37387. }
  37388. /*
  37389. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  37390. ** will be retried following a locking error - probably caused by
  37391. ** antivirus software. Also the initial delay before the first retry.
  37392. ** The delay increases linearly with each retry.
  37393. */
  37394. #ifndef SQLITE_WIN32_IOERR_RETRY
  37395. # define SQLITE_WIN32_IOERR_RETRY 10
  37396. #endif
  37397. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  37398. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  37399. #endif
  37400. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  37401. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  37402. /*
  37403. ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
  37404. ** error code obtained via GetLastError() is eligible to be retried. It
  37405. ** must accept the error code DWORD as its only argument and should return
  37406. ** non-zero if the error code is transient in nature and the operation
  37407. ** responsible for generating the original error might succeed upon being
  37408. ** retried. The argument to this macro should be a variable.
  37409. **
  37410. ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
  37411. ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
  37412. ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
  37413. ** may be used to include additional error codes in the set that should
  37414. ** result in the failing I/O operation being retried by the caller. If
  37415. ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
  37416. ** identical to those of the "winIoerrCanRetry1" macro.
  37417. */
  37418. #if !defined(winIoerrCanRetry1)
  37419. #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
  37420. ((a)==ERROR_SHARING_VIOLATION) || \
  37421. ((a)==ERROR_LOCK_VIOLATION) || \
  37422. ((a)==ERROR_DEV_NOT_EXIST) || \
  37423. ((a)==ERROR_NETNAME_DELETED) || \
  37424. ((a)==ERROR_SEM_TIMEOUT) || \
  37425. ((a)==ERROR_NETWORK_UNREACHABLE))
  37426. #endif
  37427. /*
  37428. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  37429. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  37430. ** to give up with an error.
  37431. */
  37432. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  37433. DWORD e = osGetLastError();
  37434. if( *pnRetry>=winIoerrRetry ){
  37435. if( pError ){
  37436. *pError = e;
  37437. }
  37438. return 0;
  37439. }
  37440. if( winIoerrCanRetry1(e) ){
  37441. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  37442. ++*pnRetry;
  37443. return 1;
  37444. }
  37445. #if defined(winIoerrCanRetry2)
  37446. else if( winIoerrCanRetry2(e) ){
  37447. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  37448. ++*pnRetry;
  37449. return 1;
  37450. }
  37451. #endif
  37452. if( pError ){
  37453. *pError = e;
  37454. }
  37455. return 0;
  37456. }
  37457. /*
  37458. ** Log a I/O error retry episode.
  37459. */
  37460. static void winLogIoerr(int nRetry, int lineno){
  37461. if( nRetry ){
  37462. sqlite3_log(SQLITE_NOTICE,
  37463. "delayed %dms for lock/sharing conflict at line %d",
  37464. winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
  37465. );
  37466. }
  37467. }
  37468. /*
  37469. ** This #if does not rely on the SQLITE_OS_WINCE define because the
  37470. ** corresponding section in "date.c" cannot use it.
  37471. */
  37472. #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
  37473. (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
  37474. /*
  37475. ** The MSVC CRT on Windows CE may not have a localtime() function.
  37476. ** So define a substitute.
  37477. */
  37478. /* # include <time.h> */
  37479. struct tm *__cdecl localtime(const time_t *t)
  37480. {
  37481. static struct tm y;
  37482. FILETIME uTm, lTm;
  37483. SYSTEMTIME pTm;
  37484. sqlite3_int64 t64;
  37485. t64 = *t;
  37486. t64 = (t64 + 11644473600)*10000000;
  37487. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  37488. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  37489. osFileTimeToLocalFileTime(&uTm,&lTm);
  37490. osFileTimeToSystemTime(&lTm,&pTm);
  37491. y.tm_year = pTm.wYear - 1900;
  37492. y.tm_mon = pTm.wMonth - 1;
  37493. y.tm_wday = pTm.wDayOfWeek;
  37494. y.tm_mday = pTm.wDay;
  37495. y.tm_hour = pTm.wHour;
  37496. y.tm_min = pTm.wMinute;
  37497. y.tm_sec = pTm.wSecond;
  37498. return &y;
  37499. }
  37500. #endif
  37501. #if SQLITE_OS_WINCE
  37502. /*************************************************************************
  37503. ** This section contains code for WinCE only.
  37504. */
  37505. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  37506. /*
  37507. ** Acquire a lock on the handle h
  37508. */
  37509. static void winceMutexAcquire(HANDLE h){
  37510. DWORD dwErr;
  37511. do {
  37512. dwErr = osWaitForSingleObject(h, INFINITE);
  37513. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  37514. }
  37515. /*
  37516. ** Release a lock acquired by winceMutexAcquire()
  37517. */
  37518. #define winceMutexRelease(h) ReleaseMutex(h)
  37519. /*
  37520. ** Create the mutex and shared memory used for locking in the file
  37521. ** descriptor pFile
  37522. */
  37523. static int winceCreateLock(const char *zFilename, winFile *pFile){
  37524. LPWSTR zTok;
  37525. LPWSTR zName;
  37526. DWORD lastErrno;
  37527. BOOL bLogged = FALSE;
  37528. BOOL bInit = TRUE;
  37529. zName = winUtf8ToUnicode(zFilename);
  37530. if( zName==0 ){
  37531. /* out of memory */
  37532. return SQLITE_IOERR_NOMEM_BKPT;
  37533. }
  37534. /* Initialize the local lockdata */
  37535. memset(&pFile->local, 0, sizeof(pFile->local));
  37536. /* Replace the backslashes from the filename and lowercase it
  37537. ** to derive a mutex name. */
  37538. zTok = osCharLowerW(zName);
  37539. for (;*zTok;zTok++){
  37540. if (*zTok == '\\') *zTok = '_';
  37541. }
  37542. /* Create/open the named mutex */
  37543. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  37544. if (!pFile->hMutex){
  37545. pFile->lastErrno = osGetLastError();
  37546. sqlite3_free(zName);
  37547. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  37548. "winceCreateLock1", zFilename);
  37549. }
  37550. /* Acquire the mutex before continuing */
  37551. winceMutexAcquire(pFile->hMutex);
  37552. /* Since the names of named mutexes, semaphores, file mappings etc are
  37553. ** case-sensitive, take advantage of that by uppercasing the mutex name
  37554. ** and using that as the shared filemapping name.
  37555. */
  37556. osCharUpperW(zName);
  37557. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  37558. PAGE_READWRITE, 0, sizeof(winceLock),
  37559. zName);
  37560. /* Set a flag that indicates we're the first to create the memory so it
  37561. ** must be zero-initialized */
  37562. lastErrno = osGetLastError();
  37563. if (lastErrno == ERROR_ALREADY_EXISTS){
  37564. bInit = FALSE;
  37565. }
  37566. sqlite3_free(zName);
  37567. /* If we succeeded in making the shared memory handle, map it. */
  37568. if( pFile->hShared ){
  37569. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  37570. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  37571. /* If mapping failed, close the shared memory handle and erase it */
  37572. if( !pFile->shared ){
  37573. pFile->lastErrno = osGetLastError();
  37574. winLogError(SQLITE_IOERR, pFile->lastErrno,
  37575. "winceCreateLock2", zFilename);
  37576. bLogged = TRUE;
  37577. osCloseHandle(pFile->hShared);
  37578. pFile->hShared = NULL;
  37579. }
  37580. }
  37581. /* If shared memory could not be created, then close the mutex and fail */
  37582. if( pFile->hShared==NULL ){
  37583. if( !bLogged ){
  37584. pFile->lastErrno = lastErrno;
  37585. winLogError(SQLITE_IOERR, pFile->lastErrno,
  37586. "winceCreateLock3", zFilename);
  37587. bLogged = TRUE;
  37588. }
  37589. winceMutexRelease(pFile->hMutex);
  37590. osCloseHandle(pFile->hMutex);
  37591. pFile->hMutex = NULL;
  37592. return SQLITE_IOERR;
  37593. }
  37594. /* Initialize the shared memory if we're supposed to */
  37595. if( bInit ){
  37596. memset(pFile->shared, 0, sizeof(winceLock));
  37597. }
  37598. winceMutexRelease(pFile->hMutex);
  37599. return SQLITE_OK;
  37600. }
  37601. /*
  37602. ** Destroy the part of winFile that deals with wince locks
  37603. */
  37604. static void winceDestroyLock(winFile *pFile){
  37605. if (pFile->hMutex){
  37606. /* Acquire the mutex */
  37607. winceMutexAcquire(pFile->hMutex);
  37608. /* The following blocks should probably assert in debug mode, but they
  37609. are to cleanup in case any locks remained open */
  37610. if (pFile->local.nReaders){
  37611. pFile->shared->nReaders --;
  37612. }
  37613. if (pFile->local.bReserved){
  37614. pFile->shared->bReserved = FALSE;
  37615. }
  37616. if (pFile->local.bPending){
  37617. pFile->shared->bPending = FALSE;
  37618. }
  37619. if (pFile->local.bExclusive){
  37620. pFile->shared->bExclusive = FALSE;
  37621. }
  37622. /* De-reference and close our copy of the shared memory handle */
  37623. osUnmapViewOfFile(pFile->shared);
  37624. osCloseHandle(pFile->hShared);
  37625. /* Done with the mutex */
  37626. winceMutexRelease(pFile->hMutex);
  37627. osCloseHandle(pFile->hMutex);
  37628. pFile->hMutex = NULL;
  37629. }
  37630. }
  37631. /*
  37632. ** An implementation of the LockFile() API of Windows for CE
  37633. */
  37634. static BOOL winceLockFile(
  37635. LPHANDLE phFile,
  37636. DWORD dwFileOffsetLow,
  37637. DWORD dwFileOffsetHigh,
  37638. DWORD nNumberOfBytesToLockLow,
  37639. DWORD nNumberOfBytesToLockHigh
  37640. ){
  37641. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  37642. BOOL bReturn = FALSE;
  37643. UNUSED_PARAMETER(dwFileOffsetHigh);
  37644. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  37645. if (!pFile->hMutex) return TRUE;
  37646. winceMutexAcquire(pFile->hMutex);
  37647. /* Wanting an exclusive lock? */
  37648. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  37649. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  37650. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  37651. pFile->shared->bExclusive = TRUE;
  37652. pFile->local.bExclusive = TRUE;
  37653. bReturn = TRUE;
  37654. }
  37655. }
  37656. /* Want a read-only lock? */
  37657. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  37658. nNumberOfBytesToLockLow == 1){
  37659. if (pFile->shared->bExclusive == 0){
  37660. pFile->local.nReaders ++;
  37661. if (pFile->local.nReaders == 1){
  37662. pFile->shared->nReaders ++;
  37663. }
  37664. bReturn = TRUE;
  37665. }
  37666. }
  37667. /* Want a pending lock? */
  37668. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  37669. && nNumberOfBytesToLockLow == 1){
  37670. /* If no pending lock has been acquired, then acquire it */
  37671. if (pFile->shared->bPending == 0) {
  37672. pFile->shared->bPending = TRUE;
  37673. pFile->local.bPending = TRUE;
  37674. bReturn = TRUE;
  37675. }
  37676. }
  37677. /* Want a reserved lock? */
  37678. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  37679. && nNumberOfBytesToLockLow == 1){
  37680. if (pFile->shared->bReserved == 0) {
  37681. pFile->shared->bReserved = TRUE;
  37682. pFile->local.bReserved = TRUE;
  37683. bReturn = TRUE;
  37684. }
  37685. }
  37686. winceMutexRelease(pFile->hMutex);
  37687. return bReturn;
  37688. }
  37689. /*
  37690. ** An implementation of the UnlockFile API of Windows for CE
  37691. */
  37692. static BOOL winceUnlockFile(
  37693. LPHANDLE phFile,
  37694. DWORD dwFileOffsetLow,
  37695. DWORD dwFileOffsetHigh,
  37696. DWORD nNumberOfBytesToUnlockLow,
  37697. DWORD nNumberOfBytesToUnlockHigh
  37698. ){
  37699. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  37700. BOOL bReturn = FALSE;
  37701. UNUSED_PARAMETER(dwFileOffsetHigh);
  37702. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  37703. if (!pFile->hMutex) return TRUE;
  37704. winceMutexAcquire(pFile->hMutex);
  37705. /* Releasing a reader lock or an exclusive lock */
  37706. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  37707. /* Did we have an exclusive lock? */
  37708. if (pFile->local.bExclusive){
  37709. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  37710. pFile->local.bExclusive = FALSE;
  37711. pFile->shared->bExclusive = FALSE;
  37712. bReturn = TRUE;
  37713. }
  37714. /* Did we just have a reader lock? */
  37715. else if (pFile->local.nReaders){
  37716. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  37717. || nNumberOfBytesToUnlockLow == 1);
  37718. pFile->local.nReaders --;
  37719. if (pFile->local.nReaders == 0)
  37720. {
  37721. pFile->shared->nReaders --;
  37722. }
  37723. bReturn = TRUE;
  37724. }
  37725. }
  37726. /* Releasing a pending lock */
  37727. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  37728. && nNumberOfBytesToUnlockLow == 1){
  37729. if (pFile->local.bPending){
  37730. pFile->local.bPending = FALSE;
  37731. pFile->shared->bPending = FALSE;
  37732. bReturn = TRUE;
  37733. }
  37734. }
  37735. /* Releasing a reserved lock */
  37736. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  37737. && nNumberOfBytesToUnlockLow == 1){
  37738. if (pFile->local.bReserved) {
  37739. pFile->local.bReserved = FALSE;
  37740. pFile->shared->bReserved = FALSE;
  37741. bReturn = TRUE;
  37742. }
  37743. }
  37744. winceMutexRelease(pFile->hMutex);
  37745. return bReturn;
  37746. }
  37747. /*
  37748. ** End of the special code for wince
  37749. *****************************************************************************/
  37750. #endif /* SQLITE_OS_WINCE */
  37751. /*
  37752. ** Lock a file region.
  37753. */
  37754. static BOOL winLockFile(
  37755. LPHANDLE phFile,
  37756. DWORD flags,
  37757. DWORD offsetLow,
  37758. DWORD offsetHigh,
  37759. DWORD numBytesLow,
  37760. DWORD numBytesHigh
  37761. ){
  37762. #if SQLITE_OS_WINCE
  37763. /*
  37764. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  37765. ** API LockFile.
  37766. */
  37767. return winceLockFile(phFile, offsetLow, offsetHigh,
  37768. numBytesLow, numBytesHigh);
  37769. #else
  37770. if( osIsNT() ){
  37771. OVERLAPPED ovlp;
  37772. memset(&ovlp, 0, sizeof(OVERLAPPED));
  37773. ovlp.Offset = offsetLow;
  37774. ovlp.OffsetHigh = offsetHigh;
  37775. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  37776. }else{
  37777. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  37778. numBytesHigh);
  37779. }
  37780. #endif
  37781. }
  37782. /*
  37783. ** Unlock a file region.
  37784. */
  37785. static BOOL winUnlockFile(
  37786. LPHANDLE phFile,
  37787. DWORD offsetLow,
  37788. DWORD offsetHigh,
  37789. DWORD numBytesLow,
  37790. DWORD numBytesHigh
  37791. ){
  37792. #if SQLITE_OS_WINCE
  37793. /*
  37794. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  37795. ** API UnlockFile.
  37796. */
  37797. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  37798. numBytesLow, numBytesHigh);
  37799. #else
  37800. if( osIsNT() ){
  37801. OVERLAPPED ovlp;
  37802. memset(&ovlp, 0, sizeof(OVERLAPPED));
  37803. ovlp.Offset = offsetLow;
  37804. ovlp.OffsetHigh = offsetHigh;
  37805. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  37806. }else{
  37807. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  37808. numBytesHigh);
  37809. }
  37810. #endif
  37811. }
  37812. /*****************************************************************************
  37813. ** The next group of routines implement the I/O methods specified
  37814. ** by the sqlite3_io_methods object.
  37815. ******************************************************************************/
  37816. /*
  37817. ** Some Microsoft compilers lack this definition.
  37818. */
  37819. #ifndef INVALID_SET_FILE_POINTER
  37820. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  37821. #endif
  37822. /*
  37823. ** Move the current position of the file handle passed as the first
  37824. ** argument to offset iOffset within the file. If successful, return 0.
  37825. ** Otherwise, set pFile->lastErrno and return non-zero.
  37826. */
  37827. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  37828. #if !SQLITE_OS_WINRT
  37829. LONG upperBits; /* Most sig. 32 bits of new offset */
  37830. LONG lowerBits; /* Least sig. 32 bits of new offset */
  37831. DWORD dwRet; /* Value returned by SetFilePointer() */
  37832. DWORD lastErrno; /* Value returned by GetLastError() */
  37833. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  37834. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  37835. lowerBits = (LONG)(iOffset & 0xffffffff);
  37836. /* API oddity: If successful, SetFilePointer() returns a dword
  37837. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  37838. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  37839. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  37840. ** whether an error has actually occurred, it is also necessary to call
  37841. ** GetLastError().
  37842. */
  37843. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  37844. if( (dwRet==INVALID_SET_FILE_POINTER
  37845. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  37846. pFile->lastErrno = lastErrno;
  37847. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  37848. "winSeekFile", pFile->zPath);
  37849. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  37850. return 1;
  37851. }
  37852. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  37853. return 0;
  37854. #else
  37855. /*
  37856. ** Same as above, except that this implementation works for WinRT.
  37857. */
  37858. LARGE_INTEGER x; /* The new offset */
  37859. BOOL bRet; /* Value returned by SetFilePointerEx() */
  37860. x.QuadPart = iOffset;
  37861. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  37862. if(!bRet){
  37863. pFile->lastErrno = osGetLastError();
  37864. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  37865. "winSeekFile", pFile->zPath);
  37866. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  37867. return 1;
  37868. }
  37869. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  37870. return 0;
  37871. #endif
  37872. }
  37873. #if SQLITE_MAX_MMAP_SIZE>0
  37874. /* Forward references to VFS helper methods used for memory mapped files */
  37875. static int winMapfile(winFile*, sqlite3_int64);
  37876. static int winUnmapfile(winFile*);
  37877. #endif
  37878. /*
  37879. ** Close a file.
  37880. **
  37881. ** It is reported that an attempt to close a handle might sometimes
  37882. ** fail. This is a very unreasonable result, but Windows is notorious
  37883. ** for being unreasonable so I do not doubt that it might happen. If
  37884. ** the close fails, we pause for 100 milliseconds and try again. As
  37885. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  37886. ** giving up and returning an error.
  37887. */
  37888. #define MX_CLOSE_ATTEMPT 3
  37889. static int winClose(sqlite3_file *id){
  37890. int rc, cnt = 0;
  37891. winFile *pFile = (winFile*)id;
  37892. assert( id!=0 );
  37893. #ifndef SQLITE_OMIT_WAL
  37894. assert( pFile->pShm==0 );
  37895. #endif
  37896. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  37897. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
  37898. osGetCurrentProcessId(), pFile, pFile->h));
  37899. #if SQLITE_MAX_MMAP_SIZE>0
  37900. winUnmapfile(pFile);
  37901. #endif
  37902. do{
  37903. rc = osCloseHandle(pFile->h);
  37904. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  37905. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  37906. #if SQLITE_OS_WINCE
  37907. #define WINCE_DELETION_ATTEMPTS 3
  37908. {
  37909. winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
  37910. if( pAppData==NULL || !pAppData->bNoLock ){
  37911. winceDestroyLock(pFile);
  37912. }
  37913. }
  37914. if( pFile->zDeleteOnClose ){
  37915. int cnt = 0;
  37916. while(
  37917. osDeleteFileW(pFile->zDeleteOnClose)==0
  37918. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  37919. && cnt++ < WINCE_DELETION_ATTEMPTS
  37920. ){
  37921. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  37922. }
  37923. sqlite3_free(pFile->zDeleteOnClose);
  37924. }
  37925. #endif
  37926. if( rc ){
  37927. pFile->h = NULL;
  37928. }
  37929. OpenCounter(-1);
  37930. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  37931. osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
  37932. return rc ? SQLITE_OK
  37933. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  37934. "winClose", pFile->zPath);
  37935. }
  37936. /*
  37937. ** Read data from a file into a buffer. Return SQLITE_OK if all
  37938. ** bytes were read successfully and SQLITE_IOERR if anything goes
  37939. ** wrong.
  37940. */
  37941. static int winRead(
  37942. sqlite3_file *id, /* File to read from */
  37943. void *pBuf, /* Write content into this buffer */
  37944. int amt, /* Number of bytes to read */
  37945. sqlite3_int64 offset /* Begin reading at this offset */
  37946. ){
  37947. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  37948. OVERLAPPED overlapped; /* The offset for ReadFile. */
  37949. #endif
  37950. winFile *pFile = (winFile*)id; /* file handle */
  37951. DWORD nRead; /* Number of bytes actually read from file */
  37952. int nRetry = 0; /* Number of retrys */
  37953. assert( id!=0 );
  37954. assert( amt>0 );
  37955. assert( offset>=0 );
  37956. SimulateIOError(return SQLITE_IOERR_READ);
  37957. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  37958. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  37959. pFile->h, pBuf, amt, offset, pFile->locktype));
  37960. #if SQLITE_MAX_MMAP_SIZE>0
  37961. /* Deal with as much of this read request as possible by transfering
  37962. ** data from the memory mapping using memcpy(). */
  37963. if( offset<pFile->mmapSize ){
  37964. if( offset+amt <= pFile->mmapSize ){
  37965. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  37966. OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  37967. osGetCurrentProcessId(), pFile, pFile->h));
  37968. return SQLITE_OK;
  37969. }else{
  37970. int nCopy = (int)(pFile->mmapSize - offset);
  37971. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  37972. pBuf = &((u8 *)pBuf)[nCopy];
  37973. amt -= nCopy;
  37974. offset += nCopy;
  37975. }
  37976. }
  37977. #endif
  37978. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  37979. if( winSeekFile(pFile, offset) ){
  37980. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  37981. osGetCurrentProcessId(), pFile, pFile->h));
  37982. return SQLITE_FULL;
  37983. }
  37984. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  37985. #else
  37986. memset(&overlapped, 0, sizeof(OVERLAPPED));
  37987. overlapped.Offset = (LONG)(offset & 0xffffffff);
  37988. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  37989. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  37990. osGetLastError()!=ERROR_HANDLE_EOF ){
  37991. #endif
  37992. DWORD lastErrno;
  37993. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  37994. pFile->lastErrno = lastErrno;
  37995. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
  37996. osGetCurrentProcessId(), pFile, pFile->h));
  37997. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  37998. "winRead", pFile->zPath);
  37999. }
  38000. winLogIoerr(nRetry, __LINE__);
  38001. if( nRead<(DWORD)amt ){
  38002. /* Unread parts of the buffer must be zero-filled */
  38003. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  38004. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
  38005. osGetCurrentProcessId(), pFile, pFile->h));
  38006. return SQLITE_IOERR_SHORT_READ;
  38007. }
  38008. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  38009. osGetCurrentProcessId(), pFile, pFile->h));
  38010. return SQLITE_OK;
  38011. }
  38012. /*
  38013. ** Write data from a buffer into a file. Return SQLITE_OK on success
  38014. ** or some other error code on failure.
  38015. */
  38016. static int winWrite(
  38017. sqlite3_file *id, /* File to write into */
  38018. const void *pBuf, /* The bytes to be written */
  38019. int amt, /* Number of bytes to write */
  38020. sqlite3_int64 offset /* Offset into the file to begin writing at */
  38021. ){
  38022. int rc = 0; /* True if error has occurred, else false */
  38023. winFile *pFile = (winFile*)id; /* File handle */
  38024. int nRetry = 0; /* Number of retries */
  38025. assert( amt>0 );
  38026. assert( pFile );
  38027. SimulateIOError(return SQLITE_IOERR_WRITE);
  38028. SimulateDiskfullError(return SQLITE_FULL);
  38029. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  38030. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  38031. pFile->h, pBuf, amt, offset, pFile->locktype));
  38032. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  38033. /* Deal with as much of this write request as possible by transfering
  38034. ** data from the memory mapping using memcpy(). */
  38035. if( offset<pFile->mmapSize ){
  38036. if( offset+amt <= pFile->mmapSize ){
  38037. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  38038. OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  38039. osGetCurrentProcessId(), pFile, pFile->h));
  38040. return SQLITE_OK;
  38041. }else{
  38042. int nCopy = (int)(pFile->mmapSize - offset);
  38043. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  38044. pBuf = &((u8 *)pBuf)[nCopy];
  38045. amt -= nCopy;
  38046. offset += nCopy;
  38047. }
  38048. }
  38049. #endif
  38050. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  38051. rc = winSeekFile(pFile, offset);
  38052. if( rc==0 ){
  38053. #else
  38054. {
  38055. #endif
  38056. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  38057. OVERLAPPED overlapped; /* The offset for WriteFile. */
  38058. #endif
  38059. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  38060. int nRem = amt; /* Number of bytes yet to be written */
  38061. DWORD nWrite; /* Bytes written by each WriteFile() call */
  38062. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  38063. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  38064. memset(&overlapped, 0, sizeof(OVERLAPPED));
  38065. overlapped.Offset = (LONG)(offset & 0xffffffff);
  38066. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  38067. #endif
  38068. while( nRem>0 ){
  38069. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  38070. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  38071. #else
  38072. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  38073. #endif
  38074. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  38075. break;
  38076. }
  38077. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  38078. if( nWrite==0 || nWrite>(DWORD)nRem ){
  38079. lastErrno = osGetLastError();
  38080. break;
  38081. }
  38082. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  38083. offset += nWrite;
  38084. overlapped.Offset = (LONG)(offset & 0xffffffff);
  38085. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  38086. #endif
  38087. aRem += nWrite;
  38088. nRem -= nWrite;
  38089. }
  38090. if( nRem>0 ){
  38091. pFile->lastErrno = lastErrno;
  38092. rc = 1;
  38093. }
  38094. }
  38095. if( rc ){
  38096. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  38097. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  38098. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  38099. osGetCurrentProcessId(), pFile, pFile->h));
  38100. return winLogError(SQLITE_FULL, pFile->lastErrno,
  38101. "winWrite1", pFile->zPath);
  38102. }
  38103. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
  38104. osGetCurrentProcessId(), pFile, pFile->h));
  38105. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  38106. "winWrite2", pFile->zPath);
  38107. }else{
  38108. winLogIoerr(nRetry, __LINE__);
  38109. }
  38110. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  38111. osGetCurrentProcessId(), pFile, pFile->h));
  38112. return SQLITE_OK;
  38113. }
  38114. /*
  38115. ** Truncate an open file to a specified size
  38116. */
  38117. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  38118. winFile *pFile = (winFile*)id; /* File handle object */
  38119. int rc = SQLITE_OK; /* Return code for this function */
  38120. DWORD lastErrno;
  38121. assert( pFile );
  38122. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  38123. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
  38124. osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
  38125. /* If the user has configured a chunk-size for this file, truncate the
  38126. ** file so that it consists of an integer number of chunks (i.e. the
  38127. ** actual file size after the operation may be larger than the requested
  38128. ** size).
  38129. */
  38130. if( pFile->szChunk>0 ){
  38131. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  38132. }
  38133. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  38134. if( winSeekFile(pFile, nByte) ){
  38135. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  38136. "winTruncate1", pFile->zPath);
  38137. }else if( 0==osSetEndOfFile(pFile->h) &&
  38138. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  38139. pFile->lastErrno = lastErrno;
  38140. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  38141. "winTruncate2", pFile->zPath);
  38142. }
  38143. #if SQLITE_MAX_MMAP_SIZE>0
  38144. /* If the file was truncated to a size smaller than the currently
  38145. ** mapped region, reduce the effective mapping size as well. SQLite will
  38146. ** use read() and write() to access data beyond this point from now on.
  38147. */
  38148. if( pFile->pMapRegion && nByte<pFile->mmapSize ){
  38149. pFile->mmapSize = nByte;
  38150. }
  38151. #endif
  38152. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  38153. osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
  38154. return rc;
  38155. }
  38156. #ifdef SQLITE_TEST
  38157. /*
  38158. ** Count the number of fullsyncs and normal syncs. This is used to test
  38159. ** that syncs and fullsyncs are occuring at the right times.
  38160. */
  38161. SQLITE_API int sqlite3_sync_count = 0;
  38162. SQLITE_API int sqlite3_fullsync_count = 0;
  38163. #endif
  38164. /*
  38165. ** Make sure all writes to a particular file are committed to disk.
  38166. */
  38167. static int winSync(sqlite3_file *id, int flags){
  38168. #ifndef SQLITE_NO_SYNC
  38169. /*
  38170. ** Used only when SQLITE_NO_SYNC is not defined.
  38171. */
  38172. BOOL rc;
  38173. #endif
  38174. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  38175. defined(SQLITE_HAVE_OS_TRACE)
  38176. /*
  38177. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  38178. ** OSTRACE() macros.
  38179. */
  38180. winFile *pFile = (winFile*)id;
  38181. #else
  38182. UNUSED_PARAMETER(id);
  38183. #endif
  38184. assert( pFile );
  38185. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  38186. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  38187. || (flags&0x0F)==SQLITE_SYNC_FULL
  38188. );
  38189. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  38190. ** line is to test that doing so does not cause any problems.
  38191. */
  38192. SimulateDiskfullError( return SQLITE_FULL );
  38193. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
  38194. osGetCurrentProcessId(), pFile, pFile->h, flags,
  38195. pFile->locktype));
  38196. #ifndef SQLITE_TEST
  38197. UNUSED_PARAMETER(flags);
  38198. #else
  38199. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  38200. sqlite3_fullsync_count++;
  38201. }
  38202. sqlite3_sync_count++;
  38203. #endif
  38204. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  38205. ** no-op
  38206. */
  38207. #ifdef SQLITE_NO_SYNC
  38208. OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  38209. osGetCurrentProcessId(), pFile, pFile->h));
  38210. return SQLITE_OK;
  38211. #else
  38212. #if SQLITE_MAX_MMAP_SIZE>0
  38213. if( pFile->pMapRegion ){
  38214. if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
  38215. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  38216. "rc=SQLITE_OK\n", osGetCurrentProcessId(),
  38217. pFile, pFile->pMapRegion));
  38218. }else{
  38219. pFile->lastErrno = osGetLastError();
  38220. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  38221. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
  38222. pFile, pFile->pMapRegion));
  38223. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  38224. "winSync1", pFile->zPath);
  38225. }
  38226. }
  38227. #endif
  38228. rc = osFlushFileBuffers(pFile->h);
  38229. SimulateIOError( rc=FALSE );
  38230. if( rc ){
  38231. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  38232. osGetCurrentProcessId(), pFile, pFile->h));
  38233. return SQLITE_OK;
  38234. }else{
  38235. pFile->lastErrno = osGetLastError();
  38236. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
  38237. osGetCurrentProcessId(), pFile, pFile->h));
  38238. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  38239. "winSync2", pFile->zPath);
  38240. }
  38241. #endif
  38242. }
  38243. /*
  38244. ** Determine the current size of a file in bytes
  38245. */
  38246. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  38247. winFile *pFile = (winFile*)id;
  38248. int rc = SQLITE_OK;
  38249. assert( id!=0 );
  38250. assert( pSize!=0 );
  38251. SimulateIOError(return SQLITE_IOERR_FSTAT);
  38252. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  38253. #if SQLITE_OS_WINRT
  38254. {
  38255. FILE_STANDARD_INFO info;
  38256. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  38257. &info, sizeof(info)) ){
  38258. *pSize = info.EndOfFile.QuadPart;
  38259. }else{
  38260. pFile->lastErrno = osGetLastError();
  38261. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  38262. "winFileSize", pFile->zPath);
  38263. }
  38264. }
  38265. #else
  38266. {
  38267. DWORD upperBits;
  38268. DWORD lowerBits;
  38269. DWORD lastErrno;
  38270. lowerBits = osGetFileSize(pFile->h, &upperBits);
  38271. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  38272. if( (lowerBits == INVALID_FILE_SIZE)
  38273. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  38274. pFile->lastErrno = lastErrno;
  38275. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  38276. "winFileSize", pFile->zPath);
  38277. }
  38278. }
  38279. #endif
  38280. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  38281. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  38282. return rc;
  38283. }
  38284. /*
  38285. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  38286. */
  38287. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  38288. # define LOCKFILE_FAIL_IMMEDIATELY 1
  38289. #endif
  38290. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  38291. # define LOCKFILE_EXCLUSIVE_LOCK 2
  38292. #endif
  38293. /*
  38294. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  38295. ** When the LockFile function was used, it was always expected to fail
  38296. ** immediately if the lock could not be obtained. Also, it always expected to
  38297. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  38298. ** and reflect those expectations; therefore, they should not be changed.
  38299. */
  38300. #ifndef SQLITE_LOCKFILE_FLAGS
  38301. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  38302. LOCKFILE_EXCLUSIVE_LOCK)
  38303. #endif
  38304. /*
  38305. ** Currently, SQLite never calls the LockFileEx function without wanting the
  38306. ** call to fail immediately if the lock cannot be obtained.
  38307. */
  38308. #ifndef SQLITE_LOCKFILEEX_FLAGS
  38309. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  38310. #endif
  38311. /*
  38312. ** Acquire a reader lock.
  38313. ** Different API routines are called depending on whether or not this
  38314. ** is Win9x or WinNT.
  38315. */
  38316. static int winGetReadLock(winFile *pFile){
  38317. int res;
  38318. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  38319. if( osIsNT() ){
  38320. #if SQLITE_OS_WINCE
  38321. /*
  38322. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  38323. ** API LockFileEx.
  38324. */
  38325. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  38326. #else
  38327. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  38328. SHARED_SIZE, 0);
  38329. #endif
  38330. }
  38331. #ifdef SQLITE_WIN32_HAS_ANSI
  38332. else{
  38333. int lk;
  38334. sqlite3_randomness(sizeof(lk), &lk);
  38335. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  38336. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  38337. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  38338. }
  38339. #endif
  38340. if( res == 0 ){
  38341. pFile->lastErrno = osGetLastError();
  38342. /* No need to log a failure to lock */
  38343. }
  38344. OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
  38345. return res;
  38346. }
  38347. /*
  38348. ** Undo a readlock
  38349. */
  38350. static int winUnlockReadLock(winFile *pFile){
  38351. int res;
  38352. DWORD lastErrno;
  38353. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  38354. if( osIsNT() ){
  38355. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  38356. }
  38357. #ifdef SQLITE_WIN32_HAS_ANSI
  38358. else{
  38359. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  38360. }
  38361. #endif
  38362. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  38363. pFile->lastErrno = lastErrno;
  38364. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  38365. "winUnlockReadLock", pFile->zPath);
  38366. }
  38367. OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
  38368. return res;
  38369. }
  38370. /*
  38371. ** Lock the file with the lock specified by parameter locktype - one
  38372. ** of the following:
  38373. **
  38374. ** (1) SHARED_LOCK
  38375. ** (2) RESERVED_LOCK
  38376. ** (3) PENDING_LOCK
  38377. ** (4) EXCLUSIVE_LOCK
  38378. **
  38379. ** Sometimes when requesting one lock state, additional lock states
  38380. ** are inserted in between. The locking might fail on one of the later
  38381. ** transitions leaving the lock state different from what it started but
  38382. ** still short of its goal. The following chart shows the allowed
  38383. ** transitions and the inserted intermediate states:
  38384. **
  38385. ** UNLOCKED -> SHARED
  38386. ** SHARED -> RESERVED
  38387. ** SHARED -> (PENDING) -> EXCLUSIVE
  38388. ** RESERVED -> (PENDING) -> EXCLUSIVE
  38389. ** PENDING -> EXCLUSIVE
  38390. **
  38391. ** This routine will only increase a lock. The winUnlock() routine
  38392. ** erases all locks at once and returns us immediately to locking level 0.
  38393. ** It is not possible to lower the locking level one step at a time. You
  38394. ** must go straight to locking level 0.
  38395. */
  38396. static int winLock(sqlite3_file *id, int locktype){
  38397. int rc = SQLITE_OK; /* Return code from subroutines */
  38398. int res = 1; /* Result of a Windows lock call */
  38399. int newLocktype; /* Set pFile->locktype to this value before exiting */
  38400. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  38401. winFile *pFile = (winFile*)id;
  38402. DWORD lastErrno = NO_ERROR;
  38403. assert( id!=0 );
  38404. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  38405. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  38406. /* If there is already a lock of this type or more restrictive on the
  38407. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  38408. ** sqlite3OsEnterMutex() hasn't been called yet.
  38409. */
  38410. if( pFile->locktype>=locktype ){
  38411. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  38412. return SQLITE_OK;
  38413. }
  38414. /* Do not allow any kind of write-lock on a read-only database
  38415. */
  38416. if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
  38417. return SQLITE_IOERR_LOCK;
  38418. }
  38419. /* Make sure the locking sequence is correct
  38420. */
  38421. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  38422. assert( locktype!=PENDING_LOCK );
  38423. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  38424. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  38425. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  38426. ** the PENDING_LOCK byte is temporary.
  38427. */
  38428. newLocktype = pFile->locktype;
  38429. if( pFile->locktype==NO_LOCK
  38430. || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
  38431. ){
  38432. int cnt = 3;
  38433. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  38434. PENDING_BYTE, 0, 1, 0))==0 ){
  38435. /* Try 3 times to get the pending lock. This is needed to work
  38436. ** around problems caused by indexing and/or anti-virus software on
  38437. ** Windows systems.
  38438. ** If you are using this code as a model for alternative VFSes, do not
  38439. ** copy this retry logic. It is a hack intended for Windows only.
  38440. */
  38441. lastErrno = osGetLastError();
  38442. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
  38443. pFile->h, cnt, res));
  38444. if( lastErrno==ERROR_INVALID_HANDLE ){
  38445. pFile->lastErrno = lastErrno;
  38446. rc = SQLITE_IOERR_LOCK;
  38447. OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
  38448. pFile->h, cnt, sqlite3ErrName(rc)));
  38449. return rc;
  38450. }
  38451. if( cnt ) sqlite3_win32_sleep(1);
  38452. }
  38453. gotPendingLock = res;
  38454. if( !res ){
  38455. lastErrno = osGetLastError();
  38456. }
  38457. }
  38458. /* Acquire a shared lock
  38459. */
  38460. if( locktype==SHARED_LOCK && res ){
  38461. assert( pFile->locktype==NO_LOCK );
  38462. res = winGetReadLock(pFile);
  38463. if( res ){
  38464. newLocktype = SHARED_LOCK;
  38465. }else{
  38466. lastErrno = osGetLastError();
  38467. }
  38468. }
  38469. /* Acquire a RESERVED lock
  38470. */
  38471. if( locktype==RESERVED_LOCK && res ){
  38472. assert( pFile->locktype==SHARED_LOCK );
  38473. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  38474. if( res ){
  38475. newLocktype = RESERVED_LOCK;
  38476. }else{
  38477. lastErrno = osGetLastError();
  38478. }
  38479. }
  38480. /* Acquire a PENDING lock
  38481. */
  38482. if( locktype==EXCLUSIVE_LOCK && res ){
  38483. newLocktype = PENDING_LOCK;
  38484. gotPendingLock = 0;
  38485. }
  38486. /* Acquire an EXCLUSIVE lock
  38487. */
  38488. if( locktype==EXCLUSIVE_LOCK && res ){
  38489. assert( pFile->locktype>=SHARED_LOCK );
  38490. res = winUnlockReadLock(pFile);
  38491. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  38492. SHARED_SIZE, 0);
  38493. if( res ){
  38494. newLocktype = EXCLUSIVE_LOCK;
  38495. }else{
  38496. lastErrno = osGetLastError();
  38497. winGetReadLock(pFile);
  38498. }
  38499. }
  38500. /* If we are holding a PENDING lock that ought to be released, then
  38501. ** release it now.
  38502. */
  38503. if( gotPendingLock && locktype==SHARED_LOCK ){
  38504. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  38505. }
  38506. /* Update the state of the lock has held in the file descriptor then
  38507. ** return the appropriate result code.
  38508. */
  38509. if( res ){
  38510. rc = SQLITE_OK;
  38511. }else{
  38512. pFile->lastErrno = lastErrno;
  38513. rc = SQLITE_BUSY;
  38514. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  38515. pFile->h, locktype, newLocktype));
  38516. }
  38517. pFile->locktype = (u8)newLocktype;
  38518. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  38519. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  38520. return rc;
  38521. }
  38522. /*
  38523. ** This routine checks if there is a RESERVED lock held on the specified
  38524. ** file by this or any other process. If such a lock is held, return
  38525. ** non-zero, otherwise zero.
  38526. */
  38527. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  38528. int res;
  38529. winFile *pFile = (winFile*)id;
  38530. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  38531. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  38532. assert( id!=0 );
  38533. if( pFile->locktype>=RESERVED_LOCK ){
  38534. res = 1;
  38535. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
  38536. }else{
  38537. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
  38538. if( res ){
  38539. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  38540. }
  38541. res = !res;
  38542. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
  38543. }
  38544. *pResOut = res;
  38545. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  38546. pFile->h, pResOut, *pResOut));
  38547. return SQLITE_OK;
  38548. }
  38549. /*
  38550. ** Lower the locking level on file descriptor id to locktype. locktype
  38551. ** must be either NO_LOCK or SHARED_LOCK.
  38552. **
  38553. ** If the locking level of the file descriptor is already at or below
  38554. ** the requested locking level, this routine is a no-op.
  38555. **
  38556. ** It is not possible for this routine to fail if the second argument
  38557. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  38558. ** might return SQLITE_IOERR;
  38559. */
  38560. static int winUnlock(sqlite3_file *id, int locktype){
  38561. int type;
  38562. winFile *pFile = (winFile*)id;
  38563. int rc = SQLITE_OK;
  38564. assert( pFile!=0 );
  38565. assert( locktype<=SHARED_LOCK );
  38566. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  38567. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  38568. type = pFile->locktype;
  38569. if( type>=EXCLUSIVE_LOCK ){
  38570. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  38571. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  38572. /* This should never happen. We should always be able to
  38573. ** reacquire the read lock */
  38574. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  38575. "winUnlock", pFile->zPath);
  38576. }
  38577. }
  38578. if( type>=RESERVED_LOCK ){
  38579. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  38580. }
  38581. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  38582. winUnlockReadLock(pFile);
  38583. }
  38584. if( type>=PENDING_LOCK ){
  38585. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  38586. }
  38587. pFile->locktype = (u8)locktype;
  38588. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  38589. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  38590. return rc;
  38591. }
  38592. /******************************************************************************
  38593. ****************************** No-op Locking **********************************
  38594. **
  38595. ** Of the various locking implementations available, this is by far the
  38596. ** simplest: locking is ignored. No attempt is made to lock the database
  38597. ** file for reading or writing.
  38598. **
  38599. ** This locking mode is appropriate for use on read-only databases
  38600. ** (ex: databases that are burned into CD-ROM, for example.) It can
  38601. ** also be used if the application employs some external mechanism to
  38602. ** prevent simultaneous access of the same database by two or more
  38603. ** database connections. But there is a serious risk of database
  38604. ** corruption if this locking mode is used in situations where multiple
  38605. ** database connections are accessing the same database file at the same
  38606. ** time and one or more of those connections are writing.
  38607. */
  38608. static int winNolockLock(sqlite3_file *id, int locktype){
  38609. UNUSED_PARAMETER(id);
  38610. UNUSED_PARAMETER(locktype);
  38611. return SQLITE_OK;
  38612. }
  38613. static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
  38614. UNUSED_PARAMETER(id);
  38615. UNUSED_PARAMETER(pResOut);
  38616. return SQLITE_OK;
  38617. }
  38618. static int winNolockUnlock(sqlite3_file *id, int locktype){
  38619. UNUSED_PARAMETER(id);
  38620. UNUSED_PARAMETER(locktype);
  38621. return SQLITE_OK;
  38622. }
  38623. /******************* End of the no-op lock implementation *********************
  38624. ******************************************************************************/
  38625. /*
  38626. ** If *pArg is initially negative then this is a query. Set *pArg to
  38627. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  38628. **
  38629. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  38630. */
  38631. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  38632. if( *pArg<0 ){
  38633. *pArg = (pFile->ctrlFlags & mask)!=0;
  38634. }else if( (*pArg)==0 ){
  38635. pFile->ctrlFlags &= ~mask;
  38636. }else{
  38637. pFile->ctrlFlags |= mask;
  38638. }
  38639. }
  38640. /* Forward references to VFS helper methods used for temporary files */
  38641. static int winGetTempname(sqlite3_vfs *, char **);
  38642. static int winIsDir(const void *);
  38643. static BOOL winIsDriveLetterAndColon(const char *);
  38644. /*
  38645. ** Control and query of the open file handle.
  38646. */
  38647. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  38648. winFile *pFile = (winFile*)id;
  38649. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  38650. switch( op ){
  38651. case SQLITE_FCNTL_LOCKSTATE: {
  38652. *(int*)pArg = pFile->locktype;
  38653. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  38654. return SQLITE_OK;
  38655. }
  38656. case SQLITE_FCNTL_LAST_ERRNO: {
  38657. *(int*)pArg = (int)pFile->lastErrno;
  38658. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  38659. return SQLITE_OK;
  38660. }
  38661. case SQLITE_FCNTL_CHUNK_SIZE: {
  38662. pFile->szChunk = *(int *)pArg;
  38663. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  38664. return SQLITE_OK;
  38665. }
  38666. case SQLITE_FCNTL_SIZE_HINT: {
  38667. if( pFile->szChunk>0 ){
  38668. sqlite3_int64 oldSz;
  38669. int rc = winFileSize(id, &oldSz);
  38670. if( rc==SQLITE_OK ){
  38671. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  38672. if( newSz>oldSz ){
  38673. SimulateIOErrorBenign(1);
  38674. rc = winTruncate(id, newSz);
  38675. SimulateIOErrorBenign(0);
  38676. }
  38677. }
  38678. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  38679. return rc;
  38680. }
  38681. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  38682. return SQLITE_OK;
  38683. }
  38684. case SQLITE_FCNTL_PERSIST_WAL: {
  38685. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  38686. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  38687. return SQLITE_OK;
  38688. }
  38689. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  38690. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  38691. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  38692. return SQLITE_OK;
  38693. }
  38694. case SQLITE_FCNTL_VFSNAME: {
  38695. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  38696. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  38697. return SQLITE_OK;
  38698. }
  38699. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  38700. int *a = (int*)pArg;
  38701. if( a[0]>0 ){
  38702. winIoerrRetry = a[0];
  38703. }else{
  38704. a[0] = winIoerrRetry;
  38705. }
  38706. if( a[1]>0 ){
  38707. winIoerrRetryDelay = a[1];
  38708. }else{
  38709. a[1] = winIoerrRetryDelay;
  38710. }
  38711. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  38712. return SQLITE_OK;
  38713. }
  38714. case SQLITE_FCNTL_WIN32_GET_HANDLE: {
  38715. LPHANDLE phFile = (LPHANDLE)pArg;
  38716. *phFile = pFile->h;
  38717. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  38718. return SQLITE_OK;
  38719. }
  38720. #ifdef SQLITE_TEST
  38721. case SQLITE_FCNTL_WIN32_SET_HANDLE: {
  38722. LPHANDLE phFile = (LPHANDLE)pArg;
  38723. HANDLE hOldFile = pFile->h;
  38724. pFile->h = *phFile;
  38725. *phFile = hOldFile;
  38726. OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
  38727. hOldFile, pFile->h));
  38728. return SQLITE_OK;
  38729. }
  38730. #endif
  38731. case SQLITE_FCNTL_TEMPFILENAME: {
  38732. char *zTFile = 0;
  38733. int rc = winGetTempname(pFile->pVfs, &zTFile);
  38734. if( rc==SQLITE_OK ){
  38735. *(char**)pArg = zTFile;
  38736. }
  38737. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  38738. return rc;
  38739. }
  38740. #if SQLITE_MAX_MMAP_SIZE>0
  38741. case SQLITE_FCNTL_MMAP_SIZE: {
  38742. i64 newLimit = *(i64*)pArg;
  38743. int rc = SQLITE_OK;
  38744. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  38745. newLimit = sqlite3GlobalConfig.mxMmap;
  38746. }
  38747. *(i64*)pArg = pFile->mmapSizeMax;
  38748. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  38749. pFile->mmapSizeMax = newLimit;
  38750. if( pFile->mmapSize>0 ){
  38751. winUnmapfile(pFile);
  38752. rc = winMapfile(pFile, -1);
  38753. }
  38754. }
  38755. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  38756. return rc;
  38757. }
  38758. #endif
  38759. }
  38760. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  38761. return SQLITE_NOTFOUND;
  38762. }
  38763. /*
  38764. ** Return the sector size in bytes of the underlying block device for
  38765. ** the specified file. This is almost always 512 bytes, but may be
  38766. ** larger for some devices.
  38767. **
  38768. ** SQLite code assumes this function cannot fail. It also assumes that
  38769. ** if two files are created in the same file-system directory (i.e.
  38770. ** a database and its journal file) that the sector size will be the
  38771. ** same for both.
  38772. */
  38773. static int winSectorSize(sqlite3_file *id){
  38774. (void)id;
  38775. return SQLITE_DEFAULT_SECTOR_SIZE;
  38776. }
  38777. /*
  38778. ** Return a vector of device characteristics.
  38779. */
  38780. static int winDeviceCharacteristics(sqlite3_file *id){
  38781. winFile *p = (winFile*)id;
  38782. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  38783. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  38784. }
  38785. /*
  38786. ** Windows will only let you create file view mappings
  38787. ** on allocation size granularity boundaries.
  38788. ** During sqlite3_os_init() we do a GetSystemInfo()
  38789. ** to get the granularity size.
  38790. */
  38791. static SYSTEM_INFO winSysInfo;
  38792. #ifndef SQLITE_OMIT_WAL
  38793. /*
  38794. ** Helper functions to obtain and relinquish the global mutex. The
  38795. ** global mutex is used to protect the winLockInfo objects used by
  38796. ** this file, all of which may be shared by multiple threads.
  38797. **
  38798. ** Function winShmMutexHeld() is used to assert() that the global mutex
  38799. ** is held when required. This function is only used as part of assert()
  38800. ** statements. e.g.
  38801. **
  38802. ** winShmEnterMutex()
  38803. ** assert( winShmMutexHeld() );
  38804. ** winShmLeaveMutex()
  38805. */
  38806. static void winShmEnterMutex(void){
  38807. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  38808. }
  38809. static void winShmLeaveMutex(void){
  38810. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  38811. }
  38812. #ifndef NDEBUG
  38813. static int winShmMutexHeld(void) {
  38814. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  38815. }
  38816. #endif
  38817. /*
  38818. ** Object used to represent a single file opened and mmapped to provide
  38819. ** shared memory. When multiple threads all reference the same
  38820. ** log-summary, each thread has its own winFile object, but they all
  38821. ** point to a single instance of this object. In other words, each
  38822. ** log-summary is opened only once per process.
  38823. **
  38824. ** winShmMutexHeld() must be true when creating or destroying
  38825. ** this object or while reading or writing the following fields:
  38826. **
  38827. ** nRef
  38828. ** pNext
  38829. **
  38830. ** The following fields are read-only after the object is created:
  38831. **
  38832. ** fid
  38833. ** zFilename
  38834. **
  38835. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  38836. ** winShmMutexHeld() is true when reading or writing any other field
  38837. ** in this structure.
  38838. **
  38839. */
  38840. struct winShmNode {
  38841. sqlite3_mutex *mutex; /* Mutex to access this object */
  38842. char *zFilename; /* Name of the file */
  38843. winFile hFile; /* File handle from winOpen */
  38844. int szRegion; /* Size of shared-memory regions */
  38845. int nRegion; /* Size of array apRegion */
  38846. struct ShmRegion {
  38847. HANDLE hMap; /* File handle from CreateFileMapping */
  38848. void *pMap;
  38849. } *aRegion;
  38850. DWORD lastErrno; /* The Windows errno from the last I/O error */
  38851. int nRef; /* Number of winShm objects pointing to this */
  38852. winShm *pFirst; /* All winShm objects pointing to this */
  38853. winShmNode *pNext; /* Next in list of all winShmNode objects */
  38854. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  38855. u8 nextShmId; /* Next available winShm.id value */
  38856. #endif
  38857. };
  38858. /*
  38859. ** A global array of all winShmNode objects.
  38860. **
  38861. ** The winShmMutexHeld() must be true while reading or writing this list.
  38862. */
  38863. static winShmNode *winShmNodeList = 0;
  38864. /*
  38865. ** Structure used internally by this VFS to record the state of an
  38866. ** open shared memory connection.
  38867. **
  38868. ** The following fields are initialized when this object is created and
  38869. ** are read-only thereafter:
  38870. **
  38871. ** winShm.pShmNode
  38872. ** winShm.id
  38873. **
  38874. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  38875. ** while accessing any read/write fields.
  38876. */
  38877. struct winShm {
  38878. winShmNode *pShmNode; /* The underlying winShmNode object */
  38879. winShm *pNext; /* Next winShm with the same winShmNode */
  38880. u8 hasMutex; /* True if holding the winShmNode mutex */
  38881. u16 sharedMask; /* Mask of shared locks held */
  38882. u16 exclMask; /* Mask of exclusive locks held */
  38883. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  38884. u8 id; /* Id of this connection with its winShmNode */
  38885. #endif
  38886. };
  38887. /*
  38888. ** Constants used for locking
  38889. */
  38890. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  38891. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  38892. /*
  38893. ** Apply advisory locks for all n bytes beginning at ofst.
  38894. */
  38895. #define WINSHM_UNLCK 1
  38896. #define WINSHM_RDLCK 2
  38897. #define WINSHM_WRLCK 3
  38898. static int winShmSystemLock(
  38899. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  38900. int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
  38901. int ofst, /* Offset to first byte to be locked/unlocked */
  38902. int nByte /* Number of bytes to lock or unlock */
  38903. ){
  38904. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  38905. /* Access to the winShmNode object is serialized by the caller */
  38906. assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
  38907. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  38908. pFile->hFile.h, lockType, ofst, nByte));
  38909. /* Release/Acquire the system-level lock */
  38910. if( lockType==WINSHM_UNLCK ){
  38911. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  38912. }else{
  38913. /* Initialize the locking parameters */
  38914. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  38915. if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  38916. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  38917. }
  38918. if( rc!= 0 ){
  38919. rc = SQLITE_OK;
  38920. }else{
  38921. pFile->lastErrno = osGetLastError();
  38922. rc = SQLITE_BUSY;
  38923. }
  38924. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  38925. pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
  38926. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  38927. return rc;
  38928. }
  38929. /* Forward references to VFS methods */
  38930. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  38931. static int winDelete(sqlite3_vfs *,const char*,int);
  38932. /*
  38933. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  38934. **
  38935. ** This is not a VFS shared-memory method; it is a utility function called
  38936. ** by VFS shared-memory methods.
  38937. */
  38938. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  38939. winShmNode **pp;
  38940. winShmNode *p;
  38941. assert( winShmMutexHeld() );
  38942. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  38943. osGetCurrentProcessId(), deleteFlag));
  38944. pp = &winShmNodeList;
  38945. while( (p = *pp)!=0 ){
  38946. if( p->nRef==0 ){
  38947. int i;
  38948. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  38949. for(i=0; i<p->nRegion; i++){
  38950. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  38951. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  38952. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  38953. UNUSED_VARIABLE_VALUE(bRc);
  38954. bRc = osCloseHandle(p->aRegion[i].hMap);
  38955. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  38956. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  38957. UNUSED_VARIABLE_VALUE(bRc);
  38958. }
  38959. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  38960. SimulateIOErrorBenign(1);
  38961. winClose((sqlite3_file *)&p->hFile);
  38962. SimulateIOErrorBenign(0);
  38963. }
  38964. if( deleteFlag ){
  38965. SimulateIOErrorBenign(1);
  38966. sqlite3BeginBenignMalloc();
  38967. winDelete(pVfs, p->zFilename, 0);
  38968. sqlite3EndBenignMalloc();
  38969. SimulateIOErrorBenign(0);
  38970. }
  38971. *pp = p->pNext;
  38972. sqlite3_free(p->aRegion);
  38973. sqlite3_free(p);
  38974. }else{
  38975. pp = &p->pNext;
  38976. }
  38977. }
  38978. }
  38979. /*
  38980. ** Open the shared-memory area associated with database file pDbFd.
  38981. **
  38982. ** When opening a new shared-memory file, if no other instances of that
  38983. ** file are currently open, in this process or in other processes, then
  38984. ** the file must be truncated to zero length or have its header cleared.
  38985. */
  38986. static int winOpenSharedMemory(winFile *pDbFd){
  38987. struct winShm *p; /* The connection to be opened */
  38988. struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
  38989. int rc; /* Result code */
  38990. struct winShmNode *pNew; /* Newly allocated winShmNode */
  38991. int nName; /* Size of zName in bytes */
  38992. assert( pDbFd->pShm==0 ); /* Not previously opened */
  38993. /* Allocate space for the new sqlite3_shm object. Also speculatively
  38994. ** allocate space for a new winShmNode and filename.
  38995. */
  38996. p = sqlite3MallocZero( sizeof(*p) );
  38997. if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
  38998. nName = sqlite3Strlen30(pDbFd->zPath);
  38999. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  39000. if( pNew==0 ){
  39001. sqlite3_free(p);
  39002. return SQLITE_IOERR_NOMEM_BKPT;
  39003. }
  39004. pNew->zFilename = (char*)&pNew[1];
  39005. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  39006. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  39007. /* Look to see if there is an existing winShmNode that can be used.
  39008. ** If no matching winShmNode currently exists, create a new one.
  39009. */
  39010. winShmEnterMutex();
  39011. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  39012. /* TBD need to come up with better match here. Perhaps
  39013. ** use FILE_ID_BOTH_DIR_INFO Structure.
  39014. */
  39015. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  39016. }
  39017. if( pShmNode ){
  39018. sqlite3_free(pNew);
  39019. }else{
  39020. pShmNode = pNew;
  39021. pNew = 0;
  39022. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  39023. pShmNode->pNext = winShmNodeList;
  39024. winShmNodeList = pShmNode;
  39025. if( sqlite3GlobalConfig.bCoreMutex ){
  39026. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  39027. if( pShmNode->mutex==0 ){
  39028. rc = SQLITE_IOERR_NOMEM_BKPT;
  39029. goto shm_open_err;
  39030. }
  39031. }
  39032. rc = winOpen(pDbFd->pVfs,
  39033. pShmNode->zFilename, /* Name of the file (UTF-8) */
  39034. (sqlite3_file*)&pShmNode->hFile, /* File handle here */
  39035. SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
  39036. 0);
  39037. if( SQLITE_OK!=rc ){
  39038. goto shm_open_err;
  39039. }
  39040. /* Check to see if another process is holding the dead-man switch.
  39041. ** If not, truncate the file to zero length.
  39042. */
  39043. if( winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  39044. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  39045. if( rc!=SQLITE_OK ){
  39046. rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  39047. "winOpenShm", pDbFd->zPath);
  39048. }
  39049. }
  39050. if( rc==SQLITE_OK ){
  39051. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  39052. rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
  39053. }
  39054. if( rc ) goto shm_open_err;
  39055. }
  39056. /* Make the new connection a child of the winShmNode */
  39057. p->pShmNode = pShmNode;
  39058. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  39059. p->id = pShmNode->nextShmId++;
  39060. #endif
  39061. pShmNode->nRef++;
  39062. pDbFd->pShm = p;
  39063. winShmLeaveMutex();
  39064. /* The reference count on pShmNode has already been incremented under
  39065. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  39066. ** new (struct winShm) object to the pShmNode has been set. All that is
  39067. ** left to do is to link the new object into the linked list starting
  39068. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  39069. ** mutex.
  39070. */
  39071. sqlite3_mutex_enter(pShmNode->mutex);
  39072. p->pNext = pShmNode->pFirst;
  39073. pShmNode->pFirst = p;
  39074. sqlite3_mutex_leave(pShmNode->mutex);
  39075. return SQLITE_OK;
  39076. /* Jump here on any error */
  39077. shm_open_err:
  39078. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  39079. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  39080. sqlite3_free(p);
  39081. sqlite3_free(pNew);
  39082. winShmLeaveMutex();
  39083. return rc;
  39084. }
  39085. /*
  39086. ** Close a connection to shared-memory. Delete the underlying
  39087. ** storage if deleteFlag is true.
  39088. */
  39089. static int winShmUnmap(
  39090. sqlite3_file *fd, /* Database holding shared memory */
  39091. int deleteFlag /* Delete after closing if true */
  39092. ){
  39093. winFile *pDbFd; /* Database holding shared-memory */
  39094. winShm *p; /* The connection to be closed */
  39095. winShmNode *pShmNode; /* The underlying shared-memory file */
  39096. winShm **pp; /* For looping over sibling connections */
  39097. pDbFd = (winFile*)fd;
  39098. p = pDbFd->pShm;
  39099. if( p==0 ) return SQLITE_OK;
  39100. pShmNode = p->pShmNode;
  39101. /* Remove connection p from the set of connections associated
  39102. ** with pShmNode */
  39103. sqlite3_mutex_enter(pShmNode->mutex);
  39104. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  39105. *pp = p->pNext;
  39106. /* Free the connection p */
  39107. sqlite3_free(p);
  39108. pDbFd->pShm = 0;
  39109. sqlite3_mutex_leave(pShmNode->mutex);
  39110. /* If pShmNode->nRef has reached 0, then close the underlying
  39111. ** shared-memory file, too */
  39112. winShmEnterMutex();
  39113. assert( pShmNode->nRef>0 );
  39114. pShmNode->nRef--;
  39115. if( pShmNode->nRef==0 ){
  39116. winShmPurge(pDbFd->pVfs, deleteFlag);
  39117. }
  39118. winShmLeaveMutex();
  39119. return SQLITE_OK;
  39120. }
  39121. /*
  39122. ** Change the lock state for a shared-memory segment.
  39123. */
  39124. static int winShmLock(
  39125. sqlite3_file *fd, /* Database file holding the shared memory */
  39126. int ofst, /* First lock to acquire or release */
  39127. int n, /* Number of locks to acquire or release */
  39128. int flags /* What to do with the lock */
  39129. ){
  39130. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  39131. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  39132. winShm *pX; /* For looping over all siblings */
  39133. winShmNode *pShmNode = p->pShmNode;
  39134. int rc = SQLITE_OK; /* Result code */
  39135. u16 mask; /* Mask of locks to take or release */
  39136. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  39137. assert( n>=1 );
  39138. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  39139. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  39140. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  39141. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  39142. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  39143. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  39144. assert( n>1 || mask==(1<<ofst) );
  39145. sqlite3_mutex_enter(pShmNode->mutex);
  39146. if( flags & SQLITE_SHM_UNLOCK ){
  39147. u16 allMask = 0; /* Mask of locks held by siblings */
  39148. /* See if any siblings hold this same lock */
  39149. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  39150. if( pX==p ) continue;
  39151. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  39152. allMask |= pX->sharedMask;
  39153. }
  39154. /* Unlock the system-level locks */
  39155. if( (mask & allMask)==0 ){
  39156. rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
  39157. }else{
  39158. rc = SQLITE_OK;
  39159. }
  39160. /* Undo the local locks */
  39161. if( rc==SQLITE_OK ){
  39162. p->exclMask &= ~mask;
  39163. p->sharedMask &= ~mask;
  39164. }
  39165. }else if( flags & SQLITE_SHM_SHARED ){
  39166. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  39167. /* Find out which shared locks are already held by sibling connections.
  39168. ** If any sibling already holds an exclusive lock, go ahead and return
  39169. ** SQLITE_BUSY.
  39170. */
  39171. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  39172. if( (pX->exclMask & mask)!=0 ){
  39173. rc = SQLITE_BUSY;
  39174. break;
  39175. }
  39176. allShared |= pX->sharedMask;
  39177. }
  39178. /* Get shared locks at the system level, if necessary */
  39179. if( rc==SQLITE_OK ){
  39180. if( (allShared & mask)==0 ){
  39181. rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
  39182. }else{
  39183. rc = SQLITE_OK;
  39184. }
  39185. }
  39186. /* Get the local shared locks */
  39187. if( rc==SQLITE_OK ){
  39188. p->sharedMask |= mask;
  39189. }
  39190. }else{
  39191. /* Make sure no sibling connections hold locks that will block this
  39192. ** lock. If any do, return SQLITE_BUSY right away.
  39193. */
  39194. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  39195. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  39196. rc = SQLITE_BUSY;
  39197. break;
  39198. }
  39199. }
  39200. /* Get the exclusive locks at the system level. Then if successful
  39201. ** also mark the local connection as being locked.
  39202. */
  39203. if( rc==SQLITE_OK ){
  39204. rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
  39205. if( rc==SQLITE_OK ){
  39206. assert( (p->sharedMask & mask)==0 );
  39207. p->exclMask |= mask;
  39208. }
  39209. }
  39210. }
  39211. sqlite3_mutex_leave(pShmNode->mutex);
  39212. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  39213. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  39214. sqlite3ErrName(rc)));
  39215. return rc;
  39216. }
  39217. /*
  39218. ** Implement a memory barrier or memory fence on shared memory.
  39219. **
  39220. ** All loads and stores begun before the barrier must complete before
  39221. ** any load or store begun after the barrier.
  39222. */
  39223. static void winShmBarrier(
  39224. sqlite3_file *fd /* Database holding the shared memory */
  39225. ){
  39226. UNUSED_PARAMETER(fd);
  39227. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  39228. winShmEnterMutex(); /* Also mutex, for redundancy */
  39229. winShmLeaveMutex();
  39230. }
  39231. /*
  39232. ** This function is called to obtain a pointer to region iRegion of the
  39233. ** shared-memory associated with the database file fd. Shared-memory regions
  39234. ** are numbered starting from zero. Each shared-memory region is szRegion
  39235. ** bytes in size.
  39236. **
  39237. ** If an error occurs, an error code is returned and *pp is set to NULL.
  39238. **
  39239. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  39240. ** region has not been allocated (by any client, including one running in a
  39241. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  39242. ** isWrite is non-zero and the requested shared-memory region has not yet
  39243. ** been allocated, it is allocated by this function.
  39244. **
  39245. ** If the shared-memory region has already been allocated or is allocated by
  39246. ** this call as described above, then it is mapped into this processes
  39247. ** address space (if it is not already), *pp is set to point to the mapped
  39248. ** memory and SQLITE_OK returned.
  39249. */
  39250. static int winShmMap(
  39251. sqlite3_file *fd, /* Handle open on database file */
  39252. int iRegion, /* Region to retrieve */
  39253. int szRegion, /* Size of regions */
  39254. int isWrite, /* True to extend file if necessary */
  39255. void volatile **pp /* OUT: Mapped memory */
  39256. ){
  39257. winFile *pDbFd = (winFile*)fd;
  39258. winShm *pShm = pDbFd->pShm;
  39259. winShmNode *pShmNode;
  39260. int rc = SQLITE_OK;
  39261. if( !pShm ){
  39262. rc = winOpenSharedMemory(pDbFd);
  39263. if( rc!=SQLITE_OK ) return rc;
  39264. pShm = pDbFd->pShm;
  39265. }
  39266. pShmNode = pShm->pShmNode;
  39267. sqlite3_mutex_enter(pShmNode->mutex);
  39268. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  39269. if( pShmNode->nRegion<=iRegion ){
  39270. struct ShmRegion *apNew; /* New aRegion[] array */
  39271. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  39272. sqlite3_int64 sz; /* Current size of wal-index file */
  39273. pShmNode->szRegion = szRegion;
  39274. /* The requested region is not mapped into this processes address space.
  39275. ** Check to see if it has been allocated (i.e. if the wal-index file is
  39276. ** large enough to contain the requested region).
  39277. */
  39278. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  39279. if( rc!=SQLITE_OK ){
  39280. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  39281. "winShmMap1", pDbFd->zPath);
  39282. goto shmpage_out;
  39283. }
  39284. if( sz<nByte ){
  39285. /* The requested memory region does not exist. If isWrite is set to
  39286. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  39287. **
  39288. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  39289. ** the requested memory region.
  39290. */
  39291. if( !isWrite ) goto shmpage_out;
  39292. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  39293. if( rc!=SQLITE_OK ){
  39294. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  39295. "winShmMap2", pDbFd->zPath);
  39296. goto shmpage_out;
  39297. }
  39298. }
  39299. /* Map the requested memory region into this processes address space. */
  39300. apNew = (struct ShmRegion *)sqlite3_realloc64(
  39301. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  39302. );
  39303. if( !apNew ){
  39304. rc = SQLITE_IOERR_NOMEM_BKPT;
  39305. goto shmpage_out;
  39306. }
  39307. pShmNode->aRegion = apNew;
  39308. while( pShmNode->nRegion<=iRegion ){
  39309. HANDLE hMap = NULL; /* file-mapping handle */
  39310. void *pMap = 0; /* Mapped memory region */
  39311. #if SQLITE_OS_WINRT
  39312. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  39313. NULL, PAGE_READWRITE, nByte, NULL
  39314. );
  39315. #elif defined(SQLITE_WIN32_HAS_WIDE)
  39316. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  39317. NULL, PAGE_READWRITE, 0, nByte, NULL
  39318. );
  39319. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  39320. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  39321. NULL, PAGE_READWRITE, 0, nByte, NULL
  39322. );
  39323. #endif
  39324. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  39325. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  39326. hMap ? "ok" : "failed"));
  39327. if( hMap ){
  39328. int iOffset = pShmNode->nRegion*szRegion;
  39329. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  39330. #if SQLITE_OS_WINRT
  39331. pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  39332. iOffset - iOffsetShift, szRegion + iOffsetShift
  39333. );
  39334. #else
  39335. pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  39336. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  39337. );
  39338. #endif
  39339. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  39340. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  39341. szRegion, pMap ? "ok" : "failed"));
  39342. }
  39343. if( !pMap ){
  39344. pShmNode->lastErrno = osGetLastError();
  39345. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  39346. "winShmMap3", pDbFd->zPath);
  39347. if( hMap ) osCloseHandle(hMap);
  39348. goto shmpage_out;
  39349. }
  39350. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  39351. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  39352. pShmNode->nRegion++;
  39353. }
  39354. }
  39355. shmpage_out:
  39356. if( pShmNode->nRegion>iRegion ){
  39357. int iOffset = iRegion*szRegion;
  39358. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  39359. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  39360. *pp = (void *)&p[iOffsetShift];
  39361. }else{
  39362. *pp = 0;
  39363. }
  39364. sqlite3_mutex_leave(pShmNode->mutex);
  39365. return rc;
  39366. }
  39367. #else
  39368. # define winShmMap 0
  39369. # define winShmLock 0
  39370. # define winShmBarrier 0
  39371. # define winShmUnmap 0
  39372. #endif /* #ifndef SQLITE_OMIT_WAL */
  39373. /*
  39374. ** Cleans up the mapped region of the specified file, if any.
  39375. */
  39376. #if SQLITE_MAX_MMAP_SIZE>0
  39377. static int winUnmapfile(winFile *pFile){
  39378. assert( pFile!=0 );
  39379. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  39380. "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
  39381. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  39382. pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
  39383. if( pFile->pMapRegion ){
  39384. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  39385. pFile->lastErrno = osGetLastError();
  39386. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  39387. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  39388. pFile->pMapRegion));
  39389. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  39390. "winUnmapfile1", pFile->zPath);
  39391. }
  39392. pFile->pMapRegion = 0;
  39393. pFile->mmapSize = 0;
  39394. pFile->mmapSizeActual = 0;
  39395. }
  39396. if( pFile->hMap!=NULL ){
  39397. if( !osCloseHandle(pFile->hMap) ){
  39398. pFile->lastErrno = osGetLastError();
  39399. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  39400. osGetCurrentProcessId(), pFile, pFile->hMap));
  39401. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  39402. "winUnmapfile2", pFile->zPath);
  39403. }
  39404. pFile->hMap = NULL;
  39405. }
  39406. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  39407. osGetCurrentProcessId(), pFile));
  39408. return SQLITE_OK;
  39409. }
  39410. /*
  39411. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  39412. ** is already mapped, the existing mapping is replaced by the new). Or, if
  39413. ** there already exists a mapping for this file, and there are still
  39414. ** outstanding xFetch() references to it, this function is a no-op.
  39415. **
  39416. ** If parameter nByte is non-negative, then it is the requested size of
  39417. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  39418. ** requested size is the size of the file on disk. The actual size of the
  39419. ** created mapping is either the requested size or the value configured
  39420. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  39421. **
  39422. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  39423. ** recreated as a result of outstanding references) or an SQLite error
  39424. ** code otherwise.
  39425. */
  39426. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  39427. sqlite3_int64 nMap = nByte;
  39428. int rc;
  39429. assert( nMap>=0 || pFd->nFetchOut==0 );
  39430. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  39431. osGetCurrentProcessId(), pFd, nByte));
  39432. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  39433. if( nMap<0 ){
  39434. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  39435. if( rc ){
  39436. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  39437. osGetCurrentProcessId(), pFd));
  39438. return SQLITE_IOERR_FSTAT;
  39439. }
  39440. }
  39441. if( nMap>pFd->mmapSizeMax ){
  39442. nMap = pFd->mmapSizeMax;
  39443. }
  39444. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  39445. if( nMap==0 && pFd->mmapSize>0 ){
  39446. winUnmapfile(pFd);
  39447. }
  39448. if( nMap!=pFd->mmapSize ){
  39449. void *pNew = 0;
  39450. DWORD protect = PAGE_READONLY;
  39451. DWORD flags = FILE_MAP_READ;
  39452. winUnmapfile(pFd);
  39453. #ifdef SQLITE_MMAP_READWRITE
  39454. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  39455. protect = PAGE_READWRITE;
  39456. flags |= FILE_MAP_WRITE;
  39457. }
  39458. #endif
  39459. #if SQLITE_OS_WINRT
  39460. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  39461. #elif defined(SQLITE_WIN32_HAS_WIDE)
  39462. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  39463. (DWORD)((nMap>>32) & 0xffffffff),
  39464. (DWORD)(nMap & 0xffffffff), NULL);
  39465. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  39466. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  39467. (DWORD)((nMap>>32) & 0xffffffff),
  39468. (DWORD)(nMap & 0xffffffff), NULL);
  39469. #endif
  39470. if( pFd->hMap==NULL ){
  39471. pFd->lastErrno = osGetLastError();
  39472. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  39473. "winMapfile1", pFd->zPath);
  39474. /* Log the error, but continue normal operation using xRead/xWrite */
  39475. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  39476. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  39477. return SQLITE_OK;
  39478. }
  39479. assert( (nMap % winSysInfo.dwPageSize)==0 );
  39480. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  39481. #if SQLITE_OS_WINRT
  39482. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  39483. #else
  39484. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  39485. #endif
  39486. if( pNew==NULL ){
  39487. osCloseHandle(pFd->hMap);
  39488. pFd->hMap = NULL;
  39489. pFd->lastErrno = osGetLastError();
  39490. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  39491. "winMapfile2", pFd->zPath);
  39492. /* Log the error, but continue normal operation using xRead/xWrite */
  39493. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  39494. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  39495. return SQLITE_OK;
  39496. }
  39497. pFd->pMapRegion = pNew;
  39498. pFd->mmapSize = nMap;
  39499. pFd->mmapSizeActual = nMap;
  39500. }
  39501. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  39502. osGetCurrentProcessId(), pFd));
  39503. return SQLITE_OK;
  39504. }
  39505. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  39506. /*
  39507. ** If possible, return a pointer to a mapping of file fd starting at offset
  39508. ** iOff. The mapping must be valid for at least nAmt bytes.
  39509. **
  39510. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  39511. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  39512. ** Finally, if an error does occur, return an SQLite error code. The final
  39513. ** value of *pp is undefined in this case.
  39514. **
  39515. ** If this function does return a pointer, the caller must eventually
  39516. ** release the reference by calling winUnfetch().
  39517. */
  39518. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  39519. #if SQLITE_MAX_MMAP_SIZE>0
  39520. winFile *pFd = (winFile*)fd; /* The underlying database file */
  39521. #endif
  39522. *pp = 0;
  39523. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  39524. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  39525. #if SQLITE_MAX_MMAP_SIZE>0
  39526. if( pFd->mmapSizeMax>0 ){
  39527. if( pFd->pMapRegion==0 ){
  39528. int rc = winMapfile(pFd, -1);
  39529. if( rc!=SQLITE_OK ){
  39530. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  39531. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  39532. return rc;
  39533. }
  39534. }
  39535. if( pFd->mmapSize >= iOff+nAmt ){
  39536. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  39537. pFd->nFetchOut++;
  39538. }
  39539. }
  39540. #endif
  39541. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  39542. osGetCurrentProcessId(), fd, pp, *pp));
  39543. return SQLITE_OK;
  39544. }
  39545. /*
  39546. ** If the third argument is non-NULL, then this function releases a
  39547. ** reference obtained by an earlier call to winFetch(). The second
  39548. ** argument passed to this function must be the same as the corresponding
  39549. ** argument that was passed to the winFetch() invocation.
  39550. **
  39551. ** Or, if the third argument is NULL, then this function is being called
  39552. ** to inform the VFS layer that, according to POSIX, any existing mapping
  39553. ** may now be invalid and should be unmapped.
  39554. */
  39555. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  39556. #if SQLITE_MAX_MMAP_SIZE>0
  39557. winFile *pFd = (winFile*)fd; /* The underlying database file */
  39558. /* If p==0 (unmap the entire file) then there must be no outstanding
  39559. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  39560. ** then there must be at least one outstanding. */
  39561. assert( (p==0)==(pFd->nFetchOut==0) );
  39562. /* If p!=0, it must match the iOff value. */
  39563. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  39564. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  39565. osGetCurrentProcessId(), pFd, iOff, p));
  39566. if( p ){
  39567. pFd->nFetchOut--;
  39568. }else{
  39569. /* FIXME: If Windows truly always prevents truncating or deleting a
  39570. ** file while a mapping is held, then the following winUnmapfile() call
  39571. ** is unnecessary can be omitted - potentially improving
  39572. ** performance. */
  39573. winUnmapfile(pFd);
  39574. }
  39575. assert( pFd->nFetchOut>=0 );
  39576. #endif
  39577. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  39578. osGetCurrentProcessId(), fd));
  39579. return SQLITE_OK;
  39580. }
  39581. /*
  39582. ** Here ends the implementation of all sqlite3_file methods.
  39583. **
  39584. ********************** End sqlite3_file Methods *******************************
  39585. ******************************************************************************/
  39586. /*
  39587. ** This vector defines all the methods that can operate on an
  39588. ** sqlite3_file for win32.
  39589. */
  39590. static const sqlite3_io_methods winIoMethod = {
  39591. 3, /* iVersion */
  39592. winClose, /* xClose */
  39593. winRead, /* xRead */
  39594. winWrite, /* xWrite */
  39595. winTruncate, /* xTruncate */
  39596. winSync, /* xSync */
  39597. winFileSize, /* xFileSize */
  39598. winLock, /* xLock */
  39599. winUnlock, /* xUnlock */
  39600. winCheckReservedLock, /* xCheckReservedLock */
  39601. winFileControl, /* xFileControl */
  39602. winSectorSize, /* xSectorSize */
  39603. winDeviceCharacteristics, /* xDeviceCharacteristics */
  39604. winShmMap, /* xShmMap */
  39605. winShmLock, /* xShmLock */
  39606. winShmBarrier, /* xShmBarrier */
  39607. winShmUnmap, /* xShmUnmap */
  39608. winFetch, /* xFetch */
  39609. winUnfetch /* xUnfetch */
  39610. };
  39611. /*
  39612. ** This vector defines all the methods that can operate on an
  39613. ** sqlite3_file for win32 without performing any locking.
  39614. */
  39615. static const sqlite3_io_methods winIoNolockMethod = {
  39616. 3, /* iVersion */
  39617. winClose, /* xClose */
  39618. winRead, /* xRead */
  39619. winWrite, /* xWrite */
  39620. winTruncate, /* xTruncate */
  39621. winSync, /* xSync */
  39622. winFileSize, /* xFileSize */
  39623. winNolockLock, /* xLock */
  39624. winNolockUnlock, /* xUnlock */
  39625. winNolockCheckReservedLock, /* xCheckReservedLock */
  39626. winFileControl, /* xFileControl */
  39627. winSectorSize, /* xSectorSize */
  39628. winDeviceCharacteristics, /* xDeviceCharacteristics */
  39629. winShmMap, /* xShmMap */
  39630. winShmLock, /* xShmLock */
  39631. winShmBarrier, /* xShmBarrier */
  39632. winShmUnmap, /* xShmUnmap */
  39633. winFetch, /* xFetch */
  39634. winUnfetch /* xUnfetch */
  39635. };
  39636. static winVfsAppData winAppData = {
  39637. &winIoMethod, /* pMethod */
  39638. 0, /* pAppData */
  39639. 0 /* bNoLock */
  39640. };
  39641. static winVfsAppData winNolockAppData = {
  39642. &winIoNolockMethod, /* pMethod */
  39643. 0, /* pAppData */
  39644. 1 /* bNoLock */
  39645. };
  39646. /****************************************************************************
  39647. **************************** sqlite3_vfs methods ****************************
  39648. **
  39649. ** This division contains the implementation of methods on the
  39650. ** sqlite3_vfs object.
  39651. */
  39652. #if defined(__CYGWIN__)
  39653. /*
  39654. ** Convert a filename from whatever the underlying operating system
  39655. ** supports for filenames into UTF-8. Space to hold the result is
  39656. ** obtained from malloc and must be freed by the calling function.
  39657. */
  39658. static char *winConvertToUtf8Filename(const void *zFilename){
  39659. char *zConverted = 0;
  39660. if( osIsNT() ){
  39661. zConverted = winUnicodeToUtf8(zFilename);
  39662. }
  39663. #ifdef SQLITE_WIN32_HAS_ANSI
  39664. else{
  39665. zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
  39666. }
  39667. #endif
  39668. /* caller will handle out of memory */
  39669. return zConverted;
  39670. }
  39671. #endif
  39672. /*
  39673. ** Convert a UTF-8 filename into whatever form the underlying
  39674. ** operating system wants filenames in. Space to hold the result
  39675. ** is obtained from malloc and must be freed by the calling
  39676. ** function.
  39677. */
  39678. static void *winConvertFromUtf8Filename(const char *zFilename){
  39679. void *zConverted = 0;
  39680. if( osIsNT() ){
  39681. zConverted = winUtf8ToUnicode(zFilename);
  39682. }
  39683. #ifdef SQLITE_WIN32_HAS_ANSI
  39684. else{
  39685. zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
  39686. }
  39687. #endif
  39688. /* caller will handle out of memory */
  39689. return zConverted;
  39690. }
  39691. /*
  39692. ** This function returns non-zero if the specified UTF-8 string buffer
  39693. ** ends with a directory separator character or one was successfully
  39694. ** added to it.
  39695. */
  39696. static int winMakeEndInDirSep(int nBuf, char *zBuf){
  39697. if( zBuf ){
  39698. int nLen = sqlite3Strlen30(zBuf);
  39699. if( nLen>0 ){
  39700. if( winIsDirSep(zBuf[nLen-1]) ){
  39701. return 1;
  39702. }else if( nLen+1<nBuf ){
  39703. zBuf[nLen] = winGetDirSep();
  39704. zBuf[nLen+1] = '\0';
  39705. return 1;
  39706. }
  39707. }
  39708. }
  39709. return 0;
  39710. }
  39711. /*
  39712. ** Create a temporary file name and store the resulting pointer into pzBuf.
  39713. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  39714. */
  39715. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  39716. static char zChars[] =
  39717. "abcdefghijklmnopqrstuvwxyz"
  39718. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  39719. "0123456789";
  39720. size_t i, j;
  39721. int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
  39722. int nMax, nBuf, nDir, nLen;
  39723. char *zBuf;
  39724. /* It's odd to simulate an io-error here, but really this is just
  39725. ** using the io-error infrastructure to test that SQLite handles this
  39726. ** function failing.
  39727. */
  39728. SimulateIOError( return SQLITE_IOERR );
  39729. /* Allocate a temporary buffer to store the fully qualified file
  39730. ** name for the temporary file. If this fails, we cannot continue.
  39731. */
  39732. nMax = pVfs->mxPathname; nBuf = nMax + 2;
  39733. zBuf = sqlite3MallocZero( nBuf );
  39734. if( !zBuf ){
  39735. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  39736. return SQLITE_IOERR_NOMEM_BKPT;
  39737. }
  39738. /* Figure out the effective temporary directory. First, check if one
  39739. ** has been explicitly set by the application; otherwise, use the one
  39740. ** configured by the operating system.
  39741. */
  39742. nDir = nMax - (nPre + 15);
  39743. assert( nDir>0 );
  39744. if( sqlite3_temp_directory ){
  39745. int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
  39746. if( nDirLen>0 ){
  39747. if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
  39748. nDirLen++;
  39749. }
  39750. if( nDirLen>nDir ){
  39751. sqlite3_free(zBuf);
  39752. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  39753. return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
  39754. }
  39755. sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
  39756. }
  39757. }
  39758. #if defined(__CYGWIN__)
  39759. else{
  39760. static const char *azDirs[] = {
  39761. 0, /* getenv("SQLITE_TMPDIR") */
  39762. 0, /* getenv("TMPDIR") */
  39763. 0, /* getenv("TMP") */
  39764. 0, /* getenv("TEMP") */
  39765. 0, /* getenv("USERPROFILE") */
  39766. "/var/tmp",
  39767. "/usr/tmp",
  39768. "/tmp",
  39769. ".",
  39770. 0 /* List terminator */
  39771. };
  39772. unsigned int i;
  39773. const char *zDir = 0;
  39774. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  39775. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  39776. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  39777. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  39778. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  39779. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  39780. void *zConverted;
  39781. if( zDir==0 ) continue;
  39782. /* If the path starts with a drive letter followed by the colon
  39783. ** character, assume it is already a native Win32 path; otherwise,
  39784. ** it must be converted to a native Win32 path via the Cygwin API
  39785. ** prior to using it.
  39786. */
  39787. if( winIsDriveLetterAndColon(zDir) ){
  39788. zConverted = winConvertFromUtf8Filename(zDir);
  39789. if( !zConverted ){
  39790. sqlite3_free(zBuf);
  39791. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  39792. return SQLITE_IOERR_NOMEM_BKPT;
  39793. }
  39794. if( winIsDir(zConverted) ){
  39795. sqlite3_snprintf(nMax, zBuf, "%s", zDir);
  39796. sqlite3_free(zConverted);
  39797. break;
  39798. }
  39799. sqlite3_free(zConverted);
  39800. }else{
  39801. zConverted = sqlite3MallocZero( nMax+1 );
  39802. if( !zConverted ){
  39803. sqlite3_free(zBuf);
  39804. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  39805. return SQLITE_IOERR_NOMEM_BKPT;
  39806. }
  39807. if( cygwin_conv_path(
  39808. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  39809. zConverted, nMax+1)<0 ){
  39810. sqlite3_free(zConverted);
  39811. sqlite3_free(zBuf);
  39812. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  39813. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  39814. "winGetTempname2", zDir);
  39815. }
  39816. if( winIsDir(zConverted) ){
  39817. /* At this point, we know the candidate directory exists and should
  39818. ** be used. However, we may need to convert the string containing
  39819. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  39820. */
  39821. char *zUtf8 = winConvertToUtf8Filename(zConverted);
  39822. if( !zUtf8 ){
  39823. sqlite3_free(zConverted);
  39824. sqlite3_free(zBuf);
  39825. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  39826. return SQLITE_IOERR_NOMEM_BKPT;
  39827. }
  39828. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  39829. sqlite3_free(zUtf8);
  39830. sqlite3_free(zConverted);
  39831. break;
  39832. }
  39833. sqlite3_free(zConverted);
  39834. }
  39835. }
  39836. }
  39837. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  39838. else if( osIsNT() ){
  39839. char *zMulti;
  39840. LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
  39841. if( !zWidePath ){
  39842. sqlite3_free(zBuf);
  39843. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  39844. return SQLITE_IOERR_NOMEM_BKPT;
  39845. }
  39846. if( osGetTempPathW(nMax, zWidePath)==0 ){
  39847. sqlite3_free(zWidePath);
  39848. sqlite3_free(zBuf);
  39849. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  39850. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  39851. "winGetTempname2", 0);
  39852. }
  39853. zMulti = winUnicodeToUtf8(zWidePath);
  39854. if( zMulti ){
  39855. sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
  39856. sqlite3_free(zMulti);
  39857. sqlite3_free(zWidePath);
  39858. }else{
  39859. sqlite3_free(zWidePath);
  39860. sqlite3_free(zBuf);
  39861. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  39862. return SQLITE_IOERR_NOMEM_BKPT;
  39863. }
  39864. }
  39865. #ifdef SQLITE_WIN32_HAS_ANSI
  39866. else{
  39867. char *zUtf8;
  39868. char *zMbcsPath = sqlite3MallocZero( nMax );
  39869. if( !zMbcsPath ){
  39870. sqlite3_free(zBuf);
  39871. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  39872. return SQLITE_IOERR_NOMEM_BKPT;
  39873. }
  39874. if( osGetTempPathA(nMax, zMbcsPath)==0 ){
  39875. sqlite3_free(zBuf);
  39876. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  39877. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  39878. "winGetTempname3", 0);
  39879. }
  39880. zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
  39881. if( zUtf8 ){
  39882. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  39883. sqlite3_free(zUtf8);
  39884. }else{
  39885. sqlite3_free(zBuf);
  39886. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  39887. return SQLITE_IOERR_NOMEM_BKPT;
  39888. }
  39889. }
  39890. #endif /* SQLITE_WIN32_HAS_ANSI */
  39891. #endif /* !SQLITE_OS_WINRT */
  39892. /*
  39893. ** Check to make sure the temporary directory ends with an appropriate
  39894. ** separator. If it does not and there is not enough space left to add
  39895. ** one, fail.
  39896. */
  39897. if( !winMakeEndInDirSep(nDir+1, zBuf) ){
  39898. sqlite3_free(zBuf);
  39899. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  39900. return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
  39901. }
  39902. /*
  39903. ** Check that the output buffer is large enough for the temporary file
  39904. ** name in the following format:
  39905. **
  39906. ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
  39907. **
  39908. ** If not, return SQLITE_ERROR. The number 17 is used here in order to
  39909. ** account for the space used by the 15 character random suffix and the
  39910. ** two trailing NUL characters. The final directory separator character
  39911. ** has already added if it was not already present.
  39912. */
  39913. nLen = sqlite3Strlen30(zBuf);
  39914. if( (nLen + nPre + 17) > nBuf ){
  39915. sqlite3_free(zBuf);
  39916. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  39917. return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
  39918. }
  39919. sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  39920. j = sqlite3Strlen30(zBuf);
  39921. sqlite3_randomness(15, &zBuf[j]);
  39922. for(i=0; i<15; i++, j++){
  39923. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  39924. }
  39925. zBuf[j] = 0;
  39926. zBuf[j+1] = 0;
  39927. *pzBuf = zBuf;
  39928. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  39929. return SQLITE_OK;
  39930. }
  39931. /*
  39932. ** Return TRUE if the named file is really a directory. Return false if
  39933. ** it is something other than a directory, or if there is any kind of memory
  39934. ** allocation failure.
  39935. */
  39936. static int winIsDir(const void *zConverted){
  39937. DWORD attr;
  39938. int rc = 0;
  39939. DWORD lastErrno;
  39940. if( osIsNT() ){
  39941. int cnt = 0;
  39942. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  39943. memset(&sAttrData, 0, sizeof(sAttrData));
  39944. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  39945. GetFileExInfoStandard,
  39946. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  39947. if( !rc ){
  39948. return 0; /* Invalid name? */
  39949. }
  39950. attr = sAttrData.dwFileAttributes;
  39951. #if SQLITE_OS_WINCE==0
  39952. }else{
  39953. attr = osGetFileAttributesA((char*)zConverted);
  39954. #endif
  39955. }
  39956. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  39957. }
  39958. /*
  39959. ** Open a file.
  39960. */
  39961. static int winOpen(
  39962. sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */
  39963. const char *zName, /* Name of the file (UTF-8) */
  39964. sqlite3_file *id, /* Write the SQLite file handle here */
  39965. int flags, /* Open mode flags */
  39966. int *pOutFlags /* Status return flags */
  39967. ){
  39968. HANDLE h;
  39969. DWORD lastErrno = 0;
  39970. DWORD dwDesiredAccess;
  39971. DWORD dwShareMode;
  39972. DWORD dwCreationDisposition;
  39973. DWORD dwFlagsAndAttributes = 0;
  39974. #if SQLITE_OS_WINCE
  39975. int isTemp = 0;
  39976. #endif
  39977. winVfsAppData *pAppData;
  39978. winFile *pFile = (winFile*)id;
  39979. void *zConverted; /* Filename in OS encoding */
  39980. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  39981. int cnt = 0;
  39982. /* If argument zPath is a NULL pointer, this function is required to open
  39983. ** a temporary file. Use this buffer to store the file name in.
  39984. */
  39985. char *zTmpname = 0; /* For temporary filename, if necessary. */
  39986. int rc = SQLITE_OK; /* Function Return Code */
  39987. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  39988. int eType = flags&0xFFFFFF00; /* Type of file to open */
  39989. #endif
  39990. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  39991. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  39992. int isCreate = (flags & SQLITE_OPEN_CREATE);
  39993. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  39994. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  39995. #ifndef NDEBUG
  39996. int isOpenJournal = (isCreate && (
  39997. eType==SQLITE_OPEN_MASTER_JOURNAL
  39998. || eType==SQLITE_OPEN_MAIN_JOURNAL
  39999. || eType==SQLITE_OPEN_WAL
  40000. ));
  40001. #endif
  40002. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  40003. zUtf8Name, id, flags, pOutFlags));
  40004. /* Check the following statements are true:
  40005. **
  40006. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  40007. ** (b) if CREATE is set, then READWRITE must also be set, and
  40008. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  40009. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  40010. */
  40011. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  40012. assert(isCreate==0 || isReadWrite);
  40013. assert(isExclusive==0 || isCreate);
  40014. assert(isDelete==0 || isCreate);
  40015. /* The main DB, main journal, WAL file and master journal are never
  40016. ** automatically deleted. Nor are they ever temporary files. */
  40017. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  40018. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  40019. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  40020. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  40021. /* Assert that the upper layer has set one of the "file-type" flags. */
  40022. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  40023. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  40024. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  40025. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  40026. );
  40027. assert( pFile!=0 );
  40028. memset(pFile, 0, sizeof(winFile));
  40029. pFile->h = INVALID_HANDLE_VALUE;
  40030. #if SQLITE_OS_WINRT
  40031. if( !zUtf8Name && !sqlite3_temp_directory ){
  40032. sqlite3_log(SQLITE_ERROR,
  40033. "sqlite3_temp_directory variable should be set for WinRT");
  40034. }
  40035. #endif
  40036. /* If the second argument to this function is NULL, generate a
  40037. ** temporary file name to use
  40038. */
  40039. if( !zUtf8Name ){
  40040. assert( isDelete && !isOpenJournal );
  40041. rc = winGetTempname(pVfs, &zTmpname);
  40042. if( rc!=SQLITE_OK ){
  40043. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  40044. return rc;
  40045. }
  40046. zUtf8Name = zTmpname;
  40047. }
  40048. /* Database filenames are double-zero terminated if they are not
  40049. ** URIs with parameters. Hence, they can always be passed into
  40050. ** sqlite3_uri_parameter().
  40051. */
  40052. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  40053. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  40054. /* Convert the filename to the system encoding. */
  40055. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  40056. if( zConverted==0 ){
  40057. sqlite3_free(zTmpname);
  40058. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  40059. return SQLITE_IOERR_NOMEM_BKPT;
  40060. }
  40061. if( winIsDir(zConverted) ){
  40062. sqlite3_free(zConverted);
  40063. sqlite3_free(zTmpname);
  40064. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  40065. return SQLITE_CANTOPEN_ISDIR;
  40066. }
  40067. if( isReadWrite ){
  40068. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  40069. }else{
  40070. dwDesiredAccess = GENERIC_READ;
  40071. }
  40072. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  40073. ** created. SQLite doesn't use it to indicate "exclusive access"
  40074. ** as it is usually understood.
  40075. */
  40076. if( isExclusive ){
  40077. /* Creates a new file, only if it does not already exist. */
  40078. /* If the file exists, it fails. */
  40079. dwCreationDisposition = CREATE_NEW;
  40080. }else if( isCreate ){
  40081. /* Open existing file, or create if it doesn't exist */
  40082. dwCreationDisposition = OPEN_ALWAYS;
  40083. }else{
  40084. /* Opens a file, only if it exists. */
  40085. dwCreationDisposition = OPEN_EXISTING;
  40086. }
  40087. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  40088. if( isDelete ){
  40089. #if SQLITE_OS_WINCE
  40090. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  40091. isTemp = 1;
  40092. #else
  40093. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  40094. | FILE_ATTRIBUTE_HIDDEN
  40095. | FILE_FLAG_DELETE_ON_CLOSE;
  40096. #endif
  40097. }else{
  40098. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  40099. }
  40100. /* Reports from the internet are that performance is always
  40101. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  40102. #if SQLITE_OS_WINCE
  40103. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  40104. #endif
  40105. if( osIsNT() ){
  40106. #if SQLITE_OS_WINRT
  40107. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  40108. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  40109. extendedParameters.dwFileAttributes =
  40110. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  40111. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  40112. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  40113. extendedParameters.lpSecurityAttributes = NULL;
  40114. extendedParameters.hTemplateFile = NULL;
  40115. while( (h = osCreateFile2((LPCWSTR)zConverted,
  40116. dwDesiredAccess,
  40117. dwShareMode,
  40118. dwCreationDisposition,
  40119. &extendedParameters))==INVALID_HANDLE_VALUE &&
  40120. winRetryIoerr(&cnt, &lastErrno) ){
  40121. /* Noop */
  40122. }
  40123. #else
  40124. while( (h = osCreateFileW((LPCWSTR)zConverted,
  40125. dwDesiredAccess,
  40126. dwShareMode, NULL,
  40127. dwCreationDisposition,
  40128. dwFlagsAndAttributes,
  40129. NULL))==INVALID_HANDLE_VALUE &&
  40130. winRetryIoerr(&cnt, &lastErrno) ){
  40131. /* Noop */
  40132. }
  40133. #endif
  40134. }
  40135. #ifdef SQLITE_WIN32_HAS_ANSI
  40136. else{
  40137. while( (h = osCreateFileA((LPCSTR)zConverted,
  40138. dwDesiredAccess,
  40139. dwShareMode, NULL,
  40140. dwCreationDisposition,
  40141. dwFlagsAndAttributes,
  40142. NULL))==INVALID_HANDLE_VALUE &&
  40143. winRetryIoerr(&cnt, &lastErrno) ){
  40144. /* Noop */
  40145. }
  40146. }
  40147. #endif
  40148. winLogIoerr(cnt, __LINE__);
  40149. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  40150. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  40151. if( h==INVALID_HANDLE_VALUE ){
  40152. pFile->lastErrno = lastErrno;
  40153. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  40154. sqlite3_free(zConverted);
  40155. sqlite3_free(zTmpname);
  40156. if( isReadWrite && !isExclusive ){
  40157. return winOpen(pVfs, zName, id,
  40158. ((flags|SQLITE_OPEN_READONLY) &
  40159. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  40160. pOutFlags);
  40161. }else{
  40162. return SQLITE_CANTOPEN_BKPT;
  40163. }
  40164. }
  40165. if( pOutFlags ){
  40166. if( isReadWrite ){
  40167. *pOutFlags = SQLITE_OPEN_READWRITE;
  40168. }else{
  40169. *pOutFlags = SQLITE_OPEN_READONLY;
  40170. }
  40171. }
  40172. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  40173. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  40174. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  40175. pAppData = (winVfsAppData*)pVfs->pAppData;
  40176. #if SQLITE_OS_WINCE
  40177. {
  40178. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  40179. && ((pAppData==NULL) || !pAppData->bNoLock)
  40180. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  40181. ){
  40182. osCloseHandle(h);
  40183. sqlite3_free(zConverted);
  40184. sqlite3_free(zTmpname);
  40185. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  40186. return rc;
  40187. }
  40188. }
  40189. if( isTemp ){
  40190. pFile->zDeleteOnClose = zConverted;
  40191. }else
  40192. #endif
  40193. {
  40194. sqlite3_free(zConverted);
  40195. }
  40196. sqlite3_free(zTmpname);
  40197. pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
  40198. pFile->pVfs = pVfs;
  40199. pFile->h = h;
  40200. if( isReadonly ){
  40201. pFile->ctrlFlags |= WINFILE_RDONLY;
  40202. }
  40203. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  40204. pFile->ctrlFlags |= WINFILE_PSOW;
  40205. }
  40206. pFile->lastErrno = NO_ERROR;
  40207. pFile->zPath = zName;
  40208. #if SQLITE_MAX_MMAP_SIZE>0
  40209. pFile->hMap = NULL;
  40210. pFile->pMapRegion = 0;
  40211. pFile->mmapSize = 0;
  40212. pFile->mmapSizeActual = 0;
  40213. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  40214. #endif
  40215. OpenCounter(+1);
  40216. return rc;
  40217. }
  40218. /*
  40219. ** Delete the named file.
  40220. **
  40221. ** Note that Windows does not allow a file to be deleted if some other
  40222. ** process has it open. Sometimes a virus scanner or indexing program
  40223. ** will open a journal file shortly after it is created in order to do
  40224. ** whatever it does. While this other process is holding the
  40225. ** file open, we will be unable to delete it. To work around this
  40226. ** problem, we delay 100 milliseconds and try to delete again. Up
  40227. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  40228. ** up and returning an error.
  40229. */
  40230. static int winDelete(
  40231. sqlite3_vfs *pVfs, /* Not used on win32 */
  40232. const char *zFilename, /* Name of file to delete */
  40233. int syncDir /* Not used on win32 */
  40234. ){
  40235. int cnt = 0;
  40236. int rc;
  40237. DWORD attr;
  40238. DWORD lastErrno = 0;
  40239. void *zConverted;
  40240. UNUSED_PARAMETER(pVfs);
  40241. UNUSED_PARAMETER(syncDir);
  40242. SimulateIOError(return SQLITE_IOERR_DELETE);
  40243. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  40244. zConverted = winConvertFromUtf8Filename(zFilename);
  40245. if( zConverted==0 ){
  40246. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  40247. return SQLITE_IOERR_NOMEM_BKPT;
  40248. }
  40249. if( osIsNT() ){
  40250. do {
  40251. #if SQLITE_OS_WINRT
  40252. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  40253. memset(&sAttrData, 0, sizeof(sAttrData));
  40254. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  40255. &sAttrData) ){
  40256. attr = sAttrData.dwFileAttributes;
  40257. }else{
  40258. lastErrno = osGetLastError();
  40259. if( lastErrno==ERROR_FILE_NOT_FOUND
  40260. || lastErrno==ERROR_PATH_NOT_FOUND ){
  40261. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  40262. }else{
  40263. rc = SQLITE_ERROR;
  40264. }
  40265. break;
  40266. }
  40267. #else
  40268. attr = osGetFileAttributesW(zConverted);
  40269. #endif
  40270. if ( attr==INVALID_FILE_ATTRIBUTES ){
  40271. lastErrno = osGetLastError();
  40272. if( lastErrno==ERROR_FILE_NOT_FOUND
  40273. || lastErrno==ERROR_PATH_NOT_FOUND ){
  40274. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  40275. }else{
  40276. rc = SQLITE_ERROR;
  40277. }
  40278. break;
  40279. }
  40280. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  40281. rc = SQLITE_ERROR; /* Files only. */
  40282. break;
  40283. }
  40284. if ( osDeleteFileW(zConverted) ){
  40285. rc = SQLITE_OK; /* Deleted OK. */
  40286. break;
  40287. }
  40288. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  40289. rc = SQLITE_ERROR; /* No more retries. */
  40290. break;
  40291. }
  40292. } while(1);
  40293. }
  40294. #ifdef SQLITE_WIN32_HAS_ANSI
  40295. else{
  40296. do {
  40297. attr = osGetFileAttributesA(zConverted);
  40298. if ( attr==INVALID_FILE_ATTRIBUTES ){
  40299. lastErrno = osGetLastError();
  40300. if( lastErrno==ERROR_FILE_NOT_FOUND
  40301. || lastErrno==ERROR_PATH_NOT_FOUND ){
  40302. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  40303. }else{
  40304. rc = SQLITE_ERROR;
  40305. }
  40306. break;
  40307. }
  40308. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  40309. rc = SQLITE_ERROR; /* Files only. */
  40310. break;
  40311. }
  40312. if ( osDeleteFileA(zConverted) ){
  40313. rc = SQLITE_OK; /* Deleted OK. */
  40314. break;
  40315. }
  40316. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  40317. rc = SQLITE_ERROR; /* No more retries. */
  40318. break;
  40319. }
  40320. } while(1);
  40321. }
  40322. #endif
  40323. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  40324. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  40325. }else{
  40326. winLogIoerr(cnt, __LINE__);
  40327. }
  40328. sqlite3_free(zConverted);
  40329. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  40330. return rc;
  40331. }
  40332. /*
  40333. ** Check the existence and status of a file.
  40334. */
  40335. static int winAccess(
  40336. sqlite3_vfs *pVfs, /* Not used on win32 */
  40337. const char *zFilename, /* Name of file to check */
  40338. int flags, /* Type of test to make on this file */
  40339. int *pResOut /* OUT: Result */
  40340. ){
  40341. DWORD attr;
  40342. int rc = 0;
  40343. DWORD lastErrno = 0;
  40344. void *zConverted;
  40345. UNUSED_PARAMETER(pVfs);
  40346. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  40347. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  40348. zFilename, flags, pResOut));
  40349. zConverted = winConvertFromUtf8Filename(zFilename);
  40350. if( zConverted==0 ){
  40351. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  40352. return SQLITE_IOERR_NOMEM_BKPT;
  40353. }
  40354. if( osIsNT() ){
  40355. int cnt = 0;
  40356. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  40357. memset(&sAttrData, 0, sizeof(sAttrData));
  40358. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  40359. GetFileExInfoStandard,
  40360. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  40361. if( rc ){
  40362. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  40363. ** as if it does not exist.
  40364. */
  40365. if( flags==SQLITE_ACCESS_EXISTS
  40366. && sAttrData.nFileSizeHigh==0
  40367. && sAttrData.nFileSizeLow==0 ){
  40368. attr = INVALID_FILE_ATTRIBUTES;
  40369. }else{
  40370. attr = sAttrData.dwFileAttributes;
  40371. }
  40372. }else{
  40373. winLogIoerr(cnt, __LINE__);
  40374. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  40375. sqlite3_free(zConverted);
  40376. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  40377. zFilename);
  40378. }else{
  40379. attr = INVALID_FILE_ATTRIBUTES;
  40380. }
  40381. }
  40382. }
  40383. #ifdef SQLITE_WIN32_HAS_ANSI
  40384. else{
  40385. attr = osGetFileAttributesA((char*)zConverted);
  40386. }
  40387. #endif
  40388. sqlite3_free(zConverted);
  40389. switch( flags ){
  40390. case SQLITE_ACCESS_READ:
  40391. case SQLITE_ACCESS_EXISTS:
  40392. rc = attr!=INVALID_FILE_ATTRIBUTES;
  40393. break;
  40394. case SQLITE_ACCESS_READWRITE:
  40395. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  40396. (attr & FILE_ATTRIBUTE_READONLY)==0;
  40397. break;
  40398. default:
  40399. assert(!"Invalid flags argument");
  40400. }
  40401. *pResOut = rc;
  40402. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  40403. zFilename, pResOut, *pResOut));
  40404. return SQLITE_OK;
  40405. }
  40406. /*
  40407. ** Returns non-zero if the specified path name starts with a drive letter
  40408. ** followed by a colon character.
  40409. */
  40410. static BOOL winIsDriveLetterAndColon(
  40411. const char *zPathname
  40412. ){
  40413. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  40414. }
  40415. /*
  40416. ** Returns non-zero if the specified path name should be used verbatim. If
  40417. ** non-zero is returned from this function, the calling function must simply
  40418. ** use the provided path name verbatim -OR- resolve it into a full path name
  40419. ** using the GetFullPathName Win32 API function (if available).
  40420. */
  40421. static BOOL winIsVerbatimPathname(
  40422. const char *zPathname
  40423. ){
  40424. /*
  40425. ** If the path name starts with a forward slash or a backslash, it is either
  40426. ** a legal UNC name, a volume relative path, or an absolute path name in the
  40427. ** "Unix" format on Windows. There is no easy way to differentiate between
  40428. ** the final two cases; therefore, we return the safer return value of TRUE
  40429. ** so that callers of this function will simply use it verbatim.
  40430. */
  40431. if ( winIsDirSep(zPathname[0]) ){
  40432. return TRUE;
  40433. }
  40434. /*
  40435. ** If the path name starts with a letter and a colon it is either a volume
  40436. ** relative path or an absolute path. Callers of this function must not
  40437. ** attempt to treat it as a relative path name (i.e. they should simply use
  40438. ** it verbatim).
  40439. */
  40440. if ( winIsDriveLetterAndColon(zPathname) ){
  40441. return TRUE;
  40442. }
  40443. /*
  40444. ** If we get to this point, the path name should almost certainly be a purely
  40445. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  40446. */
  40447. return FALSE;
  40448. }
  40449. /*
  40450. ** Turn a relative pathname into a full pathname. Write the full
  40451. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  40452. ** bytes in size.
  40453. */
  40454. static int winFullPathname(
  40455. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  40456. const char *zRelative, /* Possibly relative input path */
  40457. int nFull, /* Size of output buffer in bytes */
  40458. char *zFull /* Output buffer */
  40459. ){
  40460. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  40461. DWORD nByte;
  40462. void *zConverted;
  40463. char *zOut;
  40464. #endif
  40465. /* If this path name begins with "/X:", where "X" is any alphabetic
  40466. ** character, discard the initial "/" from the pathname.
  40467. */
  40468. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  40469. zRelative++;
  40470. }
  40471. #if defined(__CYGWIN__)
  40472. SimulateIOError( return SQLITE_ERROR );
  40473. UNUSED_PARAMETER(nFull);
  40474. assert( nFull>=pVfs->mxPathname );
  40475. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  40476. /*
  40477. ** NOTE: We are dealing with a relative path name and the data
  40478. ** directory has been set. Therefore, use it as the basis
  40479. ** for converting the relative path name to an absolute
  40480. ** one by prepending the data directory and a slash.
  40481. */
  40482. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  40483. if( !zOut ){
  40484. return SQLITE_IOERR_NOMEM_BKPT;
  40485. }
  40486. if( cygwin_conv_path(
  40487. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
  40488. CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
  40489. sqlite3_free(zOut);
  40490. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  40491. "winFullPathname1", zRelative);
  40492. }else{
  40493. char *zUtf8 = winConvertToUtf8Filename(zOut);
  40494. if( !zUtf8 ){
  40495. sqlite3_free(zOut);
  40496. return SQLITE_IOERR_NOMEM_BKPT;
  40497. }
  40498. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  40499. sqlite3_data_directory, winGetDirSep(), zUtf8);
  40500. sqlite3_free(zUtf8);
  40501. sqlite3_free(zOut);
  40502. }
  40503. }else{
  40504. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  40505. if( !zOut ){
  40506. return SQLITE_IOERR_NOMEM_BKPT;
  40507. }
  40508. if( cygwin_conv_path(
  40509. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
  40510. zRelative, zOut, pVfs->mxPathname+1)<0 ){
  40511. sqlite3_free(zOut);
  40512. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  40513. "winFullPathname2", zRelative);
  40514. }else{
  40515. char *zUtf8 = winConvertToUtf8Filename(zOut);
  40516. if( !zUtf8 ){
  40517. sqlite3_free(zOut);
  40518. return SQLITE_IOERR_NOMEM_BKPT;
  40519. }
  40520. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
  40521. sqlite3_free(zUtf8);
  40522. sqlite3_free(zOut);
  40523. }
  40524. }
  40525. return SQLITE_OK;
  40526. #endif
  40527. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  40528. SimulateIOError( return SQLITE_ERROR );
  40529. /* WinCE has no concept of a relative pathname, or so I am told. */
  40530. /* WinRT has no way to convert a relative path to an absolute one. */
  40531. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  40532. /*
  40533. ** NOTE: We are dealing with a relative path name and the data
  40534. ** directory has been set. Therefore, use it as the basis
  40535. ** for converting the relative path name to an absolute
  40536. ** one by prepending the data directory and a backslash.
  40537. */
  40538. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  40539. sqlite3_data_directory, winGetDirSep(), zRelative);
  40540. }else{
  40541. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  40542. }
  40543. return SQLITE_OK;
  40544. #endif
  40545. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  40546. /* It's odd to simulate an io-error here, but really this is just
  40547. ** using the io-error infrastructure to test that SQLite handles this
  40548. ** function failing. This function could fail if, for example, the
  40549. ** current working directory has been unlinked.
  40550. */
  40551. SimulateIOError( return SQLITE_ERROR );
  40552. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  40553. /*
  40554. ** NOTE: We are dealing with a relative path name and the data
  40555. ** directory has been set. Therefore, use it as the basis
  40556. ** for converting the relative path name to an absolute
  40557. ** one by prepending the data directory and a backslash.
  40558. */
  40559. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  40560. sqlite3_data_directory, winGetDirSep(), zRelative);
  40561. return SQLITE_OK;
  40562. }
  40563. zConverted = winConvertFromUtf8Filename(zRelative);
  40564. if( zConverted==0 ){
  40565. return SQLITE_IOERR_NOMEM_BKPT;
  40566. }
  40567. if( osIsNT() ){
  40568. LPWSTR zTemp;
  40569. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  40570. if( nByte==0 ){
  40571. sqlite3_free(zConverted);
  40572. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  40573. "winFullPathname1", zRelative);
  40574. }
  40575. nByte += 3;
  40576. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  40577. if( zTemp==0 ){
  40578. sqlite3_free(zConverted);
  40579. return SQLITE_IOERR_NOMEM_BKPT;
  40580. }
  40581. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  40582. if( nByte==0 ){
  40583. sqlite3_free(zConverted);
  40584. sqlite3_free(zTemp);
  40585. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  40586. "winFullPathname2", zRelative);
  40587. }
  40588. sqlite3_free(zConverted);
  40589. zOut = winUnicodeToUtf8(zTemp);
  40590. sqlite3_free(zTemp);
  40591. }
  40592. #ifdef SQLITE_WIN32_HAS_ANSI
  40593. else{
  40594. char *zTemp;
  40595. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  40596. if( nByte==0 ){
  40597. sqlite3_free(zConverted);
  40598. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  40599. "winFullPathname3", zRelative);
  40600. }
  40601. nByte += 3;
  40602. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  40603. if( zTemp==0 ){
  40604. sqlite3_free(zConverted);
  40605. return SQLITE_IOERR_NOMEM_BKPT;
  40606. }
  40607. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  40608. if( nByte==0 ){
  40609. sqlite3_free(zConverted);
  40610. sqlite3_free(zTemp);
  40611. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  40612. "winFullPathname4", zRelative);
  40613. }
  40614. sqlite3_free(zConverted);
  40615. zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
  40616. sqlite3_free(zTemp);
  40617. }
  40618. #endif
  40619. if( zOut ){
  40620. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  40621. sqlite3_free(zOut);
  40622. return SQLITE_OK;
  40623. }else{
  40624. return SQLITE_IOERR_NOMEM_BKPT;
  40625. }
  40626. #endif
  40627. }
  40628. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  40629. /*
  40630. ** Interfaces for opening a shared library, finding entry points
  40631. ** within the shared library, and closing the shared library.
  40632. */
  40633. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  40634. HANDLE h;
  40635. #if defined(__CYGWIN__)
  40636. int nFull = pVfs->mxPathname+1;
  40637. char *zFull = sqlite3MallocZero( nFull );
  40638. void *zConverted = 0;
  40639. if( zFull==0 ){
  40640. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  40641. return 0;
  40642. }
  40643. if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
  40644. sqlite3_free(zFull);
  40645. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  40646. return 0;
  40647. }
  40648. zConverted = winConvertFromUtf8Filename(zFull);
  40649. sqlite3_free(zFull);
  40650. #else
  40651. void *zConverted = winConvertFromUtf8Filename(zFilename);
  40652. UNUSED_PARAMETER(pVfs);
  40653. #endif
  40654. if( zConverted==0 ){
  40655. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  40656. return 0;
  40657. }
  40658. if( osIsNT() ){
  40659. #if SQLITE_OS_WINRT
  40660. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  40661. #else
  40662. h = osLoadLibraryW((LPCWSTR)zConverted);
  40663. #endif
  40664. }
  40665. #ifdef SQLITE_WIN32_HAS_ANSI
  40666. else{
  40667. h = osLoadLibraryA((char*)zConverted);
  40668. }
  40669. #endif
  40670. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
  40671. sqlite3_free(zConverted);
  40672. return (void*)h;
  40673. }
  40674. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  40675. UNUSED_PARAMETER(pVfs);
  40676. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  40677. }
  40678. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  40679. FARPROC proc;
  40680. UNUSED_PARAMETER(pVfs);
  40681. proc = osGetProcAddressA((HANDLE)pH, zSym);
  40682. OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
  40683. (void*)pH, zSym, (void*)proc));
  40684. return (void(*)(void))proc;
  40685. }
  40686. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  40687. UNUSED_PARAMETER(pVfs);
  40688. osFreeLibrary((HANDLE)pHandle);
  40689. OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
  40690. }
  40691. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  40692. #define winDlOpen 0
  40693. #define winDlError 0
  40694. #define winDlSym 0
  40695. #define winDlClose 0
  40696. #endif
  40697. /* State information for the randomness gatherer. */
  40698. typedef struct EntropyGatherer EntropyGatherer;
  40699. struct EntropyGatherer {
  40700. unsigned char *a; /* Gather entropy into this buffer */
  40701. int na; /* Size of a[] in bytes */
  40702. int i; /* XOR next input into a[i] */
  40703. int nXor; /* Number of XOR operations done */
  40704. };
  40705. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  40706. /* Mix sz bytes of entropy into p. */
  40707. static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
  40708. int j, k;
  40709. for(j=0, k=p->i; j<sz; j++){
  40710. p->a[k++] ^= x[j];
  40711. if( k>=p->na ) k = 0;
  40712. }
  40713. p->i = k;
  40714. p->nXor += sz;
  40715. }
  40716. #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
  40717. /*
  40718. ** Write up to nBuf bytes of randomness into zBuf.
  40719. */
  40720. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  40721. #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
  40722. UNUSED_PARAMETER(pVfs);
  40723. memset(zBuf, 0, nBuf);
  40724. return nBuf;
  40725. #else
  40726. EntropyGatherer e;
  40727. UNUSED_PARAMETER(pVfs);
  40728. memset(zBuf, 0, nBuf);
  40729. #if defined(_MSC_VER) && _MSC_VER>=1400 && !SQLITE_OS_WINCE
  40730. rand_s((unsigned int*)zBuf); /* rand_s() is not available with MinGW */
  40731. #endif /* defined(_MSC_VER) && _MSC_VER>=1400 */
  40732. e.a = (unsigned char*)zBuf;
  40733. e.na = nBuf;
  40734. e.nXor = 0;
  40735. e.i = 0;
  40736. {
  40737. SYSTEMTIME x;
  40738. osGetSystemTime(&x);
  40739. xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
  40740. }
  40741. {
  40742. DWORD pid = osGetCurrentProcessId();
  40743. xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
  40744. }
  40745. #if SQLITE_OS_WINRT
  40746. {
  40747. ULONGLONG cnt = osGetTickCount64();
  40748. xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
  40749. }
  40750. #else
  40751. {
  40752. DWORD cnt = osGetTickCount();
  40753. xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
  40754. }
  40755. #endif /* SQLITE_OS_WINRT */
  40756. {
  40757. LARGE_INTEGER i;
  40758. osQueryPerformanceCounter(&i);
  40759. xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
  40760. }
  40761. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  40762. {
  40763. UUID id;
  40764. memset(&id, 0, sizeof(UUID));
  40765. osUuidCreate(&id);
  40766. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  40767. memset(&id, 0, sizeof(UUID));
  40768. osUuidCreateSequential(&id);
  40769. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  40770. }
  40771. #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
  40772. return e.nXor>nBuf ? nBuf : e.nXor;
  40773. #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
  40774. }
  40775. /*
  40776. ** Sleep for a little while. Return the amount of time slept.
  40777. */
  40778. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  40779. sqlite3_win32_sleep((microsec+999)/1000);
  40780. UNUSED_PARAMETER(pVfs);
  40781. return ((microsec+999)/1000)*1000;
  40782. }
  40783. /*
  40784. ** The following variable, if set to a non-zero value, is interpreted as
  40785. ** the number of seconds since 1970 and is used to set the result of
  40786. ** sqlite3OsCurrentTime() during testing.
  40787. */
  40788. #ifdef SQLITE_TEST
  40789. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  40790. #endif
  40791. /*
  40792. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  40793. ** the current time and date as a Julian Day number times 86_400_000. In
  40794. ** other words, write into *piNow the number of milliseconds since the Julian
  40795. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  40796. ** proleptic Gregorian calendar.
  40797. **
  40798. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  40799. ** cannot be found.
  40800. */
  40801. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  40802. /* FILETIME structure is a 64-bit value representing the number of
  40803. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  40804. */
  40805. FILETIME ft;
  40806. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  40807. #ifdef SQLITE_TEST
  40808. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  40809. #endif
  40810. /* 2^32 - to avoid use of LL and warnings in gcc */
  40811. static const sqlite3_int64 max32BitValue =
  40812. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  40813. (sqlite3_int64)294967296;
  40814. #if SQLITE_OS_WINCE
  40815. SYSTEMTIME time;
  40816. osGetSystemTime(&time);
  40817. /* if SystemTimeToFileTime() fails, it returns zero. */
  40818. if (!osSystemTimeToFileTime(&time,&ft)){
  40819. return SQLITE_ERROR;
  40820. }
  40821. #else
  40822. osGetSystemTimeAsFileTime( &ft );
  40823. #endif
  40824. *piNow = winFiletimeEpoch +
  40825. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  40826. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  40827. #ifdef SQLITE_TEST
  40828. if( sqlite3_current_time ){
  40829. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  40830. }
  40831. #endif
  40832. UNUSED_PARAMETER(pVfs);
  40833. return SQLITE_OK;
  40834. }
  40835. /*
  40836. ** Find the current time (in Universal Coordinated Time). Write the
  40837. ** current time and date as a Julian Day number into *prNow and
  40838. ** return 0. Return 1 if the time and date cannot be found.
  40839. */
  40840. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  40841. int rc;
  40842. sqlite3_int64 i;
  40843. rc = winCurrentTimeInt64(pVfs, &i);
  40844. if( !rc ){
  40845. *prNow = i/86400000.0;
  40846. }
  40847. return rc;
  40848. }
  40849. /*
  40850. ** The idea is that this function works like a combination of
  40851. ** GetLastError() and FormatMessage() on Windows (or errno and
  40852. ** strerror_r() on Unix). After an error is returned by an OS
  40853. ** function, SQLite calls this function with zBuf pointing to
  40854. ** a buffer of nBuf bytes. The OS layer should populate the
  40855. ** buffer with a nul-terminated UTF-8 encoded error message
  40856. ** describing the last IO error to have occurred within the calling
  40857. ** thread.
  40858. **
  40859. ** If the error message is too large for the supplied buffer,
  40860. ** it should be truncated. The return value of xGetLastError
  40861. ** is zero if the error message fits in the buffer, or non-zero
  40862. ** otherwise (if the message was truncated). If non-zero is returned,
  40863. ** then it is not necessary to include the nul-terminator character
  40864. ** in the output buffer.
  40865. **
  40866. ** Not supplying an error message will have no adverse effect
  40867. ** on SQLite. It is fine to have an implementation that never
  40868. ** returns an error message:
  40869. **
  40870. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  40871. ** assert(zBuf[0]=='\0');
  40872. ** return 0;
  40873. ** }
  40874. **
  40875. ** However if an error message is supplied, it will be incorporated
  40876. ** by sqlite into the error message available to the user using
  40877. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  40878. */
  40879. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  40880. DWORD e = osGetLastError();
  40881. UNUSED_PARAMETER(pVfs);
  40882. if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
  40883. return e;
  40884. }
  40885. /*
  40886. ** Initialize and deinitialize the operating system interface.
  40887. */
  40888. SQLITE_API int sqlite3_os_init(void){
  40889. static sqlite3_vfs winVfs = {
  40890. 3, /* iVersion */
  40891. sizeof(winFile), /* szOsFile */
  40892. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  40893. 0, /* pNext */
  40894. "win32", /* zName */
  40895. &winAppData, /* pAppData */
  40896. winOpen, /* xOpen */
  40897. winDelete, /* xDelete */
  40898. winAccess, /* xAccess */
  40899. winFullPathname, /* xFullPathname */
  40900. winDlOpen, /* xDlOpen */
  40901. winDlError, /* xDlError */
  40902. winDlSym, /* xDlSym */
  40903. winDlClose, /* xDlClose */
  40904. winRandomness, /* xRandomness */
  40905. winSleep, /* xSleep */
  40906. winCurrentTime, /* xCurrentTime */
  40907. winGetLastError, /* xGetLastError */
  40908. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  40909. winSetSystemCall, /* xSetSystemCall */
  40910. winGetSystemCall, /* xGetSystemCall */
  40911. winNextSystemCall, /* xNextSystemCall */
  40912. };
  40913. #if defined(SQLITE_WIN32_HAS_WIDE)
  40914. static sqlite3_vfs winLongPathVfs = {
  40915. 3, /* iVersion */
  40916. sizeof(winFile), /* szOsFile */
  40917. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  40918. 0, /* pNext */
  40919. "win32-longpath", /* zName */
  40920. &winAppData, /* pAppData */
  40921. winOpen, /* xOpen */
  40922. winDelete, /* xDelete */
  40923. winAccess, /* xAccess */
  40924. winFullPathname, /* xFullPathname */
  40925. winDlOpen, /* xDlOpen */
  40926. winDlError, /* xDlError */
  40927. winDlSym, /* xDlSym */
  40928. winDlClose, /* xDlClose */
  40929. winRandomness, /* xRandomness */
  40930. winSleep, /* xSleep */
  40931. winCurrentTime, /* xCurrentTime */
  40932. winGetLastError, /* xGetLastError */
  40933. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  40934. winSetSystemCall, /* xSetSystemCall */
  40935. winGetSystemCall, /* xGetSystemCall */
  40936. winNextSystemCall, /* xNextSystemCall */
  40937. };
  40938. #endif
  40939. static sqlite3_vfs winNolockVfs = {
  40940. 3, /* iVersion */
  40941. sizeof(winFile), /* szOsFile */
  40942. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  40943. 0, /* pNext */
  40944. "win32-none", /* zName */
  40945. &winNolockAppData, /* pAppData */
  40946. winOpen, /* xOpen */
  40947. winDelete, /* xDelete */
  40948. winAccess, /* xAccess */
  40949. winFullPathname, /* xFullPathname */
  40950. winDlOpen, /* xDlOpen */
  40951. winDlError, /* xDlError */
  40952. winDlSym, /* xDlSym */
  40953. winDlClose, /* xDlClose */
  40954. winRandomness, /* xRandomness */
  40955. winSleep, /* xSleep */
  40956. winCurrentTime, /* xCurrentTime */
  40957. winGetLastError, /* xGetLastError */
  40958. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  40959. winSetSystemCall, /* xSetSystemCall */
  40960. winGetSystemCall, /* xGetSystemCall */
  40961. winNextSystemCall, /* xNextSystemCall */
  40962. };
  40963. #if defined(SQLITE_WIN32_HAS_WIDE)
  40964. static sqlite3_vfs winLongPathNolockVfs = {
  40965. 3, /* iVersion */
  40966. sizeof(winFile), /* szOsFile */
  40967. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  40968. 0, /* pNext */
  40969. "win32-longpath-none", /* zName */
  40970. &winNolockAppData, /* pAppData */
  40971. winOpen, /* xOpen */
  40972. winDelete, /* xDelete */
  40973. winAccess, /* xAccess */
  40974. winFullPathname, /* xFullPathname */
  40975. winDlOpen, /* xDlOpen */
  40976. winDlError, /* xDlError */
  40977. winDlSym, /* xDlSym */
  40978. winDlClose, /* xDlClose */
  40979. winRandomness, /* xRandomness */
  40980. winSleep, /* xSleep */
  40981. winCurrentTime, /* xCurrentTime */
  40982. winGetLastError, /* xGetLastError */
  40983. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  40984. winSetSystemCall, /* xSetSystemCall */
  40985. winGetSystemCall, /* xGetSystemCall */
  40986. winNextSystemCall, /* xNextSystemCall */
  40987. };
  40988. #endif
  40989. /* Double-check that the aSyscall[] array has been constructed
  40990. ** correctly. See ticket [bb3a86e890c8e96ab] */
  40991. assert( ArraySize(aSyscall)==80 );
  40992. /* get memory map allocation granularity */
  40993. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  40994. #if SQLITE_OS_WINRT
  40995. osGetNativeSystemInfo(&winSysInfo);
  40996. #else
  40997. osGetSystemInfo(&winSysInfo);
  40998. #endif
  40999. assert( winSysInfo.dwAllocationGranularity>0 );
  41000. assert( winSysInfo.dwPageSize>0 );
  41001. sqlite3_vfs_register(&winVfs, 1);
  41002. #if defined(SQLITE_WIN32_HAS_WIDE)
  41003. sqlite3_vfs_register(&winLongPathVfs, 0);
  41004. #endif
  41005. sqlite3_vfs_register(&winNolockVfs, 0);
  41006. #if defined(SQLITE_WIN32_HAS_WIDE)
  41007. sqlite3_vfs_register(&winLongPathNolockVfs, 0);
  41008. #endif
  41009. return SQLITE_OK;
  41010. }
  41011. SQLITE_API int sqlite3_os_end(void){
  41012. #if SQLITE_OS_WINRT
  41013. if( sleepObj!=NULL ){
  41014. osCloseHandle(sleepObj);
  41015. sleepObj = NULL;
  41016. }
  41017. #endif
  41018. return SQLITE_OK;
  41019. }
  41020. #endif /* SQLITE_OS_WIN */
  41021. /************** End of os_win.c **********************************************/
  41022. /************** Begin file bitvec.c ******************************************/
  41023. /*
  41024. ** 2008 February 16
  41025. **
  41026. ** The author disclaims copyright to this source code. In place of
  41027. ** a legal notice, here is a blessing:
  41028. **
  41029. ** May you do good and not evil.
  41030. ** May you find forgiveness for yourself and forgive others.
  41031. ** May you share freely, never taking more than you give.
  41032. **
  41033. *************************************************************************
  41034. ** This file implements an object that represents a fixed-length
  41035. ** bitmap. Bits are numbered starting with 1.
  41036. **
  41037. ** A bitmap is used to record which pages of a database file have been
  41038. ** journalled during a transaction, or which pages have the "dont-write"
  41039. ** property. Usually only a few pages are meet either condition.
  41040. ** So the bitmap is usually sparse and has low cardinality.
  41041. ** But sometimes (for example when during a DROP of a large table) most
  41042. ** or all of the pages in a database can get journalled. In those cases,
  41043. ** the bitmap becomes dense with high cardinality. The algorithm needs
  41044. ** to handle both cases well.
  41045. **
  41046. ** The size of the bitmap is fixed when the object is created.
  41047. **
  41048. ** All bits are clear when the bitmap is created. Individual bits
  41049. ** may be set or cleared one at a time.
  41050. **
  41051. ** Test operations are about 100 times more common that set operations.
  41052. ** Clear operations are exceedingly rare. There are usually between
  41053. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  41054. ** sometimes grow into tens of thousands or larger. The size of the
  41055. ** Bitvec object is the number of pages in the database file at the
  41056. ** start of a transaction, and is thus usually less than a few thousand,
  41057. ** but can be as large as 2 billion for a really big database.
  41058. */
  41059. /* #include "sqliteInt.h" */
  41060. /* Size of the Bitvec structure in bytes. */
  41061. #define BITVEC_SZ 512
  41062. /* Round the union size down to the nearest pointer boundary, since that's how
  41063. ** it will be aligned within the Bitvec struct. */
  41064. #define BITVEC_USIZE \
  41065. (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  41066. /* Type of the array "element" for the bitmap representation.
  41067. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  41068. ** Setting this to the "natural word" size of your CPU may improve
  41069. ** performance. */
  41070. #define BITVEC_TELEM u8
  41071. /* Size, in bits, of the bitmap element. */
  41072. #define BITVEC_SZELEM 8
  41073. /* Number of elements in a bitmap array. */
  41074. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  41075. /* Number of bits in the bitmap array. */
  41076. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  41077. /* Number of u32 values in hash table. */
  41078. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  41079. /* Maximum number of entries in hash table before
  41080. ** sub-dividing and re-hashing. */
  41081. #define BITVEC_MXHASH (BITVEC_NINT/2)
  41082. /* Hashing function for the aHash representation.
  41083. ** Empirical testing showed that the *37 multiplier
  41084. ** (an arbitrary prime)in the hash function provided
  41085. ** no fewer collisions than the no-op *1. */
  41086. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  41087. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  41088. /*
  41089. ** A bitmap is an instance of the following structure.
  41090. **
  41091. ** This bitmap records the existence of zero or more bits
  41092. ** with values between 1 and iSize, inclusive.
  41093. **
  41094. ** There are three possible representations of the bitmap.
  41095. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  41096. ** bitmap. The least significant bit is bit 1.
  41097. **
  41098. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  41099. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  41100. **
  41101. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  41102. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  41103. ** handles up to iDivisor separate values of i. apSub[0] holds
  41104. ** values between 1 and iDivisor. apSub[1] holds values between
  41105. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  41106. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  41107. ** to hold deal with values between 1 and iDivisor.
  41108. */
  41109. struct Bitvec {
  41110. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  41111. u32 nSet; /* Number of bits that are set - only valid for aHash
  41112. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  41113. ** this would be 125. */
  41114. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  41115. /* Should >=0 for apSub element. */
  41116. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  41117. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  41118. union {
  41119. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  41120. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  41121. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  41122. } u;
  41123. };
  41124. /*
  41125. ** Create a new bitmap object able to handle bits between 0 and iSize,
  41126. ** inclusive. Return a pointer to the new object. Return NULL if
  41127. ** malloc fails.
  41128. */
  41129. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  41130. Bitvec *p;
  41131. assert( sizeof(*p)==BITVEC_SZ );
  41132. p = sqlite3MallocZero( sizeof(*p) );
  41133. if( p ){
  41134. p->iSize = iSize;
  41135. }
  41136. return p;
  41137. }
  41138. /*
  41139. ** Check to see if the i-th bit is set. Return true or false.
  41140. ** If p is NULL (if the bitmap has not been created) or if
  41141. ** i is out of range, then return false.
  41142. */
  41143. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
  41144. assert( p!=0 );
  41145. i--;
  41146. if( i>=p->iSize ) return 0;
  41147. while( p->iDivisor ){
  41148. u32 bin = i/p->iDivisor;
  41149. i = i%p->iDivisor;
  41150. p = p->u.apSub[bin];
  41151. if (!p) {
  41152. return 0;
  41153. }
  41154. }
  41155. if( p->iSize<=BITVEC_NBIT ){
  41156. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  41157. } else{
  41158. u32 h = BITVEC_HASH(i++);
  41159. while( p->u.aHash[h] ){
  41160. if( p->u.aHash[h]==i ) return 1;
  41161. h = (h+1) % BITVEC_NINT;
  41162. }
  41163. return 0;
  41164. }
  41165. }
  41166. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  41167. return p!=0 && sqlite3BitvecTestNotNull(p,i);
  41168. }
  41169. /*
  41170. ** Set the i-th bit. Return 0 on success and an error code if
  41171. ** anything goes wrong.
  41172. **
  41173. ** This routine might cause sub-bitmaps to be allocated. Failing
  41174. ** to get the memory needed to hold the sub-bitmap is the only
  41175. ** that can go wrong with an insert, assuming p and i are valid.
  41176. **
  41177. ** The calling function must ensure that p is a valid Bitvec object
  41178. ** and that the value for "i" is within range of the Bitvec object.
  41179. ** Otherwise the behavior is undefined.
  41180. */
  41181. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  41182. u32 h;
  41183. if( p==0 ) return SQLITE_OK;
  41184. assert( i>0 );
  41185. assert( i<=p->iSize );
  41186. i--;
  41187. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  41188. u32 bin = i/p->iDivisor;
  41189. i = i%p->iDivisor;
  41190. if( p->u.apSub[bin]==0 ){
  41191. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  41192. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
  41193. }
  41194. p = p->u.apSub[bin];
  41195. }
  41196. if( p->iSize<=BITVEC_NBIT ){
  41197. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  41198. return SQLITE_OK;
  41199. }
  41200. h = BITVEC_HASH(i++);
  41201. /* if there wasn't a hash collision, and this doesn't */
  41202. /* completely fill the hash, then just add it without */
  41203. /* worring about sub-dividing and re-hashing. */
  41204. if( !p->u.aHash[h] ){
  41205. if (p->nSet<(BITVEC_NINT-1)) {
  41206. goto bitvec_set_end;
  41207. } else {
  41208. goto bitvec_set_rehash;
  41209. }
  41210. }
  41211. /* there was a collision, check to see if it's already */
  41212. /* in hash, if not, try to find a spot for it */
  41213. do {
  41214. if( p->u.aHash[h]==i ) return SQLITE_OK;
  41215. h++;
  41216. if( h>=BITVEC_NINT ) h = 0;
  41217. } while( p->u.aHash[h] );
  41218. /* we didn't find it in the hash. h points to the first */
  41219. /* available free spot. check to see if this is going to */
  41220. /* make our hash too "full". */
  41221. bitvec_set_rehash:
  41222. if( p->nSet>=BITVEC_MXHASH ){
  41223. unsigned int j;
  41224. int rc;
  41225. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  41226. if( aiValues==0 ){
  41227. return SQLITE_NOMEM_BKPT;
  41228. }else{
  41229. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  41230. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  41231. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  41232. rc = sqlite3BitvecSet(p, i);
  41233. for(j=0; j<BITVEC_NINT; j++){
  41234. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  41235. }
  41236. sqlite3StackFree(0, aiValues);
  41237. return rc;
  41238. }
  41239. }
  41240. bitvec_set_end:
  41241. p->nSet++;
  41242. p->u.aHash[h] = i;
  41243. return SQLITE_OK;
  41244. }
  41245. /*
  41246. ** Clear the i-th bit.
  41247. **
  41248. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  41249. ** that BitvecClear can use to rebuilt its hash table.
  41250. */
  41251. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  41252. if( p==0 ) return;
  41253. assert( i>0 );
  41254. i--;
  41255. while( p->iDivisor ){
  41256. u32 bin = i/p->iDivisor;
  41257. i = i%p->iDivisor;
  41258. p = p->u.apSub[bin];
  41259. if (!p) {
  41260. return;
  41261. }
  41262. }
  41263. if( p->iSize<=BITVEC_NBIT ){
  41264. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  41265. }else{
  41266. unsigned int j;
  41267. u32 *aiValues = pBuf;
  41268. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  41269. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  41270. p->nSet = 0;
  41271. for(j=0; j<BITVEC_NINT; j++){
  41272. if( aiValues[j] && aiValues[j]!=(i+1) ){
  41273. u32 h = BITVEC_HASH(aiValues[j]-1);
  41274. p->nSet++;
  41275. while( p->u.aHash[h] ){
  41276. h++;
  41277. if( h>=BITVEC_NINT ) h = 0;
  41278. }
  41279. p->u.aHash[h] = aiValues[j];
  41280. }
  41281. }
  41282. }
  41283. }
  41284. /*
  41285. ** Destroy a bitmap object. Reclaim all memory used.
  41286. */
  41287. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  41288. if( p==0 ) return;
  41289. if( p->iDivisor ){
  41290. unsigned int i;
  41291. for(i=0; i<BITVEC_NPTR; i++){
  41292. sqlite3BitvecDestroy(p->u.apSub[i]);
  41293. }
  41294. }
  41295. sqlite3_free(p);
  41296. }
  41297. /*
  41298. ** Return the value of the iSize parameter specified when Bitvec *p
  41299. ** was created.
  41300. */
  41301. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  41302. return p->iSize;
  41303. }
  41304. #ifndef SQLITE_UNTESTABLE
  41305. /*
  41306. ** Let V[] be an array of unsigned characters sufficient to hold
  41307. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  41308. ** Then the following macros can be used to set, clear, or test
  41309. ** individual bits within V.
  41310. */
  41311. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  41312. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  41313. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  41314. /*
  41315. ** This routine runs an extensive test of the Bitvec code.
  41316. **
  41317. ** The input is an array of integers that acts as a program
  41318. ** to test the Bitvec. The integers are opcodes followed
  41319. ** by 0, 1, or 3 operands, depending on the opcode. Another
  41320. ** opcode follows immediately after the last operand.
  41321. **
  41322. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  41323. ** "halt" opcode and causes the test to end.
  41324. **
  41325. ** 0 Halt and return the number of errors
  41326. ** 1 N S X Set N bits beginning with S and incrementing by X
  41327. ** 2 N S X Clear N bits beginning with S and incrementing by X
  41328. ** 3 N Set N randomly chosen bits
  41329. ** 4 N Clear N randomly chosen bits
  41330. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  41331. **
  41332. ** The opcodes 1 through 4 perform set and clear operations are performed
  41333. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  41334. ** Opcode 5 works on the linear array only, not on the Bitvec.
  41335. ** Opcode 5 is used to deliberately induce a fault in order to
  41336. ** confirm that error detection works.
  41337. **
  41338. ** At the conclusion of the test the linear array is compared
  41339. ** against the Bitvec object. If there are any differences,
  41340. ** an error is returned. If they are the same, zero is returned.
  41341. **
  41342. ** If a memory allocation error occurs, return -1.
  41343. */
  41344. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  41345. Bitvec *pBitvec = 0;
  41346. unsigned char *pV = 0;
  41347. int rc = -1;
  41348. int i, nx, pc, op;
  41349. void *pTmpSpace;
  41350. /* Allocate the Bitvec to be tested and a linear array of
  41351. ** bits to act as the reference */
  41352. pBitvec = sqlite3BitvecCreate( sz );
  41353. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  41354. pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
  41355. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  41356. /* NULL pBitvec tests */
  41357. sqlite3BitvecSet(0, 1);
  41358. sqlite3BitvecClear(0, 1, pTmpSpace);
  41359. /* Run the program */
  41360. pc = 0;
  41361. while( (op = aOp[pc])!=0 ){
  41362. switch( op ){
  41363. case 1:
  41364. case 2:
  41365. case 5: {
  41366. nx = 4;
  41367. i = aOp[pc+2] - 1;
  41368. aOp[pc+2] += aOp[pc+3];
  41369. break;
  41370. }
  41371. case 3:
  41372. case 4:
  41373. default: {
  41374. nx = 2;
  41375. sqlite3_randomness(sizeof(i), &i);
  41376. break;
  41377. }
  41378. }
  41379. if( (--aOp[pc+1]) > 0 ) nx = 0;
  41380. pc += nx;
  41381. i = (i & 0x7fffffff)%sz;
  41382. if( (op & 1)!=0 ){
  41383. SETBIT(pV, (i+1));
  41384. if( op!=5 ){
  41385. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  41386. }
  41387. }else{
  41388. CLEARBIT(pV, (i+1));
  41389. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  41390. }
  41391. }
  41392. /* Test to make sure the linear array exactly matches the
  41393. ** Bitvec object. Start with the assumption that they do
  41394. ** match (rc==0). Change rc to non-zero if a discrepancy
  41395. ** is found.
  41396. */
  41397. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  41398. + sqlite3BitvecTest(pBitvec, 0)
  41399. + (sqlite3BitvecSize(pBitvec) - sz);
  41400. for(i=1; i<=sz; i++){
  41401. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  41402. rc = i;
  41403. break;
  41404. }
  41405. }
  41406. /* Free allocated structure */
  41407. bitvec_end:
  41408. sqlite3_free(pTmpSpace);
  41409. sqlite3_free(pV);
  41410. sqlite3BitvecDestroy(pBitvec);
  41411. return rc;
  41412. }
  41413. #endif /* SQLITE_UNTESTABLE */
  41414. /************** End of bitvec.c **********************************************/
  41415. /************** Begin file pcache.c ******************************************/
  41416. /*
  41417. ** 2008 August 05
  41418. **
  41419. ** The author disclaims copyright to this source code. In place of
  41420. ** a legal notice, here is a blessing:
  41421. **
  41422. ** May you do good and not evil.
  41423. ** May you find forgiveness for yourself and forgive others.
  41424. ** May you share freely, never taking more than you give.
  41425. **
  41426. *************************************************************************
  41427. ** This file implements that page cache.
  41428. */
  41429. /* #include "sqliteInt.h" */
  41430. /*
  41431. ** A complete page cache is an instance of this structure. Every
  41432. ** entry in the cache holds a single page of the database file. The
  41433. ** btree layer only operates on the cached copy of the database pages.
  41434. **
  41435. ** A page cache entry is "clean" if it exactly matches what is currently
  41436. ** on disk. A page is "dirty" if it has been modified and needs to be
  41437. ** persisted to disk.
  41438. **
  41439. ** pDirty, pDirtyTail, pSynced:
  41440. ** All dirty pages are linked into the doubly linked list using
  41441. ** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
  41442. ** such that p was added to the list more recently than p->pDirtyNext.
  41443. ** PCache.pDirty points to the first (newest) element in the list and
  41444. ** pDirtyTail to the last (oldest).
  41445. **
  41446. ** The PCache.pSynced variable is used to optimize searching for a dirty
  41447. ** page to eject from the cache mid-transaction. It is better to eject
  41448. ** a page that does not require a journal sync than one that does.
  41449. ** Therefore, pSynced is maintained to that it *almost* always points
  41450. ** to either the oldest page in the pDirty/pDirtyTail list that has a
  41451. ** clear PGHDR_NEED_SYNC flag or to a page that is older than this one
  41452. ** (so that the right page to eject can be found by following pDirtyPrev
  41453. ** pointers).
  41454. */
  41455. struct PCache {
  41456. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  41457. PgHdr *pSynced; /* Last synced page in dirty page list */
  41458. int nRefSum; /* Sum of ref counts over all pages */
  41459. int szCache; /* Configured cache size */
  41460. int szSpill; /* Size before spilling occurs */
  41461. int szPage; /* Size of every page in this cache */
  41462. int szExtra; /* Size of extra space for each page */
  41463. u8 bPurgeable; /* True if pages are on backing store */
  41464. u8 eCreate; /* eCreate value for for xFetch() */
  41465. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  41466. void *pStress; /* Argument to xStress */
  41467. sqlite3_pcache *pCache; /* Pluggable cache module */
  41468. };
  41469. /********************************** Test and Debug Logic **********************/
  41470. /*
  41471. ** Debug tracing macros. Enable by by changing the "0" to "1" and
  41472. ** recompiling.
  41473. **
  41474. ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
  41475. ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
  41476. ** is displayed for many operations, resulting in a lot of output.
  41477. */
  41478. #if defined(SQLITE_DEBUG) && 0
  41479. int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */
  41480. int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */
  41481. # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
  41482. void pcacheDump(PCache *pCache){
  41483. int N;
  41484. int i, j;
  41485. sqlite3_pcache_page *pLower;
  41486. PgHdr *pPg;
  41487. unsigned char *a;
  41488. if( sqlite3PcacheTrace<2 ) return;
  41489. if( pCache->pCache==0 ) return;
  41490. N = sqlite3PcachePagecount(pCache);
  41491. if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
  41492. for(i=1; i<=N; i++){
  41493. pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
  41494. if( pLower==0 ) continue;
  41495. pPg = (PgHdr*)pLower->pExtra;
  41496. printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
  41497. a = (unsigned char *)pLower->pBuf;
  41498. for(j=0; j<12; j++) printf("%02x", a[j]);
  41499. printf("\n");
  41500. if( pPg->pPage==0 ){
  41501. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
  41502. }
  41503. }
  41504. }
  41505. #else
  41506. # define pcacheTrace(X)
  41507. # define pcacheDump(X)
  41508. #endif
  41509. /*
  41510. ** Check invariants on a PgHdr entry. Return true if everything is OK.
  41511. ** Return false if any invariant is violated.
  41512. **
  41513. ** This routine is for use inside of assert() statements only. For
  41514. ** example:
  41515. **
  41516. ** assert( sqlite3PcachePageSanity(pPg) );
  41517. */
  41518. #ifdef SQLITE_DEBUG
  41519. SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
  41520. PCache *pCache;
  41521. assert( pPg!=0 );
  41522. assert( pPg->pgno>0 || pPg->pPager==0 ); /* Page number is 1 or more */
  41523. pCache = pPg->pCache;
  41524. assert( pCache!=0 ); /* Every page has an associated PCache */
  41525. if( pPg->flags & PGHDR_CLEAN ){
  41526. assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
  41527. assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */
  41528. assert( pCache->pDirtyTail!=pPg );
  41529. }
  41530. /* WRITEABLE pages must also be DIRTY */
  41531. if( pPg->flags & PGHDR_WRITEABLE ){
  41532. assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
  41533. }
  41534. /* NEED_SYNC can be set independently of WRITEABLE. This can happen,
  41535. ** for example, when using the sqlite3PagerDontWrite() optimization:
  41536. ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK.
  41537. ** (2) Page X moved to freelist, WRITEABLE is cleared
  41538. ** (3) Page X reused, WRITEABLE is set again
  41539. ** If NEED_SYNC had been cleared in step 2, then it would not be reset
  41540. ** in step 3, and page might be written into the database without first
  41541. ** syncing the rollback journal, which might cause corruption on a power
  41542. ** loss.
  41543. **
  41544. ** Another example is when the database page size is smaller than the
  41545. ** disk sector size. When any page of a sector is journalled, all pages
  41546. ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
  41547. ** in case they are later modified, since all pages in the same sector
  41548. ** must be journalled and synced before any of those pages can be safely
  41549. ** written.
  41550. */
  41551. return 1;
  41552. }
  41553. #endif /* SQLITE_DEBUG */
  41554. /********************************** Linked List Management ********************/
  41555. /* Allowed values for second argument to pcacheManageDirtyList() */
  41556. #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
  41557. #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
  41558. #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
  41559. /*
  41560. ** Manage pPage's participation on the dirty list. Bits of the addRemove
  41561. ** argument determines what operation to do. The 0x01 bit means first
  41562. ** remove pPage from the dirty list. The 0x02 means add pPage back to
  41563. ** the dirty list. Doing both moves pPage to the front of the dirty list.
  41564. */
  41565. static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
  41566. PCache *p = pPage->pCache;
  41567. pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
  41568. addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
  41569. pPage->pgno));
  41570. if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
  41571. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  41572. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  41573. /* Update the PCache1.pSynced variable if necessary. */
  41574. if( p->pSynced==pPage ){
  41575. p->pSynced = pPage->pDirtyPrev;
  41576. }
  41577. if( pPage->pDirtyNext ){
  41578. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  41579. }else{
  41580. assert( pPage==p->pDirtyTail );
  41581. p->pDirtyTail = pPage->pDirtyPrev;
  41582. }
  41583. if( pPage->pDirtyPrev ){
  41584. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  41585. }else{
  41586. /* If there are now no dirty pages in the cache, set eCreate to 2.
  41587. ** This is an optimization that allows sqlite3PcacheFetch() to skip
  41588. ** searching for a dirty page to eject from the cache when it might
  41589. ** otherwise have to. */
  41590. assert( pPage==p->pDirty );
  41591. p->pDirty = pPage->pDirtyNext;
  41592. assert( p->bPurgeable || p->eCreate==2 );
  41593. if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
  41594. assert( p->bPurgeable==0 || p->eCreate==1 );
  41595. p->eCreate = 2;
  41596. }
  41597. }
  41598. pPage->pDirtyNext = 0;
  41599. pPage->pDirtyPrev = 0;
  41600. }
  41601. if( addRemove & PCACHE_DIRTYLIST_ADD ){
  41602. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  41603. pPage->pDirtyNext = p->pDirty;
  41604. if( pPage->pDirtyNext ){
  41605. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  41606. pPage->pDirtyNext->pDirtyPrev = pPage;
  41607. }else{
  41608. p->pDirtyTail = pPage;
  41609. if( p->bPurgeable ){
  41610. assert( p->eCreate==2 );
  41611. p->eCreate = 1;
  41612. }
  41613. }
  41614. p->pDirty = pPage;
  41615. /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
  41616. ** pSynced to point to it. Checking the NEED_SYNC flag is an
  41617. ** optimization, as if pSynced points to a page with the NEED_SYNC
  41618. ** flag set sqlite3PcacheFetchStress() searches through all newer
  41619. ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
  41620. if( !p->pSynced
  41621. && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
  41622. ){
  41623. p->pSynced = pPage;
  41624. }
  41625. }
  41626. pcacheDump(p);
  41627. }
  41628. /*
  41629. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  41630. ** being used for an in-memory database, this function is a no-op.
  41631. */
  41632. static void pcacheUnpin(PgHdr *p){
  41633. if( p->pCache->bPurgeable ){
  41634. pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
  41635. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
  41636. pcacheDump(p->pCache);
  41637. }
  41638. }
  41639. /*
  41640. ** Compute the number of pages of cache requested. p->szCache is the
  41641. ** cache size requested by the "PRAGMA cache_size" statement.
  41642. */
  41643. static int numberOfCachePages(PCache *p){
  41644. if( p->szCache>=0 ){
  41645. /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
  41646. ** suggested cache size is set to N. */
  41647. return p->szCache;
  41648. }else{
  41649. /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
  41650. ** the number of cache pages is adjusted to use approximately abs(N*1024)
  41651. ** bytes of memory. */
  41652. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  41653. }
  41654. }
  41655. /*************************************************** General Interfaces ******
  41656. **
  41657. ** Initialize and shutdown the page cache subsystem. Neither of these
  41658. ** functions are threadsafe.
  41659. */
  41660. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  41661. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  41662. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  41663. ** built-in default page cache is used instead of the application defined
  41664. ** page cache. */
  41665. sqlite3PCacheSetDefault();
  41666. }
  41667. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  41668. }
  41669. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  41670. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  41671. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  41672. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  41673. }
  41674. }
  41675. /*
  41676. ** Return the size in bytes of a PCache object.
  41677. */
  41678. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  41679. /*
  41680. ** Create a new PCache object. Storage space to hold the object
  41681. ** has already been allocated and is passed in as the p pointer.
  41682. ** The caller discovers how much space needs to be allocated by
  41683. ** calling sqlite3PcacheSize().
  41684. **
  41685. ** szExtra is some extra space allocated for each page. The first
  41686. ** 8 bytes of the extra space will be zeroed as the page is allocated,
  41687. ** but remaining content will be uninitialized. Though it is opaque
  41688. ** to this module, the extra space really ends up being the MemPage
  41689. ** structure in the pager.
  41690. */
  41691. SQLITE_PRIVATE int sqlite3PcacheOpen(
  41692. int szPage, /* Size of every page */
  41693. int szExtra, /* Extra space associated with each page */
  41694. int bPurgeable, /* True if pages are on backing store */
  41695. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  41696. void *pStress, /* Argument to xStress */
  41697. PCache *p /* Preallocated space for the PCache */
  41698. ){
  41699. memset(p, 0, sizeof(PCache));
  41700. p->szPage = 1;
  41701. p->szExtra = szExtra;
  41702. assert( szExtra>=8 ); /* First 8 bytes will be zeroed */
  41703. p->bPurgeable = bPurgeable;
  41704. p->eCreate = 2;
  41705. p->xStress = xStress;
  41706. p->pStress = pStress;
  41707. p->szCache = 100;
  41708. p->szSpill = 1;
  41709. pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
  41710. return sqlite3PcacheSetPageSize(p, szPage);
  41711. }
  41712. /*
  41713. ** Change the page size for PCache object. The caller must ensure that there
  41714. ** are no outstanding page references when this function is called.
  41715. */
  41716. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  41717. assert( pCache->nRefSum==0 && pCache->pDirty==0 );
  41718. if( pCache->szPage ){
  41719. sqlite3_pcache *pNew;
  41720. pNew = sqlite3GlobalConfig.pcache2.xCreate(
  41721. szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
  41722. pCache->bPurgeable
  41723. );
  41724. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  41725. sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
  41726. if( pCache->pCache ){
  41727. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  41728. }
  41729. pCache->pCache = pNew;
  41730. pCache->szPage = szPage;
  41731. pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
  41732. }
  41733. return SQLITE_OK;
  41734. }
  41735. /*
  41736. ** Try to obtain a page from the cache.
  41737. **
  41738. ** This routine returns a pointer to an sqlite3_pcache_page object if
  41739. ** such an object is already in cache, or if a new one is created.
  41740. ** This routine returns a NULL pointer if the object was not in cache
  41741. ** and could not be created.
  41742. **
  41743. ** The createFlags should be 0 to check for existing pages and should
  41744. ** be 3 (not 1, but 3) to try to create a new page.
  41745. **
  41746. ** If the createFlag is 0, then NULL is always returned if the page
  41747. ** is not already in the cache. If createFlag is 1, then a new page
  41748. ** is created only if that can be done without spilling dirty pages
  41749. ** and without exceeding the cache size limit.
  41750. **
  41751. ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
  41752. ** initialize the sqlite3_pcache_page object and convert it into a
  41753. ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
  41754. ** routines are split this way for performance reasons. When separated
  41755. ** they can both (usually) operate without having to push values to
  41756. ** the stack on entry and pop them back off on exit, which saves a
  41757. ** lot of pushing and popping.
  41758. */
  41759. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
  41760. PCache *pCache, /* Obtain the page from this cache */
  41761. Pgno pgno, /* Page number to obtain */
  41762. int createFlag /* If true, create page if it does not exist already */
  41763. ){
  41764. int eCreate;
  41765. sqlite3_pcache_page *pRes;
  41766. assert( pCache!=0 );
  41767. assert( pCache->pCache!=0 );
  41768. assert( createFlag==3 || createFlag==0 );
  41769. assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
  41770. /* eCreate defines what to do if the page does not exist.
  41771. ** 0 Do not allocate a new page. (createFlag==0)
  41772. ** 1 Allocate a new page if doing so is inexpensive.
  41773. ** (createFlag==1 AND bPurgeable AND pDirty)
  41774. ** 2 Allocate a new page even it doing so is difficult.
  41775. ** (createFlag==1 AND !(bPurgeable AND pDirty)
  41776. */
  41777. eCreate = createFlag & pCache->eCreate;
  41778. assert( eCreate==0 || eCreate==1 || eCreate==2 );
  41779. assert( createFlag==0 || pCache->eCreate==eCreate );
  41780. assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
  41781. pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  41782. pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
  41783. createFlag?" create":"",pRes));
  41784. return pRes;
  41785. }
  41786. /*
  41787. ** If the sqlite3PcacheFetch() routine is unable to allocate a new
  41788. ** page because no clean pages are available for reuse and the cache
  41789. ** size limit has been reached, then this routine can be invoked to
  41790. ** try harder to allocate a page. This routine might invoke the stress
  41791. ** callback to spill dirty pages to the journal. It will then try to
  41792. ** allocate the new page and will only fail to allocate a new page on
  41793. ** an OOM error.
  41794. **
  41795. ** This routine should be invoked only after sqlite3PcacheFetch() fails.
  41796. */
  41797. SQLITE_PRIVATE int sqlite3PcacheFetchStress(
  41798. PCache *pCache, /* Obtain the page from this cache */
  41799. Pgno pgno, /* Page number to obtain */
  41800. sqlite3_pcache_page **ppPage /* Write result here */
  41801. ){
  41802. PgHdr *pPg;
  41803. if( pCache->eCreate==2 ) return 0;
  41804. if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
  41805. /* Find a dirty page to write-out and recycle. First try to find a
  41806. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  41807. ** cleared), but if that is not possible settle for any other
  41808. ** unreferenced dirty page.
  41809. **
  41810. ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
  41811. ** flag is currently referenced, then the following may leave pSynced
  41812. ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
  41813. ** cleared). This is Ok, as pSynced is just an optimization. */
  41814. for(pPg=pCache->pSynced;
  41815. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  41816. pPg=pPg->pDirtyPrev
  41817. );
  41818. pCache->pSynced = pPg;
  41819. if( !pPg ){
  41820. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  41821. }
  41822. if( pPg ){
  41823. int rc;
  41824. #ifdef SQLITE_LOG_CACHE_SPILL
  41825. sqlite3_log(SQLITE_FULL,
  41826. "spill page %d making room for %d - cache used: %d/%d",
  41827. pPg->pgno, pgno,
  41828. sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
  41829. numberOfCachePages(pCache));
  41830. #endif
  41831. pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
  41832. rc = pCache->xStress(pCache->pStress, pPg);
  41833. pcacheDump(pCache);
  41834. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  41835. return rc;
  41836. }
  41837. }
  41838. }
  41839. *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  41840. return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  41841. }
  41842. /*
  41843. ** This is a helper routine for sqlite3PcacheFetchFinish()
  41844. **
  41845. ** In the uncommon case where the page being fetched has not been
  41846. ** initialized, this routine is invoked to do the initialization.
  41847. ** This routine is broken out into a separate function since it
  41848. ** requires extra stack manipulation that can be avoided in the common
  41849. ** case.
  41850. */
  41851. static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
  41852. PCache *pCache, /* Obtain the page from this cache */
  41853. Pgno pgno, /* Page number obtained */
  41854. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  41855. ){
  41856. PgHdr *pPgHdr;
  41857. assert( pPage!=0 );
  41858. pPgHdr = (PgHdr*)pPage->pExtra;
  41859. assert( pPgHdr->pPage==0 );
  41860. memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
  41861. pPgHdr->pPage = pPage;
  41862. pPgHdr->pData = pPage->pBuf;
  41863. pPgHdr->pExtra = (void *)&pPgHdr[1];
  41864. memset(pPgHdr->pExtra, 0, 8);
  41865. pPgHdr->pCache = pCache;
  41866. pPgHdr->pgno = pgno;
  41867. pPgHdr->flags = PGHDR_CLEAN;
  41868. return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
  41869. }
  41870. /*
  41871. ** This routine converts the sqlite3_pcache_page object returned by
  41872. ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
  41873. ** must be called after sqlite3PcacheFetch() in order to get a usable
  41874. ** result.
  41875. */
  41876. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
  41877. PCache *pCache, /* Obtain the page from this cache */
  41878. Pgno pgno, /* Page number obtained */
  41879. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  41880. ){
  41881. PgHdr *pPgHdr;
  41882. assert( pPage!=0 );
  41883. pPgHdr = (PgHdr *)pPage->pExtra;
  41884. if( !pPgHdr->pPage ){
  41885. return pcacheFetchFinishWithInit(pCache, pgno, pPage);
  41886. }
  41887. pCache->nRefSum++;
  41888. pPgHdr->nRef++;
  41889. assert( sqlite3PcachePageSanity(pPgHdr) );
  41890. return pPgHdr;
  41891. }
  41892. /*
  41893. ** Decrement the reference count on a page. If the page is clean and the
  41894. ** reference count drops to 0, then it is made eligible for recycling.
  41895. */
  41896. SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
  41897. assert( p->nRef>0 );
  41898. p->pCache->nRefSum--;
  41899. if( (--p->nRef)==0 ){
  41900. if( p->flags&PGHDR_CLEAN ){
  41901. pcacheUnpin(p);
  41902. }else if( p->pDirtyPrev!=0 ){ /*OPTIMIZATION-IF-FALSE*/
  41903. /* Move the page to the head of the dirty list. If p->pDirtyPrev==0,
  41904. ** then page p is already at the head of the dirty list and the
  41905. ** following call would be a no-op. Hence the OPTIMIZATION-IF-FALSE
  41906. ** tag above. */
  41907. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  41908. }
  41909. }
  41910. }
  41911. /*
  41912. ** Increase the reference count of a supplied page by 1.
  41913. */
  41914. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  41915. assert(p->nRef>0);
  41916. assert( sqlite3PcachePageSanity(p) );
  41917. p->nRef++;
  41918. p->pCache->nRefSum++;
  41919. }
  41920. /*
  41921. ** Drop a page from the cache. There must be exactly one reference to the
  41922. ** page. This function deletes that reference, so after it returns the
  41923. ** page pointed to by p is invalid.
  41924. */
  41925. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  41926. assert( p->nRef==1 );
  41927. assert( sqlite3PcachePageSanity(p) );
  41928. if( p->flags&PGHDR_DIRTY ){
  41929. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  41930. }
  41931. p->pCache->nRefSum--;
  41932. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
  41933. }
  41934. /*
  41935. ** Make sure the page is marked as dirty. If it isn't dirty already,
  41936. ** make it so.
  41937. */
  41938. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  41939. assert( p->nRef>0 );
  41940. assert( sqlite3PcachePageSanity(p) );
  41941. if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
  41942. p->flags &= ~PGHDR_DONT_WRITE;
  41943. if( p->flags & PGHDR_CLEAN ){
  41944. p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
  41945. pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
  41946. assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
  41947. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
  41948. }
  41949. assert( sqlite3PcachePageSanity(p) );
  41950. }
  41951. }
  41952. /*
  41953. ** Make sure the page is marked as clean. If it isn't clean already,
  41954. ** make it so.
  41955. */
  41956. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  41957. assert( sqlite3PcachePageSanity(p) );
  41958. if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){
  41959. assert( (p->flags & PGHDR_CLEAN)==0 );
  41960. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  41961. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  41962. p->flags |= PGHDR_CLEAN;
  41963. pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
  41964. assert( sqlite3PcachePageSanity(p) );
  41965. if( p->nRef==0 ){
  41966. pcacheUnpin(p);
  41967. }
  41968. }
  41969. }
  41970. /*
  41971. ** Make every page in the cache clean.
  41972. */
  41973. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  41974. PgHdr *p;
  41975. pcacheTrace(("%p.CLEAN-ALL\n",pCache));
  41976. while( (p = pCache->pDirty)!=0 ){
  41977. sqlite3PcacheMakeClean(p);
  41978. }
  41979. }
  41980. /*
  41981. ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
  41982. */
  41983. SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
  41984. PgHdr *p;
  41985. pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
  41986. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  41987. p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  41988. }
  41989. pCache->pSynced = pCache->pDirtyTail;
  41990. }
  41991. /*
  41992. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  41993. */
  41994. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  41995. PgHdr *p;
  41996. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  41997. p->flags &= ~PGHDR_NEED_SYNC;
  41998. }
  41999. pCache->pSynced = pCache->pDirtyTail;
  42000. }
  42001. /*
  42002. ** Change the page number of page p to newPgno.
  42003. */
  42004. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  42005. PCache *pCache = p->pCache;
  42006. assert( p->nRef>0 );
  42007. assert( newPgno>0 );
  42008. assert( sqlite3PcachePageSanity(p) );
  42009. pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
  42010. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  42011. p->pgno = newPgno;
  42012. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  42013. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  42014. }
  42015. }
  42016. /*
  42017. ** Drop every cache entry whose page number is greater than "pgno". The
  42018. ** caller must ensure that there are no outstanding references to any pages
  42019. ** other than page 1 with a page number greater than pgno.
  42020. **
  42021. ** If there is a reference to page 1 and the pgno parameter passed to this
  42022. ** function is 0, then the data area associated with page 1 is zeroed, but
  42023. ** the page object is not dropped.
  42024. */
  42025. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  42026. if( pCache->pCache ){
  42027. PgHdr *p;
  42028. PgHdr *pNext;
  42029. pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
  42030. for(p=pCache->pDirty; p; p=pNext){
  42031. pNext = p->pDirtyNext;
  42032. /* This routine never gets call with a positive pgno except right
  42033. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  42034. ** it must be that pgno==0.
  42035. */
  42036. assert( p->pgno>0 );
  42037. if( p->pgno>pgno ){
  42038. assert( p->flags&PGHDR_DIRTY );
  42039. sqlite3PcacheMakeClean(p);
  42040. }
  42041. }
  42042. if( pgno==0 && pCache->nRefSum ){
  42043. sqlite3_pcache_page *pPage1;
  42044. pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
  42045. if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
  42046. ** pCache->nRefSum>0 */
  42047. memset(pPage1->pBuf, 0, pCache->szPage);
  42048. pgno = 1;
  42049. }
  42050. }
  42051. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  42052. }
  42053. }
  42054. /*
  42055. ** Close a cache.
  42056. */
  42057. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  42058. assert( pCache->pCache!=0 );
  42059. pcacheTrace(("%p.CLOSE\n",pCache));
  42060. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  42061. }
  42062. /*
  42063. ** Discard the contents of the cache.
  42064. */
  42065. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  42066. sqlite3PcacheTruncate(pCache, 0);
  42067. }
  42068. /*
  42069. ** Merge two lists of pages connected by pDirty and in pgno order.
  42070. ** Do not bother fixing the pDirtyPrev pointers.
  42071. */
  42072. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  42073. PgHdr result, *pTail;
  42074. pTail = &result;
  42075. assert( pA!=0 && pB!=0 );
  42076. for(;;){
  42077. if( pA->pgno<pB->pgno ){
  42078. pTail->pDirty = pA;
  42079. pTail = pA;
  42080. pA = pA->pDirty;
  42081. if( pA==0 ){
  42082. pTail->pDirty = pB;
  42083. break;
  42084. }
  42085. }else{
  42086. pTail->pDirty = pB;
  42087. pTail = pB;
  42088. pB = pB->pDirty;
  42089. if( pB==0 ){
  42090. pTail->pDirty = pA;
  42091. break;
  42092. }
  42093. }
  42094. }
  42095. return result.pDirty;
  42096. }
  42097. /*
  42098. ** Sort the list of pages in accending order by pgno. Pages are
  42099. ** connected by pDirty pointers. The pDirtyPrev pointers are
  42100. ** corrupted by this sort.
  42101. **
  42102. ** Since there cannot be more than 2^31 distinct pages in a database,
  42103. ** there cannot be more than 31 buckets required by the merge sorter.
  42104. ** One extra bucket is added to catch overflow in case something
  42105. ** ever changes to make the previous sentence incorrect.
  42106. */
  42107. #define N_SORT_BUCKET 32
  42108. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  42109. PgHdr *a[N_SORT_BUCKET], *p;
  42110. int i;
  42111. memset(a, 0, sizeof(a));
  42112. while( pIn ){
  42113. p = pIn;
  42114. pIn = p->pDirty;
  42115. p->pDirty = 0;
  42116. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  42117. if( a[i]==0 ){
  42118. a[i] = p;
  42119. break;
  42120. }else{
  42121. p = pcacheMergeDirtyList(a[i], p);
  42122. a[i] = 0;
  42123. }
  42124. }
  42125. if( NEVER(i==N_SORT_BUCKET-1) ){
  42126. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  42127. ** the input list. But that is impossible.
  42128. */
  42129. a[i] = pcacheMergeDirtyList(a[i], p);
  42130. }
  42131. }
  42132. p = a[0];
  42133. for(i=1; i<N_SORT_BUCKET; i++){
  42134. if( a[i]==0 ) continue;
  42135. p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
  42136. }
  42137. return p;
  42138. }
  42139. /*
  42140. ** Return a list of all dirty pages in the cache, sorted by page number.
  42141. */
  42142. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  42143. PgHdr *p;
  42144. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  42145. p->pDirty = p->pDirtyNext;
  42146. }
  42147. return pcacheSortDirtyList(pCache->pDirty);
  42148. }
  42149. /*
  42150. ** Return the total number of references to all pages held by the cache.
  42151. **
  42152. ** This is not the total number of pages referenced, but the sum of the
  42153. ** reference count for all pages.
  42154. */
  42155. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  42156. return pCache->nRefSum;
  42157. }
  42158. /*
  42159. ** Return the number of references to the page supplied as an argument.
  42160. */
  42161. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  42162. return p->nRef;
  42163. }
  42164. /*
  42165. ** Return the total number of pages in the cache.
  42166. */
  42167. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  42168. assert( pCache->pCache!=0 );
  42169. return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  42170. }
  42171. #ifdef SQLITE_TEST
  42172. /*
  42173. ** Get the suggested cache-size value.
  42174. */
  42175. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  42176. return numberOfCachePages(pCache);
  42177. }
  42178. #endif
  42179. /*
  42180. ** Set the suggested cache-size value.
  42181. */
  42182. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  42183. assert( pCache->pCache!=0 );
  42184. pCache->szCache = mxPage;
  42185. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  42186. numberOfCachePages(pCache));
  42187. }
  42188. /*
  42189. ** Set the suggested cache-spill value. Make no changes if if the
  42190. ** argument is zero. Return the effective cache-spill size, which will
  42191. ** be the larger of the szSpill and szCache.
  42192. */
  42193. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
  42194. int res;
  42195. assert( p->pCache!=0 );
  42196. if( mxPage ){
  42197. if( mxPage<0 ){
  42198. mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
  42199. }
  42200. p->szSpill = mxPage;
  42201. }
  42202. res = numberOfCachePages(p);
  42203. if( res<p->szSpill ) res = p->szSpill;
  42204. return res;
  42205. }
  42206. /*
  42207. ** Free up as much memory as possible from the page cache.
  42208. */
  42209. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  42210. assert( pCache->pCache!=0 );
  42211. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  42212. }
  42213. /*
  42214. ** Return the size of the header added by this middleware layer
  42215. ** in the page-cache hierarchy.
  42216. */
  42217. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
  42218. /*
  42219. ** Return the number of dirty pages currently in the cache, as a percentage
  42220. ** of the configured cache size.
  42221. */
  42222. SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
  42223. PgHdr *pDirty;
  42224. int nDirty = 0;
  42225. int nCache = numberOfCachePages(pCache);
  42226. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
  42227. return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
  42228. }
  42229. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  42230. /*
  42231. ** For all dirty pages currently in the cache, invoke the specified
  42232. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  42233. ** defined.
  42234. */
  42235. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  42236. PgHdr *pDirty;
  42237. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  42238. xIter(pDirty);
  42239. }
  42240. }
  42241. #endif
  42242. /************** End of pcache.c **********************************************/
  42243. /************** Begin file pcache1.c *****************************************/
  42244. /*
  42245. ** 2008 November 05
  42246. **
  42247. ** The author disclaims copyright to this source code. In place of
  42248. ** a legal notice, here is a blessing:
  42249. **
  42250. ** May you do good and not evil.
  42251. ** May you find forgiveness for yourself and forgive others.
  42252. ** May you share freely, never taking more than you give.
  42253. **
  42254. *************************************************************************
  42255. **
  42256. ** This file implements the default page cache implementation (the
  42257. ** sqlite3_pcache interface). It also contains part of the implementation
  42258. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  42259. ** If the default page cache implementation is overridden, then neither of
  42260. ** these two features are available.
  42261. **
  42262. ** A Page cache line looks like this:
  42263. **
  42264. ** -------------------------------------------------------------
  42265. ** | database page content | PgHdr1 | MemPage | PgHdr |
  42266. ** -------------------------------------------------------------
  42267. **
  42268. ** The database page content is up front (so that buffer overreads tend to
  42269. ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
  42270. ** is the extension added by the btree.c module containing information such
  42271. ** as the database page number and how that database page is used. PgHdr
  42272. ** is added by the pcache.c layer and contains information used to keep track
  42273. ** of which pages are "dirty". PgHdr1 is an extension added by this
  42274. ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
  42275. ** PgHdr1 contains information needed to look up a page by its page number.
  42276. ** The superclass sqlite3_pcache_page.pBuf points to the start of the
  42277. ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
  42278. **
  42279. ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
  42280. ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
  42281. ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
  42282. ** size can vary according to architecture, compile-time options, and
  42283. ** SQLite library version number.
  42284. **
  42285. ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
  42286. ** using a separate memory allocation from the database page content. This
  42287. ** seeks to overcome the "clownshoe" problem (also called "internal
  42288. ** fragmentation" in academic literature) of allocating a few bytes more
  42289. ** than a power of two with the memory allocator rounding up to the next
  42290. ** power of two, and leaving the rounded-up space unused.
  42291. **
  42292. ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
  42293. ** with this module. Information is passed back and forth as PgHdr1 pointers.
  42294. **
  42295. ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
  42296. ** The btree.c module deals with pointers to MemPage objects.
  42297. **
  42298. ** SOURCE OF PAGE CACHE MEMORY:
  42299. **
  42300. ** Memory for a page might come from any of three sources:
  42301. **
  42302. ** (1) The general-purpose memory allocator - sqlite3Malloc()
  42303. ** (2) Global page-cache memory provided using sqlite3_config() with
  42304. ** SQLITE_CONFIG_PAGECACHE.
  42305. ** (3) PCache-local bulk allocation.
  42306. **
  42307. ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
  42308. ** that is allocated when the page cache is created. The size of the local
  42309. ** bulk allocation can be adjusted using
  42310. **
  42311. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
  42312. **
  42313. ** If N is positive, then N pages worth of memory are allocated using a single
  42314. ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
  42315. ** Or if N is negative, then -1024*N bytes of memory are allocated and used
  42316. ** for as many pages as can be accomodated.
  42317. **
  42318. ** Only one of (2) or (3) can be used. Once the memory available to (2) or
  42319. ** (3) is exhausted, subsequent allocations fail over to the general-purpose
  42320. ** memory allocator (1).
  42321. **
  42322. ** Earlier versions of SQLite used only methods (1) and (2). But experiments
  42323. ** show that method (3) with N==100 provides about a 5% performance boost for
  42324. ** common workloads.
  42325. */
  42326. /* #include "sqliteInt.h" */
  42327. typedef struct PCache1 PCache1;
  42328. typedef struct PgHdr1 PgHdr1;
  42329. typedef struct PgFreeslot PgFreeslot;
  42330. typedef struct PGroup PGroup;
  42331. /*
  42332. ** Each cache entry is represented by an instance of the following
  42333. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  42334. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  42335. ** in memory.
  42336. */
  42337. struct PgHdr1 {
  42338. sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
  42339. unsigned int iKey; /* Key value (page number) */
  42340. u8 isPinned; /* Page in use, not on the LRU list */
  42341. u8 isBulkLocal; /* This page from bulk local storage */
  42342. u8 isAnchor; /* This is the PGroup.lru element */
  42343. PgHdr1 *pNext; /* Next in hash table chain */
  42344. PCache1 *pCache; /* Cache that currently owns this page */
  42345. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  42346. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  42347. };
  42348. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  42349. ** of one or more PCaches that are able to recycle each other's unpinned
  42350. ** pages when they are under memory pressure. A PGroup is an instance of
  42351. ** the following object.
  42352. **
  42353. ** This page cache implementation works in one of two modes:
  42354. **
  42355. ** (1) Every PCache is the sole member of its own PGroup. There is
  42356. ** one PGroup per PCache.
  42357. **
  42358. ** (2) There is a single global PGroup that all PCaches are a member
  42359. ** of.
  42360. **
  42361. ** Mode 1 uses more memory (since PCache instances are not able to rob
  42362. ** unused pages from other PCaches) but it also operates without a mutex,
  42363. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  42364. ** threadsafe, but recycles pages more efficiently.
  42365. **
  42366. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  42367. ** PGroup which is the pcache1.grp global variable and its mutex is
  42368. ** SQLITE_MUTEX_STATIC_LRU.
  42369. */
  42370. struct PGroup {
  42371. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  42372. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  42373. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  42374. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  42375. unsigned int nCurrentPage; /* Number of purgeable pages allocated */
  42376. PgHdr1 lru; /* The beginning and end of the LRU list */
  42377. };
  42378. /* Each page cache is an instance of the following object. Every
  42379. ** open database file (including each in-memory database and each
  42380. ** temporary or transient database) has a single page cache which
  42381. ** is an instance of this object.
  42382. **
  42383. ** Pointers to structures of this type are cast and returned as
  42384. ** opaque sqlite3_pcache* handles.
  42385. */
  42386. struct PCache1 {
  42387. /* Cache configuration parameters. Page size (szPage) and the purgeable
  42388. ** flag (bPurgeable) are set when the cache is created. nMax may be
  42389. ** modified at any time by a call to the pcache1Cachesize() method.
  42390. ** The PGroup mutex must be held when accessing nMax.
  42391. */
  42392. PGroup *pGroup; /* PGroup this cache belongs to */
  42393. int szPage; /* Size of database content section */
  42394. int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
  42395. int szAlloc; /* Total size of one pcache line */
  42396. int bPurgeable; /* True if cache is purgeable */
  42397. unsigned int nMin; /* Minimum number of pages reserved */
  42398. unsigned int nMax; /* Configured "cache_size" value */
  42399. unsigned int n90pct; /* nMax*9/10 */
  42400. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  42401. /* Hash table of all pages. The following variables may only be accessed
  42402. ** when the accessor is holding the PGroup mutex.
  42403. */
  42404. unsigned int nRecyclable; /* Number of pages in the LRU list */
  42405. unsigned int nPage; /* Total number of pages in apHash */
  42406. unsigned int nHash; /* Number of slots in apHash[] */
  42407. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  42408. PgHdr1 *pFree; /* List of unused pcache-local pages */
  42409. void *pBulk; /* Bulk memory used by pcache-local */
  42410. };
  42411. /*
  42412. ** Free slots in the allocator used to divide up the global page cache
  42413. ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
  42414. */
  42415. struct PgFreeslot {
  42416. PgFreeslot *pNext; /* Next free slot */
  42417. };
  42418. /*
  42419. ** Global data used by this cache.
  42420. */
  42421. static SQLITE_WSD struct PCacheGlobal {
  42422. PGroup grp; /* The global PGroup for mode (2) */
  42423. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  42424. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  42425. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  42426. ** The nFreeSlot and pFree values do require mutex protection.
  42427. */
  42428. int isInit; /* True if initialized */
  42429. int separateCache; /* Use a new PGroup for each PCache */
  42430. int nInitPage; /* Initial bulk allocation size */
  42431. int szSlot; /* Size of each free slot */
  42432. int nSlot; /* The number of pcache slots */
  42433. int nReserve; /* Try to keep nFreeSlot above this */
  42434. void *pStart, *pEnd; /* Bounds of global page cache memory */
  42435. /* Above requires no mutex. Use mutex below for variable that follow. */
  42436. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  42437. PgFreeslot *pFree; /* Free page blocks */
  42438. int nFreeSlot; /* Number of unused pcache slots */
  42439. /* The following value requires a mutex to change. We skip the mutex on
  42440. ** reading because (1) most platforms read a 32-bit integer atomically and
  42441. ** (2) even if an incorrect value is read, no great harm is done since this
  42442. ** is really just an optimization. */
  42443. int bUnderPressure; /* True if low on PAGECACHE memory */
  42444. } pcache1_g;
  42445. /*
  42446. ** All code in this file should access the global structure above via the
  42447. ** alias "pcache1". This ensures that the WSD emulation is used when
  42448. ** compiling for systems that do not support real WSD.
  42449. */
  42450. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  42451. /*
  42452. ** Macros to enter and leave the PCache LRU mutex.
  42453. */
  42454. #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  42455. # define pcache1EnterMutex(X) assert((X)->mutex==0)
  42456. # define pcache1LeaveMutex(X) assert((X)->mutex==0)
  42457. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
  42458. #else
  42459. # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  42460. # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  42461. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
  42462. #endif
  42463. /******************************************************************************/
  42464. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  42465. /*
  42466. ** This function is called during initialization if a static buffer is
  42467. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  42468. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  42469. ** enough to contain 'n' buffers of 'sz' bytes each.
  42470. **
  42471. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  42472. ** to be serialized already. There is no need for further mutexing.
  42473. */
  42474. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  42475. if( pcache1.isInit ){
  42476. PgFreeslot *p;
  42477. if( pBuf==0 ) sz = n = 0;
  42478. sz = ROUNDDOWN8(sz);
  42479. pcache1.szSlot = sz;
  42480. pcache1.nSlot = pcache1.nFreeSlot = n;
  42481. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  42482. pcache1.pStart = pBuf;
  42483. pcache1.pFree = 0;
  42484. pcache1.bUnderPressure = 0;
  42485. while( n-- ){
  42486. p = (PgFreeslot*)pBuf;
  42487. p->pNext = pcache1.pFree;
  42488. pcache1.pFree = p;
  42489. pBuf = (void*)&((char*)pBuf)[sz];
  42490. }
  42491. pcache1.pEnd = pBuf;
  42492. }
  42493. }
  42494. /*
  42495. ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
  42496. ** true if pCache->pFree ends up containing one or more free pages.
  42497. */
  42498. static int pcache1InitBulk(PCache1 *pCache){
  42499. i64 szBulk;
  42500. char *zBulk;
  42501. if( pcache1.nInitPage==0 ) return 0;
  42502. /* Do not bother with a bulk allocation if the cache size very small */
  42503. if( pCache->nMax<3 ) return 0;
  42504. sqlite3BeginBenignMalloc();
  42505. if( pcache1.nInitPage>0 ){
  42506. szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
  42507. }else{
  42508. szBulk = -1024 * (i64)pcache1.nInitPage;
  42509. }
  42510. if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
  42511. szBulk = pCache->szAlloc*(i64)pCache->nMax;
  42512. }
  42513. zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
  42514. sqlite3EndBenignMalloc();
  42515. if( zBulk ){
  42516. int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
  42517. do{
  42518. PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
  42519. pX->page.pBuf = zBulk;
  42520. pX->page.pExtra = &pX[1];
  42521. pX->isBulkLocal = 1;
  42522. pX->isAnchor = 0;
  42523. pX->pNext = pCache->pFree;
  42524. pCache->pFree = pX;
  42525. zBulk += pCache->szAlloc;
  42526. }while( --nBulk );
  42527. }
  42528. return pCache->pFree!=0;
  42529. }
  42530. /*
  42531. ** Malloc function used within this file to allocate space from the buffer
  42532. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  42533. ** such buffer exists or there is no space left in it, this function falls
  42534. ** back to sqlite3Malloc().
  42535. **
  42536. ** Multiple threads can run this routine at the same time. Global variables
  42537. ** in pcache1 need to be protected via mutex.
  42538. */
  42539. static void *pcache1Alloc(int nByte){
  42540. void *p = 0;
  42541. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  42542. if( nByte<=pcache1.szSlot ){
  42543. sqlite3_mutex_enter(pcache1.mutex);
  42544. p = (PgHdr1 *)pcache1.pFree;
  42545. if( p ){
  42546. pcache1.pFree = pcache1.pFree->pNext;
  42547. pcache1.nFreeSlot--;
  42548. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  42549. assert( pcache1.nFreeSlot>=0 );
  42550. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  42551. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
  42552. }
  42553. sqlite3_mutex_leave(pcache1.mutex);
  42554. }
  42555. if( p==0 ){
  42556. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  42557. ** it from sqlite3Malloc instead.
  42558. */
  42559. p = sqlite3Malloc(nByte);
  42560. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  42561. if( p ){
  42562. int sz = sqlite3MallocSize(p);
  42563. sqlite3_mutex_enter(pcache1.mutex);
  42564. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  42565. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  42566. sqlite3_mutex_leave(pcache1.mutex);
  42567. }
  42568. #endif
  42569. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  42570. }
  42571. return p;
  42572. }
  42573. /*
  42574. ** Free an allocated buffer obtained from pcache1Alloc().
  42575. */
  42576. static void pcache1Free(void *p){
  42577. if( p==0 ) return;
  42578. if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
  42579. PgFreeslot *pSlot;
  42580. sqlite3_mutex_enter(pcache1.mutex);
  42581. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
  42582. pSlot = (PgFreeslot*)p;
  42583. pSlot->pNext = pcache1.pFree;
  42584. pcache1.pFree = pSlot;
  42585. pcache1.nFreeSlot++;
  42586. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  42587. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  42588. sqlite3_mutex_leave(pcache1.mutex);
  42589. }else{
  42590. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  42591. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  42592. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  42593. {
  42594. int nFreed = 0;
  42595. nFreed = sqlite3MallocSize(p);
  42596. sqlite3_mutex_enter(pcache1.mutex);
  42597. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
  42598. sqlite3_mutex_leave(pcache1.mutex);
  42599. }
  42600. #endif
  42601. sqlite3_free(p);
  42602. }
  42603. }
  42604. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  42605. /*
  42606. ** Return the size of a pcache allocation
  42607. */
  42608. static int pcache1MemSize(void *p){
  42609. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  42610. return pcache1.szSlot;
  42611. }else{
  42612. int iSize;
  42613. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  42614. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  42615. iSize = sqlite3MallocSize(p);
  42616. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  42617. return iSize;
  42618. }
  42619. }
  42620. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  42621. /*
  42622. ** Allocate a new page object initially associated with cache pCache.
  42623. */
  42624. static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
  42625. PgHdr1 *p = 0;
  42626. void *pPg;
  42627. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  42628. if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
  42629. p = pCache->pFree;
  42630. pCache->pFree = p->pNext;
  42631. p->pNext = 0;
  42632. }else{
  42633. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  42634. /* The group mutex must be released before pcache1Alloc() is called. This
  42635. ** is because it might call sqlite3_release_memory(), which assumes that
  42636. ** this mutex is not held. */
  42637. assert( pcache1.separateCache==0 );
  42638. assert( pCache->pGroup==&pcache1.grp );
  42639. pcache1LeaveMutex(pCache->pGroup);
  42640. #endif
  42641. if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
  42642. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  42643. pPg = pcache1Alloc(pCache->szPage);
  42644. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  42645. if( !pPg || !p ){
  42646. pcache1Free(pPg);
  42647. sqlite3_free(p);
  42648. pPg = 0;
  42649. }
  42650. #else
  42651. pPg = pcache1Alloc(pCache->szAlloc);
  42652. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  42653. #endif
  42654. if( benignMalloc ){ sqlite3EndBenignMalloc(); }
  42655. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  42656. pcache1EnterMutex(pCache->pGroup);
  42657. #endif
  42658. if( pPg==0 ) return 0;
  42659. p->page.pBuf = pPg;
  42660. p->page.pExtra = &p[1];
  42661. p->isBulkLocal = 0;
  42662. p->isAnchor = 0;
  42663. }
  42664. if( pCache->bPurgeable ){
  42665. pCache->pGroup->nCurrentPage++;
  42666. }
  42667. return p;
  42668. }
  42669. /*
  42670. ** Free a page object allocated by pcache1AllocPage().
  42671. */
  42672. static void pcache1FreePage(PgHdr1 *p){
  42673. PCache1 *pCache;
  42674. assert( p!=0 );
  42675. pCache = p->pCache;
  42676. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  42677. if( p->isBulkLocal ){
  42678. p->pNext = pCache->pFree;
  42679. pCache->pFree = p;
  42680. }else{
  42681. pcache1Free(p->page.pBuf);
  42682. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  42683. sqlite3_free(p);
  42684. #endif
  42685. }
  42686. if( pCache->bPurgeable ){
  42687. pCache->pGroup->nCurrentPage--;
  42688. }
  42689. }
  42690. /*
  42691. ** Malloc function used by SQLite to obtain space from the buffer configured
  42692. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  42693. ** exists, this function falls back to sqlite3Malloc().
  42694. */
  42695. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  42696. return pcache1Alloc(sz);
  42697. }
  42698. /*
  42699. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  42700. */
  42701. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  42702. pcache1Free(p);
  42703. }
  42704. /*
  42705. ** Return true if it desirable to avoid allocating a new page cache
  42706. ** entry.
  42707. **
  42708. ** If memory was allocated specifically to the page cache using
  42709. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  42710. ** it is desirable to avoid allocating a new page cache entry because
  42711. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  42712. ** for all page cache needs and we should not need to spill the
  42713. ** allocation onto the heap.
  42714. **
  42715. ** Or, the heap is used for all page cache memory but the heap is
  42716. ** under memory pressure, then again it is desirable to avoid
  42717. ** allocating a new page cache entry in order to avoid stressing
  42718. ** the heap even further.
  42719. */
  42720. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  42721. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  42722. return pcache1.bUnderPressure;
  42723. }else{
  42724. return sqlite3HeapNearlyFull();
  42725. }
  42726. }
  42727. /******************************************************************************/
  42728. /******** General Implementation Functions ************************************/
  42729. /*
  42730. ** This function is used to resize the hash table used by the cache passed
  42731. ** as the first argument.
  42732. **
  42733. ** The PCache mutex must be held when this function is called.
  42734. */
  42735. static void pcache1ResizeHash(PCache1 *p){
  42736. PgHdr1 **apNew;
  42737. unsigned int nNew;
  42738. unsigned int i;
  42739. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  42740. nNew = p->nHash*2;
  42741. if( nNew<256 ){
  42742. nNew = 256;
  42743. }
  42744. pcache1LeaveMutex(p->pGroup);
  42745. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  42746. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  42747. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  42748. pcache1EnterMutex(p->pGroup);
  42749. if( apNew ){
  42750. for(i=0; i<p->nHash; i++){
  42751. PgHdr1 *pPage;
  42752. PgHdr1 *pNext = p->apHash[i];
  42753. while( (pPage = pNext)!=0 ){
  42754. unsigned int h = pPage->iKey % nNew;
  42755. pNext = pPage->pNext;
  42756. pPage->pNext = apNew[h];
  42757. apNew[h] = pPage;
  42758. }
  42759. }
  42760. sqlite3_free(p->apHash);
  42761. p->apHash = apNew;
  42762. p->nHash = nNew;
  42763. }
  42764. }
  42765. /*
  42766. ** This function is used internally to remove the page pPage from the
  42767. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  42768. ** LRU list, then this function is a no-op.
  42769. **
  42770. ** The PGroup mutex must be held when this function is called.
  42771. */
  42772. static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
  42773. PCache1 *pCache;
  42774. assert( pPage!=0 );
  42775. assert( pPage->isPinned==0 );
  42776. pCache = pPage->pCache;
  42777. assert( pPage->pLruNext );
  42778. assert( pPage->pLruPrev );
  42779. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  42780. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  42781. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  42782. pPage->pLruNext = 0;
  42783. pPage->pLruPrev = 0;
  42784. pPage->isPinned = 1;
  42785. assert( pPage->isAnchor==0 );
  42786. assert( pCache->pGroup->lru.isAnchor==1 );
  42787. pCache->nRecyclable--;
  42788. return pPage;
  42789. }
  42790. /*
  42791. ** Remove the page supplied as an argument from the hash table
  42792. ** (PCache1.apHash structure) that it is currently stored in.
  42793. ** Also free the page if freePage is true.
  42794. **
  42795. ** The PGroup mutex must be held when this function is called.
  42796. */
  42797. static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
  42798. unsigned int h;
  42799. PCache1 *pCache = pPage->pCache;
  42800. PgHdr1 **pp;
  42801. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  42802. h = pPage->iKey % pCache->nHash;
  42803. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  42804. *pp = (*pp)->pNext;
  42805. pCache->nPage--;
  42806. if( freeFlag ) pcache1FreePage(pPage);
  42807. }
  42808. /*
  42809. ** If there are currently more than nMaxPage pages allocated, try
  42810. ** to recycle pages to reduce the number allocated to nMaxPage.
  42811. */
  42812. static void pcache1EnforceMaxPage(PCache1 *pCache){
  42813. PGroup *pGroup = pCache->pGroup;
  42814. PgHdr1 *p;
  42815. assert( sqlite3_mutex_held(pGroup->mutex) );
  42816. while( pGroup->nCurrentPage>pGroup->nMaxPage
  42817. && (p=pGroup->lru.pLruPrev)->isAnchor==0
  42818. ){
  42819. assert( p->pCache->pGroup==pGroup );
  42820. assert( p->isPinned==0 );
  42821. pcache1PinPage(p);
  42822. pcache1RemoveFromHash(p, 1);
  42823. }
  42824. if( pCache->nPage==0 && pCache->pBulk ){
  42825. sqlite3_free(pCache->pBulk);
  42826. pCache->pBulk = pCache->pFree = 0;
  42827. }
  42828. }
  42829. /*
  42830. ** Discard all pages from cache pCache with a page number (key value)
  42831. ** greater than or equal to iLimit. Any pinned pages that meet this
  42832. ** criteria are unpinned before they are discarded.
  42833. **
  42834. ** The PCache mutex must be held when this function is called.
  42835. */
  42836. static void pcache1TruncateUnsafe(
  42837. PCache1 *pCache, /* The cache to truncate */
  42838. unsigned int iLimit /* Drop pages with this pgno or larger */
  42839. ){
  42840. TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */
  42841. unsigned int h, iStop;
  42842. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  42843. assert( pCache->iMaxKey >= iLimit );
  42844. assert( pCache->nHash > 0 );
  42845. if( pCache->iMaxKey - iLimit < pCache->nHash ){
  42846. /* If we are just shaving the last few pages off the end of the
  42847. ** cache, then there is no point in scanning the entire hash table.
  42848. ** Only scan those hash slots that might contain pages that need to
  42849. ** be removed. */
  42850. h = iLimit % pCache->nHash;
  42851. iStop = pCache->iMaxKey % pCache->nHash;
  42852. TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */
  42853. }else{
  42854. /* This is the general case where many pages are being removed.
  42855. ** It is necessary to scan the entire hash table */
  42856. h = pCache->nHash/2;
  42857. iStop = h - 1;
  42858. }
  42859. for(;;){
  42860. PgHdr1 **pp;
  42861. PgHdr1 *pPage;
  42862. assert( h<pCache->nHash );
  42863. pp = &pCache->apHash[h];
  42864. while( (pPage = *pp)!=0 ){
  42865. if( pPage->iKey>=iLimit ){
  42866. pCache->nPage--;
  42867. *pp = pPage->pNext;
  42868. if( !pPage->isPinned ) pcache1PinPage(pPage);
  42869. pcache1FreePage(pPage);
  42870. }else{
  42871. pp = &pPage->pNext;
  42872. TESTONLY( if( nPage>=0 ) nPage++; )
  42873. }
  42874. }
  42875. if( h==iStop ) break;
  42876. h = (h+1) % pCache->nHash;
  42877. }
  42878. assert( nPage<0 || pCache->nPage==(unsigned)nPage );
  42879. }
  42880. /******************************************************************************/
  42881. /******** sqlite3_pcache Methods **********************************************/
  42882. /*
  42883. ** Implementation of the sqlite3_pcache.xInit method.
  42884. */
  42885. static int pcache1Init(void *NotUsed){
  42886. UNUSED_PARAMETER(NotUsed);
  42887. assert( pcache1.isInit==0 );
  42888. memset(&pcache1, 0, sizeof(pcache1));
  42889. /*
  42890. ** The pcache1.separateCache variable is true if each PCache has its own
  42891. ** private PGroup (mode-1). pcache1.separateCache is false if the single
  42892. ** PGroup in pcache1.grp is used for all page caches (mode-2).
  42893. **
  42894. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  42895. **
  42896. ** * Use a unified cache in single-threaded applications that have
  42897. ** configured a start-time buffer for use as page-cache memory using
  42898. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
  42899. ** pBuf argument.
  42900. **
  42901. ** * Otherwise use separate caches (mode-1)
  42902. */
  42903. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
  42904. pcache1.separateCache = 0;
  42905. #elif SQLITE_THREADSAFE
  42906. pcache1.separateCache = sqlite3GlobalConfig.pPage==0
  42907. || sqlite3GlobalConfig.bCoreMutex>0;
  42908. #else
  42909. pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
  42910. #endif
  42911. #if SQLITE_THREADSAFE
  42912. if( sqlite3GlobalConfig.bCoreMutex ){
  42913. pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
  42914. pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
  42915. }
  42916. #endif
  42917. if( pcache1.separateCache
  42918. && sqlite3GlobalConfig.nPage!=0
  42919. && sqlite3GlobalConfig.pPage==0
  42920. ){
  42921. pcache1.nInitPage = sqlite3GlobalConfig.nPage;
  42922. }else{
  42923. pcache1.nInitPage = 0;
  42924. }
  42925. pcache1.grp.mxPinned = 10;
  42926. pcache1.isInit = 1;
  42927. return SQLITE_OK;
  42928. }
  42929. /*
  42930. ** Implementation of the sqlite3_pcache.xShutdown method.
  42931. ** Note that the static mutex allocated in xInit does
  42932. ** not need to be freed.
  42933. */
  42934. static void pcache1Shutdown(void *NotUsed){
  42935. UNUSED_PARAMETER(NotUsed);
  42936. assert( pcache1.isInit!=0 );
  42937. memset(&pcache1, 0, sizeof(pcache1));
  42938. }
  42939. /* forward declaration */
  42940. static void pcache1Destroy(sqlite3_pcache *p);
  42941. /*
  42942. ** Implementation of the sqlite3_pcache.xCreate method.
  42943. **
  42944. ** Allocate a new cache.
  42945. */
  42946. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  42947. PCache1 *pCache; /* The newly created page cache */
  42948. PGroup *pGroup; /* The group the new page cache will belong to */
  42949. int sz; /* Bytes of memory required to allocate the new cache */
  42950. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  42951. assert( szExtra < 300 );
  42952. sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
  42953. pCache = (PCache1 *)sqlite3MallocZero(sz);
  42954. if( pCache ){
  42955. if( pcache1.separateCache ){
  42956. pGroup = (PGroup*)&pCache[1];
  42957. pGroup->mxPinned = 10;
  42958. }else{
  42959. pGroup = &pcache1.grp;
  42960. }
  42961. if( pGroup->lru.isAnchor==0 ){
  42962. pGroup->lru.isAnchor = 1;
  42963. pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
  42964. }
  42965. pCache->pGroup = pGroup;
  42966. pCache->szPage = szPage;
  42967. pCache->szExtra = szExtra;
  42968. pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
  42969. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  42970. pcache1EnterMutex(pGroup);
  42971. pcache1ResizeHash(pCache);
  42972. if( bPurgeable ){
  42973. pCache->nMin = 10;
  42974. pGroup->nMinPage += pCache->nMin;
  42975. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  42976. }
  42977. pcache1LeaveMutex(pGroup);
  42978. if( pCache->nHash==0 ){
  42979. pcache1Destroy((sqlite3_pcache*)pCache);
  42980. pCache = 0;
  42981. }
  42982. }
  42983. return (sqlite3_pcache *)pCache;
  42984. }
  42985. /*
  42986. ** Implementation of the sqlite3_pcache.xCachesize method.
  42987. **
  42988. ** Configure the cache_size limit for a cache.
  42989. */
  42990. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  42991. PCache1 *pCache = (PCache1 *)p;
  42992. if( pCache->bPurgeable ){
  42993. PGroup *pGroup = pCache->pGroup;
  42994. pcache1EnterMutex(pGroup);
  42995. pGroup->nMaxPage += (nMax - pCache->nMax);
  42996. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  42997. pCache->nMax = nMax;
  42998. pCache->n90pct = pCache->nMax*9/10;
  42999. pcache1EnforceMaxPage(pCache);
  43000. pcache1LeaveMutex(pGroup);
  43001. }
  43002. }
  43003. /*
  43004. ** Implementation of the sqlite3_pcache.xShrink method.
  43005. **
  43006. ** Free up as much memory as possible.
  43007. */
  43008. static void pcache1Shrink(sqlite3_pcache *p){
  43009. PCache1 *pCache = (PCache1*)p;
  43010. if( pCache->bPurgeable ){
  43011. PGroup *pGroup = pCache->pGroup;
  43012. int savedMaxPage;
  43013. pcache1EnterMutex(pGroup);
  43014. savedMaxPage = pGroup->nMaxPage;
  43015. pGroup->nMaxPage = 0;
  43016. pcache1EnforceMaxPage(pCache);
  43017. pGroup->nMaxPage = savedMaxPage;
  43018. pcache1LeaveMutex(pGroup);
  43019. }
  43020. }
  43021. /*
  43022. ** Implementation of the sqlite3_pcache.xPagecount method.
  43023. */
  43024. static int pcache1Pagecount(sqlite3_pcache *p){
  43025. int n;
  43026. PCache1 *pCache = (PCache1*)p;
  43027. pcache1EnterMutex(pCache->pGroup);
  43028. n = pCache->nPage;
  43029. pcache1LeaveMutex(pCache->pGroup);
  43030. return n;
  43031. }
  43032. /*
  43033. ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
  43034. ** in the header of the pcache1Fetch() procedure.
  43035. **
  43036. ** This steps are broken out into a separate procedure because they are
  43037. ** usually not needed, and by avoiding the stack initialization required
  43038. ** for these steps, the main pcache1Fetch() procedure can run faster.
  43039. */
  43040. static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
  43041. PCache1 *pCache,
  43042. unsigned int iKey,
  43043. int createFlag
  43044. ){
  43045. unsigned int nPinned;
  43046. PGroup *pGroup = pCache->pGroup;
  43047. PgHdr1 *pPage = 0;
  43048. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  43049. assert( pCache->nPage >= pCache->nRecyclable );
  43050. nPinned = pCache->nPage - pCache->nRecyclable;
  43051. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  43052. assert( pCache->n90pct == pCache->nMax*9/10 );
  43053. if( createFlag==1 && (
  43054. nPinned>=pGroup->mxPinned
  43055. || nPinned>=pCache->n90pct
  43056. || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
  43057. )){
  43058. return 0;
  43059. }
  43060. if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
  43061. assert( pCache->nHash>0 && pCache->apHash );
  43062. /* Step 4. Try to recycle a page. */
  43063. if( pCache->bPurgeable
  43064. && !pGroup->lru.pLruPrev->isAnchor
  43065. && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
  43066. ){
  43067. PCache1 *pOther;
  43068. pPage = pGroup->lru.pLruPrev;
  43069. assert( pPage->isPinned==0 );
  43070. pcache1RemoveFromHash(pPage, 0);
  43071. pcache1PinPage(pPage);
  43072. pOther = pPage->pCache;
  43073. if( pOther->szAlloc != pCache->szAlloc ){
  43074. pcache1FreePage(pPage);
  43075. pPage = 0;
  43076. }else{
  43077. pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
  43078. }
  43079. }
  43080. /* Step 5. If a usable page buffer has still not been found,
  43081. ** attempt to allocate a new one.
  43082. */
  43083. if( !pPage ){
  43084. pPage = pcache1AllocPage(pCache, createFlag==1);
  43085. }
  43086. if( pPage ){
  43087. unsigned int h = iKey % pCache->nHash;
  43088. pCache->nPage++;
  43089. pPage->iKey = iKey;
  43090. pPage->pNext = pCache->apHash[h];
  43091. pPage->pCache = pCache;
  43092. pPage->pLruPrev = 0;
  43093. pPage->pLruNext = 0;
  43094. pPage->isPinned = 1;
  43095. *(void **)pPage->page.pExtra = 0;
  43096. pCache->apHash[h] = pPage;
  43097. if( iKey>pCache->iMaxKey ){
  43098. pCache->iMaxKey = iKey;
  43099. }
  43100. }
  43101. return pPage;
  43102. }
  43103. /*
  43104. ** Implementation of the sqlite3_pcache.xFetch method.
  43105. **
  43106. ** Fetch a page by key value.
  43107. **
  43108. ** Whether or not a new page may be allocated by this function depends on
  43109. ** the value of the createFlag argument. 0 means do not allocate a new
  43110. ** page. 1 means allocate a new page if space is easily available. 2
  43111. ** means to try really hard to allocate a new page.
  43112. **
  43113. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  43114. ** database) there is really no difference between createFlag 1 and 2. So
  43115. ** the calling function (pcache.c) will never have a createFlag of 1 on
  43116. ** a non-purgeable cache.
  43117. **
  43118. ** There are three different approaches to obtaining space for a page,
  43119. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  43120. **
  43121. ** 1. Regardless of the value of createFlag, the cache is searched for a
  43122. ** copy of the requested page. If one is found, it is returned.
  43123. **
  43124. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  43125. ** returned.
  43126. **
  43127. ** 3. If createFlag is 1, and the page is not already in the cache, then
  43128. ** return NULL (do not allocate a new page) if any of the following
  43129. ** conditions are true:
  43130. **
  43131. ** (a) the number of pages pinned by the cache is greater than
  43132. ** PCache1.nMax, or
  43133. **
  43134. ** (b) the number of pages pinned by the cache is greater than
  43135. ** the sum of nMax for all purgeable caches, less the sum of
  43136. ** nMin for all other purgeable caches, or
  43137. **
  43138. ** 4. If none of the first three conditions apply and the cache is marked
  43139. ** as purgeable, and if one of the following is true:
  43140. **
  43141. ** (a) The number of pages allocated for the cache is already
  43142. ** PCache1.nMax, or
  43143. **
  43144. ** (b) The number of pages allocated for all purgeable caches is
  43145. ** already equal to or greater than the sum of nMax for all
  43146. ** purgeable caches,
  43147. **
  43148. ** (c) The system is under memory pressure and wants to avoid
  43149. ** unnecessary pages cache entry allocations
  43150. **
  43151. ** then attempt to recycle a page from the LRU list. If it is the right
  43152. ** size, return the recycled buffer. Otherwise, free the buffer and
  43153. ** proceed to step 5.
  43154. **
  43155. ** 5. Otherwise, allocate and return a new page buffer.
  43156. **
  43157. ** There are two versions of this routine. pcache1FetchWithMutex() is
  43158. ** the general case. pcache1FetchNoMutex() is a faster implementation for
  43159. ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
  43160. ** invokes the appropriate routine.
  43161. */
  43162. static PgHdr1 *pcache1FetchNoMutex(
  43163. sqlite3_pcache *p,
  43164. unsigned int iKey,
  43165. int createFlag
  43166. ){
  43167. PCache1 *pCache = (PCache1 *)p;
  43168. PgHdr1 *pPage = 0;
  43169. /* Step 1: Search the hash table for an existing entry. */
  43170. pPage = pCache->apHash[iKey % pCache->nHash];
  43171. while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
  43172. /* Step 2: If the page was found in the hash table, then return it.
  43173. ** If the page was not in the hash table and createFlag is 0, abort.
  43174. ** Otherwise (page not in hash and createFlag!=0) continue with
  43175. ** subsequent steps to try to create the page. */
  43176. if( pPage ){
  43177. if( !pPage->isPinned ){
  43178. return pcache1PinPage(pPage);
  43179. }else{
  43180. return pPage;
  43181. }
  43182. }else if( createFlag ){
  43183. /* Steps 3, 4, and 5 implemented by this subroutine */
  43184. return pcache1FetchStage2(pCache, iKey, createFlag);
  43185. }else{
  43186. return 0;
  43187. }
  43188. }
  43189. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  43190. static PgHdr1 *pcache1FetchWithMutex(
  43191. sqlite3_pcache *p,
  43192. unsigned int iKey,
  43193. int createFlag
  43194. ){
  43195. PCache1 *pCache = (PCache1 *)p;
  43196. PgHdr1 *pPage;
  43197. pcache1EnterMutex(pCache->pGroup);
  43198. pPage = pcache1FetchNoMutex(p, iKey, createFlag);
  43199. assert( pPage==0 || pCache->iMaxKey>=iKey );
  43200. pcache1LeaveMutex(pCache->pGroup);
  43201. return pPage;
  43202. }
  43203. #endif
  43204. static sqlite3_pcache_page *pcache1Fetch(
  43205. sqlite3_pcache *p,
  43206. unsigned int iKey,
  43207. int createFlag
  43208. ){
  43209. #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
  43210. PCache1 *pCache = (PCache1 *)p;
  43211. #endif
  43212. assert( offsetof(PgHdr1,page)==0 );
  43213. assert( pCache->bPurgeable || createFlag!=1 );
  43214. assert( pCache->bPurgeable || pCache->nMin==0 );
  43215. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  43216. assert( pCache->nMin==0 || pCache->bPurgeable );
  43217. assert( pCache->nHash>0 );
  43218. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  43219. if( pCache->pGroup->mutex ){
  43220. return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
  43221. }else
  43222. #endif
  43223. {
  43224. return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
  43225. }
  43226. }
  43227. /*
  43228. ** Implementation of the sqlite3_pcache.xUnpin method.
  43229. **
  43230. ** Mark a page as unpinned (eligible for asynchronous recycling).
  43231. */
  43232. static void pcache1Unpin(
  43233. sqlite3_pcache *p,
  43234. sqlite3_pcache_page *pPg,
  43235. int reuseUnlikely
  43236. ){
  43237. PCache1 *pCache = (PCache1 *)p;
  43238. PgHdr1 *pPage = (PgHdr1 *)pPg;
  43239. PGroup *pGroup = pCache->pGroup;
  43240. assert( pPage->pCache==pCache );
  43241. pcache1EnterMutex(pGroup);
  43242. /* It is an error to call this function if the page is already
  43243. ** part of the PGroup LRU list.
  43244. */
  43245. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  43246. assert( pPage->isPinned==1 );
  43247. if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
  43248. pcache1RemoveFromHash(pPage, 1);
  43249. }else{
  43250. /* Add the page to the PGroup LRU list. */
  43251. PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
  43252. pPage->pLruPrev = &pGroup->lru;
  43253. (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
  43254. *ppFirst = pPage;
  43255. pCache->nRecyclable++;
  43256. pPage->isPinned = 0;
  43257. }
  43258. pcache1LeaveMutex(pCache->pGroup);
  43259. }
  43260. /*
  43261. ** Implementation of the sqlite3_pcache.xRekey method.
  43262. */
  43263. static void pcache1Rekey(
  43264. sqlite3_pcache *p,
  43265. sqlite3_pcache_page *pPg,
  43266. unsigned int iOld,
  43267. unsigned int iNew
  43268. ){
  43269. PCache1 *pCache = (PCache1 *)p;
  43270. PgHdr1 *pPage = (PgHdr1 *)pPg;
  43271. PgHdr1 **pp;
  43272. unsigned int h;
  43273. assert( pPage->iKey==iOld );
  43274. assert( pPage->pCache==pCache );
  43275. pcache1EnterMutex(pCache->pGroup);
  43276. h = iOld%pCache->nHash;
  43277. pp = &pCache->apHash[h];
  43278. while( (*pp)!=pPage ){
  43279. pp = &(*pp)->pNext;
  43280. }
  43281. *pp = pPage->pNext;
  43282. h = iNew%pCache->nHash;
  43283. pPage->iKey = iNew;
  43284. pPage->pNext = pCache->apHash[h];
  43285. pCache->apHash[h] = pPage;
  43286. if( iNew>pCache->iMaxKey ){
  43287. pCache->iMaxKey = iNew;
  43288. }
  43289. pcache1LeaveMutex(pCache->pGroup);
  43290. }
  43291. /*
  43292. ** Implementation of the sqlite3_pcache.xTruncate method.
  43293. **
  43294. ** Discard all unpinned pages in the cache with a page number equal to
  43295. ** or greater than parameter iLimit. Any pinned pages with a page number
  43296. ** equal to or greater than iLimit are implicitly unpinned.
  43297. */
  43298. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  43299. PCache1 *pCache = (PCache1 *)p;
  43300. pcache1EnterMutex(pCache->pGroup);
  43301. if( iLimit<=pCache->iMaxKey ){
  43302. pcache1TruncateUnsafe(pCache, iLimit);
  43303. pCache->iMaxKey = iLimit-1;
  43304. }
  43305. pcache1LeaveMutex(pCache->pGroup);
  43306. }
  43307. /*
  43308. ** Implementation of the sqlite3_pcache.xDestroy method.
  43309. **
  43310. ** Destroy a cache allocated using pcache1Create().
  43311. */
  43312. static void pcache1Destroy(sqlite3_pcache *p){
  43313. PCache1 *pCache = (PCache1 *)p;
  43314. PGroup *pGroup = pCache->pGroup;
  43315. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  43316. pcache1EnterMutex(pGroup);
  43317. if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
  43318. assert( pGroup->nMaxPage >= pCache->nMax );
  43319. pGroup->nMaxPage -= pCache->nMax;
  43320. assert( pGroup->nMinPage >= pCache->nMin );
  43321. pGroup->nMinPage -= pCache->nMin;
  43322. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  43323. pcache1EnforceMaxPage(pCache);
  43324. pcache1LeaveMutex(pGroup);
  43325. sqlite3_free(pCache->pBulk);
  43326. sqlite3_free(pCache->apHash);
  43327. sqlite3_free(pCache);
  43328. }
  43329. /*
  43330. ** This function is called during initialization (sqlite3_initialize()) to
  43331. ** install the default pluggable cache module, assuming the user has not
  43332. ** already provided an alternative.
  43333. */
  43334. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  43335. static const sqlite3_pcache_methods2 defaultMethods = {
  43336. 1, /* iVersion */
  43337. 0, /* pArg */
  43338. pcache1Init, /* xInit */
  43339. pcache1Shutdown, /* xShutdown */
  43340. pcache1Create, /* xCreate */
  43341. pcache1Cachesize, /* xCachesize */
  43342. pcache1Pagecount, /* xPagecount */
  43343. pcache1Fetch, /* xFetch */
  43344. pcache1Unpin, /* xUnpin */
  43345. pcache1Rekey, /* xRekey */
  43346. pcache1Truncate, /* xTruncate */
  43347. pcache1Destroy, /* xDestroy */
  43348. pcache1Shrink /* xShrink */
  43349. };
  43350. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  43351. }
  43352. /*
  43353. ** Return the size of the header on each page of this PCACHE implementation.
  43354. */
  43355. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
  43356. /*
  43357. ** Return the global mutex used by this PCACHE implementation. The
  43358. ** sqlite3_status() routine needs access to this mutex.
  43359. */
  43360. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
  43361. return pcache1.mutex;
  43362. }
  43363. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  43364. /*
  43365. ** This function is called to free superfluous dynamically allocated memory
  43366. ** held by the pager system. Memory in use by any SQLite pager allocated
  43367. ** by the current thread may be sqlite3_free()ed.
  43368. **
  43369. ** nReq is the number of bytes of memory required. Once this much has
  43370. ** been released, the function returns. The return value is the total number
  43371. ** of bytes of memory released.
  43372. */
  43373. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  43374. int nFree = 0;
  43375. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  43376. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  43377. if( sqlite3GlobalConfig.pPage==0 ){
  43378. PgHdr1 *p;
  43379. pcache1EnterMutex(&pcache1.grp);
  43380. while( (nReq<0 || nFree<nReq)
  43381. && (p=pcache1.grp.lru.pLruPrev)!=0
  43382. && p->isAnchor==0
  43383. ){
  43384. nFree += pcache1MemSize(p->page.pBuf);
  43385. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  43386. nFree += sqlite3MemSize(p);
  43387. #endif
  43388. assert( p->isPinned==0 );
  43389. pcache1PinPage(p);
  43390. pcache1RemoveFromHash(p, 1);
  43391. }
  43392. pcache1LeaveMutex(&pcache1.grp);
  43393. }
  43394. return nFree;
  43395. }
  43396. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  43397. #ifdef SQLITE_TEST
  43398. /*
  43399. ** This function is used by test procedures to inspect the internal state
  43400. ** of the global cache.
  43401. */
  43402. SQLITE_PRIVATE void sqlite3PcacheStats(
  43403. int *pnCurrent, /* OUT: Total number of pages cached */
  43404. int *pnMax, /* OUT: Global maximum cache size */
  43405. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  43406. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  43407. ){
  43408. PgHdr1 *p;
  43409. int nRecyclable = 0;
  43410. for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
  43411. assert( p->isPinned==0 );
  43412. nRecyclable++;
  43413. }
  43414. *pnCurrent = pcache1.grp.nCurrentPage;
  43415. *pnMax = (int)pcache1.grp.nMaxPage;
  43416. *pnMin = (int)pcache1.grp.nMinPage;
  43417. *pnRecyclable = nRecyclable;
  43418. }
  43419. #endif
  43420. /************** End of pcache1.c *********************************************/
  43421. /************** Begin file rowset.c ******************************************/
  43422. /*
  43423. ** 2008 December 3
  43424. **
  43425. ** The author disclaims copyright to this source code. In place of
  43426. ** a legal notice, here is a blessing:
  43427. **
  43428. ** May you do good and not evil.
  43429. ** May you find forgiveness for yourself and forgive others.
  43430. ** May you share freely, never taking more than you give.
  43431. **
  43432. *************************************************************************
  43433. **
  43434. ** This module implements an object we call a "RowSet".
  43435. **
  43436. ** The RowSet object is a collection of rowids. Rowids
  43437. ** are inserted into the RowSet in an arbitrary order. Inserts
  43438. ** can be intermixed with tests to see if a given rowid has been
  43439. ** previously inserted into the RowSet.
  43440. **
  43441. ** After all inserts are finished, it is possible to extract the
  43442. ** elements of the RowSet in sorted order. Once this extraction
  43443. ** process has started, no new elements may be inserted.
  43444. **
  43445. ** Hence, the primitive operations for a RowSet are:
  43446. **
  43447. ** CREATE
  43448. ** INSERT
  43449. ** TEST
  43450. ** SMALLEST
  43451. ** DESTROY
  43452. **
  43453. ** The CREATE and DESTROY primitives are the constructor and destructor,
  43454. ** obviously. The INSERT primitive adds a new element to the RowSet.
  43455. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  43456. ** extracts the least value from the RowSet.
  43457. **
  43458. ** The INSERT primitive might allocate additional memory. Memory is
  43459. ** allocated in chunks so most INSERTs do no allocation. There is an
  43460. ** upper bound on the size of allocated memory. No memory is freed
  43461. ** until DESTROY.
  43462. **
  43463. ** The TEST primitive includes a "batch" number. The TEST primitive
  43464. ** will only see elements that were inserted before the last change
  43465. ** in the batch number. In other words, if an INSERT occurs between
  43466. ** two TESTs where the TESTs have the same batch nubmer, then the
  43467. ** value added by the INSERT will not be visible to the second TEST.
  43468. ** The initial batch number is zero, so if the very first TEST contains
  43469. ** a non-zero batch number, it will see all prior INSERTs.
  43470. **
  43471. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  43472. ** that is attempted.
  43473. **
  43474. ** The cost of an INSERT is roughly constant. (Sometimes new memory
  43475. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  43476. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  43477. ** The cost of a TEST using the same batch number is O(logN). The cost
  43478. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  43479. ** primitives are constant time. The cost of DESTROY is O(N).
  43480. **
  43481. ** TEST and SMALLEST may not be used by the same RowSet. This used to
  43482. ** be possible, but the feature was not used, so it was removed in order
  43483. ** to simplify the code.
  43484. */
  43485. /* #include "sqliteInt.h" */
  43486. /*
  43487. ** Target size for allocation chunks.
  43488. */
  43489. #define ROWSET_ALLOCATION_SIZE 1024
  43490. /*
  43491. ** The number of rowset entries per allocation chunk.
  43492. */
  43493. #define ROWSET_ENTRY_PER_CHUNK \
  43494. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  43495. /*
  43496. ** Each entry in a RowSet is an instance of the following object.
  43497. **
  43498. ** This same object is reused to store a linked list of trees of RowSetEntry
  43499. ** objects. In that alternative use, pRight points to the next entry
  43500. ** in the list, pLeft points to the tree, and v is unused. The
  43501. ** RowSet.pForest value points to the head of this forest list.
  43502. */
  43503. struct RowSetEntry {
  43504. i64 v; /* ROWID value for this entry */
  43505. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  43506. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  43507. };
  43508. /*
  43509. ** RowSetEntry objects are allocated in large chunks (instances of the
  43510. ** following structure) to reduce memory allocation overhead. The
  43511. ** chunks are kept on a linked list so that they can be deallocated
  43512. ** when the RowSet is destroyed.
  43513. */
  43514. struct RowSetChunk {
  43515. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  43516. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  43517. };
  43518. /*
  43519. ** A RowSet in an instance of the following structure.
  43520. **
  43521. ** A typedef of this structure if found in sqliteInt.h.
  43522. */
  43523. struct RowSet {
  43524. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  43525. sqlite3 *db; /* The database connection */
  43526. struct RowSetEntry *pEntry; /* List of entries using pRight */
  43527. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  43528. struct RowSetEntry *pFresh; /* Source of new entry objects */
  43529. struct RowSetEntry *pForest; /* List of binary trees of entries */
  43530. u16 nFresh; /* Number of objects on pFresh */
  43531. u16 rsFlags; /* Various flags */
  43532. int iBatch; /* Current insert batch */
  43533. };
  43534. /*
  43535. ** Allowed values for RowSet.rsFlags
  43536. */
  43537. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  43538. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  43539. /*
  43540. ** Turn bulk memory into a RowSet object. N bytes of memory
  43541. ** are available at pSpace. The db pointer is used as a memory context
  43542. ** for any subsequent allocations that need to occur.
  43543. ** Return a pointer to the new RowSet object.
  43544. **
  43545. ** It must be the case that N is sufficient to make a Rowset. If not
  43546. ** an assertion fault occurs.
  43547. **
  43548. ** If N is larger than the minimum, use the surplus as an initial
  43549. ** allocation of entries available to be filled.
  43550. */
  43551. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  43552. RowSet *p;
  43553. assert( N >= ROUND8(sizeof(*p)) );
  43554. p = pSpace;
  43555. p->pChunk = 0;
  43556. p->db = db;
  43557. p->pEntry = 0;
  43558. p->pLast = 0;
  43559. p->pForest = 0;
  43560. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  43561. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  43562. p->rsFlags = ROWSET_SORTED;
  43563. p->iBatch = 0;
  43564. return p;
  43565. }
  43566. /*
  43567. ** Deallocate all chunks from a RowSet. This frees all memory that
  43568. ** the RowSet has allocated over its lifetime. This routine is
  43569. ** the destructor for the RowSet.
  43570. */
  43571. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  43572. struct RowSetChunk *pChunk, *pNextChunk;
  43573. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  43574. pNextChunk = pChunk->pNextChunk;
  43575. sqlite3DbFree(p->db, pChunk);
  43576. }
  43577. p->pChunk = 0;
  43578. p->nFresh = 0;
  43579. p->pEntry = 0;
  43580. p->pLast = 0;
  43581. p->pForest = 0;
  43582. p->rsFlags = ROWSET_SORTED;
  43583. }
  43584. /*
  43585. ** Allocate a new RowSetEntry object that is associated with the
  43586. ** given RowSet. Return a pointer to the new and completely uninitialized
  43587. ** objected.
  43588. **
  43589. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  43590. ** routine returns NULL.
  43591. */
  43592. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  43593. assert( p!=0 );
  43594. if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
  43595. /* We could allocate a fresh RowSetEntry each time one is needed, but it
  43596. ** is more efficient to pull a preallocated entry from the pool */
  43597. struct RowSetChunk *pNew;
  43598. pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
  43599. if( pNew==0 ){
  43600. return 0;
  43601. }
  43602. pNew->pNextChunk = p->pChunk;
  43603. p->pChunk = pNew;
  43604. p->pFresh = pNew->aEntry;
  43605. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  43606. }
  43607. p->nFresh--;
  43608. return p->pFresh++;
  43609. }
  43610. /*
  43611. ** Insert a new value into a RowSet.
  43612. **
  43613. ** The mallocFailed flag of the database connection is set if a
  43614. ** memory allocation fails.
  43615. */
  43616. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  43617. struct RowSetEntry *pEntry; /* The new entry */
  43618. struct RowSetEntry *pLast; /* The last prior entry */
  43619. /* This routine is never called after sqlite3RowSetNext() */
  43620. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  43621. pEntry = rowSetEntryAlloc(p);
  43622. if( pEntry==0 ) return;
  43623. pEntry->v = rowid;
  43624. pEntry->pRight = 0;
  43625. pLast = p->pLast;
  43626. if( pLast ){
  43627. if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
  43628. /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
  43629. ** where possible */
  43630. p->rsFlags &= ~ROWSET_SORTED;
  43631. }
  43632. pLast->pRight = pEntry;
  43633. }else{
  43634. p->pEntry = pEntry;
  43635. }
  43636. p->pLast = pEntry;
  43637. }
  43638. /*
  43639. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  43640. **
  43641. ** The input lists are connected via pRight pointers and are
  43642. ** assumed to each already be in sorted order.
  43643. */
  43644. static struct RowSetEntry *rowSetEntryMerge(
  43645. struct RowSetEntry *pA, /* First sorted list to be merged */
  43646. struct RowSetEntry *pB /* Second sorted list to be merged */
  43647. ){
  43648. struct RowSetEntry head;
  43649. struct RowSetEntry *pTail;
  43650. pTail = &head;
  43651. assert( pA!=0 && pB!=0 );
  43652. for(;;){
  43653. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  43654. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  43655. if( pA->v<=pB->v ){
  43656. if( pA->v<pB->v ) pTail = pTail->pRight = pA;
  43657. pA = pA->pRight;
  43658. if( pA==0 ){
  43659. pTail->pRight = pB;
  43660. break;
  43661. }
  43662. }else{
  43663. pTail = pTail->pRight = pB;
  43664. pB = pB->pRight;
  43665. if( pB==0 ){
  43666. pTail->pRight = pA;
  43667. break;
  43668. }
  43669. }
  43670. }
  43671. return head.pRight;
  43672. }
  43673. /*
  43674. ** Sort all elements on the list of RowSetEntry objects into order of
  43675. ** increasing v.
  43676. */
  43677. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  43678. unsigned int i;
  43679. struct RowSetEntry *pNext, *aBucket[40];
  43680. memset(aBucket, 0, sizeof(aBucket));
  43681. while( pIn ){
  43682. pNext = pIn->pRight;
  43683. pIn->pRight = 0;
  43684. for(i=0; aBucket[i]; i++){
  43685. pIn = rowSetEntryMerge(aBucket[i], pIn);
  43686. aBucket[i] = 0;
  43687. }
  43688. aBucket[i] = pIn;
  43689. pIn = pNext;
  43690. }
  43691. pIn = aBucket[0];
  43692. for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  43693. if( aBucket[i]==0 ) continue;
  43694. pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
  43695. }
  43696. return pIn;
  43697. }
  43698. /*
  43699. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  43700. ** Convert this tree into a linked list connected by the pRight pointers
  43701. ** and return pointers to the first and last elements of the new list.
  43702. */
  43703. static void rowSetTreeToList(
  43704. struct RowSetEntry *pIn, /* Root of the input tree */
  43705. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  43706. struct RowSetEntry **ppLast /* Write tail of the output list here */
  43707. ){
  43708. assert( pIn!=0 );
  43709. if( pIn->pLeft ){
  43710. struct RowSetEntry *p;
  43711. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  43712. p->pRight = pIn;
  43713. }else{
  43714. *ppFirst = pIn;
  43715. }
  43716. if( pIn->pRight ){
  43717. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  43718. }else{
  43719. *ppLast = pIn;
  43720. }
  43721. assert( (*ppLast)->pRight==0 );
  43722. }
  43723. /*
  43724. ** Convert a sorted list of elements (connected by pRight) into a binary
  43725. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  43726. ** node taken from the head of *ppList. A depth of 2 means a tree with
  43727. ** three nodes. And so forth.
  43728. **
  43729. ** Use as many entries from the input list as required and update the
  43730. ** *ppList to point to the unused elements of the list. If the input
  43731. ** list contains too few elements, then construct an incomplete tree
  43732. ** and leave *ppList set to NULL.
  43733. **
  43734. ** Return a pointer to the root of the constructed binary tree.
  43735. */
  43736. static struct RowSetEntry *rowSetNDeepTree(
  43737. struct RowSetEntry **ppList,
  43738. int iDepth
  43739. ){
  43740. struct RowSetEntry *p; /* Root of the new tree */
  43741. struct RowSetEntry *pLeft; /* Left subtree */
  43742. if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
  43743. /* Prevent unnecessary deep recursion when we run out of entries */
  43744. return 0;
  43745. }
  43746. if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/
  43747. /* This branch causes a *balanced* tree to be generated. A valid tree
  43748. ** is still generated without this branch, but the tree is wildly
  43749. ** unbalanced and inefficient. */
  43750. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  43751. p = *ppList;
  43752. if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/
  43753. /* It is safe to always return here, but the resulting tree
  43754. ** would be unbalanced */
  43755. return pLeft;
  43756. }
  43757. p->pLeft = pLeft;
  43758. *ppList = p->pRight;
  43759. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  43760. }else{
  43761. p = *ppList;
  43762. *ppList = p->pRight;
  43763. p->pLeft = p->pRight = 0;
  43764. }
  43765. return p;
  43766. }
  43767. /*
  43768. ** Convert a sorted list of elements into a binary tree. Make the tree
  43769. ** as deep as it needs to be in order to contain the entire list.
  43770. */
  43771. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  43772. int iDepth; /* Depth of the tree so far */
  43773. struct RowSetEntry *p; /* Current tree root */
  43774. struct RowSetEntry *pLeft; /* Left subtree */
  43775. assert( pList!=0 );
  43776. p = pList;
  43777. pList = p->pRight;
  43778. p->pLeft = p->pRight = 0;
  43779. for(iDepth=1; pList; iDepth++){
  43780. pLeft = p;
  43781. p = pList;
  43782. pList = p->pRight;
  43783. p->pLeft = pLeft;
  43784. p->pRight = rowSetNDeepTree(&pList, iDepth);
  43785. }
  43786. return p;
  43787. }
  43788. /*
  43789. ** Extract the smallest element from the RowSet.
  43790. ** Write the element into *pRowid. Return 1 on success. Return
  43791. ** 0 if the RowSet is already empty.
  43792. **
  43793. ** After this routine has been called, the sqlite3RowSetInsert()
  43794. ** routine may not be called again.
  43795. **
  43796. ** This routine may not be called after sqlite3RowSetTest() has
  43797. ** been used. Older versions of RowSet allowed that, but as the
  43798. ** capability was not used by the code generator, it was removed
  43799. ** for code economy.
  43800. */
  43801. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  43802. assert( p!=0 );
  43803. assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */
  43804. /* Merge the forest into a single sorted list on first call */
  43805. if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  43806. if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  43807. p->pEntry = rowSetEntrySort(p->pEntry);
  43808. }
  43809. p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
  43810. }
  43811. /* Return the next entry on the list */
  43812. if( p->pEntry ){
  43813. *pRowid = p->pEntry->v;
  43814. p->pEntry = p->pEntry->pRight;
  43815. if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
  43816. /* Free memory immediately, rather than waiting on sqlite3_finalize() */
  43817. sqlite3RowSetClear(p);
  43818. }
  43819. return 1;
  43820. }else{
  43821. return 0;
  43822. }
  43823. }
  43824. /*
  43825. ** Check to see if element iRowid was inserted into the rowset as
  43826. ** part of any insert batch prior to iBatch. Return 1 or 0.
  43827. **
  43828. ** If this is the first test of a new batch and if there exist entries
  43829. ** on pRowSet->pEntry, then sort those entries into the forest at
  43830. ** pRowSet->pForest so that they can be tested.
  43831. */
  43832. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
  43833. struct RowSetEntry *p, *pTree;
  43834. /* This routine is never called after sqlite3RowSetNext() */
  43835. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  43836. /* Sort entries into the forest on the first test of a new batch.
  43837. ** To save unnecessary work, only do this when the batch number changes.
  43838. */
  43839. if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/
  43840. p = pRowSet->pEntry;
  43841. if( p ){
  43842. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  43843. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  43844. /* Only sort the current set of entiries if they need it */
  43845. p = rowSetEntrySort(p);
  43846. }
  43847. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  43848. ppPrevTree = &pTree->pRight;
  43849. if( pTree->pLeft==0 ){
  43850. pTree->pLeft = rowSetListToTree(p);
  43851. break;
  43852. }else{
  43853. struct RowSetEntry *pAux, *pTail;
  43854. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  43855. pTree->pLeft = 0;
  43856. p = rowSetEntryMerge(pAux, p);
  43857. }
  43858. }
  43859. if( pTree==0 ){
  43860. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  43861. if( pTree ){
  43862. pTree->v = 0;
  43863. pTree->pRight = 0;
  43864. pTree->pLeft = rowSetListToTree(p);
  43865. }
  43866. }
  43867. pRowSet->pEntry = 0;
  43868. pRowSet->pLast = 0;
  43869. pRowSet->rsFlags |= ROWSET_SORTED;
  43870. }
  43871. pRowSet->iBatch = iBatch;
  43872. }
  43873. /* Test to see if the iRowid value appears anywhere in the forest.
  43874. ** Return 1 if it does and 0 if not.
  43875. */
  43876. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  43877. p = pTree->pLeft;
  43878. while( p ){
  43879. if( p->v<iRowid ){
  43880. p = p->pRight;
  43881. }else if( p->v>iRowid ){
  43882. p = p->pLeft;
  43883. }else{
  43884. return 1;
  43885. }
  43886. }
  43887. }
  43888. return 0;
  43889. }
  43890. /************** End of rowset.c **********************************************/
  43891. /************** Begin file pager.c *******************************************/
  43892. /*
  43893. ** 2001 September 15
  43894. **
  43895. ** The author disclaims copyright to this source code. In place of
  43896. ** a legal notice, here is a blessing:
  43897. **
  43898. ** May you do good and not evil.
  43899. ** May you find forgiveness for yourself and forgive others.
  43900. ** May you share freely, never taking more than you give.
  43901. **
  43902. *************************************************************************
  43903. ** This is the implementation of the page cache subsystem or "pager".
  43904. **
  43905. ** The pager is used to access a database disk file. It implements
  43906. ** atomic commit and rollback through the use of a journal file that
  43907. ** is separate from the database file. The pager also implements file
  43908. ** locking to prevent two processes from writing the same database
  43909. ** file simultaneously, or one process from reading the database while
  43910. ** another is writing.
  43911. */
  43912. #ifndef SQLITE_OMIT_DISKIO
  43913. /* #include "sqliteInt.h" */
  43914. /************** Include wal.h in the middle of pager.c ***********************/
  43915. /************** Begin file wal.h *********************************************/
  43916. /*
  43917. ** 2010 February 1
  43918. **
  43919. ** The author disclaims copyright to this source code. In place of
  43920. ** a legal notice, here is a blessing:
  43921. **
  43922. ** May you do good and not evil.
  43923. ** May you find forgiveness for yourself and forgive others.
  43924. ** May you share freely, never taking more than you give.
  43925. **
  43926. *************************************************************************
  43927. ** This header file defines the interface to the write-ahead logging
  43928. ** system. Refer to the comments below and the header comment attached to
  43929. ** the implementation of each function in log.c for further details.
  43930. */
  43931. #ifndef SQLITE_WAL_H
  43932. #define SQLITE_WAL_H
  43933. /* #include "sqliteInt.h" */
  43934. /* Additional values that can be added to the sync_flags argument of
  43935. ** sqlite3WalFrames():
  43936. */
  43937. #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
  43938. #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
  43939. #ifdef SQLITE_OMIT_WAL
  43940. # define sqlite3WalOpen(x,y,z) 0
  43941. # define sqlite3WalLimit(x,y)
  43942. # define sqlite3WalClose(v,w,x,y,z) 0
  43943. # define sqlite3WalBeginReadTransaction(y,z) 0
  43944. # define sqlite3WalEndReadTransaction(z)
  43945. # define sqlite3WalDbsize(y) 0
  43946. # define sqlite3WalBeginWriteTransaction(y) 0
  43947. # define sqlite3WalEndWriteTransaction(x) 0
  43948. # define sqlite3WalUndo(x,y,z) 0
  43949. # define sqlite3WalSavepoint(y,z)
  43950. # define sqlite3WalSavepointUndo(y,z) 0
  43951. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  43952. # define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0
  43953. # define sqlite3WalCallback(z) 0
  43954. # define sqlite3WalExclusiveMode(y,z) 0
  43955. # define sqlite3WalHeapMemory(z) 0
  43956. # define sqlite3WalFramesize(z) 0
  43957. # define sqlite3WalFindFrame(x,y,z) 0
  43958. # define sqlite3WalFile(x) 0
  43959. #else
  43960. #define WAL_SAVEPOINT_NDATA 4
  43961. /* Connection to a write-ahead log (WAL) file.
  43962. ** There is one object of this type for each pager.
  43963. */
  43964. typedef struct Wal Wal;
  43965. /* Open and close a connection to a write-ahead log. */
  43966. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  43967. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);
  43968. /* Set the limiting size of a WAL file. */
  43969. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  43970. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  43971. ** snapshot is like a read-transaction. It is the state of the database
  43972. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  43973. ** preserves the current state even if the other threads or processes
  43974. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  43975. ** transaction and releases the lock.
  43976. */
  43977. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  43978. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  43979. /* Read a page from the write-ahead log, if it is present. */
  43980. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  43981. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  43982. /* If the WAL is not empty, return the size of the database. */
  43983. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  43984. /* Obtain or release the WRITER lock. */
  43985. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  43986. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  43987. /* Undo any frames written (but not committed) to the log */
  43988. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  43989. /* Return an integer that records the current (uncommitted) write
  43990. ** position in the WAL */
  43991. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  43992. /* Move the write position of the WAL back to iFrame. Called in
  43993. ** response to a ROLLBACK TO command. */
  43994. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  43995. /* Write a frame or frames to the log. */
  43996. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  43997. /* Copy pages from the log to the database file */
  43998. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  43999. Wal *pWal, /* Write-ahead log connection */
  44000. sqlite3 *db, /* Check this handle's interrupt flag */
  44001. int eMode, /* One of PASSIVE, FULL and RESTART */
  44002. int (*xBusy)(void*), /* Function to call when busy */
  44003. void *pBusyArg, /* Context argument for xBusyHandler */
  44004. int sync_flags, /* Flags to sync db file with (or 0) */
  44005. int nBuf, /* Size of buffer nBuf */
  44006. u8 *zBuf, /* Temporary buffer to use */
  44007. int *pnLog, /* OUT: Number of frames in WAL */
  44008. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  44009. );
  44010. /* Return the value to pass to a sqlite3_wal_hook callback, the
  44011. ** number of frames in the WAL at the point of the last commit since
  44012. ** sqlite3WalCallback() was called. If no commits have occurred since
  44013. ** the last call, then return 0.
  44014. */
  44015. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  44016. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  44017. ** by the pager layer on the database file.
  44018. */
  44019. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  44020. /* Return true if the argument is non-NULL and the WAL module is using
  44021. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  44022. ** WAL module is using shared-memory, return false.
  44023. */
  44024. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  44025. #ifdef SQLITE_ENABLE_SNAPSHOT
  44026. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
  44027. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
  44028. SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal);
  44029. #endif
  44030. #ifdef SQLITE_ENABLE_ZIPVFS
  44031. /* If the WAL file is not empty, return the number of bytes of content
  44032. ** stored in each frame (i.e. the db page-size when the WAL was created).
  44033. */
  44034. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  44035. #endif
  44036. /* Return the sqlite3_file object for the WAL file */
  44037. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
  44038. #endif /* ifndef SQLITE_OMIT_WAL */
  44039. #endif /* SQLITE_WAL_H */
  44040. /************** End of wal.h *************************************************/
  44041. /************** Continuing where we left off in pager.c **********************/
  44042. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  44043. **
  44044. ** This comment block describes invariants that hold when using a rollback
  44045. ** journal. These invariants do not apply for journal_mode=WAL,
  44046. ** journal_mode=MEMORY, or journal_mode=OFF.
  44047. **
  44048. ** Within this comment block, a page is deemed to have been synced
  44049. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  44050. ** Otherwise, the page is not synced until the xSync method of the VFS
  44051. ** is called successfully on the file containing the page.
  44052. **
  44053. ** Definition: A page of the database file is said to be "overwriteable" if
  44054. ** one or more of the following are true about the page:
  44055. **
  44056. ** (a) The original content of the page as it was at the beginning of
  44057. ** the transaction has been written into the rollback journal and
  44058. ** synced.
  44059. **
  44060. ** (b) The page was a freelist leaf page at the start of the transaction.
  44061. **
  44062. ** (c) The page number is greater than the largest page that existed in
  44063. ** the database file at the start of the transaction.
  44064. **
  44065. ** (1) A page of the database file is never overwritten unless one of the
  44066. ** following are true:
  44067. **
  44068. ** (a) The page and all other pages on the same sector are overwriteable.
  44069. **
  44070. ** (b) The atomic page write optimization is enabled, and the entire
  44071. ** transaction other than the update of the transaction sequence
  44072. ** number consists of a single page change.
  44073. **
  44074. ** (2) The content of a page written into the rollback journal exactly matches
  44075. ** both the content in the database when the rollback journal was written
  44076. ** and the content in the database at the beginning of the current
  44077. ** transaction.
  44078. **
  44079. ** (3) Writes to the database file are an integer multiple of the page size
  44080. ** in length and are aligned on a page boundary.
  44081. **
  44082. ** (4) Reads from the database file are either aligned on a page boundary and
  44083. ** an integer multiple of the page size in length or are taken from the
  44084. ** first 100 bytes of the database file.
  44085. **
  44086. ** (5) All writes to the database file are synced prior to the rollback journal
  44087. ** being deleted, truncated, or zeroed.
  44088. **
  44089. ** (6) If a master journal file is used, then all writes to the database file
  44090. ** are synced prior to the master journal being deleted.
  44091. **
  44092. ** Definition: Two databases (or the same database at two points it time)
  44093. ** are said to be "logically equivalent" if they give the same answer to
  44094. ** all queries. Note in particular the content of freelist leaf
  44095. ** pages can be changed arbitrarily without affecting the logical equivalence
  44096. ** of the database.
  44097. **
  44098. ** (7) At any time, if any subset, including the empty set and the total set,
  44099. ** of the unsynced changes to a rollback journal are removed and the
  44100. ** journal is rolled back, the resulting database file will be logically
  44101. ** equivalent to the database file at the beginning of the transaction.
  44102. **
  44103. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  44104. ** is called to restore the database file to the same size it was at
  44105. ** the beginning of the transaction. (In some VFSes, the xTruncate
  44106. ** method is a no-op, but that does not change the fact the SQLite will
  44107. ** invoke it.)
  44108. **
  44109. ** (9) Whenever the database file is modified, at least one bit in the range
  44110. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  44111. ** the EXCLUSIVE lock, thus signaling other connections on the same
  44112. ** database to flush their caches.
  44113. **
  44114. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  44115. ** than one billion transactions.
  44116. **
  44117. ** (11) A database file is well-formed at the beginning and at the conclusion
  44118. ** of every transaction.
  44119. **
  44120. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  44121. ** the database file.
  44122. **
  44123. ** (13) A SHARED lock is held on the database file while reading any
  44124. ** content out of the database file.
  44125. **
  44126. ******************************************************************************/
  44127. /*
  44128. ** Macros for troubleshooting. Normally turned off
  44129. */
  44130. #if 0
  44131. int sqlite3PagerTrace=1; /* True to enable tracing */
  44132. #define sqlite3DebugPrintf printf
  44133. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  44134. #else
  44135. #define PAGERTRACE(X)
  44136. #endif
  44137. /*
  44138. ** The following two macros are used within the PAGERTRACE() macros above
  44139. ** to print out file-descriptors.
  44140. **
  44141. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  44142. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  44143. ** struct as its argument.
  44144. */
  44145. #define PAGERID(p) ((int)(p->fd))
  44146. #define FILEHANDLEID(fd) ((int)fd)
  44147. /*
  44148. ** The Pager.eState variable stores the current 'state' of a pager. A
  44149. ** pager may be in any one of the seven states shown in the following
  44150. ** state diagram.
  44151. **
  44152. ** OPEN <------+------+
  44153. ** | | |
  44154. ** V | |
  44155. ** +---------> READER-------+ |
  44156. ** | | |
  44157. ** | V |
  44158. ** |<-------WRITER_LOCKED------> ERROR
  44159. ** | | ^
  44160. ** | V |
  44161. ** |<------WRITER_CACHEMOD-------->|
  44162. ** | | |
  44163. ** | V |
  44164. ** |<-------WRITER_DBMOD---------->|
  44165. ** | | |
  44166. ** | V |
  44167. ** +<------WRITER_FINISHED-------->+
  44168. **
  44169. **
  44170. ** List of state transitions and the C [function] that performs each:
  44171. **
  44172. ** OPEN -> READER [sqlite3PagerSharedLock]
  44173. ** READER -> OPEN [pager_unlock]
  44174. **
  44175. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  44176. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  44177. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  44178. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  44179. ** WRITER_*** -> READER [pager_end_transaction]
  44180. **
  44181. ** WRITER_*** -> ERROR [pager_error]
  44182. ** ERROR -> OPEN [pager_unlock]
  44183. **
  44184. **
  44185. ** OPEN:
  44186. **
  44187. ** The pager starts up in this state. Nothing is guaranteed in this
  44188. ** state - the file may or may not be locked and the database size is
  44189. ** unknown. The database may not be read or written.
  44190. **
  44191. ** * No read or write transaction is active.
  44192. ** * Any lock, or no lock at all, may be held on the database file.
  44193. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  44194. **
  44195. ** READER:
  44196. **
  44197. ** In this state all the requirements for reading the database in
  44198. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  44199. ** was) in exclusive-locking mode, a user-level read transaction is
  44200. ** open. The database size is known in this state.
  44201. **
  44202. ** A connection running with locking_mode=normal enters this state when
  44203. ** it opens a read-transaction on the database and returns to state
  44204. ** OPEN after the read-transaction is completed. However a connection
  44205. ** running in locking_mode=exclusive (including temp databases) remains in
  44206. ** this state even after the read-transaction is closed. The only way
  44207. ** a locking_mode=exclusive connection can transition from READER to OPEN
  44208. ** is via the ERROR state (see below).
  44209. **
  44210. ** * A read transaction may be active (but a write-transaction cannot).
  44211. ** * A SHARED or greater lock is held on the database file.
  44212. ** * The dbSize variable may be trusted (even if a user-level read
  44213. ** transaction is not active). The dbOrigSize and dbFileSize variables
  44214. ** may not be trusted at this point.
  44215. ** * If the database is a WAL database, then the WAL connection is open.
  44216. ** * Even if a read-transaction is not open, it is guaranteed that
  44217. ** there is no hot-journal in the file-system.
  44218. **
  44219. ** WRITER_LOCKED:
  44220. **
  44221. ** The pager moves to this state from READER when a write-transaction
  44222. ** is first opened on the database. In WRITER_LOCKED state, all locks
  44223. ** required to start a write-transaction are held, but no actual
  44224. ** modifications to the cache or database have taken place.
  44225. **
  44226. ** In rollback mode, a RESERVED or (if the transaction was opened with
  44227. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  44228. ** moving to this state, but the journal file is not written to or opened
  44229. ** to in this state. If the transaction is committed or rolled back while
  44230. ** in WRITER_LOCKED state, all that is required is to unlock the database
  44231. ** file.
  44232. **
  44233. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  44234. ** If the connection is running with locking_mode=exclusive, an attempt
  44235. ** is made to obtain an EXCLUSIVE lock on the database file.
  44236. **
  44237. ** * A write transaction is active.
  44238. ** * If the connection is open in rollback-mode, a RESERVED or greater
  44239. ** lock is held on the database file.
  44240. ** * If the connection is open in WAL-mode, a WAL write transaction
  44241. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  44242. ** called).
  44243. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  44244. ** * The contents of the pager cache have not been modified.
  44245. ** * The journal file may or may not be open.
  44246. ** * Nothing (not even the first header) has been written to the journal.
  44247. **
  44248. ** WRITER_CACHEMOD:
  44249. **
  44250. ** A pager moves from WRITER_LOCKED state to this state when a page is
  44251. ** first modified by the upper layer. In rollback mode the journal file
  44252. ** is opened (if it is not already open) and a header written to the
  44253. ** start of it. The database file on disk has not been modified.
  44254. **
  44255. ** * A write transaction is active.
  44256. ** * A RESERVED or greater lock is held on the database file.
  44257. ** * The journal file is open and the first header has been written
  44258. ** to it, but the header has not been synced to disk.
  44259. ** * The contents of the page cache have been modified.
  44260. **
  44261. ** WRITER_DBMOD:
  44262. **
  44263. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  44264. ** when it modifies the contents of the database file. WAL connections
  44265. ** never enter this state (since they do not modify the database file,
  44266. ** just the log file).
  44267. **
  44268. ** * A write transaction is active.
  44269. ** * An EXCLUSIVE or greater lock is held on the database file.
  44270. ** * The journal file is open and the first header has been written
  44271. ** and synced to disk.
  44272. ** * The contents of the page cache have been modified (and possibly
  44273. ** written to disk).
  44274. **
  44275. ** WRITER_FINISHED:
  44276. **
  44277. ** It is not possible for a WAL connection to enter this state.
  44278. **
  44279. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  44280. ** state after the entire transaction has been successfully written into the
  44281. ** database file. In this state the transaction may be committed simply
  44282. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  44283. ** not possible to modify the database further. At this point, the upper
  44284. ** layer must either commit or rollback the transaction.
  44285. **
  44286. ** * A write transaction is active.
  44287. ** * An EXCLUSIVE or greater lock is held on the database file.
  44288. ** * All writing and syncing of journal and database data has finished.
  44289. ** If no error occurred, all that remains is to finalize the journal to
  44290. ** commit the transaction. If an error did occur, the caller will need
  44291. ** to rollback the transaction.
  44292. **
  44293. ** ERROR:
  44294. **
  44295. ** The ERROR state is entered when an IO or disk-full error (including
  44296. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  44297. ** difficult to be sure that the in-memory pager state (cache contents,
  44298. ** db size etc.) are consistent with the contents of the file-system.
  44299. **
  44300. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  44301. ** cannot.
  44302. **
  44303. ** For example, if an IO error occurs while performing a rollback,
  44304. ** the contents of the page-cache may be left in an inconsistent state.
  44305. ** At this point it would be dangerous to change back to READER state
  44306. ** (as usually happens after a rollback). Any subsequent readers might
  44307. ** report database corruption (due to the inconsistent cache), and if
  44308. ** they upgrade to writers, they may inadvertently corrupt the database
  44309. ** file. To avoid this hazard, the pager switches into the ERROR state
  44310. ** instead of READER following such an error.
  44311. **
  44312. ** Once it has entered the ERROR state, any attempt to use the pager
  44313. ** to read or write data returns an error. Eventually, once all
  44314. ** outstanding transactions have been abandoned, the pager is able to
  44315. ** transition back to OPEN state, discarding the contents of the
  44316. ** page-cache and any other in-memory state at the same time. Everything
  44317. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  44318. ** when a read-transaction is next opened on the pager (transitioning
  44319. ** the pager into READER state). At that point the system has recovered
  44320. ** from the error.
  44321. **
  44322. ** Specifically, the pager jumps into the ERROR state if:
  44323. **
  44324. ** 1. An error occurs while attempting a rollback. This happens in
  44325. ** function sqlite3PagerRollback().
  44326. **
  44327. ** 2. An error occurs while attempting to finalize a journal file
  44328. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  44329. **
  44330. ** 3. An error occurs while attempting to write to the journal or
  44331. ** database file in function pagerStress() in order to free up
  44332. ** memory.
  44333. **
  44334. ** In other cases, the error is returned to the b-tree layer. The b-tree
  44335. ** layer then attempts a rollback operation. If the error condition
  44336. ** persists, the pager enters the ERROR state via condition (1) above.
  44337. **
  44338. ** Condition (3) is necessary because it can be triggered by a read-only
  44339. ** statement executed within a transaction. In this case, if the error
  44340. ** code were simply returned to the user, the b-tree layer would not
  44341. ** automatically attempt a rollback, as it assumes that an error in a
  44342. ** read-only statement cannot leave the pager in an internally inconsistent
  44343. ** state.
  44344. **
  44345. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  44346. ** * There are one or more outstanding references to pages (after the
  44347. ** last reference is dropped the pager should move back to OPEN state).
  44348. ** * The pager is not an in-memory pager.
  44349. **
  44350. **
  44351. ** Notes:
  44352. **
  44353. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  44354. ** connection is open in WAL mode. A WAL connection is always in one
  44355. ** of the first four states.
  44356. **
  44357. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  44358. ** state. There are two exceptions: immediately after exclusive-mode has
  44359. ** been turned on (and before any read or write transactions are
  44360. ** executed), and when the pager is leaving the "error state".
  44361. **
  44362. ** * See also: assert_pager_state().
  44363. */
  44364. #define PAGER_OPEN 0
  44365. #define PAGER_READER 1
  44366. #define PAGER_WRITER_LOCKED 2
  44367. #define PAGER_WRITER_CACHEMOD 3
  44368. #define PAGER_WRITER_DBMOD 4
  44369. #define PAGER_WRITER_FINISHED 5
  44370. #define PAGER_ERROR 6
  44371. /*
  44372. ** The Pager.eLock variable is almost always set to one of the
  44373. ** following locking-states, according to the lock currently held on
  44374. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  44375. ** This variable is kept up to date as locks are taken and released by
  44376. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  44377. **
  44378. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  44379. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  44380. ** the operation was successful. In these circumstances pagerLockDb() and
  44381. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  44382. ** when unlocking the file, and only updated when locking the file if the
  44383. ** VFS call is successful. This way, the Pager.eLock variable may be set
  44384. ** to a less exclusive (lower) value than the lock that is actually held
  44385. ** at the system level, but it is never set to a more exclusive value.
  44386. **
  44387. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  44388. ** be a few redundant xLock() calls or a lock may be held for longer than
  44389. ** required, but nothing really goes wrong.
  44390. **
  44391. ** The exception is when the database file is unlocked as the pager moves
  44392. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  44393. ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
  44394. ** transition, by the same pager or any other). If the call to xUnlock()
  44395. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  44396. ** can confuse the call to xCheckReservedLock() call made later as part
  44397. ** of hot-journal detection.
  44398. **
  44399. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  44400. ** lock held by this process or any others". So xCheckReservedLock may
  44401. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  44402. ** doesn't know it because of a previous error in xUnlock). If this happens
  44403. ** a hot-journal may be mistaken for a journal being created by an active
  44404. ** transaction in another process, causing SQLite to read from the database
  44405. ** without rolling it back.
  44406. **
  44407. ** To work around this, if a call to xUnlock() fails when unlocking the
  44408. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  44409. ** is only changed back to a real locking state after a successful call
  44410. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  44411. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  44412. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  44413. ** lock on the database file before attempting to roll it back. See function
  44414. ** PagerSharedLock() for more detail.
  44415. **
  44416. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  44417. ** PAGER_OPEN state.
  44418. */
  44419. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  44420. /*
  44421. ** A macro used for invoking the codec if there is one
  44422. */
  44423. #ifdef SQLITE_HAS_CODEC
  44424. # define CODEC1(P,D,N,X,E) \
  44425. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  44426. # define CODEC2(P,D,N,X,E,O) \
  44427. if( P->xCodec==0 ){ O=(char*)D; }else \
  44428. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  44429. #else
  44430. # define CODEC1(P,D,N,X,E) /* NO-OP */
  44431. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  44432. #endif
  44433. /*
  44434. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  44435. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  44436. ** This could conceivably cause corruption following a power failure on
  44437. ** such a system. This is currently an undocumented limit.
  44438. */
  44439. #define MAX_SECTOR_SIZE 0x10000
  44440. /*
  44441. ** An instance of the following structure is allocated for each active
  44442. ** savepoint and statement transaction in the system. All such structures
  44443. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  44444. ** resized using sqlite3Realloc().
  44445. **
  44446. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  44447. ** set to 0. If a journal-header is written into the main journal while
  44448. ** the savepoint is active, then iHdrOffset is set to the byte offset
  44449. ** immediately following the last journal record written into the main
  44450. ** journal before the journal-header. This is required during savepoint
  44451. ** rollback (see pagerPlaybackSavepoint()).
  44452. */
  44453. typedef struct PagerSavepoint PagerSavepoint;
  44454. struct PagerSavepoint {
  44455. i64 iOffset; /* Starting offset in main journal */
  44456. i64 iHdrOffset; /* See above */
  44457. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  44458. Pgno nOrig; /* Original number of pages in file */
  44459. Pgno iSubRec; /* Index of first record in sub-journal */
  44460. #ifndef SQLITE_OMIT_WAL
  44461. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  44462. #endif
  44463. };
  44464. /*
  44465. ** Bits of the Pager.doNotSpill flag. See further description below.
  44466. */
  44467. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  44468. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  44469. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  44470. /*
  44471. ** An open page cache is an instance of struct Pager. A description of
  44472. ** some of the more important member variables follows:
  44473. **
  44474. ** eState
  44475. **
  44476. ** The current 'state' of the pager object. See the comment and state
  44477. ** diagram above for a description of the pager state.
  44478. **
  44479. ** eLock
  44480. **
  44481. ** For a real on-disk database, the current lock held on the database file -
  44482. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  44483. **
  44484. ** For a temporary or in-memory database (neither of which require any
  44485. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  44486. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  44487. ** logic into thinking that it already has all the locks it will ever
  44488. ** need (and no reason to release them).
  44489. **
  44490. ** In some (obscure) circumstances, this variable may also be set to
  44491. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  44492. ** details.
  44493. **
  44494. ** changeCountDone
  44495. **
  44496. ** This boolean variable is used to make sure that the change-counter
  44497. ** (the 4-byte header field at byte offset 24 of the database file) is
  44498. ** not updated more often than necessary.
  44499. **
  44500. ** It is set to true when the change-counter field is updated, which
  44501. ** can only happen if an exclusive lock is held on the database file.
  44502. ** It is cleared (set to false) whenever an exclusive lock is
  44503. ** relinquished on the database file. Each time a transaction is committed,
  44504. ** The changeCountDone flag is inspected. If it is true, the work of
  44505. ** updating the change-counter is omitted for the current transaction.
  44506. **
  44507. ** This mechanism means that when running in exclusive mode, a connection
  44508. ** need only update the change-counter once, for the first transaction
  44509. ** committed.
  44510. **
  44511. ** setMaster
  44512. **
  44513. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  44514. ** (or may not) specify a master-journal name to be written into the
  44515. ** journal file before it is synced to disk.
  44516. **
  44517. ** Whether or not a journal file contains a master-journal pointer affects
  44518. ** the way in which the journal file is finalized after the transaction is
  44519. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  44520. ** If a journal file does not contain a master-journal pointer, it is
  44521. ** finalized by overwriting the first journal header with zeroes. If
  44522. ** it does contain a master-journal pointer the journal file is finalized
  44523. ** by truncating it to zero bytes, just as if the connection were
  44524. ** running in "journal_mode=truncate" mode.
  44525. **
  44526. ** Journal files that contain master journal pointers cannot be finalized
  44527. ** simply by overwriting the first journal-header with zeroes, as the
  44528. ** master journal pointer could interfere with hot-journal rollback of any
  44529. ** subsequently interrupted transaction that reuses the journal file.
  44530. **
  44531. ** The flag is cleared as soon as the journal file is finalized (either
  44532. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  44533. ** journal file from being successfully finalized, the setMaster flag
  44534. ** is cleared anyway (and the pager will move to ERROR state).
  44535. **
  44536. ** doNotSpill
  44537. **
  44538. ** This variables control the behavior of cache-spills (calls made by
  44539. ** the pcache module to the pagerStress() routine to write cached data
  44540. ** to the file-system in order to free up memory).
  44541. **
  44542. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  44543. ** writing to the database from pagerStress() is disabled altogether.
  44544. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  44545. ** comes up during savepoint rollback that requires the pcache module
  44546. ** to allocate a new page to prevent the journal file from being written
  44547. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  44548. ** case is a user preference.
  44549. **
  44550. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from
  44551. ** pagerStress() is permitted, but syncing the journal file is not.
  44552. ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
  44553. ** is larger than the database page-size in order to prevent a journal sync
  44554. ** from happening in between the journalling of two pages on the same sector.
  44555. **
  44556. ** subjInMemory
  44557. **
  44558. ** This is a boolean variable. If true, then any required sub-journal
  44559. ** is opened as an in-memory journal file. If false, then in-memory
  44560. ** sub-journals are only used for in-memory pager files.
  44561. **
  44562. ** This variable is updated by the upper layer each time a new
  44563. ** write-transaction is opened.
  44564. **
  44565. ** dbSize, dbOrigSize, dbFileSize
  44566. **
  44567. ** Variable dbSize is set to the number of pages in the database file.
  44568. ** It is valid in PAGER_READER and higher states (all states except for
  44569. ** OPEN and ERROR).
  44570. **
  44571. ** dbSize is set based on the size of the database file, which may be
  44572. ** larger than the size of the database (the value stored at offset
  44573. ** 28 of the database header by the btree). If the size of the file
  44574. ** is not an integer multiple of the page-size, the value stored in
  44575. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  44576. ** Except, any file that is greater than 0 bytes in size is considered
  44577. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  44578. ** to dbSize==1).
  44579. **
  44580. ** During a write-transaction, if pages with page-numbers greater than
  44581. ** dbSize are modified in the cache, dbSize is updated accordingly.
  44582. ** Similarly, if the database is truncated using PagerTruncateImage(),
  44583. ** dbSize is updated.
  44584. **
  44585. ** Variables dbOrigSize and dbFileSize are valid in states
  44586. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  44587. ** variable at the start of the transaction. It is used during rollback,
  44588. ** and to determine whether or not pages need to be journalled before
  44589. ** being modified.
  44590. **
  44591. ** Throughout a write-transaction, dbFileSize contains the size of
  44592. ** the file on disk in pages. It is set to a copy of dbSize when the
  44593. ** write-transaction is first opened, and updated when VFS calls are made
  44594. ** to write or truncate the database file on disk.
  44595. **
  44596. ** The only reason the dbFileSize variable is required is to suppress
  44597. ** unnecessary calls to xTruncate() after committing a transaction. If,
  44598. ** when a transaction is committed, the dbFileSize variable indicates
  44599. ** that the database file is larger than the database image (Pager.dbSize),
  44600. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  44601. ** to measure the database file on disk, and then truncates it if required.
  44602. ** dbFileSize is not used when rolling back a transaction. In this case
  44603. ** pager_truncate() is called unconditionally (which means there may be
  44604. ** a call to xFilesize() that is not strictly required). In either case,
  44605. ** pager_truncate() may cause the file to become smaller or larger.
  44606. **
  44607. ** dbHintSize
  44608. **
  44609. ** The dbHintSize variable is used to limit the number of calls made to
  44610. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  44611. **
  44612. ** dbHintSize is set to a copy of the dbSize variable when a
  44613. ** write-transaction is opened (at the same time as dbFileSize and
  44614. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  44615. ** dbHintSize is increased to the number of pages that correspond to the
  44616. ** size-hint passed to the method call. See pager_write_pagelist() for
  44617. ** details.
  44618. **
  44619. ** errCode
  44620. **
  44621. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  44622. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  44623. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  44624. ** sub-codes.
  44625. */
  44626. struct Pager {
  44627. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  44628. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  44629. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  44630. u8 useJournal; /* Use a rollback journal on this file */
  44631. u8 noSync; /* Do not sync the journal if true */
  44632. u8 fullSync; /* Do extra syncs of the journal for robustness */
  44633. u8 extraSync; /* sync directory after journal delete */
  44634. u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
  44635. u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
  44636. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  44637. u8 tempFile; /* zFilename is a temporary or immutable file */
  44638. u8 noLock; /* Do not lock (except in WAL mode) */
  44639. u8 readOnly; /* True for a read-only database */
  44640. u8 memDb; /* True to inhibit all file I/O */
  44641. /**************************************************************************
  44642. ** The following block contains those class members that change during
  44643. ** routine operation. Class members not in this block are either fixed
  44644. ** when the pager is first created or else only change when there is a
  44645. ** significant mode change (such as changing the page_size, locking_mode,
  44646. ** or the journal_mode). From another view, these class members describe
  44647. ** the "state" of the pager, while other class members describe the
  44648. ** "configuration" of the pager.
  44649. */
  44650. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  44651. u8 eLock; /* Current lock held on database file */
  44652. u8 changeCountDone; /* Set after incrementing the change-counter */
  44653. u8 setMaster; /* True if a m-j name has been written to jrnl */
  44654. u8 doNotSpill; /* Do not spill the cache when non-zero */
  44655. u8 subjInMemory; /* True to use in-memory sub-journals */
  44656. u8 bUseFetch; /* True to use xFetch() */
  44657. u8 hasHeldSharedLock; /* True if a shared lock has ever been held */
  44658. Pgno dbSize; /* Number of pages in the database */
  44659. Pgno dbOrigSize; /* dbSize before the current transaction */
  44660. Pgno dbFileSize; /* Number of pages in the database file */
  44661. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  44662. int errCode; /* One of several kinds of errors */
  44663. int nRec; /* Pages journalled since last j-header written */
  44664. u32 cksumInit; /* Quasi-random value added to every checksum */
  44665. u32 nSubRec; /* Number of records written to sub-journal */
  44666. Bitvec *pInJournal; /* One bit for each page in the database file */
  44667. sqlite3_file *fd; /* File descriptor for database */
  44668. sqlite3_file *jfd; /* File descriptor for main journal */
  44669. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  44670. i64 journalOff; /* Current write offset in the journal file */
  44671. i64 journalHdr; /* Byte offset to previous journal header */
  44672. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  44673. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  44674. int nSavepoint; /* Number of elements in aSavepoint[] */
  44675. u32 iDataVersion; /* Changes whenever database content changes */
  44676. char dbFileVers[16]; /* Changes whenever database file changes */
  44677. int nMmapOut; /* Number of mmap pages currently outstanding */
  44678. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  44679. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  44680. /*
  44681. ** End of the routinely-changing class members
  44682. ***************************************************************************/
  44683. u16 nExtra; /* Add this many bytes to each in-memory page */
  44684. i16 nReserve; /* Number of unused bytes at end of each page */
  44685. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  44686. u32 sectorSize; /* Assumed sector size during rollback */
  44687. int pageSize; /* Number of bytes in a page */
  44688. Pgno mxPgno; /* Maximum allowed size of the database */
  44689. i64 journalSizeLimit; /* Size limit for persistent journal files */
  44690. char *zFilename; /* Name of the database file */
  44691. char *zJournal; /* Name of the journal file */
  44692. int (*xBusyHandler)(void*); /* Function to call when busy */
  44693. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  44694. int aStat[3]; /* Total cache hits, misses and writes */
  44695. #ifdef SQLITE_TEST
  44696. int nRead; /* Database pages read */
  44697. #endif
  44698. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  44699. int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
  44700. #ifdef SQLITE_HAS_CODEC
  44701. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  44702. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  44703. void (*xCodecFree)(void*); /* Destructor for the codec */
  44704. void *pCodec; /* First argument to xCodec... methods */
  44705. #endif
  44706. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  44707. PCache *pPCache; /* Pointer to page cache object */
  44708. #ifndef SQLITE_OMIT_WAL
  44709. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  44710. char *zWal; /* File name for write-ahead log */
  44711. #endif
  44712. };
  44713. /*
  44714. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  44715. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  44716. ** or CACHE_WRITE to sqlite3_db_status().
  44717. */
  44718. #define PAGER_STAT_HIT 0
  44719. #define PAGER_STAT_MISS 1
  44720. #define PAGER_STAT_WRITE 2
  44721. /*
  44722. ** The following global variables hold counters used for
  44723. ** testing purposes only. These variables do not exist in
  44724. ** a non-testing build. These variables are not thread-safe.
  44725. */
  44726. #ifdef SQLITE_TEST
  44727. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  44728. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  44729. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  44730. # define PAGER_INCR(v) v++
  44731. #else
  44732. # define PAGER_INCR(v)
  44733. #endif
  44734. /*
  44735. ** Journal files begin with the following magic string. The data
  44736. ** was obtained from /dev/random. It is used only as a sanity check.
  44737. **
  44738. ** Since version 2.8.0, the journal format contains additional sanity
  44739. ** checking information. If the power fails while the journal is being
  44740. ** written, semi-random garbage data might appear in the journal
  44741. ** file after power is restored. If an attempt is then made
  44742. ** to roll the journal back, the database could be corrupted. The additional
  44743. ** sanity checking data is an attempt to discover the garbage in the
  44744. ** journal and ignore it.
  44745. **
  44746. ** The sanity checking information for the new journal format consists
  44747. ** of a 32-bit checksum on each page of data. The checksum covers both
  44748. ** the page number and the pPager->pageSize bytes of data for the page.
  44749. ** This cksum is initialized to a 32-bit random value that appears in the
  44750. ** journal file right after the header. The random initializer is important,
  44751. ** because garbage data that appears at the end of a journal is likely
  44752. ** data that was once in other files that have now been deleted. If the
  44753. ** garbage data came from an obsolete journal file, the checksums might
  44754. ** be correct. But by initializing the checksum to random value which
  44755. ** is different for every journal, we minimize that risk.
  44756. */
  44757. static const unsigned char aJournalMagic[] = {
  44758. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  44759. };
  44760. /*
  44761. ** The size of the of each page record in the journal is given by
  44762. ** the following macro.
  44763. */
  44764. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  44765. /*
  44766. ** The journal header size for this pager. This is usually the same
  44767. ** size as a single disk sector. See also setSectorSize().
  44768. */
  44769. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  44770. /*
  44771. ** The macro MEMDB is true if we are dealing with an in-memory database.
  44772. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  44773. ** the value of MEMDB will be a constant and the compiler will optimize
  44774. ** out code that would never execute.
  44775. */
  44776. #ifdef SQLITE_OMIT_MEMORYDB
  44777. # define MEMDB 0
  44778. #else
  44779. # define MEMDB pPager->memDb
  44780. #endif
  44781. /*
  44782. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  44783. ** interfaces to access the database using memory-mapped I/O.
  44784. */
  44785. #if SQLITE_MAX_MMAP_SIZE>0
  44786. # define USEFETCH(x) ((x)->bUseFetch)
  44787. #else
  44788. # define USEFETCH(x) 0
  44789. #endif
  44790. /*
  44791. ** The maximum legal page number is (2^31 - 1).
  44792. */
  44793. #define PAGER_MAX_PGNO 2147483647
  44794. /*
  44795. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  44796. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  44797. **
  44798. ** This is so that expressions can be written as:
  44799. **
  44800. ** if( isOpen(pPager->jfd) ){ ...
  44801. **
  44802. ** instead of
  44803. **
  44804. ** if( pPager->jfd->pMethods ){ ...
  44805. */
  44806. #define isOpen(pFd) ((pFd)->pMethods!=0)
  44807. /*
  44808. ** Return true if this pager uses a write-ahead log to read page pgno.
  44809. ** Return false if the pager reads pgno directly from the database.
  44810. */
  44811. #if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_DIRECT_OVERFLOW_READ)
  44812. SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno pgno){
  44813. u32 iRead = 0;
  44814. int rc;
  44815. if( pPager->pWal==0 ) return 0;
  44816. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
  44817. return rc || iRead;
  44818. }
  44819. #endif
  44820. #ifndef SQLITE_OMIT_WAL
  44821. # define pagerUseWal(x) ((x)->pWal!=0)
  44822. #else
  44823. # define pagerUseWal(x) 0
  44824. # define pagerRollbackWal(x) 0
  44825. # define pagerWalFrames(v,w,x,y) 0
  44826. # define pagerOpenWalIfPresent(z) SQLITE_OK
  44827. # define pagerBeginReadTransaction(z) SQLITE_OK
  44828. #endif
  44829. #ifndef NDEBUG
  44830. /*
  44831. ** Usage:
  44832. **
  44833. ** assert( assert_pager_state(pPager) );
  44834. **
  44835. ** This function runs many asserts to try to find inconsistencies in
  44836. ** the internal state of the Pager object.
  44837. */
  44838. static int assert_pager_state(Pager *p){
  44839. Pager *pPager = p;
  44840. /* State must be valid. */
  44841. assert( p->eState==PAGER_OPEN
  44842. || p->eState==PAGER_READER
  44843. || p->eState==PAGER_WRITER_LOCKED
  44844. || p->eState==PAGER_WRITER_CACHEMOD
  44845. || p->eState==PAGER_WRITER_DBMOD
  44846. || p->eState==PAGER_WRITER_FINISHED
  44847. || p->eState==PAGER_ERROR
  44848. );
  44849. /* Regardless of the current state, a temp-file connection always behaves
  44850. ** as if it has an exclusive lock on the database file. It never updates
  44851. ** the change-counter field, so the changeCountDone flag is always set.
  44852. */
  44853. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  44854. assert( p->tempFile==0 || pPager->changeCountDone );
  44855. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  44856. ** And if the journal-mode is "OFF", the journal file must not be open.
  44857. */
  44858. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  44859. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  44860. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  44861. ** this means an in-memory pager performs no IO at all, it cannot encounter
  44862. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  44863. ** a journal file. (although the in-memory journal implementation may
  44864. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  44865. ** is therefore not possible for an in-memory pager to enter the ERROR
  44866. ** state.
  44867. */
  44868. if( MEMDB ){
  44869. assert( !isOpen(p->fd) );
  44870. assert( p->noSync );
  44871. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  44872. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  44873. );
  44874. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  44875. assert( pagerUseWal(p)==0 );
  44876. }
  44877. /* If changeCountDone is set, a RESERVED lock or greater must be held
  44878. ** on the file.
  44879. */
  44880. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  44881. assert( p->eLock!=PENDING_LOCK );
  44882. switch( p->eState ){
  44883. case PAGER_OPEN:
  44884. assert( !MEMDB );
  44885. assert( pPager->errCode==SQLITE_OK );
  44886. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  44887. break;
  44888. case PAGER_READER:
  44889. assert( pPager->errCode==SQLITE_OK );
  44890. assert( p->eLock!=UNKNOWN_LOCK );
  44891. assert( p->eLock>=SHARED_LOCK );
  44892. break;
  44893. case PAGER_WRITER_LOCKED:
  44894. assert( p->eLock!=UNKNOWN_LOCK );
  44895. assert( pPager->errCode==SQLITE_OK );
  44896. if( !pagerUseWal(pPager) ){
  44897. assert( p->eLock>=RESERVED_LOCK );
  44898. }
  44899. assert( pPager->dbSize==pPager->dbOrigSize );
  44900. assert( pPager->dbOrigSize==pPager->dbFileSize );
  44901. assert( pPager->dbOrigSize==pPager->dbHintSize );
  44902. assert( pPager->setMaster==0 );
  44903. break;
  44904. case PAGER_WRITER_CACHEMOD:
  44905. assert( p->eLock!=UNKNOWN_LOCK );
  44906. assert( pPager->errCode==SQLITE_OK );
  44907. if( !pagerUseWal(pPager) ){
  44908. /* It is possible that if journal_mode=wal here that neither the
  44909. ** journal file nor the WAL file are open. This happens during
  44910. ** a rollback transaction that switches from journal_mode=off
  44911. ** to journal_mode=wal.
  44912. */
  44913. assert( p->eLock>=RESERVED_LOCK );
  44914. assert( isOpen(p->jfd)
  44915. || p->journalMode==PAGER_JOURNALMODE_OFF
  44916. || p->journalMode==PAGER_JOURNALMODE_WAL
  44917. );
  44918. }
  44919. assert( pPager->dbOrigSize==pPager->dbFileSize );
  44920. assert( pPager->dbOrigSize==pPager->dbHintSize );
  44921. break;
  44922. case PAGER_WRITER_DBMOD:
  44923. assert( p->eLock==EXCLUSIVE_LOCK );
  44924. assert( pPager->errCode==SQLITE_OK );
  44925. assert( !pagerUseWal(pPager) );
  44926. assert( p->eLock>=EXCLUSIVE_LOCK );
  44927. assert( isOpen(p->jfd)
  44928. || p->journalMode==PAGER_JOURNALMODE_OFF
  44929. || p->journalMode==PAGER_JOURNALMODE_WAL
  44930. );
  44931. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  44932. break;
  44933. case PAGER_WRITER_FINISHED:
  44934. assert( p->eLock==EXCLUSIVE_LOCK );
  44935. assert( pPager->errCode==SQLITE_OK );
  44936. assert( !pagerUseWal(pPager) );
  44937. assert( isOpen(p->jfd)
  44938. || p->journalMode==PAGER_JOURNALMODE_OFF
  44939. || p->journalMode==PAGER_JOURNALMODE_WAL
  44940. );
  44941. break;
  44942. case PAGER_ERROR:
  44943. /* There must be at least one outstanding reference to the pager if
  44944. ** in ERROR state. Otherwise the pager should have already dropped
  44945. ** back to OPEN state.
  44946. */
  44947. assert( pPager->errCode!=SQLITE_OK );
  44948. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
  44949. break;
  44950. }
  44951. return 1;
  44952. }
  44953. #endif /* ifndef NDEBUG */
  44954. #ifdef SQLITE_DEBUG
  44955. /*
  44956. ** Return a pointer to a human readable string in a static buffer
  44957. ** containing the state of the Pager object passed as an argument. This
  44958. ** is intended to be used within debuggers. For example, as an alternative
  44959. ** to "print *pPager" in gdb:
  44960. **
  44961. ** (gdb) printf "%s", print_pager_state(pPager)
  44962. */
  44963. static char *print_pager_state(Pager *p){
  44964. static char zRet[1024];
  44965. sqlite3_snprintf(1024, zRet,
  44966. "Filename: %s\n"
  44967. "State: %s errCode=%d\n"
  44968. "Lock: %s\n"
  44969. "Locking mode: locking_mode=%s\n"
  44970. "Journal mode: journal_mode=%s\n"
  44971. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  44972. "Journal: journalOff=%lld journalHdr=%lld\n"
  44973. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  44974. , p->zFilename
  44975. , p->eState==PAGER_OPEN ? "OPEN" :
  44976. p->eState==PAGER_READER ? "READER" :
  44977. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  44978. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  44979. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  44980. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  44981. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  44982. , (int)p->errCode
  44983. , p->eLock==NO_LOCK ? "NO_LOCK" :
  44984. p->eLock==RESERVED_LOCK ? "RESERVED" :
  44985. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  44986. p->eLock==SHARED_LOCK ? "SHARED" :
  44987. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  44988. , p->exclusiveMode ? "exclusive" : "normal"
  44989. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  44990. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  44991. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  44992. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  44993. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  44994. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  44995. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  44996. , p->journalOff, p->journalHdr
  44997. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  44998. );
  44999. return zRet;
  45000. }
  45001. #endif
  45002. /* Forward references to the various page getters */
  45003. static int getPageNormal(Pager*,Pgno,DbPage**,int);
  45004. static int getPageError(Pager*,Pgno,DbPage**,int);
  45005. #if SQLITE_MAX_MMAP_SIZE>0
  45006. static int getPageMMap(Pager*,Pgno,DbPage**,int);
  45007. #endif
  45008. /*
  45009. ** Set the Pager.xGet method for the appropriate routine used to fetch
  45010. ** content from the pager.
  45011. */
  45012. static void setGetterMethod(Pager *pPager){
  45013. if( pPager->errCode ){
  45014. pPager->xGet = getPageError;
  45015. #if SQLITE_MAX_MMAP_SIZE>0
  45016. }else if( USEFETCH(pPager)
  45017. #ifdef SQLITE_HAS_CODEC
  45018. && pPager->xCodec==0
  45019. #endif
  45020. ){
  45021. pPager->xGet = getPageMMap;
  45022. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  45023. }else{
  45024. pPager->xGet = getPageNormal;
  45025. }
  45026. }
  45027. /*
  45028. ** Return true if it is necessary to write page *pPg into the sub-journal.
  45029. ** A page needs to be written into the sub-journal if there exists one
  45030. ** or more open savepoints for which:
  45031. **
  45032. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  45033. ** * The bit corresponding to the page-number is not set in
  45034. ** PagerSavepoint.pInSavepoint.
  45035. */
  45036. static int subjRequiresPage(PgHdr *pPg){
  45037. Pager *pPager = pPg->pPager;
  45038. PagerSavepoint *p;
  45039. Pgno pgno = pPg->pgno;
  45040. int i;
  45041. for(i=0; i<pPager->nSavepoint; i++){
  45042. p = &pPager->aSavepoint[i];
  45043. if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
  45044. return 1;
  45045. }
  45046. }
  45047. return 0;
  45048. }
  45049. #ifdef SQLITE_DEBUG
  45050. /*
  45051. ** Return true if the page is already in the journal file.
  45052. */
  45053. static int pageInJournal(Pager *pPager, PgHdr *pPg){
  45054. return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
  45055. }
  45056. #endif
  45057. /*
  45058. ** Read a 32-bit integer from the given file descriptor. Store the integer
  45059. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  45060. ** error code is something goes wrong.
  45061. **
  45062. ** All values are stored on disk as big-endian.
  45063. */
  45064. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  45065. unsigned char ac[4];
  45066. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  45067. if( rc==SQLITE_OK ){
  45068. *pRes = sqlite3Get4byte(ac);
  45069. }
  45070. return rc;
  45071. }
  45072. /*
  45073. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  45074. */
  45075. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  45076. /*
  45077. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  45078. ** on success or an error code is something goes wrong.
  45079. */
  45080. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  45081. char ac[4];
  45082. put32bits(ac, val);
  45083. return sqlite3OsWrite(fd, ac, 4, offset);
  45084. }
  45085. /*
  45086. ** Unlock the database file to level eLock, which must be either NO_LOCK
  45087. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  45088. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  45089. **
  45090. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  45091. ** called, do not modify it. See the comment above the #define of
  45092. ** UNKNOWN_LOCK for an explanation of this.
  45093. */
  45094. static int pagerUnlockDb(Pager *pPager, int eLock){
  45095. int rc = SQLITE_OK;
  45096. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  45097. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  45098. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  45099. if( isOpen(pPager->fd) ){
  45100. assert( pPager->eLock>=eLock );
  45101. rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
  45102. if( pPager->eLock!=UNKNOWN_LOCK ){
  45103. pPager->eLock = (u8)eLock;
  45104. }
  45105. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  45106. }
  45107. return rc;
  45108. }
  45109. /*
  45110. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  45111. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  45112. ** Pager.eLock variable to the new locking state.
  45113. **
  45114. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  45115. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  45116. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  45117. ** of this.
  45118. */
  45119. static int pagerLockDb(Pager *pPager, int eLock){
  45120. int rc = SQLITE_OK;
  45121. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  45122. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  45123. rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
  45124. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  45125. pPager->eLock = (u8)eLock;
  45126. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  45127. }
  45128. }
  45129. return rc;
  45130. }
  45131. /*
  45132. ** This function determines whether or not the atomic-write optimization
  45133. ** can be used with this pager. The optimization can be used if:
  45134. **
  45135. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  45136. ** a database page may be written atomically, and
  45137. ** (b) the value returned by OsSectorSize() is less than or equal
  45138. ** to the page size.
  45139. **
  45140. ** The optimization is also always enabled for temporary files. It is
  45141. ** an error to call this function if pPager is opened on an in-memory
  45142. ** database.
  45143. **
  45144. ** If the optimization cannot be used, 0 is returned. If it can be used,
  45145. ** then the value returned is the size of the journal file when it
  45146. ** contains rollback data for exactly one page.
  45147. */
  45148. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  45149. static int jrnlBufferSize(Pager *pPager){
  45150. assert( !MEMDB );
  45151. if( !pPager->tempFile ){
  45152. int dc; /* Device characteristics */
  45153. int nSector; /* Sector size */
  45154. int szPage; /* Page size */
  45155. assert( isOpen(pPager->fd) );
  45156. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  45157. nSector = pPager->sectorSize;
  45158. szPage = pPager->pageSize;
  45159. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  45160. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  45161. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  45162. return 0;
  45163. }
  45164. }
  45165. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  45166. }
  45167. #else
  45168. # define jrnlBufferSize(x) 0
  45169. #endif
  45170. /*
  45171. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  45172. ** on the cache using a hash function. This is used for testing
  45173. ** and debugging only.
  45174. */
  45175. #ifdef SQLITE_CHECK_PAGES
  45176. /*
  45177. ** Return a 32-bit hash of the page data for pPage.
  45178. */
  45179. static u32 pager_datahash(int nByte, unsigned char *pData){
  45180. u32 hash = 0;
  45181. int i;
  45182. for(i=0; i<nByte; i++){
  45183. hash = (hash*1039) + pData[i];
  45184. }
  45185. return hash;
  45186. }
  45187. static u32 pager_pagehash(PgHdr *pPage){
  45188. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  45189. }
  45190. static void pager_set_pagehash(PgHdr *pPage){
  45191. pPage->pageHash = pager_pagehash(pPage);
  45192. }
  45193. /*
  45194. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  45195. ** is defined, and NDEBUG is not defined, an assert() statement checks
  45196. ** that the page is either dirty or still matches the calculated page-hash.
  45197. */
  45198. #define CHECK_PAGE(x) checkPage(x)
  45199. static void checkPage(PgHdr *pPg){
  45200. Pager *pPager = pPg->pPager;
  45201. assert( pPager->eState!=PAGER_ERROR );
  45202. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  45203. }
  45204. #else
  45205. #define pager_datahash(X,Y) 0
  45206. #define pager_pagehash(X) 0
  45207. #define pager_set_pagehash(X)
  45208. #define CHECK_PAGE(x)
  45209. #endif /* SQLITE_CHECK_PAGES */
  45210. /*
  45211. ** When this is called the journal file for pager pPager must be open.
  45212. ** This function attempts to read a master journal file name from the
  45213. ** end of the file and, if successful, copies it into memory supplied
  45214. ** by the caller. See comments above writeMasterJournal() for the format
  45215. ** used to store a master journal file name at the end of a journal file.
  45216. **
  45217. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  45218. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  45219. ** enough space to write the master journal name). If the master journal
  45220. ** name in the journal is longer than nMaster bytes (including a
  45221. ** nul-terminator), then this is handled as if no master journal name
  45222. ** were present in the journal.
  45223. **
  45224. ** If a master journal file name is present at the end of the journal
  45225. ** file, then it is copied into the buffer pointed to by zMaster. A
  45226. ** nul-terminator byte is appended to the buffer following the master
  45227. ** journal file name.
  45228. **
  45229. ** If it is determined that no master journal file name is present
  45230. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  45231. **
  45232. ** If an error occurs while reading from the journal file, an SQLite
  45233. ** error code is returned.
  45234. */
  45235. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  45236. int rc; /* Return code */
  45237. u32 len; /* Length in bytes of master journal name */
  45238. i64 szJ; /* Total size in bytes of journal file pJrnl */
  45239. u32 cksum; /* MJ checksum value read from journal */
  45240. u32 u; /* Unsigned loop counter */
  45241. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  45242. zMaster[0] = '\0';
  45243. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  45244. || szJ<16
  45245. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  45246. || len>=nMaster
  45247. || len==0
  45248. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  45249. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  45250. || memcmp(aMagic, aJournalMagic, 8)
  45251. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  45252. ){
  45253. return rc;
  45254. }
  45255. /* See if the checksum matches the master journal name */
  45256. for(u=0; u<len; u++){
  45257. cksum -= zMaster[u];
  45258. }
  45259. if( cksum ){
  45260. /* If the checksum doesn't add up, then one or more of the disk sectors
  45261. ** containing the master journal filename is corrupted. This means
  45262. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  45263. ** master-journal filename.
  45264. */
  45265. len = 0;
  45266. }
  45267. zMaster[len] = '\0';
  45268. return SQLITE_OK;
  45269. }
  45270. /*
  45271. ** Return the offset of the sector boundary at or immediately
  45272. ** following the value in pPager->journalOff, assuming a sector
  45273. ** size of pPager->sectorSize bytes.
  45274. **
  45275. ** i.e for a sector size of 512:
  45276. **
  45277. ** Pager.journalOff Return value
  45278. ** ---------------------------------------
  45279. ** 0 0
  45280. ** 512 512
  45281. ** 100 512
  45282. ** 2000 2048
  45283. **
  45284. */
  45285. static i64 journalHdrOffset(Pager *pPager){
  45286. i64 offset = 0;
  45287. i64 c = pPager->journalOff;
  45288. if( c ){
  45289. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  45290. }
  45291. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  45292. assert( offset>=c );
  45293. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  45294. return offset;
  45295. }
  45296. /*
  45297. ** The journal file must be open when this function is called.
  45298. **
  45299. ** This function is a no-op if the journal file has not been written to
  45300. ** within the current transaction (i.e. if Pager.journalOff==0).
  45301. **
  45302. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  45303. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  45304. ** zero the 28-byte header at the start of the journal file. In either case,
  45305. ** if the pager is not in no-sync mode, sync the journal file immediately
  45306. ** after writing or truncating it.
  45307. **
  45308. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  45309. ** following the truncation or zeroing described above the size of the
  45310. ** journal file in bytes is larger than this value, then truncate the
  45311. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  45312. ** not need to be synced following this operation.
  45313. **
  45314. ** If an IO error occurs, abandon processing and return the IO error code.
  45315. ** Otherwise, return SQLITE_OK.
  45316. */
  45317. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  45318. int rc = SQLITE_OK; /* Return code */
  45319. assert( isOpen(pPager->jfd) );
  45320. assert( !sqlite3JournalIsInMemory(pPager->jfd) );
  45321. if( pPager->journalOff ){
  45322. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  45323. IOTRACE(("JZEROHDR %p\n", pPager))
  45324. if( doTruncate || iLimit==0 ){
  45325. rc = sqlite3OsTruncate(pPager->jfd, 0);
  45326. }else{
  45327. static const char zeroHdr[28] = {0};
  45328. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  45329. }
  45330. if( rc==SQLITE_OK && !pPager->noSync ){
  45331. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  45332. }
  45333. /* At this point the transaction is committed but the write lock
  45334. ** is still held on the file. If there is a size limit configured for
  45335. ** the persistent journal and the journal file currently consumes more
  45336. ** space than that limit allows for, truncate it now. There is no need
  45337. ** to sync the file following this operation.
  45338. */
  45339. if( rc==SQLITE_OK && iLimit>0 ){
  45340. i64 sz;
  45341. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  45342. if( rc==SQLITE_OK && sz>iLimit ){
  45343. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  45344. }
  45345. }
  45346. }
  45347. return rc;
  45348. }
  45349. /*
  45350. ** The journal file must be open when this routine is called. A journal
  45351. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  45352. ** current location.
  45353. **
  45354. ** The format for the journal header is as follows:
  45355. ** - 8 bytes: Magic identifying journal format.
  45356. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  45357. ** - 4 bytes: Random number used for page hash.
  45358. ** - 4 bytes: Initial database page count.
  45359. ** - 4 bytes: Sector size used by the process that wrote this journal.
  45360. ** - 4 bytes: Database page size.
  45361. **
  45362. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  45363. */
  45364. static int writeJournalHdr(Pager *pPager){
  45365. int rc = SQLITE_OK; /* Return code */
  45366. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  45367. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  45368. u32 nWrite; /* Bytes of header sector written */
  45369. int ii; /* Loop counter */
  45370. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  45371. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  45372. nHeader = JOURNAL_HDR_SZ(pPager);
  45373. }
  45374. /* If there are active savepoints and any of them were created
  45375. ** since the most recent journal header was written, update the
  45376. ** PagerSavepoint.iHdrOffset fields now.
  45377. */
  45378. for(ii=0; ii<pPager->nSavepoint; ii++){
  45379. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  45380. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  45381. }
  45382. }
  45383. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  45384. /*
  45385. ** Write the nRec Field - the number of page records that follow this
  45386. ** journal header. Normally, zero is written to this value at this time.
  45387. ** After the records are added to the journal (and the journal synced,
  45388. ** if in full-sync mode), the zero is overwritten with the true number
  45389. ** of records (see syncJournal()).
  45390. **
  45391. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  45392. ** reading the journal this value tells SQLite to assume that the
  45393. ** rest of the journal file contains valid page records. This assumption
  45394. ** is dangerous, as if a failure occurred whilst writing to the journal
  45395. ** file it may contain some garbage data. There are two scenarios
  45396. ** where this risk can be ignored:
  45397. **
  45398. ** * When the pager is in no-sync mode. Corruption can follow a
  45399. ** power failure in this case anyway.
  45400. **
  45401. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  45402. ** that garbage data is never appended to the journal file.
  45403. */
  45404. assert( isOpen(pPager->fd) || pPager->noSync );
  45405. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  45406. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  45407. ){
  45408. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  45409. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  45410. }else{
  45411. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  45412. }
  45413. /* The random check-hash initializer */
  45414. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  45415. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  45416. /* The initial database size */
  45417. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  45418. /* The assumed sector size for this process */
  45419. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  45420. /* The page size */
  45421. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  45422. /* Initializing the tail of the buffer is not necessary. Everything
  45423. ** works find if the following memset() is omitted. But initializing
  45424. ** the memory prevents valgrind from complaining, so we are willing to
  45425. ** take the performance hit.
  45426. */
  45427. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  45428. nHeader-(sizeof(aJournalMagic)+20));
  45429. /* In theory, it is only necessary to write the 28 bytes that the
  45430. ** journal header consumes to the journal file here. Then increment the
  45431. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  45432. ** record is written to the following sector (leaving a gap in the file
  45433. ** that will be implicitly filled in by the OS).
  45434. **
  45435. ** However it has been discovered that on some systems this pattern can
  45436. ** be significantly slower than contiguously writing data to the file,
  45437. ** even if that means explicitly writing data to the block of
  45438. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  45439. ** is done.
  45440. **
  45441. ** The loop is required here in case the sector-size is larger than the
  45442. ** database page size. Since the zHeader buffer is only Pager.pageSize
  45443. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  45444. ** to populate the entire journal header sector.
  45445. */
  45446. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  45447. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  45448. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  45449. assert( pPager->journalHdr <= pPager->journalOff );
  45450. pPager->journalOff += nHeader;
  45451. }
  45452. return rc;
  45453. }
  45454. /*
  45455. ** The journal file must be open when this is called. A journal header file
  45456. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  45457. ** file. The current location in the journal file is given by
  45458. ** pPager->journalOff. See comments above function writeJournalHdr() for
  45459. ** a description of the journal header format.
  45460. **
  45461. ** If the header is read successfully, *pNRec is set to the number of
  45462. ** page records following this header and *pDbSize is set to the size of the
  45463. ** database before the transaction began, in pages. Also, pPager->cksumInit
  45464. ** is set to the value read from the journal header. SQLITE_OK is returned
  45465. ** in this case.
  45466. **
  45467. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  45468. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  45469. ** cannot be read from the journal file an error code is returned.
  45470. */
  45471. static int readJournalHdr(
  45472. Pager *pPager, /* Pager object */
  45473. int isHot,
  45474. i64 journalSize, /* Size of the open journal file in bytes */
  45475. u32 *pNRec, /* OUT: Value read from the nRec field */
  45476. u32 *pDbSize /* OUT: Value of original database size field */
  45477. ){
  45478. int rc; /* Return code */
  45479. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  45480. i64 iHdrOff; /* Offset of journal header being read */
  45481. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  45482. /* Advance Pager.journalOff to the start of the next sector. If the
  45483. ** journal file is too small for there to be a header stored at this
  45484. ** point, return SQLITE_DONE.
  45485. */
  45486. pPager->journalOff = journalHdrOffset(pPager);
  45487. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  45488. return SQLITE_DONE;
  45489. }
  45490. iHdrOff = pPager->journalOff;
  45491. /* Read in the first 8 bytes of the journal header. If they do not match
  45492. ** the magic string found at the start of each journal header, return
  45493. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  45494. ** proceed.
  45495. */
  45496. if( isHot || iHdrOff!=pPager->journalHdr ){
  45497. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  45498. if( rc ){
  45499. return rc;
  45500. }
  45501. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  45502. return SQLITE_DONE;
  45503. }
  45504. }
  45505. /* Read the first three 32-bit fields of the journal header: The nRec
  45506. ** field, the checksum-initializer and the database size at the start
  45507. ** of the transaction. Return an error code if anything goes wrong.
  45508. */
  45509. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  45510. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  45511. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  45512. ){
  45513. return rc;
  45514. }
  45515. if( pPager->journalOff==0 ){
  45516. u32 iPageSize; /* Page-size field of journal header */
  45517. u32 iSectorSize; /* Sector-size field of journal header */
  45518. /* Read the page-size and sector-size journal header fields. */
  45519. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  45520. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  45521. ){
  45522. return rc;
  45523. }
  45524. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  45525. ** journal header to zero. In this case, assume that the Pager.pageSize
  45526. ** variable is already set to the correct page size.
  45527. */
  45528. if( iPageSize==0 ){
  45529. iPageSize = pPager->pageSize;
  45530. }
  45531. /* Check that the values read from the page-size and sector-size fields
  45532. ** are within range. To be 'in range', both values need to be a power
  45533. ** of two greater than or equal to 512 or 32, and not greater than their
  45534. ** respective compile time maximum limits.
  45535. */
  45536. if( iPageSize<512 || iSectorSize<32
  45537. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  45538. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  45539. ){
  45540. /* If the either the page-size or sector-size in the journal-header is
  45541. ** invalid, then the process that wrote the journal-header must have
  45542. ** crashed before the header was synced. In this case stop reading
  45543. ** the journal file here.
  45544. */
  45545. return SQLITE_DONE;
  45546. }
  45547. /* Update the page-size to match the value read from the journal.
  45548. ** Use a testcase() macro to make sure that malloc failure within
  45549. ** PagerSetPagesize() is tested.
  45550. */
  45551. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  45552. testcase( rc!=SQLITE_OK );
  45553. /* Update the assumed sector-size to match the value used by
  45554. ** the process that created this journal. If this journal was
  45555. ** created by a process other than this one, then this routine
  45556. ** is being called from within pager_playback(). The local value
  45557. ** of Pager.sectorSize is restored at the end of that routine.
  45558. */
  45559. pPager->sectorSize = iSectorSize;
  45560. }
  45561. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  45562. return rc;
  45563. }
  45564. /*
  45565. ** Write the supplied master journal name into the journal file for pager
  45566. ** pPager at the current location. The master journal name must be the last
  45567. ** thing written to a journal file. If the pager is in full-sync mode, the
  45568. ** journal file descriptor is advanced to the next sector boundary before
  45569. ** anything is written. The format is:
  45570. **
  45571. ** + 4 bytes: PAGER_MJ_PGNO.
  45572. ** + N bytes: Master journal filename in utf-8.
  45573. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  45574. ** + 4 bytes: Master journal name checksum.
  45575. ** + 8 bytes: aJournalMagic[].
  45576. **
  45577. ** The master journal page checksum is the sum of the bytes in the master
  45578. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  45579. **
  45580. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  45581. ** this call is a no-op.
  45582. */
  45583. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  45584. int rc; /* Return code */
  45585. int nMaster; /* Length of string zMaster */
  45586. i64 iHdrOff; /* Offset of header in journal file */
  45587. i64 jrnlSize; /* Size of journal file on disk */
  45588. u32 cksum = 0; /* Checksum of string zMaster */
  45589. assert( pPager->setMaster==0 );
  45590. assert( !pagerUseWal(pPager) );
  45591. if( !zMaster
  45592. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  45593. || !isOpen(pPager->jfd)
  45594. ){
  45595. return SQLITE_OK;
  45596. }
  45597. pPager->setMaster = 1;
  45598. assert( pPager->journalHdr <= pPager->journalOff );
  45599. /* Calculate the length in bytes and the checksum of zMaster */
  45600. for(nMaster=0; zMaster[nMaster]; nMaster++){
  45601. cksum += zMaster[nMaster];
  45602. }
  45603. /* If in full-sync mode, advance to the next disk sector before writing
  45604. ** the master journal name. This is in case the previous page written to
  45605. ** the journal has already been synced.
  45606. */
  45607. if( pPager->fullSync ){
  45608. pPager->journalOff = journalHdrOffset(pPager);
  45609. }
  45610. iHdrOff = pPager->journalOff;
  45611. /* Write the master journal data to the end of the journal file. If
  45612. ** an error occurs, return the error code to the caller.
  45613. */
  45614. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  45615. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  45616. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  45617. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  45618. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
  45619. iHdrOff+4+nMaster+8)))
  45620. ){
  45621. return rc;
  45622. }
  45623. pPager->journalOff += (nMaster+20);
  45624. /* If the pager is in peristent-journal mode, then the physical
  45625. ** journal-file may extend past the end of the master-journal name
  45626. ** and 8 bytes of magic data just written to the file. This is
  45627. ** dangerous because the code to rollback a hot-journal file
  45628. ** will not be able to find the master-journal name to determine
  45629. ** whether or not the journal is hot.
  45630. **
  45631. ** Easiest thing to do in this scenario is to truncate the journal
  45632. ** file to the required size.
  45633. */
  45634. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  45635. && jrnlSize>pPager->journalOff
  45636. ){
  45637. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  45638. }
  45639. return rc;
  45640. }
  45641. /*
  45642. ** Discard the entire contents of the in-memory page-cache.
  45643. */
  45644. static void pager_reset(Pager *pPager){
  45645. pPager->iDataVersion++;
  45646. sqlite3BackupRestart(pPager->pBackup);
  45647. sqlite3PcacheClear(pPager->pPCache);
  45648. }
  45649. /*
  45650. ** Return the pPager->iDataVersion value
  45651. */
  45652. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
  45653. assert( pPager->eState>PAGER_OPEN );
  45654. return pPager->iDataVersion;
  45655. }
  45656. /*
  45657. ** Free all structures in the Pager.aSavepoint[] array and set both
  45658. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  45659. ** if it is open and the pager is not in exclusive mode.
  45660. */
  45661. static void releaseAllSavepoints(Pager *pPager){
  45662. int ii; /* Iterator for looping through Pager.aSavepoint */
  45663. for(ii=0; ii<pPager->nSavepoint; ii++){
  45664. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  45665. }
  45666. if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
  45667. sqlite3OsClose(pPager->sjfd);
  45668. }
  45669. sqlite3_free(pPager->aSavepoint);
  45670. pPager->aSavepoint = 0;
  45671. pPager->nSavepoint = 0;
  45672. pPager->nSubRec = 0;
  45673. }
  45674. /*
  45675. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  45676. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  45677. ** or SQLITE_NOMEM if a malloc failure occurs.
  45678. */
  45679. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  45680. int ii; /* Loop counter */
  45681. int rc = SQLITE_OK; /* Result code */
  45682. for(ii=0; ii<pPager->nSavepoint; ii++){
  45683. PagerSavepoint *p = &pPager->aSavepoint[ii];
  45684. if( pgno<=p->nOrig ){
  45685. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  45686. testcase( rc==SQLITE_NOMEM );
  45687. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  45688. }
  45689. }
  45690. return rc;
  45691. }
  45692. /*
  45693. ** This function is a no-op if the pager is in exclusive mode and not
  45694. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  45695. ** state.
  45696. **
  45697. ** If the pager is not in exclusive-access mode, the database file is
  45698. ** completely unlocked. If the file is unlocked and the file-system does
  45699. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  45700. ** closed (if it is open).
  45701. **
  45702. ** If the pager is in ERROR state when this function is called, the
  45703. ** contents of the pager cache are discarded before switching back to
  45704. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  45705. ** or not, any journal file left in the file-system will be treated
  45706. ** as a hot-journal and rolled back the next time a read-transaction
  45707. ** is opened (by this or by any other connection).
  45708. */
  45709. static void pager_unlock(Pager *pPager){
  45710. assert( pPager->eState==PAGER_READER
  45711. || pPager->eState==PAGER_OPEN
  45712. || pPager->eState==PAGER_ERROR
  45713. );
  45714. sqlite3BitvecDestroy(pPager->pInJournal);
  45715. pPager->pInJournal = 0;
  45716. releaseAllSavepoints(pPager);
  45717. if( pagerUseWal(pPager) ){
  45718. assert( !isOpen(pPager->jfd) );
  45719. sqlite3WalEndReadTransaction(pPager->pWal);
  45720. pPager->eState = PAGER_OPEN;
  45721. }else if( !pPager->exclusiveMode ){
  45722. int rc; /* Error code returned by pagerUnlockDb() */
  45723. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  45724. /* If the operating system support deletion of open files, then
  45725. ** close the journal file when dropping the database lock. Otherwise
  45726. ** another connection with journal_mode=delete might delete the file
  45727. ** out from under us.
  45728. */
  45729. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  45730. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  45731. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  45732. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  45733. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  45734. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  45735. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  45736. || 1!=(pPager->journalMode & 5)
  45737. ){
  45738. sqlite3OsClose(pPager->jfd);
  45739. }
  45740. /* If the pager is in the ERROR state and the call to unlock the database
  45741. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  45742. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  45743. ** is necessary.
  45744. */
  45745. rc = pagerUnlockDb(pPager, NO_LOCK);
  45746. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  45747. pPager->eLock = UNKNOWN_LOCK;
  45748. }
  45749. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  45750. ** without clearing the error code. This is intentional - the error
  45751. ** code is cleared and the cache reset in the block below.
  45752. */
  45753. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  45754. pPager->changeCountDone = 0;
  45755. pPager->eState = PAGER_OPEN;
  45756. }
  45757. /* If Pager.errCode is set, the contents of the pager cache cannot be
  45758. ** trusted. Now that there are no outstanding references to the pager,
  45759. ** it can safely move back to PAGER_OPEN state. This happens in both
  45760. ** normal and exclusive-locking mode.
  45761. */
  45762. assert( pPager->errCode==SQLITE_OK || !MEMDB );
  45763. if( pPager->errCode ){
  45764. if( pPager->tempFile==0 ){
  45765. pager_reset(pPager);
  45766. pPager->changeCountDone = 0;
  45767. pPager->eState = PAGER_OPEN;
  45768. }else{
  45769. pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
  45770. }
  45771. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  45772. pPager->errCode = SQLITE_OK;
  45773. setGetterMethod(pPager);
  45774. }
  45775. pPager->journalOff = 0;
  45776. pPager->journalHdr = 0;
  45777. pPager->setMaster = 0;
  45778. }
  45779. /*
  45780. ** This function is called whenever an IOERR or FULL error that requires
  45781. ** the pager to transition into the ERROR state may ahve occurred.
  45782. ** The first argument is a pointer to the pager structure, the second
  45783. ** the error-code about to be returned by a pager API function. The
  45784. ** value returned is a copy of the second argument to this function.
  45785. **
  45786. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  45787. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  45788. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  45789. ** all major API calls on the Pager will immediately return Pager.errCode.
  45790. **
  45791. ** The ERROR state indicates that the contents of the pager-cache
  45792. ** cannot be trusted. This state can be cleared by completely discarding
  45793. ** the contents of the pager-cache. If a transaction was active when
  45794. ** the persistent error occurred, then the rollback journal may need
  45795. ** to be replayed to restore the contents of the database file (as if
  45796. ** it were a hot-journal).
  45797. */
  45798. static int pager_error(Pager *pPager, int rc){
  45799. int rc2 = rc & 0xff;
  45800. assert( rc==SQLITE_OK || !MEMDB );
  45801. assert(
  45802. pPager->errCode==SQLITE_FULL ||
  45803. pPager->errCode==SQLITE_OK ||
  45804. (pPager->errCode & 0xff)==SQLITE_IOERR
  45805. );
  45806. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  45807. pPager->errCode = rc;
  45808. pPager->eState = PAGER_ERROR;
  45809. setGetterMethod(pPager);
  45810. }
  45811. return rc;
  45812. }
  45813. static int pager_truncate(Pager *pPager, Pgno nPage);
  45814. /*
  45815. ** The write transaction open on pPager is being committed (bCommit==1)
  45816. ** or rolled back (bCommit==0).
  45817. **
  45818. ** Return TRUE if and only if all dirty pages should be flushed to disk.
  45819. **
  45820. ** Rules:
  45821. **
  45822. ** * For non-TEMP databases, always sync to disk. This is necessary
  45823. ** for transactions to be durable.
  45824. **
  45825. ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
  45826. ** file has been created already (via a spill on pagerStress()) and
  45827. ** when the number of dirty pages in memory exceeds 25% of the total
  45828. ** cache size.
  45829. */
  45830. static int pagerFlushOnCommit(Pager *pPager, int bCommit){
  45831. if( pPager->tempFile==0 ) return 1;
  45832. if( !bCommit ) return 0;
  45833. if( !isOpen(pPager->fd) ) return 0;
  45834. return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
  45835. }
  45836. /*
  45837. ** This routine ends a transaction. A transaction is usually ended by
  45838. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  45839. ** after rollback of a hot-journal, or if an error occurs while opening
  45840. ** the journal file or writing the very first journal-header of a
  45841. ** database transaction.
  45842. **
  45843. ** This routine is never called in PAGER_ERROR state. If it is called
  45844. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  45845. ** exclusive than a RESERVED lock, it is a no-op.
  45846. **
  45847. ** Otherwise, any active savepoints are released.
  45848. **
  45849. ** If the journal file is open, then it is "finalized". Once a journal
  45850. ** file has been finalized it is not possible to use it to roll back a
  45851. ** transaction. Nor will it be considered to be a hot-journal by this
  45852. ** or any other database connection. Exactly how a journal is finalized
  45853. ** depends on whether or not the pager is running in exclusive mode and
  45854. ** the current journal-mode (Pager.journalMode value), as follows:
  45855. **
  45856. ** journalMode==MEMORY
  45857. ** Journal file descriptor is simply closed. This destroys an
  45858. ** in-memory journal.
  45859. **
  45860. ** journalMode==TRUNCATE
  45861. ** Journal file is truncated to zero bytes in size.
  45862. **
  45863. ** journalMode==PERSIST
  45864. ** The first 28 bytes of the journal file are zeroed. This invalidates
  45865. ** the first journal header in the file, and hence the entire journal
  45866. ** file. An invalid journal file cannot be rolled back.
  45867. **
  45868. ** journalMode==DELETE
  45869. ** The journal file is closed and deleted using sqlite3OsDelete().
  45870. **
  45871. ** If the pager is running in exclusive mode, this method of finalizing
  45872. ** the journal file is never used. Instead, if the journalMode is
  45873. ** DELETE and the pager is in exclusive mode, the method described under
  45874. ** journalMode==PERSIST is used instead.
  45875. **
  45876. ** After the journal is finalized, the pager moves to PAGER_READER state.
  45877. ** If running in non-exclusive rollback mode, the lock on the file is
  45878. ** downgraded to a SHARED_LOCK.
  45879. **
  45880. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  45881. ** any of the IO operations to finalize the journal file or unlock the
  45882. ** database then the IO error code is returned to the user. If the
  45883. ** operation to finalize the journal file fails, then the code still
  45884. ** tries to unlock the database file if not in exclusive mode. If the
  45885. ** unlock operation fails as well, then the first error code related
  45886. ** to the first error encountered (the journal finalization one) is
  45887. ** returned.
  45888. */
  45889. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  45890. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  45891. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  45892. /* Do nothing if the pager does not have an open write transaction
  45893. ** or at least a RESERVED lock. This function may be called when there
  45894. ** is no write-transaction active but a RESERVED or greater lock is
  45895. ** held under two circumstances:
  45896. **
  45897. ** 1. After a successful hot-journal rollback, it is called with
  45898. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  45899. **
  45900. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  45901. ** lock switches back to locking_mode=normal and then executes a
  45902. ** read-transaction, this function is called with eState==PAGER_READER
  45903. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  45904. */
  45905. assert( assert_pager_state(pPager) );
  45906. assert( pPager->eState!=PAGER_ERROR );
  45907. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  45908. return SQLITE_OK;
  45909. }
  45910. releaseAllSavepoints(pPager);
  45911. assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  45912. if( isOpen(pPager->jfd) ){
  45913. assert( !pagerUseWal(pPager) );
  45914. /* Finalize the journal file. */
  45915. if( sqlite3JournalIsInMemory(pPager->jfd) ){
  45916. /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
  45917. sqlite3OsClose(pPager->jfd);
  45918. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  45919. if( pPager->journalOff==0 ){
  45920. rc = SQLITE_OK;
  45921. }else{
  45922. rc = sqlite3OsTruncate(pPager->jfd, 0);
  45923. if( rc==SQLITE_OK && pPager->fullSync ){
  45924. /* Make sure the new file size is written into the inode right away.
  45925. ** Otherwise the journal might resurrect following a power loss and
  45926. ** cause the last transaction to roll back. See
  45927. ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
  45928. */
  45929. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  45930. }
  45931. }
  45932. pPager->journalOff = 0;
  45933. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  45934. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  45935. ){
  45936. rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
  45937. pPager->journalOff = 0;
  45938. }else{
  45939. /* This branch may be executed with Pager.journalMode==MEMORY if
  45940. ** a hot-journal was just rolled back. In this case the journal
  45941. ** file should be closed and deleted. If this connection writes to
  45942. ** the database file, it will do so using an in-memory journal.
  45943. */
  45944. int bDelete = !pPager->tempFile;
  45945. assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
  45946. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  45947. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  45948. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  45949. );
  45950. sqlite3OsClose(pPager->jfd);
  45951. if( bDelete ){
  45952. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
  45953. }
  45954. }
  45955. }
  45956. #ifdef SQLITE_CHECK_PAGES
  45957. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  45958. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  45959. PgHdr *p = sqlite3PagerLookup(pPager, 1);
  45960. if( p ){
  45961. p->pageHash = 0;
  45962. sqlite3PagerUnrefNotNull(p);
  45963. }
  45964. }
  45965. #endif
  45966. sqlite3BitvecDestroy(pPager->pInJournal);
  45967. pPager->pInJournal = 0;
  45968. pPager->nRec = 0;
  45969. if( rc==SQLITE_OK ){
  45970. if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){
  45971. sqlite3PcacheCleanAll(pPager->pPCache);
  45972. }else{
  45973. sqlite3PcacheClearWritable(pPager->pPCache);
  45974. }
  45975. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  45976. }
  45977. if( pagerUseWal(pPager) ){
  45978. /* Drop the WAL write-lock, if any. Also, if the connection was in
  45979. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  45980. ** lock held on the database file.
  45981. */
  45982. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  45983. assert( rc2==SQLITE_OK );
  45984. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  45985. /* This branch is taken when committing a transaction in rollback-journal
  45986. ** mode if the database file on disk is larger than the database image.
  45987. ** At this point the journal has been finalized and the transaction
  45988. ** successfully committed, but the EXCLUSIVE lock is still held on the
  45989. ** file. So it is safe to truncate the database file to its minimum
  45990. ** required size. */
  45991. assert( pPager->eLock==EXCLUSIVE_LOCK );
  45992. rc = pager_truncate(pPager, pPager->dbSize);
  45993. }
  45994. if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
  45995. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
  45996. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  45997. }
  45998. if( !pPager->exclusiveMode
  45999. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  46000. ){
  46001. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  46002. pPager->changeCountDone = 0;
  46003. }
  46004. pPager->eState = PAGER_READER;
  46005. pPager->setMaster = 0;
  46006. return (rc==SQLITE_OK?rc2:rc);
  46007. }
  46008. /*
  46009. ** Execute a rollback if a transaction is active and unlock the
  46010. ** database file.
  46011. **
  46012. ** If the pager has already entered the ERROR state, do not attempt
  46013. ** the rollback at this time. Instead, pager_unlock() is called. The
  46014. ** call to pager_unlock() will discard all in-memory pages, unlock
  46015. ** the database file and move the pager back to OPEN state. If this
  46016. ** means that there is a hot-journal left in the file-system, the next
  46017. ** connection to obtain a shared lock on the pager (which may be this one)
  46018. ** will roll it back.
  46019. **
  46020. ** If the pager has not already entered the ERROR state, but an IO or
  46021. ** malloc error occurs during a rollback, then this will itself cause
  46022. ** the pager to enter the ERROR state. Which will be cleared by the
  46023. ** call to pager_unlock(), as described above.
  46024. */
  46025. static void pagerUnlockAndRollback(Pager *pPager){
  46026. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  46027. assert( assert_pager_state(pPager) );
  46028. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  46029. sqlite3BeginBenignMalloc();
  46030. sqlite3PagerRollback(pPager);
  46031. sqlite3EndBenignMalloc();
  46032. }else if( !pPager->exclusiveMode ){
  46033. assert( pPager->eState==PAGER_READER );
  46034. pager_end_transaction(pPager, 0, 0);
  46035. }
  46036. }
  46037. pager_unlock(pPager);
  46038. }
  46039. /*
  46040. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  46041. ** of data. Compute and return a checksum based ont the contents of the
  46042. ** page of data and the current value of pPager->cksumInit.
  46043. **
  46044. ** This is not a real checksum. It is really just the sum of the
  46045. ** random initial value (pPager->cksumInit) and every 200th byte
  46046. ** of the page data, starting with byte offset (pPager->pageSize%200).
  46047. ** Each byte is interpreted as an 8-bit unsigned integer.
  46048. **
  46049. ** Changing the formula used to compute this checksum results in an
  46050. ** incompatible journal file format.
  46051. **
  46052. ** If journal corruption occurs due to a power failure, the most likely
  46053. ** scenario is that one end or the other of the record will be changed.
  46054. ** It is much less likely that the two ends of the journal record will be
  46055. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  46056. ** though fast and simple, catches the mostly likely kind of corruption.
  46057. */
  46058. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  46059. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  46060. int i = pPager->pageSize-200; /* Loop counter */
  46061. while( i>0 ){
  46062. cksum += aData[i];
  46063. i -= 200;
  46064. }
  46065. return cksum;
  46066. }
  46067. /*
  46068. ** Report the current page size and number of reserved bytes back
  46069. ** to the codec.
  46070. */
  46071. #ifdef SQLITE_HAS_CODEC
  46072. static void pagerReportSize(Pager *pPager){
  46073. if( pPager->xCodecSizeChng ){
  46074. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  46075. (int)pPager->nReserve);
  46076. }
  46077. }
  46078. #else
  46079. # define pagerReportSize(X) /* No-op if we do not support a codec */
  46080. #endif
  46081. #ifdef SQLITE_HAS_CODEC
  46082. /*
  46083. ** Make sure the number of reserved bits is the same in the destination
  46084. ** pager as it is in the source. This comes up when a VACUUM changes the
  46085. ** number of reserved bits to the "optimal" amount.
  46086. */
  46087. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
  46088. if( pDest->nReserve!=pSrc->nReserve ){
  46089. pDest->nReserve = pSrc->nReserve;
  46090. pagerReportSize(pDest);
  46091. }
  46092. }
  46093. #endif
  46094. /*
  46095. ** Read a single page from either the journal file (if isMainJrnl==1) or
  46096. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  46097. ** The page begins at offset *pOffset into the file. The *pOffset
  46098. ** value is increased to the start of the next page in the journal.
  46099. **
  46100. ** The main rollback journal uses checksums - the statement journal does
  46101. ** not.
  46102. **
  46103. ** If the page number of the page record read from the (sub-)journal file
  46104. ** is greater than the current value of Pager.dbSize, then playback is
  46105. ** skipped and SQLITE_OK is returned.
  46106. **
  46107. ** If pDone is not NULL, then it is a record of pages that have already
  46108. ** been played back. If the page at *pOffset has already been played back
  46109. ** (if the corresponding pDone bit is set) then skip the playback.
  46110. ** Make sure the pDone bit corresponding to the *pOffset page is set
  46111. ** prior to returning.
  46112. **
  46113. ** If the page record is successfully read from the (sub-)journal file
  46114. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  46115. ** while reading the record from the (sub-)journal file or while writing
  46116. ** to the database file, then the IO error code is returned. If data
  46117. ** is successfully read from the (sub-)journal file but appears to be
  46118. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  46119. ** two circumstances:
  46120. **
  46121. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  46122. ** * If the record is being rolled back from the main journal file
  46123. ** and the checksum field does not match the record content.
  46124. **
  46125. ** Neither of these two scenarios are possible during a savepoint rollback.
  46126. **
  46127. ** If this is a savepoint rollback, then memory may have to be dynamically
  46128. ** allocated by this function. If this is the case and an allocation fails,
  46129. ** SQLITE_NOMEM is returned.
  46130. */
  46131. static int pager_playback_one_page(
  46132. Pager *pPager, /* The pager being played back */
  46133. i64 *pOffset, /* Offset of record to playback */
  46134. Bitvec *pDone, /* Bitvec of pages already played back */
  46135. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  46136. int isSavepnt /* True for a savepoint rollback */
  46137. ){
  46138. int rc;
  46139. PgHdr *pPg; /* An existing page in the cache */
  46140. Pgno pgno; /* The page number of a page in journal */
  46141. u32 cksum; /* Checksum used for sanity checking */
  46142. char *aData; /* Temporary storage for the page */
  46143. sqlite3_file *jfd; /* The file descriptor for the journal file */
  46144. int isSynced; /* True if journal page is synced */
  46145. #ifdef SQLITE_HAS_CODEC
  46146. /* The jrnlEnc flag is true if Journal pages should be passed through
  46147. ** the codec. It is false for pure in-memory journals. */
  46148. const int jrnlEnc = (isMainJrnl || pPager->subjInMemory==0);
  46149. #endif
  46150. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  46151. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  46152. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  46153. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  46154. aData = pPager->pTmpSpace;
  46155. assert( aData ); /* Temp storage must have already been allocated */
  46156. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  46157. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  46158. ** or savepoint rollback done at the request of the caller) or this is
  46159. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  46160. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  46161. ** only reads from the main journal, not the sub-journal.
  46162. */
  46163. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  46164. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  46165. );
  46166. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  46167. /* Read the page number and page data from the journal or sub-journal
  46168. ** file. Return an error code to the caller if an IO error occurs.
  46169. */
  46170. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  46171. rc = read32bits(jfd, *pOffset, &pgno);
  46172. if( rc!=SQLITE_OK ) return rc;
  46173. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  46174. if( rc!=SQLITE_OK ) return rc;
  46175. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  46176. /* Sanity checking on the page. This is more important that I originally
  46177. ** thought. If a power failure occurs while the journal is being written,
  46178. ** it could cause invalid data to be written into the journal. We need to
  46179. ** detect this invalid data (with high probability) and ignore it.
  46180. */
  46181. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  46182. assert( !isSavepnt );
  46183. return SQLITE_DONE;
  46184. }
  46185. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  46186. return SQLITE_OK;
  46187. }
  46188. if( isMainJrnl ){
  46189. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  46190. if( rc ) return rc;
  46191. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  46192. return SQLITE_DONE;
  46193. }
  46194. }
  46195. /* If this page has already been played back before during the current
  46196. ** rollback, then don't bother to play it back again.
  46197. */
  46198. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  46199. return rc;
  46200. }
  46201. /* When playing back page 1, restore the nReserve setting
  46202. */
  46203. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  46204. pPager->nReserve = ((u8*)aData)[20];
  46205. pagerReportSize(pPager);
  46206. }
  46207. /* If the pager is in CACHEMOD state, then there must be a copy of this
  46208. ** page in the pager cache. In this case just update the pager cache,
  46209. ** not the database file. The page is left marked dirty in this case.
  46210. **
  46211. ** An exception to the above rule: If the database is in no-sync mode
  46212. ** and a page is moved during an incremental vacuum then the page may
  46213. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  46214. ** during a Movepage() call, then the page may not be in the cache
  46215. ** either. So the condition described in the above paragraph is not
  46216. ** assert()able.
  46217. **
  46218. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  46219. ** pager cache if it exists and the main file. The page is then marked
  46220. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  46221. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  46222. ** if the pager is in OPEN state.
  46223. **
  46224. ** Ticket #1171: The statement journal might contain page content that is
  46225. ** different from the page content at the start of the transaction.
  46226. ** This occurs when a page is changed prior to the start of a statement
  46227. ** then changed again within the statement. When rolling back such a
  46228. ** statement we must not write to the original database unless we know
  46229. ** for certain that original page contents are synced into the main rollback
  46230. ** journal. Otherwise, a power loss might leave modified data in the
  46231. ** database file without an entry in the rollback journal that can
  46232. ** restore the database to its original form. Two conditions must be
  46233. ** met before writing to the database files. (1) the database must be
  46234. ** locked. (2) we know that the original page content is fully synced
  46235. ** in the main journal either because the page is not in cache or else
  46236. ** the page is marked as needSync==0.
  46237. **
  46238. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  46239. ** is possible to fail a statement on a database that does not yet exist.
  46240. ** Do not attempt to write if database file has never been opened.
  46241. */
  46242. if( pagerUseWal(pPager) ){
  46243. pPg = 0;
  46244. }else{
  46245. pPg = sqlite3PagerLookup(pPager, pgno);
  46246. }
  46247. assert( pPg || !MEMDB );
  46248. assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
  46249. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  46250. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  46251. (isMainJrnl?"main-journal":"sub-journal")
  46252. ));
  46253. if( isMainJrnl ){
  46254. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  46255. }else{
  46256. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  46257. }
  46258. if( isOpen(pPager->fd)
  46259. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  46260. && isSynced
  46261. ){
  46262. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  46263. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  46264. assert( !pagerUseWal(pPager) );
  46265. /* Write the data read from the journal back into the database file.
  46266. ** This is usually safe even for an encrypted database - as the data
  46267. ** was encrypted before it was written to the journal file. The exception
  46268. ** is if the data was just read from an in-memory sub-journal. In that
  46269. ** case it must be encrypted here before it is copied into the database
  46270. ** file. */
  46271. #ifdef SQLITE_HAS_CODEC
  46272. if( !jrnlEnc ){
  46273. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
  46274. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  46275. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
  46276. }else
  46277. #endif
  46278. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  46279. if( pgno>pPager->dbFileSize ){
  46280. pPager->dbFileSize = pgno;
  46281. }
  46282. if( pPager->pBackup ){
  46283. #ifdef SQLITE_HAS_CODEC
  46284. if( jrnlEnc ){
  46285. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
  46286. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  46287. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT,aData);
  46288. }else
  46289. #endif
  46290. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  46291. }
  46292. }else if( !isMainJrnl && pPg==0 ){
  46293. /* If this is a rollback of a savepoint and data was not written to
  46294. ** the database and the page is not in-memory, there is a potential
  46295. ** problem. When the page is next fetched by the b-tree layer, it
  46296. ** will be read from the database file, which may or may not be
  46297. ** current.
  46298. **
  46299. ** There are a couple of different ways this can happen. All are quite
  46300. ** obscure. When running in synchronous mode, this can only happen
  46301. ** if the page is on the free-list at the start of the transaction, then
  46302. ** populated, then moved using sqlite3PagerMovepage().
  46303. **
  46304. ** The solution is to add an in-memory page to the cache containing
  46305. ** the data just read from the sub-journal. Mark the page as dirty
  46306. ** and if the pager requires a journal-sync, then mark the page as
  46307. ** requiring a journal-sync before it is written.
  46308. */
  46309. assert( isSavepnt );
  46310. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  46311. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  46312. rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
  46313. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  46314. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  46315. if( rc!=SQLITE_OK ) return rc;
  46316. sqlite3PcacheMakeDirty(pPg);
  46317. }
  46318. if( pPg ){
  46319. /* No page should ever be explicitly rolled back that is in use, except
  46320. ** for page 1 which is held in use in order to keep the lock on the
  46321. ** database active. However such a page may be rolled back as a result
  46322. ** of an internal error resulting in an automatic call to
  46323. ** sqlite3PagerRollback().
  46324. */
  46325. void *pData;
  46326. pData = pPg->pData;
  46327. memcpy(pData, (u8*)aData, pPager->pageSize);
  46328. pPager->xReiniter(pPg);
  46329. /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But
  46330. ** that call was dangerous and had no detectable benefit since the cache
  46331. ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
  46332. ** has been removed. */
  46333. pager_set_pagehash(pPg);
  46334. /* If this was page 1, then restore the value of Pager.dbFileVers.
  46335. ** Do this before any decoding. */
  46336. if( pgno==1 ){
  46337. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  46338. }
  46339. /* Decode the page just read from disk */
  46340. #if SQLITE_HAS_CODEC
  46341. if( jrnlEnc ){ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); }
  46342. #endif
  46343. sqlite3PcacheRelease(pPg);
  46344. }
  46345. return rc;
  46346. }
  46347. /*
  46348. ** Parameter zMaster is the name of a master journal file. A single journal
  46349. ** file that referred to the master journal file has just been rolled back.
  46350. ** This routine checks if it is possible to delete the master journal file,
  46351. ** and does so if it is.
  46352. **
  46353. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  46354. ** available for use within this function.
  46355. **
  46356. ** When a master journal file is created, it is populated with the names
  46357. ** of all of its child journals, one after another, formatted as utf-8
  46358. ** encoded text. The end of each child journal file is marked with a
  46359. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  46360. ** file for a transaction involving two databases might be:
  46361. **
  46362. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  46363. **
  46364. ** A master journal file may only be deleted once all of its child
  46365. ** journals have been rolled back.
  46366. **
  46367. ** This function reads the contents of the master-journal file into
  46368. ** memory and loops through each of the child journal names. For
  46369. ** each child journal, it checks if:
  46370. **
  46371. ** * if the child journal exists, and if so
  46372. ** * if the child journal contains a reference to master journal
  46373. ** file zMaster
  46374. **
  46375. ** If a child journal can be found that matches both of the criteria
  46376. ** above, this function returns without doing anything. Otherwise, if
  46377. ** no such child journal can be found, file zMaster is deleted from
  46378. ** the file-system using sqlite3OsDelete().
  46379. **
  46380. ** If an IO error within this function, an error code is returned. This
  46381. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  46382. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  46383. ** occur, SQLITE_OK is returned.
  46384. **
  46385. ** TODO: This function allocates a single block of memory to load
  46386. ** the entire contents of the master journal file. This could be
  46387. ** a couple of kilobytes or so - potentially larger than the page
  46388. ** size.
  46389. */
  46390. static int pager_delmaster(Pager *pPager, const char *zMaster){
  46391. sqlite3_vfs *pVfs = pPager->pVfs;
  46392. int rc; /* Return code */
  46393. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  46394. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  46395. char *zMasterJournal = 0; /* Contents of master journal file */
  46396. i64 nMasterJournal; /* Size of master journal file */
  46397. char *zJournal; /* Pointer to one journal within MJ file */
  46398. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  46399. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  46400. /* Allocate space for both the pJournal and pMaster file descriptors.
  46401. ** If successful, open the master journal file for reading.
  46402. */
  46403. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  46404. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  46405. if( !pMaster ){
  46406. rc = SQLITE_NOMEM_BKPT;
  46407. }else{
  46408. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  46409. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  46410. }
  46411. if( rc!=SQLITE_OK ) goto delmaster_out;
  46412. /* Load the entire master journal file into space obtained from
  46413. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  46414. ** sufficient space (in zMasterPtr) to hold the names of master
  46415. ** journal files extracted from regular rollback-journals.
  46416. */
  46417. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  46418. if( rc!=SQLITE_OK ) goto delmaster_out;
  46419. nMasterPtr = pVfs->mxPathname+1;
  46420. zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
  46421. if( !zMasterJournal ){
  46422. rc = SQLITE_NOMEM_BKPT;
  46423. goto delmaster_out;
  46424. }
  46425. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  46426. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  46427. if( rc!=SQLITE_OK ) goto delmaster_out;
  46428. zMasterJournal[nMasterJournal] = 0;
  46429. zJournal = zMasterJournal;
  46430. while( (zJournal-zMasterJournal)<nMasterJournal ){
  46431. int exists;
  46432. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  46433. if( rc!=SQLITE_OK ){
  46434. goto delmaster_out;
  46435. }
  46436. if( exists ){
  46437. /* One of the journals pointed to by the master journal exists.
  46438. ** Open it and check if it points at the master journal. If
  46439. ** so, return without deleting the master journal file.
  46440. */
  46441. int c;
  46442. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  46443. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  46444. if( rc!=SQLITE_OK ){
  46445. goto delmaster_out;
  46446. }
  46447. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  46448. sqlite3OsClose(pJournal);
  46449. if( rc!=SQLITE_OK ){
  46450. goto delmaster_out;
  46451. }
  46452. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  46453. if( c ){
  46454. /* We have a match. Do not delete the master journal file. */
  46455. goto delmaster_out;
  46456. }
  46457. }
  46458. zJournal += (sqlite3Strlen30(zJournal)+1);
  46459. }
  46460. sqlite3OsClose(pMaster);
  46461. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  46462. delmaster_out:
  46463. sqlite3_free(zMasterJournal);
  46464. if( pMaster ){
  46465. sqlite3OsClose(pMaster);
  46466. assert( !isOpen(pJournal) );
  46467. sqlite3_free(pMaster);
  46468. }
  46469. return rc;
  46470. }
  46471. /*
  46472. ** This function is used to change the actual size of the database
  46473. ** file in the file-system. This only happens when committing a transaction,
  46474. ** or rolling back a transaction (including rolling back a hot-journal).
  46475. **
  46476. ** If the main database file is not open, or the pager is not in either
  46477. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  46478. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  46479. ** If the file on disk is currently larger than nPage pages, then use the VFS
  46480. ** xTruncate() method to truncate it.
  46481. **
  46482. ** Or, it might be the case that the file on disk is smaller than
  46483. ** nPage pages. Some operating system implementations can get confused if
  46484. ** you try to truncate a file to some size that is larger than it
  46485. ** currently is, so detect this case and write a single zero byte to
  46486. ** the end of the new file instead.
  46487. **
  46488. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  46489. ** the database file, return the error code to the caller.
  46490. */
  46491. static int pager_truncate(Pager *pPager, Pgno nPage){
  46492. int rc = SQLITE_OK;
  46493. assert( pPager->eState!=PAGER_ERROR );
  46494. assert( pPager->eState!=PAGER_READER );
  46495. if( isOpen(pPager->fd)
  46496. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  46497. ){
  46498. i64 currentSize, newSize;
  46499. int szPage = pPager->pageSize;
  46500. assert( pPager->eLock==EXCLUSIVE_LOCK );
  46501. /* TODO: Is it safe to use Pager.dbFileSize here? */
  46502. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  46503. newSize = szPage*(i64)nPage;
  46504. if( rc==SQLITE_OK && currentSize!=newSize ){
  46505. if( currentSize>newSize ){
  46506. rc = sqlite3OsTruncate(pPager->fd, newSize);
  46507. }else if( (currentSize+szPage)<=newSize ){
  46508. char *pTmp = pPager->pTmpSpace;
  46509. memset(pTmp, 0, szPage);
  46510. testcase( (newSize-szPage) == currentSize );
  46511. testcase( (newSize-szPage) > currentSize );
  46512. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  46513. }
  46514. if( rc==SQLITE_OK ){
  46515. pPager->dbFileSize = nPage;
  46516. }
  46517. }
  46518. }
  46519. return rc;
  46520. }
  46521. /*
  46522. ** Return a sanitized version of the sector-size of OS file pFile. The
  46523. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  46524. */
  46525. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  46526. int iRet = sqlite3OsSectorSize(pFile);
  46527. if( iRet<32 ){
  46528. iRet = 512;
  46529. }else if( iRet>MAX_SECTOR_SIZE ){
  46530. assert( MAX_SECTOR_SIZE>=512 );
  46531. iRet = MAX_SECTOR_SIZE;
  46532. }
  46533. return iRet;
  46534. }
  46535. /*
  46536. ** Set the value of the Pager.sectorSize variable for the given
  46537. ** pager based on the value returned by the xSectorSize method
  46538. ** of the open database file. The sector size will be used
  46539. ** to determine the size and alignment of journal header and
  46540. ** master journal pointers within created journal files.
  46541. **
  46542. ** For temporary files the effective sector size is always 512 bytes.
  46543. **
  46544. ** Otherwise, for non-temporary files, the effective sector size is
  46545. ** the value returned by the xSectorSize() method rounded up to 32 if
  46546. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  46547. ** is greater than MAX_SECTOR_SIZE.
  46548. **
  46549. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  46550. ** the effective sector size to its minimum value (512). The purpose of
  46551. ** pPager->sectorSize is to define the "blast radius" of bytes that
  46552. ** might change if a crash occurs while writing to a single byte in
  46553. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  46554. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  46555. ** size. For backwards compatibility of the rollback journal file format,
  46556. ** we cannot reduce the effective sector size below 512.
  46557. */
  46558. static void setSectorSize(Pager *pPager){
  46559. assert( isOpen(pPager->fd) || pPager->tempFile );
  46560. if( pPager->tempFile
  46561. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  46562. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  46563. ){
  46564. /* Sector size doesn't matter for temporary files. Also, the file
  46565. ** may not have been opened yet, in which case the OsSectorSize()
  46566. ** call will segfault. */
  46567. pPager->sectorSize = 512;
  46568. }else{
  46569. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  46570. }
  46571. }
  46572. /*
  46573. ** Playback the journal and thus restore the database file to
  46574. ** the state it was in before we started making changes.
  46575. **
  46576. ** The journal file format is as follows:
  46577. **
  46578. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  46579. ** (2) 4 byte big-endian integer which is the number of valid page records
  46580. ** in the journal. If this value is 0xffffffff, then compute the
  46581. ** number of page records from the journal size.
  46582. ** (3) 4 byte big-endian integer which is the initial value for the
  46583. ** sanity checksum.
  46584. ** (4) 4 byte integer which is the number of pages to truncate the
  46585. ** database to during a rollback.
  46586. ** (5) 4 byte big-endian integer which is the sector size. The header
  46587. ** is this many bytes in size.
  46588. ** (6) 4 byte big-endian integer which is the page size.
  46589. ** (7) zero padding out to the next sector size.
  46590. ** (8) Zero or more pages instances, each as follows:
  46591. ** + 4 byte page number.
  46592. ** + pPager->pageSize bytes of data.
  46593. ** + 4 byte checksum
  46594. **
  46595. ** When we speak of the journal header, we mean the first 7 items above.
  46596. ** Each entry in the journal is an instance of the 8th item.
  46597. **
  46598. ** Call the value from the second bullet "nRec". nRec is the number of
  46599. ** valid page entries in the journal. In most cases, you can compute the
  46600. ** value of nRec from the size of the journal file. But if a power
  46601. ** failure occurred while the journal was being written, it could be the
  46602. ** case that the size of the journal file had already been increased but
  46603. ** the extra entries had not yet made it safely to disk. In such a case,
  46604. ** the value of nRec computed from the file size would be too large. For
  46605. ** that reason, we always use the nRec value in the header.
  46606. **
  46607. ** If the nRec value is 0xffffffff it means that nRec should be computed
  46608. ** from the file size. This value is used when the user selects the
  46609. ** no-sync option for the journal. A power failure could lead to corruption
  46610. ** in this case. But for things like temporary table (which will be
  46611. ** deleted when the power is restored) we don't care.
  46612. **
  46613. ** If the file opened as the journal file is not a well-formed
  46614. ** journal file then all pages up to the first corrupted page are rolled
  46615. ** back (or no pages if the journal header is corrupted). The journal file
  46616. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  46617. ** been encountered.
  46618. **
  46619. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  46620. ** and an error code is returned.
  46621. **
  46622. ** The isHot parameter indicates that we are trying to rollback a journal
  46623. ** that might be a hot journal. Or, it could be that the journal is
  46624. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  46625. ** If the journal really is hot, reset the pager cache prior rolling
  46626. ** back any content. If the journal is merely persistent, no reset is
  46627. ** needed.
  46628. */
  46629. static int pager_playback(Pager *pPager, int isHot){
  46630. sqlite3_vfs *pVfs = pPager->pVfs;
  46631. i64 szJ; /* Size of the journal file in bytes */
  46632. u32 nRec; /* Number of Records in the journal */
  46633. u32 u; /* Unsigned loop counter */
  46634. Pgno mxPg = 0; /* Size of the original file in pages */
  46635. int rc; /* Result code of a subroutine */
  46636. int res = 1; /* Value returned by sqlite3OsAccess() */
  46637. char *zMaster = 0; /* Name of master journal file if any */
  46638. int needPagerReset; /* True to reset page prior to first page rollback */
  46639. int nPlayback = 0; /* Total number of pages restored from journal */
  46640. /* Figure out how many records are in the journal. Abort early if
  46641. ** the journal is empty.
  46642. */
  46643. assert( isOpen(pPager->jfd) );
  46644. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  46645. if( rc!=SQLITE_OK ){
  46646. goto end_playback;
  46647. }
  46648. /* Read the master journal name from the journal, if it is present.
  46649. ** If a master journal file name is specified, but the file is not
  46650. ** present on disk, then the journal is not hot and does not need to be
  46651. ** played back.
  46652. **
  46653. ** TODO: Technically the following is an error because it assumes that
  46654. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  46655. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  46656. ** mxPathname is 512, which is the same as the minimum allowable value
  46657. ** for pageSize.
  46658. */
  46659. zMaster = pPager->pTmpSpace;
  46660. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  46661. if( rc==SQLITE_OK && zMaster[0] ){
  46662. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  46663. }
  46664. zMaster = 0;
  46665. if( rc!=SQLITE_OK || !res ){
  46666. goto end_playback;
  46667. }
  46668. pPager->journalOff = 0;
  46669. needPagerReset = isHot;
  46670. /* This loop terminates either when a readJournalHdr() or
  46671. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  46672. ** occurs.
  46673. */
  46674. while( 1 ){
  46675. /* Read the next journal header from the journal file. If there are
  46676. ** not enough bytes left in the journal file for a complete header, or
  46677. ** it is corrupted, then a process must have failed while writing it.
  46678. ** This indicates nothing more needs to be rolled back.
  46679. */
  46680. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  46681. if( rc!=SQLITE_OK ){
  46682. if( rc==SQLITE_DONE ){
  46683. rc = SQLITE_OK;
  46684. }
  46685. goto end_playback;
  46686. }
  46687. /* If nRec is 0xffffffff, then this journal was created by a process
  46688. ** working in no-sync mode. This means that the rest of the journal
  46689. ** file consists of pages, there are no more journal headers. Compute
  46690. ** the value of nRec based on this assumption.
  46691. */
  46692. if( nRec==0xffffffff ){
  46693. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  46694. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  46695. }
  46696. /* If nRec is 0 and this rollback is of a transaction created by this
  46697. ** process and if this is the final header in the journal, then it means
  46698. ** that this part of the journal was being filled but has not yet been
  46699. ** synced to disk. Compute the number of pages based on the remaining
  46700. ** size of the file.
  46701. **
  46702. ** The third term of the test was added to fix ticket #2565.
  46703. ** When rolling back a hot journal, nRec==0 always means that the next
  46704. ** chunk of the journal contains zero pages to be rolled back. But
  46705. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  46706. ** the journal, it means that the journal might contain additional
  46707. ** pages that need to be rolled back and that the number of pages
  46708. ** should be computed based on the journal file size.
  46709. */
  46710. if( nRec==0 && !isHot &&
  46711. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  46712. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  46713. }
  46714. /* If this is the first header read from the journal, truncate the
  46715. ** database file back to its original size.
  46716. */
  46717. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  46718. rc = pager_truncate(pPager, mxPg);
  46719. if( rc!=SQLITE_OK ){
  46720. goto end_playback;
  46721. }
  46722. pPager->dbSize = mxPg;
  46723. }
  46724. /* Copy original pages out of the journal and back into the
  46725. ** database file and/or page cache.
  46726. */
  46727. for(u=0; u<nRec; u++){
  46728. if( needPagerReset ){
  46729. pager_reset(pPager);
  46730. needPagerReset = 0;
  46731. }
  46732. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  46733. if( rc==SQLITE_OK ){
  46734. nPlayback++;
  46735. }else{
  46736. if( rc==SQLITE_DONE ){
  46737. pPager->journalOff = szJ;
  46738. break;
  46739. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  46740. /* If the journal has been truncated, simply stop reading and
  46741. ** processing the journal. This might happen if the journal was
  46742. ** not completely written and synced prior to a crash. In that
  46743. ** case, the database should have never been written in the
  46744. ** first place so it is OK to simply abandon the rollback. */
  46745. rc = SQLITE_OK;
  46746. goto end_playback;
  46747. }else{
  46748. /* If we are unable to rollback, quit and return the error
  46749. ** code. This will cause the pager to enter the error state
  46750. ** so that no further harm will be done. Perhaps the next
  46751. ** process to come along will be able to rollback the database.
  46752. */
  46753. goto end_playback;
  46754. }
  46755. }
  46756. }
  46757. }
  46758. /*NOTREACHED*/
  46759. assert( 0 );
  46760. end_playback:
  46761. /* Following a rollback, the database file should be back in its original
  46762. ** state prior to the start of the transaction, so invoke the
  46763. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  46764. ** assertion that the transaction counter was modified.
  46765. */
  46766. #ifdef SQLITE_DEBUG
  46767. if( pPager->fd->pMethods ){
  46768. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  46769. }
  46770. #endif
  46771. /* If this playback is happening automatically as a result of an IO or
  46772. ** malloc error that occurred after the change-counter was updated but
  46773. ** before the transaction was committed, then the change-counter
  46774. ** modification may just have been reverted. If this happens in exclusive
  46775. ** mode, then subsequent transactions performed by the connection will not
  46776. ** update the change-counter at all. This may lead to cache inconsistency
  46777. ** problems for other processes at some point in the future. So, just
  46778. ** in case this has happened, clear the changeCountDone flag now.
  46779. */
  46780. pPager->changeCountDone = pPager->tempFile;
  46781. if( rc==SQLITE_OK ){
  46782. zMaster = pPager->pTmpSpace;
  46783. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  46784. testcase( rc!=SQLITE_OK );
  46785. }
  46786. if( rc==SQLITE_OK
  46787. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  46788. ){
  46789. rc = sqlite3PagerSync(pPager, 0);
  46790. }
  46791. if( rc==SQLITE_OK ){
  46792. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  46793. testcase( rc!=SQLITE_OK );
  46794. }
  46795. if( rc==SQLITE_OK && zMaster[0] && res ){
  46796. /* If there was a master journal and this routine will return success,
  46797. ** see if it is possible to delete the master journal.
  46798. */
  46799. rc = pager_delmaster(pPager, zMaster);
  46800. testcase( rc!=SQLITE_OK );
  46801. }
  46802. if( isHot && nPlayback ){
  46803. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  46804. nPlayback, pPager->zJournal);
  46805. }
  46806. /* The Pager.sectorSize variable may have been updated while rolling
  46807. ** back a journal created by a process with a different sector size
  46808. ** value. Reset it to the correct value for this process.
  46809. */
  46810. setSectorSize(pPager);
  46811. return rc;
  46812. }
  46813. /*
  46814. ** Read the content for page pPg out of the database file and into
  46815. ** pPg->pData. A shared lock or greater must be held on the database
  46816. ** file before this function is called.
  46817. **
  46818. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  46819. ** the value read from the database file.
  46820. **
  46821. ** If an IO error occurs, then the IO error is returned to the caller.
  46822. ** Otherwise, SQLITE_OK is returned.
  46823. */
  46824. static int readDbPage(PgHdr *pPg, u32 iFrame){
  46825. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  46826. Pgno pgno = pPg->pgno; /* Page number to read */
  46827. int rc = SQLITE_OK; /* Return code */
  46828. int pgsz = pPager->pageSize; /* Number of bytes to read */
  46829. assert( pPager->eState>=PAGER_READER && !MEMDB );
  46830. assert( isOpen(pPager->fd) );
  46831. #ifndef SQLITE_OMIT_WAL
  46832. if( iFrame ){
  46833. /* Try to pull the page from the write-ahead log. */
  46834. rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
  46835. }else
  46836. #endif
  46837. {
  46838. i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
  46839. rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
  46840. if( rc==SQLITE_IOERR_SHORT_READ ){
  46841. rc = SQLITE_OK;
  46842. }
  46843. }
  46844. if( pgno==1 ){
  46845. if( rc ){
  46846. /* If the read is unsuccessful, set the dbFileVers[] to something
  46847. ** that will never be a valid file version. dbFileVers[] is a copy
  46848. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  46849. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  46850. ** should be page numbers which are never 0xffffffff. So filling
  46851. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  46852. **
  46853. ** For an encrypted database, the situation is more complex: bytes
  46854. ** 24..39 of the database are white noise. But the probability of
  46855. ** white noise equaling 16 bytes of 0xff is vanishingly small so
  46856. ** we should still be ok.
  46857. */
  46858. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  46859. }else{
  46860. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  46861. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  46862. }
  46863. }
  46864. CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM_BKPT);
  46865. PAGER_INCR(sqlite3_pager_readdb_count);
  46866. PAGER_INCR(pPager->nRead);
  46867. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  46868. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  46869. PAGERID(pPager), pgno, pager_pagehash(pPg)));
  46870. return rc;
  46871. }
  46872. /*
  46873. ** Update the value of the change-counter at offsets 24 and 92 in
  46874. ** the header and the sqlite version number at offset 96.
  46875. **
  46876. ** This is an unconditional update. See also the pager_incr_changecounter()
  46877. ** routine which only updates the change-counter if the update is actually
  46878. ** needed, as determined by the pPager->changeCountDone state variable.
  46879. */
  46880. static void pager_write_changecounter(PgHdr *pPg){
  46881. u32 change_counter;
  46882. /* Increment the value just read and write it back to byte 24. */
  46883. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  46884. put32bits(((char*)pPg->pData)+24, change_counter);
  46885. /* Also store the SQLite version number in bytes 96..99 and in
  46886. ** bytes 92..95 store the change counter for which the version number
  46887. ** is valid. */
  46888. put32bits(((char*)pPg->pData)+92, change_counter);
  46889. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  46890. }
  46891. #ifndef SQLITE_OMIT_WAL
  46892. /*
  46893. ** This function is invoked once for each page that has already been
  46894. ** written into the log file when a WAL transaction is rolled back.
  46895. ** Parameter iPg is the page number of said page. The pCtx argument
  46896. ** is actually a pointer to the Pager structure.
  46897. **
  46898. ** If page iPg is present in the cache, and has no outstanding references,
  46899. ** it is discarded. Otherwise, if there are one or more outstanding
  46900. ** references, the page content is reloaded from the database. If the
  46901. ** attempt to reload content from the database is required and fails,
  46902. ** return an SQLite error code. Otherwise, SQLITE_OK.
  46903. */
  46904. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  46905. int rc = SQLITE_OK;
  46906. Pager *pPager = (Pager *)pCtx;
  46907. PgHdr *pPg;
  46908. assert( pagerUseWal(pPager) );
  46909. pPg = sqlite3PagerLookup(pPager, iPg);
  46910. if( pPg ){
  46911. if( sqlite3PcachePageRefcount(pPg)==1 ){
  46912. sqlite3PcacheDrop(pPg);
  46913. }else{
  46914. u32 iFrame = 0;
  46915. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  46916. if( rc==SQLITE_OK ){
  46917. rc = readDbPage(pPg, iFrame);
  46918. }
  46919. if( rc==SQLITE_OK ){
  46920. pPager->xReiniter(pPg);
  46921. }
  46922. sqlite3PagerUnrefNotNull(pPg);
  46923. }
  46924. }
  46925. /* Normally, if a transaction is rolled back, any backup processes are
  46926. ** updated as data is copied out of the rollback journal and into the
  46927. ** database. This is not generally possible with a WAL database, as
  46928. ** rollback involves simply truncating the log file. Therefore, if one
  46929. ** or more frames have already been written to the log (and therefore
  46930. ** also copied into the backup databases) as part of this transaction,
  46931. ** the backups must be restarted.
  46932. */
  46933. sqlite3BackupRestart(pPager->pBackup);
  46934. return rc;
  46935. }
  46936. /*
  46937. ** This function is called to rollback a transaction on a WAL database.
  46938. */
  46939. static int pagerRollbackWal(Pager *pPager){
  46940. int rc; /* Return Code */
  46941. PgHdr *pList; /* List of dirty pages to revert */
  46942. /* For all pages in the cache that are currently dirty or have already
  46943. ** been written (but not committed) to the log file, do one of the
  46944. ** following:
  46945. **
  46946. ** + Discard the cached page (if refcount==0), or
  46947. ** + Reload page content from the database (if refcount>0).
  46948. */
  46949. pPager->dbSize = pPager->dbOrigSize;
  46950. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  46951. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  46952. while( pList && rc==SQLITE_OK ){
  46953. PgHdr *pNext = pList->pDirty;
  46954. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  46955. pList = pNext;
  46956. }
  46957. return rc;
  46958. }
  46959. /*
  46960. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  46961. ** the contents of the list of pages headed by pList (connected by pDirty),
  46962. ** this function notifies any active backup processes that the pages have
  46963. ** changed.
  46964. **
  46965. ** The list of pages passed into this routine is always sorted by page number.
  46966. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  46967. */
  46968. static int pagerWalFrames(
  46969. Pager *pPager, /* Pager object */
  46970. PgHdr *pList, /* List of frames to log */
  46971. Pgno nTruncate, /* Database size after this commit */
  46972. int isCommit /* True if this is a commit */
  46973. ){
  46974. int rc; /* Return code */
  46975. int nList; /* Number of pages in pList */
  46976. PgHdr *p; /* For looping over pages */
  46977. assert( pPager->pWal );
  46978. assert( pList );
  46979. #ifdef SQLITE_DEBUG
  46980. /* Verify that the page list is in accending order */
  46981. for(p=pList; p && p->pDirty; p=p->pDirty){
  46982. assert( p->pgno < p->pDirty->pgno );
  46983. }
  46984. #endif
  46985. assert( pList->pDirty==0 || isCommit );
  46986. if( isCommit ){
  46987. /* If a WAL transaction is being committed, there is no point in writing
  46988. ** any pages with page numbers greater than nTruncate into the WAL file.
  46989. ** They will never be read by any client. So remove them from the pDirty
  46990. ** list here. */
  46991. PgHdr **ppNext = &pList;
  46992. nList = 0;
  46993. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  46994. if( p->pgno<=nTruncate ){
  46995. ppNext = &p->pDirty;
  46996. nList++;
  46997. }
  46998. }
  46999. assert( pList );
  47000. }else{
  47001. nList = 1;
  47002. }
  47003. pPager->aStat[PAGER_STAT_WRITE] += nList;
  47004. if( pList->pgno==1 ) pager_write_changecounter(pList);
  47005. rc = sqlite3WalFrames(pPager->pWal,
  47006. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  47007. );
  47008. if( rc==SQLITE_OK && pPager->pBackup ){
  47009. for(p=pList; p; p=p->pDirty){
  47010. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  47011. }
  47012. }
  47013. #ifdef SQLITE_CHECK_PAGES
  47014. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  47015. for(p=pList; p; p=p->pDirty){
  47016. pager_set_pagehash(p);
  47017. }
  47018. #endif
  47019. return rc;
  47020. }
  47021. /*
  47022. ** Begin a read transaction on the WAL.
  47023. **
  47024. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  47025. ** makes a snapshot of the database at the current point in time and preserves
  47026. ** that snapshot for use by the reader in spite of concurrently changes by
  47027. ** other writers or checkpointers.
  47028. */
  47029. static int pagerBeginReadTransaction(Pager *pPager){
  47030. int rc; /* Return code */
  47031. int changed = 0; /* True if cache must be reset */
  47032. assert( pagerUseWal(pPager) );
  47033. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  47034. /* sqlite3WalEndReadTransaction() was not called for the previous
  47035. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  47036. ** are in locking_mode=NORMAL and EndRead() was previously called,
  47037. ** the duplicate call is harmless.
  47038. */
  47039. sqlite3WalEndReadTransaction(pPager->pWal);
  47040. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  47041. if( rc!=SQLITE_OK || changed ){
  47042. pager_reset(pPager);
  47043. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  47044. }
  47045. return rc;
  47046. }
  47047. #endif
  47048. /*
  47049. ** This function is called as part of the transition from PAGER_OPEN
  47050. ** to PAGER_READER state to determine the size of the database file
  47051. ** in pages (assuming the page size currently stored in Pager.pageSize).
  47052. **
  47053. ** If no error occurs, SQLITE_OK is returned and the size of the database
  47054. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  47055. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  47056. */
  47057. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  47058. Pgno nPage; /* Value to return via *pnPage */
  47059. /* Query the WAL sub-system for the database size. The WalDbsize()
  47060. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  47061. ** if the database size is not available. The database size is not
  47062. ** available from the WAL sub-system if the log file is empty or
  47063. ** contains no valid committed transactions.
  47064. */
  47065. assert( pPager->eState==PAGER_OPEN );
  47066. assert( pPager->eLock>=SHARED_LOCK );
  47067. assert( isOpen(pPager->fd) );
  47068. assert( pPager->tempFile==0 );
  47069. nPage = sqlite3WalDbsize(pPager->pWal);
  47070. /* If the number of pages in the database is not available from the
  47071. ** WAL sub-system, determine the page counte based on the size of
  47072. ** the database file. If the size of the database file is not an
  47073. ** integer multiple of the page-size, round up the result.
  47074. */
  47075. if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
  47076. i64 n = 0; /* Size of db file in bytes */
  47077. int rc = sqlite3OsFileSize(pPager->fd, &n);
  47078. if( rc!=SQLITE_OK ){
  47079. return rc;
  47080. }
  47081. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  47082. }
  47083. /* If the current number of pages in the file is greater than the
  47084. ** configured maximum pager number, increase the allowed limit so
  47085. ** that the file can be read.
  47086. */
  47087. if( nPage>pPager->mxPgno ){
  47088. pPager->mxPgno = (Pgno)nPage;
  47089. }
  47090. *pnPage = nPage;
  47091. return SQLITE_OK;
  47092. }
  47093. #ifndef SQLITE_OMIT_WAL
  47094. /*
  47095. ** Check if the *-wal file that corresponds to the database opened by pPager
  47096. ** exists if the database is not empy, or verify that the *-wal file does
  47097. ** not exist (by deleting it) if the database file is empty.
  47098. **
  47099. ** If the database is not empty and the *-wal file exists, open the pager
  47100. ** in WAL mode. If the database is empty or if no *-wal file exists and
  47101. ** if no error occurs, make sure Pager.journalMode is not set to
  47102. ** PAGER_JOURNALMODE_WAL.
  47103. **
  47104. ** Return SQLITE_OK or an error code.
  47105. **
  47106. ** The caller must hold a SHARED lock on the database file to call this
  47107. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  47108. ** a WAL on a none-empty database, this ensures there is no race condition
  47109. ** between the xAccess() below and an xDelete() being executed by some
  47110. ** other connection.
  47111. */
  47112. static int pagerOpenWalIfPresent(Pager *pPager){
  47113. int rc = SQLITE_OK;
  47114. assert( pPager->eState==PAGER_OPEN );
  47115. assert( pPager->eLock>=SHARED_LOCK );
  47116. if( !pPager->tempFile ){
  47117. int isWal; /* True if WAL file exists */
  47118. Pgno nPage; /* Size of the database file */
  47119. rc = pagerPagecount(pPager, &nPage);
  47120. if( rc ) return rc;
  47121. if( nPage==0 ){
  47122. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  47123. if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
  47124. isWal = 0;
  47125. }else{
  47126. rc = sqlite3OsAccess(
  47127. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  47128. );
  47129. }
  47130. if( rc==SQLITE_OK ){
  47131. if( isWal ){
  47132. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  47133. rc = sqlite3PagerOpenWal(pPager, 0);
  47134. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  47135. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  47136. }
  47137. }
  47138. }
  47139. return rc;
  47140. }
  47141. #endif
  47142. /*
  47143. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  47144. ** the entire master journal file. The case pSavepoint==NULL occurs when
  47145. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  47146. ** savepoint.
  47147. **
  47148. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  47149. ** being rolled back), then the rollback consists of up to three stages,
  47150. ** performed in the order specified:
  47151. **
  47152. ** * Pages are played back from the main journal starting at byte
  47153. ** offset PagerSavepoint.iOffset and continuing to
  47154. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  47155. ** file if PagerSavepoint.iHdrOffset is zero.
  47156. **
  47157. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  47158. ** back starting from the journal header immediately following
  47159. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  47160. **
  47161. ** * Pages are then played back from the sub-journal file, starting
  47162. ** with the PagerSavepoint.iSubRec and continuing to the end of
  47163. ** the journal file.
  47164. **
  47165. ** Throughout the rollback process, each time a page is rolled back, the
  47166. ** corresponding bit is set in a bitvec structure (variable pDone in the
  47167. ** implementation below). This is used to ensure that a page is only
  47168. ** rolled back the first time it is encountered in either journal.
  47169. **
  47170. ** If pSavepoint is NULL, then pages are only played back from the main
  47171. ** journal file. There is no need for a bitvec in this case.
  47172. **
  47173. ** In either case, before playback commences the Pager.dbSize variable
  47174. ** is reset to the value that it held at the start of the savepoint
  47175. ** (or transaction). No page with a page-number greater than this value
  47176. ** is played back. If one is encountered it is simply skipped.
  47177. */
  47178. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  47179. i64 szJ; /* Effective size of the main journal */
  47180. i64 iHdrOff; /* End of first segment of main-journal records */
  47181. int rc = SQLITE_OK; /* Return code */
  47182. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  47183. assert( pPager->eState!=PAGER_ERROR );
  47184. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  47185. /* Allocate a bitvec to use to store the set of pages rolled back */
  47186. if( pSavepoint ){
  47187. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  47188. if( !pDone ){
  47189. return SQLITE_NOMEM_BKPT;
  47190. }
  47191. }
  47192. /* Set the database size back to the value it was before the savepoint
  47193. ** being reverted was opened.
  47194. */
  47195. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  47196. pPager->changeCountDone = pPager->tempFile;
  47197. if( !pSavepoint && pagerUseWal(pPager) ){
  47198. return pagerRollbackWal(pPager);
  47199. }
  47200. /* Use pPager->journalOff as the effective size of the main rollback
  47201. ** journal. The actual file might be larger than this in
  47202. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  47203. ** past pPager->journalOff is off-limits to us.
  47204. */
  47205. szJ = pPager->journalOff;
  47206. assert( pagerUseWal(pPager)==0 || szJ==0 );
  47207. /* Begin by rolling back records from the main journal starting at
  47208. ** PagerSavepoint.iOffset and continuing to the next journal header.
  47209. ** There might be records in the main journal that have a page number
  47210. ** greater than the current database size (pPager->dbSize) but those
  47211. ** will be skipped automatically. Pages are added to pDone as they
  47212. ** are played back.
  47213. */
  47214. if( pSavepoint && !pagerUseWal(pPager) ){
  47215. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  47216. pPager->journalOff = pSavepoint->iOffset;
  47217. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  47218. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  47219. }
  47220. assert( rc!=SQLITE_DONE );
  47221. }else{
  47222. pPager->journalOff = 0;
  47223. }
  47224. /* Continue rolling back records out of the main journal starting at
  47225. ** the first journal header seen and continuing until the effective end
  47226. ** of the main journal file. Continue to skip out-of-range pages and
  47227. ** continue adding pages rolled back to pDone.
  47228. */
  47229. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  47230. u32 ii; /* Loop counter */
  47231. u32 nJRec = 0; /* Number of Journal Records */
  47232. u32 dummy;
  47233. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  47234. assert( rc!=SQLITE_DONE );
  47235. /*
  47236. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  47237. ** test is related to ticket #2565. See the discussion in the
  47238. ** pager_playback() function for additional information.
  47239. */
  47240. if( nJRec==0
  47241. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  47242. ){
  47243. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  47244. }
  47245. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  47246. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  47247. }
  47248. assert( rc!=SQLITE_DONE );
  47249. }
  47250. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  47251. /* Finally, rollback pages from the sub-journal. Page that were
  47252. ** previously rolled back out of the main journal (and are hence in pDone)
  47253. ** will be skipped. Out-of-range pages are also skipped.
  47254. */
  47255. if( pSavepoint ){
  47256. u32 ii; /* Loop counter */
  47257. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  47258. if( pagerUseWal(pPager) ){
  47259. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  47260. }
  47261. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  47262. assert( offset==(i64)ii*(4+pPager->pageSize) );
  47263. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  47264. }
  47265. assert( rc!=SQLITE_DONE );
  47266. }
  47267. sqlite3BitvecDestroy(pDone);
  47268. if( rc==SQLITE_OK ){
  47269. pPager->journalOff = szJ;
  47270. }
  47271. return rc;
  47272. }
  47273. /*
  47274. ** Change the maximum number of in-memory pages that are allowed
  47275. ** before attempting to recycle clean and unused pages.
  47276. */
  47277. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  47278. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  47279. }
  47280. /*
  47281. ** Change the maximum number of in-memory pages that are allowed
  47282. ** before attempting to spill pages to journal.
  47283. */
  47284. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
  47285. return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
  47286. }
  47287. /*
  47288. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  47289. */
  47290. static void pagerFixMaplimit(Pager *pPager){
  47291. #if SQLITE_MAX_MMAP_SIZE>0
  47292. sqlite3_file *fd = pPager->fd;
  47293. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  47294. sqlite3_int64 sz;
  47295. sz = pPager->szMmap;
  47296. pPager->bUseFetch = (sz>0);
  47297. setGetterMethod(pPager);
  47298. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  47299. }
  47300. #endif
  47301. }
  47302. /*
  47303. ** Change the maximum size of any memory mapping made of the database file.
  47304. */
  47305. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  47306. pPager->szMmap = szMmap;
  47307. pagerFixMaplimit(pPager);
  47308. }
  47309. /*
  47310. ** Free as much memory as possible from the pager.
  47311. */
  47312. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  47313. sqlite3PcacheShrink(pPager->pPCache);
  47314. }
  47315. /*
  47316. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  47317. **
  47318. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  47319. ** of the database to damage due to OS crashes or power failures by
  47320. ** changing the number of syncs()s when writing the journals.
  47321. ** There are four levels:
  47322. **
  47323. ** OFF sqlite3OsSync() is never called. This is the default
  47324. ** for temporary and transient files.
  47325. **
  47326. ** NORMAL The journal is synced once before writes begin on the
  47327. ** database. This is normally adequate protection, but
  47328. ** it is theoretically possible, though very unlikely,
  47329. ** that an inopertune power failure could leave the journal
  47330. ** in a state which would cause damage to the database
  47331. ** when it is rolled back.
  47332. **
  47333. ** FULL The journal is synced twice before writes begin on the
  47334. ** database (with some additional information - the nRec field
  47335. ** of the journal header - being written in between the two
  47336. ** syncs). If we assume that writing a
  47337. ** single disk sector is atomic, then this mode provides
  47338. ** assurance that the journal will not be corrupted to the
  47339. ** point of causing damage to the database during rollback.
  47340. **
  47341. ** EXTRA This is like FULL except that is also syncs the directory
  47342. ** that contains the rollback journal after the rollback
  47343. ** journal is unlinked.
  47344. **
  47345. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  47346. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  47347. ** prior to the start of checkpoint and that the database file is synced
  47348. ** at the conclusion of the checkpoint if the entire content of the WAL
  47349. ** was written back into the database. But no sync operations occur for
  47350. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  47351. ** file is synced following each commit operation, in addition to the
  47352. ** syncs associated with NORMAL. There is no difference between FULL
  47353. ** and EXTRA for WAL mode.
  47354. **
  47355. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  47356. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  47357. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  47358. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  47359. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  47360. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  47361. ** the xSync primitive is called and is relevant to all platforms.
  47362. **
  47363. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  47364. ** and FULL=3.
  47365. */
  47366. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  47367. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  47368. Pager *pPager, /* The pager to set safety level for */
  47369. unsigned pgFlags /* Various flags */
  47370. ){
  47371. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  47372. if( pPager->tempFile ){
  47373. pPager->noSync = 1;
  47374. pPager->fullSync = 0;
  47375. pPager->extraSync = 0;
  47376. }else{
  47377. pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0;
  47378. pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
  47379. pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
  47380. }
  47381. if( pPager->noSync ){
  47382. pPager->syncFlags = 0;
  47383. pPager->ckptSyncFlags = 0;
  47384. }else if( pgFlags & PAGER_FULLFSYNC ){
  47385. pPager->syncFlags = SQLITE_SYNC_FULL;
  47386. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  47387. }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
  47388. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  47389. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  47390. }else{
  47391. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  47392. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  47393. }
  47394. pPager->walSyncFlags = pPager->syncFlags;
  47395. if( pPager->fullSync ){
  47396. pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
  47397. }
  47398. if( pgFlags & PAGER_CACHESPILL ){
  47399. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  47400. }else{
  47401. pPager->doNotSpill |= SPILLFLAG_OFF;
  47402. }
  47403. }
  47404. #endif
  47405. /*
  47406. ** The following global variable is incremented whenever the library
  47407. ** attempts to open a temporary file. This information is used for
  47408. ** testing and analysis only.
  47409. */
  47410. #ifdef SQLITE_TEST
  47411. SQLITE_API int sqlite3_opentemp_count = 0;
  47412. #endif
  47413. /*
  47414. ** Open a temporary file.
  47415. **
  47416. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  47417. ** or some other error code if we fail. The OS will automatically
  47418. ** delete the temporary file when it is closed.
  47419. **
  47420. ** The flags passed to the VFS layer xOpen() call are those specified
  47421. ** by parameter vfsFlags ORed with the following:
  47422. **
  47423. ** SQLITE_OPEN_READWRITE
  47424. ** SQLITE_OPEN_CREATE
  47425. ** SQLITE_OPEN_EXCLUSIVE
  47426. ** SQLITE_OPEN_DELETEONCLOSE
  47427. */
  47428. static int pagerOpentemp(
  47429. Pager *pPager, /* The pager object */
  47430. sqlite3_file *pFile, /* Write the file descriptor here */
  47431. int vfsFlags /* Flags passed through to the VFS */
  47432. ){
  47433. int rc; /* Return code */
  47434. #ifdef SQLITE_TEST
  47435. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  47436. #endif
  47437. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  47438. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  47439. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  47440. assert( rc!=SQLITE_OK || isOpen(pFile) );
  47441. return rc;
  47442. }
  47443. /*
  47444. ** Set the busy handler function.
  47445. **
  47446. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  47447. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  47448. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  47449. ** lock. It does *not* invoke the busy handler when upgrading from
  47450. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  47451. ** (which occurs during hot-journal rollback). Summary:
  47452. **
  47453. ** Transition | Invokes xBusyHandler
  47454. ** --------------------------------------------------------
  47455. ** NO_LOCK -> SHARED_LOCK | Yes
  47456. ** SHARED_LOCK -> RESERVED_LOCK | No
  47457. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  47458. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  47459. **
  47460. ** If the busy-handler callback returns non-zero, the lock is
  47461. ** retried. If it returns zero, then the SQLITE_BUSY error is
  47462. ** returned to the caller of the pager API function.
  47463. */
  47464. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  47465. Pager *pPager, /* Pager object */
  47466. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  47467. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  47468. ){
  47469. pPager->xBusyHandler = xBusyHandler;
  47470. pPager->pBusyHandlerArg = pBusyHandlerArg;
  47471. if( isOpen(pPager->fd) ){
  47472. void **ap = (void **)&pPager->xBusyHandler;
  47473. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  47474. assert( ap[1]==pBusyHandlerArg );
  47475. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  47476. }
  47477. }
  47478. /*
  47479. ** Change the page size used by the Pager object. The new page size
  47480. ** is passed in *pPageSize.
  47481. **
  47482. ** If the pager is in the error state when this function is called, it
  47483. ** is a no-op. The value returned is the error state error code (i.e.
  47484. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  47485. **
  47486. ** Otherwise, if all of the following are true:
  47487. **
  47488. ** * the new page size (value of *pPageSize) is valid (a power
  47489. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  47490. **
  47491. ** * there are no outstanding page references, and
  47492. **
  47493. ** * the database is either not an in-memory database or it is
  47494. ** an in-memory database that currently consists of zero pages.
  47495. **
  47496. ** then the pager object page size is set to *pPageSize.
  47497. **
  47498. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  47499. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  47500. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  47501. ** In all other cases, SQLITE_OK is returned.
  47502. **
  47503. ** If the page size is not changed, either because one of the enumerated
  47504. ** conditions above is not true, the pager was in error state when this
  47505. ** function was called, or because the memory allocation attempt failed,
  47506. ** then *pPageSize is set to the old, retained page size before returning.
  47507. */
  47508. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  47509. int rc = SQLITE_OK;
  47510. /* It is not possible to do a full assert_pager_state() here, as this
  47511. ** function may be called from within PagerOpen(), before the state
  47512. ** of the Pager object is internally consistent.
  47513. **
  47514. ** At one point this function returned an error if the pager was in
  47515. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  47516. ** there is at least one outstanding page reference, this function
  47517. ** is a no-op for that case anyhow.
  47518. */
  47519. u32 pageSize = *pPageSize;
  47520. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  47521. if( (pPager->memDb==0 || pPager->dbSize==0)
  47522. && sqlite3PcacheRefCount(pPager->pPCache)==0
  47523. && pageSize && pageSize!=(u32)pPager->pageSize
  47524. ){
  47525. char *pNew = NULL; /* New temp space */
  47526. i64 nByte = 0;
  47527. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  47528. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  47529. }
  47530. if( rc==SQLITE_OK ){
  47531. pNew = (char *)sqlite3PageMalloc(pageSize);
  47532. if( !pNew ) rc = SQLITE_NOMEM_BKPT;
  47533. }
  47534. if( rc==SQLITE_OK ){
  47535. pager_reset(pPager);
  47536. rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  47537. }
  47538. if( rc==SQLITE_OK ){
  47539. sqlite3PageFree(pPager->pTmpSpace);
  47540. pPager->pTmpSpace = pNew;
  47541. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  47542. pPager->pageSize = pageSize;
  47543. }else{
  47544. sqlite3PageFree(pNew);
  47545. }
  47546. }
  47547. *pPageSize = pPager->pageSize;
  47548. if( rc==SQLITE_OK ){
  47549. if( nReserve<0 ) nReserve = pPager->nReserve;
  47550. assert( nReserve>=0 && nReserve<1000 );
  47551. pPager->nReserve = (i16)nReserve;
  47552. pagerReportSize(pPager);
  47553. pagerFixMaplimit(pPager);
  47554. }
  47555. return rc;
  47556. }
  47557. /*
  47558. ** Return a pointer to the "temporary page" buffer held internally
  47559. ** by the pager. This is a buffer that is big enough to hold the
  47560. ** entire content of a database page. This buffer is used internally
  47561. ** during rollback and will be overwritten whenever a rollback
  47562. ** occurs. But other modules are free to use it too, as long as
  47563. ** no rollbacks are happening.
  47564. */
  47565. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  47566. return pPager->pTmpSpace;
  47567. }
  47568. /*
  47569. ** Attempt to set the maximum database page count if mxPage is positive.
  47570. ** Make no changes if mxPage is zero or negative. And never reduce the
  47571. ** maximum page count below the current size of the database.
  47572. **
  47573. ** Regardless of mxPage, return the current maximum page count.
  47574. */
  47575. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  47576. if( mxPage>0 ){
  47577. pPager->mxPgno = mxPage;
  47578. }
  47579. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  47580. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  47581. return pPager->mxPgno;
  47582. }
  47583. /*
  47584. ** The following set of routines are used to disable the simulated
  47585. ** I/O error mechanism. These routines are used to avoid simulated
  47586. ** errors in places where we do not care about errors.
  47587. **
  47588. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  47589. ** and generate no code.
  47590. */
  47591. #ifdef SQLITE_TEST
  47592. SQLITE_API extern int sqlite3_io_error_pending;
  47593. SQLITE_API extern int sqlite3_io_error_hit;
  47594. static int saved_cnt;
  47595. void disable_simulated_io_errors(void){
  47596. saved_cnt = sqlite3_io_error_pending;
  47597. sqlite3_io_error_pending = -1;
  47598. }
  47599. void enable_simulated_io_errors(void){
  47600. sqlite3_io_error_pending = saved_cnt;
  47601. }
  47602. #else
  47603. # define disable_simulated_io_errors()
  47604. # define enable_simulated_io_errors()
  47605. #endif
  47606. /*
  47607. ** Read the first N bytes from the beginning of the file into memory
  47608. ** that pDest points to.
  47609. **
  47610. ** If the pager was opened on a transient file (zFilename==""), or
  47611. ** opened on a file less than N bytes in size, the output buffer is
  47612. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  47613. ** function is used to read database headers, and a new transient or
  47614. ** zero sized database has a header than consists entirely of zeroes.
  47615. **
  47616. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  47617. ** the error code is returned to the caller and the contents of the
  47618. ** output buffer undefined.
  47619. */
  47620. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  47621. int rc = SQLITE_OK;
  47622. memset(pDest, 0, N);
  47623. assert( isOpen(pPager->fd) || pPager->tempFile );
  47624. /* This routine is only called by btree immediately after creating
  47625. ** the Pager object. There has not been an opportunity to transition
  47626. ** to WAL mode yet.
  47627. */
  47628. assert( !pagerUseWal(pPager) );
  47629. if( isOpen(pPager->fd) ){
  47630. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  47631. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  47632. if( rc==SQLITE_IOERR_SHORT_READ ){
  47633. rc = SQLITE_OK;
  47634. }
  47635. }
  47636. return rc;
  47637. }
  47638. /*
  47639. ** This function may only be called when a read-transaction is open on
  47640. ** the pager. It returns the total number of pages in the database.
  47641. **
  47642. ** However, if the file is between 1 and <page-size> bytes in size, then
  47643. ** this is considered a 1 page file.
  47644. */
  47645. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  47646. assert( pPager->eState>=PAGER_READER );
  47647. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  47648. *pnPage = (int)pPager->dbSize;
  47649. }
  47650. /*
  47651. ** Try to obtain a lock of type locktype on the database file. If
  47652. ** a similar or greater lock is already held, this function is a no-op
  47653. ** (returning SQLITE_OK immediately).
  47654. **
  47655. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  47656. ** the busy callback if the lock is currently not available. Repeat
  47657. ** until the busy callback returns false or until the attempt to
  47658. ** obtain the lock succeeds.
  47659. **
  47660. ** Return SQLITE_OK on success and an error code if we cannot obtain
  47661. ** the lock. If the lock is obtained successfully, set the Pager.state
  47662. ** variable to locktype before returning.
  47663. */
  47664. static int pager_wait_on_lock(Pager *pPager, int locktype){
  47665. int rc; /* Return code */
  47666. /* Check that this is either a no-op (because the requested lock is
  47667. ** already held), or one of the transitions that the busy-handler
  47668. ** may be invoked during, according to the comment above
  47669. ** sqlite3PagerSetBusyhandler().
  47670. */
  47671. assert( (pPager->eLock>=locktype)
  47672. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  47673. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  47674. );
  47675. do {
  47676. rc = pagerLockDb(pPager, locktype);
  47677. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  47678. return rc;
  47679. }
  47680. /*
  47681. ** Function assertTruncateConstraint(pPager) checks that one of the
  47682. ** following is true for all dirty pages currently in the page-cache:
  47683. **
  47684. ** a) The page number is less than or equal to the size of the
  47685. ** current database image, in pages, OR
  47686. **
  47687. ** b) if the page content were written at this time, it would not
  47688. ** be necessary to write the current content out to the sub-journal
  47689. ** (as determined by function subjRequiresPage()).
  47690. **
  47691. ** If the condition asserted by this function were not true, and the
  47692. ** dirty page were to be discarded from the cache via the pagerStress()
  47693. ** routine, pagerStress() would not write the current page content to
  47694. ** the database file. If a savepoint transaction were rolled back after
  47695. ** this happened, the correct behavior would be to restore the current
  47696. ** content of the page. However, since this content is not present in either
  47697. ** the database file or the portion of the rollback journal and
  47698. ** sub-journal rolled back the content could not be restored and the
  47699. ** database image would become corrupt. It is therefore fortunate that
  47700. ** this circumstance cannot arise.
  47701. */
  47702. #if defined(SQLITE_DEBUG)
  47703. static void assertTruncateConstraintCb(PgHdr *pPg){
  47704. assert( pPg->flags&PGHDR_DIRTY );
  47705. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  47706. }
  47707. static void assertTruncateConstraint(Pager *pPager){
  47708. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  47709. }
  47710. #else
  47711. # define assertTruncateConstraint(pPager)
  47712. #endif
  47713. /*
  47714. ** Truncate the in-memory database file image to nPage pages. This
  47715. ** function does not actually modify the database file on disk. It
  47716. ** just sets the internal state of the pager object so that the
  47717. ** truncation will be done when the current transaction is committed.
  47718. **
  47719. ** This function is only called right before committing a transaction.
  47720. ** Once this function has been called, the transaction must either be
  47721. ** rolled back or committed. It is not safe to call this function and
  47722. ** then continue writing to the database.
  47723. */
  47724. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  47725. assert( pPager->dbSize>=nPage );
  47726. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  47727. pPager->dbSize = nPage;
  47728. /* At one point the code here called assertTruncateConstraint() to
  47729. ** ensure that all pages being truncated away by this operation are,
  47730. ** if one or more savepoints are open, present in the savepoint
  47731. ** journal so that they can be restored if the savepoint is rolled
  47732. ** back. This is no longer necessary as this function is now only
  47733. ** called right before committing a transaction. So although the
  47734. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  47735. ** they cannot be rolled back. So the assertTruncateConstraint() call
  47736. ** is no longer correct. */
  47737. }
  47738. /*
  47739. ** This function is called before attempting a hot-journal rollback. It
  47740. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  47741. ** size of the journal file so that the pager_playback() routine knows
  47742. ** that the entire journal file has been synced.
  47743. **
  47744. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  47745. ** that if a power-failure occurs during the rollback, the process that
  47746. ** attempts rollback following system recovery sees the same journal
  47747. ** content as this process.
  47748. **
  47749. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  47750. ** an SQLite error code.
  47751. */
  47752. static int pagerSyncHotJournal(Pager *pPager){
  47753. int rc = SQLITE_OK;
  47754. if( !pPager->noSync ){
  47755. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  47756. }
  47757. if( rc==SQLITE_OK ){
  47758. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  47759. }
  47760. return rc;
  47761. }
  47762. #if SQLITE_MAX_MMAP_SIZE>0
  47763. /*
  47764. ** Obtain a reference to a memory mapped page object for page number pgno.
  47765. ** The new object will use the pointer pData, obtained from xFetch().
  47766. ** If successful, set *ppPage to point to the new page reference
  47767. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  47768. ** *ppPage to zero.
  47769. **
  47770. ** Page references obtained by calling this function should be released
  47771. ** by calling pagerReleaseMapPage().
  47772. */
  47773. static int pagerAcquireMapPage(
  47774. Pager *pPager, /* Pager object */
  47775. Pgno pgno, /* Page number */
  47776. void *pData, /* xFetch()'d data for this page */
  47777. PgHdr **ppPage /* OUT: Acquired page object */
  47778. ){
  47779. PgHdr *p; /* Memory mapped page to return */
  47780. if( pPager->pMmapFreelist ){
  47781. *ppPage = p = pPager->pMmapFreelist;
  47782. pPager->pMmapFreelist = p->pDirty;
  47783. p->pDirty = 0;
  47784. assert( pPager->nExtra>=8 );
  47785. memset(p->pExtra, 0, 8);
  47786. }else{
  47787. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  47788. if( p==0 ){
  47789. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  47790. return SQLITE_NOMEM_BKPT;
  47791. }
  47792. p->pExtra = (void *)&p[1];
  47793. p->flags = PGHDR_MMAP;
  47794. p->nRef = 1;
  47795. p->pPager = pPager;
  47796. }
  47797. assert( p->pExtra==(void *)&p[1] );
  47798. assert( p->pPage==0 );
  47799. assert( p->flags==PGHDR_MMAP );
  47800. assert( p->pPager==pPager );
  47801. assert( p->nRef==1 );
  47802. p->pgno = pgno;
  47803. p->pData = pData;
  47804. pPager->nMmapOut++;
  47805. return SQLITE_OK;
  47806. }
  47807. #endif
  47808. /*
  47809. ** Release a reference to page pPg. pPg must have been returned by an
  47810. ** earlier call to pagerAcquireMapPage().
  47811. */
  47812. static void pagerReleaseMapPage(PgHdr *pPg){
  47813. Pager *pPager = pPg->pPager;
  47814. pPager->nMmapOut--;
  47815. pPg->pDirty = pPager->pMmapFreelist;
  47816. pPager->pMmapFreelist = pPg;
  47817. assert( pPager->fd->pMethods->iVersion>=3 );
  47818. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  47819. }
  47820. /*
  47821. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  47822. */
  47823. static void pagerFreeMapHdrs(Pager *pPager){
  47824. PgHdr *p;
  47825. PgHdr *pNext;
  47826. for(p=pPager->pMmapFreelist; p; p=pNext){
  47827. pNext = p->pDirty;
  47828. sqlite3_free(p);
  47829. }
  47830. }
  47831. /*
  47832. ** Shutdown the page cache. Free all memory and close all files.
  47833. **
  47834. ** If a transaction was in progress when this routine is called, that
  47835. ** transaction is rolled back. All outstanding pages are invalidated
  47836. ** and their memory is freed. Any attempt to use a page associated
  47837. ** with this page cache after this function returns will likely
  47838. ** result in a coredump.
  47839. **
  47840. ** This function always succeeds. If a transaction is active an attempt
  47841. ** is made to roll it back. If an error occurs during the rollback
  47842. ** a hot journal may be left in the filesystem but no error is returned
  47843. ** to the caller.
  47844. */
  47845. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
  47846. u8 *pTmp = (u8 *)pPager->pTmpSpace;
  47847. assert( db || pagerUseWal(pPager)==0 );
  47848. assert( assert_pager_state(pPager) );
  47849. disable_simulated_io_errors();
  47850. sqlite3BeginBenignMalloc();
  47851. pagerFreeMapHdrs(pPager);
  47852. /* pPager->errCode = 0; */
  47853. pPager->exclusiveMode = 0;
  47854. #ifndef SQLITE_OMIT_WAL
  47855. assert( db || pPager->pWal==0 );
  47856. sqlite3WalClose(pPager->pWal, db, pPager->ckptSyncFlags, pPager->pageSize,
  47857. (db && (db->flags & SQLITE_NoCkptOnClose) ? 0 : pTmp)
  47858. );
  47859. pPager->pWal = 0;
  47860. #endif
  47861. pager_reset(pPager);
  47862. if( MEMDB ){
  47863. pager_unlock(pPager);
  47864. }else{
  47865. /* If it is open, sync the journal file before calling UnlockAndRollback.
  47866. ** If this is not done, then an unsynced portion of the open journal
  47867. ** file may be played back into the database. If a power failure occurs
  47868. ** while this is happening, the database could become corrupt.
  47869. **
  47870. ** If an error occurs while trying to sync the journal, shift the pager
  47871. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  47872. ** database and close the journal file without attempting to roll it
  47873. ** back or finalize it. The next database user will have to do hot-journal
  47874. ** rollback before accessing the database file.
  47875. */
  47876. if( isOpen(pPager->jfd) ){
  47877. pager_error(pPager, pagerSyncHotJournal(pPager));
  47878. }
  47879. pagerUnlockAndRollback(pPager);
  47880. }
  47881. sqlite3EndBenignMalloc();
  47882. enable_simulated_io_errors();
  47883. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  47884. IOTRACE(("CLOSE %p\n", pPager))
  47885. sqlite3OsClose(pPager->jfd);
  47886. sqlite3OsClose(pPager->fd);
  47887. sqlite3PageFree(pTmp);
  47888. sqlite3PcacheClose(pPager->pPCache);
  47889. #ifdef SQLITE_HAS_CODEC
  47890. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  47891. #endif
  47892. assert( !pPager->aSavepoint && !pPager->pInJournal );
  47893. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  47894. sqlite3_free(pPager);
  47895. return SQLITE_OK;
  47896. }
  47897. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  47898. /*
  47899. ** Return the page number for page pPg.
  47900. */
  47901. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  47902. return pPg->pgno;
  47903. }
  47904. #endif
  47905. /*
  47906. ** Increment the reference count for page pPg.
  47907. */
  47908. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  47909. sqlite3PcacheRef(pPg);
  47910. }
  47911. /*
  47912. ** Sync the journal. In other words, make sure all the pages that have
  47913. ** been written to the journal have actually reached the surface of the
  47914. ** disk and can be restored in the event of a hot-journal rollback.
  47915. **
  47916. ** If the Pager.noSync flag is set, then this function is a no-op.
  47917. ** Otherwise, the actions required depend on the journal-mode and the
  47918. ** device characteristics of the file-system, as follows:
  47919. **
  47920. ** * If the journal file is an in-memory journal file, no action need
  47921. ** be taken.
  47922. **
  47923. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  47924. ** then the nRec field of the most recently written journal header
  47925. ** is updated to contain the number of journal records that have
  47926. ** been written following it. If the pager is operating in full-sync
  47927. ** mode, then the journal file is synced before this field is updated.
  47928. **
  47929. ** * If the device does not support the SEQUENTIAL property, then
  47930. ** journal file is synced.
  47931. **
  47932. ** Or, in pseudo-code:
  47933. **
  47934. ** if( NOT <in-memory journal> ){
  47935. ** if( NOT SAFE_APPEND ){
  47936. ** if( <full-sync mode> ) xSync(<journal file>);
  47937. ** <update nRec field>
  47938. ** }
  47939. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  47940. ** }
  47941. **
  47942. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  47943. ** page currently held in memory before returning SQLITE_OK. If an IO
  47944. ** error is encountered, then the IO error code is returned to the caller.
  47945. */
  47946. static int syncJournal(Pager *pPager, int newHdr){
  47947. int rc; /* Return code */
  47948. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  47949. || pPager->eState==PAGER_WRITER_DBMOD
  47950. );
  47951. assert( assert_pager_state(pPager) );
  47952. assert( !pagerUseWal(pPager) );
  47953. rc = sqlite3PagerExclusiveLock(pPager);
  47954. if( rc!=SQLITE_OK ) return rc;
  47955. if( !pPager->noSync ){
  47956. assert( !pPager->tempFile );
  47957. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  47958. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  47959. assert( isOpen(pPager->jfd) );
  47960. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  47961. /* This block deals with an obscure problem. If the last connection
  47962. ** that wrote to this database was operating in persistent-journal
  47963. ** mode, then the journal file may at this point actually be larger
  47964. ** than Pager.journalOff bytes. If the next thing in the journal
  47965. ** file happens to be a journal-header (written as part of the
  47966. ** previous connection's transaction), and a crash or power-failure
  47967. ** occurs after nRec is updated but before this connection writes
  47968. ** anything else to the journal file (or commits/rolls back its
  47969. ** transaction), then SQLite may become confused when doing the
  47970. ** hot-journal rollback following recovery. It may roll back all
  47971. ** of this connections data, then proceed to rolling back the old,
  47972. ** out-of-date data that follows it. Database corruption.
  47973. **
  47974. ** To work around this, if the journal file does appear to contain
  47975. ** a valid header following Pager.journalOff, then write a 0x00
  47976. ** byte to the start of it to prevent it from being recognized.
  47977. **
  47978. ** Variable iNextHdrOffset is set to the offset at which this
  47979. ** problematic header will occur, if it exists. aMagic is used
  47980. ** as a temporary buffer to inspect the first couple of bytes of
  47981. ** the potential journal header.
  47982. */
  47983. i64 iNextHdrOffset;
  47984. u8 aMagic[8];
  47985. u8 zHeader[sizeof(aJournalMagic)+4];
  47986. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  47987. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  47988. iNextHdrOffset = journalHdrOffset(pPager);
  47989. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  47990. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  47991. static const u8 zerobyte = 0;
  47992. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  47993. }
  47994. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  47995. return rc;
  47996. }
  47997. /* Write the nRec value into the journal file header. If in
  47998. ** full-synchronous mode, sync the journal first. This ensures that
  47999. ** all data has really hit the disk before nRec is updated to mark
  48000. ** it as a candidate for rollback.
  48001. **
  48002. ** This is not required if the persistent media supports the
  48003. ** SAFE_APPEND property. Because in this case it is not possible
  48004. ** for garbage data to be appended to the file, the nRec field
  48005. ** is populated with 0xFFFFFFFF when the journal header is written
  48006. ** and never needs to be updated.
  48007. */
  48008. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  48009. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  48010. IOTRACE(("JSYNC %p\n", pPager))
  48011. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  48012. if( rc!=SQLITE_OK ) return rc;
  48013. }
  48014. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  48015. rc = sqlite3OsWrite(
  48016. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  48017. );
  48018. if( rc!=SQLITE_OK ) return rc;
  48019. }
  48020. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  48021. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  48022. IOTRACE(("JSYNC %p\n", pPager))
  48023. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  48024. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  48025. );
  48026. if( rc!=SQLITE_OK ) return rc;
  48027. }
  48028. pPager->journalHdr = pPager->journalOff;
  48029. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  48030. pPager->nRec = 0;
  48031. rc = writeJournalHdr(pPager);
  48032. if( rc!=SQLITE_OK ) return rc;
  48033. }
  48034. }else{
  48035. pPager->journalHdr = pPager->journalOff;
  48036. }
  48037. }
  48038. /* Unless the pager is in noSync mode, the journal file was just
  48039. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  48040. ** all pages.
  48041. */
  48042. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  48043. pPager->eState = PAGER_WRITER_DBMOD;
  48044. assert( assert_pager_state(pPager) );
  48045. return SQLITE_OK;
  48046. }
  48047. /*
  48048. ** The argument is the first in a linked list of dirty pages connected
  48049. ** by the PgHdr.pDirty pointer. This function writes each one of the
  48050. ** in-memory pages in the list to the database file. The argument may
  48051. ** be NULL, representing an empty list. In this case this function is
  48052. ** a no-op.
  48053. **
  48054. ** The pager must hold at least a RESERVED lock when this function
  48055. ** is called. Before writing anything to the database file, this lock
  48056. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  48057. ** SQLITE_BUSY is returned and no data is written to the database file.
  48058. **
  48059. ** If the pager is a temp-file pager and the actual file-system file
  48060. ** is not yet open, it is created and opened before any data is
  48061. ** written out.
  48062. **
  48063. ** Once the lock has been upgraded and, if necessary, the file opened,
  48064. ** the pages are written out to the database file in list order. Writing
  48065. ** a page is skipped if it meets either of the following criteria:
  48066. **
  48067. ** * The page number is greater than Pager.dbSize, or
  48068. ** * The PGHDR_DONT_WRITE flag is set on the page.
  48069. **
  48070. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  48071. ** is updated accordingly. If page 1 is written out, then the value cached
  48072. ** in Pager.dbFileVers[] is updated to match the new value stored in
  48073. ** the database file.
  48074. **
  48075. ** If everything is successful, SQLITE_OK is returned. If an IO error
  48076. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  48077. ** be obtained, SQLITE_BUSY is returned.
  48078. */
  48079. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  48080. int rc = SQLITE_OK; /* Return code */
  48081. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  48082. assert( !pagerUseWal(pPager) );
  48083. assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
  48084. assert( pPager->eLock==EXCLUSIVE_LOCK );
  48085. assert( isOpen(pPager->fd) || pList->pDirty==0 );
  48086. /* If the file is a temp-file has not yet been opened, open it now. It
  48087. ** is not possible for rc to be other than SQLITE_OK if this branch
  48088. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  48089. */
  48090. if( !isOpen(pPager->fd) ){
  48091. assert( pPager->tempFile && rc==SQLITE_OK );
  48092. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  48093. }
  48094. /* Before the first write, give the VFS a hint of what the final
  48095. ** file size will be.
  48096. */
  48097. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  48098. if( rc==SQLITE_OK
  48099. && pPager->dbHintSize<pPager->dbSize
  48100. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  48101. ){
  48102. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  48103. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  48104. pPager->dbHintSize = pPager->dbSize;
  48105. }
  48106. while( rc==SQLITE_OK && pList ){
  48107. Pgno pgno = pList->pgno;
  48108. /* If there are dirty pages in the page cache with page numbers greater
  48109. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  48110. ** make the file smaller (presumably by auto-vacuum code). Do not write
  48111. ** any such pages to the file.
  48112. **
  48113. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  48114. ** set (set by sqlite3PagerDontWrite()).
  48115. */
  48116. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  48117. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  48118. char *pData; /* Data to write */
  48119. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  48120. if( pList->pgno==1 ) pager_write_changecounter(pList);
  48121. /* Encode the database */
  48122. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
  48123. /* Write out the page data. */
  48124. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  48125. /* If page 1 was just written, update Pager.dbFileVers to match
  48126. ** the value now stored in the database file. If writing this
  48127. ** page caused the database file to grow, update dbFileSize.
  48128. */
  48129. if( pgno==1 ){
  48130. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  48131. }
  48132. if( pgno>pPager->dbFileSize ){
  48133. pPager->dbFileSize = pgno;
  48134. }
  48135. pPager->aStat[PAGER_STAT_WRITE]++;
  48136. /* Update any backup objects copying the contents of this pager. */
  48137. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  48138. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  48139. PAGERID(pPager), pgno, pager_pagehash(pList)));
  48140. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  48141. PAGER_INCR(sqlite3_pager_writedb_count);
  48142. }else{
  48143. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  48144. }
  48145. pager_set_pagehash(pList);
  48146. pList = pList->pDirty;
  48147. }
  48148. return rc;
  48149. }
  48150. /*
  48151. ** Ensure that the sub-journal file is open. If it is already open, this
  48152. ** function is a no-op.
  48153. **
  48154. ** SQLITE_OK is returned if everything goes according to plan. An
  48155. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  48156. ** fails.
  48157. */
  48158. static int openSubJournal(Pager *pPager){
  48159. int rc = SQLITE_OK;
  48160. if( !isOpen(pPager->sjfd) ){
  48161. const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
  48162. | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
  48163. | SQLITE_OPEN_DELETEONCLOSE;
  48164. int nStmtSpill = sqlite3Config.nStmtSpill;
  48165. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  48166. nStmtSpill = -1;
  48167. }
  48168. rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
  48169. }
  48170. return rc;
  48171. }
  48172. /*
  48173. ** Append a record of the current state of page pPg to the sub-journal.
  48174. **
  48175. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  48176. ** for all open savepoints before returning.
  48177. **
  48178. ** This function returns SQLITE_OK if everything is successful, an IO
  48179. ** error code if the attempt to write to the sub-journal fails, or
  48180. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  48181. ** bitvec.
  48182. */
  48183. static int subjournalPage(PgHdr *pPg){
  48184. int rc = SQLITE_OK;
  48185. Pager *pPager = pPg->pPager;
  48186. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  48187. /* Open the sub-journal, if it has not already been opened */
  48188. assert( pPager->useJournal );
  48189. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  48190. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  48191. assert( pagerUseWal(pPager)
  48192. || pageInJournal(pPager, pPg)
  48193. || pPg->pgno>pPager->dbOrigSize
  48194. );
  48195. rc = openSubJournal(pPager);
  48196. /* If the sub-journal was opened successfully (or was already open),
  48197. ** write the journal record into the file. */
  48198. if( rc==SQLITE_OK ){
  48199. void *pData = pPg->pData;
  48200. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  48201. char *pData2;
  48202. #if SQLITE_HAS_CODEC
  48203. if( !pPager->subjInMemory ){
  48204. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
  48205. }else
  48206. #endif
  48207. pData2 = pData;
  48208. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  48209. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  48210. if( rc==SQLITE_OK ){
  48211. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  48212. }
  48213. }
  48214. }
  48215. if( rc==SQLITE_OK ){
  48216. pPager->nSubRec++;
  48217. assert( pPager->nSavepoint>0 );
  48218. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  48219. }
  48220. return rc;
  48221. }
  48222. static int subjournalPageIfRequired(PgHdr *pPg){
  48223. if( subjRequiresPage(pPg) ){
  48224. return subjournalPage(pPg);
  48225. }else{
  48226. return SQLITE_OK;
  48227. }
  48228. }
  48229. /*
  48230. ** This function is called by the pcache layer when it has reached some
  48231. ** soft memory limit. The first argument is a pointer to a Pager object
  48232. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  48233. ** database). The second argument is a reference to a page that is
  48234. ** currently dirty but has no outstanding references. The page
  48235. ** is always associated with the Pager object passed as the first
  48236. ** argument.
  48237. **
  48238. ** The job of this function is to make pPg clean by writing its contents
  48239. ** out to the database file, if possible. This may involve syncing the
  48240. ** journal file.
  48241. **
  48242. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  48243. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  48244. ** page clean, the IO error code is returned. If the page cannot be
  48245. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  48246. ** is returned by sqlite3PcacheMakeClean() is not called.
  48247. */
  48248. static int pagerStress(void *p, PgHdr *pPg){
  48249. Pager *pPager = (Pager *)p;
  48250. int rc = SQLITE_OK;
  48251. assert( pPg->pPager==pPager );
  48252. assert( pPg->flags&PGHDR_DIRTY );
  48253. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  48254. ** journal (and adding a new header) is not allowed. This occurs
  48255. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  48256. ** pages belonging to the same sector.
  48257. **
  48258. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  48259. ** regardless of whether or not a sync is required. This is set during
  48260. ** a rollback or by user request, respectively.
  48261. **
  48262. ** Spilling is also prohibited when in an error state since that could
  48263. ** lead to database corruption. In the current implementation it
  48264. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
  48265. ** while in the error state, hence it is impossible for this routine to
  48266. ** be called in the error state. Nevertheless, we include a NEVER()
  48267. ** test for the error state as a safeguard against future changes.
  48268. */
  48269. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  48270. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  48271. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  48272. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  48273. if( pPager->doNotSpill
  48274. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  48275. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  48276. ){
  48277. return SQLITE_OK;
  48278. }
  48279. pPg->pDirty = 0;
  48280. if( pagerUseWal(pPager) ){
  48281. /* Write a single frame for this page to the log. */
  48282. rc = subjournalPageIfRequired(pPg);
  48283. if( rc==SQLITE_OK ){
  48284. rc = pagerWalFrames(pPager, pPg, 0, 0);
  48285. }
  48286. }else{
  48287. /* Sync the journal file if required. */
  48288. if( pPg->flags&PGHDR_NEED_SYNC
  48289. || pPager->eState==PAGER_WRITER_CACHEMOD
  48290. ){
  48291. rc = syncJournal(pPager, 1);
  48292. }
  48293. /* Write the contents of the page out to the database file. */
  48294. if( rc==SQLITE_OK ){
  48295. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  48296. rc = pager_write_pagelist(pPager, pPg);
  48297. }
  48298. }
  48299. /* Mark the page as clean. */
  48300. if( rc==SQLITE_OK ){
  48301. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  48302. sqlite3PcacheMakeClean(pPg);
  48303. }
  48304. return pager_error(pPager, rc);
  48305. }
  48306. /*
  48307. ** Flush all unreferenced dirty pages to disk.
  48308. */
  48309. SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
  48310. int rc = pPager->errCode;
  48311. if( !MEMDB ){
  48312. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  48313. assert( assert_pager_state(pPager) );
  48314. while( rc==SQLITE_OK && pList ){
  48315. PgHdr *pNext = pList->pDirty;
  48316. if( pList->nRef==0 ){
  48317. rc = pagerStress((void*)pPager, pList);
  48318. }
  48319. pList = pNext;
  48320. }
  48321. }
  48322. return rc;
  48323. }
  48324. /*
  48325. ** Allocate and initialize a new Pager object and put a pointer to it
  48326. ** in *ppPager. The pager should eventually be freed by passing it
  48327. ** to sqlite3PagerClose().
  48328. **
  48329. ** The zFilename argument is the path to the database file to open.
  48330. ** If zFilename is NULL then a randomly-named temporary file is created
  48331. ** and used as the file to be cached. Temporary files are be deleted
  48332. ** automatically when they are closed. If zFilename is ":memory:" then
  48333. ** all information is held in cache. It is never written to disk.
  48334. ** This can be used to implement an in-memory database.
  48335. **
  48336. ** The nExtra parameter specifies the number of bytes of space allocated
  48337. ** along with each page reference. This space is available to the user
  48338. ** via the sqlite3PagerGetExtra() API. When a new page is allocated, the
  48339. ** first 8 bytes of this space are zeroed but the remainder is uninitialized.
  48340. ** (The extra space is used by btree as the MemPage object.)
  48341. **
  48342. ** The flags argument is used to specify properties that affect the
  48343. ** operation of the pager. It should be passed some bitwise combination
  48344. ** of the PAGER_* flags.
  48345. **
  48346. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  48347. ** of the xOpen() method of the supplied VFS when opening files.
  48348. **
  48349. ** If the pager object is allocated and the specified file opened
  48350. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  48351. ** the new pager object. If an error occurs, *ppPager is set to NULL
  48352. ** and error code returned. This function may return SQLITE_NOMEM
  48353. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  48354. ** various SQLITE_IO_XXX errors.
  48355. */
  48356. SQLITE_PRIVATE int sqlite3PagerOpen(
  48357. sqlite3_vfs *pVfs, /* The virtual file system to use */
  48358. Pager **ppPager, /* OUT: Return the Pager structure here */
  48359. const char *zFilename, /* Name of the database file to open */
  48360. int nExtra, /* Extra bytes append to each in-memory page */
  48361. int flags, /* flags controlling this file */
  48362. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  48363. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  48364. ){
  48365. u8 *pPtr;
  48366. Pager *pPager = 0; /* Pager object to allocate and return */
  48367. int rc = SQLITE_OK; /* Return code */
  48368. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  48369. int memDb = 0; /* True if this is an in-memory file */
  48370. int readOnly = 0; /* True if this is a read-only file */
  48371. int journalFileSize; /* Bytes to allocate for each journal fd */
  48372. char *zPathname = 0; /* Full path to database file */
  48373. int nPathname = 0; /* Number of bytes in zPathname */
  48374. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  48375. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  48376. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  48377. const char *zUri = 0; /* URI args to copy */
  48378. int nUri = 0; /* Number of bytes of URI args at *zUri */
  48379. /* Figure out how much space is required for each journal file-handle
  48380. ** (there are two of them, the main journal and the sub-journal). */
  48381. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  48382. /* Set the output variable to NULL in case an error occurs. */
  48383. *ppPager = 0;
  48384. #ifndef SQLITE_OMIT_MEMORYDB
  48385. if( flags & PAGER_MEMORY ){
  48386. memDb = 1;
  48387. if( zFilename && zFilename[0] ){
  48388. zPathname = sqlite3DbStrDup(0, zFilename);
  48389. if( zPathname==0 ) return SQLITE_NOMEM_BKPT;
  48390. nPathname = sqlite3Strlen30(zPathname);
  48391. zFilename = 0;
  48392. }
  48393. }
  48394. #endif
  48395. /* Compute and store the full pathname in an allocated buffer pointed
  48396. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  48397. ** leave both nPathname and zPathname set to 0.
  48398. */
  48399. if( zFilename && zFilename[0] ){
  48400. const char *z;
  48401. nPathname = pVfs->mxPathname+1;
  48402. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  48403. if( zPathname==0 ){
  48404. return SQLITE_NOMEM_BKPT;
  48405. }
  48406. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  48407. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  48408. nPathname = sqlite3Strlen30(zPathname);
  48409. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  48410. while( *z ){
  48411. z += sqlite3Strlen30(z)+1;
  48412. z += sqlite3Strlen30(z)+1;
  48413. }
  48414. nUri = (int)(&z[1] - zUri);
  48415. assert( nUri>=0 );
  48416. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  48417. /* This branch is taken when the journal path required by
  48418. ** the database being opened will be more than pVfs->mxPathname
  48419. ** bytes in length. This means the database cannot be opened,
  48420. ** as it will not be possible to open the journal file or even
  48421. ** check for a hot-journal before reading.
  48422. */
  48423. rc = SQLITE_CANTOPEN_BKPT;
  48424. }
  48425. if( rc!=SQLITE_OK ){
  48426. sqlite3DbFree(0, zPathname);
  48427. return rc;
  48428. }
  48429. }
  48430. /* Allocate memory for the Pager structure, PCache object, the
  48431. ** three file descriptors, the database file name and the journal
  48432. ** file name. The layout in memory is as follows:
  48433. **
  48434. ** Pager object (sizeof(Pager) bytes)
  48435. ** PCache object (sqlite3PcacheSize() bytes)
  48436. ** Database file handle (pVfs->szOsFile bytes)
  48437. ** Sub-journal file handle (journalFileSize bytes)
  48438. ** Main journal file handle (journalFileSize bytes)
  48439. ** Database file name (nPathname+1 bytes)
  48440. ** Journal file name (nPathname+8+1 bytes)
  48441. */
  48442. pPtr = (u8 *)sqlite3MallocZero(
  48443. ROUND8(sizeof(*pPager)) + /* Pager structure */
  48444. ROUND8(pcacheSize) + /* PCache object */
  48445. ROUND8(pVfs->szOsFile) + /* The main db file */
  48446. journalFileSize * 2 + /* The two journal files */
  48447. nPathname + 1 + nUri + /* zFilename */
  48448. nPathname + 8 + 2 /* zJournal */
  48449. #ifndef SQLITE_OMIT_WAL
  48450. + nPathname + 4 + 2 /* zWal */
  48451. #endif
  48452. );
  48453. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  48454. if( !pPtr ){
  48455. sqlite3DbFree(0, zPathname);
  48456. return SQLITE_NOMEM_BKPT;
  48457. }
  48458. pPager = (Pager*)(pPtr);
  48459. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  48460. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  48461. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  48462. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  48463. pPager->zFilename = (char*)(pPtr += journalFileSize);
  48464. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  48465. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  48466. if( zPathname ){
  48467. assert( nPathname>0 );
  48468. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  48469. memcpy(pPager->zFilename, zPathname, nPathname);
  48470. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  48471. memcpy(pPager->zJournal, zPathname, nPathname);
  48472. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  48473. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  48474. #ifndef SQLITE_OMIT_WAL
  48475. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  48476. memcpy(pPager->zWal, zPathname, nPathname);
  48477. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  48478. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  48479. #endif
  48480. sqlite3DbFree(0, zPathname);
  48481. }
  48482. pPager->pVfs = pVfs;
  48483. pPager->vfsFlags = vfsFlags;
  48484. /* Open the pager file.
  48485. */
  48486. if( zFilename && zFilename[0] ){
  48487. int fout = 0; /* VFS flags returned by xOpen() */
  48488. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  48489. assert( !memDb );
  48490. readOnly = (fout&SQLITE_OPEN_READONLY);
  48491. /* If the file was successfully opened for read/write access,
  48492. ** choose a default page size in case we have to create the
  48493. ** database file. The default page size is the maximum of:
  48494. **
  48495. ** + SQLITE_DEFAULT_PAGE_SIZE,
  48496. ** + The value returned by sqlite3OsSectorSize()
  48497. ** + The largest page size that can be written atomically.
  48498. */
  48499. if( rc==SQLITE_OK ){
  48500. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  48501. if( !readOnly ){
  48502. setSectorSize(pPager);
  48503. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  48504. if( szPageDflt<pPager->sectorSize ){
  48505. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  48506. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  48507. }else{
  48508. szPageDflt = (u32)pPager->sectorSize;
  48509. }
  48510. }
  48511. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  48512. {
  48513. int ii;
  48514. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  48515. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  48516. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  48517. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  48518. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  48519. szPageDflt = ii;
  48520. }
  48521. }
  48522. }
  48523. #endif
  48524. }
  48525. pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
  48526. if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
  48527. || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
  48528. vfsFlags |= SQLITE_OPEN_READONLY;
  48529. goto act_like_temp_file;
  48530. }
  48531. }
  48532. }else{
  48533. /* If a temporary file is requested, it is not opened immediately.
  48534. ** In this case we accept the default page size and delay actually
  48535. ** opening the file until the first call to OsWrite().
  48536. **
  48537. ** This branch is also run for an in-memory database. An in-memory
  48538. ** database is the same as a temp-file that is never written out to
  48539. ** disk and uses an in-memory rollback journal.
  48540. **
  48541. ** This branch also runs for files marked as immutable.
  48542. */
  48543. act_like_temp_file:
  48544. tempFile = 1;
  48545. pPager->eState = PAGER_READER; /* Pretend we already have a lock */
  48546. pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
  48547. pPager->noLock = 1; /* Do no locking */
  48548. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  48549. }
  48550. /* The following call to PagerSetPagesize() serves to set the value of
  48551. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  48552. */
  48553. if( rc==SQLITE_OK ){
  48554. assert( pPager->memDb==0 );
  48555. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  48556. testcase( rc!=SQLITE_OK );
  48557. }
  48558. /* Initialize the PCache object. */
  48559. if( rc==SQLITE_OK ){
  48560. nExtra = ROUND8(nExtra);
  48561. assert( nExtra>=8 && nExtra<1000 );
  48562. rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  48563. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  48564. }
  48565. /* If an error occurred above, free the Pager structure and close the file.
  48566. */
  48567. if( rc!=SQLITE_OK ){
  48568. sqlite3OsClose(pPager->fd);
  48569. sqlite3PageFree(pPager->pTmpSpace);
  48570. sqlite3_free(pPager);
  48571. return rc;
  48572. }
  48573. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  48574. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  48575. pPager->useJournal = (u8)useJournal;
  48576. /* pPager->stmtOpen = 0; */
  48577. /* pPager->stmtInUse = 0; */
  48578. /* pPager->nRef = 0; */
  48579. /* pPager->stmtSize = 0; */
  48580. /* pPager->stmtJSize = 0; */
  48581. /* pPager->nPage = 0; */
  48582. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  48583. /* pPager->state = PAGER_UNLOCK; */
  48584. /* pPager->errMask = 0; */
  48585. pPager->tempFile = (u8)tempFile;
  48586. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  48587. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  48588. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  48589. pPager->exclusiveMode = (u8)tempFile;
  48590. pPager->changeCountDone = pPager->tempFile;
  48591. pPager->memDb = (u8)memDb;
  48592. pPager->readOnly = (u8)readOnly;
  48593. assert( useJournal || pPager->tempFile );
  48594. pPager->noSync = pPager->tempFile;
  48595. if( pPager->noSync ){
  48596. assert( pPager->fullSync==0 );
  48597. assert( pPager->extraSync==0 );
  48598. assert( pPager->syncFlags==0 );
  48599. assert( pPager->walSyncFlags==0 );
  48600. assert( pPager->ckptSyncFlags==0 );
  48601. }else{
  48602. pPager->fullSync = 1;
  48603. pPager->extraSync = 0;
  48604. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  48605. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
  48606. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  48607. }
  48608. /* pPager->pFirst = 0; */
  48609. /* pPager->pFirstSynced = 0; */
  48610. /* pPager->pLast = 0; */
  48611. pPager->nExtra = (u16)nExtra;
  48612. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  48613. assert( isOpen(pPager->fd) || tempFile );
  48614. setSectorSize(pPager);
  48615. if( !useJournal ){
  48616. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  48617. }else if( memDb ){
  48618. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  48619. }
  48620. /* pPager->xBusyHandler = 0; */
  48621. /* pPager->pBusyHandlerArg = 0; */
  48622. pPager->xReiniter = xReinit;
  48623. setGetterMethod(pPager);
  48624. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  48625. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  48626. *ppPager = pPager;
  48627. return SQLITE_OK;
  48628. }
  48629. /* Verify that the database file has not be deleted or renamed out from
  48630. ** under the pager. Return SQLITE_OK if the database is still were it ought
  48631. ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
  48632. ** code from sqlite3OsAccess()) if the database has gone missing.
  48633. */
  48634. static int databaseIsUnmoved(Pager *pPager){
  48635. int bHasMoved = 0;
  48636. int rc;
  48637. if( pPager->tempFile ) return SQLITE_OK;
  48638. if( pPager->dbSize==0 ) return SQLITE_OK;
  48639. assert( pPager->zFilename && pPager->zFilename[0] );
  48640. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
  48641. if( rc==SQLITE_NOTFOUND ){
  48642. /* If the HAS_MOVED file-control is unimplemented, assume that the file
  48643. ** has not been moved. That is the historical behavior of SQLite: prior to
  48644. ** version 3.8.3, it never checked */
  48645. rc = SQLITE_OK;
  48646. }else if( rc==SQLITE_OK && bHasMoved ){
  48647. rc = SQLITE_READONLY_DBMOVED;
  48648. }
  48649. return rc;
  48650. }
  48651. /*
  48652. ** This function is called after transitioning from PAGER_UNLOCK to
  48653. ** PAGER_SHARED state. It tests if there is a hot journal present in
  48654. ** the file-system for the given pager. A hot journal is one that
  48655. ** needs to be played back. According to this function, a hot-journal
  48656. ** file exists if the following criteria are met:
  48657. **
  48658. ** * The journal file exists in the file system, and
  48659. ** * No process holds a RESERVED or greater lock on the database file, and
  48660. ** * The database file itself is greater than 0 bytes in size, and
  48661. ** * The first byte of the journal file exists and is not 0x00.
  48662. **
  48663. ** If the current size of the database file is 0 but a journal file
  48664. ** exists, that is probably an old journal left over from a prior
  48665. ** database with the same name. In this case the journal file is
  48666. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  48667. ** is returned.
  48668. **
  48669. ** This routine does not check if there is a master journal filename
  48670. ** at the end of the file. If there is, and that master journal file
  48671. ** does not exist, then the journal file is not really hot. In this
  48672. ** case this routine will return a false-positive. The pager_playback()
  48673. ** routine will discover that the journal file is not really hot and
  48674. ** will not roll it back.
  48675. **
  48676. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  48677. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  48678. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  48679. ** to determine whether or not a hot-journal file exists, the IO error
  48680. ** code is returned and the value of *pExists is undefined.
  48681. */
  48682. static int hasHotJournal(Pager *pPager, int *pExists){
  48683. sqlite3_vfs * const pVfs = pPager->pVfs;
  48684. int rc = SQLITE_OK; /* Return code */
  48685. int exists = 1; /* True if a journal file is present */
  48686. int jrnlOpen = !!isOpen(pPager->jfd);
  48687. assert( pPager->useJournal );
  48688. assert( isOpen(pPager->fd) );
  48689. assert( pPager->eState==PAGER_OPEN );
  48690. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  48691. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  48692. ));
  48693. *pExists = 0;
  48694. if( !jrnlOpen ){
  48695. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  48696. }
  48697. if( rc==SQLITE_OK && exists ){
  48698. int locked = 0; /* True if some process holds a RESERVED lock */
  48699. /* Race condition here: Another process might have been holding the
  48700. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  48701. ** call above, but then delete the journal and drop the lock before
  48702. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  48703. ** is the case, this routine might think there is a hot journal when
  48704. ** in fact there is none. This results in a false-positive which will
  48705. ** be dealt with by the playback routine. Ticket #3883.
  48706. */
  48707. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  48708. if( rc==SQLITE_OK && !locked ){
  48709. Pgno nPage; /* Number of pages in database file */
  48710. assert( pPager->tempFile==0 );
  48711. rc = pagerPagecount(pPager, &nPage);
  48712. if( rc==SQLITE_OK ){
  48713. /* If the database is zero pages in size, that means that either (1) the
  48714. ** journal is a remnant from a prior database with the same name where
  48715. ** the database file but not the journal was deleted, or (2) the initial
  48716. ** transaction that populates a new database is being rolled back.
  48717. ** In either case, the journal file can be deleted. However, take care
  48718. ** not to delete the journal file if it is already open due to
  48719. ** journal_mode=PERSIST.
  48720. */
  48721. if( nPage==0 && !jrnlOpen ){
  48722. sqlite3BeginBenignMalloc();
  48723. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  48724. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  48725. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  48726. }
  48727. sqlite3EndBenignMalloc();
  48728. }else{
  48729. /* The journal file exists and no other connection has a reserved
  48730. ** or greater lock on the database file. Now check that there is
  48731. ** at least one non-zero bytes at the start of the journal file.
  48732. ** If there is, then we consider this journal to be hot. If not,
  48733. ** it can be ignored.
  48734. */
  48735. if( !jrnlOpen ){
  48736. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  48737. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  48738. }
  48739. if( rc==SQLITE_OK ){
  48740. u8 first = 0;
  48741. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  48742. if( rc==SQLITE_IOERR_SHORT_READ ){
  48743. rc = SQLITE_OK;
  48744. }
  48745. if( !jrnlOpen ){
  48746. sqlite3OsClose(pPager->jfd);
  48747. }
  48748. *pExists = (first!=0);
  48749. }else if( rc==SQLITE_CANTOPEN ){
  48750. /* If we cannot open the rollback journal file in order to see if
  48751. ** it has a zero header, that might be due to an I/O error, or
  48752. ** it might be due to the race condition described above and in
  48753. ** ticket #3883. Either way, assume that the journal is hot.
  48754. ** This might be a false positive. But if it is, then the
  48755. ** automatic journal playback and recovery mechanism will deal
  48756. ** with it under an EXCLUSIVE lock where we do not need to
  48757. ** worry so much with race conditions.
  48758. */
  48759. *pExists = 1;
  48760. rc = SQLITE_OK;
  48761. }
  48762. }
  48763. }
  48764. }
  48765. }
  48766. return rc;
  48767. }
  48768. /*
  48769. ** This function is called to obtain a shared lock on the database file.
  48770. ** It is illegal to call sqlite3PagerGet() until after this function
  48771. ** has been successfully called. If a shared-lock is already held when
  48772. ** this function is called, it is a no-op.
  48773. **
  48774. ** The following operations are also performed by this function.
  48775. **
  48776. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  48777. ** on the database file), then an attempt is made to obtain a
  48778. ** SHARED lock on the database file. Immediately after obtaining
  48779. ** the SHARED lock, the file-system is checked for a hot-journal,
  48780. ** which is played back if present. Following any hot-journal
  48781. ** rollback, the contents of the cache are validated by checking
  48782. ** the 'change-counter' field of the database file header and
  48783. ** discarded if they are found to be invalid.
  48784. **
  48785. ** 2) If the pager is running in exclusive-mode, and there are currently
  48786. ** no outstanding references to any pages, and is in the error state,
  48787. ** then an attempt is made to clear the error state by discarding
  48788. ** the contents of the page cache and rolling back any open journal
  48789. ** file.
  48790. **
  48791. ** If everything is successful, SQLITE_OK is returned. If an IO error
  48792. ** occurs while locking the database, checking for a hot-journal file or
  48793. ** rolling back a journal file, the IO error code is returned.
  48794. */
  48795. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  48796. int rc = SQLITE_OK; /* Return code */
  48797. /* This routine is only called from b-tree and only when there are no
  48798. ** outstanding pages. This implies that the pager state should either
  48799. ** be OPEN or READER. READER is only possible if the pager is or was in
  48800. ** exclusive access mode. */
  48801. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  48802. assert( assert_pager_state(pPager) );
  48803. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  48804. assert( pPager->errCode==SQLITE_OK );
  48805. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  48806. int bHotJournal = 1; /* True if there exists a hot journal-file */
  48807. assert( !MEMDB );
  48808. assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
  48809. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  48810. if( rc!=SQLITE_OK ){
  48811. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  48812. goto failed;
  48813. }
  48814. /* If a journal file exists, and there is no RESERVED lock on the
  48815. ** database file, then it either needs to be played back or deleted.
  48816. */
  48817. if( pPager->eLock<=SHARED_LOCK ){
  48818. rc = hasHotJournal(pPager, &bHotJournal);
  48819. }
  48820. if( rc!=SQLITE_OK ){
  48821. goto failed;
  48822. }
  48823. if( bHotJournal ){
  48824. if( pPager->readOnly ){
  48825. rc = SQLITE_READONLY_ROLLBACK;
  48826. goto failed;
  48827. }
  48828. /* Get an EXCLUSIVE lock on the database file. At this point it is
  48829. ** important that a RESERVED lock is not obtained on the way to the
  48830. ** EXCLUSIVE lock. If it were, another process might open the
  48831. ** database file, detect the RESERVED lock, and conclude that the
  48832. ** database is safe to read while this process is still rolling the
  48833. ** hot-journal back.
  48834. **
  48835. ** Because the intermediate RESERVED lock is not requested, any
  48836. ** other process attempting to access the database file will get to
  48837. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  48838. ** on the database file.
  48839. **
  48840. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  48841. ** downgraded to SHARED_LOCK before this function returns.
  48842. */
  48843. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  48844. if( rc!=SQLITE_OK ){
  48845. goto failed;
  48846. }
  48847. /* If it is not already open and the file exists on disk, open the
  48848. ** journal for read/write access. Write access is required because
  48849. ** in exclusive-access mode the file descriptor will be kept open
  48850. ** and possibly used for a transaction later on. Also, write-access
  48851. ** is usually required to finalize the journal in journal_mode=persist
  48852. ** mode (and also for journal_mode=truncate on some systems).
  48853. **
  48854. ** If the journal does not exist, it usually means that some
  48855. ** other connection managed to get in and roll it back before
  48856. ** this connection obtained the exclusive lock above. Or, it
  48857. ** may mean that the pager was in the error-state when this
  48858. ** function was called and the journal file does not exist.
  48859. */
  48860. if( !isOpen(pPager->jfd) ){
  48861. sqlite3_vfs * const pVfs = pPager->pVfs;
  48862. int bExists; /* True if journal file exists */
  48863. rc = sqlite3OsAccess(
  48864. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  48865. if( rc==SQLITE_OK && bExists ){
  48866. int fout = 0;
  48867. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  48868. assert( !pPager->tempFile );
  48869. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  48870. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  48871. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  48872. rc = SQLITE_CANTOPEN_BKPT;
  48873. sqlite3OsClose(pPager->jfd);
  48874. }
  48875. }
  48876. }
  48877. /* Playback and delete the journal. Drop the database write
  48878. ** lock and reacquire the read lock. Purge the cache before
  48879. ** playing back the hot-journal so that we don't end up with
  48880. ** an inconsistent cache. Sync the hot journal before playing
  48881. ** it back since the process that crashed and left the hot journal
  48882. ** probably did not sync it and we are required to always sync
  48883. ** the journal before playing it back.
  48884. */
  48885. if( isOpen(pPager->jfd) ){
  48886. assert( rc==SQLITE_OK );
  48887. rc = pagerSyncHotJournal(pPager);
  48888. if( rc==SQLITE_OK ){
  48889. rc = pager_playback(pPager, !pPager->tempFile);
  48890. pPager->eState = PAGER_OPEN;
  48891. }
  48892. }else if( !pPager->exclusiveMode ){
  48893. pagerUnlockDb(pPager, SHARED_LOCK);
  48894. }
  48895. if( rc!=SQLITE_OK ){
  48896. /* This branch is taken if an error occurs while trying to open
  48897. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  48898. ** pager_unlock() routine will be called before returning to unlock
  48899. ** the file. If the unlock attempt fails, then Pager.eLock must be
  48900. ** set to UNKNOWN_LOCK (see the comment above the #define for
  48901. ** UNKNOWN_LOCK above for an explanation).
  48902. **
  48903. ** In order to get pager_unlock() to do this, set Pager.eState to
  48904. ** PAGER_ERROR now. This is not actually counted as a transition
  48905. ** to ERROR state in the state diagram at the top of this file,
  48906. ** since we know that the same call to pager_unlock() will very
  48907. ** shortly transition the pager object to the OPEN state. Calling
  48908. ** assert_pager_state() would fail now, as it should not be possible
  48909. ** to be in ERROR state when there are zero outstanding page
  48910. ** references.
  48911. */
  48912. pager_error(pPager, rc);
  48913. goto failed;
  48914. }
  48915. assert( pPager->eState==PAGER_OPEN );
  48916. assert( (pPager->eLock==SHARED_LOCK)
  48917. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  48918. );
  48919. }
  48920. if( !pPager->tempFile && pPager->hasHeldSharedLock ){
  48921. /* The shared-lock has just been acquired then check to
  48922. ** see if the database has been modified. If the database has changed,
  48923. ** flush the cache. The hasHeldSharedLock flag prevents this from
  48924. ** occurring on the very first access to a file, in order to save a
  48925. ** single unnecessary sqlite3OsRead() call at the start-up.
  48926. **
  48927. ** Database changes are detected by looking at 15 bytes beginning
  48928. ** at offset 24 into the file. The first 4 of these 16 bytes are
  48929. ** a 32-bit counter that is incremented with each change. The
  48930. ** other bytes change randomly with each file change when
  48931. ** a codec is in use.
  48932. **
  48933. ** There is a vanishingly small chance that a change will not be
  48934. ** detected. The chance of an undetected change is so small that
  48935. ** it can be neglected.
  48936. */
  48937. Pgno nPage = 0;
  48938. char dbFileVers[sizeof(pPager->dbFileVers)];
  48939. rc = pagerPagecount(pPager, &nPage);
  48940. if( rc ) goto failed;
  48941. if( nPage>0 ){
  48942. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  48943. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  48944. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  48945. goto failed;
  48946. }
  48947. }else{
  48948. memset(dbFileVers, 0, sizeof(dbFileVers));
  48949. }
  48950. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  48951. pager_reset(pPager);
  48952. /* Unmap the database file. It is possible that external processes
  48953. ** may have truncated the database file and then extended it back
  48954. ** to its original size while this process was not holding a lock.
  48955. ** In this case there may exist a Pager.pMap mapping that appears
  48956. ** to be the right size but is not actually valid. Avoid this
  48957. ** possibility by unmapping the db here. */
  48958. if( USEFETCH(pPager) ){
  48959. sqlite3OsUnfetch(pPager->fd, 0, 0);
  48960. }
  48961. }
  48962. }
  48963. /* If there is a WAL file in the file-system, open this database in WAL
  48964. ** mode. Otherwise, the following function call is a no-op.
  48965. */
  48966. rc = pagerOpenWalIfPresent(pPager);
  48967. #ifndef SQLITE_OMIT_WAL
  48968. assert( pPager->pWal==0 || rc==SQLITE_OK );
  48969. #endif
  48970. }
  48971. if( pagerUseWal(pPager) ){
  48972. assert( rc==SQLITE_OK );
  48973. rc = pagerBeginReadTransaction(pPager);
  48974. }
  48975. if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  48976. rc = pagerPagecount(pPager, &pPager->dbSize);
  48977. }
  48978. failed:
  48979. if( rc!=SQLITE_OK ){
  48980. assert( !MEMDB );
  48981. pager_unlock(pPager);
  48982. assert( pPager->eState==PAGER_OPEN );
  48983. }else{
  48984. pPager->eState = PAGER_READER;
  48985. pPager->hasHeldSharedLock = 1;
  48986. }
  48987. return rc;
  48988. }
  48989. /*
  48990. ** If the reference count has reached zero, rollback any active
  48991. ** transaction and unlock the pager.
  48992. **
  48993. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  48994. ** the rollback journal, the unlock is not performed and there is
  48995. ** nothing to rollback, so this routine is a no-op.
  48996. */
  48997. static void pagerUnlockIfUnused(Pager *pPager){
  48998. if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
  48999. pagerUnlockAndRollback(pPager);
  49000. }
  49001. }
  49002. /*
  49003. ** The page getter methods each try to acquire a reference to a
  49004. ** page with page number pgno. If the requested reference is
  49005. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  49006. **
  49007. ** There are different implementations of the getter method depending
  49008. ** on the current state of the pager.
  49009. **
  49010. ** getPageNormal() -- The normal getter
  49011. ** getPageError() -- Used if the pager is in an error state
  49012. ** getPageMmap() -- Used if memory-mapped I/O is enabled
  49013. **
  49014. ** If the requested page is already in the cache, it is returned.
  49015. ** Otherwise, a new page object is allocated and populated with data
  49016. ** read from the database file. In some cases, the pcache module may
  49017. ** choose not to allocate a new page object and may reuse an existing
  49018. ** object with no outstanding references.
  49019. **
  49020. ** The extra data appended to a page is always initialized to zeros the
  49021. ** first time a page is loaded into memory. If the page requested is
  49022. ** already in the cache when this function is called, then the extra
  49023. ** data is left as it was when the page object was last used.
  49024. **
  49025. ** If the database image is smaller than the requested page or if
  49026. ** the flags parameter contains the PAGER_GET_NOCONTENT bit and the
  49027. ** requested page is not already stored in the cache, then no
  49028. ** actual disk read occurs. In this case the memory image of the
  49029. ** page is initialized to all zeros.
  49030. **
  49031. ** If PAGER_GET_NOCONTENT is true, it means that we do not care about
  49032. ** the contents of the page. This occurs in two scenarios:
  49033. **
  49034. ** a) When reading a free-list leaf page from the database, and
  49035. **
  49036. ** b) When a savepoint is being rolled back and we need to load
  49037. ** a new page into the cache to be filled with the data read
  49038. ** from the savepoint journal.
  49039. **
  49040. ** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead
  49041. ** of being read from the database. Additionally, the bits corresponding
  49042. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  49043. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  49044. ** savepoints are set. This means if the page is made writable at any
  49045. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  49046. ** will not be journaled. This saves IO.
  49047. **
  49048. ** The acquisition might fail for several reasons. In all cases,
  49049. ** an appropriate error code is returned and *ppPage is set to NULL.
  49050. **
  49051. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  49052. ** to find a page in the in-memory cache first. If the page is not already
  49053. ** in memory, this routine goes to disk to read it in whereas Lookup()
  49054. ** just returns 0. This routine acquires a read-lock the first time it
  49055. ** has to go to disk, and could also playback an old journal if necessary.
  49056. ** Since Lookup() never goes to disk, it never has to deal with locks
  49057. ** or journal files.
  49058. */
  49059. static int getPageNormal(
  49060. Pager *pPager, /* The pager open on the database file */
  49061. Pgno pgno, /* Page number to fetch */
  49062. DbPage **ppPage, /* Write a pointer to the page here */
  49063. int flags /* PAGER_GET_XXX flags */
  49064. ){
  49065. int rc = SQLITE_OK;
  49066. PgHdr *pPg;
  49067. u8 noContent; /* True if PAGER_GET_NOCONTENT is set */
  49068. sqlite3_pcache_page *pBase;
  49069. assert( pPager->errCode==SQLITE_OK );
  49070. assert( pPager->eState>=PAGER_READER );
  49071. assert( assert_pager_state(pPager) );
  49072. assert( pPager->hasHeldSharedLock==1 );
  49073. if( pgno==0 ) return SQLITE_CORRUPT_BKPT;
  49074. pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
  49075. if( pBase==0 ){
  49076. pPg = 0;
  49077. rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
  49078. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  49079. if( pBase==0 ){
  49080. rc = SQLITE_NOMEM_BKPT;
  49081. goto pager_acquire_err;
  49082. }
  49083. }
  49084. pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
  49085. assert( pPg==(*ppPage) );
  49086. assert( pPg->pgno==pgno );
  49087. assert( pPg->pPager==pPager || pPg->pPager==0 );
  49088. noContent = (flags & PAGER_GET_NOCONTENT)!=0;
  49089. if( pPg->pPager && !noContent ){
  49090. /* In this case the pcache already contains an initialized copy of
  49091. ** the page. Return without further ado. */
  49092. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  49093. pPager->aStat[PAGER_STAT_HIT]++;
  49094. return SQLITE_OK;
  49095. }else{
  49096. /* The pager cache has created a new page. Its content needs to
  49097. ** be initialized. But first some error checks:
  49098. **
  49099. ** (1) The maximum page number is 2^31
  49100. ** (2) Never try to fetch the locking page
  49101. */
  49102. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  49103. rc = SQLITE_CORRUPT_BKPT;
  49104. goto pager_acquire_err;
  49105. }
  49106. pPg->pPager = pPager;
  49107. assert( !isOpen(pPager->fd) || !MEMDB );
  49108. if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
  49109. if( pgno>pPager->mxPgno ){
  49110. rc = SQLITE_FULL;
  49111. goto pager_acquire_err;
  49112. }
  49113. if( noContent ){
  49114. /* Failure to set the bits in the InJournal bit-vectors is benign.
  49115. ** It merely means that we might do some extra work to journal a
  49116. ** page that does not need to be journaled. Nevertheless, be sure
  49117. ** to test the case where a malloc error occurs while trying to set
  49118. ** a bit in a bit vector.
  49119. */
  49120. sqlite3BeginBenignMalloc();
  49121. if( pgno<=pPager->dbOrigSize ){
  49122. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  49123. testcase( rc==SQLITE_NOMEM );
  49124. }
  49125. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  49126. testcase( rc==SQLITE_NOMEM );
  49127. sqlite3EndBenignMalloc();
  49128. }
  49129. memset(pPg->pData, 0, pPager->pageSize);
  49130. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  49131. }else{
  49132. u32 iFrame = 0; /* Frame to read from WAL file */
  49133. if( pagerUseWal(pPager) ){
  49134. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  49135. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  49136. }
  49137. assert( pPg->pPager==pPager );
  49138. pPager->aStat[PAGER_STAT_MISS]++;
  49139. rc = readDbPage(pPg, iFrame);
  49140. if( rc!=SQLITE_OK ){
  49141. goto pager_acquire_err;
  49142. }
  49143. }
  49144. pager_set_pagehash(pPg);
  49145. }
  49146. return SQLITE_OK;
  49147. pager_acquire_err:
  49148. assert( rc!=SQLITE_OK );
  49149. if( pPg ){
  49150. sqlite3PcacheDrop(pPg);
  49151. }
  49152. pagerUnlockIfUnused(pPager);
  49153. *ppPage = 0;
  49154. return rc;
  49155. }
  49156. #if SQLITE_MAX_MMAP_SIZE>0
  49157. /* The page getter for when memory-mapped I/O is enabled */
  49158. static int getPageMMap(
  49159. Pager *pPager, /* The pager open on the database file */
  49160. Pgno pgno, /* Page number to fetch */
  49161. DbPage **ppPage, /* Write a pointer to the page here */
  49162. int flags /* PAGER_GET_XXX flags */
  49163. ){
  49164. int rc = SQLITE_OK;
  49165. PgHdr *pPg = 0;
  49166. u32 iFrame = 0; /* Frame to read from WAL file */
  49167. /* It is acceptable to use a read-only (mmap) page for any page except
  49168. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  49169. ** flag was specified by the caller. And so long as the db is not a
  49170. ** temporary or in-memory database. */
  49171. const int bMmapOk = (pgno>1
  49172. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  49173. );
  49174. assert( USEFETCH(pPager) );
  49175. #ifdef SQLITE_HAS_CODEC
  49176. assert( pPager->xCodec==0 );
  49177. #endif
  49178. /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here
  49179. ** allows the compiler optimizer to reuse the results of the "pgno>1"
  49180. ** test in the previous statement, and avoid testing pgno==0 in the
  49181. ** common case where pgno is large. */
  49182. if( pgno<=1 && pgno==0 ){
  49183. return SQLITE_CORRUPT_BKPT;
  49184. }
  49185. assert( pPager->eState>=PAGER_READER );
  49186. assert( assert_pager_state(pPager) );
  49187. assert( pPager->hasHeldSharedLock==1 );
  49188. assert( pPager->errCode==SQLITE_OK );
  49189. if( bMmapOk && pagerUseWal(pPager) ){
  49190. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  49191. if( rc!=SQLITE_OK ){
  49192. *ppPage = 0;
  49193. return rc;
  49194. }
  49195. }
  49196. if( bMmapOk && iFrame==0 ){
  49197. void *pData = 0;
  49198. rc = sqlite3OsFetch(pPager->fd,
  49199. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  49200. );
  49201. if( rc==SQLITE_OK && pData ){
  49202. if( pPager->eState>PAGER_READER || pPager->tempFile ){
  49203. pPg = sqlite3PagerLookup(pPager, pgno);
  49204. }
  49205. if( pPg==0 ){
  49206. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  49207. }else{
  49208. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  49209. }
  49210. if( pPg ){
  49211. assert( rc==SQLITE_OK );
  49212. *ppPage = pPg;
  49213. return SQLITE_OK;
  49214. }
  49215. }
  49216. if( rc!=SQLITE_OK ){
  49217. *ppPage = 0;
  49218. return rc;
  49219. }
  49220. }
  49221. return getPageNormal(pPager, pgno, ppPage, flags);
  49222. }
  49223. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  49224. /* The page getter method for when the pager is an error state */
  49225. static int getPageError(
  49226. Pager *pPager, /* The pager open on the database file */
  49227. Pgno pgno, /* Page number to fetch */
  49228. DbPage **ppPage, /* Write a pointer to the page here */
  49229. int flags /* PAGER_GET_XXX flags */
  49230. ){
  49231. UNUSED_PARAMETER(pgno);
  49232. UNUSED_PARAMETER(flags);
  49233. assert( pPager->errCode!=SQLITE_OK );
  49234. *ppPage = 0;
  49235. return pPager->errCode;
  49236. }
  49237. /* Dispatch all page fetch requests to the appropriate getter method.
  49238. */
  49239. SQLITE_PRIVATE int sqlite3PagerGet(
  49240. Pager *pPager, /* The pager open on the database file */
  49241. Pgno pgno, /* Page number to fetch */
  49242. DbPage **ppPage, /* Write a pointer to the page here */
  49243. int flags /* PAGER_GET_XXX flags */
  49244. ){
  49245. return pPager->xGet(pPager, pgno, ppPage, flags);
  49246. }
  49247. /*
  49248. ** Acquire a page if it is already in the in-memory cache. Do
  49249. ** not read the page from disk. Return a pointer to the page,
  49250. ** or 0 if the page is not in cache.
  49251. **
  49252. ** See also sqlite3PagerGet(). The difference between this routine
  49253. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  49254. ** in the page if the page is not already in cache. This routine
  49255. ** returns NULL if the page is not in cache or if a disk I/O error
  49256. ** has ever happened.
  49257. */
  49258. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  49259. sqlite3_pcache_page *pPage;
  49260. assert( pPager!=0 );
  49261. assert( pgno!=0 );
  49262. assert( pPager->pPCache!=0 );
  49263. pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
  49264. assert( pPage==0 || pPager->hasHeldSharedLock );
  49265. if( pPage==0 ) return 0;
  49266. return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
  49267. }
  49268. /*
  49269. ** Release a page reference.
  49270. **
  49271. ** If the number of references to the page drop to zero, then the
  49272. ** page is added to the LRU list. When all references to all pages
  49273. ** are released, a rollback occurs and the lock on the database is
  49274. ** removed.
  49275. */
  49276. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
  49277. Pager *pPager;
  49278. assert( pPg!=0 );
  49279. pPager = pPg->pPager;
  49280. if( pPg->flags & PGHDR_MMAP ){
  49281. pagerReleaseMapPage(pPg);
  49282. }else{
  49283. sqlite3PcacheRelease(pPg);
  49284. }
  49285. pagerUnlockIfUnused(pPager);
  49286. }
  49287. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  49288. if( pPg ) sqlite3PagerUnrefNotNull(pPg);
  49289. }
  49290. /*
  49291. ** This function is called at the start of every write transaction.
  49292. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  49293. ** file when this routine is called.
  49294. **
  49295. ** Open the journal file for pager pPager and write a journal header
  49296. ** to the start of it. If there are active savepoints, open the sub-journal
  49297. ** as well. This function is only used when the journal file is being
  49298. ** opened to write a rollback log for a transaction. It is not used
  49299. ** when opening a hot journal file to roll it back.
  49300. **
  49301. ** If the journal file is already open (as it may be in exclusive mode),
  49302. ** then this function just writes a journal header to the start of the
  49303. ** already open file.
  49304. **
  49305. ** Whether or not the journal file is opened by this function, the
  49306. ** Pager.pInJournal bitvec structure is allocated.
  49307. **
  49308. ** Return SQLITE_OK if everything is successful. Otherwise, return
  49309. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  49310. ** an IO error code if opening or writing the journal file fails.
  49311. */
  49312. static int pager_open_journal(Pager *pPager){
  49313. int rc = SQLITE_OK; /* Return code */
  49314. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  49315. assert( pPager->eState==PAGER_WRITER_LOCKED );
  49316. assert( assert_pager_state(pPager) );
  49317. assert( pPager->pInJournal==0 );
  49318. /* If already in the error state, this function is a no-op. But on
  49319. ** the other hand, this routine is never called if we are already in
  49320. ** an error state. */
  49321. if( NEVER(pPager->errCode) ) return pPager->errCode;
  49322. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  49323. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  49324. if( pPager->pInJournal==0 ){
  49325. return SQLITE_NOMEM_BKPT;
  49326. }
  49327. /* Open the journal file if it is not already open. */
  49328. if( !isOpen(pPager->jfd) ){
  49329. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  49330. sqlite3MemJournalOpen(pPager->jfd);
  49331. }else{
  49332. int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
  49333. int nSpill;
  49334. if( pPager->tempFile ){
  49335. flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
  49336. nSpill = sqlite3Config.nStmtSpill;
  49337. }else{
  49338. flags |= SQLITE_OPEN_MAIN_JOURNAL;
  49339. nSpill = jrnlBufferSize(pPager);
  49340. }
  49341. /* Verify that the database still has the same name as it did when
  49342. ** it was originally opened. */
  49343. rc = databaseIsUnmoved(pPager);
  49344. if( rc==SQLITE_OK ){
  49345. rc = sqlite3JournalOpen (
  49346. pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
  49347. );
  49348. }
  49349. }
  49350. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  49351. }
  49352. /* Write the first journal header to the journal file and open
  49353. ** the sub-journal if necessary.
  49354. */
  49355. if( rc==SQLITE_OK ){
  49356. /* TODO: Check if all of these are really required. */
  49357. pPager->nRec = 0;
  49358. pPager->journalOff = 0;
  49359. pPager->setMaster = 0;
  49360. pPager->journalHdr = 0;
  49361. rc = writeJournalHdr(pPager);
  49362. }
  49363. }
  49364. if( rc!=SQLITE_OK ){
  49365. sqlite3BitvecDestroy(pPager->pInJournal);
  49366. pPager->pInJournal = 0;
  49367. }else{
  49368. assert( pPager->eState==PAGER_WRITER_LOCKED );
  49369. pPager->eState = PAGER_WRITER_CACHEMOD;
  49370. }
  49371. return rc;
  49372. }
  49373. /*
  49374. ** Begin a write-transaction on the specified pager object. If a
  49375. ** write-transaction has already been opened, this function is a no-op.
  49376. **
  49377. ** If the exFlag argument is false, then acquire at least a RESERVED
  49378. ** lock on the database file. If exFlag is true, then acquire at least
  49379. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  49380. ** functions need be called.
  49381. **
  49382. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  49383. ** within this transaction will be opened as an in-memory file. This
  49384. ** has no effect if the sub-journal is already opened (as it may be when
  49385. ** running in exclusive mode) or if the transaction does not require a
  49386. ** sub-journal. If the subjInMemory argument is zero, then any required
  49387. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  49388. ** or using a temporary file otherwise.
  49389. */
  49390. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  49391. int rc = SQLITE_OK;
  49392. if( pPager->errCode ) return pPager->errCode;
  49393. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  49394. pPager->subjInMemory = (u8)subjInMemory;
  49395. if( ALWAYS(pPager->eState==PAGER_READER) ){
  49396. assert( pPager->pInJournal==0 );
  49397. if( pagerUseWal(pPager) ){
  49398. /* If the pager is configured to use locking_mode=exclusive, and an
  49399. ** exclusive lock on the database is not already held, obtain it now.
  49400. */
  49401. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  49402. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  49403. if( rc!=SQLITE_OK ){
  49404. return rc;
  49405. }
  49406. (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
  49407. }
  49408. /* Grab the write lock on the log file. If successful, upgrade to
  49409. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  49410. ** The busy-handler is not invoked if another connection already
  49411. ** holds the write-lock. If possible, the upper layer will call it.
  49412. */
  49413. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  49414. }else{
  49415. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  49416. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  49417. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  49418. ** lock, but not when obtaining the RESERVED lock.
  49419. */
  49420. rc = pagerLockDb(pPager, RESERVED_LOCK);
  49421. if( rc==SQLITE_OK && exFlag ){
  49422. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  49423. }
  49424. }
  49425. if( rc==SQLITE_OK ){
  49426. /* Change to WRITER_LOCKED state.
  49427. **
  49428. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  49429. ** when it has an open transaction, but never to DBMOD or FINISHED.
  49430. ** This is because in those states the code to roll back savepoint
  49431. ** transactions may copy data from the sub-journal into the database
  49432. ** file as well as into the page cache. Which would be incorrect in
  49433. ** WAL mode.
  49434. */
  49435. pPager->eState = PAGER_WRITER_LOCKED;
  49436. pPager->dbHintSize = pPager->dbSize;
  49437. pPager->dbFileSize = pPager->dbSize;
  49438. pPager->dbOrigSize = pPager->dbSize;
  49439. pPager->journalOff = 0;
  49440. }
  49441. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  49442. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  49443. assert( assert_pager_state(pPager) );
  49444. }
  49445. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  49446. return rc;
  49447. }
  49448. /*
  49449. ** Write page pPg onto the end of the rollback journal.
  49450. */
  49451. static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
  49452. Pager *pPager = pPg->pPager;
  49453. int rc;
  49454. u32 cksum;
  49455. char *pData2;
  49456. i64 iOff = pPager->journalOff;
  49457. /* We should never write to the journal file the page that
  49458. ** contains the database locks. The following assert verifies
  49459. ** that we do not. */
  49460. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  49461. assert( pPager->journalHdr<=pPager->journalOff );
  49462. CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
  49463. cksum = pager_cksum(pPager, (u8*)pData2);
  49464. /* Even if an IO or diskfull error occurs while journalling the
  49465. ** page in the block above, set the need-sync flag for the page.
  49466. ** Otherwise, when the transaction is rolled back, the logic in
  49467. ** playback_one_page() will think that the page needs to be restored
  49468. ** in the database file. And if an IO error occurs while doing so,
  49469. ** then corruption may follow.
  49470. */
  49471. pPg->flags |= PGHDR_NEED_SYNC;
  49472. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  49473. if( rc!=SQLITE_OK ) return rc;
  49474. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  49475. if( rc!=SQLITE_OK ) return rc;
  49476. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  49477. if( rc!=SQLITE_OK ) return rc;
  49478. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  49479. pPager->journalOff, pPager->pageSize));
  49480. PAGER_INCR(sqlite3_pager_writej_count);
  49481. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  49482. PAGERID(pPager), pPg->pgno,
  49483. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  49484. pPager->journalOff += 8 + pPager->pageSize;
  49485. pPager->nRec++;
  49486. assert( pPager->pInJournal!=0 );
  49487. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  49488. testcase( rc==SQLITE_NOMEM );
  49489. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  49490. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  49491. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  49492. return rc;
  49493. }
  49494. /*
  49495. ** Mark a single data page as writeable. The page is written into the
  49496. ** main journal or sub-journal as required. If the page is written into
  49497. ** one of the journals, the corresponding bit is set in the
  49498. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  49499. ** of any open savepoints as appropriate.
  49500. */
  49501. static int pager_write(PgHdr *pPg){
  49502. Pager *pPager = pPg->pPager;
  49503. int rc = SQLITE_OK;
  49504. /* This routine is not called unless a write-transaction has already
  49505. ** been started. The journal file may or may not be open at this point.
  49506. ** It is never called in the ERROR state.
  49507. */
  49508. assert( pPager->eState==PAGER_WRITER_LOCKED
  49509. || pPager->eState==PAGER_WRITER_CACHEMOD
  49510. || pPager->eState==PAGER_WRITER_DBMOD
  49511. );
  49512. assert( assert_pager_state(pPager) );
  49513. assert( pPager->errCode==0 );
  49514. assert( pPager->readOnly==0 );
  49515. CHECK_PAGE(pPg);
  49516. /* The journal file needs to be opened. Higher level routines have already
  49517. ** obtained the necessary locks to begin the write-transaction, but the
  49518. ** rollback journal might not yet be open. Open it now if this is the case.
  49519. **
  49520. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  49521. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  49522. ** an error might occur and the pager would end up in WRITER_LOCKED state
  49523. ** with pages marked as dirty in the cache.
  49524. */
  49525. if( pPager->eState==PAGER_WRITER_LOCKED ){
  49526. rc = pager_open_journal(pPager);
  49527. if( rc!=SQLITE_OK ) return rc;
  49528. }
  49529. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  49530. assert( assert_pager_state(pPager) );
  49531. /* Mark the page that is about to be modified as dirty. */
  49532. sqlite3PcacheMakeDirty(pPg);
  49533. /* If a rollback journal is in use, them make sure the page that is about
  49534. ** to change is in the rollback journal, or if the page is a new page off
  49535. ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
  49536. */
  49537. assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
  49538. if( pPager->pInJournal!=0
  49539. && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
  49540. ){
  49541. assert( pagerUseWal(pPager)==0 );
  49542. if( pPg->pgno<=pPager->dbOrigSize ){
  49543. rc = pagerAddPageToRollbackJournal(pPg);
  49544. if( rc!=SQLITE_OK ){
  49545. return rc;
  49546. }
  49547. }else{
  49548. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  49549. pPg->flags |= PGHDR_NEED_SYNC;
  49550. }
  49551. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  49552. PAGERID(pPager), pPg->pgno,
  49553. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  49554. }
  49555. }
  49556. /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
  49557. ** and before writing the page into the rollback journal. Wait until now,
  49558. ** after the page has been successfully journalled, before setting the
  49559. ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
  49560. */
  49561. pPg->flags |= PGHDR_WRITEABLE;
  49562. /* If the statement journal is open and the page is not in it,
  49563. ** then write the page into the statement journal.
  49564. */
  49565. if( pPager->nSavepoint>0 ){
  49566. rc = subjournalPageIfRequired(pPg);
  49567. }
  49568. /* Update the database size and return. */
  49569. if( pPager->dbSize<pPg->pgno ){
  49570. pPager->dbSize = pPg->pgno;
  49571. }
  49572. return rc;
  49573. }
  49574. /*
  49575. ** This is a variant of sqlite3PagerWrite() that runs when the sector size
  49576. ** is larger than the page size. SQLite makes the (reasonable) assumption that
  49577. ** all bytes of a sector are written together by hardware. Hence, all bytes of
  49578. ** a sector need to be journalled in case of a power loss in the middle of
  49579. ** a write.
  49580. **
  49581. ** Usually, the sector size is less than or equal to the page size, in which
  49582. ** case pages can be individually written. This routine only runs in the
  49583. ** exceptional case where the page size is smaller than the sector size.
  49584. */
  49585. static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
  49586. int rc = SQLITE_OK; /* Return code */
  49587. Pgno nPageCount; /* Total number of pages in database file */
  49588. Pgno pg1; /* First page of the sector pPg is located on. */
  49589. int nPage = 0; /* Number of pages starting at pg1 to journal */
  49590. int ii; /* Loop counter */
  49591. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  49592. Pager *pPager = pPg->pPager; /* The pager that owns pPg */
  49593. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  49594. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  49595. ** a journal header to be written between the pages journaled by
  49596. ** this function.
  49597. */
  49598. assert( !MEMDB );
  49599. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  49600. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  49601. /* This trick assumes that both the page-size and sector-size are
  49602. ** an integer power of 2. It sets variable pg1 to the identifier
  49603. ** of the first page of the sector pPg is located on.
  49604. */
  49605. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  49606. nPageCount = pPager->dbSize;
  49607. if( pPg->pgno>nPageCount ){
  49608. nPage = (pPg->pgno - pg1)+1;
  49609. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  49610. nPage = nPageCount+1-pg1;
  49611. }else{
  49612. nPage = nPagePerSector;
  49613. }
  49614. assert(nPage>0);
  49615. assert(pg1<=pPg->pgno);
  49616. assert((pg1+nPage)>pPg->pgno);
  49617. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  49618. Pgno pg = pg1+ii;
  49619. PgHdr *pPage;
  49620. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  49621. if( pg!=PAGER_MJ_PGNO(pPager) ){
  49622. rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
  49623. if( rc==SQLITE_OK ){
  49624. rc = pager_write(pPage);
  49625. if( pPage->flags&PGHDR_NEED_SYNC ){
  49626. needSync = 1;
  49627. }
  49628. sqlite3PagerUnrefNotNull(pPage);
  49629. }
  49630. }
  49631. }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
  49632. if( pPage->flags&PGHDR_NEED_SYNC ){
  49633. needSync = 1;
  49634. }
  49635. sqlite3PagerUnrefNotNull(pPage);
  49636. }
  49637. }
  49638. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  49639. ** starting at pg1, then it needs to be set for all of them. Because
  49640. ** writing to any of these nPage pages may damage the others, the
  49641. ** journal file must contain sync()ed copies of all of them
  49642. ** before any of them can be written out to the database file.
  49643. */
  49644. if( rc==SQLITE_OK && needSync ){
  49645. assert( !MEMDB );
  49646. for(ii=0; ii<nPage; ii++){
  49647. PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
  49648. if( pPage ){
  49649. pPage->flags |= PGHDR_NEED_SYNC;
  49650. sqlite3PagerUnrefNotNull(pPage);
  49651. }
  49652. }
  49653. }
  49654. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  49655. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  49656. return rc;
  49657. }
  49658. /*
  49659. ** Mark a data page as writeable. This routine must be called before
  49660. ** making changes to a page. The caller must check the return value
  49661. ** of this function and be careful not to change any page data unless
  49662. ** this routine returns SQLITE_OK.
  49663. **
  49664. ** The difference between this function and pager_write() is that this
  49665. ** function also deals with the special case where 2 or more pages
  49666. ** fit on a single disk sector. In this case all co-resident pages
  49667. ** must have been written to the journal file before returning.
  49668. **
  49669. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  49670. ** as appropriate. Otherwise, SQLITE_OK.
  49671. */
  49672. SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
  49673. Pager *pPager = pPg->pPager;
  49674. assert( (pPg->flags & PGHDR_MMAP)==0 );
  49675. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  49676. assert( assert_pager_state(pPager) );
  49677. if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
  49678. if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
  49679. return SQLITE_OK;
  49680. }else if( pPager->errCode ){
  49681. return pPager->errCode;
  49682. }else if( pPager->sectorSize > (u32)pPager->pageSize ){
  49683. assert( pPager->tempFile==0 );
  49684. return pagerWriteLargeSector(pPg);
  49685. }else{
  49686. return pager_write(pPg);
  49687. }
  49688. }
  49689. /*
  49690. ** Return TRUE if the page given in the argument was previously passed
  49691. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  49692. ** to change the content of the page.
  49693. */
  49694. #ifndef NDEBUG
  49695. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  49696. return pPg->flags & PGHDR_WRITEABLE;
  49697. }
  49698. #endif
  49699. /*
  49700. ** A call to this routine tells the pager that it is not necessary to
  49701. ** write the information on page pPg back to the disk, even though
  49702. ** that page might be marked as dirty. This happens, for example, when
  49703. ** the page has been added as a leaf of the freelist and so its
  49704. ** content no longer matters.
  49705. **
  49706. ** The overlying software layer calls this routine when all of the data
  49707. ** on the given page is unused. The pager marks the page as clean so
  49708. ** that it does not get written to disk.
  49709. **
  49710. ** Tests show that this optimization can quadruple the speed of large
  49711. ** DELETE operations.
  49712. **
  49713. ** This optimization cannot be used with a temp-file, as the page may
  49714. ** have been dirty at the start of the transaction. In that case, if
  49715. ** memory pressure forces page pPg out of the cache, the data does need
  49716. ** to be written out to disk so that it may be read back in if the
  49717. ** current transaction is rolled back.
  49718. */
  49719. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  49720. Pager *pPager = pPg->pPager;
  49721. if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  49722. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  49723. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  49724. pPg->flags |= PGHDR_DONT_WRITE;
  49725. pPg->flags &= ~PGHDR_WRITEABLE;
  49726. testcase( pPg->flags & PGHDR_NEED_SYNC );
  49727. pager_set_pagehash(pPg);
  49728. }
  49729. }
  49730. /*
  49731. ** This routine is called to increment the value of the database file
  49732. ** change-counter, stored as a 4-byte big-endian integer starting at
  49733. ** byte offset 24 of the pager file. The secondary change counter at
  49734. ** 92 is also updated, as is the SQLite version number at offset 96.
  49735. **
  49736. ** But this only happens if the pPager->changeCountDone flag is false.
  49737. ** To avoid excess churning of page 1, the update only happens once.
  49738. ** See also the pager_write_changecounter() routine that does an
  49739. ** unconditional update of the change counters.
  49740. **
  49741. ** If the isDirectMode flag is zero, then this is done by calling
  49742. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  49743. ** page data. In this case the file will be updated when the current
  49744. ** transaction is committed.
  49745. **
  49746. ** The isDirectMode flag may only be non-zero if the library was compiled
  49747. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  49748. ** if isDirect is non-zero, then the database file is updated directly
  49749. ** by writing an updated version of page 1 using a call to the
  49750. ** sqlite3OsWrite() function.
  49751. */
  49752. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  49753. int rc = SQLITE_OK;
  49754. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  49755. || pPager->eState==PAGER_WRITER_DBMOD
  49756. );
  49757. assert( assert_pager_state(pPager) );
  49758. /* Declare and initialize constant integer 'isDirect'. If the
  49759. ** atomic-write optimization is enabled in this build, then isDirect
  49760. ** is initialized to the value passed as the isDirectMode parameter
  49761. ** to this function. Otherwise, it is always set to zero.
  49762. **
  49763. ** The idea is that if the atomic-write optimization is not
  49764. ** enabled at compile time, the compiler can omit the tests of
  49765. ** 'isDirect' below, as well as the block enclosed in the
  49766. ** "if( isDirect )" condition.
  49767. */
  49768. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  49769. # define DIRECT_MODE 0
  49770. assert( isDirectMode==0 );
  49771. UNUSED_PARAMETER(isDirectMode);
  49772. #else
  49773. # define DIRECT_MODE isDirectMode
  49774. #endif
  49775. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  49776. PgHdr *pPgHdr; /* Reference to page 1 */
  49777. assert( !pPager->tempFile && isOpen(pPager->fd) );
  49778. /* Open page 1 of the file for writing. */
  49779. rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
  49780. assert( pPgHdr==0 || rc==SQLITE_OK );
  49781. /* If page one was fetched successfully, and this function is not
  49782. ** operating in direct-mode, make page 1 writable. When not in
  49783. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  49784. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  49785. */
  49786. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  49787. rc = sqlite3PagerWrite(pPgHdr);
  49788. }
  49789. if( rc==SQLITE_OK ){
  49790. /* Actually do the update of the change counter */
  49791. pager_write_changecounter(pPgHdr);
  49792. /* If running in direct mode, write the contents of page 1 to the file. */
  49793. if( DIRECT_MODE ){
  49794. const void *zBuf;
  49795. assert( pPager->dbFileSize>0 );
  49796. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
  49797. if( rc==SQLITE_OK ){
  49798. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  49799. pPager->aStat[PAGER_STAT_WRITE]++;
  49800. }
  49801. if( rc==SQLITE_OK ){
  49802. /* Update the pager's copy of the change-counter. Otherwise, the
  49803. ** next time a read transaction is opened the cache will be
  49804. ** flushed (as the change-counter values will not match). */
  49805. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  49806. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  49807. pPager->changeCountDone = 1;
  49808. }
  49809. }else{
  49810. pPager->changeCountDone = 1;
  49811. }
  49812. }
  49813. /* Release the page reference. */
  49814. sqlite3PagerUnref(pPgHdr);
  49815. }
  49816. return rc;
  49817. }
  49818. /*
  49819. ** Sync the database file to disk. This is a no-op for in-memory databases
  49820. ** or pages with the Pager.noSync flag set.
  49821. **
  49822. ** If successful, or if called on a pager for which it is a no-op, this
  49823. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  49824. */
  49825. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
  49826. int rc = SQLITE_OK;
  49827. if( isOpen(pPager->fd) ){
  49828. void *pArg = (void*)zMaster;
  49829. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
  49830. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  49831. }
  49832. if( rc==SQLITE_OK && !pPager->noSync ){
  49833. assert( !MEMDB );
  49834. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  49835. }
  49836. return rc;
  49837. }
  49838. /*
  49839. ** This function may only be called while a write-transaction is active in
  49840. ** rollback. If the connection is in WAL mode, this call is a no-op.
  49841. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  49842. ** the database file, an attempt is made to obtain one.
  49843. **
  49844. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  49845. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  49846. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  49847. ** returned.
  49848. */
  49849. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  49850. int rc = pPager->errCode;
  49851. assert( assert_pager_state(pPager) );
  49852. if( rc==SQLITE_OK ){
  49853. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  49854. || pPager->eState==PAGER_WRITER_DBMOD
  49855. || pPager->eState==PAGER_WRITER_LOCKED
  49856. );
  49857. assert( assert_pager_state(pPager) );
  49858. if( 0==pagerUseWal(pPager) ){
  49859. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  49860. }
  49861. }
  49862. return rc;
  49863. }
  49864. /*
  49865. ** Sync the database file for the pager pPager. zMaster points to the name
  49866. ** of a master journal file that should be written into the individual
  49867. ** journal file. zMaster may be NULL, which is interpreted as no master
  49868. ** journal (a single database transaction).
  49869. **
  49870. ** This routine ensures that:
  49871. **
  49872. ** * The database file change-counter is updated,
  49873. ** * the journal is synced (unless the atomic-write optimization is used),
  49874. ** * all dirty pages are written to the database file,
  49875. ** * the database file is truncated (if required), and
  49876. ** * the database file synced.
  49877. **
  49878. ** The only thing that remains to commit the transaction is to finalize
  49879. ** (delete, truncate or zero the first part of) the journal file (or
  49880. ** delete the master journal file if specified).
  49881. **
  49882. ** Note that if zMaster==NULL, this does not overwrite a previous value
  49883. ** passed to an sqlite3PagerCommitPhaseOne() call.
  49884. **
  49885. ** If the final parameter - noSync - is true, then the database file itself
  49886. ** is not synced. The caller must call sqlite3PagerSync() directly to
  49887. ** sync the database file before calling CommitPhaseTwo() to delete the
  49888. ** journal file in this case.
  49889. */
  49890. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  49891. Pager *pPager, /* Pager object */
  49892. const char *zMaster, /* If not NULL, the master journal name */
  49893. int noSync /* True to omit the xSync on the db file */
  49894. ){
  49895. int rc = SQLITE_OK; /* Return code */
  49896. assert( pPager->eState==PAGER_WRITER_LOCKED
  49897. || pPager->eState==PAGER_WRITER_CACHEMOD
  49898. || pPager->eState==PAGER_WRITER_DBMOD
  49899. || pPager->eState==PAGER_ERROR
  49900. );
  49901. assert( assert_pager_state(pPager) );
  49902. /* If a prior error occurred, report that error again. */
  49903. if( NEVER(pPager->errCode) ) return pPager->errCode;
  49904. /* Provide the ability to easily simulate an I/O error during testing */
  49905. if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
  49906. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  49907. pPager->zFilename, zMaster, pPager->dbSize));
  49908. /* If no database changes have been made, return early. */
  49909. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  49910. assert( MEMDB==0 || pPager->tempFile );
  49911. assert( isOpen(pPager->fd) || pPager->tempFile );
  49912. if( 0==pagerFlushOnCommit(pPager, 1) ){
  49913. /* If this is an in-memory db, or no pages have been written to, or this
  49914. ** function has already been called, it is mostly a no-op. However, any
  49915. ** backup in progress needs to be restarted. */
  49916. sqlite3BackupRestart(pPager->pBackup);
  49917. }else{
  49918. if( pagerUseWal(pPager) ){
  49919. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  49920. PgHdr *pPageOne = 0;
  49921. if( pList==0 ){
  49922. /* Must have at least one page for the WAL commit flag.
  49923. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  49924. rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
  49925. pList = pPageOne;
  49926. pList->pDirty = 0;
  49927. }
  49928. assert( rc==SQLITE_OK );
  49929. if( ALWAYS(pList) ){
  49930. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  49931. }
  49932. sqlite3PagerUnref(pPageOne);
  49933. if( rc==SQLITE_OK ){
  49934. sqlite3PcacheCleanAll(pPager->pPCache);
  49935. }
  49936. }else{
  49937. /* The following block updates the change-counter. Exactly how it
  49938. ** does this depends on whether or not the atomic-update optimization
  49939. ** was enabled at compile time, and if this transaction meets the
  49940. ** runtime criteria to use the operation:
  49941. **
  49942. ** * The file-system supports the atomic-write property for
  49943. ** blocks of size page-size, and
  49944. ** * This commit is not part of a multi-file transaction, and
  49945. ** * Exactly one page has been modified and store in the journal file.
  49946. **
  49947. ** If the optimization was not enabled at compile time, then the
  49948. ** pager_incr_changecounter() function is called to update the change
  49949. ** counter in 'indirect-mode'. If the optimization is compiled in but
  49950. ** is not applicable to this transaction, call sqlite3JournalCreate()
  49951. ** to make sure the journal file has actually been created, then call
  49952. ** pager_incr_changecounter() to update the change-counter in indirect
  49953. ** mode.
  49954. **
  49955. ** Otherwise, if the optimization is both enabled and applicable,
  49956. ** then call pager_incr_changecounter() to update the change-counter
  49957. ** in 'direct' mode. In this case the journal file will never be
  49958. ** created for this transaction.
  49959. */
  49960. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  49961. PgHdr *pPg;
  49962. assert( isOpen(pPager->jfd)
  49963. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  49964. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  49965. );
  49966. if( !zMaster && isOpen(pPager->jfd)
  49967. && pPager->journalOff==jrnlBufferSize(pPager)
  49968. && pPager->dbSize>=pPager->dbOrigSize
  49969. && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  49970. ){
  49971. /* Update the db file change counter via the direct-write method. The
  49972. ** following call will modify the in-memory representation of page 1
  49973. ** to include the updated change counter and then write page 1
  49974. ** directly to the database file. Because of the atomic-write
  49975. ** property of the host file-system, this is safe.
  49976. */
  49977. rc = pager_incr_changecounter(pPager, 1);
  49978. }else{
  49979. rc = sqlite3JournalCreate(pPager->jfd);
  49980. if( rc==SQLITE_OK ){
  49981. rc = pager_incr_changecounter(pPager, 0);
  49982. }
  49983. }
  49984. #else
  49985. rc = pager_incr_changecounter(pPager, 0);
  49986. #endif
  49987. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  49988. /* Write the master journal name into the journal file. If a master
  49989. ** journal file name has already been written to the journal file,
  49990. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  49991. */
  49992. rc = writeMasterJournal(pPager, zMaster);
  49993. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  49994. /* Sync the journal file and write all dirty pages to the database.
  49995. ** If the atomic-update optimization is being used, this sync will not
  49996. ** create the journal file or perform any real IO.
  49997. **
  49998. ** Because the change-counter page was just modified, unless the
  49999. ** atomic-update optimization is used it is almost certain that the
  50000. ** journal requires a sync here. However, in locking_mode=exclusive
  50001. ** on a system under memory pressure it is just possible that this is
  50002. ** not the case. In this case it is likely enough that the redundant
  50003. ** xSync() call will be changed to a no-op by the OS anyhow.
  50004. */
  50005. rc = syncJournal(pPager, 0);
  50006. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  50007. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  50008. if( rc!=SQLITE_OK ){
  50009. assert( rc!=SQLITE_IOERR_BLOCKED );
  50010. goto commit_phase_one_exit;
  50011. }
  50012. sqlite3PcacheCleanAll(pPager->pPCache);
  50013. /* If the file on disk is smaller than the database image, use
  50014. ** pager_truncate to grow the file here. This can happen if the database
  50015. ** image was extended as part of the current transaction and then the
  50016. ** last page in the db image moved to the free-list. In this case the
  50017. ** last page is never written out to disk, leaving the database file
  50018. ** undersized. Fix this now if it is the case. */
  50019. if( pPager->dbSize>pPager->dbFileSize ){
  50020. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  50021. assert( pPager->eState==PAGER_WRITER_DBMOD );
  50022. rc = pager_truncate(pPager, nNew);
  50023. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  50024. }
  50025. /* Finally, sync the database file. */
  50026. if( !noSync ){
  50027. rc = sqlite3PagerSync(pPager, zMaster);
  50028. }
  50029. IOTRACE(("DBSYNC %p\n", pPager))
  50030. }
  50031. }
  50032. commit_phase_one_exit:
  50033. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  50034. pPager->eState = PAGER_WRITER_FINISHED;
  50035. }
  50036. return rc;
  50037. }
  50038. /*
  50039. ** When this function is called, the database file has been completely
  50040. ** updated to reflect the changes made by the current transaction and
  50041. ** synced to disk. The journal file still exists in the file-system
  50042. ** though, and if a failure occurs at this point it will eventually
  50043. ** be used as a hot-journal and the current transaction rolled back.
  50044. **
  50045. ** This function finalizes the journal file, either by deleting,
  50046. ** truncating or partially zeroing it, so that it cannot be used
  50047. ** for hot-journal rollback. Once this is done the transaction is
  50048. ** irrevocably committed.
  50049. **
  50050. ** If an error occurs, an IO error code is returned and the pager
  50051. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  50052. */
  50053. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  50054. int rc = SQLITE_OK; /* Return code */
  50055. /* This routine should not be called if a prior error has occurred.
  50056. ** But if (due to a coding error elsewhere in the system) it does get
  50057. ** called, just return the same error code without doing anything. */
  50058. if( NEVER(pPager->errCode) ) return pPager->errCode;
  50059. assert( pPager->eState==PAGER_WRITER_LOCKED
  50060. || pPager->eState==PAGER_WRITER_FINISHED
  50061. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  50062. );
  50063. assert( assert_pager_state(pPager) );
  50064. /* An optimization. If the database was not actually modified during
  50065. ** this transaction, the pager is running in exclusive-mode and is
  50066. ** using persistent journals, then this function is a no-op.
  50067. **
  50068. ** The start of the journal file currently contains a single journal
  50069. ** header with the nRec field set to 0. If such a journal is used as
  50070. ** a hot-journal during hot-journal rollback, 0 changes will be made
  50071. ** to the database file. So there is no need to zero the journal
  50072. ** header. Since the pager is in exclusive mode, there is no need
  50073. ** to drop any locks either.
  50074. */
  50075. if( pPager->eState==PAGER_WRITER_LOCKED
  50076. && pPager->exclusiveMode
  50077. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  50078. ){
  50079. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  50080. pPager->eState = PAGER_READER;
  50081. return SQLITE_OK;
  50082. }
  50083. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  50084. pPager->iDataVersion++;
  50085. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  50086. return pager_error(pPager, rc);
  50087. }
  50088. /*
  50089. ** If a write transaction is open, then all changes made within the
  50090. ** transaction are reverted and the current write-transaction is closed.
  50091. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  50092. ** state if an error occurs.
  50093. **
  50094. ** If the pager is already in PAGER_ERROR state when this function is called,
  50095. ** it returns Pager.errCode immediately. No work is performed in this case.
  50096. **
  50097. ** Otherwise, in rollback mode, this function performs two functions:
  50098. **
  50099. ** 1) It rolls back the journal file, restoring all database file and
  50100. ** in-memory cache pages to the state they were in when the transaction
  50101. ** was opened, and
  50102. **
  50103. ** 2) It finalizes the journal file, so that it is not used for hot
  50104. ** rollback at any point in the future.
  50105. **
  50106. ** Finalization of the journal file (task 2) is only performed if the
  50107. ** rollback is successful.
  50108. **
  50109. ** In WAL mode, all cache-entries containing data modified within the
  50110. ** current transaction are either expelled from the cache or reverted to
  50111. ** their pre-transaction state by re-reading data from the database or
  50112. ** WAL files. The WAL transaction is then closed.
  50113. */
  50114. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  50115. int rc = SQLITE_OK; /* Return code */
  50116. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  50117. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  50118. ** the pager is already in the ERROR state, the rollback is not
  50119. ** attempted here. Instead, the error code is returned to the caller.
  50120. */
  50121. assert( assert_pager_state(pPager) );
  50122. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  50123. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  50124. if( pagerUseWal(pPager) ){
  50125. int rc2;
  50126. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  50127. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  50128. if( rc==SQLITE_OK ) rc = rc2;
  50129. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  50130. int eState = pPager->eState;
  50131. rc = pager_end_transaction(pPager, 0, 0);
  50132. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  50133. /* This can happen using journal_mode=off. Move the pager to the error
  50134. ** state to indicate that the contents of the cache may not be trusted.
  50135. ** Any active readers will get SQLITE_ABORT.
  50136. */
  50137. pPager->errCode = SQLITE_ABORT;
  50138. pPager->eState = PAGER_ERROR;
  50139. setGetterMethod(pPager);
  50140. return rc;
  50141. }
  50142. }else{
  50143. rc = pager_playback(pPager, 0);
  50144. }
  50145. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  50146. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  50147. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
  50148. || rc==SQLITE_CANTOPEN
  50149. );
  50150. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  50151. ** cache. So call pager_error() on the way out to make any error persistent.
  50152. */
  50153. return pager_error(pPager, rc);
  50154. }
  50155. /*
  50156. ** Return TRUE if the database file is opened read-only. Return FALSE
  50157. ** if the database is (in theory) writable.
  50158. */
  50159. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  50160. return pPager->readOnly;
  50161. }
  50162. #ifdef SQLITE_DEBUG
  50163. /*
  50164. ** Return the sum of the reference counts for all pages held by pPager.
  50165. */
  50166. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  50167. return sqlite3PcacheRefCount(pPager->pPCache);
  50168. }
  50169. #endif
  50170. /*
  50171. ** Return the approximate number of bytes of memory currently
  50172. ** used by the pager and its associated cache.
  50173. */
  50174. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  50175. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  50176. + 5*sizeof(void*);
  50177. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  50178. + sqlite3MallocSize(pPager)
  50179. + pPager->pageSize;
  50180. }
  50181. /*
  50182. ** Return the number of references to the specified page.
  50183. */
  50184. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  50185. return sqlite3PcachePageRefcount(pPage);
  50186. }
  50187. #ifdef SQLITE_TEST
  50188. /*
  50189. ** This routine is used for testing and analysis only.
  50190. */
  50191. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  50192. static int a[11];
  50193. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  50194. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  50195. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  50196. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  50197. a[4] = pPager->eState;
  50198. a[5] = pPager->errCode;
  50199. a[6] = pPager->aStat[PAGER_STAT_HIT];
  50200. a[7] = pPager->aStat[PAGER_STAT_MISS];
  50201. a[8] = 0; /* Used to be pPager->nOvfl */
  50202. a[9] = pPager->nRead;
  50203. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  50204. return a;
  50205. }
  50206. #endif
  50207. /*
  50208. ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
  50209. ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
  50210. ** current cache hit or miss count, according to the value of eStat. If the
  50211. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  50212. ** returning.
  50213. */
  50214. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  50215. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  50216. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  50217. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  50218. );
  50219. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  50220. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  50221. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
  50222. *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
  50223. if( reset ){
  50224. pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
  50225. }
  50226. }
  50227. /*
  50228. ** Return true if this is an in-memory or temp-file backed pager.
  50229. */
  50230. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  50231. return pPager->tempFile;
  50232. }
  50233. /*
  50234. ** Check that there are at least nSavepoint savepoints open. If there are
  50235. ** currently less than nSavepoints open, then open one or more savepoints
  50236. ** to make up the difference. If the number of savepoints is already
  50237. ** equal to nSavepoint, then this function is a no-op.
  50238. **
  50239. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  50240. ** occurs while opening the sub-journal file, then an IO error code is
  50241. ** returned. Otherwise, SQLITE_OK.
  50242. */
  50243. static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
  50244. int rc = SQLITE_OK; /* Return code */
  50245. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  50246. int ii; /* Iterator variable */
  50247. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  50248. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  50249. assert( assert_pager_state(pPager) );
  50250. assert( nSavepoint>nCurrent && pPager->useJournal );
  50251. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  50252. ** if the allocation fails. Otherwise, zero the new portion in case a
  50253. ** malloc failure occurs while populating it in the for(...) loop below.
  50254. */
  50255. aNew = (PagerSavepoint *)sqlite3Realloc(
  50256. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  50257. );
  50258. if( !aNew ){
  50259. return SQLITE_NOMEM_BKPT;
  50260. }
  50261. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  50262. pPager->aSavepoint = aNew;
  50263. /* Populate the PagerSavepoint structures just allocated. */
  50264. for(ii=nCurrent; ii<nSavepoint; ii++){
  50265. aNew[ii].nOrig = pPager->dbSize;
  50266. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  50267. aNew[ii].iOffset = pPager->journalOff;
  50268. }else{
  50269. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  50270. }
  50271. aNew[ii].iSubRec = pPager->nSubRec;
  50272. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  50273. if( !aNew[ii].pInSavepoint ){
  50274. return SQLITE_NOMEM_BKPT;
  50275. }
  50276. if( pagerUseWal(pPager) ){
  50277. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  50278. }
  50279. pPager->nSavepoint = ii+1;
  50280. }
  50281. assert( pPager->nSavepoint==nSavepoint );
  50282. assertTruncateConstraint(pPager);
  50283. return rc;
  50284. }
  50285. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  50286. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  50287. assert( assert_pager_state(pPager) );
  50288. if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
  50289. return pagerOpenSavepoint(pPager, nSavepoint);
  50290. }else{
  50291. return SQLITE_OK;
  50292. }
  50293. }
  50294. /*
  50295. ** This function is called to rollback or release (commit) a savepoint.
  50296. ** The savepoint to release or rollback need not be the most recently
  50297. ** created savepoint.
  50298. **
  50299. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  50300. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  50301. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  50302. ** that have occurred since the specified savepoint was created.
  50303. **
  50304. ** The savepoint to rollback or release is identified by parameter
  50305. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  50306. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  50307. ** on the most recently created savepoint. If iSavepoint is greater than
  50308. ** (Pager.nSavepoint-1), then this function is a no-op.
  50309. **
  50310. ** If a negative value is passed to this function, then the current
  50311. ** transaction is rolled back. This is different to calling
  50312. ** sqlite3PagerRollback() because this function does not terminate
  50313. ** the transaction or unlock the database, it just restores the
  50314. ** contents of the database to its original state.
  50315. **
  50316. ** In any case, all savepoints with an index greater than iSavepoint
  50317. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  50318. ** then savepoint iSavepoint is also destroyed.
  50319. **
  50320. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  50321. ** or an IO error code if an IO error occurs while rolling back a
  50322. ** savepoint. If no errors occur, SQLITE_OK is returned.
  50323. */
  50324. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  50325. int rc = pPager->errCode;
  50326. #ifdef SQLITE_ENABLE_ZIPVFS
  50327. if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
  50328. #endif
  50329. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  50330. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  50331. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  50332. int ii; /* Iterator variable */
  50333. int nNew; /* Number of remaining savepoints after this op. */
  50334. /* Figure out how many savepoints will still be active after this
  50335. ** operation. Store this value in nNew. Then free resources associated
  50336. ** with any savepoints that are destroyed by this operation.
  50337. */
  50338. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  50339. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  50340. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  50341. }
  50342. pPager->nSavepoint = nNew;
  50343. /* If this is a release of the outermost savepoint, truncate
  50344. ** the sub-journal to zero bytes in size. */
  50345. if( op==SAVEPOINT_RELEASE ){
  50346. if( nNew==0 && isOpen(pPager->sjfd) ){
  50347. /* Only truncate if it is an in-memory sub-journal. */
  50348. if( sqlite3JournalIsInMemory(pPager->sjfd) ){
  50349. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  50350. assert( rc==SQLITE_OK );
  50351. }
  50352. pPager->nSubRec = 0;
  50353. }
  50354. }
  50355. /* Else this is a rollback operation, playback the specified savepoint.
  50356. ** If this is a temp-file, it is possible that the journal file has
  50357. ** not yet been opened. In this case there have been no changes to
  50358. ** the database file, so the playback operation can be skipped.
  50359. */
  50360. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  50361. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  50362. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  50363. assert(rc!=SQLITE_DONE);
  50364. }
  50365. #ifdef SQLITE_ENABLE_ZIPVFS
  50366. /* If the cache has been modified but the savepoint cannot be rolled
  50367. ** back journal_mode=off, put the pager in the error state. This way,
  50368. ** if the VFS used by this pager includes ZipVFS, the entire transaction
  50369. ** can be rolled back at the ZipVFS level. */
  50370. else if(
  50371. pPager->journalMode==PAGER_JOURNALMODE_OFF
  50372. && pPager->eState>=PAGER_WRITER_CACHEMOD
  50373. ){
  50374. pPager->errCode = SQLITE_ABORT;
  50375. pPager->eState = PAGER_ERROR;
  50376. setGetterMethod(pPager);
  50377. }
  50378. #endif
  50379. }
  50380. return rc;
  50381. }
  50382. /*
  50383. ** Return the full pathname of the database file.
  50384. **
  50385. ** Except, if the pager is in-memory only, then return an empty string if
  50386. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  50387. ** used to report the filename to the user, for compatibility with legacy
  50388. ** behavior. But when the Btree needs to know the filename for matching to
  50389. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  50390. ** participate in shared-cache.
  50391. */
  50392. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  50393. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  50394. }
  50395. /*
  50396. ** Return the VFS structure for the pager.
  50397. */
  50398. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  50399. return pPager->pVfs;
  50400. }
  50401. /*
  50402. ** Return the file handle for the database file associated
  50403. ** with the pager. This might return NULL if the file has
  50404. ** not yet been opened.
  50405. */
  50406. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  50407. return pPager->fd;
  50408. }
  50409. /*
  50410. ** Return the file handle for the journal file (if it exists).
  50411. ** This will be either the rollback journal or the WAL file.
  50412. */
  50413. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
  50414. #if SQLITE_OMIT_WAL
  50415. return pPager->jfd;
  50416. #else
  50417. return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
  50418. #endif
  50419. }
  50420. /*
  50421. ** Return the full pathname of the journal file.
  50422. */
  50423. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  50424. return pPager->zJournal;
  50425. }
  50426. #ifdef SQLITE_HAS_CODEC
  50427. /*
  50428. ** Set or retrieve the codec for this pager
  50429. */
  50430. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  50431. Pager *pPager,
  50432. void *(*xCodec)(void*,void*,Pgno,int),
  50433. void (*xCodecSizeChng)(void*,int,int),
  50434. void (*xCodecFree)(void*),
  50435. void *pCodec
  50436. ){
  50437. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  50438. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  50439. pPager->xCodecSizeChng = xCodecSizeChng;
  50440. pPager->xCodecFree = xCodecFree;
  50441. pPager->pCodec = pCodec;
  50442. setGetterMethod(pPager);
  50443. pagerReportSize(pPager);
  50444. }
  50445. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  50446. return pPager->pCodec;
  50447. }
  50448. /*
  50449. ** This function is called by the wal module when writing page content
  50450. ** into the log file.
  50451. **
  50452. ** This function returns a pointer to a buffer containing the encrypted
  50453. ** page content. If a malloc fails, this function may return NULL.
  50454. */
  50455. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  50456. void *aData = 0;
  50457. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  50458. return aData;
  50459. }
  50460. /*
  50461. ** Return the current pager state
  50462. */
  50463. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  50464. return pPager->eState;
  50465. }
  50466. #endif /* SQLITE_HAS_CODEC */
  50467. #ifndef SQLITE_OMIT_AUTOVACUUM
  50468. /*
  50469. ** Move the page pPg to location pgno in the file.
  50470. **
  50471. ** There must be no references to the page previously located at
  50472. ** pgno (which we call pPgOld) though that page is allowed to be
  50473. ** in cache. If the page previously located at pgno is not already
  50474. ** in the rollback journal, it is not put there by by this routine.
  50475. **
  50476. ** References to the page pPg remain valid. Updating any
  50477. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  50478. ** allocated along with the page) is the responsibility of the caller.
  50479. **
  50480. ** A transaction must be active when this routine is called. It used to be
  50481. ** required that a statement transaction was not active, but this restriction
  50482. ** has been removed (CREATE INDEX needs to move a page when a statement
  50483. ** transaction is active).
  50484. **
  50485. ** If the fourth argument, isCommit, is non-zero, then this page is being
  50486. ** moved as part of a database reorganization just before the transaction
  50487. ** is being committed. In this case, it is guaranteed that the database page
  50488. ** pPg refers to will not be written to again within this transaction.
  50489. **
  50490. ** This function may return SQLITE_NOMEM or an IO error code if an error
  50491. ** occurs. Otherwise, it returns SQLITE_OK.
  50492. */
  50493. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  50494. PgHdr *pPgOld; /* The page being overwritten. */
  50495. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  50496. int rc; /* Return code */
  50497. Pgno origPgno; /* The original page number */
  50498. assert( pPg->nRef>0 );
  50499. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  50500. || pPager->eState==PAGER_WRITER_DBMOD
  50501. );
  50502. assert( assert_pager_state(pPager) );
  50503. /* In order to be able to rollback, an in-memory database must journal
  50504. ** the page we are moving from.
  50505. */
  50506. assert( pPager->tempFile || !MEMDB );
  50507. if( pPager->tempFile ){
  50508. rc = sqlite3PagerWrite(pPg);
  50509. if( rc ) return rc;
  50510. }
  50511. /* If the page being moved is dirty and has not been saved by the latest
  50512. ** savepoint, then save the current contents of the page into the
  50513. ** sub-journal now. This is required to handle the following scenario:
  50514. **
  50515. ** BEGIN;
  50516. ** <journal page X, then modify it in memory>
  50517. ** SAVEPOINT one;
  50518. ** <Move page X to location Y>
  50519. ** ROLLBACK TO one;
  50520. **
  50521. ** If page X were not written to the sub-journal here, it would not
  50522. ** be possible to restore its contents when the "ROLLBACK TO one"
  50523. ** statement were is processed.
  50524. **
  50525. ** subjournalPage() may need to allocate space to store pPg->pgno into
  50526. ** one or more savepoint bitvecs. This is the reason this function
  50527. ** may return SQLITE_NOMEM.
  50528. */
  50529. if( (pPg->flags & PGHDR_DIRTY)!=0
  50530. && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
  50531. ){
  50532. return rc;
  50533. }
  50534. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  50535. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  50536. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  50537. /* If the journal needs to be sync()ed before page pPg->pgno can
  50538. ** be written to, store pPg->pgno in local variable needSyncPgno.
  50539. **
  50540. ** If the isCommit flag is set, there is no need to remember that
  50541. ** the journal needs to be sync()ed before database page pPg->pgno
  50542. ** can be written to. The caller has already promised not to write to it.
  50543. */
  50544. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  50545. needSyncPgno = pPg->pgno;
  50546. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  50547. pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
  50548. assert( pPg->flags&PGHDR_DIRTY );
  50549. }
  50550. /* If the cache contains a page with page-number pgno, remove it
  50551. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  50552. ** page pgno before the 'move' operation, it needs to be retained
  50553. ** for the page moved there.
  50554. */
  50555. pPg->flags &= ~PGHDR_NEED_SYNC;
  50556. pPgOld = sqlite3PagerLookup(pPager, pgno);
  50557. assert( !pPgOld || pPgOld->nRef==1 );
  50558. if( pPgOld ){
  50559. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  50560. if( pPager->tempFile ){
  50561. /* Do not discard pages from an in-memory database since we might
  50562. ** need to rollback later. Just move the page out of the way. */
  50563. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  50564. }else{
  50565. sqlite3PcacheDrop(pPgOld);
  50566. }
  50567. }
  50568. origPgno = pPg->pgno;
  50569. sqlite3PcacheMove(pPg, pgno);
  50570. sqlite3PcacheMakeDirty(pPg);
  50571. /* For an in-memory database, make sure the original page continues
  50572. ** to exist, in case the transaction needs to roll back. Use pPgOld
  50573. ** as the original page since it has already been allocated.
  50574. */
  50575. if( pPager->tempFile && pPgOld ){
  50576. sqlite3PcacheMove(pPgOld, origPgno);
  50577. sqlite3PagerUnrefNotNull(pPgOld);
  50578. }
  50579. if( needSyncPgno ){
  50580. /* If needSyncPgno is non-zero, then the journal file needs to be
  50581. ** sync()ed before any data is written to database file page needSyncPgno.
  50582. ** Currently, no such page exists in the page-cache and the
  50583. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  50584. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  50585. ** flag.
  50586. **
  50587. ** If the attempt to load the page into the page-cache fails, (due
  50588. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  50589. ** array. Otherwise, if the page is loaded and written again in
  50590. ** this transaction, it may be written to the database file before
  50591. ** it is synced into the journal file. This way, it may end up in
  50592. ** the journal file twice, but that is not a problem.
  50593. */
  50594. PgHdr *pPgHdr;
  50595. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
  50596. if( rc!=SQLITE_OK ){
  50597. if( needSyncPgno<=pPager->dbOrigSize ){
  50598. assert( pPager->pTmpSpace!=0 );
  50599. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  50600. }
  50601. return rc;
  50602. }
  50603. pPgHdr->flags |= PGHDR_NEED_SYNC;
  50604. sqlite3PcacheMakeDirty(pPgHdr);
  50605. sqlite3PagerUnrefNotNull(pPgHdr);
  50606. }
  50607. return SQLITE_OK;
  50608. }
  50609. #endif
  50610. /*
  50611. ** The page handle passed as the first argument refers to a dirty page
  50612. ** with a page number other than iNew. This function changes the page's
  50613. ** page number to iNew and sets the value of the PgHdr.flags field to
  50614. ** the value passed as the third parameter.
  50615. */
  50616. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
  50617. assert( pPg->pgno!=iNew );
  50618. pPg->flags = flags;
  50619. sqlite3PcacheMove(pPg, iNew);
  50620. }
  50621. /*
  50622. ** Return a pointer to the data for the specified page.
  50623. */
  50624. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  50625. assert( pPg->nRef>0 || pPg->pPager->memDb );
  50626. return pPg->pData;
  50627. }
  50628. /*
  50629. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  50630. ** allocated along with the specified page.
  50631. */
  50632. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  50633. return pPg->pExtra;
  50634. }
  50635. /*
  50636. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  50637. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  50638. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  50639. ** the locking-mode is set to the value specified.
  50640. **
  50641. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  50642. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  50643. ** locking-mode.
  50644. */
  50645. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  50646. assert( eMode==PAGER_LOCKINGMODE_QUERY
  50647. || eMode==PAGER_LOCKINGMODE_NORMAL
  50648. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  50649. assert( PAGER_LOCKINGMODE_QUERY<0 );
  50650. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  50651. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  50652. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  50653. pPager->exclusiveMode = (u8)eMode;
  50654. }
  50655. return (int)pPager->exclusiveMode;
  50656. }
  50657. /*
  50658. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  50659. **
  50660. ** PAGER_JOURNALMODE_DELETE
  50661. ** PAGER_JOURNALMODE_TRUNCATE
  50662. ** PAGER_JOURNALMODE_PERSIST
  50663. ** PAGER_JOURNALMODE_OFF
  50664. ** PAGER_JOURNALMODE_MEMORY
  50665. ** PAGER_JOURNALMODE_WAL
  50666. **
  50667. ** The journalmode is set to the value specified if the change is allowed.
  50668. ** The change may be disallowed for the following reasons:
  50669. **
  50670. ** * An in-memory database can only have its journal_mode set to _OFF
  50671. ** or _MEMORY.
  50672. **
  50673. ** * Temporary databases cannot have _WAL journalmode.
  50674. **
  50675. ** The returned indicate the current (possibly updated) journal-mode.
  50676. */
  50677. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  50678. u8 eOld = pPager->journalMode; /* Prior journalmode */
  50679. #ifdef SQLITE_DEBUG
  50680. /* The print_pager_state() routine is intended to be used by the debugger
  50681. ** only. We invoke it once here to suppress a compiler warning. */
  50682. print_pager_state(pPager);
  50683. #endif
  50684. /* The eMode parameter is always valid */
  50685. assert( eMode==PAGER_JOURNALMODE_DELETE
  50686. || eMode==PAGER_JOURNALMODE_TRUNCATE
  50687. || eMode==PAGER_JOURNALMODE_PERSIST
  50688. || eMode==PAGER_JOURNALMODE_OFF
  50689. || eMode==PAGER_JOURNALMODE_WAL
  50690. || eMode==PAGER_JOURNALMODE_MEMORY );
  50691. /* This routine is only called from the OP_JournalMode opcode, and
  50692. ** the logic there will never allow a temporary file to be changed
  50693. ** to WAL mode.
  50694. */
  50695. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  50696. /* Do allow the journalmode of an in-memory database to be set to
  50697. ** anything other than MEMORY or OFF
  50698. */
  50699. if( MEMDB ){
  50700. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  50701. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  50702. eMode = eOld;
  50703. }
  50704. }
  50705. if( eMode!=eOld ){
  50706. /* Change the journal mode. */
  50707. assert( pPager->eState!=PAGER_ERROR );
  50708. pPager->journalMode = (u8)eMode;
  50709. /* When transistioning from TRUNCATE or PERSIST to any other journal
  50710. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  50711. ** delete the journal file.
  50712. */
  50713. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  50714. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  50715. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  50716. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  50717. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  50718. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  50719. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  50720. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  50721. /* In this case we would like to delete the journal file. If it is
  50722. ** not possible, then that is not a problem. Deleting the journal file
  50723. ** here is an optimization only.
  50724. **
  50725. ** Before deleting the journal file, obtain a RESERVED lock on the
  50726. ** database file. This ensures that the journal file is not deleted
  50727. ** while it is in use by some other client.
  50728. */
  50729. sqlite3OsClose(pPager->jfd);
  50730. if( pPager->eLock>=RESERVED_LOCK ){
  50731. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  50732. }else{
  50733. int rc = SQLITE_OK;
  50734. int state = pPager->eState;
  50735. assert( state==PAGER_OPEN || state==PAGER_READER );
  50736. if( state==PAGER_OPEN ){
  50737. rc = sqlite3PagerSharedLock(pPager);
  50738. }
  50739. if( pPager->eState==PAGER_READER ){
  50740. assert( rc==SQLITE_OK );
  50741. rc = pagerLockDb(pPager, RESERVED_LOCK);
  50742. }
  50743. if( rc==SQLITE_OK ){
  50744. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  50745. }
  50746. if( rc==SQLITE_OK && state==PAGER_READER ){
  50747. pagerUnlockDb(pPager, SHARED_LOCK);
  50748. }else if( state==PAGER_OPEN ){
  50749. pager_unlock(pPager);
  50750. }
  50751. assert( state==pPager->eState );
  50752. }
  50753. }else if( eMode==PAGER_JOURNALMODE_OFF ){
  50754. sqlite3OsClose(pPager->jfd);
  50755. }
  50756. }
  50757. /* Return the new journal mode */
  50758. return (int)pPager->journalMode;
  50759. }
  50760. /*
  50761. ** Return the current journal mode.
  50762. */
  50763. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  50764. return (int)pPager->journalMode;
  50765. }
  50766. /*
  50767. ** Return TRUE if the pager is in a state where it is OK to change the
  50768. ** journalmode. Journalmode changes can only happen when the database
  50769. ** is unmodified.
  50770. */
  50771. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  50772. assert( assert_pager_state(pPager) );
  50773. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  50774. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  50775. return 1;
  50776. }
  50777. /*
  50778. ** Get/set the size-limit used for persistent journal files.
  50779. **
  50780. ** Setting the size limit to -1 means no limit is enforced.
  50781. ** An attempt to set a limit smaller than -1 is a no-op.
  50782. */
  50783. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  50784. if( iLimit>=-1 ){
  50785. pPager->journalSizeLimit = iLimit;
  50786. sqlite3WalLimit(pPager->pWal, iLimit);
  50787. }
  50788. return pPager->journalSizeLimit;
  50789. }
  50790. /*
  50791. ** Return a pointer to the pPager->pBackup variable. The backup module
  50792. ** in backup.c maintains the content of this variable. This module
  50793. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  50794. ** sqlite3BackupUpdate() only.
  50795. */
  50796. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  50797. return &pPager->pBackup;
  50798. }
  50799. #ifndef SQLITE_OMIT_VACUUM
  50800. /*
  50801. ** Unless this is an in-memory or temporary database, clear the pager cache.
  50802. */
  50803. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  50804. assert( MEMDB==0 || pPager->tempFile );
  50805. if( pPager->tempFile==0 ) pager_reset(pPager);
  50806. }
  50807. #endif
  50808. #ifndef SQLITE_OMIT_WAL
  50809. /*
  50810. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  50811. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  50812. ** or wal_blocking_checkpoint() API functions.
  50813. **
  50814. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  50815. */
  50816. SQLITE_PRIVATE int sqlite3PagerCheckpoint(
  50817. Pager *pPager, /* Checkpoint on this pager */
  50818. sqlite3 *db, /* Db handle used to check for interrupts */
  50819. int eMode, /* Type of checkpoint */
  50820. int *pnLog, /* OUT: Final number of frames in log */
  50821. int *pnCkpt /* OUT: Final number of checkpointed frames */
  50822. ){
  50823. int rc = SQLITE_OK;
  50824. if( pPager->pWal ){
  50825. rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
  50826. (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
  50827. pPager->pBusyHandlerArg,
  50828. pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  50829. pnLog, pnCkpt
  50830. );
  50831. }
  50832. return rc;
  50833. }
  50834. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  50835. return sqlite3WalCallback(pPager->pWal);
  50836. }
  50837. /*
  50838. ** Return true if the underlying VFS for the given pager supports the
  50839. ** primitives necessary for write-ahead logging.
  50840. */
  50841. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  50842. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  50843. if( pPager->noLock ) return 0;
  50844. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  50845. }
  50846. /*
  50847. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  50848. ** is obtained instead, immediately release it.
  50849. */
  50850. static int pagerExclusiveLock(Pager *pPager){
  50851. int rc; /* Return code */
  50852. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  50853. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  50854. if( rc!=SQLITE_OK ){
  50855. /* If the attempt to grab the exclusive lock failed, release the
  50856. ** pending lock that may have been obtained instead. */
  50857. pagerUnlockDb(pPager, SHARED_LOCK);
  50858. }
  50859. return rc;
  50860. }
  50861. /*
  50862. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  50863. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  50864. ** lock on the database file and use heap-memory to store the wal-index
  50865. ** in. Otherwise, use the normal shared-memory.
  50866. */
  50867. static int pagerOpenWal(Pager *pPager){
  50868. int rc = SQLITE_OK;
  50869. assert( pPager->pWal==0 && pPager->tempFile==0 );
  50870. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  50871. /* If the pager is already in exclusive-mode, the WAL module will use
  50872. ** heap-memory for the wal-index instead of the VFS shared-memory
  50873. ** implementation. Take the exclusive lock now, before opening the WAL
  50874. ** file, to make sure this is safe.
  50875. */
  50876. if( pPager->exclusiveMode ){
  50877. rc = pagerExclusiveLock(pPager);
  50878. }
  50879. /* Open the connection to the log file. If this operation fails,
  50880. ** (e.g. due to malloc() failure), return an error code.
  50881. */
  50882. if( rc==SQLITE_OK ){
  50883. rc = sqlite3WalOpen(pPager->pVfs,
  50884. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  50885. pPager->journalSizeLimit, &pPager->pWal
  50886. );
  50887. }
  50888. pagerFixMaplimit(pPager);
  50889. return rc;
  50890. }
  50891. /*
  50892. ** The caller must be holding a SHARED lock on the database file to call
  50893. ** this function.
  50894. **
  50895. ** If the pager passed as the first argument is open on a real database
  50896. ** file (not a temp file or an in-memory database), and the WAL file
  50897. ** is not already open, make an attempt to open it now. If successful,
  50898. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  50899. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  50900. ** not modified in either case.
  50901. **
  50902. ** If the pager is open on a temp-file (or in-memory database), or if
  50903. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  50904. ** without doing anything.
  50905. */
  50906. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  50907. Pager *pPager, /* Pager object */
  50908. int *pbOpen /* OUT: Set to true if call is a no-op */
  50909. ){
  50910. int rc = SQLITE_OK; /* Return code */
  50911. assert( assert_pager_state(pPager) );
  50912. assert( pPager->eState==PAGER_OPEN || pbOpen );
  50913. assert( pPager->eState==PAGER_READER || !pbOpen );
  50914. assert( pbOpen==0 || *pbOpen==0 );
  50915. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  50916. if( !pPager->tempFile && !pPager->pWal ){
  50917. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  50918. /* Close any rollback journal previously open */
  50919. sqlite3OsClose(pPager->jfd);
  50920. rc = pagerOpenWal(pPager);
  50921. if( rc==SQLITE_OK ){
  50922. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  50923. pPager->eState = PAGER_OPEN;
  50924. }
  50925. }else{
  50926. *pbOpen = 1;
  50927. }
  50928. return rc;
  50929. }
  50930. /*
  50931. ** This function is called to close the connection to the log file prior
  50932. ** to switching from WAL to rollback mode.
  50933. **
  50934. ** Before closing the log file, this function attempts to take an
  50935. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  50936. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  50937. ** If successful, the EXCLUSIVE lock is not released before returning.
  50938. */
  50939. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
  50940. int rc = SQLITE_OK;
  50941. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  50942. /* If the log file is not already open, but does exist in the file-system,
  50943. ** it may need to be checkpointed before the connection can switch to
  50944. ** rollback mode. Open it now so this can happen.
  50945. */
  50946. if( !pPager->pWal ){
  50947. int logexists = 0;
  50948. rc = pagerLockDb(pPager, SHARED_LOCK);
  50949. if( rc==SQLITE_OK ){
  50950. rc = sqlite3OsAccess(
  50951. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  50952. );
  50953. }
  50954. if( rc==SQLITE_OK && logexists ){
  50955. rc = pagerOpenWal(pPager);
  50956. }
  50957. }
  50958. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  50959. ** the database file, the log and log-summary files will be deleted.
  50960. */
  50961. if( rc==SQLITE_OK && pPager->pWal ){
  50962. rc = pagerExclusiveLock(pPager);
  50963. if( rc==SQLITE_OK ){
  50964. rc = sqlite3WalClose(pPager->pWal, db, pPager->ckptSyncFlags,
  50965. pPager->pageSize, (u8*)pPager->pTmpSpace);
  50966. pPager->pWal = 0;
  50967. pagerFixMaplimit(pPager);
  50968. if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  50969. }
  50970. }
  50971. return rc;
  50972. }
  50973. #ifdef SQLITE_ENABLE_SNAPSHOT
  50974. /*
  50975. ** If this is a WAL database, obtain a snapshot handle for the snapshot
  50976. ** currently open. Otherwise, return an error.
  50977. */
  50978. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
  50979. int rc = SQLITE_ERROR;
  50980. if( pPager->pWal ){
  50981. rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
  50982. }
  50983. return rc;
  50984. }
  50985. /*
  50986. ** If this is a WAL database, store a pointer to pSnapshot. Next time a
  50987. ** read transaction is opened, attempt to read from the snapshot it
  50988. ** identifies. If this is not a WAL database, return an error.
  50989. */
  50990. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
  50991. int rc = SQLITE_OK;
  50992. if( pPager->pWal ){
  50993. sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
  50994. }else{
  50995. rc = SQLITE_ERROR;
  50996. }
  50997. return rc;
  50998. }
  50999. /*
  51000. ** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this
  51001. ** is not a WAL database, return an error.
  51002. */
  51003. SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
  51004. int rc;
  51005. if( pPager->pWal ){
  51006. rc = sqlite3WalSnapshotRecover(pPager->pWal);
  51007. }else{
  51008. rc = SQLITE_ERROR;
  51009. }
  51010. return rc;
  51011. }
  51012. #endif /* SQLITE_ENABLE_SNAPSHOT */
  51013. #endif /* !SQLITE_OMIT_WAL */
  51014. #ifdef SQLITE_ENABLE_ZIPVFS
  51015. /*
  51016. ** A read-lock must be held on the pager when this function is called. If
  51017. ** the pager is in WAL mode and the WAL file currently contains one or more
  51018. ** frames, return the size in bytes of the page images stored within the
  51019. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  51020. ** is empty, return 0.
  51021. */
  51022. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  51023. assert( pPager->eState>=PAGER_READER );
  51024. return sqlite3WalFramesize(pPager->pWal);
  51025. }
  51026. #endif
  51027. #endif /* SQLITE_OMIT_DISKIO */
  51028. /************** End of pager.c ***********************************************/
  51029. /************** Begin file wal.c *********************************************/
  51030. /*
  51031. ** 2010 February 1
  51032. **
  51033. ** The author disclaims copyright to this source code. In place of
  51034. ** a legal notice, here is a blessing:
  51035. **
  51036. ** May you do good and not evil.
  51037. ** May you find forgiveness for yourself and forgive others.
  51038. ** May you share freely, never taking more than you give.
  51039. **
  51040. *************************************************************************
  51041. **
  51042. ** This file contains the implementation of a write-ahead log (WAL) used in
  51043. ** "journal_mode=WAL" mode.
  51044. **
  51045. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  51046. **
  51047. ** A WAL file consists of a header followed by zero or more "frames".
  51048. ** Each frame records the revised content of a single page from the
  51049. ** database file. All changes to the database are recorded by writing
  51050. ** frames into the WAL. Transactions commit when a frame is written that
  51051. ** contains a commit marker. A single WAL can and usually does record
  51052. ** multiple transactions. Periodically, the content of the WAL is
  51053. ** transferred back into the database file in an operation called a
  51054. ** "checkpoint".
  51055. **
  51056. ** A single WAL file can be used multiple times. In other words, the
  51057. ** WAL can fill up with frames and then be checkpointed and then new
  51058. ** frames can overwrite the old ones. A WAL always grows from beginning
  51059. ** toward the end. Checksums and counters attached to each frame are
  51060. ** used to determine which frames within the WAL are valid and which
  51061. ** are leftovers from prior checkpoints.
  51062. **
  51063. ** The WAL header is 32 bytes in size and consists of the following eight
  51064. ** big-endian 32-bit unsigned integer values:
  51065. **
  51066. ** 0: Magic number. 0x377f0682 or 0x377f0683
  51067. ** 4: File format version. Currently 3007000
  51068. ** 8: Database page size. Example: 1024
  51069. ** 12: Checkpoint sequence number
  51070. ** 16: Salt-1, random integer incremented with each checkpoint
  51071. ** 20: Salt-2, a different random integer changing with each ckpt
  51072. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  51073. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  51074. **
  51075. ** Immediately following the wal-header are zero or more frames. Each
  51076. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  51077. ** of page data. The frame-header is six big-endian 32-bit unsigned
  51078. ** integer values, as follows:
  51079. **
  51080. ** 0: Page number.
  51081. ** 4: For commit records, the size of the database image in pages
  51082. ** after the commit. For all other records, zero.
  51083. ** 8: Salt-1 (copied from the header)
  51084. ** 12: Salt-2 (copied from the header)
  51085. ** 16: Checksum-1.
  51086. ** 20: Checksum-2.
  51087. **
  51088. ** A frame is considered valid if and only if the following conditions are
  51089. ** true:
  51090. **
  51091. ** (1) The salt-1 and salt-2 values in the frame-header match
  51092. ** salt values in the wal-header
  51093. **
  51094. ** (2) The checksum values in the final 8 bytes of the frame-header
  51095. ** exactly match the checksum computed consecutively on the
  51096. ** WAL header and the first 8 bytes and the content of all frames
  51097. ** up to and including the current frame.
  51098. **
  51099. ** The checksum is computed using 32-bit big-endian integers if the
  51100. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  51101. ** is computed using little-endian if the magic number is 0x377f0682.
  51102. ** The checksum values are always stored in the frame header in a
  51103. ** big-endian format regardless of which byte order is used to compute
  51104. ** the checksum. The checksum is computed by interpreting the input as
  51105. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  51106. ** algorithm used for the checksum is as follows:
  51107. **
  51108. ** for i from 0 to n-1 step 2:
  51109. ** s0 += x[i] + s1;
  51110. ** s1 += x[i+1] + s0;
  51111. ** endfor
  51112. **
  51113. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  51114. ** in reverse order (the largest fibonacci weight occurs on the first element
  51115. ** of the sequence being summed.) The s1 value spans all 32-bit
  51116. ** terms of the sequence whereas s0 omits the final term.
  51117. **
  51118. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  51119. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  51120. ** The VFS.xSync operations serve as write barriers - all writes launched
  51121. ** before the xSync must complete before any write that launches after the
  51122. ** xSync begins.
  51123. **
  51124. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  51125. ** value is randomized. This prevents old and new frames in the WAL from
  51126. ** being considered valid at the same time and being checkpointing together
  51127. ** following a crash.
  51128. **
  51129. ** READER ALGORITHM
  51130. **
  51131. ** To read a page from the database (call it page number P), a reader
  51132. ** first checks the WAL to see if it contains page P. If so, then the
  51133. ** last valid instance of page P that is a followed by a commit frame
  51134. ** or is a commit frame itself becomes the value read. If the WAL
  51135. ** contains no copies of page P that are valid and which are a commit
  51136. ** frame or are followed by a commit frame, then page P is read from
  51137. ** the database file.
  51138. **
  51139. ** To start a read transaction, the reader records the index of the last
  51140. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  51141. ** for all subsequent read operations. New transactions can be appended
  51142. ** to the WAL, but as long as the reader uses its original mxFrame value
  51143. ** and ignores the newly appended content, it will see a consistent snapshot
  51144. ** of the database from a single point in time. This technique allows
  51145. ** multiple concurrent readers to view different versions of the database
  51146. ** content simultaneously.
  51147. **
  51148. ** The reader algorithm in the previous paragraphs works correctly, but
  51149. ** because frames for page P can appear anywhere within the WAL, the
  51150. ** reader has to scan the entire WAL looking for page P frames. If the
  51151. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  51152. ** and read performance suffers. To overcome this problem, a separate
  51153. ** data structure called the wal-index is maintained to expedite the
  51154. ** search for frames of a particular page.
  51155. **
  51156. ** WAL-INDEX FORMAT
  51157. **
  51158. ** Conceptually, the wal-index is shared memory, though VFS implementations
  51159. ** might choose to implement the wal-index using a mmapped file. Because
  51160. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  51161. ** on a network filesystem. All users of the database must be able to
  51162. ** share memory.
  51163. **
  51164. ** The wal-index is transient. After a crash, the wal-index can (and should
  51165. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  51166. ** to either truncate or zero the header of the wal-index when the last
  51167. ** connection to it closes. Because the wal-index is transient, it can
  51168. ** use an architecture-specific format; it does not have to be cross-platform.
  51169. ** Hence, unlike the database and WAL file formats which store all values
  51170. ** as big endian, the wal-index can store multi-byte values in the native
  51171. ** byte order of the host computer.
  51172. **
  51173. ** The purpose of the wal-index is to answer this question quickly: Given
  51174. ** a page number P and a maximum frame index M, return the index of the
  51175. ** last frame in the wal before frame M for page P in the WAL, or return
  51176. ** NULL if there are no frames for page P in the WAL prior to M.
  51177. **
  51178. ** The wal-index consists of a header region, followed by an one or
  51179. ** more index blocks.
  51180. **
  51181. ** The wal-index header contains the total number of frames within the WAL
  51182. ** in the mxFrame field.
  51183. **
  51184. ** Each index block except for the first contains information on
  51185. ** HASHTABLE_NPAGE frames. The first index block contains information on
  51186. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  51187. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  51188. ** first index block are the same size as all other index blocks in the
  51189. ** wal-index.
  51190. **
  51191. ** Each index block contains two sections, a page-mapping that contains the
  51192. ** database page number associated with each wal frame, and a hash-table
  51193. ** that allows readers to query an index block for a specific page number.
  51194. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  51195. ** for the first index block) 32-bit page numbers. The first entry in the
  51196. ** first index-block contains the database page number corresponding to the
  51197. ** first frame in the WAL file. The first entry in the second index block
  51198. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  51199. ** the log, and so on.
  51200. **
  51201. ** The last index block in a wal-index usually contains less than the full
  51202. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  51203. ** depending on the contents of the WAL file. This does not change the
  51204. ** allocated size of the page-mapping array - the page-mapping array merely
  51205. ** contains unused entries.
  51206. **
  51207. ** Even without using the hash table, the last frame for page P
  51208. ** can be found by scanning the page-mapping sections of each index block
  51209. ** starting with the last index block and moving toward the first, and
  51210. ** within each index block, starting at the end and moving toward the
  51211. ** beginning. The first entry that equals P corresponds to the frame
  51212. ** holding the content for that page.
  51213. **
  51214. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  51215. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  51216. ** hash table for each page number in the mapping section, so the hash
  51217. ** table is never more than half full. The expected number of collisions
  51218. ** prior to finding a match is 1. Each entry of the hash table is an
  51219. ** 1-based index of an entry in the mapping section of the same
  51220. ** index block. Let K be the 1-based index of the largest entry in
  51221. ** the mapping section. (For index blocks other than the last, K will
  51222. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  51223. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  51224. ** contain a value of 0.
  51225. **
  51226. ** To look for page P in the hash table, first compute a hash iKey on
  51227. ** P as follows:
  51228. **
  51229. ** iKey = (P * 383) % HASHTABLE_NSLOT
  51230. **
  51231. ** Then start scanning entries of the hash table, starting with iKey
  51232. ** (wrapping around to the beginning when the end of the hash table is
  51233. ** reached) until an unused hash slot is found. Let the first unused slot
  51234. ** be at index iUnused. (iUnused might be less than iKey if there was
  51235. ** wrap-around.) Because the hash table is never more than half full,
  51236. ** the search is guaranteed to eventually hit an unused entry. Let
  51237. ** iMax be the value between iKey and iUnused, closest to iUnused,
  51238. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  51239. ** no hash slot such that aHash[i]==p) then page P is not in the
  51240. ** current index block. Otherwise the iMax-th mapping entry of the
  51241. ** current index block corresponds to the last entry that references
  51242. ** page P.
  51243. **
  51244. ** A hash search begins with the last index block and moves toward the
  51245. ** first index block, looking for entries corresponding to page P. On
  51246. ** average, only two or three slots in each index block need to be
  51247. ** examined in order to either find the last entry for page P, or to
  51248. ** establish that no such entry exists in the block. Each index block
  51249. ** holds over 4000 entries. So two or three index blocks are sufficient
  51250. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  51251. ** comparisons (on average) suffice to either locate a frame in the
  51252. ** WAL or to establish that the frame does not exist in the WAL. This
  51253. ** is much faster than scanning the entire 10MB WAL.
  51254. **
  51255. ** Note that entries are added in order of increasing K. Hence, one
  51256. ** reader might be using some value K0 and a second reader that started
  51257. ** at a later time (after additional transactions were added to the WAL
  51258. ** and to the wal-index) might be using a different value K1, where K1>K0.
  51259. ** Both readers can use the same hash table and mapping section to get
  51260. ** the correct result. There may be entries in the hash table with
  51261. ** K>K0 but to the first reader, those entries will appear to be unused
  51262. ** slots in the hash table and so the first reader will get an answer as
  51263. ** if no values greater than K0 had ever been inserted into the hash table
  51264. ** in the first place - which is what reader one wants. Meanwhile, the
  51265. ** second reader using K1 will see additional values that were inserted
  51266. ** later, which is exactly what reader two wants.
  51267. **
  51268. ** When a rollback occurs, the value of K is decreased. Hash table entries
  51269. ** that correspond to frames greater than the new K value are removed
  51270. ** from the hash table at this point.
  51271. */
  51272. #ifndef SQLITE_OMIT_WAL
  51273. /* #include "wal.h" */
  51274. /*
  51275. ** Trace output macros
  51276. */
  51277. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  51278. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  51279. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  51280. #else
  51281. # define WALTRACE(X)
  51282. #endif
  51283. /*
  51284. ** The maximum (and only) versions of the wal and wal-index formats
  51285. ** that may be interpreted by this version of SQLite.
  51286. **
  51287. ** If a client begins recovering a WAL file and finds that (a) the checksum
  51288. ** values in the wal-header are correct and (b) the version field is not
  51289. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  51290. **
  51291. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  51292. ** checksum test is successful) and finds that the version field is not
  51293. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  51294. ** returns SQLITE_CANTOPEN.
  51295. */
  51296. #define WAL_MAX_VERSION 3007000
  51297. #define WALINDEX_MAX_VERSION 3007000
  51298. /*
  51299. ** Indices of various locking bytes. WAL_NREADER is the number
  51300. ** of available reader locks and should be at least 3. The default
  51301. ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5.
  51302. */
  51303. #define WAL_WRITE_LOCK 0
  51304. #define WAL_ALL_BUT_WRITE 1
  51305. #define WAL_CKPT_LOCK 1
  51306. #define WAL_RECOVER_LOCK 2
  51307. #define WAL_READ_LOCK(I) (3+(I))
  51308. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  51309. /* Object declarations */
  51310. typedef struct WalIndexHdr WalIndexHdr;
  51311. typedef struct WalIterator WalIterator;
  51312. typedef struct WalCkptInfo WalCkptInfo;
  51313. /*
  51314. ** The following object holds a copy of the wal-index header content.
  51315. **
  51316. ** The actual header in the wal-index consists of two copies of this
  51317. ** object followed by one instance of the WalCkptInfo object.
  51318. ** For all versions of SQLite through 3.10.0 and probably beyond,
  51319. ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
  51320. ** the total header size is 136 bytes.
  51321. **
  51322. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  51323. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  51324. ** added in 3.7.1 when support for 64K pages was added.
  51325. */
  51326. struct WalIndexHdr {
  51327. u32 iVersion; /* Wal-index version */
  51328. u32 unused; /* Unused (padding) field */
  51329. u32 iChange; /* Counter incremented each transaction */
  51330. u8 isInit; /* 1 when initialized */
  51331. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  51332. u16 szPage; /* Database page size in bytes. 1==64K */
  51333. u32 mxFrame; /* Index of last valid frame in the WAL */
  51334. u32 nPage; /* Size of database in pages */
  51335. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  51336. u32 aSalt[2]; /* Two salt values copied from WAL header */
  51337. u32 aCksum[2]; /* Checksum over all prior fields */
  51338. };
  51339. /*
  51340. ** A copy of the following object occurs in the wal-index immediately
  51341. ** following the second copy of the WalIndexHdr. This object stores
  51342. ** information used by checkpoint.
  51343. **
  51344. ** nBackfill is the number of frames in the WAL that have been written
  51345. ** back into the database. (We call the act of moving content from WAL to
  51346. ** database "backfilling".) The nBackfill number is never greater than
  51347. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  51348. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  51349. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  51350. ** mxFrame back to zero when the WAL is reset.
  51351. **
  51352. ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
  51353. ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however
  51354. ** the nBackfillAttempted is set before any backfilling is done and the
  51355. ** nBackfill is only set after all backfilling completes. So if a checkpoint
  51356. ** crashes, nBackfillAttempted might be larger than nBackfill. The
  51357. ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
  51358. **
  51359. ** The aLock[] field is a set of bytes used for locking. These bytes should
  51360. ** never be read or written.
  51361. **
  51362. ** There is one entry in aReadMark[] for each reader lock. If a reader
  51363. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  51364. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  51365. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  51366. ** a special case; its value is never used and it exists as a place-holder
  51367. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  51368. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  51369. ** directly from the database.
  51370. **
  51371. ** The value of aReadMark[K] may only be changed by a thread that
  51372. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  51373. ** aReadMark[K] cannot changed while there is a reader is using that mark
  51374. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  51375. **
  51376. ** The checkpointer may only transfer frames from WAL to database where
  51377. ** the frame numbers are less than or equal to every aReadMark[] that is
  51378. ** in use (that is, every aReadMark[j] for which there is a corresponding
  51379. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  51380. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  51381. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  51382. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  51383. ** in the WAL has been backfilled into the database) then new readers
  51384. ** will choose aReadMark[0] which has value 0 and hence such reader will
  51385. ** get all their all content directly from the database file and ignore
  51386. ** the WAL.
  51387. **
  51388. ** Writers normally append new frames to the end of the WAL. However,
  51389. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  51390. ** written back into the database) and if no readers are using the WAL
  51391. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  51392. ** the writer will first "reset" the WAL back to the beginning and start
  51393. ** writing new content beginning at frame 1.
  51394. **
  51395. ** We assume that 32-bit loads are atomic and so no locks are needed in
  51396. ** order to read from any aReadMark[] entries.
  51397. */
  51398. struct WalCkptInfo {
  51399. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  51400. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  51401. u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */
  51402. u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */
  51403. u32 notUsed0; /* Available for future enhancements */
  51404. };
  51405. #define READMARK_NOT_USED 0xffffffff
  51406. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  51407. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  51408. ** only support mandatory file-locks, we do not read or write data
  51409. ** from the region of the file on which locks are applied.
  51410. */
  51411. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
  51412. #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
  51413. /* Size of header before each frame in wal */
  51414. #define WAL_FRAME_HDRSIZE 24
  51415. /* Size of write ahead log header, including checksum. */
  51416. /* #define WAL_HDRSIZE 24 */
  51417. #define WAL_HDRSIZE 32
  51418. /* WAL magic value. Either this value, or the same value with the least
  51419. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  51420. ** big-endian format in the first 4 bytes of a WAL file.
  51421. **
  51422. ** If the LSB is set, then the checksums for each frame within the WAL
  51423. ** file are calculated by treating all data as an array of 32-bit
  51424. ** big-endian words. Otherwise, they are calculated by interpreting
  51425. ** all data as 32-bit little-endian words.
  51426. */
  51427. #define WAL_MAGIC 0x377f0682
  51428. /*
  51429. ** Return the offset of frame iFrame in the write-ahead log file,
  51430. ** assuming a database page size of szPage bytes. The offset returned
  51431. ** is to the start of the write-ahead log frame-header.
  51432. */
  51433. #define walFrameOffset(iFrame, szPage) ( \
  51434. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  51435. )
  51436. /*
  51437. ** An open write-ahead log file is represented by an instance of the
  51438. ** following object.
  51439. */
  51440. struct Wal {
  51441. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  51442. sqlite3_file *pDbFd; /* File handle for the database file */
  51443. sqlite3_file *pWalFd; /* File handle for WAL file */
  51444. u32 iCallback; /* Value to pass to log callback (or 0) */
  51445. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  51446. int nWiData; /* Size of array apWiData */
  51447. int szFirstBlock; /* Size of first block written to WAL file */
  51448. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  51449. u32 szPage; /* Database page size */
  51450. i16 readLock; /* Which read lock is being held. -1 for none */
  51451. u8 syncFlags; /* Flags to use to sync header writes */
  51452. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  51453. u8 writeLock; /* True if in a write transaction */
  51454. u8 ckptLock; /* True if holding a checkpoint lock */
  51455. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  51456. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  51457. u8 syncHeader; /* Fsync the WAL header if true */
  51458. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  51459. WalIndexHdr hdr; /* Wal-index header for current transaction */
  51460. u32 minFrame; /* Ignore wal frames before this one */
  51461. u32 iReCksum; /* On commit, recalculate checksums from here */
  51462. const char *zWalName; /* Name of WAL file */
  51463. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  51464. #ifdef SQLITE_DEBUG
  51465. u8 lockError; /* True if a locking error has occurred */
  51466. #endif
  51467. #ifdef SQLITE_ENABLE_SNAPSHOT
  51468. WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */
  51469. #endif
  51470. };
  51471. /*
  51472. ** Candidate values for Wal.exclusiveMode.
  51473. */
  51474. #define WAL_NORMAL_MODE 0
  51475. #define WAL_EXCLUSIVE_MODE 1
  51476. #define WAL_HEAPMEMORY_MODE 2
  51477. /*
  51478. ** Possible values for WAL.readOnly
  51479. */
  51480. #define WAL_RDWR 0 /* Normal read/write connection */
  51481. #define WAL_RDONLY 1 /* The WAL file is readonly */
  51482. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  51483. /*
  51484. ** Each page of the wal-index mapping contains a hash-table made up of
  51485. ** an array of HASHTABLE_NSLOT elements of the following type.
  51486. */
  51487. typedef u16 ht_slot;
  51488. /*
  51489. ** This structure is used to implement an iterator that loops through
  51490. ** all frames in the WAL in database page order. Where two or more frames
  51491. ** correspond to the same database page, the iterator visits only the
  51492. ** frame most recently written to the WAL (in other words, the frame with
  51493. ** the largest index).
  51494. **
  51495. ** The internals of this structure are only accessed by:
  51496. **
  51497. ** walIteratorInit() - Create a new iterator,
  51498. ** walIteratorNext() - Step an iterator,
  51499. ** walIteratorFree() - Free an iterator.
  51500. **
  51501. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  51502. */
  51503. struct WalIterator {
  51504. int iPrior; /* Last result returned from the iterator */
  51505. int nSegment; /* Number of entries in aSegment[] */
  51506. struct WalSegment {
  51507. int iNext; /* Next slot in aIndex[] not yet returned */
  51508. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  51509. u32 *aPgno; /* Array of page numbers. */
  51510. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  51511. int iZero; /* Frame number associated with aPgno[0] */
  51512. } aSegment[1]; /* One for every 32KB page in the wal-index */
  51513. };
  51514. /*
  51515. ** Define the parameters of the hash tables in the wal-index file. There
  51516. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  51517. ** wal-index.
  51518. **
  51519. ** Changing any of these constants will alter the wal-index format and
  51520. ** create incompatibilities.
  51521. */
  51522. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  51523. #define HASHTABLE_HASH_1 383 /* Should be prime */
  51524. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  51525. /*
  51526. ** The block of page numbers associated with the first hash-table in a
  51527. ** wal-index is smaller than usual. This is so that there is a complete
  51528. ** hash-table on each aligned 32KB page of the wal-index.
  51529. */
  51530. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  51531. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  51532. #define WALINDEX_PGSZ ( \
  51533. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  51534. )
  51535. /*
  51536. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  51537. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  51538. ** numbered from zero.
  51539. **
  51540. ** If this call is successful, *ppPage is set to point to the wal-index
  51541. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  51542. ** then an SQLite error code is returned and *ppPage is set to 0.
  51543. */
  51544. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  51545. int rc = SQLITE_OK;
  51546. /* Enlarge the pWal->apWiData[] array if required */
  51547. if( pWal->nWiData<=iPage ){
  51548. int nByte = sizeof(u32*)*(iPage+1);
  51549. volatile u32 **apNew;
  51550. apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
  51551. if( !apNew ){
  51552. *ppPage = 0;
  51553. return SQLITE_NOMEM_BKPT;
  51554. }
  51555. memset((void*)&apNew[pWal->nWiData], 0,
  51556. sizeof(u32*)*(iPage+1-pWal->nWiData));
  51557. pWal->apWiData = apNew;
  51558. pWal->nWiData = iPage+1;
  51559. }
  51560. /* Request a pointer to the required page from the VFS */
  51561. if( pWal->apWiData[iPage]==0 ){
  51562. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  51563. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  51564. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
  51565. }else{
  51566. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  51567. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  51568. );
  51569. if( rc==SQLITE_READONLY ){
  51570. pWal->readOnly |= WAL_SHM_RDONLY;
  51571. rc = SQLITE_OK;
  51572. }
  51573. }
  51574. }
  51575. *ppPage = pWal->apWiData[iPage];
  51576. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  51577. return rc;
  51578. }
  51579. /*
  51580. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  51581. */
  51582. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  51583. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  51584. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  51585. }
  51586. /*
  51587. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  51588. */
  51589. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  51590. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  51591. return (volatile WalIndexHdr*)pWal->apWiData[0];
  51592. }
  51593. /*
  51594. ** The argument to this macro must be of type u32. On a little-endian
  51595. ** architecture, it returns the u32 value that results from interpreting
  51596. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  51597. ** returns the value that would be produced by interpreting the 4 bytes
  51598. ** of the input value as a little-endian integer.
  51599. */
  51600. #define BYTESWAP32(x) ( \
  51601. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  51602. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  51603. )
  51604. /*
  51605. ** Generate or extend an 8 byte checksum based on the data in
  51606. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  51607. ** initial values of 0 and 0 if aIn==NULL).
  51608. **
  51609. ** The checksum is written back into aOut[] before returning.
  51610. **
  51611. ** nByte must be a positive multiple of 8.
  51612. */
  51613. static void walChecksumBytes(
  51614. int nativeCksum, /* True for native byte-order, false for non-native */
  51615. u8 *a, /* Content to be checksummed */
  51616. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  51617. const u32 *aIn, /* Initial checksum value input */
  51618. u32 *aOut /* OUT: Final checksum value output */
  51619. ){
  51620. u32 s1, s2;
  51621. u32 *aData = (u32 *)a;
  51622. u32 *aEnd = (u32 *)&a[nByte];
  51623. if( aIn ){
  51624. s1 = aIn[0];
  51625. s2 = aIn[1];
  51626. }else{
  51627. s1 = s2 = 0;
  51628. }
  51629. assert( nByte>=8 );
  51630. assert( (nByte&0x00000007)==0 );
  51631. if( nativeCksum ){
  51632. do {
  51633. s1 += *aData++ + s2;
  51634. s2 += *aData++ + s1;
  51635. }while( aData<aEnd );
  51636. }else{
  51637. do {
  51638. s1 += BYTESWAP32(aData[0]) + s2;
  51639. s2 += BYTESWAP32(aData[1]) + s1;
  51640. aData += 2;
  51641. }while( aData<aEnd );
  51642. }
  51643. aOut[0] = s1;
  51644. aOut[1] = s2;
  51645. }
  51646. static void walShmBarrier(Wal *pWal){
  51647. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  51648. sqlite3OsShmBarrier(pWal->pDbFd);
  51649. }
  51650. }
  51651. /*
  51652. ** Write the header information in pWal->hdr into the wal-index.
  51653. **
  51654. ** The checksum on pWal->hdr is updated before it is written.
  51655. */
  51656. static void walIndexWriteHdr(Wal *pWal){
  51657. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  51658. const int nCksum = offsetof(WalIndexHdr, aCksum);
  51659. assert( pWal->writeLock );
  51660. pWal->hdr.isInit = 1;
  51661. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  51662. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  51663. memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  51664. walShmBarrier(pWal);
  51665. memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  51666. }
  51667. /*
  51668. ** This function encodes a single frame header and writes it to a buffer
  51669. ** supplied by the caller. A frame-header is made up of a series of
  51670. ** 4-byte big-endian integers, as follows:
  51671. **
  51672. ** 0: Page number.
  51673. ** 4: For commit records, the size of the database image in pages
  51674. ** after the commit. For all other records, zero.
  51675. ** 8: Salt-1 (copied from the wal-header)
  51676. ** 12: Salt-2 (copied from the wal-header)
  51677. ** 16: Checksum-1.
  51678. ** 20: Checksum-2.
  51679. */
  51680. static void walEncodeFrame(
  51681. Wal *pWal, /* The write-ahead log */
  51682. u32 iPage, /* Database page number for frame */
  51683. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  51684. u8 *aData, /* Pointer to page data */
  51685. u8 *aFrame /* OUT: Write encoded frame here */
  51686. ){
  51687. int nativeCksum; /* True for native byte-order checksums */
  51688. u32 *aCksum = pWal->hdr.aFrameCksum;
  51689. assert( WAL_FRAME_HDRSIZE==24 );
  51690. sqlite3Put4byte(&aFrame[0], iPage);
  51691. sqlite3Put4byte(&aFrame[4], nTruncate);
  51692. if( pWal->iReCksum==0 ){
  51693. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  51694. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  51695. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  51696. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  51697. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  51698. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  51699. }else{
  51700. memset(&aFrame[8], 0, 16);
  51701. }
  51702. }
  51703. /*
  51704. ** Check to see if the frame with header in aFrame[] and content
  51705. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  51706. ** *pnTruncate and return true. Return if the frame is not valid.
  51707. */
  51708. static int walDecodeFrame(
  51709. Wal *pWal, /* The write-ahead log */
  51710. u32 *piPage, /* OUT: Database page number for frame */
  51711. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  51712. u8 *aData, /* Pointer to page data (for checksum) */
  51713. u8 *aFrame /* Frame data */
  51714. ){
  51715. int nativeCksum; /* True for native byte-order checksums */
  51716. u32 *aCksum = pWal->hdr.aFrameCksum;
  51717. u32 pgno; /* Page number of the frame */
  51718. assert( WAL_FRAME_HDRSIZE==24 );
  51719. /* A frame is only valid if the salt values in the frame-header
  51720. ** match the salt values in the wal-header.
  51721. */
  51722. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  51723. return 0;
  51724. }
  51725. /* A frame is only valid if the page number is creater than zero.
  51726. */
  51727. pgno = sqlite3Get4byte(&aFrame[0]);
  51728. if( pgno==0 ){
  51729. return 0;
  51730. }
  51731. /* A frame is only valid if a checksum of the WAL header,
  51732. ** all prior frams, the first 16 bytes of this frame-header,
  51733. ** and the frame-data matches the checksum in the last 8
  51734. ** bytes of this frame-header.
  51735. */
  51736. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  51737. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  51738. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  51739. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  51740. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  51741. ){
  51742. /* Checksum failed. */
  51743. return 0;
  51744. }
  51745. /* If we reach this point, the frame is valid. Return the page number
  51746. ** and the new database size.
  51747. */
  51748. *piPage = pgno;
  51749. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  51750. return 1;
  51751. }
  51752. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  51753. /*
  51754. ** Names of locks. This routine is used to provide debugging output and is not
  51755. ** a part of an ordinary build.
  51756. */
  51757. static const char *walLockName(int lockIdx){
  51758. if( lockIdx==WAL_WRITE_LOCK ){
  51759. return "WRITE-LOCK";
  51760. }else if( lockIdx==WAL_CKPT_LOCK ){
  51761. return "CKPT-LOCK";
  51762. }else if( lockIdx==WAL_RECOVER_LOCK ){
  51763. return "RECOVER-LOCK";
  51764. }else{
  51765. static char zName[15];
  51766. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  51767. lockIdx-WAL_READ_LOCK(0));
  51768. return zName;
  51769. }
  51770. }
  51771. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  51772. /*
  51773. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  51774. ** A lock cannot be moved directly between shared and exclusive - it must go
  51775. ** through the unlocked state first.
  51776. **
  51777. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  51778. */
  51779. static int walLockShared(Wal *pWal, int lockIdx){
  51780. int rc;
  51781. if( pWal->exclusiveMode ) return SQLITE_OK;
  51782. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  51783. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  51784. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  51785. walLockName(lockIdx), rc ? "failed" : "ok"));
  51786. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  51787. return rc;
  51788. }
  51789. static void walUnlockShared(Wal *pWal, int lockIdx){
  51790. if( pWal->exclusiveMode ) return;
  51791. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  51792. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  51793. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  51794. }
  51795. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  51796. int rc;
  51797. if( pWal->exclusiveMode ) return SQLITE_OK;
  51798. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  51799. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  51800. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  51801. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  51802. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  51803. return rc;
  51804. }
  51805. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  51806. if( pWal->exclusiveMode ) return;
  51807. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  51808. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  51809. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  51810. walLockName(lockIdx), n));
  51811. }
  51812. /*
  51813. ** Compute a hash on a page number. The resulting hash value must land
  51814. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  51815. ** the hash to the next value in the event of a collision.
  51816. */
  51817. static int walHash(u32 iPage){
  51818. assert( iPage>0 );
  51819. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  51820. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  51821. }
  51822. static int walNextHash(int iPriorHash){
  51823. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  51824. }
  51825. /*
  51826. ** Return pointers to the hash table and page number array stored on
  51827. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  51828. ** numbered starting from 0.
  51829. **
  51830. ** Set output variable *paHash to point to the start of the hash table
  51831. ** in the wal-index file. Set *piZero to one less than the frame
  51832. ** number of the first frame indexed by this hash table. If a
  51833. ** slot in the hash table is set to N, it refers to frame number
  51834. ** (*piZero+N) in the log.
  51835. **
  51836. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  51837. ** first frame indexed by the hash table, frame (*piZero+1).
  51838. */
  51839. static int walHashGet(
  51840. Wal *pWal, /* WAL handle */
  51841. int iHash, /* Find the iHash'th table */
  51842. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  51843. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  51844. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  51845. ){
  51846. int rc; /* Return code */
  51847. volatile u32 *aPgno;
  51848. rc = walIndexPage(pWal, iHash, &aPgno);
  51849. assert( rc==SQLITE_OK || iHash>0 );
  51850. if( rc==SQLITE_OK ){
  51851. u32 iZero;
  51852. volatile ht_slot *aHash;
  51853. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  51854. if( iHash==0 ){
  51855. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  51856. iZero = 0;
  51857. }else{
  51858. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  51859. }
  51860. *paPgno = &aPgno[-1];
  51861. *paHash = aHash;
  51862. *piZero = iZero;
  51863. }
  51864. return rc;
  51865. }
  51866. /*
  51867. ** Return the number of the wal-index page that contains the hash-table
  51868. ** and page-number array that contain entries corresponding to WAL frame
  51869. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  51870. ** are numbered starting from 0.
  51871. */
  51872. static int walFramePage(u32 iFrame){
  51873. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  51874. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  51875. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  51876. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  51877. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  51878. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  51879. );
  51880. return iHash;
  51881. }
  51882. /*
  51883. ** Return the page number associated with frame iFrame in this WAL.
  51884. */
  51885. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  51886. int iHash = walFramePage(iFrame);
  51887. if( iHash==0 ){
  51888. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  51889. }
  51890. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  51891. }
  51892. /*
  51893. ** Remove entries from the hash table that point to WAL slots greater
  51894. ** than pWal->hdr.mxFrame.
  51895. **
  51896. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  51897. ** to a rollback or savepoint.
  51898. **
  51899. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  51900. ** updated. Any later hash tables will be automatically cleared when
  51901. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  51902. ** actually needed.
  51903. */
  51904. static void walCleanupHash(Wal *pWal){
  51905. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  51906. volatile u32 *aPgno = 0; /* Page number array for hash table */
  51907. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  51908. int iLimit = 0; /* Zero values greater than this */
  51909. int nByte; /* Number of bytes to zero in aPgno[] */
  51910. int i; /* Used to iterate through aHash[] */
  51911. assert( pWal->writeLock );
  51912. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  51913. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  51914. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  51915. if( pWal->hdr.mxFrame==0 ) return;
  51916. /* Obtain pointers to the hash-table and page-number array containing
  51917. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  51918. ** that the page said hash-table and array reside on is already mapped.
  51919. */
  51920. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  51921. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  51922. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  51923. /* Zero all hash-table entries that correspond to frame numbers greater
  51924. ** than pWal->hdr.mxFrame.
  51925. */
  51926. iLimit = pWal->hdr.mxFrame - iZero;
  51927. assert( iLimit>0 );
  51928. for(i=0; i<HASHTABLE_NSLOT; i++){
  51929. if( aHash[i]>iLimit ){
  51930. aHash[i] = 0;
  51931. }
  51932. }
  51933. /* Zero the entries in the aPgno array that correspond to frames with
  51934. ** frame numbers greater than pWal->hdr.mxFrame.
  51935. */
  51936. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  51937. memset((void *)&aPgno[iLimit+1], 0, nByte);
  51938. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  51939. /* Verify that the every entry in the mapping region is still reachable
  51940. ** via the hash table even after the cleanup.
  51941. */
  51942. if( iLimit ){
  51943. int j; /* Loop counter */
  51944. int iKey; /* Hash key */
  51945. for(j=1; j<=iLimit; j++){
  51946. for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
  51947. if( aHash[iKey]==j ) break;
  51948. }
  51949. assert( aHash[iKey]==j );
  51950. }
  51951. }
  51952. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  51953. }
  51954. /*
  51955. ** Set an entry in the wal-index that will map database page number
  51956. ** pPage into WAL frame iFrame.
  51957. */
  51958. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  51959. int rc; /* Return code */
  51960. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  51961. volatile u32 *aPgno = 0; /* Page number array */
  51962. volatile ht_slot *aHash = 0; /* Hash table */
  51963. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  51964. /* Assuming the wal-index file was successfully mapped, populate the
  51965. ** page number array and hash table entry.
  51966. */
  51967. if( rc==SQLITE_OK ){
  51968. int iKey; /* Hash table key */
  51969. int idx; /* Value to write to hash-table slot */
  51970. int nCollide; /* Number of hash collisions */
  51971. idx = iFrame - iZero;
  51972. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  51973. /* If this is the first entry to be added to this hash-table, zero the
  51974. ** entire hash table and aPgno[] array before proceeding.
  51975. */
  51976. if( idx==1 ){
  51977. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  51978. memset((void*)&aPgno[1], 0, nByte);
  51979. }
  51980. /* If the entry in aPgno[] is already set, then the previous writer
  51981. ** must have exited unexpectedly in the middle of a transaction (after
  51982. ** writing one or more dirty pages to the WAL to free up memory).
  51983. ** Remove the remnants of that writers uncommitted transaction from
  51984. ** the hash-table before writing any new entries.
  51985. */
  51986. if( aPgno[idx] ){
  51987. walCleanupHash(pWal);
  51988. assert( !aPgno[idx] );
  51989. }
  51990. /* Write the aPgno[] array entry and the hash-table slot. */
  51991. nCollide = idx;
  51992. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  51993. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  51994. }
  51995. aPgno[idx] = iPage;
  51996. aHash[iKey] = (ht_slot)idx;
  51997. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  51998. /* Verify that the number of entries in the hash table exactly equals
  51999. ** the number of entries in the mapping region.
  52000. */
  52001. {
  52002. int i; /* Loop counter */
  52003. int nEntry = 0; /* Number of entries in the hash table */
  52004. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  52005. assert( nEntry==idx );
  52006. }
  52007. /* Verify that the every entry in the mapping region is reachable
  52008. ** via the hash table. This turns out to be a really, really expensive
  52009. ** thing to check, so only do this occasionally - not on every
  52010. ** iteration.
  52011. */
  52012. if( (idx&0x3ff)==0 ){
  52013. int i; /* Loop counter */
  52014. for(i=1; i<=idx; i++){
  52015. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  52016. if( aHash[iKey]==i ) break;
  52017. }
  52018. assert( aHash[iKey]==i );
  52019. }
  52020. }
  52021. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  52022. }
  52023. return rc;
  52024. }
  52025. /*
  52026. ** Recover the wal-index by reading the write-ahead log file.
  52027. **
  52028. ** This routine first tries to establish an exclusive lock on the
  52029. ** wal-index to prevent other threads/processes from doing anything
  52030. ** with the WAL or wal-index while recovery is running. The
  52031. ** WAL_RECOVER_LOCK is also held so that other threads will know
  52032. ** that this thread is running recovery. If unable to establish
  52033. ** the necessary locks, this routine returns SQLITE_BUSY.
  52034. */
  52035. static int walIndexRecover(Wal *pWal){
  52036. int rc; /* Return Code */
  52037. i64 nSize; /* Size of log file */
  52038. u32 aFrameCksum[2] = {0, 0};
  52039. int iLock; /* Lock offset to lock for checkpoint */
  52040. int nLock; /* Number of locks to hold */
  52041. /* Obtain an exclusive lock on all byte in the locking range not already
  52042. ** locked by the caller. The caller is guaranteed to have locked the
  52043. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  52044. ** If successful, the same bytes that are locked here are unlocked before
  52045. ** this function returns.
  52046. */
  52047. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  52048. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  52049. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  52050. assert( pWal->writeLock );
  52051. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  52052. nLock = SQLITE_SHM_NLOCK - iLock;
  52053. rc = walLockExclusive(pWal, iLock, nLock);
  52054. if( rc ){
  52055. return rc;
  52056. }
  52057. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  52058. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  52059. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  52060. if( rc!=SQLITE_OK ){
  52061. goto recovery_error;
  52062. }
  52063. if( nSize>WAL_HDRSIZE ){
  52064. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  52065. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  52066. int szFrame; /* Number of bytes in buffer aFrame[] */
  52067. u8 *aData; /* Pointer to data part of aFrame buffer */
  52068. int iFrame; /* Index of last frame read */
  52069. i64 iOffset; /* Next offset to read from log file */
  52070. int szPage; /* Page size according to the log */
  52071. u32 magic; /* Magic value read from WAL header */
  52072. u32 version; /* Magic value read from WAL header */
  52073. int isValid; /* True if this frame is valid */
  52074. /* Read in the WAL header. */
  52075. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  52076. if( rc!=SQLITE_OK ){
  52077. goto recovery_error;
  52078. }
  52079. /* If the database page size is not a power of two, or is greater than
  52080. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  52081. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  52082. ** WAL file.
  52083. */
  52084. magic = sqlite3Get4byte(&aBuf[0]);
  52085. szPage = sqlite3Get4byte(&aBuf[8]);
  52086. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  52087. || szPage&(szPage-1)
  52088. || szPage>SQLITE_MAX_PAGE_SIZE
  52089. || szPage<512
  52090. ){
  52091. goto finished;
  52092. }
  52093. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  52094. pWal->szPage = szPage;
  52095. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  52096. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  52097. /* Verify that the WAL header checksum is correct */
  52098. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  52099. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  52100. );
  52101. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  52102. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  52103. ){
  52104. goto finished;
  52105. }
  52106. /* Verify that the version number on the WAL format is one that
  52107. ** are able to understand */
  52108. version = sqlite3Get4byte(&aBuf[4]);
  52109. if( version!=WAL_MAX_VERSION ){
  52110. rc = SQLITE_CANTOPEN_BKPT;
  52111. goto finished;
  52112. }
  52113. /* Malloc a buffer to read frames into. */
  52114. szFrame = szPage + WAL_FRAME_HDRSIZE;
  52115. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  52116. if( !aFrame ){
  52117. rc = SQLITE_NOMEM_BKPT;
  52118. goto recovery_error;
  52119. }
  52120. aData = &aFrame[WAL_FRAME_HDRSIZE];
  52121. /* Read all frames from the log file. */
  52122. iFrame = 0;
  52123. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  52124. u32 pgno; /* Database page number for frame */
  52125. u32 nTruncate; /* dbsize field from frame header */
  52126. /* Read and decode the next log frame. */
  52127. iFrame++;
  52128. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  52129. if( rc!=SQLITE_OK ) break;
  52130. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  52131. if( !isValid ) break;
  52132. rc = walIndexAppend(pWal, iFrame, pgno);
  52133. if( rc!=SQLITE_OK ) break;
  52134. /* If nTruncate is non-zero, this is a commit record. */
  52135. if( nTruncate ){
  52136. pWal->hdr.mxFrame = iFrame;
  52137. pWal->hdr.nPage = nTruncate;
  52138. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  52139. testcase( szPage<=32768 );
  52140. testcase( szPage>=65536 );
  52141. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  52142. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  52143. }
  52144. }
  52145. sqlite3_free(aFrame);
  52146. }
  52147. finished:
  52148. if( rc==SQLITE_OK ){
  52149. volatile WalCkptInfo *pInfo;
  52150. int i;
  52151. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  52152. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  52153. walIndexWriteHdr(pWal);
  52154. /* Reset the checkpoint-header. This is safe because this thread is
  52155. ** currently holding locks that exclude all other readers, writers and
  52156. ** checkpointers.
  52157. */
  52158. pInfo = walCkptInfo(pWal);
  52159. pInfo->nBackfill = 0;
  52160. pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
  52161. pInfo->aReadMark[0] = 0;
  52162. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  52163. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  52164. /* If more than one frame was recovered from the log file, report an
  52165. ** event via sqlite3_log(). This is to help with identifying performance
  52166. ** problems caused by applications routinely shutting down without
  52167. ** checkpointing the log file.
  52168. */
  52169. if( pWal->hdr.nPage ){
  52170. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  52171. "recovered %d frames from WAL file %s",
  52172. pWal->hdr.mxFrame, pWal->zWalName
  52173. );
  52174. }
  52175. }
  52176. recovery_error:
  52177. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  52178. walUnlockExclusive(pWal, iLock, nLock);
  52179. return rc;
  52180. }
  52181. /*
  52182. ** Close an open wal-index.
  52183. */
  52184. static void walIndexClose(Wal *pWal, int isDelete){
  52185. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  52186. int i;
  52187. for(i=0; i<pWal->nWiData; i++){
  52188. sqlite3_free((void *)pWal->apWiData[i]);
  52189. pWal->apWiData[i] = 0;
  52190. }
  52191. }else{
  52192. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  52193. }
  52194. }
  52195. /*
  52196. ** Open a connection to the WAL file zWalName. The database file must
  52197. ** already be opened on connection pDbFd. The buffer that zWalName points
  52198. ** to must remain valid for the lifetime of the returned Wal* handle.
  52199. **
  52200. ** A SHARED lock should be held on the database file when this function
  52201. ** is called. The purpose of this SHARED lock is to prevent any other
  52202. ** client from unlinking the WAL or wal-index file. If another process
  52203. ** were to do this just after this client opened one of these files, the
  52204. ** system would be badly broken.
  52205. **
  52206. ** If the log file is successfully opened, SQLITE_OK is returned and
  52207. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  52208. ** an SQLite error code is returned and *ppWal is left unmodified.
  52209. */
  52210. SQLITE_PRIVATE int sqlite3WalOpen(
  52211. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  52212. sqlite3_file *pDbFd, /* The open database file */
  52213. const char *zWalName, /* Name of the WAL file */
  52214. int bNoShm, /* True to run in heap-memory mode */
  52215. i64 mxWalSize, /* Truncate WAL to this size on reset */
  52216. Wal **ppWal /* OUT: Allocated Wal handle */
  52217. ){
  52218. int rc; /* Return Code */
  52219. Wal *pRet; /* Object to allocate and return */
  52220. int flags; /* Flags passed to OsOpen() */
  52221. assert( zWalName && zWalName[0] );
  52222. assert( pDbFd );
  52223. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  52224. ** this source file. Verify that the #defines of the locking byte offsets
  52225. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  52226. ** For that matter, if the lock offset ever changes from its initial design
  52227. ** value of 120, we need to know that so there is an assert() to check it.
  52228. */
  52229. assert( 120==WALINDEX_LOCK_OFFSET );
  52230. assert( 136==WALINDEX_HDR_SIZE );
  52231. #ifdef WIN_SHM_BASE
  52232. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  52233. #endif
  52234. #ifdef UNIX_SHM_BASE
  52235. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  52236. #endif
  52237. /* Allocate an instance of struct Wal to return. */
  52238. *ppWal = 0;
  52239. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  52240. if( !pRet ){
  52241. return SQLITE_NOMEM_BKPT;
  52242. }
  52243. pRet->pVfs = pVfs;
  52244. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  52245. pRet->pDbFd = pDbFd;
  52246. pRet->readLock = -1;
  52247. pRet->mxWalSize = mxWalSize;
  52248. pRet->zWalName = zWalName;
  52249. pRet->syncHeader = 1;
  52250. pRet->padToSectorBoundary = 1;
  52251. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  52252. /* Open file handle on the write-ahead log file. */
  52253. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  52254. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  52255. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  52256. pRet->readOnly = WAL_RDONLY;
  52257. }
  52258. if( rc!=SQLITE_OK ){
  52259. walIndexClose(pRet, 0);
  52260. sqlite3OsClose(pRet->pWalFd);
  52261. sqlite3_free(pRet);
  52262. }else{
  52263. int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
  52264. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  52265. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  52266. pRet->padToSectorBoundary = 0;
  52267. }
  52268. *ppWal = pRet;
  52269. WALTRACE(("WAL%d: opened\n", pRet));
  52270. }
  52271. return rc;
  52272. }
  52273. /*
  52274. ** Change the size to which the WAL file is trucated on each reset.
  52275. */
  52276. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  52277. if( pWal ) pWal->mxWalSize = iLimit;
  52278. }
  52279. /*
  52280. ** Find the smallest page number out of all pages held in the WAL that
  52281. ** has not been returned by any prior invocation of this method on the
  52282. ** same WalIterator object. Write into *piFrame the frame index where
  52283. ** that page was last written into the WAL. Write into *piPage the page
  52284. ** number.
  52285. **
  52286. ** Return 0 on success. If there are no pages in the WAL with a page
  52287. ** number larger than *piPage, then return 1.
  52288. */
  52289. static int walIteratorNext(
  52290. WalIterator *p, /* Iterator */
  52291. u32 *piPage, /* OUT: The page number of the next page */
  52292. u32 *piFrame /* OUT: Wal frame index of next page */
  52293. ){
  52294. u32 iMin; /* Result pgno must be greater than iMin */
  52295. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  52296. int i; /* For looping through segments */
  52297. iMin = p->iPrior;
  52298. assert( iMin<0xffffffff );
  52299. for(i=p->nSegment-1; i>=0; i--){
  52300. struct WalSegment *pSegment = &p->aSegment[i];
  52301. while( pSegment->iNext<pSegment->nEntry ){
  52302. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  52303. if( iPg>iMin ){
  52304. if( iPg<iRet ){
  52305. iRet = iPg;
  52306. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  52307. }
  52308. break;
  52309. }
  52310. pSegment->iNext++;
  52311. }
  52312. }
  52313. *piPage = p->iPrior = iRet;
  52314. return (iRet==0xFFFFFFFF);
  52315. }
  52316. /*
  52317. ** This function merges two sorted lists into a single sorted list.
  52318. **
  52319. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  52320. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  52321. ** is guaranteed for all J<K:
  52322. **
  52323. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  52324. ** aContent[aRight[J]] < aContent[aRight[K]]
  52325. **
  52326. ** This routine overwrites aRight[] with a new (probably longer) sequence
  52327. ** of indices such that the aRight[] contains every index that appears in
  52328. ** either aLeft[] or the old aRight[] and such that the second condition
  52329. ** above is still met.
  52330. **
  52331. ** The aContent[aLeft[X]] values will be unique for all X. And the
  52332. ** aContent[aRight[X]] values will be unique too. But there might be
  52333. ** one or more combinations of X and Y such that
  52334. **
  52335. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  52336. **
  52337. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  52338. */
  52339. static void walMerge(
  52340. const u32 *aContent, /* Pages in wal - keys for the sort */
  52341. ht_slot *aLeft, /* IN: Left hand input list */
  52342. int nLeft, /* IN: Elements in array *paLeft */
  52343. ht_slot **paRight, /* IN/OUT: Right hand input list */
  52344. int *pnRight, /* IN/OUT: Elements in *paRight */
  52345. ht_slot *aTmp /* Temporary buffer */
  52346. ){
  52347. int iLeft = 0; /* Current index in aLeft */
  52348. int iRight = 0; /* Current index in aRight */
  52349. int iOut = 0; /* Current index in output buffer */
  52350. int nRight = *pnRight;
  52351. ht_slot *aRight = *paRight;
  52352. assert( nLeft>0 && nRight>0 );
  52353. while( iRight<nRight || iLeft<nLeft ){
  52354. ht_slot logpage;
  52355. Pgno dbpage;
  52356. if( (iLeft<nLeft)
  52357. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  52358. ){
  52359. logpage = aLeft[iLeft++];
  52360. }else{
  52361. logpage = aRight[iRight++];
  52362. }
  52363. dbpage = aContent[logpage];
  52364. aTmp[iOut++] = logpage;
  52365. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  52366. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  52367. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  52368. }
  52369. *paRight = aLeft;
  52370. *pnRight = iOut;
  52371. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  52372. }
  52373. /*
  52374. ** Sort the elements in list aList using aContent[] as the sort key.
  52375. ** Remove elements with duplicate keys, preferring to keep the
  52376. ** larger aList[] values.
  52377. **
  52378. ** The aList[] entries are indices into aContent[]. The values in
  52379. ** aList[] are to be sorted so that for all J<K:
  52380. **
  52381. ** aContent[aList[J]] < aContent[aList[K]]
  52382. **
  52383. ** For any X and Y such that
  52384. **
  52385. ** aContent[aList[X]] == aContent[aList[Y]]
  52386. **
  52387. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  52388. ** the smaller.
  52389. */
  52390. static void walMergesort(
  52391. const u32 *aContent, /* Pages in wal */
  52392. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  52393. ht_slot *aList, /* IN/OUT: List to sort */
  52394. int *pnList /* IN/OUT: Number of elements in aList[] */
  52395. ){
  52396. struct Sublist {
  52397. int nList; /* Number of elements in aList */
  52398. ht_slot *aList; /* Pointer to sub-list content */
  52399. };
  52400. const int nList = *pnList; /* Size of input list */
  52401. int nMerge = 0; /* Number of elements in list aMerge */
  52402. ht_slot *aMerge = 0; /* List to be merged */
  52403. int iList; /* Index into input list */
  52404. u32 iSub = 0; /* Index into aSub array */
  52405. struct Sublist aSub[13]; /* Array of sub-lists */
  52406. memset(aSub, 0, sizeof(aSub));
  52407. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  52408. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  52409. for(iList=0; iList<nList; iList++){
  52410. nMerge = 1;
  52411. aMerge = &aList[iList];
  52412. for(iSub=0; iList & (1<<iSub); iSub++){
  52413. struct Sublist *p;
  52414. assert( iSub<ArraySize(aSub) );
  52415. p = &aSub[iSub];
  52416. assert( p->aList && p->nList<=(1<<iSub) );
  52417. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  52418. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  52419. }
  52420. aSub[iSub].aList = aMerge;
  52421. aSub[iSub].nList = nMerge;
  52422. }
  52423. for(iSub++; iSub<ArraySize(aSub); iSub++){
  52424. if( nList & (1<<iSub) ){
  52425. struct Sublist *p;
  52426. assert( iSub<ArraySize(aSub) );
  52427. p = &aSub[iSub];
  52428. assert( p->nList<=(1<<iSub) );
  52429. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  52430. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  52431. }
  52432. }
  52433. assert( aMerge==aList );
  52434. *pnList = nMerge;
  52435. #ifdef SQLITE_DEBUG
  52436. {
  52437. int i;
  52438. for(i=1; i<*pnList; i++){
  52439. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  52440. }
  52441. }
  52442. #endif
  52443. }
  52444. /*
  52445. ** Free an iterator allocated by walIteratorInit().
  52446. */
  52447. static void walIteratorFree(WalIterator *p){
  52448. sqlite3_free(p);
  52449. }
  52450. /*
  52451. ** Construct a WalInterator object that can be used to loop over all
  52452. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  52453. ** lock.
  52454. **
  52455. ** On success, make *pp point to the newly allocated WalInterator object
  52456. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  52457. ** returns an error, the value of *pp is undefined.
  52458. **
  52459. ** The calling routine should invoke walIteratorFree() to destroy the
  52460. ** WalIterator object when it has finished with it.
  52461. */
  52462. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  52463. WalIterator *p; /* Return value */
  52464. int nSegment; /* Number of segments to merge */
  52465. u32 iLast; /* Last frame in log */
  52466. int nByte; /* Number of bytes to allocate */
  52467. int i; /* Iterator variable */
  52468. ht_slot *aTmp; /* Temp space used by merge-sort */
  52469. int rc = SQLITE_OK; /* Return Code */
  52470. /* This routine only runs while holding the checkpoint lock. And
  52471. ** it only runs if there is actually content in the log (mxFrame>0).
  52472. */
  52473. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  52474. iLast = pWal->hdr.mxFrame;
  52475. /* Allocate space for the WalIterator object. */
  52476. nSegment = walFramePage(iLast) + 1;
  52477. nByte = sizeof(WalIterator)
  52478. + (nSegment-1)*sizeof(struct WalSegment)
  52479. + iLast*sizeof(ht_slot);
  52480. p = (WalIterator *)sqlite3_malloc64(nByte);
  52481. if( !p ){
  52482. return SQLITE_NOMEM_BKPT;
  52483. }
  52484. memset(p, 0, nByte);
  52485. p->nSegment = nSegment;
  52486. /* Allocate temporary space used by the merge-sort routine. This block
  52487. ** of memory will be freed before this function returns.
  52488. */
  52489. aTmp = (ht_slot *)sqlite3_malloc64(
  52490. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  52491. );
  52492. if( !aTmp ){
  52493. rc = SQLITE_NOMEM_BKPT;
  52494. }
  52495. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  52496. volatile ht_slot *aHash;
  52497. u32 iZero;
  52498. volatile u32 *aPgno;
  52499. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  52500. if( rc==SQLITE_OK ){
  52501. int j; /* Counter variable */
  52502. int nEntry; /* Number of entries in this segment */
  52503. ht_slot *aIndex; /* Sorted index for this segment */
  52504. aPgno++;
  52505. if( (i+1)==nSegment ){
  52506. nEntry = (int)(iLast - iZero);
  52507. }else{
  52508. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  52509. }
  52510. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  52511. iZero++;
  52512. for(j=0; j<nEntry; j++){
  52513. aIndex[j] = (ht_slot)j;
  52514. }
  52515. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  52516. p->aSegment[i].iZero = iZero;
  52517. p->aSegment[i].nEntry = nEntry;
  52518. p->aSegment[i].aIndex = aIndex;
  52519. p->aSegment[i].aPgno = (u32 *)aPgno;
  52520. }
  52521. }
  52522. sqlite3_free(aTmp);
  52523. if( rc!=SQLITE_OK ){
  52524. walIteratorFree(p);
  52525. }
  52526. *pp = p;
  52527. return rc;
  52528. }
  52529. /*
  52530. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  52531. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  52532. ** busy-handler function. Invoke it and retry the lock until either the
  52533. ** lock is successfully obtained or the busy-handler returns 0.
  52534. */
  52535. static int walBusyLock(
  52536. Wal *pWal, /* WAL connection */
  52537. int (*xBusy)(void*), /* Function to call when busy */
  52538. void *pBusyArg, /* Context argument for xBusyHandler */
  52539. int lockIdx, /* Offset of first byte to lock */
  52540. int n /* Number of bytes to lock */
  52541. ){
  52542. int rc;
  52543. do {
  52544. rc = walLockExclusive(pWal, lockIdx, n);
  52545. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  52546. return rc;
  52547. }
  52548. /*
  52549. ** The cache of the wal-index header must be valid to call this function.
  52550. ** Return the page-size in bytes used by the database.
  52551. */
  52552. static int walPagesize(Wal *pWal){
  52553. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  52554. }
  52555. /*
  52556. ** The following is guaranteed when this function is called:
  52557. **
  52558. ** a) the WRITER lock is held,
  52559. ** b) the entire log file has been checkpointed, and
  52560. ** c) any existing readers are reading exclusively from the database
  52561. ** file - there are no readers that may attempt to read a frame from
  52562. ** the log file.
  52563. **
  52564. ** This function updates the shared-memory structures so that the next
  52565. ** client to write to the database (which may be this one) does so by
  52566. ** writing frames into the start of the log file.
  52567. **
  52568. ** The value of parameter salt1 is used as the aSalt[1] value in the
  52569. ** new wal-index header. It should be passed a pseudo-random value (i.e.
  52570. ** one obtained from sqlite3_randomness()).
  52571. */
  52572. static void walRestartHdr(Wal *pWal, u32 salt1){
  52573. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  52574. int i; /* Loop counter */
  52575. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  52576. pWal->nCkpt++;
  52577. pWal->hdr.mxFrame = 0;
  52578. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  52579. memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
  52580. walIndexWriteHdr(pWal);
  52581. pInfo->nBackfill = 0;
  52582. pInfo->nBackfillAttempted = 0;
  52583. pInfo->aReadMark[1] = 0;
  52584. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  52585. assert( pInfo->aReadMark[0]==0 );
  52586. }
  52587. /*
  52588. ** Copy as much content as we can from the WAL back into the database file
  52589. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  52590. **
  52591. ** The amount of information copies from WAL to database might be limited
  52592. ** by active readers. This routine will never overwrite a database page
  52593. ** that a concurrent reader might be using.
  52594. **
  52595. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  52596. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  52597. ** checkpoints are always run by a background thread or background
  52598. ** process, foreground threads will never block on a lengthy fsync call.
  52599. **
  52600. ** Fsync is called on the WAL before writing content out of the WAL and
  52601. ** into the database. This ensures that if the new content is persistent
  52602. ** in the WAL and can be recovered following a power-loss or hard reset.
  52603. **
  52604. ** Fsync is also called on the database file if (and only if) the entire
  52605. ** WAL content is copied into the database file. This second fsync makes
  52606. ** it safe to delete the WAL since the new content will persist in the
  52607. ** database file.
  52608. **
  52609. ** This routine uses and updates the nBackfill field of the wal-index header.
  52610. ** This is the only routine that will increase the value of nBackfill.
  52611. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  52612. ** its value.)
  52613. **
  52614. ** The caller must be holding sufficient locks to ensure that no other
  52615. ** checkpoint is running (in any other thread or process) at the same
  52616. ** time.
  52617. */
  52618. static int walCheckpoint(
  52619. Wal *pWal, /* Wal connection */
  52620. sqlite3 *db, /* Check for interrupts on this handle */
  52621. int eMode, /* One of PASSIVE, FULL or RESTART */
  52622. int (*xBusy)(void*), /* Function to call when busy */
  52623. void *pBusyArg, /* Context argument for xBusyHandler */
  52624. int sync_flags, /* Flags for OsSync() (or 0) */
  52625. u8 *zBuf /* Temporary buffer to use */
  52626. ){
  52627. int rc = SQLITE_OK; /* Return code */
  52628. int szPage; /* Database page-size */
  52629. WalIterator *pIter = 0; /* Wal iterator context */
  52630. u32 iDbpage = 0; /* Next database page to write */
  52631. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  52632. u32 mxSafeFrame; /* Max frame that can be backfilled */
  52633. u32 mxPage; /* Max database page to write */
  52634. int i; /* Loop counter */
  52635. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  52636. szPage = walPagesize(pWal);
  52637. testcase( szPage<=32768 );
  52638. testcase( szPage>=65536 );
  52639. pInfo = walCkptInfo(pWal);
  52640. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  52641. /* Allocate the iterator */
  52642. rc = walIteratorInit(pWal, &pIter);
  52643. if( rc!=SQLITE_OK ){
  52644. return rc;
  52645. }
  52646. assert( pIter );
  52647. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  52648. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  52649. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  52650. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  52651. ** safe to write into the database. Frames beyond mxSafeFrame might
  52652. ** overwrite database pages that are in use by active readers and thus
  52653. ** cannot be backfilled from the WAL.
  52654. */
  52655. mxSafeFrame = pWal->hdr.mxFrame;
  52656. mxPage = pWal->hdr.nPage;
  52657. for(i=1; i<WAL_NREADER; i++){
  52658. /* Thread-sanitizer reports that the following is an unsafe read,
  52659. ** as some other thread may be in the process of updating the value
  52660. ** of the aReadMark[] slot. The assumption here is that if that is
  52661. ** happening, the other client may only be increasing the value,
  52662. ** not decreasing it. So assuming either that either the "old" or
  52663. ** "new" version of the value is read, and not some arbitrary value
  52664. ** that would never be written by a real client, things are still
  52665. ** safe. */
  52666. u32 y = pInfo->aReadMark[i];
  52667. if( mxSafeFrame>y ){
  52668. assert( y<=pWal->hdr.mxFrame );
  52669. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  52670. if( rc==SQLITE_OK ){
  52671. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  52672. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  52673. }else if( rc==SQLITE_BUSY ){
  52674. mxSafeFrame = y;
  52675. xBusy = 0;
  52676. }else{
  52677. goto walcheckpoint_out;
  52678. }
  52679. }
  52680. }
  52681. if( pInfo->nBackfill<mxSafeFrame
  52682. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
  52683. ){
  52684. i64 nSize; /* Current size of database file */
  52685. u32 nBackfill = pInfo->nBackfill;
  52686. pInfo->nBackfillAttempted = mxSafeFrame;
  52687. /* Sync the WAL to disk */
  52688. if( sync_flags ){
  52689. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  52690. }
  52691. /* If the database may grow as a result of this checkpoint, hint
  52692. ** about the eventual size of the db file to the VFS layer.
  52693. */
  52694. if( rc==SQLITE_OK ){
  52695. i64 nReq = ((i64)mxPage * szPage);
  52696. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  52697. if( rc==SQLITE_OK && nSize<nReq ){
  52698. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  52699. }
  52700. }
  52701. /* Iterate through the contents of the WAL, copying data to the db file */
  52702. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  52703. i64 iOffset;
  52704. assert( walFramePgno(pWal, iFrame)==iDbpage );
  52705. if( db->u1.isInterrupted ){
  52706. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  52707. break;
  52708. }
  52709. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
  52710. continue;
  52711. }
  52712. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  52713. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  52714. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  52715. if( rc!=SQLITE_OK ) break;
  52716. iOffset = (iDbpage-1)*(i64)szPage;
  52717. testcase( IS_BIG_INT(iOffset) );
  52718. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  52719. if( rc!=SQLITE_OK ) break;
  52720. }
  52721. /* If work was actually accomplished... */
  52722. if( rc==SQLITE_OK ){
  52723. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  52724. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  52725. testcase( IS_BIG_INT(szDb) );
  52726. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  52727. if( rc==SQLITE_OK && sync_flags ){
  52728. rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
  52729. }
  52730. }
  52731. if( rc==SQLITE_OK ){
  52732. pInfo->nBackfill = mxSafeFrame;
  52733. }
  52734. }
  52735. /* Release the reader lock held while backfilling */
  52736. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  52737. }
  52738. if( rc==SQLITE_BUSY ){
  52739. /* Reset the return code so as not to report a checkpoint failure
  52740. ** just because there are active readers. */
  52741. rc = SQLITE_OK;
  52742. }
  52743. }
  52744. /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
  52745. ** entire wal file has been copied into the database file, then block
  52746. ** until all readers have finished using the wal file. This ensures that
  52747. ** the next process to write to the database restarts the wal file.
  52748. */
  52749. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  52750. assert( pWal->writeLock );
  52751. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  52752. rc = SQLITE_BUSY;
  52753. }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
  52754. u32 salt1;
  52755. sqlite3_randomness(4, &salt1);
  52756. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  52757. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  52758. if( rc==SQLITE_OK ){
  52759. if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
  52760. /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
  52761. ** SQLITE_CHECKPOINT_RESTART with the addition that it also
  52762. ** truncates the log file to zero bytes just prior to a
  52763. ** successful return.
  52764. **
  52765. ** In theory, it might be safe to do this without updating the
  52766. ** wal-index header in shared memory, as all subsequent reader or
  52767. ** writer clients should see that the entire log file has been
  52768. ** checkpointed and behave accordingly. This seems unsafe though,
  52769. ** as it would leave the system in a state where the contents of
  52770. ** the wal-index header do not match the contents of the
  52771. ** file-system. To avoid this, update the wal-index header to
  52772. ** indicate that the log file contains zero valid frames. */
  52773. walRestartHdr(pWal, salt1);
  52774. rc = sqlite3OsTruncate(pWal->pWalFd, 0);
  52775. }
  52776. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  52777. }
  52778. }
  52779. }
  52780. walcheckpoint_out:
  52781. walIteratorFree(pIter);
  52782. return rc;
  52783. }
  52784. /*
  52785. ** If the WAL file is currently larger than nMax bytes in size, truncate
  52786. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  52787. */
  52788. static void walLimitSize(Wal *pWal, i64 nMax){
  52789. i64 sz;
  52790. int rx;
  52791. sqlite3BeginBenignMalloc();
  52792. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  52793. if( rx==SQLITE_OK && (sz > nMax ) ){
  52794. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  52795. }
  52796. sqlite3EndBenignMalloc();
  52797. if( rx ){
  52798. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  52799. }
  52800. }
  52801. /*
  52802. ** Close a connection to a log file.
  52803. */
  52804. SQLITE_PRIVATE int sqlite3WalClose(
  52805. Wal *pWal, /* Wal to close */
  52806. sqlite3 *db, /* For interrupt flag */
  52807. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  52808. int nBuf,
  52809. u8 *zBuf /* Buffer of at least nBuf bytes */
  52810. ){
  52811. int rc = SQLITE_OK;
  52812. if( pWal ){
  52813. int isDelete = 0; /* True to unlink wal and wal-index files */
  52814. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  52815. ** ordinary, rollback-mode locking methods, this guarantees that the
  52816. ** connection associated with this log file is the only connection to
  52817. ** the database. In this case checkpoint the database and unlink both
  52818. ** the wal and wal-index files.
  52819. **
  52820. ** The EXCLUSIVE lock is not released before returning.
  52821. */
  52822. if( zBuf!=0
  52823. && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
  52824. ){
  52825. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  52826. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  52827. }
  52828. rc = sqlite3WalCheckpoint(pWal, db,
  52829. SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  52830. );
  52831. if( rc==SQLITE_OK ){
  52832. int bPersist = -1;
  52833. sqlite3OsFileControlHint(
  52834. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  52835. );
  52836. if( bPersist!=1 ){
  52837. /* Try to delete the WAL file if the checkpoint completed and
  52838. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  52839. ** mode (!bPersist) */
  52840. isDelete = 1;
  52841. }else if( pWal->mxWalSize>=0 ){
  52842. /* Try to truncate the WAL file to zero bytes if the checkpoint
  52843. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  52844. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  52845. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  52846. ** to zero bytes as truncating to the journal_size_limit might
  52847. ** leave a corrupt WAL file on disk. */
  52848. walLimitSize(pWal, 0);
  52849. }
  52850. }
  52851. }
  52852. walIndexClose(pWal, isDelete);
  52853. sqlite3OsClose(pWal->pWalFd);
  52854. if( isDelete ){
  52855. sqlite3BeginBenignMalloc();
  52856. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  52857. sqlite3EndBenignMalloc();
  52858. }
  52859. WALTRACE(("WAL%p: closed\n", pWal));
  52860. sqlite3_free((void *)pWal->apWiData);
  52861. sqlite3_free(pWal);
  52862. }
  52863. return rc;
  52864. }
  52865. /*
  52866. ** Try to read the wal-index header. Return 0 on success and 1 if
  52867. ** there is a problem.
  52868. **
  52869. ** The wal-index is in shared memory. Another thread or process might
  52870. ** be writing the header at the same time this procedure is trying to
  52871. ** read it, which might result in inconsistency. A dirty read is detected
  52872. ** by verifying that both copies of the header are the same and also by
  52873. ** a checksum on the header.
  52874. **
  52875. ** If and only if the read is consistent and the header is different from
  52876. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  52877. ** and *pChanged is set to 1.
  52878. **
  52879. ** If the checksum cannot be verified return non-zero. If the header
  52880. ** is read successfully and the checksum verified, return zero.
  52881. */
  52882. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  52883. u32 aCksum[2]; /* Checksum on the header content */
  52884. WalIndexHdr h1, h2; /* Two copies of the header content */
  52885. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  52886. /* The first page of the wal-index must be mapped at this point. */
  52887. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  52888. /* Read the header. This might happen concurrently with a write to the
  52889. ** same area of shared memory on a different CPU in a SMP,
  52890. ** meaning it is possible that an inconsistent snapshot is read
  52891. ** from the file. If this happens, return non-zero.
  52892. **
  52893. ** There are two copies of the header at the beginning of the wal-index.
  52894. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  52895. ** Memory barriers are used to prevent the compiler or the hardware from
  52896. ** reordering the reads and writes.
  52897. */
  52898. aHdr = walIndexHdr(pWal);
  52899. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  52900. walShmBarrier(pWal);
  52901. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  52902. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  52903. return 1; /* Dirty read */
  52904. }
  52905. if( h1.isInit==0 ){
  52906. return 1; /* Malformed header - probably all zeros */
  52907. }
  52908. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  52909. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  52910. return 1; /* Checksum does not match */
  52911. }
  52912. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  52913. *pChanged = 1;
  52914. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  52915. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  52916. testcase( pWal->szPage<=32768 );
  52917. testcase( pWal->szPage>=65536 );
  52918. }
  52919. /* The header was successfully read. Return zero. */
  52920. return 0;
  52921. }
  52922. /*
  52923. ** Read the wal-index header from the wal-index and into pWal->hdr.
  52924. ** If the wal-header appears to be corrupt, try to reconstruct the
  52925. ** wal-index from the WAL before returning.
  52926. **
  52927. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  52928. ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
  52929. ** to 0.
  52930. **
  52931. ** If the wal-index header is successfully read, return SQLITE_OK.
  52932. ** Otherwise an SQLite error code.
  52933. */
  52934. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  52935. int rc; /* Return code */
  52936. int badHdr; /* True if a header read failed */
  52937. volatile u32 *page0; /* Chunk of wal-index containing header */
  52938. /* Ensure that page 0 of the wal-index (the page that contains the
  52939. ** wal-index header) is mapped. Return early if an error occurs here.
  52940. */
  52941. assert( pChanged );
  52942. rc = walIndexPage(pWal, 0, &page0);
  52943. if( rc!=SQLITE_OK ){
  52944. return rc;
  52945. };
  52946. assert( page0 || pWal->writeLock==0 );
  52947. /* If the first page of the wal-index has been mapped, try to read the
  52948. ** wal-index header immediately, without holding any lock. This usually
  52949. ** works, but may fail if the wal-index header is corrupt or currently
  52950. ** being modified by another thread or process.
  52951. */
  52952. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  52953. /* If the first attempt failed, it might have been due to a race
  52954. ** with a writer. So get a WRITE lock and try again.
  52955. */
  52956. assert( badHdr==0 || pWal->writeLock==0 );
  52957. if( badHdr ){
  52958. if( pWal->readOnly & WAL_SHM_RDONLY ){
  52959. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  52960. walUnlockShared(pWal, WAL_WRITE_LOCK);
  52961. rc = SQLITE_READONLY_RECOVERY;
  52962. }
  52963. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  52964. pWal->writeLock = 1;
  52965. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  52966. badHdr = walIndexTryHdr(pWal, pChanged);
  52967. if( badHdr ){
  52968. /* If the wal-index header is still malformed even while holding
  52969. ** a WRITE lock, it can only mean that the header is corrupted and
  52970. ** needs to be reconstructed. So run recovery to do exactly that.
  52971. */
  52972. rc = walIndexRecover(pWal);
  52973. *pChanged = 1;
  52974. }
  52975. }
  52976. pWal->writeLock = 0;
  52977. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  52978. }
  52979. }
  52980. /* If the header is read successfully, check the version number to make
  52981. ** sure the wal-index was not constructed with some future format that
  52982. ** this version of SQLite cannot understand.
  52983. */
  52984. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  52985. rc = SQLITE_CANTOPEN_BKPT;
  52986. }
  52987. return rc;
  52988. }
  52989. /*
  52990. ** This is the value that walTryBeginRead returns when it needs to
  52991. ** be retried.
  52992. */
  52993. #define WAL_RETRY (-1)
  52994. /*
  52995. ** Attempt to start a read transaction. This might fail due to a race or
  52996. ** other transient condition. When that happens, it returns WAL_RETRY to
  52997. ** indicate to the caller that it is safe to retry immediately.
  52998. **
  52999. ** On success return SQLITE_OK. On a permanent failure (such an
  53000. ** I/O error or an SQLITE_BUSY because another process is running
  53001. ** recovery) return a positive error code.
  53002. **
  53003. ** The useWal parameter is true to force the use of the WAL and disable
  53004. ** the case where the WAL is bypassed because it has been completely
  53005. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  53006. ** to make a copy of the wal-index header into pWal->hdr. If the
  53007. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  53008. ** to the caller that the local paget cache is obsolete and needs to be
  53009. ** flushed.) When useWal==1, the wal-index header is assumed to already
  53010. ** be loaded and the pChanged parameter is unused.
  53011. **
  53012. ** The caller must set the cnt parameter to the number of prior calls to
  53013. ** this routine during the current read attempt that returned WAL_RETRY.
  53014. ** This routine will start taking more aggressive measures to clear the
  53015. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  53016. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  53017. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  53018. ** and is not honoring the locking protocol. There is a vanishingly small
  53019. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  53020. ** bad luck when there is lots of contention for the wal-index, but that
  53021. ** possibility is so small that it can be safely neglected, we believe.
  53022. **
  53023. ** On success, this routine obtains a read lock on
  53024. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  53025. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  53026. ** that means the Wal does not hold any read lock. The reader must not
  53027. ** access any database page that is modified by a WAL frame up to and
  53028. ** including frame number aReadMark[pWal->readLock]. The reader will
  53029. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  53030. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  53031. ** completely and get all content directly from the database file.
  53032. ** If the useWal parameter is 1 then the WAL will never be ignored and
  53033. ** this routine will always set pWal->readLock>0 on success.
  53034. ** When the read transaction is completed, the caller must release the
  53035. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  53036. **
  53037. ** This routine uses the nBackfill and aReadMark[] fields of the header
  53038. ** to select a particular WAL_READ_LOCK() that strives to let the
  53039. ** checkpoint process do as much work as possible. This routine might
  53040. ** update values of the aReadMark[] array in the header, but if it does
  53041. ** so it takes care to hold an exclusive lock on the corresponding
  53042. ** WAL_READ_LOCK() while changing values.
  53043. */
  53044. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  53045. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  53046. u32 mxReadMark; /* Largest aReadMark[] value */
  53047. int mxI; /* Index of largest aReadMark[] value */
  53048. int i; /* Loop counter */
  53049. int rc = SQLITE_OK; /* Return code */
  53050. u32 mxFrame; /* Wal frame to lock to */
  53051. assert( pWal->readLock<0 ); /* Not currently locked */
  53052. /* Take steps to avoid spinning forever if there is a protocol error.
  53053. **
  53054. ** Circumstances that cause a RETRY should only last for the briefest
  53055. ** instances of time. No I/O or other system calls are done while the
  53056. ** locks are held, so the locks should not be held for very long. But
  53057. ** if we are unlucky, another process that is holding a lock might get
  53058. ** paged out or take a page-fault that is time-consuming to resolve,
  53059. ** during the few nanoseconds that it is holding the lock. In that case,
  53060. ** it might take longer than normal for the lock to free.
  53061. **
  53062. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  53063. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  53064. ** is more of a scheduler yield than an actual delay. But on the 10th
  53065. ** an subsequent retries, the delays start becoming longer and longer,
  53066. ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
  53067. ** The total delay time before giving up is less than 10 seconds.
  53068. */
  53069. if( cnt>5 ){
  53070. int nDelay = 1; /* Pause time in microseconds */
  53071. if( cnt>100 ){
  53072. VVA_ONLY( pWal->lockError = 1; )
  53073. return SQLITE_PROTOCOL;
  53074. }
  53075. if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
  53076. sqlite3OsSleep(pWal->pVfs, nDelay);
  53077. }
  53078. if( !useWal ){
  53079. rc = walIndexReadHdr(pWal, pChanged);
  53080. if( rc==SQLITE_BUSY ){
  53081. /* If there is not a recovery running in another thread or process
  53082. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  53083. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  53084. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  53085. ** would be technically correct. But the race is benign since with
  53086. ** WAL_RETRY this routine will be called again and will probably be
  53087. ** right on the second iteration.
  53088. */
  53089. if( pWal->apWiData[0]==0 ){
  53090. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  53091. ** We assume this is a transient condition, so return WAL_RETRY. The
  53092. ** xShmMap() implementation used by the default unix and win32 VFS
  53093. ** modules may return SQLITE_BUSY due to a race condition in the
  53094. ** code that determines whether or not the shared-memory region
  53095. ** must be zeroed before the requested page is returned.
  53096. */
  53097. rc = WAL_RETRY;
  53098. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  53099. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  53100. rc = WAL_RETRY;
  53101. }else if( rc==SQLITE_BUSY ){
  53102. rc = SQLITE_BUSY_RECOVERY;
  53103. }
  53104. }
  53105. if( rc!=SQLITE_OK ){
  53106. return rc;
  53107. }
  53108. }
  53109. pInfo = walCkptInfo(pWal);
  53110. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
  53111. #ifdef SQLITE_ENABLE_SNAPSHOT
  53112. && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0
  53113. || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr)))
  53114. #endif
  53115. ){
  53116. /* The WAL has been completely backfilled (or it is empty).
  53117. ** and can be safely ignored.
  53118. */
  53119. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  53120. walShmBarrier(pWal);
  53121. if( rc==SQLITE_OK ){
  53122. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  53123. /* It is not safe to allow the reader to continue here if frames
  53124. ** may have been appended to the log before READ_LOCK(0) was obtained.
  53125. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  53126. ** which implies that the database file contains a trustworthy
  53127. ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
  53128. ** happening, this is usually correct.
  53129. **
  53130. ** However, if frames have been appended to the log (or if the log
  53131. ** is wrapped and written for that matter) before the READ_LOCK(0)
  53132. ** is obtained, that is not necessarily true. A checkpointer may
  53133. ** have started to backfill the appended frames but crashed before
  53134. ** it finished. Leaving a corrupt image in the database file.
  53135. */
  53136. walUnlockShared(pWal, WAL_READ_LOCK(0));
  53137. return WAL_RETRY;
  53138. }
  53139. pWal->readLock = 0;
  53140. return SQLITE_OK;
  53141. }else if( rc!=SQLITE_BUSY ){
  53142. return rc;
  53143. }
  53144. }
  53145. /* If we get this far, it means that the reader will want to use
  53146. ** the WAL to get at content from recent commits. The job now is
  53147. ** to select one of the aReadMark[] entries that is closest to
  53148. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  53149. */
  53150. mxReadMark = 0;
  53151. mxI = 0;
  53152. mxFrame = pWal->hdr.mxFrame;
  53153. #ifdef SQLITE_ENABLE_SNAPSHOT
  53154. if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
  53155. mxFrame = pWal->pSnapshot->mxFrame;
  53156. }
  53157. #endif
  53158. for(i=1; i<WAL_NREADER; i++){
  53159. u32 thisMark = pInfo->aReadMark[i];
  53160. if( mxReadMark<=thisMark && thisMark<=mxFrame ){
  53161. assert( thisMark!=READMARK_NOT_USED );
  53162. mxReadMark = thisMark;
  53163. mxI = i;
  53164. }
  53165. }
  53166. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  53167. && (mxReadMark<mxFrame || mxI==0)
  53168. ){
  53169. for(i=1; i<WAL_NREADER; i++){
  53170. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  53171. if( rc==SQLITE_OK ){
  53172. mxReadMark = pInfo->aReadMark[i] = mxFrame;
  53173. mxI = i;
  53174. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  53175. break;
  53176. }else if( rc!=SQLITE_BUSY ){
  53177. return rc;
  53178. }
  53179. }
  53180. }
  53181. if( mxI==0 ){
  53182. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  53183. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
  53184. }
  53185. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  53186. if( rc ){
  53187. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  53188. }
  53189. /* Now that the read-lock has been obtained, check that neither the
  53190. ** value in the aReadMark[] array or the contents of the wal-index
  53191. ** header have changed.
  53192. **
  53193. ** It is necessary to check that the wal-index header did not change
  53194. ** between the time it was read and when the shared-lock was obtained
  53195. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  53196. ** that the log file may have been wrapped by a writer, or that frames
  53197. ** that occur later in the log than pWal->hdr.mxFrame may have been
  53198. ** copied into the database by a checkpointer. If either of these things
  53199. ** happened, then reading the database with the current value of
  53200. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  53201. ** instead.
  53202. **
  53203. ** Before checking that the live wal-index header has not changed
  53204. ** since it was read, set Wal.minFrame to the first frame in the wal
  53205. ** file that has not yet been checkpointed. This client will not need
  53206. ** to read any frames earlier than minFrame from the wal file - they
  53207. ** can be safely read directly from the database file.
  53208. **
  53209. ** Because a ShmBarrier() call is made between taking the copy of
  53210. ** nBackfill and checking that the wal-header in shared-memory still
  53211. ** matches the one cached in pWal->hdr, it is guaranteed that the
  53212. ** checkpointer that set nBackfill was not working with a wal-index
  53213. ** header newer than that cached in pWal->hdr. If it were, that could
  53214. ** cause a problem. The checkpointer could omit to checkpoint
  53215. ** a version of page X that lies before pWal->minFrame (call that version
  53216. ** A) on the basis that there is a newer version (version B) of the same
  53217. ** page later in the wal file. But if version B happens to like past
  53218. ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
  53219. ** that it can read version A from the database file. However, since
  53220. ** we can guarantee that the checkpointer that set nBackfill could not
  53221. ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
  53222. */
  53223. pWal->minFrame = pInfo->nBackfill+1;
  53224. walShmBarrier(pWal);
  53225. if( pInfo->aReadMark[mxI]!=mxReadMark
  53226. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  53227. ){
  53228. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  53229. return WAL_RETRY;
  53230. }else{
  53231. assert( mxReadMark<=pWal->hdr.mxFrame );
  53232. pWal->readLock = (i16)mxI;
  53233. }
  53234. return rc;
  53235. }
  53236. #ifdef SQLITE_ENABLE_SNAPSHOT
  53237. /*
  53238. ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
  53239. ** variable so that older snapshots can be accessed. To do this, loop
  53240. ** through all wal frames from nBackfillAttempted to (nBackfill+1),
  53241. ** comparing their content to the corresponding page with the database
  53242. ** file, if any. Set nBackfillAttempted to the frame number of the
  53243. ** first frame for which the wal file content matches the db file.
  53244. **
  53245. ** This is only really safe if the file-system is such that any page
  53246. ** writes made by earlier checkpointers were atomic operations, which
  53247. ** is not always true. It is also possible that nBackfillAttempted
  53248. ** may be left set to a value larger than expected, if a wal frame
  53249. ** contains content that duplicate of an earlier version of the same
  53250. ** page.
  53251. **
  53252. ** SQLITE_OK is returned if successful, or an SQLite error code if an
  53253. ** error occurs. It is not an error if nBackfillAttempted cannot be
  53254. ** decreased at all.
  53255. */
  53256. SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
  53257. int rc;
  53258. assert( pWal->readLock>=0 );
  53259. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  53260. if( rc==SQLITE_OK ){
  53261. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  53262. int szPage = (int)pWal->szPage;
  53263. i64 szDb; /* Size of db file in bytes */
  53264. rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
  53265. if( rc==SQLITE_OK ){
  53266. void *pBuf1 = sqlite3_malloc(szPage);
  53267. void *pBuf2 = sqlite3_malloc(szPage);
  53268. if( pBuf1==0 || pBuf2==0 ){
  53269. rc = SQLITE_NOMEM;
  53270. }else{
  53271. u32 i = pInfo->nBackfillAttempted;
  53272. for(i=pInfo->nBackfillAttempted; i>pInfo->nBackfill; i--){
  53273. volatile ht_slot *dummy;
  53274. volatile u32 *aPgno; /* Array of page numbers */
  53275. u32 iZero; /* Frame corresponding to aPgno[0] */
  53276. u32 pgno; /* Page number in db file */
  53277. i64 iDbOff; /* Offset of db file entry */
  53278. i64 iWalOff; /* Offset of wal file entry */
  53279. rc = walHashGet(pWal, walFramePage(i), &dummy, &aPgno, &iZero);
  53280. if( rc!=SQLITE_OK ) break;
  53281. pgno = aPgno[i-iZero];
  53282. iDbOff = (i64)(pgno-1) * szPage;
  53283. if( iDbOff+szPage<=szDb ){
  53284. iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
  53285. rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
  53286. if( rc==SQLITE_OK ){
  53287. rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
  53288. }
  53289. if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
  53290. break;
  53291. }
  53292. }
  53293. pInfo->nBackfillAttempted = i-1;
  53294. }
  53295. }
  53296. sqlite3_free(pBuf1);
  53297. sqlite3_free(pBuf2);
  53298. }
  53299. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  53300. }
  53301. return rc;
  53302. }
  53303. #endif /* SQLITE_ENABLE_SNAPSHOT */
  53304. /*
  53305. ** Begin a read transaction on the database.
  53306. **
  53307. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  53308. ** it takes a snapshot of the state of the WAL and wal-index for the current
  53309. ** instant in time. The current thread will continue to use this snapshot.
  53310. ** Other threads might append new content to the WAL and wal-index but
  53311. ** that extra content is ignored by the current thread.
  53312. **
  53313. ** If the database contents have changes since the previous read
  53314. ** transaction, then *pChanged is set to 1 before returning. The
  53315. ** Pager layer will use this to know that is cache is stale and
  53316. ** needs to be flushed.
  53317. */
  53318. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  53319. int rc; /* Return code */
  53320. int cnt = 0; /* Number of TryBeginRead attempts */
  53321. #ifdef SQLITE_ENABLE_SNAPSHOT
  53322. int bChanged = 0;
  53323. WalIndexHdr *pSnapshot = pWal->pSnapshot;
  53324. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  53325. bChanged = 1;
  53326. }
  53327. #endif
  53328. do{
  53329. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  53330. }while( rc==WAL_RETRY );
  53331. testcase( (rc&0xff)==SQLITE_BUSY );
  53332. testcase( (rc&0xff)==SQLITE_IOERR );
  53333. testcase( rc==SQLITE_PROTOCOL );
  53334. testcase( rc==SQLITE_OK );
  53335. #ifdef SQLITE_ENABLE_SNAPSHOT
  53336. if( rc==SQLITE_OK ){
  53337. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  53338. /* At this point the client has a lock on an aReadMark[] slot holding
  53339. ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
  53340. ** is populated with the wal-index header corresponding to the head
  53341. ** of the wal file. Verify that pSnapshot is still valid before
  53342. ** continuing. Reasons why pSnapshot might no longer be valid:
  53343. **
  53344. ** (1) The WAL file has been reset since the snapshot was taken.
  53345. ** In this case, the salt will have changed.
  53346. **
  53347. ** (2) A checkpoint as been attempted that wrote frames past
  53348. ** pSnapshot->mxFrame into the database file. Note that the
  53349. ** checkpoint need not have completed for this to cause problems.
  53350. */
  53351. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  53352. assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
  53353. assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
  53354. /* It is possible that there is a checkpointer thread running
  53355. ** concurrent with this code. If this is the case, it may be that the
  53356. ** checkpointer has already determined that it will checkpoint
  53357. ** snapshot X, where X is later in the wal file than pSnapshot, but
  53358. ** has not yet set the pInfo->nBackfillAttempted variable to indicate
  53359. ** its intent. To avoid the race condition this leads to, ensure that
  53360. ** there is no checkpointer process by taking a shared CKPT lock
  53361. ** before checking pInfo->nBackfillAttempted.
  53362. **
  53363. ** TODO: Does the aReadMark[] lock prevent a checkpointer from doing
  53364. ** this already?
  53365. */
  53366. rc = walLockShared(pWal, WAL_CKPT_LOCK);
  53367. if( rc==SQLITE_OK ){
  53368. /* Check that the wal file has not been wrapped. Assuming that it has
  53369. ** not, also check that no checkpointer has attempted to checkpoint any
  53370. ** frames beyond pSnapshot->mxFrame. If either of these conditions are
  53371. ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr
  53372. ** with *pSnapshot and set *pChanged as appropriate for opening the
  53373. ** snapshot. */
  53374. if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
  53375. && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
  53376. ){
  53377. assert( pWal->readLock>0 );
  53378. memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
  53379. *pChanged = bChanged;
  53380. }else{
  53381. rc = SQLITE_BUSY_SNAPSHOT;
  53382. }
  53383. /* Release the shared CKPT lock obtained above. */
  53384. walUnlockShared(pWal, WAL_CKPT_LOCK);
  53385. }
  53386. if( rc!=SQLITE_OK ){
  53387. sqlite3WalEndReadTransaction(pWal);
  53388. }
  53389. }
  53390. }
  53391. #endif
  53392. return rc;
  53393. }
  53394. /*
  53395. ** Finish with a read transaction. All this does is release the
  53396. ** read-lock.
  53397. */
  53398. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  53399. sqlite3WalEndWriteTransaction(pWal);
  53400. if( pWal->readLock>=0 ){
  53401. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  53402. pWal->readLock = -1;
  53403. }
  53404. }
  53405. /*
  53406. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  53407. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  53408. ** to zero.
  53409. **
  53410. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  53411. ** error does occur, the final value of *piRead is undefined.
  53412. */
  53413. SQLITE_PRIVATE int sqlite3WalFindFrame(
  53414. Wal *pWal, /* WAL handle */
  53415. Pgno pgno, /* Database page number to read data for */
  53416. u32 *piRead /* OUT: Frame number (or zero) */
  53417. ){
  53418. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  53419. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  53420. int iHash; /* Used to loop through N hash tables */
  53421. int iMinHash;
  53422. /* This routine is only be called from within a read transaction. */
  53423. assert( pWal->readLock>=0 || pWal->lockError );
  53424. /* If the "last page" field of the wal-index header snapshot is 0, then
  53425. ** no data will be read from the wal under any circumstances. Return early
  53426. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  53427. ** then the WAL is ignored by the reader so return early, as if the
  53428. ** WAL were empty.
  53429. */
  53430. if( iLast==0 || pWal->readLock==0 ){
  53431. *piRead = 0;
  53432. return SQLITE_OK;
  53433. }
  53434. /* Search the hash table or tables for an entry matching page number
  53435. ** pgno. Each iteration of the following for() loop searches one
  53436. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  53437. **
  53438. ** This code might run concurrently to the code in walIndexAppend()
  53439. ** that adds entries to the wal-index (and possibly to this hash
  53440. ** table). This means the value just read from the hash
  53441. ** slot (aHash[iKey]) may have been added before or after the
  53442. ** current read transaction was opened. Values added after the
  53443. ** read transaction was opened may have been written incorrectly -
  53444. ** i.e. these slots may contain garbage data. However, we assume
  53445. ** that any slots written before the current read transaction was
  53446. ** opened remain unmodified.
  53447. **
  53448. ** For the reasons above, the if(...) condition featured in the inner
  53449. ** loop of the following block is more stringent that would be required
  53450. ** if we had exclusive access to the hash-table:
  53451. **
  53452. ** (aPgno[iFrame]==pgno):
  53453. ** This condition filters out normal hash-table collisions.
  53454. **
  53455. ** (iFrame<=iLast):
  53456. ** This condition filters out entries that were added to the hash
  53457. ** table after the current read-transaction had started.
  53458. */
  53459. iMinHash = walFramePage(pWal->minFrame);
  53460. for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
  53461. volatile ht_slot *aHash; /* Pointer to hash table */
  53462. volatile u32 *aPgno; /* Pointer to array of page numbers */
  53463. u32 iZero; /* Frame number corresponding to aPgno[0] */
  53464. int iKey; /* Hash slot index */
  53465. int nCollide; /* Number of hash collisions remaining */
  53466. int rc; /* Error code */
  53467. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  53468. if( rc!=SQLITE_OK ){
  53469. return rc;
  53470. }
  53471. nCollide = HASHTABLE_NSLOT;
  53472. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  53473. u32 iFrame = aHash[iKey] + iZero;
  53474. if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
  53475. assert( iFrame>iRead || CORRUPT_DB );
  53476. iRead = iFrame;
  53477. }
  53478. if( (nCollide--)==0 ){
  53479. return SQLITE_CORRUPT_BKPT;
  53480. }
  53481. }
  53482. }
  53483. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  53484. /* If expensive assert() statements are available, do a linear search
  53485. ** of the wal-index file content. Make sure the results agree with the
  53486. ** result obtained using the hash indexes above. */
  53487. {
  53488. u32 iRead2 = 0;
  53489. u32 iTest;
  53490. assert( pWal->minFrame>0 );
  53491. for(iTest=iLast; iTest>=pWal->minFrame; iTest--){
  53492. if( walFramePgno(pWal, iTest)==pgno ){
  53493. iRead2 = iTest;
  53494. break;
  53495. }
  53496. }
  53497. assert( iRead==iRead2 );
  53498. }
  53499. #endif
  53500. *piRead = iRead;
  53501. return SQLITE_OK;
  53502. }
  53503. /*
  53504. ** Read the contents of frame iRead from the wal file into buffer pOut
  53505. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  53506. ** error code otherwise.
  53507. */
  53508. SQLITE_PRIVATE int sqlite3WalReadFrame(
  53509. Wal *pWal, /* WAL handle */
  53510. u32 iRead, /* Frame to read */
  53511. int nOut, /* Size of buffer pOut in bytes */
  53512. u8 *pOut /* Buffer to write page data to */
  53513. ){
  53514. int sz;
  53515. i64 iOffset;
  53516. sz = pWal->hdr.szPage;
  53517. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  53518. testcase( sz<=32768 );
  53519. testcase( sz>=65536 );
  53520. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  53521. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  53522. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  53523. }
  53524. /*
  53525. ** Return the size of the database in pages (or zero, if unknown).
  53526. */
  53527. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  53528. if( pWal && ALWAYS(pWal->readLock>=0) ){
  53529. return pWal->hdr.nPage;
  53530. }
  53531. return 0;
  53532. }
  53533. /*
  53534. ** This function starts a write transaction on the WAL.
  53535. **
  53536. ** A read transaction must have already been started by a prior call
  53537. ** to sqlite3WalBeginReadTransaction().
  53538. **
  53539. ** If another thread or process has written into the database since
  53540. ** the read transaction was started, then it is not possible for this
  53541. ** thread to write as doing so would cause a fork. So this routine
  53542. ** returns SQLITE_BUSY in that case and no write transaction is started.
  53543. **
  53544. ** There can only be a single writer active at a time.
  53545. */
  53546. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  53547. int rc;
  53548. /* Cannot start a write transaction without first holding a read
  53549. ** transaction. */
  53550. assert( pWal->readLock>=0 );
  53551. assert( pWal->writeLock==0 && pWal->iReCksum==0 );
  53552. if( pWal->readOnly ){
  53553. return SQLITE_READONLY;
  53554. }
  53555. /* Only one writer allowed at a time. Get the write lock. Return
  53556. ** SQLITE_BUSY if unable.
  53557. */
  53558. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  53559. if( rc ){
  53560. return rc;
  53561. }
  53562. pWal->writeLock = 1;
  53563. /* If another connection has written to the database file since the
  53564. ** time the read transaction on this connection was started, then
  53565. ** the write is disallowed.
  53566. */
  53567. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  53568. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  53569. pWal->writeLock = 0;
  53570. rc = SQLITE_BUSY_SNAPSHOT;
  53571. }
  53572. return rc;
  53573. }
  53574. /*
  53575. ** End a write transaction. The commit has already been done. This
  53576. ** routine merely releases the lock.
  53577. */
  53578. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  53579. if( pWal->writeLock ){
  53580. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  53581. pWal->writeLock = 0;
  53582. pWal->iReCksum = 0;
  53583. pWal->truncateOnCommit = 0;
  53584. }
  53585. return SQLITE_OK;
  53586. }
  53587. /*
  53588. ** If any data has been written (but not committed) to the log file, this
  53589. ** function moves the write-pointer back to the start of the transaction.
  53590. **
  53591. ** Additionally, the callback function is invoked for each frame written
  53592. ** to the WAL since the start of the transaction. If the callback returns
  53593. ** other than SQLITE_OK, it is not invoked again and the error code is
  53594. ** returned to the caller.
  53595. **
  53596. ** Otherwise, if the callback function does not return an error, this
  53597. ** function returns SQLITE_OK.
  53598. */
  53599. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  53600. int rc = SQLITE_OK;
  53601. if( ALWAYS(pWal->writeLock) ){
  53602. Pgno iMax = pWal->hdr.mxFrame;
  53603. Pgno iFrame;
  53604. /* Restore the clients cache of the wal-index header to the state it
  53605. ** was in before the client began writing to the database.
  53606. */
  53607. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  53608. for(iFrame=pWal->hdr.mxFrame+1;
  53609. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  53610. iFrame++
  53611. ){
  53612. /* This call cannot fail. Unless the page for which the page number
  53613. ** is passed as the second argument is (a) in the cache and
  53614. ** (b) has an outstanding reference, then xUndo is either a no-op
  53615. ** (if (a) is false) or simply expels the page from the cache (if (b)
  53616. ** is false).
  53617. **
  53618. ** If the upper layer is doing a rollback, it is guaranteed that there
  53619. ** are no outstanding references to any page other than page 1. And
  53620. ** page 1 is never written to the log until the transaction is
  53621. ** committed. As a result, the call to xUndo may not fail.
  53622. */
  53623. assert( walFramePgno(pWal, iFrame)!=1 );
  53624. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  53625. }
  53626. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  53627. }
  53628. return rc;
  53629. }
  53630. /*
  53631. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  53632. ** values. This function populates the array with values required to
  53633. ** "rollback" the write position of the WAL handle back to the current
  53634. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  53635. */
  53636. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  53637. assert( pWal->writeLock );
  53638. aWalData[0] = pWal->hdr.mxFrame;
  53639. aWalData[1] = pWal->hdr.aFrameCksum[0];
  53640. aWalData[2] = pWal->hdr.aFrameCksum[1];
  53641. aWalData[3] = pWal->nCkpt;
  53642. }
  53643. /*
  53644. ** Move the write position of the WAL back to the point identified by
  53645. ** the values in the aWalData[] array. aWalData must point to an array
  53646. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  53647. ** by a call to WalSavepoint().
  53648. */
  53649. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  53650. int rc = SQLITE_OK;
  53651. assert( pWal->writeLock );
  53652. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  53653. if( aWalData[3]!=pWal->nCkpt ){
  53654. /* This savepoint was opened immediately after the write-transaction
  53655. ** was started. Right after that, the writer decided to wrap around
  53656. ** to the start of the log. Update the savepoint values to match.
  53657. */
  53658. aWalData[0] = 0;
  53659. aWalData[3] = pWal->nCkpt;
  53660. }
  53661. if( aWalData[0]<pWal->hdr.mxFrame ){
  53662. pWal->hdr.mxFrame = aWalData[0];
  53663. pWal->hdr.aFrameCksum[0] = aWalData[1];
  53664. pWal->hdr.aFrameCksum[1] = aWalData[2];
  53665. walCleanupHash(pWal);
  53666. }
  53667. return rc;
  53668. }
  53669. /*
  53670. ** This function is called just before writing a set of frames to the log
  53671. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  53672. ** to the current log file, it is possible to overwrite the start of the
  53673. ** existing log file with the new frames (i.e. "reset" the log). If so,
  53674. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  53675. ** unchanged.
  53676. **
  53677. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  53678. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  53679. ** if an error occurs.
  53680. */
  53681. static int walRestartLog(Wal *pWal){
  53682. int rc = SQLITE_OK;
  53683. int cnt;
  53684. if( pWal->readLock==0 ){
  53685. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  53686. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  53687. if( pInfo->nBackfill>0 ){
  53688. u32 salt1;
  53689. sqlite3_randomness(4, &salt1);
  53690. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  53691. if( rc==SQLITE_OK ){
  53692. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  53693. ** readers are currently using the WAL), then the transactions
  53694. ** frames will overwrite the start of the existing log. Update the
  53695. ** wal-index header to reflect this.
  53696. **
  53697. ** In theory it would be Ok to update the cache of the header only
  53698. ** at this point. But updating the actual wal-index header is also
  53699. ** safe and means there is no special case for sqlite3WalUndo()
  53700. ** to handle if this transaction is rolled back. */
  53701. walRestartHdr(pWal, salt1);
  53702. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  53703. }else if( rc!=SQLITE_BUSY ){
  53704. return rc;
  53705. }
  53706. }
  53707. walUnlockShared(pWal, WAL_READ_LOCK(0));
  53708. pWal->readLock = -1;
  53709. cnt = 0;
  53710. do{
  53711. int notUsed;
  53712. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  53713. }while( rc==WAL_RETRY );
  53714. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  53715. testcase( (rc&0xff)==SQLITE_IOERR );
  53716. testcase( rc==SQLITE_PROTOCOL );
  53717. testcase( rc==SQLITE_OK );
  53718. }
  53719. return rc;
  53720. }
  53721. /*
  53722. ** Information about the current state of the WAL file and where
  53723. ** the next fsync should occur - passed from sqlite3WalFrames() into
  53724. ** walWriteToLog().
  53725. */
  53726. typedef struct WalWriter {
  53727. Wal *pWal; /* The complete WAL information */
  53728. sqlite3_file *pFd; /* The WAL file to which we write */
  53729. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  53730. int syncFlags; /* Flags for the fsync */
  53731. int szPage; /* Size of one page */
  53732. } WalWriter;
  53733. /*
  53734. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  53735. ** Do a sync when crossing the p->iSyncPoint boundary.
  53736. **
  53737. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  53738. ** first write the part before iSyncPoint, then sync, then write the
  53739. ** rest.
  53740. */
  53741. static int walWriteToLog(
  53742. WalWriter *p, /* WAL to write to */
  53743. void *pContent, /* Content to be written */
  53744. int iAmt, /* Number of bytes to write */
  53745. sqlite3_int64 iOffset /* Start writing at this offset */
  53746. ){
  53747. int rc;
  53748. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  53749. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  53750. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  53751. if( rc ) return rc;
  53752. iOffset += iFirstAmt;
  53753. iAmt -= iFirstAmt;
  53754. pContent = (void*)(iFirstAmt + (char*)pContent);
  53755. assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
  53756. rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
  53757. if( iAmt==0 || rc ) return rc;
  53758. }
  53759. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  53760. return rc;
  53761. }
  53762. /*
  53763. ** Write out a single frame of the WAL
  53764. */
  53765. static int walWriteOneFrame(
  53766. WalWriter *p, /* Where to write the frame */
  53767. PgHdr *pPage, /* The page of the frame to be written */
  53768. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  53769. sqlite3_int64 iOffset /* Byte offset at which to write */
  53770. ){
  53771. int rc; /* Result code from subfunctions */
  53772. void *pData; /* Data actually written */
  53773. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  53774. #if defined(SQLITE_HAS_CODEC)
  53775. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
  53776. #else
  53777. pData = pPage->pData;
  53778. #endif
  53779. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  53780. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  53781. if( rc ) return rc;
  53782. /* Write the page data */
  53783. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  53784. return rc;
  53785. }
  53786. /*
  53787. ** This function is called as part of committing a transaction within which
  53788. ** one or more frames have been overwritten. It updates the checksums for
  53789. ** all frames written to the wal file by the current transaction starting
  53790. ** with the earliest to have been overwritten.
  53791. **
  53792. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  53793. */
  53794. static int walRewriteChecksums(Wal *pWal, u32 iLast){
  53795. const int szPage = pWal->szPage;/* Database page size */
  53796. int rc = SQLITE_OK; /* Return code */
  53797. u8 *aBuf; /* Buffer to load data from wal file into */
  53798. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
  53799. u32 iRead; /* Next frame to read from wal file */
  53800. i64 iCksumOff;
  53801. aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
  53802. if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
  53803. /* Find the checksum values to use as input for the recalculating the
  53804. ** first checksum. If the first frame is frame 1 (implying that the current
  53805. ** transaction restarted the wal file), these values must be read from the
  53806. ** wal-file header. Otherwise, read them from the frame header of the
  53807. ** previous frame. */
  53808. assert( pWal->iReCksum>0 );
  53809. if( pWal->iReCksum==1 ){
  53810. iCksumOff = 24;
  53811. }else{
  53812. iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
  53813. }
  53814. rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
  53815. pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
  53816. pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
  53817. iRead = pWal->iReCksum;
  53818. pWal->iReCksum = 0;
  53819. for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
  53820. i64 iOff = walFrameOffset(iRead, szPage);
  53821. rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
  53822. if( rc==SQLITE_OK ){
  53823. u32 iPgno, nDbSize;
  53824. iPgno = sqlite3Get4byte(aBuf);
  53825. nDbSize = sqlite3Get4byte(&aBuf[4]);
  53826. walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
  53827. rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
  53828. }
  53829. }
  53830. sqlite3_free(aBuf);
  53831. return rc;
  53832. }
  53833. /*
  53834. ** Write a set of frames to the log. The caller must hold the write-lock
  53835. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  53836. */
  53837. SQLITE_PRIVATE int sqlite3WalFrames(
  53838. Wal *pWal, /* Wal handle to write to */
  53839. int szPage, /* Database page-size in bytes */
  53840. PgHdr *pList, /* List of dirty pages to write */
  53841. Pgno nTruncate, /* Database size after this commit */
  53842. int isCommit, /* True if this is a commit */
  53843. int sync_flags /* Flags to pass to OsSync() (or 0) */
  53844. ){
  53845. int rc; /* Used to catch return codes */
  53846. u32 iFrame; /* Next frame address */
  53847. PgHdr *p; /* Iterator to run through pList with. */
  53848. PgHdr *pLast = 0; /* Last frame in list */
  53849. int nExtra = 0; /* Number of extra copies of last page */
  53850. int szFrame; /* The size of a single frame */
  53851. i64 iOffset; /* Next byte to write in WAL file */
  53852. WalWriter w; /* The writer */
  53853. u32 iFirst = 0; /* First frame that may be overwritten */
  53854. WalIndexHdr *pLive; /* Pointer to shared header */
  53855. assert( pList );
  53856. assert( pWal->writeLock );
  53857. /* If this frame set completes a transaction, then nTruncate>0. If
  53858. ** nTruncate==0 then this frame set does not complete the transaction. */
  53859. assert( (isCommit!=0)==(nTruncate!=0) );
  53860. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  53861. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  53862. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  53863. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  53864. }
  53865. #endif
  53866. pLive = (WalIndexHdr*)walIndexHdr(pWal);
  53867. if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
  53868. iFirst = pLive->mxFrame+1;
  53869. }
  53870. /* See if it is possible to write these frames into the start of the
  53871. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  53872. */
  53873. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  53874. return rc;
  53875. }
  53876. /* If this is the first frame written into the log, write the WAL
  53877. ** header to the start of the WAL file. See comments at the top of
  53878. ** this source file for a description of the WAL header format.
  53879. */
  53880. iFrame = pWal->hdr.mxFrame;
  53881. if( iFrame==0 ){
  53882. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  53883. u32 aCksum[2]; /* Checksum for wal-header */
  53884. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  53885. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  53886. sqlite3Put4byte(&aWalHdr[8], szPage);
  53887. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  53888. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  53889. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  53890. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  53891. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  53892. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  53893. pWal->szPage = szPage;
  53894. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  53895. pWal->hdr.aFrameCksum[0] = aCksum[0];
  53896. pWal->hdr.aFrameCksum[1] = aCksum[1];
  53897. pWal->truncateOnCommit = 1;
  53898. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  53899. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  53900. if( rc!=SQLITE_OK ){
  53901. return rc;
  53902. }
  53903. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  53904. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  53905. ** an out-of-order write following a WAL restart could result in
  53906. ** database corruption. See the ticket:
  53907. **
  53908. ** http://localhost:591/sqlite/info/ff5be73dee
  53909. */
  53910. if( pWal->syncHeader && sync_flags ){
  53911. rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
  53912. if( rc ) return rc;
  53913. }
  53914. }
  53915. assert( (int)pWal->szPage==szPage );
  53916. /* Setup information needed to write frames into the WAL */
  53917. w.pWal = pWal;
  53918. w.pFd = pWal->pWalFd;
  53919. w.iSyncPoint = 0;
  53920. w.syncFlags = sync_flags;
  53921. w.szPage = szPage;
  53922. iOffset = walFrameOffset(iFrame+1, szPage);
  53923. szFrame = szPage + WAL_FRAME_HDRSIZE;
  53924. /* Write all frames into the log file exactly once */
  53925. for(p=pList; p; p=p->pDirty){
  53926. int nDbSize; /* 0 normally. Positive == commit flag */
  53927. /* Check if this page has already been written into the wal file by
  53928. ** the current transaction. If so, overwrite the existing frame and
  53929. ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
  53930. ** checksums must be recomputed when the transaction is committed. */
  53931. if( iFirst && (p->pDirty || isCommit==0) ){
  53932. u32 iWrite = 0;
  53933. VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
  53934. assert( rc==SQLITE_OK || iWrite==0 );
  53935. if( iWrite>=iFirst ){
  53936. i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
  53937. void *pData;
  53938. if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
  53939. pWal->iReCksum = iWrite;
  53940. }
  53941. #if defined(SQLITE_HAS_CODEC)
  53942. if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
  53943. #else
  53944. pData = p->pData;
  53945. #endif
  53946. rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
  53947. if( rc ) return rc;
  53948. p->flags &= ~PGHDR_WAL_APPEND;
  53949. continue;
  53950. }
  53951. }
  53952. iFrame++;
  53953. assert( iOffset==walFrameOffset(iFrame, szPage) );
  53954. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  53955. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  53956. if( rc ) return rc;
  53957. pLast = p;
  53958. iOffset += szFrame;
  53959. p->flags |= PGHDR_WAL_APPEND;
  53960. }
  53961. /* Recalculate checksums within the wal file if required. */
  53962. if( isCommit && pWal->iReCksum ){
  53963. rc = walRewriteChecksums(pWal, iFrame);
  53964. if( rc ) return rc;
  53965. }
  53966. /* If this is the end of a transaction, then we might need to pad
  53967. ** the transaction and/or sync the WAL file.
  53968. **
  53969. ** Padding and syncing only occur if this set of frames complete a
  53970. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  53971. ** or synchronous==OFF, then no padding or syncing are needed.
  53972. **
  53973. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  53974. ** needed and only the sync is done. If padding is needed, then the
  53975. ** final frame is repeated (with its commit mark) until the next sector
  53976. ** boundary is crossed. Only the part of the WAL prior to the last
  53977. ** sector boundary is synced; the part of the last frame that extends
  53978. ** past the sector boundary is written after the sync.
  53979. */
  53980. if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
  53981. int bSync = 1;
  53982. if( pWal->padToSectorBoundary ){
  53983. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  53984. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  53985. bSync = (w.iSyncPoint==iOffset);
  53986. testcase( bSync );
  53987. while( iOffset<w.iSyncPoint ){
  53988. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  53989. if( rc ) return rc;
  53990. iOffset += szFrame;
  53991. nExtra++;
  53992. }
  53993. }
  53994. if( bSync ){
  53995. assert( rc==SQLITE_OK );
  53996. rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
  53997. }
  53998. }
  53999. /* If this frame set completes the first transaction in the WAL and
  54000. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  54001. ** journal size limit, if possible.
  54002. */
  54003. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  54004. i64 sz = pWal->mxWalSize;
  54005. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  54006. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  54007. }
  54008. walLimitSize(pWal, sz);
  54009. pWal->truncateOnCommit = 0;
  54010. }
  54011. /* Append data to the wal-index. It is not necessary to lock the
  54012. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  54013. ** guarantees that there are no other writers, and no data that may
  54014. ** be in use by existing readers is being overwritten.
  54015. */
  54016. iFrame = pWal->hdr.mxFrame;
  54017. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  54018. if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
  54019. iFrame++;
  54020. rc = walIndexAppend(pWal, iFrame, p->pgno);
  54021. }
  54022. while( rc==SQLITE_OK && nExtra>0 ){
  54023. iFrame++;
  54024. nExtra--;
  54025. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  54026. }
  54027. if( rc==SQLITE_OK ){
  54028. /* Update the private copy of the header. */
  54029. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  54030. testcase( szPage<=32768 );
  54031. testcase( szPage>=65536 );
  54032. pWal->hdr.mxFrame = iFrame;
  54033. if( isCommit ){
  54034. pWal->hdr.iChange++;
  54035. pWal->hdr.nPage = nTruncate;
  54036. }
  54037. /* If this is a commit, update the wal-index header too. */
  54038. if( isCommit ){
  54039. walIndexWriteHdr(pWal);
  54040. pWal->iCallback = iFrame;
  54041. }
  54042. }
  54043. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  54044. return rc;
  54045. }
  54046. /*
  54047. ** This routine is called to implement sqlite3_wal_checkpoint() and
  54048. ** related interfaces.
  54049. **
  54050. ** Obtain a CHECKPOINT lock and then backfill as much information as
  54051. ** we can from WAL into the database.
  54052. **
  54053. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  54054. ** callback. In this case this function runs a blocking checkpoint.
  54055. */
  54056. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  54057. Wal *pWal, /* Wal connection */
  54058. sqlite3 *db, /* Check this handle's interrupt flag */
  54059. int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
  54060. int (*xBusy)(void*), /* Function to call when busy */
  54061. void *pBusyArg, /* Context argument for xBusyHandler */
  54062. int sync_flags, /* Flags to sync db file with (or 0) */
  54063. int nBuf, /* Size of temporary buffer */
  54064. u8 *zBuf, /* Temporary buffer to use */
  54065. int *pnLog, /* OUT: Number of frames in WAL */
  54066. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  54067. ){
  54068. int rc; /* Return code */
  54069. int isChanged = 0; /* True if a new wal-index header is loaded */
  54070. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  54071. int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
  54072. assert( pWal->ckptLock==0 );
  54073. assert( pWal->writeLock==0 );
  54074. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  54075. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  54076. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  54077. if( pWal->readOnly ) return SQLITE_READONLY;
  54078. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  54079. /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
  54080. ** "checkpoint" lock on the database file. */
  54081. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  54082. if( rc ){
  54083. /* EVIDENCE-OF: R-10421-19736 If any other process is running a
  54084. ** checkpoint operation at the same time, the lock cannot be obtained and
  54085. ** SQLITE_BUSY is returned.
  54086. ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
  54087. ** it will not be invoked in this case.
  54088. */
  54089. testcase( rc==SQLITE_BUSY );
  54090. testcase( xBusy!=0 );
  54091. return rc;
  54092. }
  54093. pWal->ckptLock = 1;
  54094. /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
  54095. ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
  54096. ** file.
  54097. **
  54098. ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
  54099. ** immediately, and a busy-handler is configured, it is invoked and the
  54100. ** writer lock retried until either the busy-handler returns 0 or the
  54101. ** lock is successfully obtained.
  54102. */
  54103. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  54104. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  54105. if( rc==SQLITE_OK ){
  54106. pWal->writeLock = 1;
  54107. }else if( rc==SQLITE_BUSY ){
  54108. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  54109. xBusy2 = 0;
  54110. rc = SQLITE_OK;
  54111. }
  54112. }
  54113. /* Read the wal-index header. */
  54114. if( rc==SQLITE_OK ){
  54115. rc = walIndexReadHdr(pWal, &isChanged);
  54116. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  54117. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  54118. }
  54119. }
  54120. /* Copy data from the log to the database file. */
  54121. if( rc==SQLITE_OK ){
  54122. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  54123. rc = SQLITE_CORRUPT_BKPT;
  54124. }else{
  54125. rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
  54126. }
  54127. /* If no error occurred, set the output variables. */
  54128. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  54129. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  54130. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  54131. }
  54132. }
  54133. if( isChanged ){
  54134. /* If a new wal-index header was loaded before the checkpoint was
  54135. ** performed, then the pager-cache associated with pWal is now
  54136. ** out of date. So zero the cached wal-index header to ensure that
  54137. ** next time the pager opens a snapshot on this database it knows that
  54138. ** the cache needs to be reset.
  54139. */
  54140. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  54141. }
  54142. /* Release the locks. */
  54143. sqlite3WalEndWriteTransaction(pWal);
  54144. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  54145. pWal->ckptLock = 0;
  54146. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  54147. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  54148. }
  54149. /* Return the value to pass to a sqlite3_wal_hook callback, the
  54150. ** number of frames in the WAL at the point of the last commit since
  54151. ** sqlite3WalCallback() was called. If no commits have occurred since
  54152. ** the last call, then return 0.
  54153. */
  54154. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  54155. u32 ret = 0;
  54156. if( pWal ){
  54157. ret = pWal->iCallback;
  54158. pWal->iCallback = 0;
  54159. }
  54160. return (int)ret;
  54161. }
  54162. /*
  54163. ** This function is called to change the WAL subsystem into or out
  54164. ** of locking_mode=EXCLUSIVE.
  54165. **
  54166. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  54167. ** into locking_mode=NORMAL. This means that we must acquire a lock
  54168. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  54169. ** or if the acquisition of the lock fails, then return 0. If the
  54170. ** transition out of exclusive-mode is successful, return 1. This
  54171. ** operation must occur while the pager is still holding the exclusive
  54172. ** lock on the main database file.
  54173. **
  54174. ** If op is one, then change from locking_mode=NORMAL into
  54175. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  54176. ** be released. Return 1 if the transition is made and 0 if the
  54177. ** WAL is already in exclusive-locking mode - meaning that this
  54178. ** routine is a no-op. The pager must already hold the exclusive lock
  54179. ** on the main database file before invoking this operation.
  54180. **
  54181. ** If op is negative, then do a dry-run of the op==1 case but do
  54182. ** not actually change anything. The pager uses this to see if it
  54183. ** should acquire the database exclusive lock prior to invoking
  54184. ** the op==1 case.
  54185. */
  54186. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  54187. int rc;
  54188. assert( pWal->writeLock==0 );
  54189. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  54190. /* pWal->readLock is usually set, but might be -1 if there was a
  54191. ** prior error while attempting to acquire are read-lock. This cannot
  54192. ** happen if the connection is actually in exclusive mode (as no xShmLock
  54193. ** locks are taken in this case). Nor should the pager attempt to
  54194. ** upgrade to exclusive-mode following such an error.
  54195. */
  54196. assert( pWal->readLock>=0 || pWal->lockError );
  54197. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  54198. if( op==0 ){
  54199. if( pWal->exclusiveMode ){
  54200. pWal->exclusiveMode = 0;
  54201. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  54202. pWal->exclusiveMode = 1;
  54203. }
  54204. rc = pWal->exclusiveMode==0;
  54205. }else{
  54206. /* Already in locking_mode=NORMAL */
  54207. rc = 0;
  54208. }
  54209. }else if( op>0 ){
  54210. assert( pWal->exclusiveMode==0 );
  54211. assert( pWal->readLock>=0 );
  54212. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  54213. pWal->exclusiveMode = 1;
  54214. rc = 1;
  54215. }else{
  54216. rc = pWal->exclusiveMode==0;
  54217. }
  54218. return rc;
  54219. }
  54220. /*
  54221. ** Return true if the argument is non-NULL and the WAL module is using
  54222. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  54223. ** WAL module is using shared-memory, return false.
  54224. */
  54225. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  54226. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  54227. }
  54228. #ifdef SQLITE_ENABLE_SNAPSHOT
  54229. /* Create a snapshot object. The content of a snapshot is opaque to
  54230. ** every other subsystem, so the WAL module can put whatever it needs
  54231. ** in the object.
  54232. */
  54233. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
  54234. int rc = SQLITE_OK;
  54235. WalIndexHdr *pRet;
  54236. static const u32 aZero[4] = { 0, 0, 0, 0 };
  54237. assert( pWal->readLock>=0 && pWal->writeLock==0 );
  54238. if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
  54239. *ppSnapshot = 0;
  54240. return SQLITE_ERROR;
  54241. }
  54242. pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
  54243. if( pRet==0 ){
  54244. rc = SQLITE_NOMEM_BKPT;
  54245. }else{
  54246. memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
  54247. *ppSnapshot = (sqlite3_snapshot*)pRet;
  54248. }
  54249. return rc;
  54250. }
  54251. /* Try to open on pSnapshot when the next read-transaction starts
  54252. */
  54253. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
  54254. pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
  54255. }
  54256. /*
  54257. ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
  54258. ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
  54259. */
  54260. SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
  54261. WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
  54262. WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
  54263. /* aSalt[0] is a copy of the value stored in the wal file header. It
  54264. ** is incremented each time the wal file is restarted. */
  54265. if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
  54266. if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
  54267. if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
  54268. if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
  54269. return 0;
  54270. }
  54271. #endif /* SQLITE_ENABLE_SNAPSHOT */
  54272. #ifdef SQLITE_ENABLE_ZIPVFS
  54273. /*
  54274. ** If the argument is not NULL, it points to a Wal object that holds a
  54275. ** read-lock. This function returns the database page-size if it is known,
  54276. ** or zero if it is not (or if pWal is NULL).
  54277. */
  54278. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  54279. assert( pWal==0 || pWal->readLock>=0 );
  54280. return (pWal ? pWal->szPage : 0);
  54281. }
  54282. #endif
  54283. /* Return the sqlite3_file object for the WAL file
  54284. */
  54285. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
  54286. return pWal->pWalFd;
  54287. }
  54288. #endif /* #ifndef SQLITE_OMIT_WAL */
  54289. /************** End of wal.c *************************************************/
  54290. /************** Begin file btmutex.c *****************************************/
  54291. /*
  54292. ** 2007 August 27
  54293. **
  54294. ** The author disclaims copyright to this source code. In place of
  54295. ** a legal notice, here is a blessing:
  54296. **
  54297. ** May you do good and not evil.
  54298. ** May you find forgiveness for yourself and forgive others.
  54299. ** May you share freely, never taking more than you give.
  54300. **
  54301. *************************************************************************
  54302. **
  54303. ** This file contains code used to implement mutexes on Btree objects.
  54304. ** This code really belongs in btree.c. But btree.c is getting too
  54305. ** big and we want to break it down some. This packaged seemed like
  54306. ** a good breakout.
  54307. */
  54308. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  54309. /************** Begin file btreeInt.h ****************************************/
  54310. /*
  54311. ** 2004 April 6
  54312. **
  54313. ** The author disclaims copyright to this source code. In place of
  54314. ** a legal notice, here is a blessing:
  54315. **
  54316. ** May you do good and not evil.
  54317. ** May you find forgiveness for yourself and forgive others.
  54318. ** May you share freely, never taking more than you give.
  54319. **
  54320. *************************************************************************
  54321. ** This file implements an external (disk-based) database using BTrees.
  54322. ** For a detailed discussion of BTrees, refer to
  54323. **
  54324. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  54325. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  54326. ** Publishing Company, Reading, Massachusetts.
  54327. **
  54328. ** The basic idea is that each page of the file contains N database
  54329. ** entries and N+1 pointers to subpages.
  54330. **
  54331. ** ----------------------------------------------------------------
  54332. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  54333. ** ----------------------------------------------------------------
  54334. **
  54335. ** All of the keys on the page that Ptr(0) points to have values less
  54336. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  54337. ** values greater than Key(0) and less than Key(1). All of the keys
  54338. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  54339. ** so forth.
  54340. **
  54341. ** Finding a particular key requires reading O(log(M)) pages from the
  54342. ** disk where M is the number of entries in the tree.
  54343. **
  54344. ** In this implementation, a single file can hold one or more separate
  54345. ** BTrees. Each BTree is identified by the index of its root page. The
  54346. ** key and data for any entry are combined to form the "payload". A
  54347. ** fixed amount of payload can be carried directly on the database
  54348. ** page. If the payload is larger than the preset amount then surplus
  54349. ** bytes are stored on overflow pages. The payload for an entry
  54350. ** and the preceding pointer are combined to form a "Cell". Each
  54351. ** page has a small header which contains the Ptr(N) pointer and other
  54352. ** information such as the size of key and data.
  54353. **
  54354. ** FORMAT DETAILS
  54355. **
  54356. ** The file is divided into pages. The first page is called page 1,
  54357. ** the second is page 2, and so forth. A page number of zero indicates
  54358. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  54359. ** Each page can be either a btree page, a freelist page, an overflow
  54360. ** page, or a pointer-map page.
  54361. **
  54362. ** The first page is always a btree page. The first 100 bytes of the first
  54363. ** page contain a special header (the "file header") that describes the file.
  54364. ** The format of the file header is as follows:
  54365. **
  54366. ** OFFSET SIZE DESCRIPTION
  54367. ** 0 16 Header string: "SQLite format 3\000"
  54368. ** 16 2 Page size in bytes. (1 means 65536)
  54369. ** 18 1 File format write version
  54370. ** 19 1 File format read version
  54371. ** 20 1 Bytes of unused space at the end of each page
  54372. ** 21 1 Max embedded payload fraction (must be 64)
  54373. ** 22 1 Min embedded payload fraction (must be 32)
  54374. ** 23 1 Min leaf payload fraction (must be 32)
  54375. ** 24 4 File change counter
  54376. ** 28 4 Reserved for future use
  54377. ** 32 4 First freelist page
  54378. ** 36 4 Number of freelist pages in the file
  54379. ** 40 60 15 4-byte meta values passed to higher layers
  54380. **
  54381. ** 40 4 Schema cookie
  54382. ** 44 4 File format of schema layer
  54383. ** 48 4 Size of page cache
  54384. ** 52 4 Largest root-page (auto/incr_vacuum)
  54385. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  54386. ** 60 4 User version
  54387. ** 64 4 Incremental vacuum mode
  54388. ** 68 4 Application-ID
  54389. ** 72 20 unused
  54390. ** 92 4 The version-valid-for number
  54391. ** 96 4 SQLITE_VERSION_NUMBER
  54392. **
  54393. ** All of the integer values are big-endian (most significant byte first).
  54394. **
  54395. ** The file change counter is incremented when the database is changed
  54396. ** This counter allows other processes to know when the file has changed
  54397. ** and thus when they need to flush their cache.
  54398. **
  54399. ** The max embedded payload fraction is the amount of the total usable
  54400. ** space in a page that can be consumed by a single cell for standard
  54401. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  54402. ** is to limit the maximum cell size so that at least 4 cells will fit
  54403. ** on one page. Thus the default max embedded payload fraction is 64.
  54404. **
  54405. ** If the payload for a cell is larger than the max payload, then extra
  54406. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  54407. ** as many bytes as possible are moved into the overflow pages without letting
  54408. ** the cell size drop below the min embedded payload fraction.
  54409. **
  54410. ** The min leaf payload fraction is like the min embedded payload fraction
  54411. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  54412. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  54413. ** not specified in the header.
  54414. **
  54415. ** Each btree pages is divided into three sections: The header, the
  54416. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  54417. ** file header that occurs before the page header.
  54418. **
  54419. ** |----------------|
  54420. ** | file header | 100 bytes. Page 1 only.
  54421. ** |----------------|
  54422. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  54423. ** |----------------|
  54424. ** | cell pointer | | 2 bytes per cell. Sorted order.
  54425. ** | array | | Grows downward
  54426. ** | | v
  54427. ** |----------------|
  54428. ** | unallocated |
  54429. ** | space |
  54430. ** |----------------| ^ Grows upwards
  54431. ** | cell content | | Arbitrary order interspersed with freeblocks.
  54432. ** | area | | and free space fragments.
  54433. ** |----------------|
  54434. **
  54435. ** The page headers looks like this:
  54436. **
  54437. ** OFFSET SIZE DESCRIPTION
  54438. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  54439. ** 1 2 byte offset to the first freeblock
  54440. ** 3 2 number of cells on this page
  54441. ** 5 2 first byte of the cell content area
  54442. ** 7 1 number of fragmented free bytes
  54443. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  54444. **
  54445. ** The flags define the format of this btree page. The leaf flag means that
  54446. ** this page has no children. The zerodata flag means that this page carries
  54447. ** only keys and no data. The intkey flag means that the key is an integer
  54448. ** which is stored in the key size entry of the cell header rather than in
  54449. ** the payload area.
  54450. **
  54451. ** The cell pointer array begins on the first byte after the page header.
  54452. ** The cell pointer array contains zero or more 2-byte numbers which are
  54453. ** offsets from the beginning of the page to the cell content in the cell
  54454. ** content area. The cell pointers occur in sorted order. The system strives
  54455. ** to keep free space after the last cell pointer so that new cells can
  54456. ** be easily added without having to defragment the page.
  54457. **
  54458. ** Cell content is stored at the very end of the page and grows toward the
  54459. ** beginning of the page.
  54460. **
  54461. ** Unused space within the cell content area is collected into a linked list of
  54462. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  54463. ** to the first freeblock is given in the header. Freeblocks occur in
  54464. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  54465. ** any group of 3 or fewer unused bytes in the cell content area cannot
  54466. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  54467. ** a fragment. The total number of bytes in all fragments is recorded.
  54468. ** in the page header at offset 7.
  54469. **
  54470. ** SIZE DESCRIPTION
  54471. ** 2 Byte offset of the next freeblock
  54472. ** 2 Bytes in this freeblock
  54473. **
  54474. ** Cells are of variable length. Cells are stored in the cell content area at
  54475. ** the end of the page. Pointers to the cells are in the cell pointer array
  54476. ** that immediately follows the page header. Cells is not necessarily
  54477. ** contiguous or in order, but cell pointers are contiguous and in order.
  54478. **
  54479. ** Cell content makes use of variable length integers. A variable
  54480. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  54481. ** byte are used. The integer consists of all bytes that have bit 8 set and
  54482. ** the first byte with bit 8 clear. The most significant byte of the integer
  54483. ** appears first. A variable-length integer may not be more than 9 bytes long.
  54484. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  54485. ** allows a 64-bit integer to be encoded in 9 bytes.
  54486. **
  54487. ** 0x00 becomes 0x00000000
  54488. ** 0x7f becomes 0x0000007f
  54489. ** 0x81 0x00 becomes 0x00000080
  54490. ** 0x82 0x00 becomes 0x00000100
  54491. ** 0x80 0x7f becomes 0x0000007f
  54492. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  54493. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  54494. **
  54495. ** Variable length integers are used for rowids and to hold the number of
  54496. ** bytes of key and data in a btree cell.
  54497. **
  54498. ** The content of a cell looks like this:
  54499. **
  54500. ** SIZE DESCRIPTION
  54501. ** 4 Page number of the left child. Omitted if leaf flag is set.
  54502. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  54503. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  54504. ** * Payload
  54505. ** 4 First page of the overflow chain. Omitted if no overflow
  54506. **
  54507. ** Overflow pages form a linked list. Each page except the last is completely
  54508. ** filled with data (pagesize - 4 bytes). The last page can have as little
  54509. ** as 1 byte of data.
  54510. **
  54511. ** SIZE DESCRIPTION
  54512. ** 4 Page number of next overflow page
  54513. ** * Data
  54514. **
  54515. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  54516. ** file header points to the first in a linked list of trunk page. Each trunk
  54517. ** page points to multiple leaf pages. The content of a leaf page is
  54518. ** unspecified. A trunk page looks like this:
  54519. **
  54520. ** SIZE DESCRIPTION
  54521. ** 4 Page number of next trunk page
  54522. ** 4 Number of leaf pointers on this page
  54523. ** * zero or more pages numbers of leaves
  54524. */
  54525. /* #include "sqliteInt.h" */
  54526. /* The following value is the maximum cell size assuming a maximum page
  54527. ** size give above.
  54528. */
  54529. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  54530. /* The maximum number of cells on a single page of the database. This
  54531. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  54532. ** plus 2 bytes for the index to the cell in the page header). Such
  54533. ** small cells will be rare, but they are possible.
  54534. */
  54535. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  54536. /* Forward declarations */
  54537. typedef struct MemPage MemPage;
  54538. typedef struct BtLock BtLock;
  54539. typedef struct CellInfo CellInfo;
  54540. /*
  54541. ** This is a magic string that appears at the beginning of every
  54542. ** SQLite database in order to identify the file as a real database.
  54543. **
  54544. ** You can change this value at compile-time by specifying a
  54545. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  54546. ** header must be exactly 16 bytes including the zero-terminator so
  54547. ** the string itself should be 15 characters long. If you change
  54548. ** the header, then your custom library will not be able to read
  54549. ** databases generated by the standard tools and the standard tools
  54550. ** will not be able to read databases created by your custom library.
  54551. */
  54552. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  54553. # define SQLITE_FILE_HEADER "SQLite format 3"
  54554. #endif
  54555. /*
  54556. ** Page type flags. An ORed combination of these flags appear as the
  54557. ** first byte of on-disk image of every BTree page.
  54558. */
  54559. #define PTF_INTKEY 0x01
  54560. #define PTF_ZERODATA 0x02
  54561. #define PTF_LEAFDATA 0x04
  54562. #define PTF_LEAF 0x08
  54563. /*
  54564. ** An instance of this object stores information about each a single database
  54565. ** page that has been loaded into memory. The information in this object
  54566. ** is derived from the raw on-disk page content.
  54567. **
  54568. ** As each database page is loaded into memory, the pager allocats an
  54569. ** instance of this object and zeros the first 8 bytes. (This is the
  54570. ** "extra" information associated with each page of the pager.)
  54571. **
  54572. ** Access to all fields of this structure is controlled by the mutex
  54573. ** stored in MemPage.pBt->mutex.
  54574. */
  54575. struct MemPage {
  54576. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  54577. u8 bBusy; /* Prevent endless loops on corrupt database files */
  54578. u8 intKey; /* True if table b-trees. False for index b-trees */
  54579. u8 intKeyLeaf; /* True if the leaf of an intKey table */
  54580. Pgno pgno; /* Page number for this page */
  54581. /* Only the first 8 bytes (above) are zeroed by pager.c when a new page
  54582. ** is allocated. All fields that follow must be initialized before use */
  54583. u8 leaf; /* True if a leaf page */
  54584. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  54585. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  54586. u8 max1bytePayload; /* min(maxLocal,127) */
  54587. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  54588. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  54589. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  54590. u16 cellOffset; /* Index in aData of first cell pointer */
  54591. u16 nFree; /* Number of free bytes on the page */
  54592. u16 nCell; /* Number of cells on this page, local and ovfl */
  54593. u16 maskPage; /* Mask for page offset */
  54594. u16 aiOvfl[4]; /* Insert the i-th overflow cell before the aiOvfl-th
  54595. ** non-overflow cell */
  54596. u8 *apOvfl[4]; /* Pointers to the body of overflow cells */
  54597. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  54598. u8 *aData; /* Pointer to disk image of the page data */
  54599. u8 *aDataEnd; /* One byte past the end of usable data */
  54600. u8 *aCellIdx; /* The cell index area */
  54601. u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
  54602. DbPage *pDbPage; /* Pager page handle */
  54603. u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
  54604. void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
  54605. };
  54606. /*
  54607. ** A linked list of the following structures is stored at BtShared.pLock.
  54608. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  54609. ** is opened on the table with root page BtShared.iTable. Locks are removed
  54610. ** from this list when a transaction is committed or rolled back, or when
  54611. ** a btree handle is closed.
  54612. */
  54613. struct BtLock {
  54614. Btree *pBtree; /* Btree handle holding this lock */
  54615. Pgno iTable; /* Root page of table */
  54616. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  54617. BtLock *pNext; /* Next in BtShared.pLock list */
  54618. };
  54619. /* Candidate values for BtLock.eLock */
  54620. #define READ_LOCK 1
  54621. #define WRITE_LOCK 2
  54622. /* A Btree handle
  54623. **
  54624. ** A database connection contains a pointer to an instance of
  54625. ** this object for every database file that it has open. This structure
  54626. ** is opaque to the database connection. The database connection cannot
  54627. ** see the internals of this structure and only deals with pointers to
  54628. ** this structure.
  54629. **
  54630. ** For some database files, the same underlying database cache might be
  54631. ** shared between multiple connections. In that case, each connection
  54632. ** has it own instance of this object. But each instance of this object
  54633. ** points to the same BtShared object. The database cache and the
  54634. ** schema associated with the database file are all contained within
  54635. ** the BtShared object.
  54636. **
  54637. ** All fields in this structure are accessed under sqlite3.mutex.
  54638. ** The pBt pointer itself may not be changed while there exists cursors
  54639. ** in the referenced BtShared that point back to this Btree since those
  54640. ** cursors have to go through this Btree to find their BtShared and
  54641. ** they often do so without holding sqlite3.mutex.
  54642. */
  54643. struct Btree {
  54644. sqlite3 *db; /* The database connection holding this btree */
  54645. BtShared *pBt; /* Sharable content of this btree */
  54646. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  54647. u8 sharable; /* True if we can share pBt with another db */
  54648. u8 locked; /* True if db currently has pBt locked */
  54649. u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
  54650. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  54651. int nBackup; /* Number of backup operations reading this btree */
  54652. u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
  54653. Btree *pNext; /* List of other sharable Btrees from the same db */
  54654. Btree *pPrev; /* Back pointer of the same list */
  54655. #ifndef SQLITE_OMIT_SHARED_CACHE
  54656. BtLock lock; /* Object used to lock page 1 */
  54657. #endif
  54658. };
  54659. /*
  54660. ** Btree.inTrans may take one of the following values.
  54661. **
  54662. ** If the shared-data extension is enabled, there may be multiple users
  54663. ** of the Btree structure. At most one of these may open a write transaction,
  54664. ** but any number may have active read transactions.
  54665. */
  54666. #define TRANS_NONE 0
  54667. #define TRANS_READ 1
  54668. #define TRANS_WRITE 2
  54669. /*
  54670. ** An instance of this object represents a single database file.
  54671. **
  54672. ** A single database file can be in use at the same time by two
  54673. ** or more database connections. When two or more connections are
  54674. ** sharing the same database file, each connection has it own
  54675. ** private Btree object for the file and each of those Btrees points
  54676. ** to this one BtShared object. BtShared.nRef is the number of
  54677. ** connections currently sharing this database file.
  54678. **
  54679. ** Fields in this structure are accessed under the BtShared.mutex
  54680. ** mutex, except for nRef and pNext which are accessed under the
  54681. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  54682. ** may not be modified once it is initially set as long as nRef>0.
  54683. ** The pSchema field may be set once under BtShared.mutex and
  54684. ** thereafter is unchanged as long as nRef>0.
  54685. **
  54686. ** isPending:
  54687. **
  54688. ** If a BtShared client fails to obtain a write-lock on a database
  54689. ** table (because there exists one or more read-locks on the table),
  54690. ** the shared-cache enters 'pending-lock' state and isPending is
  54691. ** set to true.
  54692. **
  54693. ** The shared-cache leaves the 'pending lock' state when either of
  54694. ** the following occur:
  54695. **
  54696. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  54697. ** 2) The number of locks held by other connections drops to zero.
  54698. **
  54699. ** while in the 'pending-lock' state, no connection may start a new
  54700. ** transaction.
  54701. **
  54702. ** This feature is included to help prevent writer-starvation.
  54703. */
  54704. struct BtShared {
  54705. Pager *pPager; /* The page cache */
  54706. sqlite3 *db; /* Database connection currently using this Btree */
  54707. BtCursor *pCursor; /* A list of all open cursors */
  54708. MemPage *pPage1; /* First page of the database */
  54709. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  54710. #ifndef SQLITE_OMIT_AUTOVACUUM
  54711. u8 autoVacuum; /* True if auto-vacuum is enabled */
  54712. u8 incrVacuum; /* True if incr-vacuum is enabled */
  54713. u8 bDoTruncate; /* True to truncate db on commit */
  54714. #endif
  54715. u8 inTransaction; /* Transaction state */
  54716. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  54717. #ifdef SQLITE_HAS_CODEC
  54718. u8 optimalReserve; /* Desired amount of reserved space per page */
  54719. #endif
  54720. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  54721. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  54722. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  54723. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  54724. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  54725. u32 pageSize; /* Total number of bytes on a page */
  54726. u32 usableSize; /* Number of usable bytes on each page */
  54727. int nTransaction; /* Number of open transactions (read + write) */
  54728. u32 nPage; /* Number of pages in the database */
  54729. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  54730. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  54731. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  54732. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  54733. #ifndef SQLITE_OMIT_SHARED_CACHE
  54734. int nRef; /* Number of references to this structure */
  54735. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  54736. BtLock *pLock; /* List of locks held on this shared-btree struct */
  54737. Btree *pWriter; /* Btree with currently open write transaction */
  54738. #endif
  54739. u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
  54740. };
  54741. /*
  54742. ** Allowed values for BtShared.btsFlags
  54743. */
  54744. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  54745. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  54746. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  54747. #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
  54748. #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
  54749. #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
  54750. #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
  54751. /*
  54752. ** An instance of the following structure is used to hold information
  54753. ** about a cell. The parseCellPtr() function fills in this structure
  54754. ** based on information extract from the raw disk page.
  54755. */
  54756. struct CellInfo {
  54757. i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
  54758. u8 *pPayload; /* Pointer to the start of payload */
  54759. u32 nPayload; /* Bytes of payload */
  54760. u16 nLocal; /* Amount of payload held locally, not on overflow */
  54761. u16 nSize; /* Size of the cell content on the main b-tree page */
  54762. };
  54763. /*
  54764. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  54765. ** this will be declared corrupt. This value is calculated based on a
  54766. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  54767. ** root-node and 3 for all other internal nodes.
  54768. **
  54769. ** If a tree that appears to be taller than this is encountered, it is
  54770. ** assumed that the database is corrupt.
  54771. */
  54772. #define BTCURSOR_MAX_DEPTH 20
  54773. /*
  54774. ** A cursor is a pointer to a particular entry within a particular
  54775. ** b-tree within a database file.
  54776. **
  54777. ** The entry is identified by its MemPage and the index in
  54778. ** MemPage.aCell[] of the entry.
  54779. **
  54780. ** A single database file can be shared by two more database connections,
  54781. ** but cursors cannot be shared. Each cursor is associated with a
  54782. ** particular database connection identified BtCursor.pBtree.db.
  54783. **
  54784. ** Fields in this structure are accessed under the BtShared.mutex
  54785. ** found at self->pBt->mutex.
  54786. **
  54787. ** skipNext meaning:
  54788. ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op.
  54789. ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op.
  54790. ** eState==FAULT: Cursor fault with skipNext as error code.
  54791. */
  54792. struct BtCursor {
  54793. Btree *pBtree; /* The Btree to which this cursor belongs */
  54794. BtShared *pBt; /* The BtShared this cursor points to */
  54795. BtCursor *pNext; /* Forms a linked list of all cursors */
  54796. Pgno *aOverflow; /* Cache of overflow page locations */
  54797. CellInfo info; /* A parse of the cell we are pointing at */
  54798. i64 nKey; /* Size of pKey, or last integer key */
  54799. void *pKey; /* Saved key that was cursor last known position */
  54800. Pgno pgnoRoot; /* The root page of this tree */
  54801. int nOvflAlloc; /* Allocated size of aOverflow[] array */
  54802. int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
  54803. ** Error code if eState==CURSOR_FAULT */
  54804. u8 curFlags; /* zero or more BTCF_* flags defined below */
  54805. u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */
  54806. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  54807. u8 hints; /* As configured by CursorSetHints() */
  54808. /* All fields above are zeroed when the cursor is allocated. See
  54809. ** sqlite3BtreeCursorZero(). Fields that follow must be manually
  54810. ** initialized. */
  54811. i8 iPage; /* Index of current page in apPage */
  54812. u8 curIntKey; /* Value of apPage[0]->intKey */
  54813. u16 ix; /* Current index for apPage[iPage] */
  54814. u16 aiIdx[BTCURSOR_MAX_DEPTH-1]; /* Current index in apPage[i] */
  54815. struct KeyInfo *pKeyInfo; /* Arg passed to comparison function */
  54816. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  54817. };
  54818. /*
  54819. ** Legal values for BtCursor.curFlags
  54820. */
  54821. #define BTCF_WriteFlag 0x01 /* True if a write cursor */
  54822. #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
  54823. #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
  54824. #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
  54825. #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
  54826. #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
  54827. /*
  54828. ** Potential values for BtCursor.eState.
  54829. **
  54830. ** CURSOR_INVALID:
  54831. ** Cursor does not point to a valid entry. This can happen (for example)
  54832. ** because the table is empty or because BtreeCursorFirst() has not been
  54833. ** called.
  54834. **
  54835. ** CURSOR_VALID:
  54836. ** Cursor points to a valid entry. getPayload() etc. may be called.
  54837. **
  54838. ** CURSOR_SKIPNEXT:
  54839. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  54840. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  54841. ** operation should be a no-op.
  54842. **
  54843. ** CURSOR_REQUIRESEEK:
  54844. ** The table that this cursor was opened on still exists, but has been
  54845. ** modified since the cursor was last used. The cursor position is saved
  54846. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  54847. ** this state, restoreCursorPosition() can be called to attempt to
  54848. ** seek the cursor to the saved position.
  54849. **
  54850. ** CURSOR_FAULT:
  54851. ** An unrecoverable error (an I/O error or a malloc failure) has occurred
  54852. ** on a different connection that shares the BtShared cache with this
  54853. ** cursor. The error has left the cache in an inconsistent state.
  54854. ** Do nothing else with this cursor. Any attempt to use the cursor
  54855. ** should return the error code stored in BtCursor.skipNext
  54856. */
  54857. #define CURSOR_INVALID 0
  54858. #define CURSOR_VALID 1
  54859. #define CURSOR_SKIPNEXT 2
  54860. #define CURSOR_REQUIRESEEK 3
  54861. #define CURSOR_FAULT 4
  54862. /*
  54863. ** The database page the PENDING_BYTE occupies. This page is never used.
  54864. */
  54865. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  54866. /*
  54867. ** These macros define the location of the pointer-map entry for a
  54868. ** database page. The first argument to each is the number of usable
  54869. ** bytes on each page of the database (often 1024). The second is the
  54870. ** page number to look up in the pointer map.
  54871. **
  54872. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  54873. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  54874. ** the offset of the requested map entry.
  54875. **
  54876. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  54877. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  54878. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  54879. ** this test.
  54880. */
  54881. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  54882. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  54883. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  54884. /*
  54885. ** The pointer map is a lookup table that identifies the parent page for
  54886. ** each child page in the database file. The parent page is the page that
  54887. ** contains a pointer to the child. Every page in the database contains
  54888. ** 0 or 1 parent pages. (In this context 'database page' refers
  54889. ** to any page that is not part of the pointer map itself.) Each pointer map
  54890. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  54891. ** The PTRMAP_XXX identifiers below are the valid types.
  54892. **
  54893. ** The purpose of the pointer map is to facility moving pages from one
  54894. ** position in the file to another as part of autovacuum. When a page
  54895. ** is moved, the pointer in its parent must be updated to point to the
  54896. ** new location. The pointer map is used to locate the parent page quickly.
  54897. **
  54898. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  54899. ** used in this case.
  54900. **
  54901. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  54902. ** is not used in this case.
  54903. **
  54904. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  54905. ** overflow pages. The page number identifies the page that
  54906. ** contains the cell with a pointer to this overflow page.
  54907. **
  54908. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  54909. ** overflow pages. The page-number identifies the previous
  54910. ** page in the overflow page list.
  54911. **
  54912. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  54913. ** identifies the parent page in the btree.
  54914. */
  54915. #define PTRMAP_ROOTPAGE 1
  54916. #define PTRMAP_FREEPAGE 2
  54917. #define PTRMAP_OVERFLOW1 3
  54918. #define PTRMAP_OVERFLOW2 4
  54919. #define PTRMAP_BTREE 5
  54920. /* A bunch of assert() statements to check the transaction state variables
  54921. ** of handle p (type Btree*) are internally consistent.
  54922. */
  54923. #define btreeIntegrity(p) \
  54924. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  54925. assert( p->pBt->inTransaction>=p->inTrans );
  54926. /*
  54927. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  54928. ** if the database supports auto-vacuum or not. Because it is used
  54929. ** within an expression that is an argument to another macro
  54930. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  54931. ** So, this macro is defined instead.
  54932. */
  54933. #ifndef SQLITE_OMIT_AUTOVACUUM
  54934. #define ISAUTOVACUUM (pBt->autoVacuum)
  54935. #else
  54936. #define ISAUTOVACUUM 0
  54937. #endif
  54938. /*
  54939. ** This structure is passed around through all the sanity checking routines
  54940. ** in order to keep track of some global state information.
  54941. **
  54942. ** The aRef[] array is allocated so that there is 1 bit for each page in
  54943. ** the database. As the integrity-check proceeds, for each page used in
  54944. ** the database the corresponding bit is set. This allows integrity-check to
  54945. ** detect pages that are used twice and orphaned pages (both of which
  54946. ** indicate corruption).
  54947. */
  54948. typedef struct IntegrityCk IntegrityCk;
  54949. struct IntegrityCk {
  54950. BtShared *pBt; /* The tree being checked out */
  54951. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  54952. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  54953. Pgno nPage; /* Number of pages in the database */
  54954. int mxErr; /* Stop accumulating errors when this reaches zero */
  54955. int nErr; /* Number of messages written to zErrMsg so far */
  54956. int mallocFailed; /* A memory allocation error has occurred */
  54957. const char *zPfx; /* Error message prefix */
  54958. int v1, v2; /* Values for up to two %d fields in zPfx */
  54959. StrAccum errMsg; /* Accumulate the error message text here */
  54960. u32 *heap; /* Min-heap used for analyzing cell coverage */
  54961. };
  54962. /*
  54963. ** Routines to read or write a two- and four-byte big-endian integer values.
  54964. */
  54965. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  54966. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  54967. #define get4byte sqlite3Get4byte
  54968. #define put4byte sqlite3Put4byte
  54969. /*
  54970. ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
  54971. ** two-byte aligned address. get2bytea() is only used for accessing the
  54972. ** cell addresses in a btree header.
  54973. */
  54974. #if SQLITE_BYTEORDER==4321
  54975. # define get2byteAligned(x) (*(u16*)(x))
  54976. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
  54977. # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
  54978. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  54979. # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
  54980. #else
  54981. # define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
  54982. #endif
  54983. /************** End of btreeInt.h ********************************************/
  54984. /************** Continuing where we left off in btmutex.c ********************/
  54985. #ifndef SQLITE_OMIT_SHARED_CACHE
  54986. #if SQLITE_THREADSAFE
  54987. /*
  54988. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  54989. ** set BtShared.db to the database handle associated with p and the
  54990. ** p->locked boolean to true.
  54991. */
  54992. static void lockBtreeMutex(Btree *p){
  54993. assert( p->locked==0 );
  54994. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  54995. assert( sqlite3_mutex_held(p->db->mutex) );
  54996. sqlite3_mutex_enter(p->pBt->mutex);
  54997. p->pBt->db = p->db;
  54998. p->locked = 1;
  54999. }
  55000. /*
  55001. ** Release the BtShared mutex associated with B-Tree handle p and
  55002. ** clear the p->locked boolean.
  55003. */
  55004. static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
  55005. BtShared *pBt = p->pBt;
  55006. assert( p->locked==1 );
  55007. assert( sqlite3_mutex_held(pBt->mutex) );
  55008. assert( sqlite3_mutex_held(p->db->mutex) );
  55009. assert( p->db==pBt->db );
  55010. sqlite3_mutex_leave(pBt->mutex);
  55011. p->locked = 0;
  55012. }
  55013. /* Forward reference */
  55014. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
  55015. /*
  55016. ** Enter a mutex on the given BTree object.
  55017. **
  55018. ** If the object is not sharable, then no mutex is ever required
  55019. ** and this routine is a no-op. The underlying mutex is non-recursive.
  55020. ** But we keep a reference count in Btree.wantToLock so the behavior
  55021. ** of this interface is recursive.
  55022. **
  55023. ** To avoid deadlocks, multiple Btrees are locked in the same order
  55024. ** by all database connections. The p->pNext is a list of other
  55025. ** Btrees belonging to the same database connection as the p Btree
  55026. ** which need to be locked after p. If we cannot get a lock on
  55027. ** p, then first unlock all of the others on p->pNext, then wait
  55028. ** for the lock to become available on p, then relock all of the
  55029. ** subsequent Btrees that desire a lock.
  55030. */
  55031. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  55032. /* Some basic sanity checking on the Btree. The list of Btrees
  55033. ** connected by pNext and pPrev should be in sorted order by
  55034. ** Btree.pBt value. All elements of the list should belong to
  55035. ** the same connection. Only shared Btrees are on the list. */
  55036. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  55037. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  55038. assert( p->pNext==0 || p->pNext->db==p->db );
  55039. assert( p->pPrev==0 || p->pPrev->db==p->db );
  55040. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  55041. /* Check for locking consistency */
  55042. assert( !p->locked || p->wantToLock>0 );
  55043. assert( p->sharable || p->wantToLock==0 );
  55044. /* We should already hold a lock on the database connection */
  55045. assert( sqlite3_mutex_held(p->db->mutex) );
  55046. /* Unless the database is sharable and unlocked, then BtShared.db
  55047. ** should already be set correctly. */
  55048. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  55049. if( !p->sharable ) return;
  55050. p->wantToLock++;
  55051. if( p->locked ) return;
  55052. btreeLockCarefully(p);
  55053. }
  55054. /* This is a helper function for sqlite3BtreeLock(). By moving
  55055. ** complex, but seldom used logic, out of sqlite3BtreeLock() and
  55056. ** into this routine, we avoid unnecessary stack pointer changes
  55057. ** and thus help the sqlite3BtreeLock() routine to run much faster
  55058. ** in the common case.
  55059. */
  55060. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
  55061. Btree *pLater;
  55062. /* In most cases, we should be able to acquire the lock we
  55063. ** want without having to go through the ascending lock
  55064. ** procedure that follows. Just be sure not to block.
  55065. */
  55066. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  55067. p->pBt->db = p->db;
  55068. p->locked = 1;
  55069. return;
  55070. }
  55071. /* To avoid deadlock, first release all locks with a larger
  55072. ** BtShared address. Then acquire our lock. Then reacquire
  55073. ** the other BtShared locks that we used to hold in ascending
  55074. ** order.
  55075. */
  55076. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  55077. assert( pLater->sharable );
  55078. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  55079. assert( !pLater->locked || pLater->wantToLock>0 );
  55080. if( pLater->locked ){
  55081. unlockBtreeMutex(pLater);
  55082. }
  55083. }
  55084. lockBtreeMutex(p);
  55085. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  55086. if( pLater->wantToLock ){
  55087. lockBtreeMutex(pLater);
  55088. }
  55089. }
  55090. }
  55091. /*
  55092. ** Exit the recursive mutex on a Btree.
  55093. */
  55094. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  55095. assert( sqlite3_mutex_held(p->db->mutex) );
  55096. if( p->sharable ){
  55097. assert( p->wantToLock>0 );
  55098. p->wantToLock--;
  55099. if( p->wantToLock==0 ){
  55100. unlockBtreeMutex(p);
  55101. }
  55102. }
  55103. }
  55104. #ifndef NDEBUG
  55105. /*
  55106. ** Return true if the BtShared mutex is held on the btree, or if the
  55107. ** B-Tree is not marked as sharable.
  55108. **
  55109. ** This routine is used only from within assert() statements.
  55110. */
  55111. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  55112. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  55113. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  55114. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  55115. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  55116. return (p->sharable==0 || p->locked);
  55117. }
  55118. #endif
  55119. /*
  55120. ** Enter the mutex on every Btree associated with a database
  55121. ** connection. This is needed (for example) prior to parsing
  55122. ** a statement since we will be comparing table and column names
  55123. ** against all schemas and we do not want those schemas being
  55124. ** reset out from under us.
  55125. **
  55126. ** There is a corresponding leave-all procedures.
  55127. **
  55128. ** Enter the mutexes in accending order by BtShared pointer address
  55129. ** to avoid the possibility of deadlock when two threads with
  55130. ** two or more btrees in common both try to lock all their btrees
  55131. ** at the same instant.
  55132. */
  55133. static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){
  55134. int i;
  55135. int skipOk = 1;
  55136. Btree *p;
  55137. assert( sqlite3_mutex_held(db->mutex) );
  55138. for(i=0; i<db->nDb; i++){
  55139. p = db->aDb[i].pBt;
  55140. if( p && p->sharable ){
  55141. sqlite3BtreeEnter(p);
  55142. skipOk = 0;
  55143. }
  55144. }
  55145. db->skipBtreeMutex = skipOk;
  55146. }
  55147. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  55148. if( db->skipBtreeMutex==0 ) btreeEnterAll(db);
  55149. }
  55150. static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){
  55151. int i;
  55152. Btree *p;
  55153. assert( sqlite3_mutex_held(db->mutex) );
  55154. for(i=0; i<db->nDb; i++){
  55155. p = db->aDb[i].pBt;
  55156. if( p ) sqlite3BtreeLeave(p);
  55157. }
  55158. }
  55159. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  55160. if( db->skipBtreeMutex==0 ) btreeLeaveAll(db);
  55161. }
  55162. #ifndef NDEBUG
  55163. /*
  55164. ** Return true if the current thread holds the database connection
  55165. ** mutex and all required BtShared mutexes.
  55166. **
  55167. ** This routine is used inside assert() statements only.
  55168. */
  55169. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  55170. int i;
  55171. if( !sqlite3_mutex_held(db->mutex) ){
  55172. return 0;
  55173. }
  55174. for(i=0; i<db->nDb; i++){
  55175. Btree *p;
  55176. p = db->aDb[i].pBt;
  55177. if( p && p->sharable &&
  55178. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  55179. return 0;
  55180. }
  55181. }
  55182. return 1;
  55183. }
  55184. #endif /* NDEBUG */
  55185. #ifndef NDEBUG
  55186. /*
  55187. ** Return true if the correct mutexes are held for accessing the
  55188. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  55189. ** access are:
  55190. **
  55191. ** (1) The mutex on db
  55192. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  55193. **
  55194. ** If pSchema is not NULL, then iDb is computed from pSchema and
  55195. ** db using sqlite3SchemaToIndex().
  55196. */
  55197. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  55198. Btree *p;
  55199. assert( db!=0 );
  55200. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  55201. assert( iDb>=0 && iDb<db->nDb );
  55202. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  55203. if( iDb==1 ) return 1;
  55204. p = db->aDb[iDb].pBt;
  55205. assert( p!=0 );
  55206. return p->sharable==0 || p->locked==1;
  55207. }
  55208. #endif /* NDEBUG */
  55209. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  55210. /*
  55211. ** The following are special cases for mutex enter routines for use
  55212. ** in single threaded applications that use shared cache. Except for
  55213. ** these two routines, all mutex operations are no-ops in that case and
  55214. ** are null #defines in btree.h.
  55215. **
  55216. ** If shared cache is disabled, then all btree mutex routines, including
  55217. ** the ones below, are no-ops and are null #defines in btree.h.
  55218. */
  55219. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  55220. p->pBt->db = p->db;
  55221. }
  55222. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  55223. int i;
  55224. for(i=0; i<db->nDb; i++){
  55225. Btree *p = db->aDb[i].pBt;
  55226. if( p ){
  55227. p->pBt->db = p->db;
  55228. }
  55229. }
  55230. }
  55231. #endif /* if SQLITE_THREADSAFE */
  55232. #ifndef SQLITE_OMIT_INCRBLOB
  55233. /*
  55234. ** Enter a mutex on a Btree given a cursor owned by that Btree.
  55235. **
  55236. ** These entry points are used by incremental I/O only. Enter() is required
  55237. ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
  55238. ** the build is threadsafe. Leave() is only required by threadsafe builds.
  55239. */
  55240. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  55241. sqlite3BtreeEnter(pCur->pBtree);
  55242. }
  55243. # if SQLITE_THREADSAFE
  55244. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  55245. sqlite3BtreeLeave(pCur->pBtree);
  55246. }
  55247. # endif
  55248. #endif /* ifndef SQLITE_OMIT_INCRBLOB */
  55249. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  55250. /************** End of btmutex.c *********************************************/
  55251. /************** Begin file btree.c *******************************************/
  55252. /*
  55253. ** 2004 April 6
  55254. **
  55255. ** The author disclaims copyright to this source code. In place of
  55256. ** a legal notice, here is a blessing:
  55257. **
  55258. ** May you do good and not evil.
  55259. ** May you find forgiveness for yourself and forgive others.
  55260. ** May you share freely, never taking more than you give.
  55261. **
  55262. *************************************************************************
  55263. ** This file implements an external (disk-based) database using BTrees.
  55264. ** See the header comment on "btreeInt.h" for additional information.
  55265. ** Including a description of file format and an overview of operation.
  55266. */
  55267. /* #include "btreeInt.h" */
  55268. /*
  55269. ** The header string that appears at the beginning of every
  55270. ** SQLite database.
  55271. */
  55272. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  55273. /*
  55274. ** Set this global variable to 1 to enable tracing using the TRACE
  55275. ** macro.
  55276. */
  55277. #if 0
  55278. int sqlite3BtreeTrace=1; /* True to enable tracing */
  55279. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  55280. #else
  55281. # define TRACE(X)
  55282. #endif
  55283. /*
  55284. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  55285. ** But if the value is zero, make it 65536.
  55286. **
  55287. ** This routine is used to extract the "offset to cell content area" value
  55288. ** from the header of a btree page. If the page size is 65536 and the page
  55289. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  55290. ** This routine makes the necessary adjustment to 65536.
  55291. */
  55292. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  55293. /*
  55294. ** Values passed as the 5th argument to allocateBtreePage()
  55295. */
  55296. #define BTALLOC_ANY 0 /* Allocate any page */
  55297. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  55298. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  55299. /*
  55300. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  55301. ** defined, or 0 if it is. For example:
  55302. **
  55303. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  55304. */
  55305. #ifndef SQLITE_OMIT_AUTOVACUUM
  55306. #define IfNotOmitAV(expr) (expr)
  55307. #else
  55308. #define IfNotOmitAV(expr) 0
  55309. #endif
  55310. #ifndef SQLITE_OMIT_SHARED_CACHE
  55311. /*
  55312. ** A list of BtShared objects that are eligible for participation
  55313. ** in shared cache. This variable has file scope during normal builds,
  55314. ** but the test harness needs to access it so we make it global for
  55315. ** test builds.
  55316. **
  55317. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  55318. */
  55319. #ifdef SQLITE_TEST
  55320. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  55321. #else
  55322. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  55323. #endif
  55324. #endif /* SQLITE_OMIT_SHARED_CACHE */
  55325. #ifndef SQLITE_OMIT_SHARED_CACHE
  55326. /*
  55327. ** Enable or disable the shared pager and schema features.
  55328. **
  55329. ** This routine has no effect on existing database connections.
  55330. ** The shared cache setting effects only future calls to
  55331. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  55332. */
  55333. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  55334. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  55335. return SQLITE_OK;
  55336. }
  55337. #endif
  55338. #ifdef SQLITE_OMIT_SHARED_CACHE
  55339. /*
  55340. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  55341. ** and clearAllSharedCacheTableLocks()
  55342. ** manipulate entries in the BtShared.pLock linked list used to store
  55343. ** shared-cache table level locks. If the library is compiled with the
  55344. ** shared-cache feature disabled, then there is only ever one user
  55345. ** of each BtShared structure and so this locking is not necessary.
  55346. ** So define the lock related functions as no-ops.
  55347. */
  55348. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  55349. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  55350. #define clearAllSharedCacheTableLocks(a)
  55351. #define downgradeAllSharedCacheTableLocks(a)
  55352. #define hasSharedCacheTableLock(a,b,c,d) 1
  55353. #define hasReadConflicts(a, b) 0
  55354. #endif
  55355. #ifndef SQLITE_OMIT_SHARED_CACHE
  55356. #ifdef SQLITE_DEBUG
  55357. /*
  55358. **** This function is only used as part of an assert() statement. ***
  55359. **
  55360. ** Check to see if pBtree holds the required locks to read or write to the
  55361. ** table with root page iRoot. Return 1 if it does and 0 if not.
  55362. **
  55363. ** For example, when writing to a table with root-page iRoot via
  55364. ** Btree connection pBtree:
  55365. **
  55366. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  55367. **
  55368. ** When writing to an index that resides in a sharable database, the
  55369. ** caller should have first obtained a lock specifying the root page of
  55370. ** the corresponding table. This makes things a bit more complicated,
  55371. ** as this module treats each table as a separate structure. To determine
  55372. ** the table corresponding to the index being written, this
  55373. ** function has to search through the database schema.
  55374. **
  55375. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  55376. ** hold a write-lock on the schema table (root page 1). This is also
  55377. ** acceptable.
  55378. */
  55379. static int hasSharedCacheTableLock(
  55380. Btree *pBtree, /* Handle that must hold lock */
  55381. Pgno iRoot, /* Root page of b-tree */
  55382. int isIndex, /* True if iRoot is the root of an index b-tree */
  55383. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  55384. ){
  55385. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  55386. Pgno iTab = 0;
  55387. BtLock *pLock;
  55388. /* If this database is not shareable, or if the client is reading
  55389. ** and has the read-uncommitted flag set, then no lock is required.
  55390. ** Return true immediately.
  55391. */
  55392. if( (pBtree->sharable==0)
  55393. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
  55394. ){
  55395. return 1;
  55396. }
  55397. /* If the client is reading or writing an index and the schema is
  55398. ** not loaded, then it is too difficult to actually check to see if
  55399. ** the correct locks are held. So do not bother - just return true.
  55400. ** This case does not come up very often anyhow.
  55401. */
  55402. if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
  55403. return 1;
  55404. }
  55405. /* Figure out the root-page that the lock should be held on. For table
  55406. ** b-trees, this is just the root page of the b-tree being read or
  55407. ** written. For index b-trees, it is the root page of the associated
  55408. ** table. */
  55409. if( isIndex ){
  55410. HashElem *p;
  55411. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  55412. Index *pIdx = (Index *)sqliteHashData(p);
  55413. if( pIdx->tnum==(int)iRoot ){
  55414. if( iTab ){
  55415. /* Two or more indexes share the same root page. There must
  55416. ** be imposter tables. So just return true. The assert is not
  55417. ** useful in that case. */
  55418. return 1;
  55419. }
  55420. iTab = pIdx->pTable->tnum;
  55421. }
  55422. }
  55423. }else{
  55424. iTab = iRoot;
  55425. }
  55426. /* Search for the required lock. Either a write-lock on root-page iTab, a
  55427. ** write-lock on the schema table, or (if the client is reading) a
  55428. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  55429. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  55430. if( pLock->pBtree==pBtree
  55431. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  55432. && pLock->eLock>=eLockType
  55433. ){
  55434. return 1;
  55435. }
  55436. }
  55437. /* Failed to find the required lock. */
  55438. return 0;
  55439. }
  55440. #endif /* SQLITE_DEBUG */
  55441. #ifdef SQLITE_DEBUG
  55442. /*
  55443. **** This function may be used as part of assert() statements only. ****
  55444. **
  55445. ** Return true if it would be illegal for pBtree to write into the
  55446. ** table or index rooted at iRoot because other shared connections are
  55447. ** simultaneously reading that same table or index.
  55448. **
  55449. ** It is illegal for pBtree to write if some other Btree object that
  55450. ** shares the same BtShared object is currently reading or writing
  55451. ** the iRoot table. Except, if the other Btree object has the
  55452. ** read-uncommitted flag set, then it is OK for the other object to
  55453. ** have a read cursor.
  55454. **
  55455. ** For example, before writing to any part of the table or index
  55456. ** rooted at page iRoot, one should call:
  55457. **
  55458. ** assert( !hasReadConflicts(pBtree, iRoot) );
  55459. */
  55460. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  55461. BtCursor *p;
  55462. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  55463. if( p->pgnoRoot==iRoot
  55464. && p->pBtree!=pBtree
  55465. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
  55466. ){
  55467. return 1;
  55468. }
  55469. }
  55470. return 0;
  55471. }
  55472. #endif /* #ifdef SQLITE_DEBUG */
  55473. /*
  55474. ** Query to see if Btree handle p may obtain a lock of type eLock
  55475. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  55476. ** SQLITE_OK if the lock may be obtained (by calling
  55477. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  55478. */
  55479. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  55480. BtShared *pBt = p->pBt;
  55481. BtLock *pIter;
  55482. assert( sqlite3BtreeHoldsMutex(p) );
  55483. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  55484. assert( p->db!=0 );
  55485. assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
  55486. /* If requesting a write-lock, then the Btree must have an open write
  55487. ** transaction on this file. And, obviously, for this to be so there
  55488. ** must be an open write transaction on the file itself.
  55489. */
  55490. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  55491. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  55492. /* This routine is a no-op if the shared-cache is not enabled */
  55493. if( !p->sharable ){
  55494. return SQLITE_OK;
  55495. }
  55496. /* If some other connection is holding an exclusive lock, the
  55497. ** requested lock may not be obtained.
  55498. */
  55499. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  55500. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  55501. return SQLITE_LOCKED_SHAREDCACHE;
  55502. }
  55503. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  55504. /* The condition (pIter->eLock!=eLock) in the following if(...)
  55505. ** statement is a simplification of:
  55506. **
  55507. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  55508. **
  55509. ** since we know that if eLock==WRITE_LOCK, then no other connection
  55510. ** may hold a WRITE_LOCK on any table in this file (since there can
  55511. ** only be a single writer).
  55512. */
  55513. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  55514. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  55515. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  55516. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  55517. if( eLock==WRITE_LOCK ){
  55518. assert( p==pBt->pWriter );
  55519. pBt->btsFlags |= BTS_PENDING;
  55520. }
  55521. return SQLITE_LOCKED_SHAREDCACHE;
  55522. }
  55523. }
  55524. return SQLITE_OK;
  55525. }
  55526. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  55527. #ifndef SQLITE_OMIT_SHARED_CACHE
  55528. /*
  55529. ** Add a lock on the table with root-page iTable to the shared-btree used
  55530. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  55531. ** WRITE_LOCK.
  55532. **
  55533. ** This function assumes the following:
  55534. **
  55535. ** (a) The specified Btree object p is connected to a sharable
  55536. ** database (one with the BtShared.sharable flag set), and
  55537. **
  55538. ** (b) No other Btree objects hold a lock that conflicts
  55539. ** with the requested lock (i.e. querySharedCacheTableLock() has
  55540. ** already been called and returned SQLITE_OK).
  55541. **
  55542. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  55543. ** is returned if a malloc attempt fails.
  55544. */
  55545. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  55546. BtShared *pBt = p->pBt;
  55547. BtLock *pLock = 0;
  55548. BtLock *pIter;
  55549. assert( sqlite3BtreeHoldsMutex(p) );
  55550. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  55551. assert( p->db!=0 );
  55552. /* A connection with the read-uncommitted flag set will never try to
  55553. ** obtain a read-lock using this function. The only read-lock obtained
  55554. ** by a connection in read-uncommitted mode is on the sqlite_master
  55555. ** table, and that lock is obtained in BtreeBeginTrans(). */
  55556. assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
  55557. /* This function should only be called on a sharable b-tree after it
  55558. ** has been determined that no other b-tree holds a conflicting lock. */
  55559. assert( p->sharable );
  55560. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  55561. /* First search the list for an existing lock on this table. */
  55562. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  55563. if( pIter->iTable==iTable && pIter->pBtree==p ){
  55564. pLock = pIter;
  55565. break;
  55566. }
  55567. }
  55568. /* If the above search did not find a BtLock struct associating Btree p
  55569. ** with table iTable, allocate one and link it into the list.
  55570. */
  55571. if( !pLock ){
  55572. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  55573. if( !pLock ){
  55574. return SQLITE_NOMEM_BKPT;
  55575. }
  55576. pLock->iTable = iTable;
  55577. pLock->pBtree = p;
  55578. pLock->pNext = pBt->pLock;
  55579. pBt->pLock = pLock;
  55580. }
  55581. /* Set the BtLock.eLock variable to the maximum of the current lock
  55582. ** and the requested lock. This means if a write-lock was already held
  55583. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  55584. */
  55585. assert( WRITE_LOCK>READ_LOCK );
  55586. if( eLock>pLock->eLock ){
  55587. pLock->eLock = eLock;
  55588. }
  55589. return SQLITE_OK;
  55590. }
  55591. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  55592. #ifndef SQLITE_OMIT_SHARED_CACHE
  55593. /*
  55594. ** Release all the table locks (locks obtained via calls to
  55595. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  55596. **
  55597. ** This function assumes that Btree p has an open read or write
  55598. ** transaction. If it does not, then the BTS_PENDING flag
  55599. ** may be incorrectly cleared.
  55600. */
  55601. static void clearAllSharedCacheTableLocks(Btree *p){
  55602. BtShared *pBt = p->pBt;
  55603. BtLock **ppIter = &pBt->pLock;
  55604. assert( sqlite3BtreeHoldsMutex(p) );
  55605. assert( p->sharable || 0==*ppIter );
  55606. assert( p->inTrans>0 );
  55607. while( *ppIter ){
  55608. BtLock *pLock = *ppIter;
  55609. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  55610. assert( pLock->pBtree->inTrans>=pLock->eLock );
  55611. if( pLock->pBtree==p ){
  55612. *ppIter = pLock->pNext;
  55613. assert( pLock->iTable!=1 || pLock==&p->lock );
  55614. if( pLock->iTable!=1 ){
  55615. sqlite3_free(pLock);
  55616. }
  55617. }else{
  55618. ppIter = &pLock->pNext;
  55619. }
  55620. }
  55621. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  55622. if( pBt->pWriter==p ){
  55623. pBt->pWriter = 0;
  55624. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  55625. }else if( pBt->nTransaction==2 ){
  55626. /* This function is called when Btree p is concluding its
  55627. ** transaction. If there currently exists a writer, and p is not
  55628. ** that writer, then the number of locks held by connections other
  55629. ** than the writer must be about to drop to zero. In this case
  55630. ** set the BTS_PENDING flag to 0.
  55631. **
  55632. ** If there is not currently a writer, then BTS_PENDING must
  55633. ** be zero already. So this next line is harmless in that case.
  55634. */
  55635. pBt->btsFlags &= ~BTS_PENDING;
  55636. }
  55637. }
  55638. /*
  55639. ** This function changes all write-locks held by Btree p into read-locks.
  55640. */
  55641. static void downgradeAllSharedCacheTableLocks(Btree *p){
  55642. BtShared *pBt = p->pBt;
  55643. if( pBt->pWriter==p ){
  55644. BtLock *pLock;
  55645. pBt->pWriter = 0;
  55646. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  55647. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  55648. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  55649. pLock->eLock = READ_LOCK;
  55650. }
  55651. }
  55652. }
  55653. #endif /* SQLITE_OMIT_SHARED_CACHE */
  55654. static void releasePage(MemPage *pPage); /* Forward reference */
  55655. /*
  55656. ***** This routine is used inside of assert() only ****
  55657. **
  55658. ** Verify that the cursor holds the mutex on its BtShared
  55659. */
  55660. #ifdef SQLITE_DEBUG
  55661. static int cursorHoldsMutex(BtCursor *p){
  55662. return sqlite3_mutex_held(p->pBt->mutex);
  55663. }
  55664. /* Verify that the cursor and the BtShared agree about what is the current
  55665. ** database connetion. This is important in shared-cache mode. If the database
  55666. ** connection pointers get out-of-sync, it is possible for routines like
  55667. ** btreeInitPage() to reference an stale connection pointer that references a
  55668. ** a connection that has already closed. This routine is used inside assert()
  55669. ** statements only and for the purpose of double-checking that the btree code
  55670. ** does keep the database connection pointers up-to-date.
  55671. */
  55672. static int cursorOwnsBtShared(BtCursor *p){
  55673. assert( cursorHoldsMutex(p) );
  55674. return (p->pBtree->db==p->pBt->db);
  55675. }
  55676. #endif
  55677. /*
  55678. ** Invalidate the overflow cache of the cursor passed as the first argument.
  55679. ** on the shared btree structure pBt.
  55680. */
  55681. #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
  55682. /*
  55683. ** Invalidate the overflow page-list cache for all cursors opened
  55684. ** on the shared btree structure pBt.
  55685. */
  55686. static void invalidateAllOverflowCache(BtShared *pBt){
  55687. BtCursor *p;
  55688. assert( sqlite3_mutex_held(pBt->mutex) );
  55689. for(p=pBt->pCursor; p; p=p->pNext){
  55690. invalidateOverflowCache(p);
  55691. }
  55692. }
  55693. #ifndef SQLITE_OMIT_INCRBLOB
  55694. /*
  55695. ** This function is called before modifying the contents of a table
  55696. ** to invalidate any incrblob cursors that are open on the
  55697. ** row or one of the rows being modified.
  55698. **
  55699. ** If argument isClearTable is true, then the entire contents of the
  55700. ** table is about to be deleted. In this case invalidate all incrblob
  55701. ** cursors open on any row within the table with root-page pgnoRoot.
  55702. **
  55703. ** Otherwise, if argument isClearTable is false, then the row with
  55704. ** rowid iRow is being replaced or deleted. In this case invalidate
  55705. ** only those incrblob cursors open on that specific row.
  55706. */
  55707. static void invalidateIncrblobCursors(
  55708. Btree *pBtree, /* The database file to check */
  55709. Pgno pgnoRoot, /* The table that might be changing */
  55710. i64 iRow, /* The rowid that might be changing */
  55711. int isClearTable /* True if all rows are being deleted */
  55712. ){
  55713. BtCursor *p;
  55714. if( pBtree->hasIncrblobCur==0 ) return;
  55715. assert( sqlite3BtreeHoldsMutex(pBtree) );
  55716. pBtree->hasIncrblobCur = 0;
  55717. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  55718. if( (p->curFlags & BTCF_Incrblob)!=0 ){
  55719. pBtree->hasIncrblobCur = 1;
  55720. if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
  55721. p->eState = CURSOR_INVALID;
  55722. }
  55723. }
  55724. }
  55725. }
  55726. #else
  55727. /* Stub function when INCRBLOB is omitted */
  55728. #define invalidateIncrblobCursors(w,x,y,z)
  55729. #endif /* SQLITE_OMIT_INCRBLOB */
  55730. /*
  55731. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  55732. ** when a page that previously contained data becomes a free-list leaf
  55733. ** page.
  55734. **
  55735. ** The BtShared.pHasContent bitvec exists to work around an obscure
  55736. ** bug caused by the interaction of two useful IO optimizations surrounding
  55737. ** free-list leaf pages:
  55738. **
  55739. ** 1) When all data is deleted from a page and the page becomes
  55740. ** a free-list leaf page, the page is not written to the database
  55741. ** (as free-list leaf pages contain no meaningful data). Sometimes
  55742. ** such a page is not even journalled (as it will not be modified,
  55743. ** why bother journalling it?).
  55744. **
  55745. ** 2) When a free-list leaf page is reused, its content is not read
  55746. ** from the database or written to the journal file (why should it
  55747. ** be, if it is not at all meaningful?).
  55748. **
  55749. ** By themselves, these optimizations work fine and provide a handy
  55750. ** performance boost to bulk delete or insert operations. However, if
  55751. ** a page is moved to the free-list and then reused within the same
  55752. ** transaction, a problem comes up. If the page is not journalled when
  55753. ** it is moved to the free-list and it is also not journalled when it
  55754. ** is extracted from the free-list and reused, then the original data
  55755. ** may be lost. In the event of a rollback, it may not be possible
  55756. ** to restore the database to its original configuration.
  55757. **
  55758. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  55759. ** moved to become a free-list leaf page, the corresponding bit is
  55760. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  55761. ** optimization 2 above is omitted if the corresponding bit is already
  55762. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  55763. ** at the end of every transaction.
  55764. */
  55765. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  55766. int rc = SQLITE_OK;
  55767. if( !pBt->pHasContent ){
  55768. assert( pgno<=pBt->nPage );
  55769. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  55770. if( !pBt->pHasContent ){
  55771. rc = SQLITE_NOMEM_BKPT;
  55772. }
  55773. }
  55774. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  55775. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  55776. }
  55777. return rc;
  55778. }
  55779. /*
  55780. ** Query the BtShared.pHasContent vector.
  55781. **
  55782. ** This function is called when a free-list leaf page is removed from the
  55783. ** free-list for reuse. It returns false if it is safe to retrieve the
  55784. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  55785. */
  55786. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  55787. Bitvec *p = pBt->pHasContent;
  55788. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  55789. }
  55790. /*
  55791. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  55792. ** invoked at the conclusion of each write-transaction.
  55793. */
  55794. static void btreeClearHasContent(BtShared *pBt){
  55795. sqlite3BitvecDestroy(pBt->pHasContent);
  55796. pBt->pHasContent = 0;
  55797. }
  55798. /*
  55799. ** Release all of the apPage[] pages for a cursor.
  55800. */
  55801. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  55802. int i;
  55803. for(i=0; i<=pCur->iPage; i++){
  55804. releasePage(pCur->apPage[i]);
  55805. pCur->apPage[i] = 0;
  55806. }
  55807. pCur->iPage = -1;
  55808. }
  55809. /*
  55810. ** The cursor passed as the only argument must point to a valid entry
  55811. ** when this function is called (i.e. have eState==CURSOR_VALID). This
  55812. ** function saves the current cursor key in variables pCur->nKey and
  55813. ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
  55814. ** code otherwise.
  55815. **
  55816. ** If the cursor is open on an intkey table, then the integer key
  55817. ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
  55818. ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
  55819. ** set to point to a malloced buffer pCur->nKey bytes in size containing
  55820. ** the key.
  55821. */
  55822. static int saveCursorKey(BtCursor *pCur){
  55823. int rc = SQLITE_OK;
  55824. assert( CURSOR_VALID==pCur->eState );
  55825. assert( 0==pCur->pKey );
  55826. assert( cursorHoldsMutex(pCur) );
  55827. if( pCur->curIntKey ){
  55828. /* Only the rowid is required for a table btree */
  55829. pCur->nKey = sqlite3BtreeIntegerKey(pCur);
  55830. }else{
  55831. /* For an index btree, save the complete key content */
  55832. void *pKey;
  55833. pCur->nKey = sqlite3BtreePayloadSize(pCur);
  55834. pKey = sqlite3Malloc( pCur->nKey );
  55835. if( pKey ){
  55836. rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
  55837. if( rc==SQLITE_OK ){
  55838. pCur->pKey = pKey;
  55839. }else{
  55840. sqlite3_free(pKey);
  55841. }
  55842. }else{
  55843. rc = SQLITE_NOMEM_BKPT;
  55844. }
  55845. }
  55846. assert( !pCur->curIntKey || !pCur->pKey );
  55847. return rc;
  55848. }
  55849. /*
  55850. ** Save the current cursor position in the variables BtCursor.nKey
  55851. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  55852. **
  55853. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  55854. ** prior to calling this routine.
  55855. */
  55856. static int saveCursorPosition(BtCursor *pCur){
  55857. int rc;
  55858. assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
  55859. assert( 0==pCur->pKey );
  55860. assert( cursorHoldsMutex(pCur) );
  55861. if( pCur->eState==CURSOR_SKIPNEXT ){
  55862. pCur->eState = CURSOR_VALID;
  55863. }else{
  55864. pCur->skipNext = 0;
  55865. }
  55866. rc = saveCursorKey(pCur);
  55867. if( rc==SQLITE_OK ){
  55868. btreeReleaseAllCursorPages(pCur);
  55869. pCur->eState = CURSOR_REQUIRESEEK;
  55870. }
  55871. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
  55872. return rc;
  55873. }
  55874. /* Forward reference */
  55875. static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
  55876. /*
  55877. ** Save the positions of all cursors (except pExcept) that are open on
  55878. ** the table with root-page iRoot. "Saving the cursor position" means that
  55879. ** the location in the btree is remembered in such a way that it can be
  55880. ** moved back to the same spot after the btree has been modified. This
  55881. ** routine is called just before cursor pExcept is used to modify the
  55882. ** table, for example in BtreeDelete() or BtreeInsert().
  55883. **
  55884. ** If there are two or more cursors on the same btree, then all such
  55885. ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
  55886. ** routine enforces that rule. This routine only needs to be called in
  55887. ** the uncommon case when pExpect has the BTCF_Multiple flag set.
  55888. **
  55889. ** If pExpect!=NULL and if no other cursors are found on the same root-page,
  55890. ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
  55891. ** pointless call to this routine.
  55892. **
  55893. ** Implementation note: This routine merely checks to see if any cursors
  55894. ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
  55895. ** event that cursors are in need to being saved.
  55896. */
  55897. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  55898. BtCursor *p;
  55899. assert( sqlite3_mutex_held(pBt->mutex) );
  55900. assert( pExcept==0 || pExcept->pBt==pBt );
  55901. for(p=pBt->pCursor; p; p=p->pNext){
  55902. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
  55903. }
  55904. if( p ) return saveCursorsOnList(p, iRoot, pExcept);
  55905. if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
  55906. return SQLITE_OK;
  55907. }
  55908. /* This helper routine to saveAllCursors does the actual work of saving
  55909. ** the cursors if and when a cursor is found that actually requires saving.
  55910. ** The common case is that no cursors need to be saved, so this routine is
  55911. ** broken out from its caller to avoid unnecessary stack pointer movement.
  55912. */
  55913. static int SQLITE_NOINLINE saveCursorsOnList(
  55914. BtCursor *p, /* The first cursor that needs saving */
  55915. Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
  55916. BtCursor *pExcept /* Do not save this cursor */
  55917. ){
  55918. do{
  55919. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  55920. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  55921. int rc = saveCursorPosition(p);
  55922. if( SQLITE_OK!=rc ){
  55923. return rc;
  55924. }
  55925. }else{
  55926. testcase( p->iPage>0 );
  55927. btreeReleaseAllCursorPages(p);
  55928. }
  55929. }
  55930. p = p->pNext;
  55931. }while( p );
  55932. return SQLITE_OK;
  55933. }
  55934. /*
  55935. ** Clear the current cursor position.
  55936. */
  55937. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  55938. assert( cursorHoldsMutex(pCur) );
  55939. sqlite3_free(pCur->pKey);
  55940. pCur->pKey = 0;
  55941. pCur->eState = CURSOR_INVALID;
  55942. }
  55943. /*
  55944. ** In this version of BtreeMoveto, pKey is a packed index record
  55945. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  55946. ** record and then call BtreeMovetoUnpacked() to do the work.
  55947. */
  55948. static int btreeMoveto(
  55949. BtCursor *pCur, /* Cursor open on the btree to be searched */
  55950. const void *pKey, /* Packed key if the btree is an index */
  55951. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  55952. int bias, /* Bias search to the high end */
  55953. int *pRes /* Write search results here */
  55954. ){
  55955. int rc; /* Status code */
  55956. UnpackedRecord *pIdxKey; /* Unpacked index key */
  55957. if( pKey ){
  55958. assert( nKey==(i64)(int)nKey );
  55959. pIdxKey = sqlite3VdbeAllocUnpackedRecord(pCur->pKeyInfo);
  55960. if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
  55961. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  55962. if( pIdxKey->nField==0 ){
  55963. rc = SQLITE_CORRUPT_BKPT;
  55964. goto moveto_done;
  55965. }
  55966. }else{
  55967. pIdxKey = 0;
  55968. }
  55969. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  55970. moveto_done:
  55971. if( pIdxKey ){
  55972. sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
  55973. }
  55974. return rc;
  55975. }
  55976. /*
  55977. ** Restore the cursor to the position it was in (or as close to as possible)
  55978. ** when saveCursorPosition() was called. Note that this call deletes the
  55979. ** saved position info stored by saveCursorPosition(), so there can be
  55980. ** at most one effective restoreCursorPosition() call after each
  55981. ** saveCursorPosition().
  55982. */
  55983. static int btreeRestoreCursorPosition(BtCursor *pCur){
  55984. int rc;
  55985. int skipNext;
  55986. assert( cursorOwnsBtShared(pCur) );
  55987. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  55988. if( pCur->eState==CURSOR_FAULT ){
  55989. return pCur->skipNext;
  55990. }
  55991. pCur->eState = CURSOR_INVALID;
  55992. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
  55993. if( rc==SQLITE_OK ){
  55994. sqlite3_free(pCur->pKey);
  55995. pCur->pKey = 0;
  55996. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  55997. pCur->skipNext |= skipNext;
  55998. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  55999. pCur->eState = CURSOR_SKIPNEXT;
  56000. }
  56001. }
  56002. return rc;
  56003. }
  56004. #define restoreCursorPosition(p) \
  56005. (p->eState>=CURSOR_REQUIRESEEK ? \
  56006. btreeRestoreCursorPosition(p) : \
  56007. SQLITE_OK)
  56008. /*
  56009. ** Determine whether or not a cursor has moved from the position where
  56010. ** it was last placed, or has been invalidated for any other reason.
  56011. ** Cursors can move when the row they are pointing at is deleted out
  56012. ** from under them, for example. Cursor might also move if a btree
  56013. ** is rebalanced.
  56014. **
  56015. ** Calling this routine with a NULL cursor pointer returns false.
  56016. **
  56017. ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
  56018. ** back to where it ought to be if this routine returns true.
  56019. */
  56020. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
  56021. return pCur->eState!=CURSOR_VALID;
  56022. }
  56023. /*
  56024. ** This routine restores a cursor back to its original position after it
  56025. ** has been moved by some outside activity (such as a btree rebalance or
  56026. ** a row having been deleted out from under the cursor).
  56027. **
  56028. ** On success, the *pDifferentRow parameter is false if the cursor is left
  56029. ** pointing at exactly the same row. *pDifferntRow is the row the cursor
  56030. ** was pointing to has been deleted, forcing the cursor to point to some
  56031. ** nearby row.
  56032. **
  56033. ** This routine should only be called for a cursor that just returned
  56034. ** TRUE from sqlite3BtreeCursorHasMoved().
  56035. */
  56036. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
  56037. int rc;
  56038. assert( pCur!=0 );
  56039. assert( pCur->eState!=CURSOR_VALID );
  56040. rc = restoreCursorPosition(pCur);
  56041. if( rc ){
  56042. *pDifferentRow = 1;
  56043. return rc;
  56044. }
  56045. if( pCur->eState!=CURSOR_VALID ){
  56046. *pDifferentRow = 1;
  56047. }else{
  56048. assert( pCur->skipNext==0 );
  56049. *pDifferentRow = 0;
  56050. }
  56051. return SQLITE_OK;
  56052. }
  56053. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  56054. /*
  56055. ** Provide hints to the cursor. The particular hint given (and the type
  56056. ** and number of the varargs parameters) is determined by the eHintType
  56057. ** parameter. See the definitions of the BTREE_HINT_* macros for details.
  56058. */
  56059. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
  56060. /* Used only by system that substitute their own storage engine */
  56061. }
  56062. #endif
  56063. /*
  56064. ** Provide flag hints to the cursor.
  56065. */
  56066. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
  56067. assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
  56068. pCur->hints = x;
  56069. }
  56070. #ifndef SQLITE_OMIT_AUTOVACUUM
  56071. /*
  56072. ** Given a page number of a regular database page, return the page
  56073. ** number for the pointer-map page that contains the entry for the
  56074. ** input page number.
  56075. **
  56076. ** Return 0 (not a valid page) for pgno==1 since there is
  56077. ** no pointer map associated with page 1. The integrity_check logic
  56078. ** requires that ptrmapPageno(*,1)!=1.
  56079. */
  56080. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  56081. int nPagesPerMapPage;
  56082. Pgno iPtrMap, ret;
  56083. assert( sqlite3_mutex_held(pBt->mutex) );
  56084. if( pgno<2 ) return 0;
  56085. nPagesPerMapPage = (pBt->usableSize/5)+1;
  56086. iPtrMap = (pgno-2)/nPagesPerMapPage;
  56087. ret = (iPtrMap*nPagesPerMapPage) + 2;
  56088. if( ret==PENDING_BYTE_PAGE(pBt) ){
  56089. ret++;
  56090. }
  56091. return ret;
  56092. }
  56093. /*
  56094. ** Write an entry into the pointer map.
  56095. **
  56096. ** This routine updates the pointer map entry for page number 'key'
  56097. ** so that it maps to type 'eType' and parent page number 'pgno'.
  56098. **
  56099. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  56100. ** a no-op. If an error occurs, the appropriate error code is written
  56101. ** into *pRC.
  56102. */
  56103. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  56104. DbPage *pDbPage; /* The pointer map page */
  56105. u8 *pPtrmap; /* The pointer map data */
  56106. Pgno iPtrmap; /* The pointer map page number */
  56107. int offset; /* Offset in pointer map page */
  56108. int rc; /* Return code from subfunctions */
  56109. if( *pRC ) return;
  56110. assert( sqlite3_mutex_held(pBt->mutex) );
  56111. /* The master-journal page number must never be used as a pointer map page */
  56112. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  56113. assert( pBt->autoVacuum );
  56114. if( key==0 ){
  56115. *pRC = SQLITE_CORRUPT_BKPT;
  56116. return;
  56117. }
  56118. iPtrmap = PTRMAP_PAGENO(pBt, key);
  56119. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  56120. if( rc!=SQLITE_OK ){
  56121. *pRC = rc;
  56122. return;
  56123. }
  56124. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  56125. if( offset<0 ){
  56126. *pRC = SQLITE_CORRUPT_BKPT;
  56127. goto ptrmap_exit;
  56128. }
  56129. assert( offset <= (int)pBt->usableSize-5 );
  56130. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  56131. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  56132. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  56133. *pRC= rc = sqlite3PagerWrite(pDbPage);
  56134. if( rc==SQLITE_OK ){
  56135. pPtrmap[offset] = eType;
  56136. put4byte(&pPtrmap[offset+1], parent);
  56137. }
  56138. }
  56139. ptrmap_exit:
  56140. sqlite3PagerUnref(pDbPage);
  56141. }
  56142. /*
  56143. ** Read an entry from the pointer map.
  56144. **
  56145. ** This routine retrieves the pointer map entry for page 'key', writing
  56146. ** the type and parent page number to *pEType and *pPgno respectively.
  56147. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  56148. */
  56149. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  56150. DbPage *pDbPage; /* The pointer map page */
  56151. int iPtrmap; /* Pointer map page index */
  56152. u8 *pPtrmap; /* Pointer map page data */
  56153. int offset; /* Offset of entry in pointer map */
  56154. int rc;
  56155. assert( sqlite3_mutex_held(pBt->mutex) );
  56156. iPtrmap = PTRMAP_PAGENO(pBt, key);
  56157. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  56158. if( rc!=0 ){
  56159. return rc;
  56160. }
  56161. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  56162. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  56163. if( offset<0 ){
  56164. sqlite3PagerUnref(pDbPage);
  56165. return SQLITE_CORRUPT_BKPT;
  56166. }
  56167. assert( offset <= (int)pBt->usableSize-5 );
  56168. assert( pEType!=0 );
  56169. *pEType = pPtrmap[offset];
  56170. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  56171. sqlite3PagerUnref(pDbPage);
  56172. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  56173. return SQLITE_OK;
  56174. }
  56175. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  56176. #define ptrmapPut(w,x,y,z,rc)
  56177. #define ptrmapGet(w,x,y,z) SQLITE_OK
  56178. #define ptrmapPutOvflPtr(x, y, rc)
  56179. #endif
  56180. /*
  56181. ** Given a btree page and a cell index (0 means the first cell on
  56182. ** the page, 1 means the second cell, and so forth) return a pointer
  56183. ** to the cell content.
  56184. **
  56185. ** findCellPastPtr() does the same except it skips past the initial
  56186. ** 4-byte child pointer found on interior pages, if there is one.
  56187. **
  56188. ** This routine works only for pages that do not contain overflow cells.
  56189. */
  56190. #define findCell(P,I) \
  56191. ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  56192. #define findCellPastPtr(P,I) \
  56193. ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  56194. /*
  56195. ** This is common tail processing for btreeParseCellPtr() and
  56196. ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
  56197. ** on a single B-tree page. Make necessary adjustments to the CellInfo
  56198. ** structure.
  56199. */
  56200. static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
  56201. MemPage *pPage, /* Page containing the cell */
  56202. u8 *pCell, /* Pointer to the cell text. */
  56203. CellInfo *pInfo /* Fill in this structure */
  56204. ){
  56205. /* If the payload will not fit completely on the local page, we have
  56206. ** to decide how much to store locally and how much to spill onto
  56207. ** overflow pages. The strategy is to minimize the amount of unused
  56208. ** space on overflow pages while keeping the amount of local storage
  56209. ** in between minLocal and maxLocal.
  56210. **
  56211. ** Warning: changing the way overflow payload is distributed in any
  56212. ** way will result in an incompatible file format.
  56213. */
  56214. int minLocal; /* Minimum amount of payload held locally */
  56215. int maxLocal; /* Maximum amount of payload held locally */
  56216. int surplus; /* Overflow payload available for local storage */
  56217. minLocal = pPage->minLocal;
  56218. maxLocal = pPage->maxLocal;
  56219. surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
  56220. testcase( surplus==maxLocal );
  56221. testcase( surplus==maxLocal+1 );
  56222. if( surplus <= maxLocal ){
  56223. pInfo->nLocal = (u16)surplus;
  56224. }else{
  56225. pInfo->nLocal = (u16)minLocal;
  56226. }
  56227. pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
  56228. }
  56229. /*
  56230. ** The following routines are implementations of the MemPage.xParseCell()
  56231. ** method.
  56232. **
  56233. ** Parse a cell content block and fill in the CellInfo structure.
  56234. **
  56235. ** btreeParseCellPtr() => table btree leaf nodes
  56236. ** btreeParseCellNoPayload() => table btree internal nodes
  56237. ** btreeParseCellPtrIndex() => index btree nodes
  56238. **
  56239. ** There is also a wrapper function btreeParseCell() that works for
  56240. ** all MemPage types and that references the cell by index rather than
  56241. ** by pointer.
  56242. */
  56243. static void btreeParseCellPtrNoPayload(
  56244. MemPage *pPage, /* Page containing the cell */
  56245. u8 *pCell, /* Pointer to the cell text. */
  56246. CellInfo *pInfo /* Fill in this structure */
  56247. ){
  56248. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56249. assert( pPage->leaf==0 );
  56250. assert( pPage->childPtrSize==4 );
  56251. #ifndef SQLITE_DEBUG
  56252. UNUSED_PARAMETER(pPage);
  56253. #endif
  56254. pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
  56255. pInfo->nPayload = 0;
  56256. pInfo->nLocal = 0;
  56257. pInfo->pPayload = 0;
  56258. return;
  56259. }
  56260. static void btreeParseCellPtr(
  56261. MemPage *pPage, /* Page containing the cell */
  56262. u8 *pCell, /* Pointer to the cell text. */
  56263. CellInfo *pInfo /* Fill in this structure */
  56264. ){
  56265. u8 *pIter; /* For scanning through pCell */
  56266. u32 nPayload; /* Number of bytes of cell payload */
  56267. u64 iKey; /* Extracted Key value */
  56268. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56269. assert( pPage->leaf==0 || pPage->leaf==1 );
  56270. assert( pPage->intKeyLeaf );
  56271. assert( pPage->childPtrSize==0 );
  56272. pIter = pCell;
  56273. /* The next block of code is equivalent to:
  56274. **
  56275. ** pIter += getVarint32(pIter, nPayload);
  56276. **
  56277. ** The code is inlined to avoid a function call.
  56278. */
  56279. nPayload = *pIter;
  56280. if( nPayload>=0x80 ){
  56281. u8 *pEnd = &pIter[8];
  56282. nPayload &= 0x7f;
  56283. do{
  56284. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  56285. }while( (*pIter)>=0x80 && pIter<pEnd );
  56286. }
  56287. pIter++;
  56288. /* The next block of code is equivalent to:
  56289. **
  56290. ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
  56291. **
  56292. ** The code is inlined to avoid a function call.
  56293. */
  56294. iKey = *pIter;
  56295. if( iKey>=0x80 ){
  56296. u8 *pEnd = &pIter[7];
  56297. iKey &= 0x7f;
  56298. while(1){
  56299. iKey = (iKey<<7) | (*++pIter & 0x7f);
  56300. if( (*pIter)<0x80 ) break;
  56301. if( pIter>=pEnd ){
  56302. iKey = (iKey<<8) | *++pIter;
  56303. break;
  56304. }
  56305. }
  56306. }
  56307. pIter++;
  56308. pInfo->nKey = *(i64*)&iKey;
  56309. pInfo->nPayload = nPayload;
  56310. pInfo->pPayload = pIter;
  56311. testcase( nPayload==pPage->maxLocal );
  56312. testcase( nPayload==pPage->maxLocal+1 );
  56313. if( nPayload<=pPage->maxLocal ){
  56314. /* This is the (easy) common case where the entire payload fits
  56315. ** on the local page. No overflow is required.
  56316. */
  56317. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  56318. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  56319. pInfo->nLocal = (u16)nPayload;
  56320. }else{
  56321. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  56322. }
  56323. }
  56324. static void btreeParseCellPtrIndex(
  56325. MemPage *pPage, /* Page containing the cell */
  56326. u8 *pCell, /* Pointer to the cell text. */
  56327. CellInfo *pInfo /* Fill in this structure */
  56328. ){
  56329. u8 *pIter; /* For scanning through pCell */
  56330. u32 nPayload; /* Number of bytes of cell payload */
  56331. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56332. assert( pPage->leaf==0 || pPage->leaf==1 );
  56333. assert( pPage->intKeyLeaf==0 );
  56334. pIter = pCell + pPage->childPtrSize;
  56335. nPayload = *pIter;
  56336. if( nPayload>=0x80 ){
  56337. u8 *pEnd = &pIter[8];
  56338. nPayload &= 0x7f;
  56339. do{
  56340. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  56341. }while( *(pIter)>=0x80 && pIter<pEnd );
  56342. }
  56343. pIter++;
  56344. pInfo->nKey = nPayload;
  56345. pInfo->nPayload = nPayload;
  56346. pInfo->pPayload = pIter;
  56347. testcase( nPayload==pPage->maxLocal );
  56348. testcase( nPayload==pPage->maxLocal+1 );
  56349. if( nPayload<=pPage->maxLocal ){
  56350. /* This is the (easy) common case where the entire payload fits
  56351. ** on the local page. No overflow is required.
  56352. */
  56353. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  56354. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  56355. pInfo->nLocal = (u16)nPayload;
  56356. }else{
  56357. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  56358. }
  56359. }
  56360. static void btreeParseCell(
  56361. MemPage *pPage, /* Page containing the cell */
  56362. int iCell, /* The cell index. First cell is 0 */
  56363. CellInfo *pInfo /* Fill in this structure */
  56364. ){
  56365. pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
  56366. }
  56367. /*
  56368. ** The following routines are implementations of the MemPage.xCellSize
  56369. ** method.
  56370. **
  56371. ** Compute the total number of bytes that a Cell needs in the cell
  56372. ** data area of the btree-page. The return number includes the cell
  56373. ** data header and the local payload, but not any overflow page or
  56374. ** the space used by the cell pointer.
  56375. **
  56376. ** cellSizePtrNoPayload() => table internal nodes
  56377. ** cellSizePtr() => all index nodes & table leaf nodes
  56378. */
  56379. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  56380. u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
  56381. u8 *pEnd; /* End mark for a varint */
  56382. u32 nSize; /* Size value to return */
  56383. #ifdef SQLITE_DEBUG
  56384. /* The value returned by this function should always be the same as
  56385. ** the (CellInfo.nSize) value found by doing a full parse of the
  56386. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  56387. ** this function verifies that this invariant is not violated. */
  56388. CellInfo debuginfo;
  56389. pPage->xParseCell(pPage, pCell, &debuginfo);
  56390. #endif
  56391. nSize = *pIter;
  56392. if( nSize>=0x80 ){
  56393. pEnd = &pIter[8];
  56394. nSize &= 0x7f;
  56395. do{
  56396. nSize = (nSize<<7) | (*++pIter & 0x7f);
  56397. }while( *(pIter)>=0x80 && pIter<pEnd );
  56398. }
  56399. pIter++;
  56400. if( pPage->intKey ){
  56401. /* pIter now points at the 64-bit integer key value, a variable length
  56402. ** integer. The following block moves pIter to point at the first byte
  56403. ** past the end of the key value. */
  56404. pEnd = &pIter[9];
  56405. while( (*pIter++)&0x80 && pIter<pEnd );
  56406. }
  56407. testcase( nSize==pPage->maxLocal );
  56408. testcase( nSize==pPage->maxLocal+1 );
  56409. if( nSize<=pPage->maxLocal ){
  56410. nSize += (u32)(pIter - pCell);
  56411. if( nSize<4 ) nSize = 4;
  56412. }else{
  56413. int minLocal = pPage->minLocal;
  56414. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  56415. testcase( nSize==pPage->maxLocal );
  56416. testcase( nSize==pPage->maxLocal+1 );
  56417. if( nSize>pPage->maxLocal ){
  56418. nSize = minLocal;
  56419. }
  56420. nSize += 4 + (u16)(pIter - pCell);
  56421. }
  56422. assert( nSize==debuginfo.nSize || CORRUPT_DB );
  56423. return (u16)nSize;
  56424. }
  56425. static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
  56426. u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
  56427. u8 *pEnd; /* End mark for a varint */
  56428. #ifdef SQLITE_DEBUG
  56429. /* The value returned by this function should always be the same as
  56430. ** the (CellInfo.nSize) value found by doing a full parse of the
  56431. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  56432. ** this function verifies that this invariant is not violated. */
  56433. CellInfo debuginfo;
  56434. pPage->xParseCell(pPage, pCell, &debuginfo);
  56435. #else
  56436. UNUSED_PARAMETER(pPage);
  56437. #endif
  56438. assert( pPage->childPtrSize==4 );
  56439. pEnd = pIter + 9;
  56440. while( (*pIter++)&0x80 && pIter<pEnd );
  56441. assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
  56442. return (u16)(pIter - pCell);
  56443. }
  56444. #ifdef SQLITE_DEBUG
  56445. /* This variation on cellSizePtr() is used inside of assert() statements
  56446. ** only. */
  56447. static u16 cellSize(MemPage *pPage, int iCell){
  56448. return pPage->xCellSize(pPage, findCell(pPage, iCell));
  56449. }
  56450. #endif
  56451. #ifndef SQLITE_OMIT_AUTOVACUUM
  56452. /*
  56453. ** If the cell pCell, part of page pPage contains a pointer
  56454. ** to an overflow page, insert an entry into the pointer-map
  56455. ** for the overflow page.
  56456. */
  56457. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  56458. CellInfo info;
  56459. if( *pRC ) return;
  56460. assert( pCell!=0 );
  56461. pPage->xParseCell(pPage, pCell, &info);
  56462. if( info.nLocal<info.nPayload ){
  56463. Pgno ovfl = get4byte(&pCell[info.nSize-4]);
  56464. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  56465. }
  56466. }
  56467. #endif
  56468. /*
  56469. ** Defragment the page given. This routine reorganizes cells within the
  56470. ** page so that there are no free-blocks on the free-block list.
  56471. **
  56472. ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
  56473. ** present in the page after this routine returns.
  56474. **
  56475. ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
  56476. ** b-tree page so that there are no freeblocks or fragment bytes, all
  56477. ** unused bytes are contained in the unallocated space region, and all
  56478. ** cells are packed tightly at the end of the page.
  56479. */
  56480. static int defragmentPage(MemPage *pPage, int nMaxFrag){
  56481. int i; /* Loop counter */
  56482. int pc; /* Address of the i-th cell */
  56483. int hdr; /* Offset to the page header */
  56484. int size; /* Size of a cell */
  56485. int usableSize; /* Number of usable bytes on a page */
  56486. int cellOffset; /* Offset to the cell pointer array */
  56487. int cbrk; /* Offset to the cell content area */
  56488. int nCell; /* Number of cells on the page */
  56489. unsigned char *data; /* The page data */
  56490. unsigned char *temp; /* Temp area for cell content */
  56491. unsigned char *src; /* Source of content */
  56492. int iCellFirst; /* First allowable cell index */
  56493. int iCellLast; /* Last possible cell index */
  56494. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  56495. assert( pPage->pBt!=0 );
  56496. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  56497. assert( pPage->nOverflow==0 );
  56498. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56499. temp = 0;
  56500. src = data = pPage->aData;
  56501. hdr = pPage->hdrOffset;
  56502. cellOffset = pPage->cellOffset;
  56503. nCell = pPage->nCell;
  56504. assert( nCell==get2byte(&data[hdr+3]) );
  56505. iCellFirst = cellOffset + 2*nCell;
  56506. usableSize = pPage->pBt->usableSize;
  56507. /* This block handles pages with two or fewer free blocks and nMaxFrag
  56508. ** or fewer fragmented bytes. In this case it is faster to move the
  56509. ** two (or one) blocks of cells using memmove() and add the required
  56510. ** offsets to each pointer in the cell-pointer array than it is to
  56511. ** reconstruct the entire page. */
  56512. if( (int)data[hdr+7]<=nMaxFrag ){
  56513. int iFree = get2byte(&data[hdr+1]);
  56514. if( iFree ){
  56515. int iFree2 = get2byte(&data[iFree]);
  56516. /* pageFindSlot() has already verified that free blocks are sorted
  56517. ** in order of offset within the page, and that no block extends
  56518. ** past the end of the page. Provided the two free slots do not
  56519. ** overlap, this guarantees that the memmove() calls below will not
  56520. ** overwrite the usableSize byte buffer, even if the database page
  56521. ** is corrupt. */
  56522. assert( iFree2==0 || iFree2>iFree );
  56523. assert( iFree+get2byte(&data[iFree+2]) <= usableSize );
  56524. assert( iFree2==0 || iFree2+get2byte(&data[iFree2+2]) <= usableSize );
  56525. if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
  56526. u8 *pEnd = &data[cellOffset + nCell*2];
  56527. u8 *pAddr;
  56528. int sz2 = 0;
  56529. int sz = get2byte(&data[iFree+2]);
  56530. int top = get2byte(&data[hdr+5]);
  56531. if( iFree2 ){
  56532. if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_BKPT;
  56533. sz2 = get2byte(&data[iFree2+2]);
  56534. assert( iFree+sz+sz2+iFree2-(iFree+sz) <= usableSize );
  56535. memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
  56536. sz += sz2;
  56537. }
  56538. cbrk = top+sz;
  56539. assert( cbrk+(iFree-top) <= usableSize );
  56540. memmove(&data[cbrk], &data[top], iFree-top);
  56541. for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
  56542. pc = get2byte(pAddr);
  56543. if( pc<iFree ){ put2byte(pAddr, pc+sz); }
  56544. else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
  56545. }
  56546. goto defragment_out;
  56547. }
  56548. }
  56549. }
  56550. cbrk = usableSize;
  56551. iCellLast = usableSize - 4;
  56552. for(i=0; i<nCell; i++){
  56553. u8 *pAddr; /* The i-th cell pointer */
  56554. pAddr = &data[cellOffset + i*2];
  56555. pc = get2byte(pAddr);
  56556. testcase( pc==iCellFirst );
  56557. testcase( pc==iCellLast );
  56558. /* These conditions have already been verified in btreeInitPage()
  56559. ** if PRAGMA cell_size_check=ON.
  56560. */
  56561. if( pc<iCellFirst || pc>iCellLast ){
  56562. return SQLITE_CORRUPT_BKPT;
  56563. }
  56564. assert( pc>=iCellFirst && pc<=iCellLast );
  56565. size = pPage->xCellSize(pPage, &src[pc]);
  56566. cbrk -= size;
  56567. if( cbrk<iCellFirst || pc+size>usableSize ){
  56568. return SQLITE_CORRUPT_BKPT;
  56569. }
  56570. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  56571. testcase( cbrk+size==usableSize );
  56572. testcase( pc+size==usableSize );
  56573. put2byte(pAddr, cbrk);
  56574. if( temp==0 ){
  56575. int x;
  56576. if( cbrk==pc ) continue;
  56577. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  56578. x = get2byte(&data[hdr+5]);
  56579. memcpy(&temp[x], &data[x], (cbrk+size) - x);
  56580. src = temp;
  56581. }
  56582. memcpy(&data[cbrk], &src[pc], size);
  56583. }
  56584. data[hdr+7] = 0;
  56585. defragment_out:
  56586. if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
  56587. return SQLITE_CORRUPT_BKPT;
  56588. }
  56589. assert( cbrk>=iCellFirst );
  56590. put2byte(&data[hdr+5], cbrk);
  56591. data[hdr+1] = 0;
  56592. data[hdr+2] = 0;
  56593. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  56594. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  56595. return SQLITE_OK;
  56596. }
  56597. /*
  56598. ** Search the free-list on page pPg for space to store a cell nByte bytes in
  56599. ** size. If one can be found, return a pointer to the space and remove it
  56600. ** from the free-list.
  56601. **
  56602. ** If no suitable space can be found on the free-list, return NULL.
  56603. **
  56604. ** This function may detect corruption within pPg. If corruption is
  56605. ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
  56606. **
  56607. ** Slots on the free list that are between 1 and 3 bytes larger than nByte
  56608. ** will be ignored if adding the extra space to the fragmentation count
  56609. ** causes the fragmentation count to exceed 60.
  56610. */
  56611. static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
  56612. const int hdr = pPg->hdrOffset;
  56613. u8 * const aData = pPg->aData;
  56614. int iAddr = hdr + 1;
  56615. int pc = get2byte(&aData[iAddr]);
  56616. int x;
  56617. int usableSize = pPg->pBt->usableSize;
  56618. assert( pc>0 );
  56619. do{
  56620. int size; /* Size of the free slot */
  56621. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  56622. ** increasing offset. */
  56623. if( pc>usableSize-4 || pc<iAddr+4 ){
  56624. *pRc = SQLITE_CORRUPT_BKPT;
  56625. return 0;
  56626. }
  56627. /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
  56628. ** freeblock form a big-endian integer which is the size of the freeblock
  56629. ** in bytes, including the 4-byte header. */
  56630. size = get2byte(&aData[pc+2]);
  56631. if( (x = size - nByte)>=0 ){
  56632. testcase( x==4 );
  56633. testcase( x==3 );
  56634. if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){
  56635. *pRc = SQLITE_CORRUPT_BKPT;
  56636. return 0;
  56637. }else if( x<4 ){
  56638. /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
  56639. ** number of bytes in fragments may not exceed 60. */
  56640. if( aData[hdr+7]>57 ) return 0;
  56641. /* Remove the slot from the free-list. Update the number of
  56642. ** fragmented bytes within the page. */
  56643. memcpy(&aData[iAddr], &aData[pc], 2);
  56644. aData[hdr+7] += (u8)x;
  56645. }else{
  56646. /* The slot remains on the free-list. Reduce its size to account
  56647. ** for the portion used by the new allocation. */
  56648. put2byte(&aData[pc+2], x);
  56649. }
  56650. return &aData[pc + x];
  56651. }
  56652. iAddr = pc;
  56653. pc = get2byte(&aData[pc]);
  56654. }while( pc );
  56655. return 0;
  56656. }
  56657. /*
  56658. ** Allocate nByte bytes of space from within the B-Tree page passed
  56659. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  56660. ** of the first byte of allocated space. Return either SQLITE_OK or
  56661. ** an error code (usually SQLITE_CORRUPT).
  56662. **
  56663. ** The caller guarantees that there is sufficient space to make the
  56664. ** allocation. This routine might need to defragment in order to bring
  56665. ** all the space together, however. This routine will avoid using
  56666. ** the first two bytes past the cell pointer area since presumably this
  56667. ** allocation is being made in order to insert a new cell, so we will
  56668. ** also end up needing a new cell pointer.
  56669. */
  56670. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  56671. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  56672. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  56673. int top; /* First byte of cell content area */
  56674. int rc = SQLITE_OK; /* Integer return code */
  56675. int gap; /* First byte of gap between cell pointers and cell content */
  56676. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  56677. assert( pPage->pBt );
  56678. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56679. assert( nByte>=0 ); /* Minimum cell size is 4 */
  56680. assert( pPage->nFree>=nByte );
  56681. assert( pPage->nOverflow==0 );
  56682. assert( nByte < (int)(pPage->pBt->usableSize-8) );
  56683. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  56684. gap = pPage->cellOffset + 2*pPage->nCell;
  56685. assert( gap<=65536 );
  56686. /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
  56687. ** and the reserved space is zero (the usual value for reserved space)
  56688. ** then the cell content offset of an empty page wants to be 65536.
  56689. ** However, that integer is too large to be stored in a 2-byte unsigned
  56690. ** integer, so a value of 0 is used in its place. */
  56691. top = get2byte(&data[hdr+5]);
  56692. assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
  56693. if( gap>top ){
  56694. if( top==0 && pPage->pBt->usableSize==65536 ){
  56695. top = 65536;
  56696. }else{
  56697. return SQLITE_CORRUPT_BKPT;
  56698. }
  56699. }
  56700. /* If there is enough space between gap and top for one more cell pointer
  56701. ** array entry offset, and if the freelist is not empty, then search the
  56702. ** freelist looking for a free slot big enough to satisfy the request.
  56703. */
  56704. testcase( gap+2==top );
  56705. testcase( gap+1==top );
  56706. testcase( gap==top );
  56707. if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
  56708. u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
  56709. if( pSpace ){
  56710. assert( pSpace>=data && (pSpace - data)<65536 );
  56711. *pIdx = (int)(pSpace - data);
  56712. return SQLITE_OK;
  56713. }else if( rc ){
  56714. return rc;
  56715. }
  56716. }
  56717. /* The request could not be fulfilled using a freelist slot. Check
  56718. ** to see if defragmentation is necessary.
  56719. */
  56720. testcase( gap+2+nByte==top );
  56721. if( gap+2+nByte>top ){
  56722. assert( pPage->nCell>0 || CORRUPT_DB );
  56723. rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
  56724. if( rc ) return rc;
  56725. top = get2byteNotZero(&data[hdr+5]);
  56726. assert( gap+2+nByte<=top );
  56727. }
  56728. /* Allocate memory from the gap in between the cell pointer array
  56729. ** and the cell content area. The btreeInitPage() call has already
  56730. ** validated the freelist. Given that the freelist is valid, there
  56731. ** is no way that the allocation can extend off the end of the page.
  56732. ** The assert() below verifies the previous sentence.
  56733. */
  56734. top -= nByte;
  56735. put2byte(&data[hdr+5], top);
  56736. assert( top+nByte <= (int)pPage->pBt->usableSize );
  56737. *pIdx = top;
  56738. return SQLITE_OK;
  56739. }
  56740. /*
  56741. ** Return a section of the pPage->aData to the freelist.
  56742. ** The first byte of the new free block is pPage->aData[iStart]
  56743. ** and the size of the block is iSize bytes.
  56744. **
  56745. ** Adjacent freeblocks are coalesced.
  56746. **
  56747. ** Note that even though the freeblock list was checked by btreeInitPage(),
  56748. ** that routine will not detect overlap between cells or freeblocks. Nor
  56749. ** does it detect cells or freeblocks that encrouch into the reserved bytes
  56750. ** at the end of the page. So do additional corruption checks inside this
  56751. ** routine and return SQLITE_CORRUPT if any problems are found.
  56752. */
  56753. static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
  56754. u16 iPtr; /* Address of ptr to next freeblock */
  56755. u16 iFreeBlk; /* Address of the next freeblock */
  56756. u8 hdr; /* Page header size. 0 or 100 */
  56757. u8 nFrag = 0; /* Reduction in fragmentation */
  56758. u16 iOrigSize = iSize; /* Original value of iSize */
  56759. u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
  56760. u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
  56761. unsigned char *data = pPage->aData; /* Page content */
  56762. assert( pPage->pBt!=0 );
  56763. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  56764. assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
  56765. assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
  56766. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56767. assert( iSize>=4 ); /* Minimum cell size is 4 */
  56768. assert( iStart<=iLast );
  56769. /* Overwrite deleted information with zeros when the secure_delete
  56770. ** option is enabled */
  56771. if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
  56772. memset(&data[iStart], 0, iSize);
  56773. }
  56774. /* The list of freeblocks must be in ascending order. Find the
  56775. ** spot on the list where iStart should be inserted.
  56776. */
  56777. hdr = pPage->hdrOffset;
  56778. iPtr = hdr + 1;
  56779. if( data[iPtr+1]==0 && data[iPtr]==0 ){
  56780. iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
  56781. }else{
  56782. while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
  56783. if( iFreeBlk<iPtr+4 ){
  56784. if( iFreeBlk==0 ) break;
  56785. return SQLITE_CORRUPT_BKPT;
  56786. }
  56787. iPtr = iFreeBlk;
  56788. }
  56789. if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
  56790. assert( iFreeBlk>iPtr || iFreeBlk==0 );
  56791. /* At this point:
  56792. ** iFreeBlk: First freeblock after iStart, or zero if none
  56793. ** iPtr: The address of a pointer to iFreeBlk
  56794. **
  56795. ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
  56796. */
  56797. if( iFreeBlk && iEnd+3>=iFreeBlk ){
  56798. nFrag = iFreeBlk - iEnd;
  56799. if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
  56800. iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
  56801. if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT;
  56802. iSize = iEnd - iStart;
  56803. iFreeBlk = get2byte(&data[iFreeBlk]);
  56804. }
  56805. /* If iPtr is another freeblock (that is, if iPtr is not the freelist
  56806. ** pointer in the page header) then check to see if iStart should be
  56807. ** coalesced onto the end of iPtr.
  56808. */
  56809. if( iPtr>hdr+1 ){
  56810. int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
  56811. if( iPtrEnd+3>=iStart ){
  56812. if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
  56813. nFrag += iStart - iPtrEnd;
  56814. iSize = iEnd - iPtr;
  56815. iStart = iPtr;
  56816. }
  56817. }
  56818. if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
  56819. data[hdr+7] -= nFrag;
  56820. }
  56821. if( iStart==get2byte(&data[hdr+5]) ){
  56822. /* The new freeblock is at the beginning of the cell content area,
  56823. ** so just extend the cell content area rather than create another
  56824. ** freelist entry */
  56825. if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
  56826. put2byte(&data[hdr+1], iFreeBlk);
  56827. put2byte(&data[hdr+5], iEnd);
  56828. }else{
  56829. /* Insert the new freeblock into the freelist */
  56830. put2byte(&data[iPtr], iStart);
  56831. put2byte(&data[iStart], iFreeBlk);
  56832. put2byte(&data[iStart+2], iSize);
  56833. }
  56834. pPage->nFree += iOrigSize;
  56835. return SQLITE_OK;
  56836. }
  56837. /*
  56838. ** Decode the flags byte (the first byte of the header) for a page
  56839. ** and initialize fields of the MemPage structure accordingly.
  56840. **
  56841. ** Only the following combinations are supported. Anything different
  56842. ** indicates a corrupt database files:
  56843. **
  56844. ** PTF_ZERODATA
  56845. ** PTF_ZERODATA | PTF_LEAF
  56846. ** PTF_LEAFDATA | PTF_INTKEY
  56847. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  56848. */
  56849. static int decodeFlags(MemPage *pPage, int flagByte){
  56850. BtShared *pBt; /* A copy of pPage->pBt */
  56851. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  56852. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56853. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  56854. flagByte &= ~PTF_LEAF;
  56855. pPage->childPtrSize = 4-4*pPage->leaf;
  56856. pPage->xCellSize = cellSizePtr;
  56857. pBt = pPage->pBt;
  56858. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  56859. /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
  56860. ** interior table b-tree page. */
  56861. assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
  56862. /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
  56863. ** leaf table b-tree page. */
  56864. assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
  56865. pPage->intKey = 1;
  56866. if( pPage->leaf ){
  56867. pPage->intKeyLeaf = 1;
  56868. pPage->xParseCell = btreeParseCellPtr;
  56869. }else{
  56870. pPage->intKeyLeaf = 0;
  56871. pPage->xCellSize = cellSizePtrNoPayload;
  56872. pPage->xParseCell = btreeParseCellPtrNoPayload;
  56873. }
  56874. pPage->maxLocal = pBt->maxLeaf;
  56875. pPage->minLocal = pBt->minLeaf;
  56876. }else if( flagByte==PTF_ZERODATA ){
  56877. /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
  56878. ** interior index b-tree page. */
  56879. assert( (PTF_ZERODATA)==2 );
  56880. /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
  56881. ** leaf index b-tree page. */
  56882. assert( (PTF_ZERODATA|PTF_LEAF)==10 );
  56883. pPage->intKey = 0;
  56884. pPage->intKeyLeaf = 0;
  56885. pPage->xParseCell = btreeParseCellPtrIndex;
  56886. pPage->maxLocal = pBt->maxLocal;
  56887. pPage->minLocal = pBt->minLocal;
  56888. }else{
  56889. /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
  56890. ** an error. */
  56891. return SQLITE_CORRUPT_BKPT;
  56892. }
  56893. pPage->max1bytePayload = pBt->max1bytePayload;
  56894. return SQLITE_OK;
  56895. }
  56896. /*
  56897. ** Initialize the auxiliary information for a disk block.
  56898. **
  56899. ** Return SQLITE_OK on success. If we see that the page does
  56900. ** not contain a well-formed database page, then return
  56901. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  56902. ** guarantee that the page is well-formed. It only shows that
  56903. ** we failed to detect any corruption.
  56904. */
  56905. static int btreeInitPage(MemPage *pPage){
  56906. assert( pPage->pBt!=0 );
  56907. assert( pPage->pBt->db!=0 );
  56908. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56909. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  56910. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  56911. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  56912. if( !pPage->isInit ){
  56913. int pc; /* Address of a freeblock within pPage->aData[] */
  56914. u8 hdr; /* Offset to beginning of page header */
  56915. u8 *data; /* Equal to pPage->aData */
  56916. BtShared *pBt; /* The main btree structure */
  56917. int usableSize; /* Amount of usable space on each page */
  56918. u16 cellOffset; /* Offset from start of page to first cell pointer */
  56919. int nFree; /* Number of unused bytes on the page */
  56920. int top; /* First byte of the cell content area */
  56921. int iCellFirst; /* First allowable cell or freeblock offset */
  56922. int iCellLast; /* Last possible cell or freeblock offset */
  56923. pBt = pPage->pBt;
  56924. hdr = pPage->hdrOffset;
  56925. data = pPage->aData;
  56926. /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
  56927. ** the b-tree page type. */
  56928. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  56929. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  56930. pPage->maskPage = (u16)(pBt->pageSize - 1);
  56931. pPage->nOverflow = 0;
  56932. usableSize = pBt->usableSize;
  56933. pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
  56934. pPage->aDataEnd = &data[usableSize];
  56935. pPage->aCellIdx = &data[cellOffset];
  56936. pPage->aDataOfst = &data[pPage->childPtrSize];
  56937. /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
  56938. ** the start of the cell content area. A zero value for this integer is
  56939. ** interpreted as 65536. */
  56940. top = get2byteNotZero(&data[hdr+5]);
  56941. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  56942. ** number of cells on the page. */
  56943. pPage->nCell = get2byte(&data[hdr+3]);
  56944. if( pPage->nCell>MX_CELL(pBt) ){
  56945. /* To many cells for a single page. The page must be corrupt */
  56946. return SQLITE_CORRUPT_BKPT;
  56947. }
  56948. testcase( pPage->nCell==MX_CELL(pBt) );
  56949. /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
  56950. ** possible for a root page of a table that contains no rows) then the
  56951. ** offset to the cell content area will equal the page size minus the
  56952. ** bytes of reserved space. */
  56953. assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
  56954. /* A malformed database page might cause us to read past the end
  56955. ** of page when parsing a cell.
  56956. **
  56957. ** The following block of code checks early to see if a cell extends
  56958. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  56959. ** returned if it does.
  56960. */
  56961. iCellFirst = cellOffset + 2*pPage->nCell;
  56962. iCellLast = usableSize - 4;
  56963. if( pBt->db->flags & SQLITE_CellSizeCk ){
  56964. int i; /* Index into the cell pointer array */
  56965. int sz; /* Size of a cell */
  56966. if( !pPage->leaf ) iCellLast--;
  56967. for(i=0; i<pPage->nCell; i++){
  56968. pc = get2byteAligned(&data[cellOffset+i*2]);
  56969. testcase( pc==iCellFirst );
  56970. testcase( pc==iCellLast );
  56971. if( pc<iCellFirst || pc>iCellLast ){
  56972. return SQLITE_CORRUPT_BKPT;
  56973. }
  56974. sz = pPage->xCellSize(pPage, &data[pc]);
  56975. testcase( pc+sz==usableSize );
  56976. if( pc+sz>usableSize ){
  56977. return SQLITE_CORRUPT_BKPT;
  56978. }
  56979. }
  56980. if( !pPage->leaf ) iCellLast++;
  56981. }
  56982. /* Compute the total free space on the page
  56983. ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
  56984. ** start of the first freeblock on the page, or is zero if there are no
  56985. ** freeblocks. */
  56986. pc = get2byte(&data[hdr+1]);
  56987. nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
  56988. if( pc>0 ){
  56989. u32 next, size;
  56990. if( pc<iCellFirst ){
  56991. /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
  56992. ** always be at least one cell before the first freeblock.
  56993. */
  56994. return SQLITE_CORRUPT_BKPT;
  56995. }
  56996. while( 1 ){
  56997. if( pc>iCellLast ){
  56998. return SQLITE_CORRUPT_BKPT; /* Freeblock off the end of the page */
  56999. }
  57000. next = get2byte(&data[pc]);
  57001. size = get2byte(&data[pc+2]);
  57002. nFree = nFree + size;
  57003. if( next<=pc+size+3 ) break;
  57004. pc = next;
  57005. }
  57006. if( next>0 ){
  57007. return SQLITE_CORRUPT_BKPT; /* Freeblock not in ascending order */
  57008. }
  57009. if( pc+size>(unsigned int)usableSize ){
  57010. return SQLITE_CORRUPT_BKPT; /* Last freeblock extends past page end */
  57011. }
  57012. }
  57013. /* At this point, nFree contains the sum of the offset to the start
  57014. ** of the cell-content area plus the number of free bytes within
  57015. ** the cell-content area. If this is greater than the usable-size
  57016. ** of the page, then the page must be corrupted. This check also
  57017. ** serves to verify that the offset to the start of the cell-content
  57018. ** area, according to the page header, lies within the page.
  57019. */
  57020. if( nFree>usableSize ){
  57021. return SQLITE_CORRUPT_BKPT;
  57022. }
  57023. pPage->nFree = (u16)(nFree - iCellFirst);
  57024. pPage->isInit = 1;
  57025. }
  57026. return SQLITE_OK;
  57027. }
  57028. /*
  57029. ** Set up a raw page so that it looks like a database page holding
  57030. ** no entries.
  57031. */
  57032. static void zeroPage(MemPage *pPage, int flags){
  57033. unsigned char *data = pPage->aData;
  57034. BtShared *pBt = pPage->pBt;
  57035. u8 hdr = pPage->hdrOffset;
  57036. u16 first;
  57037. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  57038. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  57039. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  57040. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  57041. assert( sqlite3_mutex_held(pBt->mutex) );
  57042. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  57043. memset(&data[hdr], 0, pBt->usableSize - hdr);
  57044. }
  57045. data[hdr] = (char)flags;
  57046. first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
  57047. memset(&data[hdr+1], 0, 4);
  57048. data[hdr+7] = 0;
  57049. put2byte(&data[hdr+5], pBt->usableSize);
  57050. pPage->nFree = (u16)(pBt->usableSize - first);
  57051. decodeFlags(pPage, flags);
  57052. pPage->cellOffset = first;
  57053. pPage->aDataEnd = &data[pBt->usableSize];
  57054. pPage->aCellIdx = &data[first];
  57055. pPage->aDataOfst = &data[pPage->childPtrSize];
  57056. pPage->nOverflow = 0;
  57057. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  57058. pPage->maskPage = (u16)(pBt->pageSize - 1);
  57059. pPage->nCell = 0;
  57060. pPage->isInit = 1;
  57061. }
  57062. /*
  57063. ** Convert a DbPage obtained from the pager into a MemPage used by
  57064. ** the btree layer.
  57065. */
  57066. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  57067. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  57068. if( pgno!=pPage->pgno ){
  57069. pPage->aData = sqlite3PagerGetData(pDbPage);
  57070. pPage->pDbPage = pDbPage;
  57071. pPage->pBt = pBt;
  57072. pPage->pgno = pgno;
  57073. pPage->hdrOffset = pgno==1 ? 100 : 0;
  57074. }
  57075. assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
  57076. return pPage;
  57077. }
  57078. /*
  57079. ** Get a page from the pager. Initialize the MemPage.pBt and
  57080. ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
  57081. **
  57082. ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
  57083. ** about the content of the page at this time. So do not go to the disk
  57084. ** to fetch the content. Just fill in the content with zeros for now.
  57085. ** If in the future we call sqlite3PagerWrite() on this page, that
  57086. ** means we have started to be concerned about content and the disk
  57087. ** read should occur at that point.
  57088. */
  57089. static int btreeGetPage(
  57090. BtShared *pBt, /* The btree */
  57091. Pgno pgno, /* Number of the page to fetch */
  57092. MemPage **ppPage, /* Return the page in this parameter */
  57093. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  57094. ){
  57095. int rc;
  57096. DbPage *pDbPage;
  57097. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  57098. assert( sqlite3_mutex_held(pBt->mutex) );
  57099. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  57100. if( rc ) return rc;
  57101. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  57102. return SQLITE_OK;
  57103. }
  57104. /*
  57105. ** Retrieve a page from the pager cache. If the requested page is not
  57106. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  57107. ** MemPage.aData elements if needed.
  57108. */
  57109. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  57110. DbPage *pDbPage;
  57111. assert( sqlite3_mutex_held(pBt->mutex) );
  57112. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  57113. if( pDbPage ){
  57114. return btreePageFromDbPage(pDbPage, pgno, pBt);
  57115. }
  57116. return 0;
  57117. }
  57118. /*
  57119. ** Return the size of the database file in pages. If there is any kind of
  57120. ** error, return ((unsigned int)-1).
  57121. */
  57122. static Pgno btreePagecount(BtShared *pBt){
  57123. return pBt->nPage;
  57124. }
  57125. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  57126. assert( sqlite3BtreeHoldsMutex(p) );
  57127. assert( ((p->pBt->nPage)&0x8000000)==0 );
  57128. return btreePagecount(p->pBt);
  57129. }
  57130. /*
  57131. ** Get a page from the pager and initialize it.
  57132. **
  57133. ** If pCur!=0 then the page is being fetched as part of a moveToChild()
  57134. ** call. Do additional sanity checking on the page in this case.
  57135. ** And if the fetch fails, this routine must decrement pCur->iPage.
  57136. **
  57137. ** The page is fetched as read-write unless pCur is not NULL and is
  57138. ** a read-only cursor.
  57139. **
  57140. ** If an error occurs, then *ppPage is undefined. It
  57141. ** may remain unchanged, or it may be set to an invalid value.
  57142. */
  57143. static int getAndInitPage(
  57144. BtShared *pBt, /* The database file */
  57145. Pgno pgno, /* Number of the page to get */
  57146. MemPage **ppPage, /* Write the page pointer here */
  57147. BtCursor *pCur, /* Cursor to receive the page, or NULL */
  57148. int bReadOnly /* True for a read-only page */
  57149. ){
  57150. int rc;
  57151. DbPage *pDbPage;
  57152. assert( sqlite3_mutex_held(pBt->mutex) );
  57153. assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] );
  57154. assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
  57155. assert( pCur==0 || pCur->iPage>0 );
  57156. if( pgno>btreePagecount(pBt) ){
  57157. rc = SQLITE_CORRUPT_BKPT;
  57158. goto getAndInitPage_error;
  57159. }
  57160. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
  57161. if( rc ){
  57162. goto getAndInitPage_error;
  57163. }
  57164. *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  57165. if( (*ppPage)->isInit==0 ){
  57166. btreePageFromDbPage(pDbPage, pgno, pBt);
  57167. rc = btreeInitPage(*ppPage);
  57168. if( rc!=SQLITE_OK ){
  57169. releasePage(*ppPage);
  57170. goto getAndInitPage_error;
  57171. }
  57172. }
  57173. assert( (*ppPage)->pgno==pgno );
  57174. assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
  57175. /* If obtaining a child page for a cursor, we must verify that the page is
  57176. ** compatible with the root page. */
  57177. if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
  57178. rc = SQLITE_CORRUPT_BKPT;
  57179. releasePage(*ppPage);
  57180. goto getAndInitPage_error;
  57181. }
  57182. return SQLITE_OK;
  57183. getAndInitPage_error:
  57184. if( pCur ) pCur->iPage--;
  57185. testcase( pgno==0 );
  57186. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  57187. return rc;
  57188. }
  57189. /*
  57190. ** Release a MemPage. This should be called once for each prior
  57191. ** call to btreeGetPage.
  57192. */
  57193. static void releasePageNotNull(MemPage *pPage){
  57194. assert( pPage->aData );
  57195. assert( pPage->pBt );
  57196. assert( pPage->pDbPage!=0 );
  57197. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  57198. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  57199. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57200. sqlite3PagerUnrefNotNull(pPage->pDbPage);
  57201. }
  57202. static void releasePage(MemPage *pPage){
  57203. if( pPage ) releasePageNotNull(pPage);
  57204. }
  57205. /*
  57206. ** Get an unused page.
  57207. **
  57208. ** This works just like btreeGetPage() with the addition:
  57209. **
  57210. ** * If the page is already in use for some other purpose, immediately
  57211. ** release it and return an SQLITE_CURRUPT error.
  57212. ** * Make sure the isInit flag is clear
  57213. */
  57214. static int btreeGetUnusedPage(
  57215. BtShared *pBt, /* The btree */
  57216. Pgno pgno, /* Number of the page to fetch */
  57217. MemPage **ppPage, /* Return the page in this parameter */
  57218. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  57219. ){
  57220. int rc = btreeGetPage(pBt, pgno, ppPage, flags);
  57221. if( rc==SQLITE_OK ){
  57222. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  57223. releasePage(*ppPage);
  57224. *ppPage = 0;
  57225. return SQLITE_CORRUPT_BKPT;
  57226. }
  57227. (*ppPage)->isInit = 0;
  57228. }else{
  57229. *ppPage = 0;
  57230. }
  57231. return rc;
  57232. }
  57233. /*
  57234. ** During a rollback, when the pager reloads information into the cache
  57235. ** so that the cache is restored to its original state at the start of
  57236. ** the transaction, for each page restored this routine is called.
  57237. **
  57238. ** This routine needs to reset the extra data section at the end of the
  57239. ** page to agree with the restored data.
  57240. */
  57241. static void pageReinit(DbPage *pData){
  57242. MemPage *pPage;
  57243. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  57244. assert( sqlite3PagerPageRefcount(pData)>0 );
  57245. if( pPage->isInit ){
  57246. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  57247. pPage->isInit = 0;
  57248. if( sqlite3PagerPageRefcount(pData)>1 ){
  57249. /* pPage might not be a btree page; it might be an overflow page
  57250. ** or ptrmap page or a free page. In those cases, the following
  57251. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  57252. ** But no harm is done by this. And it is very important that
  57253. ** btreeInitPage() be called on every btree page so we make
  57254. ** the call for every page that comes in for re-initing. */
  57255. btreeInitPage(pPage);
  57256. }
  57257. }
  57258. }
  57259. /*
  57260. ** Invoke the busy handler for a btree.
  57261. */
  57262. static int btreeInvokeBusyHandler(void *pArg){
  57263. BtShared *pBt = (BtShared*)pArg;
  57264. assert( pBt->db );
  57265. assert( sqlite3_mutex_held(pBt->db->mutex) );
  57266. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  57267. }
  57268. /*
  57269. ** Open a database file.
  57270. **
  57271. ** zFilename is the name of the database file. If zFilename is NULL
  57272. ** then an ephemeral database is created. The ephemeral database might
  57273. ** be exclusively in memory, or it might use a disk-based memory cache.
  57274. ** Either way, the ephemeral database will be automatically deleted
  57275. ** when sqlite3BtreeClose() is called.
  57276. **
  57277. ** If zFilename is ":memory:" then an in-memory database is created
  57278. ** that is automatically destroyed when it is closed.
  57279. **
  57280. ** The "flags" parameter is a bitmask that might contain bits like
  57281. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  57282. **
  57283. ** If the database is already opened in the same database connection
  57284. ** and we are in shared cache mode, then the open will fail with an
  57285. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  57286. ** objects in the same database connection since doing so will lead
  57287. ** to problems with locking.
  57288. */
  57289. SQLITE_PRIVATE int sqlite3BtreeOpen(
  57290. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  57291. const char *zFilename, /* Name of the file containing the BTree database */
  57292. sqlite3 *db, /* Associated database handle */
  57293. Btree **ppBtree, /* Pointer to new Btree object written here */
  57294. int flags, /* Options */
  57295. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  57296. ){
  57297. BtShared *pBt = 0; /* Shared part of btree structure */
  57298. Btree *p; /* Handle to return */
  57299. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  57300. int rc = SQLITE_OK; /* Result code from this function */
  57301. u8 nReserve; /* Byte of unused space on each page */
  57302. unsigned char zDbHeader[100]; /* Database header content */
  57303. /* True if opening an ephemeral, temporary database */
  57304. const int isTempDb = zFilename==0 || zFilename[0]==0;
  57305. /* Set the variable isMemdb to true for an in-memory database, or
  57306. ** false for a file-based database.
  57307. */
  57308. #ifdef SQLITE_OMIT_MEMORYDB
  57309. const int isMemdb = 0;
  57310. #else
  57311. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  57312. || (isTempDb && sqlite3TempInMemory(db))
  57313. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  57314. #endif
  57315. assert( db!=0 );
  57316. assert( pVfs!=0 );
  57317. assert( sqlite3_mutex_held(db->mutex) );
  57318. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  57319. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  57320. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  57321. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  57322. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  57323. if( isMemdb ){
  57324. flags |= BTREE_MEMORY;
  57325. }
  57326. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  57327. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  57328. }
  57329. p = sqlite3MallocZero(sizeof(Btree));
  57330. if( !p ){
  57331. return SQLITE_NOMEM_BKPT;
  57332. }
  57333. p->inTrans = TRANS_NONE;
  57334. p->db = db;
  57335. #ifndef SQLITE_OMIT_SHARED_CACHE
  57336. p->lock.pBtree = p;
  57337. p->lock.iTable = 1;
  57338. #endif
  57339. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  57340. /*
  57341. ** If this Btree is a candidate for shared cache, try to find an
  57342. ** existing BtShared object that we can share with
  57343. */
  57344. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  57345. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  57346. int nFilename = sqlite3Strlen30(zFilename)+1;
  57347. int nFullPathname = pVfs->mxPathname+1;
  57348. char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
  57349. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  57350. p->sharable = 1;
  57351. if( !zFullPathname ){
  57352. sqlite3_free(p);
  57353. return SQLITE_NOMEM_BKPT;
  57354. }
  57355. if( isMemdb ){
  57356. memcpy(zFullPathname, zFilename, nFilename);
  57357. }else{
  57358. rc = sqlite3OsFullPathname(pVfs, zFilename,
  57359. nFullPathname, zFullPathname);
  57360. if( rc ){
  57361. sqlite3_free(zFullPathname);
  57362. sqlite3_free(p);
  57363. return rc;
  57364. }
  57365. }
  57366. #if SQLITE_THREADSAFE
  57367. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  57368. sqlite3_mutex_enter(mutexOpen);
  57369. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  57370. sqlite3_mutex_enter(mutexShared);
  57371. #endif
  57372. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  57373. assert( pBt->nRef>0 );
  57374. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  57375. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  57376. int iDb;
  57377. for(iDb=db->nDb-1; iDb>=0; iDb--){
  57378. Btree *pExisting = db->aDb[iDb].pBt;
  57379. if( pExisting && pExisting->pBt==pBt ){
  57380. sqlite3_mutex_leave(mutexShared);
  57381. sqlite3_mutex_leave(mutexOpen);
  57382. sqlite3_free(zFullPathname);
  57383. sqlite3_free(p);
  57384. return SQLITE_CONSTRAINT;
  57385. }
  57386. }
  57387. p->pBt = pBt;
  57388. pBt->nRef++;
  57389. break;
  57390. }
  57391. }
  57392. sqlite3_mutex_leave(mutexShared);
  57393. sqlite3_free(zFullPathname);
  57394. }
  57395. #ifdef SQLITE_DEBUG
  57396. else{
  57397. /* In debug mode, we mark all persistent databases as sharable
  57398. ** even when they are not. This exercises the locking code and
  57399. ** gives more opportunity for asserts(sqlite3_mutex_held())
  57400. ** statements to find locking problems.
  57401. */
  57402. p->sharable = 1;
  57403. }
  57404. #endif
  57405. }
  57406. #endif
  57407. if( pBt==0 ){
  57408. /*
  57409. ** The following asserts make sure that structures used by the btree are
  57410. ** the right size. This is to guard against size changes that result
  57411. ** when compiling on a different architecture.
  57412. */
  57413. assert( sizeof(i64)==8 );
  57414. assert( sizeof(u64)==8 );
  57415. assert( sizeof(u32)==4 );
  57416. assert( sizeof(u16)==2 );
  57417. assert( sizeof(Pgno)==4 );
  57418. pBt = sqlite3MallocZero( sizeof(*pBt) );
  57419. if( pBt==0 ){
  57420. rc = SQLITE_NOMEM_BKPT;
  57421. goto btree_open_out;
  57422. }
  57423. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  57424. sizeof(MemPage), flags, vfsFlags, pageReinit);
  57425. if( rc==SQLITE_OK ){
  57426. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  57427. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  57428. }
  57429. if( rc!=SQLITE_OK ){
  57430. goto btree_open_out;
  57431. }
  57432. pBt->openFlags = (u8)flags;
  57433. pBt->db = db;
  57434. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  57435. p->pBt = pBt;
  57436. pBt->pCursor = 0;
  57437. pBt->pPage1 = 0;
  57438. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  57439. #ifdef SQLITE_SECURE_DELETE
  57440. pBt->btsFlags |= BTS_SECURE_DELETE;
  57441. #endif
  57442. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  57443. ** determined by the 2-byte integer located at an offset of 16 bytes from
  57444. ** the beginning of the database file. */
  57445. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  57446. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  57447. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  57448. pBt->pageSize = 0;
  57449. #ifndef SQLITE_OMIT_AUTOVACUUM
  57450. /* If the magic name ":memory:" will create an in-memory database, then
  57451. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  57452. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  57453. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  57454. ** regular file-name. In this case the auto-vacuum applies as per normal.
  57455. */
  57456. if( zFilename && !isMemdb ){
  57457. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  57458. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  57459. }
  57460. #endif
  57461. nReserve = 0;
  57462. }else{
  57463. /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  57464. ** determined by the one-byte unsigned integer found at an offset of 20
  57465. ** into the database file header. */
  57466. nReserve = zDbHeader[20];
  57467. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  57468. #ifndef SQLITE_OMIT_AUTOVACUUM
  57469. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  57470. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  57471. #endif
  57472. }
  57473. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  57474. if( rc ) goto btree_open_out;
  57475. pBt->usableSize = pBt->pageSize - nReserve;
  57476. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  57477. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  57478. /* Add the new BtShared object to the linked list sharable BtShareds.
  57479. */
  57480. pBt->nRef = 1;
  57481. if( p->sharable ){
  57482. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  57483. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  57484. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  57485. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  57486. if( pBt->mutex==0 ){
  57487. rc = SQLITE_NOMEM_BKPT;
  57488. goto btree_open_out;
  57489. }
  57490. }
  57491. sqlite3_mutex_enter(mutexShared);
  57492. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  57493. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  57494. sqlite3_mutex_leave(mutexShared);
  57495. }
  57496. #endif
  57497. }
  57498. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  57499. /* If the new Btree uses a sharable pBtShared, then link the new
  57500. ** Btree into the list of all sharable Btrees for the same connection.
  57501. ** The list is kept in ascending order by pBt address.
  57502. */
  57503. if( p->sharable ){
  57504. int i;
  57505. Btree *pSib;
  57506. for(i=0; i<db->nDb; i++){
  57507. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  57508. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  57509. if( (uptr)p->pBt<(uptr)pSib->pBt ){
  57510. p->pNext = pSib;
  57511. p->pPrev = 0;
  57512. pSib->pPrev = p;
  57513. }else{
  57514. while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
  57515. pSib = pSib->pNext;
  57516. }
  57517. p->pNext = pSib->pNext;
  57518. p->pPrev = pSib;
  57519. if( p->pNext ){
  57520. p->pNext->pPrev = p;
  57521. }
  57522. pSib->pNext = p;
  57523. }
  57524. break;
  57525. }
  57526. }
  57527. }
  57528. #endif
  57529. *ppBtree = p;
  57530. btree_open_out:
  57531. if( rc!=SQLITE_OK ){
  57532. if( pBt && pBt->pPager ){
  57533. sqlite3PagerClose(pBt->pPager, 0);
  57534. }
  57535. sqlite3_free(pBt);
  57536. sqlite3_free(p);
  57537. *ppBtree = 0;
  57538. }else{
  57539. sqlite3_file *pFile;
  57540. /* If the B-Tree was successfully opened, set the pager-cache size to the
  57541. ** default value. Except, when opening on an existing shared pager-cache,
  57542. ** do not change the pager-cache size.
  57543. */
  57544. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  57545. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  57546. }
  57547. pFile = sqlite3PagerFile(pBt->pPager);
  57548. if( pFile->pMethods ){
  57549. sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
  57550. }
  57551. }
  57552. if( mutexOpen ){
  57553. assert( sqlite3_mutex_held(mutexOpen) );
  57554. sqlite3_mutex_leave(mutexOpen);
  57555. }
  57556. assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
  57557. return rc;
  57558. }
  57559. /*
  57560. ** Decrement the BtShared.nRef counter. When it reaches zero,
  57561. ** remove the BtShared structure from the sharing list. Return
  57562. ** true if the BtShared.nRef counter reaches zero and return
  57563. ** false if it is still positive.
  57564. */
  57565. static int removeFromSharingList(BtShared *pBt){
  57566. #ifndef SQLITE_OMIT_SHARED_CACHE
  57567. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  57568. BtShared *pList;
  57569. int removed = 0;
  57570. assert( sqlite3_mutex_notheld(pBt->mutex) );
  57571. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  57572. sqlite3_mutex_enter(pMaster);
  57573. pBt->nRef--;
  57574. if( pBt->nRef<=0 ){
  57575. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  57576. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  57577. }else{
  57578. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  57579. while( ALWAYS(pList) && pList->pNext!=pBt ){
  57580. pList=pList->pNext;
  57581. }
  57582. if( ALWAYS(pList) ){
  57583. pList->pNext = pBt->pNext;
  57584. }
  57585. }
  57586. if( SQLITE_THREADSAFE ){
  57587. sqlite3_mutex_free(pBt->mutex);
  57588. }
  57589. removed = 1;
  57590. }
  57591. sqlite3_mutex_leave(pMaster);
  57592. return removed;
  57593. #else
  57594. return 1;
  57595. #endif
  57596. }
  57597. /*
  57598. ** Make sure pBt->pTmpSpace points to an allocation of
  57599. ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
  57600. ** pointer.
  57601. */
  57602. static void allocateTempSpace(BtShared *pBt){
  57603. if( !pBt->pTmpSpace ){
  57604. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  57605. /* One of the uses of pBt->pTmpSpace is to format cells before
  57606. ** inserting them into a leaf page (function fillInCell()). If
  57607. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  57608. ** by the various routines that manipulate binary cells. Which
  57609. ** can mean that fillInCell() only initializes the first 2 or 3
  57610. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  57611. ** it into a database page. This is not actually a problem, but it
  57612. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  57613. ** data is passed to system call write(). So to avoid this error,
  57614. ** zero the first 4 bytes of temp space here.
  57615. **
  57616. ** Also: Provide four bytes of initialized space before the
  57617. ** beginning of pTmpSpace as an area available to prepend the
  57618. ** left-child pointer to the beginning of a cell.
  57619. */
  57620. if( pBt->pTmpSpace ){
  57621. memset(pBt->pTmpSpace, 0, 8);
  57622. pBt->pTmpSpace += 4;
  57623. }
  57624. }
  57625. }
  57626. /*
  57627. ** Free the pBt->pTmpSpace allocation
  57628. */
  57629. static void freeTempSpace(BtShared *pBt){
  57630. if( pBt->pTmpSpace ){
  57631. pBt->pTmpSpace -= 4;
  57632. sqlite3PageFree(pBt->pTmpSpace);
  57633. pBt->pTmpSpace = 0;
  57634. }
  57635. }
  57636. /*
  57637. ** Close an open database and invalidate all cursors.
  57638. */
  57639. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  57640. BtShared *pBt = p->pBt;
  57641. BtCursor *pCur;
  57642. /* Close all cursors opened via this handle. */
  57643. assert( sqlite3_mutex_held(p->db->mutex) );
  57644. sqlite3BtreeEnter(p);
  57645. pCur = pBt->pCursor;
  57646. while( pCur ){
  57647. BtCursor *pTmp = pCur;
  57648. pCur = pCur->pNext;
  57649. if( pTmp->pBtree==p ){
  57650. sqlite3BtreeCloseCursor(pTmp);
  57651. }
  57652. }
  57653. /* Rollback any active transaction and free the handle structure.
  57654. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  57655. ** this handle.
  57656. */
  57657. sqlite3BtreeRollback(p, SQLITE_OK, 0);
  57658. sqlite3BtreeLeave(p);
  57659. /* If there are still other outstanding references to the shared-btree
  57660. ** structure, return now. The remainder of this procedure cleans
  57661. ** up the shared-btree.
  57662. */
  57663. assert( p->wantToLock==0 && p->locked==0 );
  57664. if( !p->sharable || removeFromSharingList(pBt) ){
  57665. /* The pBt is no longer on the sharing list, so we can access
  57666. ** it without having to hold the mutex.
  57667. **
  57668. ** Clean out and delete the BtShared object.
  57669. */
  57670. assert( !pBt->pCursor );
  57671. sqlite3PagerClose(pBt->pPager, p->db);
  57672. if( pBt->xFreeSchema && pBt->pSchema ){
  57673. pBt->xFreeSchema(pBt->pSchema);
  57674. }
  57675. sqlite3DbFree(0, pBt->pSchema);
  57676. freeTempSpace(pBt);
  57677. sqlite3_free(pBt);
  57678. }
  57679. #ifndef SQLITE_OMIT_SHARED_CACHE
  57680. assert( p->wantToLock==0 );
  57681. assert( p->locked==0 );
  57682. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  57683. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  57684. #endif
  57685. sqlite3_free(p);
  57686. return SQLITE_OK;
  57687. }
  57688. /*
  57689. ** Change the "soft" limit on the number of pages in the cache.
  57690. ** Unused and unmodified pages will be recycled when the number of
  57691. ** pages in the cache exceeds this soft limit. But the size of the
  57692. ** cache is allowed to grow larger than this limit if it contains
  57693. ** dirty pages or pages still in active use.
  57694. */
  57695. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  57696. BtShared *pBt = p->pBt;
  57697. assert( sqlite3_mutex_held(p->db->mutex) );
  57698. sqlite3BtreeEnter(p);
  57699. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  57700. sqlite3BtreeLeave(p);
  57701. return SQLITE_OK;
  57702. }
  57703. /*
  57704. ** Change the "spill" limit on the number of pages in the cache.
  57705. ** If the number of pages exceeds this limit during a write transaction,
  57706. ** the pager might attempt to "spill" pages to the journal early in
  57707. ** order to free up memory.
  57708. **
  57709. ** The value returned is the current spill size. If zero is passed
  57710. ** as an argument, no changes are made to the spill size setting, so
  57711. ** using mxPage of 0 is a way to query the current spill size.
  57712. */
  57713. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
  57714. BtShared *pBt = p->pBt;
  57715. int res;
  57716. assert( sqlite3_mutex_held(p->db->mutex) );
  57717. sqlite3BtreeEnter(p);
  57718. res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
  57719. sqlite3BtreeLeave(p);
  57720. return res;
  57721. }
  57722. #if SQLITE_MAX_MMAP_SIZE>0
  57723. /*
  57724. ** Change the limit on the amount of the database file that may be
  57725. ** memory mapped.
  57726. */
  57727. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  57728. BtShared *pBt = p->pBt;
  57729. assert( sqlite3_mutex_held(p->db->mutex) );
  57730. sqlite3BtreeEnter(p);
  57731. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  57732. sqlite3BtreeLeave(p);
  57733. return SQLITE_OK;
  57734. }
  57735. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  57736. /*
  57737. ** Change the way data is synced to disk in order to increase or decrease
  57738. ** how well the database resists damage due to OS crashes and power
  57739. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  57740. ** there is a high probability of damage) Level 2 is the default. There
  57741. ** is a very low but non-zero probability of damage. Level 3 reduces the
  57742. ** probability of damage to near zero but with a write performance reduction.
  57743. */
  57744. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  57745. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  57746. Btree *p, /* The btree to set the safety level on */
  57747. unsigned pgFlags /* Various PAGER_* flags */
  57748. ){
  57749. BtShared *pBt = p->pBt;
  57750. assert( sqlite3_mutex_held(p->db->mutex) );
  57751. sqlite3BtreeEnter(p);
  57752. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  57753. sqlite3BtreeLeave(p);
  57754. return SQLITE_OK;
  57755. }
  57756. #endif
  57757. /*
  57758. ** Change the default pages size and the number of reserved bytes per page.
  57759. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  57760. ** without changing anything.
  57761. **
  57762. ** The page size must be a power of 2 between 512 and 65536. If the page
  57763. ** size supplied does not meet this constraint then the page size is not
  57764. ** changed.
  57765. **
  57766. ** Page sizes are constrained to be a power of two so that the region
  57767. ** of the database file used for locking (beginning at PENDING_BYTE,
  57768. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  57769. ** at the beginning of a page.
  57770. **
  57771. ** If parameter nReserve is less than zero, then the number of reserved
  57772. ** bytes per page is left unchanged.
  57773. **
  57774. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  57775. ** and autovacuum mode can no longer be changed.
  57776. */
  57777. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  57778. int rc = SQLITE_OK;
  57779. BtShared *pBt = p->pBt;
  57780. assert( nReserve>=-1 && nReserve<=255 );
  57781. sqlite3BtreeEnter(p);
  57782. #if SQLITE_HAS_CODEC
  57783. if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
  57784. #endif
  57785. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  57786. sqlite3BtreeLeave(p);
  57787. return SQLITE_READONLY;
  57788. }
  57789. if( nReserve<0 ){
  57790. nReserve = pBt->pageSize - pBt->usableSize;
  57791. }
  57792. assert( nReserve>=0 && nReserve<=255 );
  57793. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  57794. ((pageSize-1)&pageSize)==0 ){
  57795. assert( (pageSize & 7)==0 );
  57796. assert( !pBt->pCursor );
  57797. pBt->pageSize = (u32)pageSize;
  57798. freeTempSpace(pBt);
  57799. }
  57800. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  57801. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  57802. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  57803. sqlite3BtreeLeave(p);
  57804. return rc;
  57805. }
  57806. /*
  57807. ** Return the currently defined page size
  57808. */
  57809. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  57810. return p->pBt->pageSize;
  57811. }
  57812. /*
  57813. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  57814. ** may only be called if it is guaranteed that the b-tree mutex is already
  57815. ** held.
  57816. **
  57817. ** This is useful in one special case in the backup API code where it is
  57818. ** known that the shared b-tree mutex is held, but the mutex on the
  57819. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  57820. ** were to be called, it might collide with some other operation on the
  57821. ** database handle that owns *p, causing undefined behavior.
  57822. */
  57823. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  57824. int n;
  57825. assert( sqlite3_mutex_held(p->pBt->mutex) );
  57826. n = p->pBt->pageSize - p->pBt->usableSize;
  57827. return n;
  57828. }
  57829. /*
  57830. ** Return the number of bytes of space at the end of every page that
  57831. ** are intentually left unused. This is the "reserved" space that is
  57832. ** sometimes used by extensions.
  57833. **
  57834. ** If SQLITE_HAS_MUTEX is defined then the number returned is the
  57835. ** greater of the current reserved space and the maximum requested
  57836. ** reserve space.
  57837. */
  57838. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
  57839. int n;
  57840. sqlite3BtreeEnter(p);
  57841. n = sqlite3BtreeGetReserveNoMutex(p);
  57842. #ifdef SQLITE_HAS_CODEC
  57843. if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
  57844. #endif
  57845. sqlite3BtreeLeave(p);
  57846. return n;
  57847. }
  57848. /*
  57849. ** Set the maximum page count for a database if mxPage is positive.
  57850. ** No changes are made if mxPage is 0 or negative.
  57851. ** Regardless of the value of mxPage, return the maximum page count.
  57852. */
  57853. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  57854. int n;
  57855. sqlite3BtreeEnter(p);
  57856. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  57857. sqlite3BtreeLeave(p);
  57858. return n;
  57859. }
  57860. /*
  57861. ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
  57862. ** then make no changes. Always return the value of the BTS_SECURE_DELETE
  57863. ** setting after the change.
  57864. */
  57865. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  57866. int b;
  57867. if( p==0 ) return 0;
  57868. sqlite3BtreeEnter(p);
  57869. if( newFlag>=0 ){
  57870. p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
  57871. if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
  57872. }
  57873. b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
  57874. sqlite3BtreeLeave(p);
  57875. return b;
  57876. }
  57877. /*
  57878. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  57879. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  57880. ** is disabled. The default value for the auto-vacuum property is
  57881. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  57882. */
  57883. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  57884. #ifdef SQLITE_OMIT_AUTOVACUUM
  57885. return SQLITE_READONLY;
  57886. #else
  57887. BtShared *pBt = p->pBt;
  57888. int rc = SQLITE_OK;
  57889. u8 av = (u8)autoVacuum;
  57890. sqlite3BtreeEnter(p);
  57891. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  57892. rc = SQLITE_READONLY;
  57893. }else{
  57894. pBt->autoVacuum = av ?1:0;
  57895. pBt->incrVacuum = av==2 ?1:0;
  57896. }
  57897. sqlite3BtreeLeave(p);
  57898. return rc;
  57899. #endif
  57900. }
  57901. /*
  57902. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  57903. ** enabled 1 is returned. Otherwise 0.
  57904. */
  57905. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  57906. #ifdef SQLITE_OMIT_AUTOVACUUM
  57907. return BTREE_AUTOVACUUM_NONE;
  57908. #else
  57909. int rc;
  57910. sqlite3BtreeEnter(p);
  57911. rc = (
  57912. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  57913. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  57914. BTREE_AUTOVACUUM_INCR
  57915. );
  57916. sqlite3BtreeLeave(p);
  57917. return rc;
  57918. #endif
  57919. }
  57920. /*
  57921. ** If the user has not set the safety-level for this database connection
  57922. ** using "PRAGMA synchronous", and if the safety-level is not already
  57923. ** set to the value passed to this function as the second parameter,
  57924. ** set it so.
  57925. */
  57926. #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS
  57927. static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
  57928. sqlite3 *db;
  57929. Db *pDb;
  57930. if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
  57931. while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
  57932. if( pDb->bSyncSet==0
  57933. && pDb->safety_level!=safety_level
  57934. && pDb!=&db->aDb[1]
  57935. ){
  57936. pDb->safety_level = safety_level;
  57937. sqlite3PagerSetFlags(pBt->pPager,
  57938. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
  57939. }
  57940. }
  57941. }
  57942. #else
  57943. # define setDefaultSyncFlag(pBt,safety_level)
  57944. #endif
  57945. /*
  57946. ** Get a reference to pPage1 of the database file. This will
  57947. ** also acquire a readlock on that file.
  57948. **
  57949. ** SQLITE_OK is returned on success. If the file is not a
  57950. ** well-formed database file, then SQLITE_CORRUPT is returned.
  57951. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  57952. ** is returned if we run out of memory.
  57953. */
  57954. static int lockBtree(BtShared *pBt){
  57955. int rc; /* Result code from subfunctions */
  57956. MemPage *pPage1; /* Page 1 of the database file */
  57957. int nPage; /* Number of pages in the database */
  57958. int nPageFile = 0; /* Number of pages in the database file */
  57959. int nPageHeader; /* Number of pages in the database according to hdr */
  57960. assert( sqlite3_mutex_held(pBt->mutex) );
  57961. assert( pBt->pPage1==0 );
  57962. rc = sqlite3PagerSharedLock(pBt->pPager);
  57963. if( rc!=SQLITE_OK ) return rc;
  57964. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  57965. if( rc!=SQLITE_OK ) return rc;
  57966. /* Do some checking to help insure the file we opened really is
  57967. ** a valid database file.
  57968. */
  57969. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  57970. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  57971. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  57972. nPage = nPageFile;
  57973. }
  57974. if( nPage>0 ){
  57975. u32 pageSize;
  57976. u32 usableSize;
  57977. u8 *page1 = pPage1->aData;
  57978. rc = SQLITE_NOTADB;
  57979. /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
  57980. ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
  57981. ** 61 74 20 33 00. */
  57982. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  57983. goto page1_init_failed;
  57984. }
  57985. #ifdef SQLITE_OMIT_WAL
  57986. if( page1[18]>1 ){
  57987. pBt->btsFlags |= BTS_READ_ONLY;
  57988. }
  57989. if( page1[19]>1 ){
  57990. goto page1_init_failed;
  57991. }
  57992. #else
  57993. if( page1[18]>2 ){
  57994. pBt->btsFlags |= BTS_READ_ONLY;
  57995. }
  57996. if( page1[19]>2 ){
  57997. goto page1_init_failed;
  57998. }
  57999. /* If the write version is set to 2, this database should be accessed
  58000. ** in WAL mode. If the log is not already open, open it now. Then
  58001. ** return SQLITE_OK and return without populating BtShared.pPage1.
  58002. ** The caller detects this and calls this function again. This is
  58003. ** required as the version of page 1 currently in the page1 buffer
  58004. ** may not be the latest version - there may be a newer one in the log
  58005. ** file.
  58006. */
  58007. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  58008. int isOpen = 0;
  58009. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  58010. if( rc!=SQLITE_OK ){
  58011. goto page1_init_failed;
  58012. }else{
  58013. setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
  58014. if( isOpen==0 ){
  58015. releasePage(pPage1);
  58016. return SQLITE_OK;
  58017. }
  58018. }
  58019. rc = SQLITE_NOTADB;
  58020. }else{
  58021. setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
  58022. }
  58023. #endif
  58024. /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
  58025. ** fractions and the leaf payload fraction values must be 64, 32, and 32.
  58026. **
  58027. ** The original design allowed these amounts to vary, but as of
  58028. ** version 3.6.0, we require them to be fixed.
  58029. */
  58030. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  58031. goto page1_init_failed;
  58032. }
  58033. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  58034. ** determined by the 2-byte integer located at an offset of 16 bytes from
  58035. ** the beginning of the database file. */
  58036. pageSize = (page1[16]<<8) | (page1[17]<<16);
  58037. /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
  58038. ** between 512 and 65536 inclusive. */
  58039. if( ((pageSize-1)&pageSize)!=0
  58040. || pageSize>SQLITE_MAX_PAGE_SIZE
  58041. || pageSize<=256
  58042. ){
  58043. goto page1_init_failed;
  58044. }
  58045. assert( (pageSize & 7)==0 );
  58046. /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
  58047. ** integer at offset 20 is the number of bytes of space at the end of
  58048. ** each page to reserve for extensions.
  58049. **
  58050. ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  58051. ** determined by the one-byte unsigned integer found at an offset of 20
  58052. ** into the database file header. */
  58053. usableSize = pageSize - page1[20];
  58054. if( (u32)pageSize!=pBt->pageSize ){
  58055. /* After reading the first page of the database assuming a page size
  58056. ** of BtShared.pageSize, we have discovered that the page-size is
  58057. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  58058. ** zero and return SQLITE_OK. The caller will call this function
  58059. ** again with the correct page-size.
  58060. */
  58061. releasePage(pPage1);
  58062. pBt->usableSize = usableSize;
  58063. pBt->pageSize = pageSize;
  58064. freeTempSpace(pBt);
  58065. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  58066. pageSize-usableSize);
  58067. return rc;
  58068. }
  58069. if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
  58070. rc = SQLITE_CORRUPT_BKPT;
  58071. goto page1_init_failed;
  58072. }
  58073. /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
  58074. ** be less than 480. In other words, if the page size is 512, then the
  58075. ** reserved space size cannot exceed 32. */
  58076. if( usableSize<480 ){
  58077. goto page1_init_failed;
  58078. }
  58079. pBt->pageSize = pageSize;
  58080. pBt->usableSize = usableSize;
  58081. #ifndef SQLITE_OMIT_AUTOVACUUM
  58082. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  58083. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  58084. #endif
  58085. }
  58086. /* maxLocal is the maximum amount of payload to store locally for
  58087. ** a cell. Make sure it is small enough so that at least minFanout
  58088. ** cells can will fit on one page. We assume a 10-byte page header.
  58089. ** Besides the payload, the cell must store:
  58090. ** 2-byte pointer to the cell
  58091. ** 4-byte child pointer
  58092. ** 9-byte nKey value
  58093. ** 4-byte nData value
  58094. ** 4-byte overflow page pointer
  58095. ** So a cell consists of a 2-byte pointer, a header which is as much as
  58096. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  58097. ** page pointer.
  58098. */
  58099. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  58100. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  58101. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  58102. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  58103. if( pBt->maxLocal>127 ){
  58104. pBt->max1bytePayload = 127;
  58105. }else{
  58106. pBt->max1bytePayload = (u8)pBt->maxLocal;
  58107. }
  58108. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  58109. pBt->pPage1 = pPage1;
  58110. pBt->nPage = nPage;
  58111. return SQLITE_OK;
  58112. page1_init_failed:
  58113. releasePage(pPage1);
  58114. pBt->pPage1 = 0;
  58115. return rc;
  58116. }
  58117. #ifndef NDEBUG
  58118. /*
  58119. ** Return the number of cursors open on pBt. This is for use
  58120. ** in assert() expressions, so it is only compiled if NDEBUG is not
  58121. ** defined.
  58122. **
  58123. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  58124. ** false then all cursors are counted.
  58125. **
  58126. ** For the purposes of this routine, a cursor is any cursor that
  58127. ** is capable of reading or writing to the database. Cursors that
  58128. ** have been tripped into the CURSOR_FAULT state are not counted.
  58129. */
  58130. static int countValidCursors(BtShared *pBt, int wrOnly){
  58131. BtCursor *pCur;
  58132. int r = 0;
  58133. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  58134. if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
  58135. && pCur->eState!=CURSOR_FAULT ) r++;
  58136. }
  58137. return r;
  58138. }
  58139. #endif
  58140. /*
  58141. ** If there are no outstanding cursors and we are not in the middle
  58142. ** of a transaction but there is a read lock on the database, then
  58143. ** this routine unrefs the first page of the database file which
  58144. ** has the effect of releasing the read lock.
  58145. **
  58146. ** If there is a transaction in progress, this routine is a no-op.
  58147. */
  58148. static void unlockBtreeIfUnused(BtShared *pBt){
  58149. assert( sqlite3_mutex_held(pBt->mutex) );
  58150. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  58151. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  58152. MemPage *pPage1 = pBt->pPage1;
  58153. assert( pPage1->aData );
  58154. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  58155. pBt->pPage1 = 0;
  58156. releasePageNotNull(pPage1);
  58157. }
  58158. }
  58159. /*
  58160. ** If pBt points to an empty file then convert that empty file
  58161. ** into a new empty database by initializing the first page of
  58162. ** the database.
  58163. */
  58164. static int newDatabase(BtShared *pBt){
  58165. MemPage *pP1;
  58166. unsigned char *data;
  58167. int rc;
  58168. assert( sqlite3_mutex_held(pBt->mutex) );
  58169. if( pBt->nPage>0 ){
  58170. return SQLITE_OK;
  58171. }
  58172. pP1 = pBt->pPage1;
  58173. assert( pP1!=0 );
  58174. data = pP1->aData;
  58175. rc = sqlite3PagerWrite(pP1->pDbPage);
  58176. if( rc ) return rc;
  58177. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  58178. assert( sizeof(zMagicHeader)==16 );
  58179. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  58180. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  58181. data[18] = 1;
  58182. data[19] = 1;
  58183. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  58184. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  58185. data[21] = 64;
  58186. data[22] = 32;
  58187. data[23] = 32;
  58188. memset(&data[24], 0, 100-24);
  58189. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  58190. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  58191. #ifndef SQLITE_OMIT_AUTOVACUUM
  58192. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  58193. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  58194. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  58195. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  58196. #endif
  58197. pBt->nPage = 1;
  58198. data[31] = 1;
  58199. return SQLITE_OK;
  58200. }
  58201. /*
  58202. ** Initialize the first page of the database file (creating a database
  58203. ** consisting of a single page and no schema objects). Return SQLITE_OK
  58204. ** if successful, or an SQLite error code otherwise.
  58205. */
  58206. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  58207. int rc;
  58208. sqlite3BtreeEnter(p);
  58209. p->pBt->nPage = 0;
  58210. rc = newDatabase(p->pBt);
  58211. sqlite3BtreeLeave(p);
  58212. return rc;
  58213. }
  58214. /*
  58215. ** Attempt to start a new transaction. A write-transaction
  58216. ** is started if the second argument is nonzero, otherwise a read-
  58217. ** transaction. If the second argument is 2 or more and exclusive
  58218. ** transaction is started, meaning that no other process is allowed
  58219. ** to access the database. A preexisting transaction may not be
  58220. ** upgraded to exclusive by calling this routine a second time - the
  58221. ** exclusivity flag only works for a new transaction.
  58222. **
  58223. ** A write-transaction must be started before attempting any
  58224. ** changes to the database. None of the following routines
  58225. ** will work unless a transaction is started first:
  58226. **
  58227. ** sqlite3BtreeCreateTable()
  58228. ** sqlite3BtreeCreateIndex()
  58229. ** sqlite3BtreeClearTable()
  58230. ** sqlite3BtreeDropTable()
  58231. ** sqlite3BtreeInsert()
  58232. ** sqlite3BtreeDelete()
  58233. ** sqlite3BtreeUpdateMeta()
  58234. **
  58235. ** If an initial attempt to acquire the lock fails because of lock contention
  58236. ** and the database was previously unlocked, then invoke the busy handler
  58237. ** if there is one. But if there was previously a read-lock, do not
  58238. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  58239. ** returned when there is already a read-lock in order to avoid a deadlock.
  58240. **
  58241. ** Suppose there are two processes A and B. A has a read lock and B has
  58242. ** a reserved lock. B tries to promote to exclusive but is blocked because
  58243. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  58244. ** One or the other of the two processes must give way or there can be
  58245. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  58246. ** when A already has a read lock, we encourage A to give up and let B
  58247. ** proceed.
  58248. */
  58249. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  58250. BtShared *pBt = p->pBt;
  58251. int rc = SQLITE_OK;
  58252. sqlite3BtreeEnter(p);
  58253. btreeIntegrity(p);
  58254. /* If the btree is already in a write-transaction, or it
  58255. ** is already in a read-transaction and a read-transaction
  58256. ** is requested, this is a no-op.
  58257. */
  58258. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  58259. goto trans_begun;
  58260. }
  58261. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  58262. /* Write transactions are not possible on a read-only database */
  58263. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  58264. rc = SQLITE_READONLY;
  58265. goto trans_begun;
  58266. }
  58267. #ifndef SQLITE_OMIT_SHARED_CACHE
  58268. {
  58269. sqlite3 *pBlock = 0;
  58270. /* If another database handle has already opened a write transaction
  58271. ** on this shared-btree structure and a second write transaction is
  58272. ** requested, return SQLITE_LOCKED.
  58273. */
  58274. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  58275. || (pBt->btsFlags & BTS_PENDING)!=0
  58276. ){
  58277. pBlock = pBt->pWriter->db;
  58278. }else if( wrflag>1 ){
  58279. BtLock *pIter;
  58280. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  58281. if( pIter->pBtree!=p ){
  58282. pBlock = pIter->pBtree->db;
  58283. break;
  58284. }
  58285. }
  58286. }
  58287. if( pBlock ){
  58288. sqlite3ConnectionBlocked(p->db, pBlock);
  58289. rc = SQLITE_LOCKED_SHAREDCACHE;
  58290. goto trans_begun;
  58291. }
  58292. }
  58293. #endif
  58294. /* Any read-only or read-write transaction implies a read-lock on
  58295. ** page 1. So if some other shared-cache client already has a write-lock
  58296. ** on page 1, the transaction cannot be opened. */
  58297. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  58298. if( SQLITE_OK!=rc ) goto trans_begun;
  58299. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  58300. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  58301. do {
  58302. /* Call lockBtree() until either pBt->pPage1 is populated or
  58303. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  58304. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  58305. ** reading page 1 it discovers that the page-size of the database
  58306. ** file is not pBt->pageSize. In this case lockBtree() will update
  58307. ** pBt->pageSize to the page-size of the file on disk.
  58308. */
  58309. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  58310. if( rc==SQLITE_OK && wrflag ){
  58311. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  58312. rc = SQLITE_READONLY;
  58313. }else{
  58314. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  58315. if( rc==SQLITE_OK ){
  58316. rc = newDatabase(pBt);
  58317. }
  58318. }
  58319. }
  58320. if( rc!=SQLITE_OK ){
  58321. unlockBtreeIfUnused(pBt);
  58322. }
  58323. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  58324. btreeInvokeBusyHandler(pBt) );
  58325. if( rc==SQLITE_OK ){
  58326. if( p->inTrans==TRANS_NONE ){
  58327. pBt->nTransaction++;
  58328. #ifndef SQLITE_OMIT_SHARED_CACHE
  58329. if( p->sharable ){
  58330. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  58331. p->lock.eLock = READ_LOCK;
  58332. p->lock.pNext = pBt->pLock;
  58333. pBt->pLock = &p->lock;
  58334. }
  58335. #endif
  58336. }
  58337. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  58338. if( p->inTrans>pBt->inTransaction ){
  58339. pBt->inTransaction = p->inTrans;
  58340. }
  58341. if( wrflag ){
  58342. MemPage *pPage1 = pBt->pPage1;
  58343. #ifndef SQLITE_OMIT_SHARED_CACHE
  58344. assert( !pBt->pWriter );
  58345. pBt->pWriter = p;
  58346. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  58347. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  58348. #endif
  58349. /* If the db-size header field is incorrect (as it may be if an old
  58350. ** client has been writing the database file), update it now. Doing
  58351. ** this sooner rather than later means the database size can safely
  58352. ** re-read the database size from page 1 if a savepoint or transaction
  58353. ** rollback occurs within the transaction.
  58354. */
  58355. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  58356. rc = sqlite3PagerWrite(pPage1->pDbPage);
  58357. if( rc==SQLITE_OK ){
  58358. put4byte(&pPage1->aData[28], pBt->nPage);
  58359. }
  58360. }
  58361. }
  58362. }
  58363. trans_begun:
  58364. if( rc==SQLITE_OK && wrflag ){
  58365. /* This call makes sure that the pager has the correct number of
  58366. ** open savepoints. If the second parameter is greater than 0 and
  58367. ** the sub-journal is not already open, then it will be opened here.
  58368. */
  58369. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  58370. }
  58371. btreeIntegrity(p);
  58372. sqlite3BtreeLeave(p);
  58373. return rc;
  58374. }
  58375. #ifndef SQLITE_OMIT_AUTOVACUUM
  58376. /*
  58377. ** Set the pointer-map entries for all children of page pPage. Also, if
  58378. ** pPage contains cells that point to overflow pages, set the pointer
  58379. ** map entries for the overflow pages as well.
  58380. */
  58381. static int setChildPtrmaps(MemPage *pPage){
  58382. int i; /* Counter variable */
  58383. int nCell; /* Number of cells in page pPage */
  58384. int rc; /* Return code */
  58385. BtShared *pBt = pPage->pBt;
  58386. Pgno pgno = pPage->pgno;
  58387. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  58388. rc = btreeInitPage(pPage);
  58389. if( rc!=SQLITE_OK ) return rc;
  58390. nCell = pPage->nCell;
  58391. for(i=0; i<nCell; i++){
  58392. u8 *pCell = findCell(pPage, i);
  58393. ptrmapPutOvflPtr(pPage, pCell, &rc);
  58394. if( !pPage->leaf ){
  58395. Pgno childPgno = get4byte(pCell);
  58396. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  58397. }
  58398. }
  58399. if( !pPage->leaf ){
  58400. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  58401. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  58402. }
  58403. return rc;
  58404. }
  58405. /*
  58406. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  58407. ** that it points to iTo. Parameter eType describes the type of pointer to
  58408. ** be modified, as follows:
  58409. **
  58410. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  58411. ** page of pPage.
  58412. **
  58413. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  58414. ** page pointed to by one of the cells on pPage.
  58415. **
  58416. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  58417. ** overflow page in the list.
  58418. */
  58419. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  58420. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  58421. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  58422. if( eType==PTRMAP_OVERFLOW2 ){
  58423. /* The pointer is always the first 4 bytes of the page in this case. */
  58424. if( get4byte(pPage->aData)!=iFrom ){
  58425. return SQLITE_CORRUPT_BKPT;
  58426. }
  58427. put4byte(pPage->aData, iTo);
  58428. }else{
  58429. int i;
  58430. int nCell;
  58431. int rc;
  58432. rc = btreeInitPage(pPage);
  58433. if( rc ) return rc;
  58434. nCell = pPage->nCell;
  58435. for(i=0; i<nCell; i++){
  58436. u8 *pCell = findCell(pPage, i);
  58437. if( eType==PTRMAP_OVERFLOW1 ){
  58438. CellInfo info;
  58439. pPage->xParseCell(pPage, pCell, &info);
  58440. if( info.nLocal<info.nPayload ){
  58441. if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
  58442. return SQLITE_CORRUPT_BKPT;
  58443. }
  58444. if( iFrom==get4byte(pCell+info.nSize-4) ){
  58445. put4byte(pCell+info.nSize-4, iTo);
  58446. break;
  58447. }
  58448. }
  58449. }else{
  58450. if( get4byte(pCell)==iFrom ){
  58451. put4byte(pCell, iTo);
  58452. break;
  58453. }
  58454. }
  58455. }
  58456. if( i==nCell ){
  58457. if( eType!=PTRMAP_BTREE ||
  58458. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  58459. return SQLITE_CORRUPT_BKPT;
  58460. }
  58461. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  58462. }
  58463. }
  58464. return SQLITE_OK;
  58465. }
  58466. /*
  58467. ** Move the open database page pDbPage to location iFreePage in the
  58468. ** database. The pDbPage reference remains valid.
  58469. **
  58470. ** The isCommit flag indicates that there is no need to remember that
  58471. ** the journal needs to be sync()ed before database page pDbPage->pgno
  58472. ** can be written to. The caller has already promised not to write to that
  58473. ** page.
  58474. */
  58475. static int relocatePage(
  58476. BtShared *pBt, /* Btree */
  58477. MemPage *pDbPage, /* Open page to move */
  58478. u8 eType, /* Pointer map 'type' entry for pDbPage */
  58479. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  58480. Pgno iFreePage, /* The location to move pDbPage to */
  58481. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  58482. ){
  58483. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  58484. Pgno iDbPage = pDbPage->pgno;
  58485. Pager *pPager = pBt->pPager;
  58486. int rc;
  58487. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  58488. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  58489. assert( sqlite3_mutex_held(pBt->mutex) );
  58490. assert( pDbPage->pBt==pBt );
  58491. /* Move page iDbPage from its current location to page number iFreePage */
  58492. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  58493. iDbPage, iFreePage, iPtrPage, eType));
  58494. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  58495. if( rc!=SQLITE_OK ){
  58496. return rc;
  58497. }
  58498. pDbPage->pgno = iFreePage;
  58499. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  58500. ** that point to overflow pages. The pointer map entries for all these
  58501. ** pages need to be changed.
  58502. **
  58503. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  58504. ** pointer to a subsequent overflow page. If this is the case, then
  58505. ** the pointer map needs to be updated for the subsequent overflow page.
  58506. */
  58507. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  58508. rc = setChildPtrmaps(pDbPage);
  58509. if( rc!=SQLITE_OK ){
  58510. return rc;
  58511. }
  58512. }else{
  58513. Pgno nextOvfl = get4byte(pDbPage->aData);
  58514. if( nextOvfl!=0 ){
  58515. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  58516. if( rc!=SQLITE_OK ){
  58517. return rc;
  58518. }
  58519. }
  58520. }
  58521. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  58522. ** that it points at iFreePage. Also fix the pointer map entry for
  58523. ** iPtrPage.
  58524. */
  58525. if( eType!=PTRMAP_ROOTPAGE ){
  58526. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  58527. if( rc!=SQLITE_OK ){
  58528. return rc;
  58529. }
  58530. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  58531. if( rc!=SQLITE_OK ){
  58532. releasePage(pPtrPage);
  58533. return rc;
  58534. }
  58535. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  58536. releasePage(pPtrPage);
  58537. if( rc==SQLITE_OK ){
  58538. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  58539. }
  58540. }
  58541. return rc;
  58542. }
  58543. /* Forward declaration required by incrVacuumStep(). */
  58544. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  58545. /*
  58546. ** Perform a single step of an incremental-vacuum. If successful, return
  58547. ** SQLITE_OK. If there is no work to do (and therefore no point in
  58548. ** calling this function again), return SQLITE_DONE. Or, if an error
  58549. ** occurs, return some other error code.
  58550. **
  58551. ** More specifically, this function attempts to re-organize the database so
  58552. ** that the last page of the file currently in use is no longer in use.
  58553. **
  58554. ** Parameter nFin is the number of pages that this database would contain
  58555. ** were this function called until it returns SQLITE_DONE.
  58556. **
  58557. ** If the bCommit parameter is non-zero, this function assumes that the
  58558. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  58559. ** or an error. bCommit is passed true for an auto-vacuum-on-commit
  58560. ** operation, or false for an incremental vacuum.
  58561. */
  58562. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  58563. Pgno nFreeList; /* Number of pages still on the free-list */
  58564. int rc;
  58565. assert( sqlite3_mutex_held(pBt->mutex) );
  58566. assert( iLastPg>nFin );
  58567. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  58568. u8 eType;
  58569. Pgno iPtrPage;
  58570. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  58571. if( nFreeList==0 ){
  58572. return SQLITE_DONE;
  58573. }
  58574. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  58575. if( rc!=SQLITE_OK ){
  58576. return rc;
  58577. }
  58578. if( eType==PTRMAP_ROOTPAGE ){
  58579. return SQLITE_CORRUPT_BKPT;
  58580. }
  58581. if( eType==PTRMAP_FREEPAGE ){
  58582. if( bCommit==0 ){
  58583. /* Remove the page from the files free-list. This is not required
  58584. ** if bCommit is non-zero. In that case, the free-list will be
  58585. ** truncated to zero after this function returns, so it doesn't
  58586. ** matter if it still contains some garbage entries.
  58587. */
  58588. Pgno iFreePg;
  58589. MemPage *pFreePg;
  58590. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  58591. if( rc!=SQLITE_OK ){
  58592. return rc;
  58593. }
  58594. assert( iFreePg==iLastPg );
  58595. releasePage(pFreePg);
  58596. }
  58597. } else {
  58598. Pgno iFreePg; /* Index of free page to move pLastPg to */
  58599. MemPage *pLastPg;
  58600. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  58601. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  58602. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  58603. if( rc!=SQLITE_OK ){
  58604. return rc;
  58605. }
  58606. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  58607. ** is swapped with the first free page pulled off the free list.
  58608. **
  58609. ** On the other hand, if bCommit is greater than zero, then keep
  58610. ** looping until a free-page located within the first nFin pages
  58611. ** of the file is found.
  58612. */
  58613. if( bCommit==0 ){
  58614. eMode = BTALLOC_LE;
  58615. iNear = nFin;
  58616. }
  58617. do {
  58618. MemPage *pFreePg;
  58619. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  58620. if( rc!=SQLITE_OK ){
  58621. releasePage(pLastPg);
  58622. return rc;
  58623. }
  58624. releasePage(pFreePg);
  58625. }while( bCommit && iFreePg>nFin );
  58626. assert( iFreePg<iLastPg );
  58627. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  58628. releasePage(pLastPg);
  58629. if( rc!=SQLITE_OK ){
  58630. return rc;
  58631. }
  58632. }
  58633. }
  58634. if( bCommit==0 ){
  58635. do {
  58636. iLastPg--;
  58637. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  58638. pBt->bDoTruncate = 1;
  58639. pBt->nPage = iLastPg;
  58640. }
  58641. return SQLITE_OK;
  58642. }
  58643. /*
  58644. ** The database opened by the first argument is an auto-vacuum database
  58645. ** nOrig pages in size containing nFree free pages. Return the expected
  58646. ** size of the database in pages following an auto-vacuum operation.
  58647. */
  58648. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  58649. int nEntry; /* Number of entries on one ptrmap page */
  58650. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  58651. Pgno nFin; /* Return value */
  58652. nEntry = pBt->usableSize/5;
  58653. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  58654. nFin = nOrig - nFree - nPtrmap;
  58655. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  58656. nFin--;
  58657. }
  58658. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  58659. nFin--;
  58660. }
  58661. return nFin;
  58662. }
  58663. /*
  58664. ** A write-transaction must be opened before calling this function.
  58665. ** It performs a single unit of work towards an incremental vacuum.
  58666. **
  58667. ** If the incremental vacuum is finished after this function has run,
  58668. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  58669. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  58670. */
  58671. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  58672. int rc;
  58673. BtShared *pBt = p->pBt;
  58674. sqlite3BtreeEnter(p);
  58675. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  58676. if( !pBt->autoVacuum ){
  58677. rc = SQLITE_DONE;
  58678. }else{
  58679. Pgno nOrig = btreePagecount(pBt);
  58680. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  58681. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  58682. if( nOrig<nFin ){
  58683. rc = SQLITE_CORRUPT_BKPT;
  58684. }else if( nFree>0 ){
  58685. rc = saveAllCursors(pBt, 0, 0);
  58686. if( rc==SQLITE_OK ){
  58687. invalidateAllOverflowCache(pBt);
  58688. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  58689. }
  58690. if( rc==SQLITE_OK ){
  58691. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  58692. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  58693. }
  58694. }else{
  58695. rc = SQLITE_DONE;
  58696. }
  58697. }
  58698. sqlite3BtreeLeave(p);
  58699. return rc;
  58700. }
  58701. /*
  58702. ** This routine is called prior to sqlite3PagerCommit when a transaction
  58703. ** is committed for an auto-vacuum database.
  58704. **
  58705. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  58706. ** the database file should be truncated to during the commit process.
  58707. ** i.e. the database has been reorganized so that only the first *pnTrunc
  58708. ** pages are in use.
  58709. */
  58710. static int autoVacuumCommit(BtShared *pBt){
  58711. int rc = SQLITE_OK;
  58712. Pager *pPager = pBt->pPager;
  58713. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
  58714. assert( sqlite3_mutex_held(pBt->mutex) );
  58715. invalidateAllOverflowCache(pBt);
  58716. assert(pBt->autoVacuum);
  58717. if( !pBt->incrVacuum ){
  58718. Pgno nFin; /* Number of pages in database after autovacuuming */
  58719. Pgno nFree; /* Number of pages on the freelist initially */
  58720. Pgno iFree; /* The next page to be freed */
  58721. Pgno nOrig; /* Database size before freeing */
  58722. nOrig = btreePagecount(pBt);
  58723. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  58724. /* It is not possible to create a database for which the final page
  58725. ** is either a pointer-map page or the pending-byte page. If one
  58726. ** is encountered, this indicates corruption.
  58727. */
  58728. return SQLITE_CORRUPT_BKPT;
  58729. }
  58730. nFree = get4byte(&pBt->pPage1->aData[36]);
  58731. nFin = finalDbSize(pBt, nOrig, nFree);
  58732. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  58733. if( nFin<nOrig ){
  58734. rc = saveAllCursors(pBt, 0, 0);
  58735. }
  58736. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  58737. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  58738. }
  58739. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  58740. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  58741. put4byte(&pBt->pPage1->aData[32], 0);
  58742. put4byte(&pBt->pPage1->aData[36], 0);
  58743. put4byte(&pBt->pPage1->aData[28], nFin);
  58744. pBt->bDoTruncate = 1;
  58745. pBt->nPage = nFin;
  58746. }
  58747. if( rc!=SQLITE_OK ){
  58748. sqlite3PagerRollback(pPager);
  58749. }
  58750. }
  58751. assert( nRef>=sqlite3PagerRefcount(pPager) );
  58752. return rc;
  58753. }
  58754. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  58755. # define setChildPtrmaps(x) SQLITE_OK
  58756. #endif
  58757. /*
  58758. ** This routine does the first phase of a two-phase commit. This routine
  58759. ** causes a rollback journal to be created (if it does not already exist)
  58760. ** and populated with enough information so that if a power loss occurs
  58761. ** the database can be restored to its original state by playing back
  58762. ** the journal. Then the contents of the journal are flushed out to
  58763. ** the disk. After the journal is safely on oxide, the changes to the
  58764. ** database are written into the database file and flushed to oxide.
  58765. ** At the end of this call, the rollback journal still exists on the
  58766. ** disk and we are still holding all locks, so the transaction has not
  58767. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  58768. ** commit process.
  58769. **
  58770. ** This call is a no-op if no write-transaction is currently active on pBt.
  58771. **
  58772. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  58773. ** the name of a master journal file that should be written into the
  58774. ** individual journal file, or is NULL, indicating no master journal file
  58775. ** (single database transaction).
  58776. **
  58777. ** When this is called, the master journal should already have been
  58778. ** created, populated with this journal pointer and synced to disk.
  58779. **
  58780. ** Once this is routine has returned, the only thing required to commit
  58781. ** the write-transaction for this database file is to delete the journal.
  58782. */
  58783. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  58784. int rc = SQLITE_OK;
  58785. if( p->inTrans==TRANS_WRITE ){
  58786. BtShared *pBt = p->pBt;
  58787. sqlite3BtreeEnter(p);
  58788. #ifndef SQLITE_OMIT_AUTOVACUUM
  58789. if( pBt->autoVacuum ){
  58790. rc = autoVacuumCommit(pBt);
  58791. if( rc!=SQLITE_OK ){
  58792. sqlite3BtreeLeave(p);
  58793. return rc;
  58794. }
  58795. }
  58796. if( pBt->bDoTruncate ){
  58797. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  58798. }
  58799. #endif
  58800. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  58801. sqlite3BtreeLeave(p);
  58802. }
  58803. return rc;
  58804. }
  58805. /*
  58806. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  58807. ** at the conclusion of a transaction.
  58808. */
  58809. static void btreeEndTransaction(Btree *p){
  58810. BtShared *pBt = p->pBt;
  58811. sqlite3 *db = p->db;
  58812. assert( sqlite3BtreeHoldsMutex(p) );
  58813. #ifndef SQLITE_OMIT_AUTOVACUUM
  58814. pBt->bDoTruncate = 0;
  58815. #endif
  58816. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  58817. /* If there are other active statements that belong to this database
  58818. ** handle, downgrade to a read-only transaction. The other statements
  58819. ** may still be reading from the database. */
  58820. downgradeAllSharedCacheTableLocks(p);
  58821. p->inTrans = TRANS_READ;
  58822. }else{
  58823. /* If the handle had any kind of transaction open, decrement the
  58824. ** transaction count of the shared btree. If the transaction count
  58825. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  58826. ** call below will unlock the pager. */
  58827. if( p->inTrans!=TRANS_NONE ){
  58828. clearAllSharedCacheTableLocks(p);
  58829. pBt->nTransaction--;
  58830. if( 0==pBt->nTransaction ){
  58831. pBt->inTransaction = TRANS_NONE;
  58832. }
  58833. }
  58834. /* Set the current transaction state to TRANS_NONE and unlock the
  58835. ** pager if this call closed the only read or write transaction. */
  58836. p->inTrans = TRANS_NONE;
  58837. unlockBtreeIfUnused(pBt);
  58838. }
  58839. btreeIntegrity(p);
  58840. }
  58841. /*
  58842. ** Commit the transaction currently in progress.
  58843. **
  58844. ** This routine implements the second phase of a 2-phase commit. The
  58845. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  58846. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  58847. ** routine did all the work of writing information out to disk and flushing the
  58848. ** contents so that they are written onto the disk platter. All this
  58849. ** routine has to do is delete or truncate or zero the header in the
  58850. ** the rollback journal (which causes the transaction to commit) and
  58851. ** drop locks.
  58852. **
  58853. ** Normally, if an error occurs while the pager layer is attempting to
  58854. ** finalize the underlying journal file, this function returns an error and
  58855. ** the upper layer will attempt a rollback. However, if the second argument
  58856. ** is non-zero then this b-tree transaction is part of a multi-file
  58857. ** transaction. In this case, the transaction has already been committed
  58858. ** (by deleting a master journal file) and the caller will ignore this
  58859. ** functions return code. So, even if an error occurs in the pager layer,
  58860. ** reset the b-tree objects internal state to indicate that the write
  58861. ** transaction has been closed. This is quite safe, as the pager will have
  58862. ** transitioned to the error state.
  58863. **
  58864. ** This will release the write lock on the database file. If there
  58865. ** are no active cursors, it also releases the read lock.
  58866. */
  58867. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  58868. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  58869. sqlite3BtreeEnter(p);
  58870. btreeIntegrity(p);
  58871. /* If the handle has a write-transaction open, commit the shared-btrees
  58872. ** transaction and set the shared state to TRANS_READ.
  58873. */
  58874. if( p->inTrans==TRANS_WRITE ){
  58875. int rc;
  58876. BtShared *pBt = p->pBt;
  58877. assert( pBt->inTransaction==TRANS_WRITE );
  58878. assert( pBt->nTransaction>0 );
  58879. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  58880. if( rc!=SQLITE_OK && bCleanup==0 ){
  58881. sqlite3BtreeLeave(p);
  58882. return rc;
  58883. }
  58884. p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
  58885. pBt->inTransaction = TRANS_READ;
  58886. btreeClearHasContent(pBt);
  58887. }
  58888. btreeEndTransaction(p);
  58889. sqlite3BtreeLeave(p);
  58890. return SQLITE_OK;
  58891. }
  58892. /*
  58893. ** Do both phases of a commit.
  58894. */
  58895. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  58896. int rc;
  58897. sqlite3BtreeEnter(p);
  58898. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  58899. if( rc==SQLITE_OK ){
  58900. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  58901. }
  58902. sqlite3BtreeLeave(p);
  58903. return rc;
  58904. }
  58905. /*
  58906. ** This routine sets the state to CURSOR_FAULT and the error
  58907. ** code to errCode for every cursor on any BtShared that pBtree
  58908. ** references. Or if the writeOnly flag is set to 1, then only
  58909. ** trip write cursors and leave read cursors unchanged.
  58910. **
  58911. ** Every cursor is a candidate to be tripped, including cursors
  58912. ** that belong to other database connections that happen to be
  58913. ** sharing the cache with pBtree.
  58914. **
  58915. ** This routine gets called when a rollback occurs. If the writeOnly
  58916. ** flag is true, then only write-cursors need be tripped - read-only
  58917. ** cursors save their current positions so that they may continue
  58918. ** following the rollback. Or, if writeOnly is false, all cursors are
  58919. ** tripped. In general, writeOnly is false if the transaction being
  58920. ** rolled back modified the database schema. In this case b-tree root
  58921. ** pages may be moved or deleted from the database altogether, making
  58922. ** it unsafe for read cursors to continue.
  58923. **
  58924. ** If the writeOnly flag is true and an error is encountered while
  58925. ** saving the current position of a read-only cursor, all cursors,
  58926. ** including all read-cursors are tripped.
  58927. **
  58928. ** SQLITE_OK is returned if successful, or if an error occurs while
  58929. ** saving a cursor position, an SQLite error code.
  58930. */
  58931. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
  58932. BtCursor *p;
  58933. int rc = SQLITE_OK;
  58934. assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
  58935. if( pBtree ){
  58936. sqlite3BtreeEnter(pBtree);
  58937. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  58938. int i;
  58939. if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
  58940. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  58941. rc = saveCursorPosition(p);
  58942. if( rc!=SQLITE_OK ){
  58943. (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
  58944. break;
  58945. }
  58946. }
  58947. }else{
  58948. sqlite3BtreeClearCursor(p);
  58949. p->eState = CURSOR_FAULT;
  58950. p->skipNext = errCode;
  58951. }
  58952. for(i=0; i<=p->iPage; i++){
  58953. releasePage(p->apPage[i]);
  58954. p->apPage[i] = 0;
  58955. }
  58956. }
  58957. sqlite3BtreeLeave(pBtree);
  58958. }
  58959. return rc;
  58960. }
  58961. /*
  58962. ** Rollback the transaction in progress.
  58963. **
  58964. ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
  58965. ** Only write cursors are tripped if writeOnly is true but all cursors are
  58966. ** tripped if writeOnly is false. Any attempt to use
  58967. ** a tripped cursor will result in an error.
  58968. **
  58969. ** This will release the write lock on the database file. If there
  58970. ** are no active cursors, it also releases the read lock.
  58971. */
  58972. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
  58973. int rc;
  58974. BtShared *pBt = p->pBt;
  58975. MemPage *pPage1;
  58976. assert( writeOnly==1 || writeOnly==0 );
  58977. assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
  58978. sqlite3BtreeEnter(p);
  58979. if( tripCode==SQLITE_OK ){
  58980. rc = tripCode = saveAllCursors(pBt, 0, 0);
  58981. if( rc ) writeOnly = 0;
  58982. }else{
  58983. rc = SQLITE_OK;
  58984. }
  58985. if( tripCode ){
  58986. int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
  58987. assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
  58988. if( rc2!=SQLITE_OK ) rc = rc2;
  58989. }
  58990. btreeIntegrity(p);
  58991. if( p->inTrans==TRANS_WRITE ){
  58992. int rc2;
  58993. assert( TRANS_WRITE==pBt->inTransaction );
  58994. rc2 = sqlite3PagerRollback(pBt->pPager);
  58995. if( rc2!=SQLITE_OK ){
  58996. rc = rc2;
  58997. }
  58998. /* The rollback may have destroyed the pPage1->aData value. So
  58999. ** call btreeGetPage() on page 1 again to make
  59000. ** sure pPage1->aData is set correctly. */
  59001. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  59002. int nPage = get4byte(28+(u8*)pPage1->aData);
  59003. testcase( nPage==0 );
  59004. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  59005. testcase( pBt->nPage!=nPage );
  59006. pBt->nPage = nPage;
  59007. releasePage(pPage1);
  59008. }
  59009. assert( countValidCursors(pBt, 1)==0 );
  59010. pBt->inTransaction = TRANS_READ;
  59011. btreeClearHasContent(pBt);
  59012. }
  59013. btreeEndTransaction(p);
  59014. sqlite3BtreeLeave(p);
  59015. return rc;
  59016. }
  59017. /*
  59018. ** Start a statement subtransaction. The subtransaction can be rolled
  59019. ** back independently of the main transaction. You must start a transaction
  59020. ** before starting a subtransaction. The subtransaction is ended automatically
  59021. ** if the main transaction commits or rolls back.
  59022. **
  59023. ** Statement subtransactions are used around individual SQL statements
  59024. ** that are contained within a BEGIN...COMMIT block. If a constraint
  59025. ** error occurs within the statement, the effect of that one statement
  59026. ** can be rolled back without having to rollback the entire transaction.
  59027. **
  59028. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  59029. ** value passed as the second parameter is the total number of savepoints,
  59030. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  59031. ** are no active savepoints and no other statement-transactions open,
  59032. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  59033. ** using the sqlite3BtreeSavepoint() function.
  59034. */
  59035. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  59036. int rc;
  59037. BtShared *pBt = p->pBt;
  59038. sqlite3BtreeEnter(p);
  59039. assert( p->inTrans==TRANS_WRITE );
  59040. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  59041. assert( iStatement>0 );
  59042. assert( iStatement>p->db->nSavepoint );
  59043. assert( pBt->inTransaction==TRANS_WRITE );
  59044. /* At the pager level, a statement transaction is a savepoint with
  59045. ** an index greater than all savepoints created explicitly using
  59046. ** SQL statements. It is illegal to open, release or rollback any
  59047. ** such savepoints while the statement transaction savepoint is active.
  59048. */
  59049. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  59050. sqlite3BtreeLeave(p);
  59051. return rc;
  59052. }
  59053. /*
  59054. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  59055. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  59056. ** savepoint identified by parameter iSavepoint, depending on the value
  59057. ** of op.
  59058. **
  59059. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  59060. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  59061. ** contents of the entire transaction are rolled back. This is different
  59062. ** from a normal transaction rollback, as no locks are released and the
  59063. ** transaction remains open.
  59064. */
  59065. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  59066. int rc = SQLITE_OK;
  59067. if( p && p->inTrans==TRANS_WRITE ){
  59068. BtShared *pBt = p->pBt;
  59069. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  59070. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  59071. sqlite3BtreeEnter(p);
  59072. if( op==SAVEPOINT_ROLLBACK ){
  59073. rc = saveAllCursors(pBt, 0, 0);
  59074. }
  59075. if( rc==SQLITE_OK ){
  59076. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  59077. }
  59078. if( rc==SQLITE_OK ){
  59079. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  59080. pBt->nPage = 0;
  59081. }
  59082. rc = newDatabase(pBt);
  59083. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  59084. /* The database size was written into the offset 28 of the header
  59085. ** when the transaction started, so we know that the value at offset
  59086. ** 28 is nonzero. */
  59087. assert( pBt->nPage>0 );
  59088. }
  59089. sqlite3BtreeLeave(p);
  59090. }
  59091. return rc;
  59092. }
  59093. /*
  59094. ** Create a new cursor for the BTree whose root is on the page
  59095. ** iTable. If a read-only cursor is requested, it is assumed that
  59096. ** the caller already has at least a read-only transaction open
  59097. ** on the database already. If a write-cursor is requested, then
  59098. ** the caller is assumed to have an open write transaction.
  59099. **
  59100. ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
  59101. ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
  59102. ** can be used for reading or for writing if other conditions for writing
  59103. ** are also met. These are the conditions that must be met in order
  59104. ** for writing to be allowed:
  59105. **
  59106. ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
  59107. **
  59108. ** 2: Other database connections that share the same pager cache
  59109. ** but which are not in the READ_UNCOMMITTED state may not have
  59110. ** cursors open with wrFlag==0 on the same table. Otherwise
  59111. ** the changes made by this write cursor would be visible to
  59112. ** the read cursors in the other database connection.
  59113. **
  59114. ** 3: The database must be writable (not on read-only media)
  59115. **
  59116. ** 4: There must be an active transaction.
  59117. **
  59118. ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
  59119. ** is set. If FORDELETE is set, that is a hint to the implementation that
  59120. ** this cursor will only be used to seek to and delete entries of an index
  59121. ** as part of a larger DELETE statement. The FORDELETE hint is not used by
  59122. ** this implementation. But in a hypothetical alternative storage engine
  59123. ** in which index entries are automatically deleted when corresponding table
  59124. ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
  59125. ** operations on this cursor can be no-ops and all READ operations can
  59126. ** return a null row (2-bytes: 0x01 0x00).
  59127. **
  59128. ** No checking is done to make sure that page iTable really is the
  59129. ** root page of a b-tree. If it is not, then the cursor acquired
  59130. ** will not work correctly.
  59131. **
  59132. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  59133. ** on pCur to initialize the memory space prior to invoking this routine.
  59134. */
  59135. static int btreeCursor(
  59136. Btree *p, /* The btree */
  59137. int iTable, /* Root page of table to open */
  59138. int wrFlag, /* 1 to write. 0 read-only */
  59139. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  59140. BtCursor *pCur /* Space for new cursor */
  59141. ){
  59142. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  59143. BtCursor *pX; /* Looping over other all cursors */
  59144. assert( sqlite3BtreeHoldsMutex(p) );
  59145. assert( wrFlag==0
  59146. || wrFlag==BTREE_WRCSR
  59147. || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
  59148. );
  59149. /* The following assert statements verify that if this is a sharable
  59150. ** b-tree database, the connection is holding the required table locks,
  59151. ** and that no other connection has any open cursor that conflicts with
  59152. ** this lock. */
  59153. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
  59154. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  59155. /* Assert that the caller has opened the required transaction. */
  59156. assert( p->inTrans>TRANS_NONE );
  59157. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  59158. assert( pBt->pPage1 && pBt->pPage1->aData );
  59159. assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
  59160. if( wrFlag ){
  59161. allocateTempSpace(pBt);
  59162. if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
  59163. }
  59164. if( iTable==1 && btreePagecount(pBt)==0 ){
  59165. assert( wrFlag==0 );
  59166. iTable = 0;
  59167. }
  59168. /* Now that no other errors can occur, finish filling in the BtCursor
  59169. ** variables and link the cursor into the BtShared list. */
  59170. pCur->pgnoRoot = (Pgno)iTable;
  59171. pCur->iPage = -1;
  59172. pCur->pKeyInfo = pKeyInfo;
  59173. pCur->pBtree = p;
  59174. pCur->pBt = pBt;
  59175. pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
  59176. pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
  59177. /* If there are two or more cursors on the same btree, then all such
  59178. ** cursors *must* have the BTCF_Multiple flag set. */
  59179. for(pX=pBt->pCursor; pX; pX=pX->pNext){
  59180. if( pX->pgnoRoot==(Pgno)iTable ){
  59181. pX->curFlags |= BTCF_Multiple;
  59182. pCur->curFlags |= BTCF_Multiple;
  59183. }
  59184. }
  59185. pCur->pNext = pBt->pCursor;
  59186. pBt->pCursor = pCur;
  59187. pCur->eState = CURSOR_INVALID;
  59188. return SQLITE_OK;
  59189. }
  59190. SQLITE_PRIVATE int sqlite3BtreeCursor(
  59191. Btree *p, /* The btree */
  59192. int iTable, /* Root page of table to open */
  59193. int wrFlag, /* 1 to write. 0 read-only */
  59194. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  59195. BtCursor *pCur /* Write new cursor here */
  59196. ){
  59197. int rc;
  59198. if( iTable<1 ){
  59199. rc = SQLITE_CORRUPT_BKPT;
  59200. }else{
  59201. sqlite3BtreeEnter(p);
  59202. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  59203. sqlite3BtreeLeave(p);
  59204. }
  59205. return rc;
  59206. }
  59207. /*
  59208. ** Return the size of a BtCursor object in bytes.
  59209. **
  59210. ** This interfaces is needed so that users of cursors can preallocate
  59211. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  59212. ** to users so they cannot do the sizeof() themselves - they must call
  59213. ** this routine.
  59214. */
  59215. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  59216. return ROUND8(sizeof(BtCursor));
  59217. }
  59218. /*
  59219. ** Initialize memory that will be converted into a BtCursor object.
  59220. **
  59221. ** The simple approach here would be to memset() the entire object
  59222. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  59223. ** do not need to be zeroed and they are large, so we can save a lot
  59224. ** of run-time by skipping the initialization of those elements.
  59225. */
  59226. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  59227. memset(p, 0, offsetof(BtCursor, iPage));
  59228. }
  59229. /*
  59230. ** Close a cursor. The read lock on the database file is released
  59231. ** when the last cursor is closed.
  59232. */
  59233. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  59234. Btree *pBtree = pCur->pBtree;
  59235. if( pBtree ){
  59236. int i;
  59237. BtShared *pBt = pCur->pBt;
  59238. sqlite3BtreeEnter(pBtree);
  59239. sqlite3BtreeClearCursor(pCur);
  59240. assert( pBt->pCursor!=0 );
  59241. if( pBt->pCursor==pCur ){
  59242. pBt->pCursor = pCur->pNext;
  59243. }else{
  59244. BtCursor *pPrev = pBt->pCursor;
  59245. do{
  59246. if( pPrev->pNext==pCur ){
  59247. pPrev->pNext = pCur->pNext;
  59248. break;
  59249. }
  59250. pPrev = pPrev->pNext;
  59251. }while( ALWAYS(pPrev) );
  59252. }
  59253. for(i=0; i<=pCur->iPage; i++){
  59254. releasePage(pCur->apPage[i]);
  59255. }
  59256. unlockBtreeIfUnused(pBt);
  59257. sqlite3_free(pCur->aOverflow);
  59258. /* sqlite3_free(pCur); */
  59259. sqlite3BtreeLeave(pBtree);
  59260. }
  59261. return SQLITE_OK;
  59262. }
  59263. /*
  59264. ** Make sure the BtCursor* given in the argument has a valid
  59265. ** BtCursor.info structure. If it is not already valid, call
  59266. ** btreeParseCell() to fill it in.
  59267. **
  59268. ** BtCursor.info is a cache of the information in the current cell.
  59269. ** Using this cache reduces the number of calls to btreeParseCell().
  59270. */
  59271. #ifndef NDEBUG
  59272. static void assertCellInfo(BtCursor *pCur){
  59273. CellInfo info;
  59274. int iPage = pCur->iPage;
  59275. memset(&info, 0, sizeof(info));
  59276. btreeParseCell(pCur->apPage[iPage], pCur->ix, &info);
  59277. assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
  59278. }
  59279. #else
  59280. #define assertCellInfo(x)
  59281. #endif
  59282. static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
  59283. if( pCur->info.nSize==0 ){
  59284. int iPage = pCur->iPage;
  59285. pCur->curFlags |= BTCF_ValidNKey;
  59286. btreeParseCell(pCur->apPage[iPage],pCur->ix,&pCur->info);
  59287. }else{
  59288. assertCellInfo(pCur);
  59289. }
  59290. }
  59291. #ifndef NDEBUG /* The next routine used only within assert() statements */
  59292. /*
  59293. ** Return true if the given BtCursor is valid. A valid cursor is one
  59294. ** that is currently pointing to a row in a (non-empty) table.
  59295. ** This is a verification routine is used only within assert() statements.
  59296. */
  59297. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  59298. return pCur && pCur->eState==CURSOR_VALID;
  59299. }
  59300. #endif /* NDEBUG */
  59301. SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
  59302. assert( pCur!=0 );
  59303. return pCur->eState==CURSOR_VALID;
  59304. }
  59305. /*
  59306. ** Return the value of the integer key or "rowid" for a table btree.
  59307. ** This routine is only valid for a cursor that is pointing into a
  59308. ** ordinary table btree. If the cursor points to an index btree or
  59309. ** is invalid, the result of this routine is undefined.
  59310. */
  59311. SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
  59312. assert( cursorHoldsMutex(pCur) );
  59313. assert( pCur->eState==CURSOR_VALID );
  59314. assert( pCur->curIntKey );
  59315. getCellInfo(pCur);
  59316. return pCur->info.nKey;
  59317. }
  59318. /*
  59319. ** Return the number of bytes of payload for the entry that pCur is
  59320. ** currently pointing to. For table btrees, this will be the amount
  59321. ** of data. For index btrees, this will be the size of the key.
  59322. **
  59323. ** The caller must guarantee that the cursor is pointing to a non-NULL
  59324. ** valid entry. In other words, the calling procedure must guarantee
  59325. ** that the cursor has Cursor.eState==CURSOR_VALID.
  59326. */
  59327. SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
  59328. assert( cursorHoldsMutex(pCur) );
  59329. assert( pCur->eState==CURSOR_VALID );
  59330. getCellInfo(pCur);
  59331. return pCur->info.nPayload;
  59332. }
  59333. /*
  59334. ** Given the page number of an overflow page in the database (parameter
  59335. ** ovfl), this function finds the page number of the next page in the
  59336. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  59337. ** pointer-map data instead of reading the content of page ovfl to do so.
  59338. **
  59339. ** If an error occurs an SQLite error code is returned. Otherwise:
  59340. **
  59341. ** The page number of the next overflow page in the linked list is
  59342. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  59343. ** list, *pPgnoNext is set to zero.
  59344. **
  59345. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  59346. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  59347. ** reference. It is the responsibility of the caller to call releasePage()
  59348. ** on *ppPage to free the reference. In no reference was obtained (because
  59349. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  59350. ** *ppPage is set to zero.
  59351. */
  59352. static int getOverflowPage(
  59353. BtShared *pBt, /* The database file */
  59354. Pgno ovfl, /* Current overflow page number */
  59355. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  59356. Pgno *pPgnoNext /* OUT: Next overflow page number */
  59357. ){
  59358. Pgno next = 0;
  59359. MemPage *pPage = 0;
  59360. int rc = SQLITE_OK;
  59361. assert( sqlite3_mutex_held(pBt->mutex) );
  59362. assert(pPgnoNext);
  59363. #ifndef SQLITE_OMIT_AUTOVACUUM
  59364. /* Try to find the next page in the overflow list using the
  59365. ** autovacuum pointer-map pages. Guess that the next page in
  59366. ** the overflow list is page number (ovfl+1). If that guess turns
  59367. ** out to be wrong, fall back to loading the data of page
  59368. ** number ovfl to determine the next page number.
  59369. */
  59370. if( pBt->autoVacuum ){
  59371. Pgno pgno;
  59372. Pgno iGuess = ovfl+1;
  59373. u8 eType;
  59374. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  59375. iGuess++;
  59376. }
  59377. if( iGuess<=btreePagecount(pBt) ){
  59378. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  59379. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  59380. next = iGuess;
  59381. rc = SQLITE_DONE;
  59382. }
  59383. }
  59384. }
  59385. #endif
  59386. assert( next==0 || rc==SQLITE_DONE );
  59387. if( rc==SQLITE_OK ){
  59388. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  59389. assert( rc==SQLITE_OK || pPage==0 );
  59390. if( rc==SQLITE_OK ){
  59391. next = get4byte(pPage->aData);
  59392. }
  59393. }
  59394. *pPgnoNext = next;
  59395. if( ppPage ){
  59396. *ppPage = pPage;
  59397. }else{
  59398. releasePage(pPage);
  59399. }
  59400. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  59401. }
  59402. /*
  59403. ** Copy data from a buffer to a page, or from a page to a buffer.
  59404. **
  59405. ** pPayload is a pointer to data stored on database page pDbPage.
  59406. ** If argument eOp is false, then nByte bytes of data are copied
  59407. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  59408. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  59409. ** of data are copied from the buffer pBuf to pPayload.
  59410. **
  59411. ** SQLITE_OK is returned on success, otherwise an error code.
  59412. */
  59413. static int copyPayload(
  59414. void *pPayload, /* Pointer to page data */
  59415. void *pBuf, /* Pointer to buffer */
  59416. int nByte, /* Number of bytes to copy */
  59417. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  59418. DbPage *pDbPage /* Page containing pPayload */
  59419. ){
  59420. if( eOp ){
  59421. /* Copy data from buffer to page (a write operation) */
  59422. int rc = sqlite3PagerWrite(pDbPage);
  59423. if( rc!=SQLITE_OK ){
  59424. return rc;
  59425. }
  59426. memcpy(pPayload, pBuf, nByte);
  59427. }else{
  59428. /* Copy data from page to buffer (a read operation) */
  59429. memcpy(pBuf, pPayload, nByte);
  59430. }
  59431. return SQLITE_OK;
  59432. }
  59433. /*
  59434. ** This function is used to read or overwrite payload information
  59435. ** for the entry that the pCur cursor is pointing to. The eOp
  59436. ** argument is interpreted as follows:
  59437. **
  59438. ** 0: The operation is a read. Populate the overflow cache.
  59439. ** 1: The operation is a write. Populate the overflow cache.
  59440. **
  59441. ** A total of "amt" bytes are read or written beginning at "offset".
  59442. ** Data is read to or from the buffer pBuf.
  59443. **
  59444. ** The content being read or written might appear on the main page
  59445. ** or be scattered out on multiple overflow pages.
  59446. **
  59447. ** If the current cursor entry uses one or more overflow pages
  59448. ** this function may allocate space for and lazily populate
  59449. ** the overflow page-list cache array (BtCursor.aOverflow).
  59450. ** Subsequent calls use this cache to make seeking to the supplied offset
  59451. ** more efficient.
  59452. **
  59453. ** Once an overflow page-list cache has been allocated, it must be
  59454. ** invalidated if some other cursor writes to the same table, or if
  59455. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  59456. ** mode, the following events may invalidate an overflow page-list cache.
  59457. **
  59458. ** * An incremental vacuum,
  59459. ** * A commit in auto_vacuum="full" mode,
  59460. ** * Creating a table (may require moving an overflow page).
  59461. */
  59462. static int accessPayload(
  59463. BtCursor *pCur, /* Cursor pointing to entry to read from */
  59464. u32 offset, /* Begin reading this far into payload */
  59465. u32 amt, /* Read this many bytes */
  59466. unsigned char *pBuf, /* Write the bytes into this buffer */
  59467. int eOp /* zero to read. non-zero to write. */
  59468. ){
  59469. unsigned char *aPayload;
  59470. int rc = SQLITE_OK;
  59471. int iIdx = 0;
  59472. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  59473. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  59474. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  59475. unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
  59476. #endif
  59477. assert( pPage );
  59478. assert( eOp==0 || eOp==1 );
  59479. assert( pCur->eState==CURSOR_VALID );
  59480. assert( pCur->ix<pPage->nCell );
  59481. assert( cursorHoldsMutex(pCur) );
  59482. getCellInfo(pCur);
  59483. aPayload = pCur->info.pPayload;
  59484. assert( offset+amt <= pCur->info.nPayload );
  59485. assert( aPayload > pPage->aData );
  59486. if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
  59487. /* Trying to read or write past the end of the data is an error. The
  59488. ** conditional above is really:
  59489. ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  59490. ** but is recast into its current form to avoid integer overflow problems
  59491. */
  59492. return SQLITE_CORRUPT_BKPT;
  59493. }
  59494. /* Check if data must be read/written to/from the btree page itself. */
  59495. if( offset<pCur->info.nLocal ){
  59496. int a = amt;
  59497. if( a+offset>pCur->info.nLocal ){
  59498. a = pCur->info.nLocal - offset;
  59499. }
  59500. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  59501. offset = 0;
  59502. pBuf += a;
  59503. amt -= a;
  59504. }else{
  59505. offset -= pCur->info.nLocal;
  59506. }
  59507. if( rc==SQLITE_OK && amt>0 ){
  59508. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  59509. Pgno nextPage;
  59510. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  59511. /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
  59512. **
  59513. ** The aOverflow[] array is sized at one entry for each overflow page
  59514. ** in the overflow chain. The page number of the first overflow page is
  59515. ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
  59516. ** means "not yet known" (the cache is lazily populated).
  59517. */
  59518. if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
  59519. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  59520. if( nOvfl>pCur->nOvflAlloc ){
  59521. Pgno *aNew = (Pgno*)sqlite3Realloc(
  59522. pCur->aOverflow, nOvfl*2*sizeof(Pgno)
  59523. );
  59524. if( aNew==0 ){
  59525. return SQLITE_NOMEM_BKPT;
  59526. }else{
  59527. pCur->nOvflAlloc = nOvfl*2;
  59528. pCur->aOverflow = aNew;
  59529. }
  59530. }
  59531. memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
  59532. pCur->curFlags |= BTCF_ValidOvfl;
  59533. }else{
  59534. /* If the overflow page-list cache has been allocated and the
  59535. ** entry for the first required overflow page is valid, skip
  59536. ** directly to it.
  59537. */
  59538. if( pCur->aOverflow[offset/ovflSize] ){
  59539. iIdx = (offset/ovflSize);
  59540. nextPage = pCur->aOverflow[iIdx];
  59541. offset = (offset%ovflSize);
  59542. }
  59543. }
  59544. assert( rc==SQLITE_OK && amt>0 );
  59545. while( nextPage ){
  59546. /* If required, populate the overflow page-list cache. */
  59547. assert( pCur->aOverflow[iIdx]==0
  59548. || pCur->aOverflow[iIdx]==nextPage
  59549. || CORRUPT_DB );
  59550. pCur->aOverflow[iIdx] = nextPage;
  59551. if( offset>=ovflSize ){
  59552. /* The only reason to read this page is to obtain the page
  59553. ** number for the next page in the overflow chain. The page
  59554. ** data is not required. So first try to lookup the overflow
  59555. ** page-list cache, if any, then fall back to the getOverflowPage()
  59556. ** function.
  59557. */
  59558. assert( pCur->curFlags & BTCF_ValidOvfl );
  59559. assert( pCur->pBtree->db==pBt->db );
  59560. if( pCur->aOverflow[iIdx+1] ){
  59561. nextPage = pCur->aOverflow[iIdx+1];
  59562. }else{
  59563. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  59564. }
  59565. offset -= ovflSize;
  59566. }else{
  59567. /* Need to read this page properly. It contains some of the
  59568. ** range of data that is being read (eOp==0) or written (eOp!=0).
  59569. */
  59570. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  59571. sqlite3_file *fd; /* File from which to do direct overflow read */
  59572. #endif
  59573. int a = amt;
  59574. if( a + offset > ovflSize ){
  59575. a = ovflSize - offset;
  59576. }
  59577. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  59578. /* If all the following are true:
  59579. **
  59580. ** 1) this is a read operation, and
  59581. ** 2) data is required from the start of this overflow page, and
  59582. ** 3) there is no open write-transaction, and
  59583. ** 4) the database is file-backed, and
  59584. ** 5) the page is not in the WAL file
  59585. ** 6) at least 4 bytes have already been read into the output buffer
  59586. **
  59587. ** then data can be read directly from the database file into the
  59588. ** output buffer, bypassing the page-cache altogether. This speeds
  59589. ** up loading large records that span many overflow pages.
  59590. */
  59591. if( eOp==0 /* (1) */
  59592. && offset==0 /* (2) */
  59593. && pBt->inTransaction==TRANS_READ /* (3) */
  59594. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (4) */
  59595. && 0==sqlite3PagerUseWal(pBt->pPager, nextPage) /* (5) */
  59596. && &pBuf[-4]>=pBufStart /* (6) */
  59597. ){
  59598. u8 aSave[4];
  59599. u8 *aWrite = &pBuf[-4];
  59600. assert( aWrite>=pBufStart ); /* due to (6) */
  59601. memcpy(aSave, aWrite, 4);
  59602. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  59603. nextPage = get4byte(aWrite);
  59604. memcpy(aWrite, aSave, 4);
  59605. }else
  59606. #endif
  59607. {
  59608. DbPage *pDbPage;
  59609. rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
  59610. (eOp==0 ? PAGER_GET_READONLY : 0)
  59611. );
  59612. if( rc==SQLITE_OK ){
  59613. aPayload = sqlite3PagerGetData(pDbPage);
  59614. nextPage = get4byte(aPayload);
  59615. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  59616. sqlite3PagerUnref(pDbPage);
  59617. offset = 0;
  59618. }
  59619. }
  59620. amt -= a;
  59621. if( amt==0 ) return rc;
  59622. pBuf += a;
  59623. }
  59624. if( rc ) break;
  59625. iIdx++;
  59626. }
  59627. }
  59628. if( rc==SQLITE_OK && amt>0 ){
  59629. return SQLITE_CORRUPT_BKPT; /* Overflow chain ends prematurely */
  59630. }
  59631. return rc;
  59632. }
  59633. /*
  59634. ** Read part of the payload for the row at which that cursor pCur is currently
  59635. ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
  59636. ** begins at "offset".
  59637. **
  59638. ** pCur can be pointing to either a table or an index b-tree.
  59639. ** If pointing to a table btree, then the content section is read. If
  59640. ** pCur is pointing to an index b-tree then the key section is read.
  59641. **
  59642. ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
  59643. ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
  59644. ** cursor might be invalid or might need to be restored before being read.
  59645. **
  59646. ** Return SQLITE_OK on success or an error code if anything goes
  59647. ** wrong. An error is returned if "offset+amt" is larger than
  59648. ** the available payload.
  59649. */
  59650. SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  59651. assert( cursorHoldsMutex(pCur) );
  59652. assert( pCur->eState==CURSOR_VALID );
  59653. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  59654. assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
  59655. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  59656. }
  59657. /*
  59658. ** This variant of sqlite3BtreePayload() works even if the cursor has not
  59659. ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
  59660. ** interface.
  59661. */
  59662. #ifndef SQLITE_OMIT_INCRBLOB
  59663. static SQLITE_NOINLINE int accessPayloadChecked(
  59664. BtCursor *pCur,
  59665. u32 offset,
  59666. u32 amt,
  59667. void *pBuf
  59668. ){
  59669. int rc;
  59670. if ( pCur->eState==CURSOR_INVALID ){
  59671. return SQLITE_ABORT;
  59672. }
  59673. assert( cursorOwnsBtShared(pCur) );
  59674. rc = btreeRestoreCursorPosition(pCur);
  59675. return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
  59676. }
  59677. SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  59678. if( pCur->eState==CURSOR_VALID ){
  59679. assert( cursorOwnsBtShared(pCur) );
  59680. return accessPayload(pCur, offset, amt, pBuf, 0);
  59681. }else{
  59682. return accessPayloadChecked(pCur, offset, amt, pBuf);
  59683. }
  59684. }
  59685. #endif /* SQLITE_OMIT_INCRBLOB */
  59686. /*
  59687. ** Return a pointer to payload information from the entry that the
  59688. ** pCur cursor is pointing to. The pointer is to the beginning of
  59689. ** the key if index btrees (pPage->intKey==0) and is the data for
  59690. ** table btrees (pPage->intKey==1). The number of bytes of available
  59691. ** key/data is written into *pAmt. If *pAmt==0, then the value
  59692. ** returned will not be a valid pointer.
  59693. **
  59694. ** This routine is an optimization. It is common for the entire key
  59695. ** and data to fit on the local page and for there to be no overflow
  59696. ** pages. When that is so, this routine can be used to access the
  59697. ** key and data without making a copy. If the key and/or data spills
  59698. ** onto overflow pages, then accessPayload() must be used to reassemble
  59699. ** the key/data and copy it into a preallocated buffer.
  59700. **
  59701. ** The pointer returned by this routine looks directly into the cached
  59702. ** page of the database. The data might change or move the next time
  59703. ** any btree routine is called.
  59704. */
  59705. static const void *fetchPayload(
  59706. BtCursor *pCur, /* Cursor pointing to entry to read from */
  59707. u32 *pAmt /* Write the number of available bytes here */
  59708. ){
  59709. u32 amt;
  59710. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  59711. assert( pCur->eState==CURSOR_VALID );
  59712. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  59713. assert( cursorOwnsBtShared(pCur) );
  59714. assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
  59715. assert( pCur->info.nSize>0 );
  59716. assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
  59717. assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
  59718. amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
  59719. if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
  59720. *pAmt = amt;
  59721. return (void*)pCur->info.pPayload;
  59722. }
  59723. /*
  59724. ** For the entry that cursor pCur is point to, return as
  59725. ** many bytes of the key or data as are available on the local
  59726. ** b-tree page. Write the number of available bytes into *pAmt.
  59727. **
  59728. ** The pointer returned is ephemeral. The key/data may move
  59729. ** or be destroyed on the next call to any Btree routine,
  59730. ** including calls from other threads against the same cache.
  59731. ** Hence, a mutex on the BtShared should be held prior to calling
  59732. ** this routine.
  59733. **
  59734. ** These routines is used to get quick access to key and data
  59735. ** in the common case where no overflow pages are used.
  59736. */
  59737. SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
  59738. return fetchPayload(pCur, pAmt);
  59739. }
  59740. /*
  59741. ** Move the cursor down to a new child page. The newPgno argument is the
  59742. ** page number of the child page to move to.
  59743. **
  59744. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  59745. ** the new child page does not match the flags field of the parent (i.e.
  59746. ** if an intkey page appears to be the parent of a non-intkey page, or
  59747. ** vice-versa).
  59748. */
  59749. static int moveToChild(BtCursor *pCur, u32 newPgno){
  59750. BtShared *pBt = pCur->pBt;
  59751. assert( cursorOwnsBtShared(pCur) );
  59752. assert( pCur->eState==CURSOR_VALID );
  59753. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  59754. assert( pCur->iPage>=0 );
  59755. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  59756. return SQLITE_CORRUPT_BKPT;
  59757. }
  59758. pCur->info.nSize = 0;
  59759. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  59760. pCur->aiIdx[pCur->iPage++] = pCur->ix;
  59761. pCur->ix = 0;
  59762. return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
  59763. pCur, pCur->curPagerFlags);
  59764. }
  59765. #ifdef SQLITE_DEBUG
  59766. /*
  59767. ** Page pParent is an internal (non-leaf) tree page. This function
  59768. ** asserts that page number iChild is the left-child if the iIdx'th
  59769. ** cell in page pParent. Or, if iIdx is equal to the total number of
  59770. ** cells in pParent, that page number iChild is the right-child of
  59771. ** the page.
  59772. */
  59773. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  59774. if( CORRUPT_DB ) return; /* The conditions tested below might not be true
  59775. ** in a corrupt database */
  59776. assert( iIdx<=pParent->nCell );
  59777. if( iIdx==pParent->nCell ){
  59778. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  59779. }else{
  59780. assert( get4byte(findCell(pParent, iIdx))==iChild );
  59781. }
  59782. }
  59783. #else
  59784. # define assertParentIndex(x,y,z)
  59785. #endif
  59786. /*
  59787. ** Move the cursor up to the parent page.
  59788. **
  59789. ** pCur->idx is set to the cell index that contains the pointer
  59790. ** to the page we are coming from. If we are coming from the
  59791. ** right-most child page then pCur->idx is set to one more than
  59792. ** the largest cell index.
  59793. */
  59794. static void moveToParent(BtCursor *pCur){
  59795. assert( cursorOwnsBtShared(pCur) );
  59796. assert( pCur->eState==CURSOR_VALID );
  59797. assert( pCur->iPage>0 );
  59798. assert( pCur->apPage[pCur->iPage] );
  59799. assertParentIndex(
  59800. pCur->apPage[pCur->iPage-1],
  59801. pCur->aiIdx[pCur->iPage-1],
  59802. pCur->apPage[pCur->iPage]->pgno
  59803. );
  59804. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  59805. pCur->info.nSize = 0;
  59806. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  59807. pCur->ix = pCur->aiIdx[pCur->iPage-1];
  59808. releasePageNotNull(pCur->apPage[pCur->iPage--]);
  59809. }
  59810. /*
  59811. ** Move the cursor to point to the root page of its b-tree structure.
  59812. **
  59813. ** If the table has a virtual root page, then the cursor is moved to point
  59814. ** to the virtual root page instead of the actual root page. A table has a
  59815. ** virtual root page when the actual root page contains no cells and a
  59816. ** single child page. This can only happen with the table rooted at page 1.
  59817. **
  59818. ** If the b-tree structure is empty, the cursor state is set to
  59819. ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
  59820. ** cell located on the root (or virtual root) page and the cursor state
  59821. ** is set to CURSOR_VALID.
  59822. **
  59823. ** If this function returns successfully, it may be assumed that the
  59824. ** page-header flags indicate that the [virtual] root-page is the expected
  59825. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  59826. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  59827. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  59828. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  59829. ** b-tree).
  59830. */
  59831. static int moveToRoot(BtCursor *pCur){
  59832. MemPage *pRoot;
  59833. int rc = SQLITE_OK;
  59834. assert( cursorOwnsBtShared(pCur) );
  59835. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  59836. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  59837. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  59838. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  59839. if( pCur->eState==CURSOR_FAULT ){
  59840. assert( pCur->skipNext!=SQLITE_OK );
  59841. return pCur->skipNext;
  59842. }
  59843. sqlite3BtreeClearCursor(pCur);
  59844. }
  59845. if( pCur->iPage>=0 ){
  59846. if( pCur->iPage ){
  59847. do{
  59848. assert( pCur->apPage[pCur->iPage]!=0 );
  59849. releasePageNotNull(pCur->apPage[pCur->iPage--]);
  59850. }while( pCur->iPage);
  59851. goto skip_init;
  59852. }
  59853. }else if( pCur->pgnoRoot==0 ){
  59854. pCur->eState = CURSOR_INVALID;
  59855. return SQLITE_OK;
  59856. }else{
  59857. assert( pCur->iPage==(-1) );
  59858. rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
  59859. 0, pCur->curPagerFlags);
  59860. if( rc!=SQLITE_OK ){
  59861. pCur->eState = CURSOR_INVALID;
  59862. return rc;
  59863. }
  59864. pCur->iPage = 0;
  59865. pCur->curIntKey = pCur->apPage[0]->intKey;
  59866. }
  59867. pRoot = pCur->apPage[0];
  59868. assert( pRoot->pgno==pCur->pgnoRoot );
  59869. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  59870. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  59871. ** NULL, the caller expects a table b-tree. If this is not the case,
  59872. ** return an SQLITE_CORRUPT error.
  59873. **
  59874. ** Earlier versions of SQLite assumed that this test could not fail
  59875. ** if the root page was already loaded when this function was called (i.e.
  59876. ** if pCur->iPage>=0). But this is not so if the database is corrupted
  59877. ** in such a way that page pRoot is linked into a second b-tree table
  59878. ** (or the freelist). */
  59879. assert( pRoot->intKey==1 || pRoot->intKey==0 );
  59880. if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
  59881. return SQLITE_CORRUPT_BKPT;
  59882. }
  59883. skip_init:
  59884. pCur->ix = 0;
  59885. pCur->info.nSize = 0;
  59886. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
  59887. pRoot = pCur->apPage[0];
  59888. if( pRoot->nCell>0 ){
  59889. pCur->eState = CURSOR_VALID;
  59890. }else if( !pRoot->leaf ){
  59891. Pgno subpage;
  59892. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  59893. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  59894. pCur->eState = CURSOR_VALID;
  59895. rc = moveToChild(pCur, subpage);
  59896. }else{
  59897. pCur->eState = CURSOR_INVALID;
  59898. }
  59899. return rc;
  59900. }
  59901. /*
  59902. ** Move the cursor down to the left-most leaf entry beneath the
  59903. ** entry to which it is currently pointing.
  59904. **
  59905. ** The left-most leaf is the one with the smallest key - the first
  59906. ** in ascending order.
  59907. */
  59908. static int moveToLeftmost(BtCursor *pCur){
  59909. Pgno pgno;
  59910. int rc = SQLITE_OK;
  59911. MemPage *pPage;
  59912. assert( cursorOwnsBtShared(pCur) );
  59913. assert( pCur->eState==CURSOR_VALID );
  59914. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  59915. assert( pCur->ix<pPage->nCell );
  59916. pgno = get4byte(findCell(pPage, pCur->ix));
  59917. rc = moveToChild(pCur, pgno);
  59918. }
  59919. return rc;
  59920. }
  59921. /*
  59922. ** Move the cursor down to the right-most leaf entry beneath the
  59923. ** page to which it is currently pointing. Notice the difference
  59924. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  59925. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  59926. ** finds the right-most entry beneath the *page*.
  59927. **
  59928. ** The right-most entry is the one with the largest key - the last
  59929. ** key in ascending order.
  59930. */
  59931. static int moveToRightmost(BtCursor *pCur){
  59932. Pgno pgno;
  59933. int rc = SQLITE_OK;
  59934. MemPage *pPage = 0;
  59935. assert( cursorOwnsBtShared(pCur) );
  59936. assert( pCur->eState==CURSOR_VALID );
  59937. while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  59938. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  59939. pCur->ix = pPage->nCell;
  59940. rc = moveToChild(pCur, pgno);
  59941. if( rc ) return rc;
  59942. }
  59943. pCur->ix = pPage->nCell-1;
  59944. assert( pCur->info.nSize==0 );
  59945. assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
  59946. return SQLITE_OK;
  59947. }
  59948. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  59949. ** on success. Set *pRes to 0 if the cursor actually points to something
  59950. ** or set *pRes to 1 if the table is empty.
  59951. */
  59952. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  59953. int rc;
  59954. assert( cursorOwnsBtShared(pCur) );
  59955. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  59956. rc = moveToRoot(pCur);
  59957. if( rc==SQLITE_OK ){
  59958. if( pCur->eState==CURSOR_INVALID ){
  59959. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  59960. *pRes = 1;
  59961. }else{
  59962. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  59963. *pRes = 0;
  59964. rc = moveToLeftmost(pCur);
  59965. }
  59966. }
  59967. return rc;
  59968. }
  59969. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  59970. ** on success. Set *pRes to 0 if the cursor actually points to something
  59971. ** or set *pRes to 1 if the table is empty.
  59972. */
  59973. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  59974. int rc;
  59975. assert( cursorOwnsBtShared(pCur) );
  59976. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  59977. /* If the cursor already points to the last entry, this is a no-op. */
  59978. if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
  59979. #ifdef SQLITE_DEBUG
  59980. /* This block serves to assert() that the cursor really does point
  59981. ** to the last entry in the b-tree. */
  59982. int ii;
  59983. for(ii=0; ii<pCur->iPage; ii++){
  59984. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  59985. }
  59986. assert( pCur->ix==pCur->apPage[pCur->iPage]->nCell-1 );
  59987. assert( pCur->apPage[pCur->iPage]->leaf );
  59988. #endif
  59989. return SQLITE_OK;
  59990. }
  59991. rc = moveToRoot(pCur);
  59992. if( rc==SQLITE_OK ){
  59993. if( CURSOR_INVALID==pCur->eState ){
  59994. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  59995. *pRes = 1;
  59996. }else{
  59997. assert( pCur->eState==CURSOR_VALID );
  59998. *pRes = 0;
  59999. rc = moveToRightmost(pCur);
  60000. if( rc==SQLITE_OK ){
  60001. pCur->curFlags |= BTCF_AtLast;
  60002. }else{
  60003. pCur->curFlags &= ~BTCF_AtLast;
  60004. }
  60005. }
  60006. }
  60007. return rc;
  60008. }
  60009. /* Move the cursor so that it points to an entry near the key
  60010. ** specified by pIdxKey or intKey. Return a success code.
  60011. **
  60012. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  60013. ** must be NULL. For index tables, pIdxKey is used and intKey
  60014. ** is ignored.
  60015. **
  60016. ** If an exact match is not found, then the cursor is always
  60017. ** left pointing at a leaf page which would hold the entry if it
  60018. ** were present. The cursor might point to an entry that comes
  60019. ** before or after the key.
  60020. **
  60021. ** An integer is written into *pRes which is the result of
  60022. ** comparing the key with the entry to which the cursor is
  60023. ** pointing. The meaning of the integer written into
  60024. ** *pRes is as follows:
  60025. **
  60026. ** *pRes<0 The cursor is left pointing at an entry that
  60027. ** is smaller than intKey/pIdxKey or if the table is empty
  60028. ** and the cursor is therefore left point to nothing.
  60029. **
  60030. ** *pRes==0 The cursor is left pointing at an entry that
  60031. ** exactly matches intKey/pIdxKey.
  60032. **
  60033. ** *pRes>0 The cursor is left pointing at an entry that
  60034. ** is larger than intKey/pIdxKey.
  60035. **
  60036. ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
  60037. ** exists an entry in the table that exactly matches pIdxKey.
  60038. */
  60039. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  60040. BtCursor *pCur, /* The cursor to be moved */
  60041. UnpackedRecord *pIdxKey, /* Unpacked index key */
  60042. i64 intKey, /* The table key */
  60043. int biasRight, /* If true, bias the search to the high end */
  60044. int *pRes /* Write search results here */
  60045. ){
  60046. int rc;
  60047. RecordCompare xRecordCompare;
  60048. assert( cursorOwnsBtShared(pCur) );
  60049. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  60050. assert( pRes );
  60051. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  60052. assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
  60053. /* If the cursor is already positioned at the point we are trying
  60054. ** to move to, then just return without doing any work */
  60055. if( pIdxKey==0
  60056. && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
  60057. ){
  60058. if( pCur->info.nKey==intKey ){
  60059. *pRes = 0;
  60060. return SQLITE_OK;
  60061. }
  60062. if( pCur->info.nKey<intKey ){
  60063. if( (pCur->curFlags & BTCF_AtLast)!=0 ){
  60064. *pRes = -1;
  60065. return SQLITE_OK;
  60066. }
  60067. /* If the requested key is one more than the previous key, then
  60068. ** try to get there using sqlite3BtreeNext() rather than a full
  60069. ** binary search. This is an optimization only. The correct answer
  60070. ** is still obtained without this ase, only a little more slowely */
  60071. if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
  60072. *pRes = 0;
  60073. rc = sqlite3BtreeNext(pCur, pRes);
  60074. if( rc ) return rc;
  60075. if( *pRes==0 ){
  60076. getCellInfo(pCur);
  60077. if( pCur->info.nKey==intKey ){
  60078. return SQLITE_OK;
  60079. }
  60080. }
  60081. }
  60082. }
  60083. }
  60084. if( pIdxKey ){
  60085. xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
  60086. pIdxKey->errCode = 0;
  60087. assert( pIdxKey->default_rc==1
  60088. || pIdxKey->default_rc==0
  60089. || pIdxKey->default_rc==-1
  60090. );
  60091. }else{
  60092. xRecordCompare = 0; /* All keys are integers */
  60093. }
  60094. rc = moveToRoot(pCur);
  60095. if( rc ){
  60096. return rc;
  60097. }
  60098. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
  60099. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
  60100. assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
  60101. if( pCur->eState==CURSOR_INVALID ){
  60102. *pRes = -1;
  60103. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  60104. return SQLITE_OK;
  60105. }
  60106. assert( pCur->apPage[0]->intKey==pCur->curIntKey );
  60107. assert( pCur->curIntKey || pIdxKey );
  60108. for(;;){
  60109. int lwr, upr, idx, c;
  60110. Pgno chldPg;
  60111. MemPage *pPage = pCur->apPage[pCur->iPage];
  60112. u8 *pCell; /* Pointer to current cell in pPage */
  60113. /* pPage->nCell must be greater than zero. If this is the root-page
  60114. ** the cursor would have been INVALID above and this for(;;) loop
  60115. ** not run. If this is not the root-page, then the moveToChild() routine
  60116. ** would have already detected db corruption. Similarly, pPage must
  60117. ** be the right kind (index or table) of b-tree page. Otherwise
  60118. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  60119. assert( pPage->nCell>0 );
  60120. assert( pPage->intKey==(pIdxKey==0) );
  60121. lwr = 0;
  60122. upr = pPage->nCell-1;
  60123. assert( biasRight==0 || biasRight==1 );
  60124. idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
  60125. pCur->ix = (u16)idx;
  60126. if( xRecordCompare==0 ){
  60127. for(;;){
  60128. i64 nCellKey;
  60129. pCell = findCellPastPtr(pPage, idx);
  60130. if( pPage->intKeyLeaf ){
  60131. while( 0x80 <= *(pCell++) ){
  60132. if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
  60133. }
  60134. }
  60135. getVarint(pCell, (u64*)&nCellKey);
  60136. if( nCellKey<intKey ){
  60137. lwr = idx+1;
  60138. if( lwr>upr ){ c = -1; break; }
  60139. }else if( nCellKey>intKey ){
  60140. upr = idx-1;
  60141. if( lwr>upr ){ c = +1; break; }
  60142. }else{
  60143. assert( nCellKey==intKey );
  60144. pCur->ix = (u16)idx;
  60145. if( !pPage->leaf ){
  60146. lwr = idx;
  60147. goto moveto_next_layer;
  60148. }else{
  60149. pCur->curFlags |= BTCF_ValidNKey;
  60150. pCur->info.nKey = nCellKey;
  60151. pCur->info.nSize = 0;
  60152. *pRes = 0;
  60153. return SQLITE_OK;
  60154. }
  60155. }
  60156. assert( lwr+upr>=0 );
  60157. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
  60158. }
  60159. }else{
  60160. for(;;){
  60161. int nCell; /* Size of the pCell cell in bytes */
  60162. pCell = findCellPastPtr(pPage, idx);
  60163. /* The maximum supported page-size is 65536 bytes. This means that
  60164. ** the maximum number of record bytes stored on an index B-Tree
  60165. ** page is less than 16384 bytes and may be stored as a 2-byte
  60166. ** varint. This information is used to attempt to avoid parsing
  60167. ** the entire cell by checking for the cases where the record is
  60168. ** stored entirely within the b-tree page by inspecting the first
  60169. ** 2 bytes of the cell.
  60170. */
  60171. nCell = pCell[0];
  60172. if( nCell<=pPage->max1bytePayload ){
  60173. /* This branch runs if the record-size field of the cell is a
  60174. ** single byte varint and the record fits entirely on the main
  60175. ** b-tree page. */
  60176. testcase( pCell+nCell+1==pPage->aDataEnd );
  60177. c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  60178. }else if( !(pCell[1] & 0x80)
  60179. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  60180. ){
  60181. /* The record-size field is a 2 byte varint and the record
  60182. ** fits entirely on the main b-tree page. */
  60183. testcase( pCell+nCell+2==pPage->aDataEnd );
  60184. c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  60185. }else{
  60186. /* The record flows over onto one or more overflow pages. In
  60187. ** this case the whole cell needs to be parsed, a buffer allocated
  60188. ** and accessPayload() used to retrieve the record into the
  60189. ** buffer before VdbeRecordCompare() can be called.
  60190. **
  60191. ** If the record is corrupt, the xRecordCompare routine may read
  60192. ** up to two varints past the end of the buffer. An extra 18
  60193. ** bytes of padding is allocated at the end of the buffer in
  60194. ** case this happens. */
  60195. void *pCellKey;
  60196. u8 * const pCellBody = pCell - pPage->childPtrSize;
  60197. pPage->xParseCell(pPage, pCellBody, &pCur->info);
  60198. nCell = (int)pCur->info.nKey;
  60199. testcase( nCell<0 ); /* True if key size is 2^32 or more */
  60200. testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
  60201. testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
  60202. testcase( nCell==2 ); /* Minimum legal index key size */
  60203. if( nCell<2 ){
  60204. rc = SQLITE_CORRUPT_BKPT;
  60205. goto moveto_finish;
  60206. }
  60207. pCellKey = sqlite3Malloc( nCell+18 );
  60208. if( pCellKey==0 ){
  60209. rc = SQLITE_NOMEM_BKPT;
  60210. goto moveto_finish;
  60211. }
  60212. pCur->ix = (u16)idx;
  60213. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
  60214. pCur->curFlags &= ~BTCF_ValidOvfl;
  60215. if( rc ){
  60216. sqlite3_free(pCellKey);
  60217. goto moveto_finish;
  60218. }
  60219. c = xRecordCompare(nCell, pCellKey, pIdxKey);
  60220. sqlite3_free(pCellKey);
  60221. }
  60222. assert(
  60223. (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
  60224. && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
  60225. );
  60226. if( c<0 ){
  60227. lwr = idx+1;
  60228. }else if( c>0 ){
  60229. upr = idx-1;
  60230. }else{
  60231. assert( c==0 );
  60232. *pRes = 0;
  60233. rc = SQLITE_OK;
  60234. pCur->ix = (u16)idx;
  60235. if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
  60236. goto moveto_finish;
  60237. }
  60238. if( lwr>upr ) break;
  60239. assert( lwr+upr>=0 );
  60240. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
  60241. }
  60242. }
  60243. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  60244. assert( pPage->isInit );
  60245. if( pPage->leaf ){
  60246. assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
  60247. pCur->ix = (u16)idx;
  60248. *pRes = c;
  60249. rc = SQLITE_OK;
  60250. goto moveto_finish;
  60251. }
  60252. moveto_next_layer:
  60253. if( lwr>=pPage->nCell ){
  60254. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  60255. }else{
  60256. chldPg = get4byte(findCell(pPage, lwr));
  60257. }
  60258. pCur->ix = (u16)lwr;
  60259. rc = moveToChild(pCur, chldPg);
  60260. if( rc ) break;
  60261. }
  60262. moveto_finish:
  60263. pCur->info.nSize = 0;
  60264. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  60265. return rc;
  60266. }
  60267. /*
  60268. ** Return TRUE if the cursor is not pointing at an entry of the table.
  60269. **
  60270. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  60271. ** past the last entry in the table or sqlite3BtreePrev() moves past
  60272. ** the first entry. TRUE is also returned if the table is empty.
  60273. */
  60274. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  60275. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  60276. ** have been deleted? This API will need to change to return an error code
  60277. ** as well as the boolean result value.
  60278. */
  60279. return (CURSOR_VALID!=pCur->eState);
  60280. }
  60281. /*
  60282. ** Return an estimate for the number of rows in the table that pCur is
  60283. ** pointing to. Return a negative number if no estimate is currently
  60284. ** available.
  60285. */
  60286. SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
  60287. i64 n;
  60288. u8 i;
  60289. assert( cursorOwnsBtShared(pCur) );
  60290. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  60291. /* Currently this interface is only called by the OP_IfSmaller
  60292. ** opcode, and it that case the cursor will always be valid and
  60293. ** will always point to a leaf node. */
  60294. if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
  60295. if( NEVER(pCur->apPage[pCur->iPage]->leaf==0) ) return -1;
  60296. for(n=1, i=0; i<=pCur->iPage; i++){
  60297. n *= pCur->apPage[i]->nCell;
  60298. }
  60299. return n;
  60300. }
  60301. /*
  60302. ** Advance the cursor to the next entry in the database. If
  60303. ** successful then set *pRes=0. If the cursor
  60304. ** was already pointing to the last entry in the database before
  60305. ** this routine was called, then set *pRes=1.
  60306. **
  60307. ** The main entry point is sqlite3BtreeNext(). That routine is optimized
  60308. ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
  60309. ** to the next cell on the current page. The (slower) btreeNext() helper
  60310. ** routine is called when it is necessary to move to a different page or
  60311. ** to restore the cursor.
  60312. **
  60313. ** The calling function will set *pRes to 0 or 1. The initial *pRes value
  60314. ** will be 1 if the cursor being stepped corresponds to an SQL index and
  60315. ** if this routine could have been skipped if that SQL index had been
  60316. ** a unique index. Otherwise the caller will have set *pRes to zero.
  60317. ** Zero is the common case. The btree implementation is free to use the
  60318. ** initial *pRes value as a hint to improve performance, but the current
  60319. ** SQLite btree implementation does not. (Note that the comdb2 btree
  60320. ** implementation does use this hint, however.)
  60321. */
  60322. static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
  60323. int rc;
  60324. int idx;
  60325. MemPage *pPage;
  60326. assert( cursorOwnsBtShared(pCur) );
  60327. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  60328. assert( *pRes==0 );
  60329. if( pCur->eState!=CURSOR_VALID ){
  60330. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  60331. rc = restoreCursorPosition(pCur);
  60332. if( rc!=SQLITE_OK ){
  60333. return rc;
  60334. }
  60335. if( CURSOR_INVALID==pCur->eState ){
  60336. *pRes = 1;
  60337. return SQLITE_OK;
  60338. }
  60339. if( pCur->skipNext ){
  60340. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  60341. pCur->eState = CURSOR_VALID;
  60342. if( pCur->skipNext>0 ){
  60343. pCur->skipNext = 0;
  60344. return SQLITE_OK;
  60345. }
  60346. pCur->skipNext = 0;
  60347. }
  60348. }
  60349. pPage = pCur->apPage[pCur->iPage];
  60350. idx = ++pCur->ix;
  60351. assert( pPage->isInit );
  60352. /* If the database file is corrupt, it is possible for the value of idx
  60353. ** to be invalid here. This can only occur if a second cursor modifies
  60354. ** the page while cursor pCur is holding a reference to it. Which can
  60355. ** only happen if the database is corrupt in such a way as to link the
  60356. ** page into more than one b-tree structure. */
  60357. testcase( idx>pPage->nCell );
  60358. if( idx>=pPage->nCell ){
  60359. if( !pPage->leaf ){
  60360. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  60361. if( rc ) return rc;
  60362. return moveToLeftmost(pCur);
  60363. }
  60364. do{
  60365. if( pCur->iPage==0 ){
  60366. *pRes = 1;
  60367. pCur->eState = CURSOR_INVALID;
  60368. return SQLITE_OK;
  60369. }
  60370. moveToParent(pCur);
  60371. pPage = pCur->apPage[pCur->iPage];
  60372. }while( pCur->ix>=pPage->nCell );
  60373. if( pPage->intKey ){
  60374. return sqlite3BtreeNext(pCur, pRes);
  60375. }else{
  60376. return SQLITE_OK;
  60377. }
  60378. }
  60379. if( pPage->leaf ){
  60380. return SQLITE_OK;
  60381. }else{
  60382. return moveToLeftmost(pCur);
  60383. }
  60384. }
  60385. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  60386. MemPage *pPage;
  60387. assert( cursorOwnsBtShared(pCur) );
  60388. assert( pRes!=0 );
  60389. assert( *pRes==0 || *pRes==1 );
  60390. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  60391. pCur->info.nSize = 0;
  60392. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  60393. *pRes = 0;
  60394. if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
  60395. pPage = pCur->apPage[pCur->iPage];
  60396. if( (++pCur->ix)>=pPage->nCell ){
  60397. pCur->ix--;
  60398. return btreeNext(pCur, pRes);
  60399. }
  60400. if( pPage->leaf ){
  60401. return SQLITE_OK;
  60402. }else{
  60403. return moveToLeftmost(pCur);
  60404. }
  60405. }
  60406. /*
  60407. ** Step the cursor to the back to the previous entry in the database. If
  60408. ** successful then set *pRes=0. If the cursor
  60409. ** was already pointing to the first entry in the database before
  60410. ** this routine was called, then set *pRes=1.
  60411. **
  60412. ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
  60413. ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
  60414. ** to the previous cell on the current page. The (slower) btreePrevious()
  60415. ** helper routine is called when it is necessary to move to a different page
  60416. ** or to restore the cursor.
  60417. **
  60418. ** The calling function will set *pRes to 0 or 1. The initial *pRes value
  60419. ** will be 1 if the cursor being stepped corresponds to an SQL index and
  60420. ** if this routine could have been skipped if that SQL index had been
  60421. ** a unique index. Otherwise the caller will have set *pRes to zero.
  60422. ** Zero is the common case. The btree implementation is free to use the
  60423. ** initial *pRes value as a hint to improve performance, but the current
  60424. ** SQLite btree implementation does not. (Note that the comdb2 btree
  60425. ** implementation does use this hint, however.)
  60426. */
  60427. static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
  60428. int rc;
  60429. MemPage *pPage;
  60430. assert( cursorOwnsBtShared(pCur) );
  60431. assert( pRes!=0 );
  60432. assert( *pRes==0 );
  60433. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  60434. assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
  60435. assert( pCur->info.nSize==0 );
  60436. if( pCur->eState!=CURSOR_VALID ){
  60437. rc = restoreCursorPosition(pCur);
  60438. if( rc!=SQLITE_OK ){
  60439. return rc;
  60440. }
  60441. if( CURSOR_INVALID==pCur->eState ){
  60442. *pRes = 1;
  60443. return SQLITE_OK;
  60444. }
  60445. if( pCur->skipNext ){
  60446. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  60447. pCur->eState = CURSOR_VALID;
  60448. if( pCur->skipNext<0 ){
  60449. pCur->skipNext = 0;
  60450. return SQLITE_OK;
  60451. }
  60452. pCur->skipNext = 0;
  60453. }
  60454. }
  60455. pPage = pCur->apPage[pCur->iPage];
  60456. assert( pPage->isInit );
  60457. if( !pPage->leaf ){
  60458. int idx = pCur->ix;
  60459. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  60460. if( rc ) return rc;
  60461. rc = moveToRightmost(pCur);
  60462. }else{
  60463. while( pCur->ix==0 ){
  60464. if( pCur->iPage==0 ){
  60465. pCur->eState = CURSOR_INVALID;
  60466. *pRes = 1;
  60467. return SQLITE_OK;
  60468. }
  60469. moveToParent(pCur);
  60470. }
  60471. assert( pCur->info.nSize==0 );
  60472. assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
  60473. pCur->ix--;
  60474. pPage = pCur->apPage[pCur->iPage];
  60475. if( pPage->intKey && !pPage->leaf ){
  60476. rc = sqlite3BtreePrevious(pCur, pRes);
  60477. }else{
  60478. rc = SQLITE_OK;
  60479. }
  60480. }
  60481. return rc;
  60482. }
  60483. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  60484. assert( cursorOwnsBtShared(pCur) );
  60485. assert( pRes!=0 );
  60486. assert( *pRes==0 || *pRes==1 );
  60487. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  60488. *pRes = 0;
  60489. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
  60490. pCur->info.nSize = 0;
  60491. if( pCur->eState!=CURSOR_VALID
  60492. || pCur->ix==0
  60493. || pCur->apPage[pCur->iPage]->leaf==0
  60494. ){
  60495. return btreePrevious(pCur, pRes);
  60496. }
  60497. pCur->ix--;
  60498. return SQLITE_OK;
  60499. }
  60500. /*
  60501. ** Allocate a new page from the database file.
  60502. **
  60503. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  60504. ** has already been called on the new page.) The new page has also
  60505. ** been referenced and the calling routine is responsible for calling
  60506. ** sqlite3PagerUnref() on the new page when it is done.
  60507. **
  60508. ** SQLITE_OK is returned on success. Any other return value indicates
  60509. ** an error. *ppPage is set to NULL in the event of an error.
  60510. **
  60511. ** If the "nearby" parameter is not 0, then an effort is made to
  60512. ** locate a page close to the page number "nearby". This can be used in an
  60513. ** attempt to keep related pages close to each other in the database file,
  60514. ** which in turn can make database access faster.
  60515. **
  60516. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  60517. ** anywhere on the free-list, then it is guaranteed to be returned. If
  60518. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  60519. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  60520. ** are no restrictions on which page is returned.
  60521. */
  60522. static int allocateBtreePage(
  60523. BtShared *pBt, /* The btree */
  60524. MemPage **ppPage, /* Store pointer to the allocated page here */
  60525. Pgno *pPgno, /* Store the page number here */
  60526. Pgno nearby, /* Search for a page near this one */
  60527. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  60528. ){
  60529. MemPage *pPage1;
  60530. int rc;
  60531. u32 n; /* Number of pages on the freelist */
  60532. u32 k; /* Number of leaves on the trunk of the freelist */
  60533. MemPage *pTrunk = 0;
  60534. MemPage *pPrevTrunk = 0;
  60535. Pgno mxPage; /* Total size of the database file */
  60536. assert( sqlite3_mutex_held(pBt->mutex) );
  60537. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  60538. pPage1 = pBt->pPage1;
  60539. mxPage = btreePagecount(pBt);
  60540. /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
  60541. ** stores stores the total number of pages on the freelist. */
  60542. n = get4byte(&pPage1->aData[36]);
  60543. testcase( n==mxPage-1 );
  60544. if( n>=mxPage ){
  60545. return SQLITE_CORRUPT_BKPT;
  60546. }
  60547. if( n>0 ){
  60548. /* There are pages on the freelist. Reuse one of those pages. */
  60549. Pgno iTrunk;
  60550. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  60551. u32 nSearch = 0; /* Count of the number of search attempts */
  60552. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  60553. ** shows that the page 'nearby' is somewhere on the free-list, then
  60554. ** the entire-list will be searched for that page.
  60555. */
  60556. #ifndef SQLITE_OMIT_AUTOVACUUM
  60557. if( eMode==BTALLOC_EXACT ){
  60558. if( nearby<=mxPage ){
  60559. u8 eType;
  60560. assert( nearby>0 );
  60561. assert( pBt->autoVacuum );
  60562. rc = ptrmapGet(pBt, nearby, &eType, 0);
  60563. if( rc ) return rc;
  60564. if( eType==PTRMAP_FREEPAGE ){
  60565. searchList = 1;
  60566. }
  60567. }
  60568. }else if( eMode==BTALLOC_LE ){
  60569. searchList = 1;
  60570. }
  60571. #endif
  60572. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  60573. ** first free-list trunk page. iPrevTrunk is initially 1.
  60574. */
  60575. rc = sqlite3PagerWrite(pPage1->pDbPage);
  60576. if( rc ) return rc;
  60577. put4byte(&pPage1->aData[36], n-1);
  60578. /* The code within this loop is run only once if the 'searchList' variable
  60579. ** is not true. Otherwise, it runs once for each trunk-page on the
  60580. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  60581. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  60582. */
  60583. do {
  60584. pPrevTrunk = pTrunk;
  60585. if( pPrevTrunk ){
  60586. /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
  60587. ** is the page number of the next freelist trunk page in the list or
  60588. ** zero if this is the last freelist trunk page. */
  60589. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  60590. }else{
  60591. /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
  60592. ** stores the page number of the first page of the freelist, or zero if
  60593. ** the freelist is empty. */
  60594. iTrunk = get4byte(&pPage1->aData[32]);
  60595. }
  60596. testcase( iTrunk==mxPage );
  60597. if( iTrunk>mxPage || nSearch++ > n ){
  60598. rc = SQLITE_CORRUPT_BKPT;
  60599. }else{
  60600. rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
  60601. }
  60602. if( rc ){
  60603. pTrunk = 0;
  60604. goto end_allocate_page;
  60605. }
  60606. assert( pTrunk!=0 );
  60607. assert( pTrunk->aData!=0 );
  60608. /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
  60609. ** is the number of leaf page pointers to follow. */
  60610. k = get4byte(&pTrunk->aData[4]);
  60611. if( k==0 && !searchList ){
  60612. /* The trunk has no leaves and the list is not being searched.
  60613. ** So extract the trunk page itself and use it as the newly
  60614. ** allocated page */
  60615. assert( pPrevTrunk==0 );
  60616. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  60617. if( rc ){
  60618. goto end_allocate_page;
  60619. }
  60620. *pPgno = iTrunk;
  60621. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  60622. *ppPage = pTrunk;
  60623. pTrunk = 0;
  60624. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  60625. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  60626. /* Value of k is out of range. Database corruption */
  60627. rc = SQLITE_CORRUPT_BKPT;
  60628. goto end_allocate_page;
  60629. #ifndef SQLITE_OMIT_AUTOVACUUM
  60630. }else if( searchList
  60631. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  60632. ){
  60633. /* The list is being searched and this trunk page is the page
  60634. ** to allocate, regardless of whether it has leaves.
  60635. */
  60636. *pPgno = iTrunk;
  60637. *ppPage = pTrunk;
  60638. searchList = 0;
  60639. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  60640. if( rc ){
  60641. goto end_allocate_page;
  60642. }
  60643. if( k==0 ){
  60644. if( !pPrevTrunk ){
  60645. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  60646. }else{
  60647. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  60648. if( rc!=SQLITE_OK ){
  60649. goto end_allocate_page;
  60650. }
  60651. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  60652. }
  60653. }else{
  60654. /* The trunk page is required by the caller but it contains
  60655. ** pointers to free-list leaves. The first leaf becomes a trunk
  60656. ** page in this case.
  60657. */
  60658. MemPage *pNewTrunk;
  60659. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  60660. if( iNewTrunk>mxPage ){
  60661. rc = SQLITE_CORRUPT_BKPT;
  60662. goto end_allocate_page;
  60663. }
  60664. testcase( iNewTrunk==mxPage );
  60665. rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
  60666. if( rc!=SQLITE_OK ){
  60667. goto end_allocate_page;
  60668. }
  60669. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  60670. if( rc!=SQLITE_OK ){
  60671. releasePage(pNewTrunk);
  60672. goto end_allocate_page;
  60673. }
  60674. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  60675. put4byte(&pNewTrunk->aData[4], k-1);
  60676. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  60677. releasePage(pNewTrunk);
  60678. if( !pPrevTrunk ){
  60679. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  60680. put4byte(&pPage1->aData[32], iNewTrunk);
  60681. }else{
  60682. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  60683. if( rc ){
  60684. goto end_allocate_page;
  60685. }
  60686. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  60687. }
  60688. }
  60689. pTrunk = 0;
  60690. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  60691. #endif
  60692. }else if( k>0 ){
  60693. /* Extract a leaf from the trunk */
  60694. u32 closest;
  60695. Pgno iPage;
  60696. unsigned char *aData = pTrunk->aData;
  60697. if( nearby>0 ){
  60698. u32 i;
  60699. closest = 0;
  60700. if( eMode==BTALLOC_LE ){
  60701. for(i=0; i<k; i++){
  60702. iPage = get4byte(&aData[8+i*4]);
  60703. if( iPage<=nearby ){
  60704. closest = i;
  60705. break;
  60706. }
  60707. }
  60708. }else{
  60709. int dist;
  60710. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  60711. for(i=1; i<k; i++){
  60712. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  60713. if( d2<dist ){
  60714. closest = i;
  60715. dist = d2;
  60716. }
  60717. }
  60718. }
  60719. }else{
  60720. closest = 0;
  60721. }
  60722. iPage = get4byte(&aData[8+closest*4]);
  60723. testcase( iPage==mxPage );
  60724. if( iPage>mxPage ){
  60725. rc = SQLITE_CORRUPT_BKPT;
  60726. goto end_allocate_page;
  60727. }
  60728. testcase( iPage==mxPage );
  60729. if( !searchList
  60730. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  60731. ){
  60732. int noContent;
  60733. *pPgno = iPage;
  60734. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  60735. ": %d more free pages\n",
  60736. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  60737. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  60738. if( rc ) goto end_allocate_page;
  60739. if( closest<k-1 ){
  60740. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  60741. }
  60742. put4byte(&aData[4], k-1);
  60743. noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
  60744. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
  60745. if( rc==SQLITE_OK ){
  60746. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  60747. if( rc!=SQLITE_OK ){
  60748. releasePage(*ppPage);
  60749. *ppPage = 0;
  60750. }
  60751. }
  60752. searchList = 0;
  60753. }
  60754. }
  60755. releasePage(pPrevTrunk);
  60756. pPrevTrunk = 0;
  60757. }while( searchList );
  60758. }else{
  60759. /* There are no pages on the freelist, so append a new page to the
  60760. ** database image.
  60761. **
  60762. ** Normally, new pages allocated by this block can be requested from the
  60763. ** pager layer with the 'no-content' flag set. This prevents the pager
  60764. ** from trying to read the pages content from disk. However, if the
  60765. ** current transaction has already run one or more incremental-vacuum
  60766. ** steps, then the page we are about to allocate may contain content
  60767. ** that is required in the event of a rollback. In this case, do
  60768. ** not set the no-content flag. This causes the pager to load and journal
  60769. ** the current page content before overwriting it.
  60770. **
  60771. ** Note that the pager will not actually attempt to load or journal
  60772. ** content for any page that really does lie past the end of the database
  60773. ** file on disk. So the effects of disabling the no-content optimization
  60774. ** here are confined to those pages that lie between the end of the
  60775. ** database image and the end of the database file.
  60776. */
  60777. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
  60778. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  60779. if( rc ) return rc;
  60780. pBt->nPage++;
  60781. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  60782. #ifndef SQLITE_OMIT_AUTOVACUUM
  60783. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  60784. /* If *pPgno refers to a pointer-map page, allocate two new pages
  60785. ** at the end of the file instead of one. The first allocated page
  60786. ** becomes a new pointer-map page, the second is used by the caller.
  60787. */
  60788. MemPage *pPg = 0;
  60789. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  60790. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  60791. rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
  60792. if( rc==SQLITE_OK ){
  60793. rc = sqlite3PagerWrite(pPg->pDbPage);
  60794. releasePage(pPg);
  60795. }
  60796. if( rc ) return rc;
  60797. pBt->nPage++;
  60798. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  60799. }
  60800. #endif
  60801. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  60802. *pPgno = pBt->nPage;
  60803. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  60804. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
  60805. if( rc ) return rc;
  60806. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  60807. if( rc!=SQLITE_OK ){
  60808. releasePage(*ppPage);
  60809. *ppPage = 0;
  60810. }
  60811. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  60812. }
  60813. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  60814. end_allocate_page:
  60815. releasePage(pTrunk);
  60816. releasePage(pPrevTrunk);
  60817. assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
  60818. assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
  60819. return rc;
  60820. }
  60821. /*
  60822. ** This function is used to add page iPage to the database file free-list.
  60823. ** It is assumed that the page is not already a part of the free-list.
  60824. **
  60825. ** The value passed as the second argument to this function is optional.
  60826. ** If the caller happens to have a pointer to the MemPage object
  60827. ** corresponding to page iPage handy, it may pass it as the second value.
  60828. ** Otherwise, it may pass NULL.
  60829. **
  60830. ** If a pointer to a MemPage object is passed as the second argument,
  60831. ** its reference count is not altered by this function.
  60832. */
  60833. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  60834. MemPage *pTrunk = 0; /* Free-list trunk page */
  60835. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  60836. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  60837. MemPage *pPage; /* Page being freed. May be NULL. */
  60838. int rc; /* Return Code */
  60839. int nFree; /* Initial number of pages on free-list */
  60840. assert( sqlite3_mutex_held(pBt->mutex) );
  60841. assert( CORRUPT_DB || iPage>1 );
  60842. assert( !pMemPage || pMemPage->pgno==iPage );
  60843. if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
  60844. if( pMemPage ){
  60845. pPage = pMemPage;
  60846. sqlite3PagerRef(pPage->pDbPage);
  60847. }else{
  60848. pPage = btreePageLookup(pBt, iPage);
  60849. }
  60850. /* Increment the free page count on pPage1 */
  60851. rc = sqlite3PagerWrite(pPage1->pDbPage);
  60852. if( rc ) goto freepage_out;
  60853. nFree = get4byte(&pPage1->aData[36]);
  60854. put4byte(&pPage1->aData[36], nFree+1);
  60855. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  60856. /* If the secure_delete option is enabled, then
  60857. ** always fully overwrite deleted information with zeros.
  60858. */
  60859. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  60860. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  60861. ){
  60862. goto freepage_out;
  60863. }
  60864. memset(pPage->aData, 0, pPage->pBt->pageSize);
  60865. }
  60866. /* If the database supports auto-vacuum, write an entry in the pointer-map
  60867. ** to indicate that the page is free.
  60868. */
  60869. if( ISAUTOVACUUM ){
  60870. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  60871. if( rc ) goto freepage_out;
  60872. }
  60873. /* Now manipulate the actual database free-list structure. There are two
  60874. ** possibilities. If the free-list is currently empty, or if the first
  60875. ** trunk page in the free-list is full, then this page will become a
  60876. ** new free-list trunk page. Otherwise, it will become a leaf of the
  60877. ** first trunk page in the current free-list. This block tests if it
  60878. ** is possible to add the page as a new free-list leaf.
  60879. */
  60880. if( nFree!=0 ){
  60881. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  60882. iTrunk = get4byte(&pPage1->aData[32]);
  60883. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  60884. if( rc!=SQLITE_OK ){
  60885. goto freepage_out;
  60886. }
  60887. nLeaf = get4byte(&pTrunk->aData[4]);
  60888. assert( pBt->usableSize>32 );
  60889. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  60890. rc = SQLITE_CORRUPT_BKPT;
  60891. goto freepage_out;
  60892. }
  60893. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  60894. /* In this case there is room on the trunk page to insert the page
  60895. ** being freed as a new leaf.
  60896. **
  60897. ** Note that the trunk page is not really full until it contains
  60898. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  60899. ** coded. But due to a coding error in versions of SQLite prior to
  60900. ** 3.6.0, databases with freelist trunk pages holding more than
  60901. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  60902. ** to maintain backwards compatibility with older versions of SQLite,
  60903. ** we will continue to restrict the number of entries to usableSize/4 - 8
  60904. ** for now. At some point in the future (once everyone has upgraded
  60905. ** to 3.6.0 or later) we should consider fixing the conditional above
  60906. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  60907. **
  60908. ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
  60909. ** avoid using the last six entries in the freelist trunk page array in
  60910. ** order that database files created by newer versions of SQLite can be
  60911. ** read by older versions of SQLite.
  60912. */
  60913. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  60914. if( rc==SQLITE_OK ){
  60915. put4byte(&pTrunk->aData[4], nLeaf+1);
  60916. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  60917. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  60918. sqlite3PagerDontWrite(pPage->pDbPage);
  60919. }
  60920. rc = btreeSetHasContent(pBt, iPage);
  60921. }
  60922. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  60923. goto freepage_out;
  60924. }
  60925. }
  60926. /* If control flows to this point, then it was not possible to add the
  60927. ** the page being freed as a leaf page of the first trunk in the free-list.
  60928. ** Possibly because the free-list is empty, or possibly because the
  60929. ** first trunk in the free-list is full. Either way, the page being freed
  60930. ** will become the new first trunk page in the free-list.
  60931. */
  60932. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  60933. goto freepage_out;
  60934. }
  60935. rc = sqlite3PagerWrite(pPage->pDbPage);
  60936. if( rc!=SQLITE_OK ){
  60937. goto freepage_out;
  60938. }
  60939. put4byte(pPage->aData, iTrunk);
  60940. put4byte(&pPage->aData[4], 0);
  60941. put4byte(&pPage1->aData[32], iPage);
  60942. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  60943. freepage_out:
  60944. if( pPage ){
  60945. pPage->isInit = 0;
  60946. }
  60947. releasePage(pPage);
  60948. releasePage(pTrunk);
  60949. return rc;
  60950. }
  60951. static void freePage(MemPage *pPage, int *pRC){
  60952. if( (*pRC)==SQLITE_OK ){
  60953. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  60954. }
  60955. }
  60956. /*
  60957. ** Free any overflow pages associated with the given Cell. Write the
  60958. ** local Cell size (the number of bytes on the original page, omitting
  60959. ** overflow) into *pnSize.
  60960. */
  60961. static int clearCell(
  60962. MemPage *pPage, /* The page that contains the Cell */
  60963. unsigned char *pCell, /* First byte of the Cell */
  60964. CellInfo *pInfo /* Size information about the cell */
  60965. ){
  60966. BtShared *pBt = pPage->pBt;
  60967. Pgno ovflPgno;
  60968. int rc;
  60969. int nOvfl;
  60970. u32 ovflPageSize;
  60971. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60972. pPage->xParseCell(pPage, pCell, pInfo);
  60973. if( pInfo->nLocal==pInfo->nPayload ){
  60974. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  60975. }
  60976. if( pCell+pInfo->nSize-1 > pPage->aData+pPage->maskPage ){
  60977. return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
  60978. }
  60979. ovflPgno = get4byte(pCell + pInfo->nSize - 4);
  60980. assert( pBt->usableSize > 4 );
  60981. ovflPageSize = pBt->usableSize - 4;
  60982. nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
  60983. assert( nOvfl>0 ||
  60984. (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
  60985. );
  60986. while( nOvfl-- ){
  60987. Pgno iNext = 0;
  60988. MemPage *pOvfl = 0;
  60989. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  60990. /* 0 is not a legal page number and page 1 cannot be an
  60991. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  60992. ** file the database must be corrupt. */
  60993. return SQLITE_CORRUPT_BKPT;
  60994. }
  60995. if( nOvfl ){
  60996. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  60997. if( rc ) return rc;
  60998. }
  60999. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  61000. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  61001. ){
  61002. /* There is no reason any cursor should have an outstanding reference
  61003. ** to an overflow page belonging to a cell that is being deleted/updated.
  61004. ** So if there exists more than one reference to this page, then it
  61005. ** must not really be an overflow page and the database must be corrupt.
  61006. ** It is helpful to detect this before calling freePage2(), as
  61007. ** freePage2() may zero the page contents if secure-delete mode is
  61008. ** enabled. If this 'overflow' page happens to be a page that the
  61009. ** caller is iterating through or using in some other way, this
  61010. ** can be problematic.
  61011. */
  61012. rc = SQLITE_CORRUPT_BKPT;
  61013. }else{
  61014. rc = freePage2(pBt, pOvfl, ovflPgno);
  61015. }
  61016. if( pOvfl ){
  61017. sqlite3PagerUnref(pOvfl->pDbPage);
  61018. }
  61019. if( rc ) return rc;
  61020. ovflPgno = iNext;
  61021. }
  61022. return SQLITE_OK;
  61023. }
  61024. /*
  61025. ** Create the byte sequence used to represent a cell on page pPage
  61026. ** and write that byte sequence into pCell[]. Overflow pages are
  61027. ** allocated and filled in as necessary. The calling procedure
  61028. ** is responsible for making sure sufficient space has been allocated
  61029. ** for pCell[].
  61030. **
  61031. ** Note that pCell does not necessary need to point to the pPage->aData
  61032. ** area. pCell might point to some temporary storage. The cell will
  61033. ** be constructed in this temporary area then copied into pPage->aData
  61034. ** later.
  61035. */
  61036. static int fillInCell(
  61037. MemPage *pPage, /* The page that contains the cell */
  61038. unsigned char *pCell, /* Complete text of the cell */
  61039. const BtreePayload *pX, /* Payload with which to construct the cell */
  61040. int *pnSize /* Write cell size here */
  61041. ){
  61042. int nPayload;
  61043. const u8 *pSrc;
  61044. int nSrc, n, rc;
  61045. int spaceLeft;
  61046. MemPage *pOvfl = 0;
  61047. MemPage *pToRelease = 0;
  61048. unsigned char *pPrior;
  61049. unsigned char *pPayload;
  61050. BtShared *pBt = pPage->pBt;
  61051. Pgno pgnoOvfl = 0;
  61052. int nHeader;
  61053. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61054. /* pPage is not necessarily writeable since pCell might be auxiliary
  61055. ** buffer space that is separate from the pPage buffer area */
  61056. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  61057. || sqlite3PagerIswriteable(pPage->pDbPage) );
  61058. /* Fill in the header. */
  61059. nHeader = pPage->childPtrSize;
  61060. if( pPage->intKey ){
  61061. nPayload = pX->nData + pX->nZero;
  61062. pSrc = pX->pData;
  61063. nSrc = pX->nData;
  61064. assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
  61065. nHeader += putVarint32(&pCell[nHeader], nPayload);
  61066. nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
  61067. }else{
  61068. assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
  61069. nSrc = nPayload = (int)pX->nKey;
  61070. pSrc = pX->pKey;
  61071. nHeader += putVarint32(&pCell[nHeader], nPayload);
  61072. }
  61073. /* Fill in the payload */
  61074. if( nPayload<=pPage->maxLocal ){
  61075. n = nHeader + nPayload;
  61076. testcase( n==3 );
  61077. testcase( n==4 );
  61078. if( n<4 ) n = 4;
  61079. *pnSize = n;
  61080. spaceLeft = nPayload;
  61081. pPrior = pCell;
  61082. }else{
  61083. int mn = pPage->minLocal;
  61084. n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
  61085. testcase( n==pPage->maxLocal );
  61086. testcase( n==pPage->maxLocal+1 );
  61087. if( n > pPage->maxLocal ) n = mn;
  61088. spaceLeft = n;
  61089. *pnSize = n + nHeader + 4;
  61090. pPrior = &pCell[nHeader+n];
  61091. }
  61092. pPayload = &pCell[nHeader];
  61093. /* At this point variables should be set as follows:
  61094. **
  61095. ** nPayload Total payload size in bytes
  61096. ** pPayload Begin writing payload here
  61097. ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
  61098. ** that means content must spill into overflow pages.
  61099. ** *pnSize Size of the local cell (not counting overflow pages)
  61100. ** pPrior Where to write the pgno of the first overflow page
  61101. **
  61102. ** Use a call to btreeParseCellPtr() to verify that the values above
  61103. ** were computed correctly.
  61104. */
  61105. #ifdef SQLITE_DEBUG
  61106. {
  61107. CellInfo info;
  61108. pPage->xParseCell(pPage, pCell, &info);
  61109. assert( nHeader==(int)(info.pPayload - pCell) );
  61110. assert( info.nKey==pX->nKey );
  61111. assert( *pnSize == info.nSize );
  61112. assert( spaceLeft == info.nLocal );
  61113. }
  61114. #endif
  61115. /* Write the payload into the local Cell and any extra into overflow pages */
  61116. while( nPayload>0 ){
  61117. if( spaceLeft==0 ){
  61118. #ifndef SQLITE_OMIT_AUTOVACUUM
  61119. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  61120. if( pBt->autoVacuum ){
  61121. do{
  61122. pgnoOvfl++;
  61123. } while(
  61124. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  61125. );
  61126. }
  61127. #endif
  61128. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  61129. #ifndef SQLITE_OMIT_AUTOVACUUM
  61130. /* If the database supports auto-vacuum, and the second or subsequent
  61131. ** overflow page is being allocated, add an entry to the pointer-map
  61132. ** for that page now.
  61133. **
  61134. ** If this is the first overflow page, then write a partial entry
  61135. ** to the pointer-map. If we write nothing to this pointer-map slot,
  61136. ** then the optimistic overflow chain processing in clearCell()
  61137. ** may misinterpret the uninitialized values and delete the
  61138. ** wrong pages from the database.
  61139. */
  61140. if( pBt->autoVacuum && rc==SQLITE_OK ){
  61141. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  61142. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  61143. if( rc ){
  61144. releasePage(pOvfl);
  61145. }
  61146. }
  61147. #endif
  61148. if( rc ){
  61149. releasePage(pToRelease);
  61150. return rc;
  61151. }
  61152. /* If pToRelease is not zero than pPrior points into the data area
  61153. ** of pToRelease. Make sure pToRelease is still writeable. */
  61154. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  61155. /* If pPrior is part of the data area of pPage, then make sure pPage
  61156. ** is still writeable */
  61157. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  61158. || sqlite3PagerIswriteable(pPage->pDbPage) );
  61159. put4byte(pPrior, pgnoOvfl);
  61160. releasePage(pToRelease);
  61161. pToRelease = pOvfl;
  61162. pPrior = pOvfl->aData;
  61163. put4byte(pPrior, 0);
  61164. pPayload = &pOvfl->aData[4];
  61165. spaceLeft = pBt->usableSize - 4;
  61166. }
  61167. n = nPayload;
  61168. if( n>spaceLeft ) n = spaceLeft;
  61169. /* If pToRelease is not zero than pPayload points into the data area
  61170. ** of pToRelease. Make sure pToRelease is still writeable. */
  61171. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  61172. /* If pPayload is part of the data area of pPage, then make sure pPage
  61173. ** is still writeable */
  61174. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  61175. || sqlite3PagerIswriteable(pPage->pDbPage) );
  61176. if( nSrc>0 ){
  61177. if( n>nSrc ) n = nSrc;
  61178. assert( pSrc );
  61179. memcpy(pPayload, pSrc, n);
  61180. }else{
  61181. memset(pPayload, 0, n);
  61182. }
  61183. nPayload -= n;
  61184. pPayload += n;
  61185. pSrc += n;
  61186. nSrc -= n;
  61187. spaceLeft -= n;
  61188. }
  61189. releasePage(pToRelease);
  61190. return SQLITE_OK;
  61191. }
  61192. /*
  61193. ** Remove the i-th cell from pPage. This routine effects pPage only.
  61194. ** The cell content is not freed or deallocated. It is assumed that
  61195. ** the cell content has been copied someplace else. This routine just
  61196. ** removes the reference to the cell from pPage.
  61197. **
  61198. ** "sz" must be the number of bytes in the cell.
  61199. */
  61200. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  61201. u32 pc; /* Offset to cell content of cell being deleted */
  61202. u8 *data; /* pPage->aData */
  61203. u8 *ptr; /* Used to move bytes around within data[] */
  61204. int rc; /* The return code */
  61205. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  61206. if( *pRC ) return;
  61207. assert( idx>=0 && idx<pPage->nCell );
  61208. assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
  61209. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  61210. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61211. data = pPage->aData;
  61212. ptr = &pPage->aCellIdx[2*idx];
  61213. pc = get2byte(ptr);
  61214. hdr = pPage->hdrOffset;
  61215. testcase( pc==get2byte(&data[hdr+5]) );
  61216. testcase( pc+sz==pPage->pBt->usableSize );
  61217. if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
  61218. *pRC = SQLITE_CORRUPT_BKPT;
  61219. return;
  61220. }
  61221. rc = freeSpace(pPage, pc, sz);
  61222. if( rc ){
  61223. *pRC = rc;
  61224. return;
  61225. }
  61226. pPage->nCell--;
  61227. if( pPage->nCell==0 ){
  61228. memset(&data[hdr+1], 0, 4);
  61229. data[hdr+7] = 0;
  61230. put2byte(&data[hdr+5], pPage->pBt->usableSize);
  61231. pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
  61232. - pPage->childPtrSize - 8;
  61233. }else{
  61234. memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
  61235. put2byte(&data[hdr+3], pPage->nCell);
  61236. pPage->nFree += 2;
  61237. }
  61238. }
  61239. /*
  61240. ** Insert a new cell on pPage at cell index "i". pCell points to the
  61241. ** content of the cell.
  61242. **
  61243. ** If the cell content will fit on the page, then put it there. If it
  61244. ** will not fit, then make a copy of the cell content into pTemp if
  61245. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  61246. ** in pPage->apOvfl[] and make it point to the cell content (either
  61247. ** in pTemp or the original pCell) and also record its index.
  61248. ** Allocating a new entry in pPage->aCell[] implies that
  61249. ** pPage->nOverflow is incremented.
  61250. **
  61251. ** *pRC must be SQLITE_OK when this routine is called.
  61252. */
  61253. static void insertCell(
  61254. MemPage *pPage, /* Page into which we are copying */
  61255. int i, /* New cell becomes the i-th cell of the page */
  61256. u8 *pCell, /* Content of the new cell */
  61257. int sz, /* Bytes of content in pCell */
  61258. u8 *pTemp, /* Temp storage space for pCell, if needed */
  61259. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  61260. int *pRC /* Read and write return code from here */
  61261. ){
  61262. int idx = 0; /* Where to write new cell content in data[] */
  61263. int j; /* Loop counter */
  61264. u8 *data; /* The content of the whole page */
  61265. u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
  61266. assert( *pRC==SQLITE_OK );
  61267. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  61268. assert( MX_CELL(pPage->pBt)<=10921 );
  61269. assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  61270. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  61271. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  61272. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61273. /* The cell should normally be sized correctly. However, when moving a
  61274. ** malformed cell from a leaf page to an interior page, if the cell size
  61275. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  61276. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  61277. ** the term after the || in the following assert(). */
  61278. assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
  61279. if( pPage->nOverflow || sz+2>pPage->nFree ){
  61280. if( pTemp ){
  61281. memcpy(pTemp, pCell, sz);
  61282. pCell = pTemp;
  61283. }
  61284. if( iChild ){
  61285. put4byte(pCell, iChild);
  61286. }
  61287. j = pPage->nOverflow++;
  61288. /* Comparison against ArraySize-1 since we hold back one extra slot
  61289. ** as a contingency. In other words, never need more than 3 overflow
  61290. ** slots but 4 are allocated, just to be safe. */
  61291. assert( j < ArraySize(pPage->apOvfl)-1 );
  61292. pPage->apOvfl[j] = pCell;
  61293. pPage->aiOvfl[j] = (u16)i;
  61294. /* When multiple overflows occur, they are always sequential and in
  61295. ** sorted order. This invariants arise because multiple overflows can
  61296. ** only occur when inserting divider cells into the parent page during
  61297. ** balancing, and the dividers are adjacent and sorted.
  61298. */
  61299. assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
  61300. assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
  61301. }else{
  61302. int rc = sqlite3PagerWrite(pPage->pDbPage);
  61303. if( rc!=SQLITE_OK ){
  61304. *pRC = rc;
  61305. return;
  61306. }
  61307. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  61308. data = pPage->aData;
  61309. assert( &data[pPage->cellOffset]==pPage->aCellIdx );
  61310. rc = allocateSpace(pPage, sz, &idx);
  61311. if( rc ){ *pRC = rc; return; }
  61312. /* The allocateSpace() routine guarantees the following properties
  61313. ** if it returns successfully */
  61314. assert( idx >= 0 );
  61315. assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
  61316. assert( idx+sz <= (int)pPage->pBt->usableSize );
  61317. pPage->nFree -= (u16)(2 + sz);
  61318. memcpy(&data[idx], pCell, sz);
  61319. if( iChild ){
  61320. put4byte(&data[idx], iChild);
  61321. }
  61322. pIns = pPage->aCellIdx + i*2;
  61323. memmove(pIns+2, pIns, 2*(pPage->nCell - i));
  61324. put2byte(pIns, idx);
  61325. pPage->nCell++;
  61326. /* increment the cell count */
  61327. if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
  61328. assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
  61329. #ifndef SQLITE_OMIT_AUTOVACUUM
  61330. if( pPage->pBt->autoVacuum ){
  61331. /* The cell may contain a pointer to an overflow page. If so, write
  61332. ** the entry for the overflow page into the pointer map.
  61333. */
  61334. ptrmapPutOvflPtr(pPage, pCell, pRC);
  61335. }
  61336. #endif
  61337. }
  61338. }
  61339. /*
  61340. ** A CellArray object contains a cache of pointers and sizes for a
  61341. ** consecutive sequence of cells that might be held on multiple pages.
  61342. */
  61343. typedef struct CellArray CellArray;
  61344. struct CellArray {
  61345. int nCell; /* Number of cells in apCell[] */
  61346. MemPage *pRef; /* Reference page */
  61347. u8 **apCell; /* All cells begin balanced */
  61348. u16 *szCell; /* Local size of all cells in apCell[] */
  61349. };
  61350. /*
  61351. ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
  61352. ** computed.
  61353. */
  61354. static void populateCellCache(CellArray *p, int idx, int N){
  61355. assert( idx>=0 && idx+N<=p->nCell );
  61356. while( N>0 ){
  61357. assert( p->apCell[idx]!=0 );
  61358. if( p->szCell[idx]==0 ){
  61359. p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
  61360. }else{
  61361. assert( CORRUPT_DB ||
  61362. p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
  61363. }
  61364. idx++;
  61365. N--;
  61366. }
  61367. }
  61368. /*
  61369. ** Return the size of the Nth element of the cell array
  61370. */
  61371. static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
  61372. assert( N>=0 && N<p->nCell );
  61373. assert( p->szCell[N]==0 );
  61374. p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
  61375. return p->szCell[N];
  61376. }
  61377. static u16 cachedCellSize(CellArray *p, int N){
  61378. assert( N>=0 && N<p->nCell );
  61379. if( p->szCell[N] ) return p->szCell[N];
  61380. return computeCellSize(p, N);
  61381. }
  61382. /*
  61383. ** Array apCell[] contains pointers to nCell b-tree page cells. The
  61384. ** szCell[] array contains the size in bytes of each cell. This function
  61385. ** replaces the current contents of page pPg with the contents of the cell
  61386. ** array.
  61387. **
  61388. ** Some of the cells in apCell[] may currently be stored in pPg. This
  61389. ** function works around problems caused by this by making a copy of any
  61390. ** such cells before overwriting the page data.
  61391. **
  61392. ** The MemPage.nFree field is invalidated by this function. It is the
  61393. ** responsibility of the caller to set it correctly.
  61394. */
  61395. static int rebuildPage(
  61396. MemPage *pPg, /* Edit this page */
  61397. int nCell, /* Final number of cells on page */
  61398. u8 **apCell, /* Array of cells */
  61399. u16 *szCell /* Array of cell sizes */
  61400. ){
  61401. const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
  61402. u8 * const aData = pPg->aData; /* Pointer to data for pPg */
  61403. const int usableSize = pPg->pBt->usableSize;
  61404. u8 * const pEnd = &aData[usableSize];
  61405. int i;
  61406. u8 *pCellptr = pPg->aCellIdx;
  61407. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  61408. u8 *pData;
  61409. i = get2byte(&aData[hdr+5]);
  61410. memcpy(&pTmp[i], &aData[i], usableSize - i);
  61411. pData = pEnd;
  61412. for(i=0; i<nCell; i++){
  61413. u8 *pCell = apCell[i];
  61414. if( SQLITE_WITHIN(pCell,aData,pEnd) ){
  61415. pCell = &pTmp[pCell - aData];
  61416. }
  61417. pData -= szCell[i];
  61418. put2byte(pCellptr, (pData - aData));
  61419. pCellptr += 2;
  61420. if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
  61421. memcpy(pData, pCell, szCell[i]);
  61422. assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
  61423. testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
  61424. }
  61425. /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
  61426. pPg->nCell = nCell;
  61427. pPg->nOverflow = 0;
  61428. put2byte(&aData[hdr+1], 0);
  61429. put2byte(&aData[hdr+3], pPg->nCell);
  61430. put2byte(&aData[hdr+5], pData - aData);
  61431. aData[hdr+7] = 0x00;
  61432. return SQLITE_OK;
  61433. }
  61434. /*
  61435. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  61436. ** contains the size in bytes of each such cell. This function attempts to
  61437. ** add the cells stored in the array to page pPg. If it cannot (because
  61438. ** the page needs to be defragmented before the cells will fit), non-zero
  61439. ** is returned. Otherwise, if the cells are added successfully, zero is
  61440. ** returned.
  61441. **
  61442. ** Argument pCellptr points to the first entry in the cell-pointer array
  61443. ** (part of page pPg) to populate. After cell apCell[0] is written to the
  61444. ** page body, a 16-bit offset is written to pCellptr. And so on, for each
  61445. ** cell in the array. It is the responsibility of the caller to ensure
  61446. ** that it is safe to overwrite this part of the cell-pointer array.
  61447. **
  61448. ** When this function is called, *ppData points to the start of the
  61449. ** content area on page pPg. If the size of the content area is extended,
  61450. ** *ppData is updated to point to the new start of the content area
  61451. ** before returning.
  61452. **
  61453. ** Finally, argument pBegin points to the byte immediately following the
  61454. ** end of the space required by this page for the cell-pointer area (for
  61455. ** all cells - not just those inserted by the current call). If the content
  61456. ** area must be extended to before this point in order to accomodate all
  61457. ** cells in apCell[], then the cells do not fit and non-zero is returned.
  61458. */
  61459. static int pageInsertArray(
  61460. MemPage *pPg, /* Page to add cells to */
  61461. u8 *pBegin, /* End of cell-pointer array */
  61462. u8 **ppData, /* IN/OUT: Page content -area pointer */
  61463. u8 *pCellptr, /* Pointer to cell-pointer area */
  61464. int iFirst, /* Index of first cell to add */
  61465. int nCell, /* Number of cells to add to pPg */
  61466. CellArray *pCArray /* Array of cells */
  61467. ){
  61468. int i;
  61469. u8 *aData = pPg->aData;
  61470. u8 *pData = *ppData;
  61471. int iEnd = iFirst + nCell;
  61472. assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
  61473. for(i=iFirst; i<iEnd; i++){
  61474. int sz, rc;
  61475. u8 *pSlot;
  61476. sz = cachedCellSize(pCArray, i);
  61477. if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
  61478. if( (pData - pBegin)<sz ) return 1;
  61479. pData -= sz;
  61480. pSlot = pData;
  61481. }
  61482. /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
  61483. ** database. But they might for a corrupt database. Hence use memmove()
  61484. ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
  61485. assert( (pSlot+sz)<=pCArray->apCell[i]
  61486. || pSlot>=(pCArray->apCell[i]+sz)
  61487. || CORRUPT_DB );
  61488. memmove(pSlot, pCArray->apCell[i], sz);
  61489. put2byte(pCellptr, (pSlot - aData));
  61490. pCellptr += 2;
  61491. }
  61492. *ppData = pData;
  61493. return 0;
  61494. }
  61495. /*
  61496. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  61497. ** contains the size in bytes of each such cell. This function adds the
  61498. ** space associated with each cell in the array that is currently stored
  61499. ** within the body of pPg to the pPg free-list. The cell-pointers and other
  61500. ** fields of the page are not updated.
  61501. **
  61502. ** This function returns the total number of cells added to the free-list.
  61503. */
  61504. static int pageFreeArray(
  61505. MemPage *pPg, /* Page to edit */
  61506. int iFirst, /* First cell to delete */
  61507. int nCell, /* Cells to delete */
  61508. CellArray *pCArray /* Array of cells */
  61509. ){
  61510. u8 * const aData = pPg->aData;
  61511. u8 * const pEnd = &aData[pPg->pBt->usableSize];
  61512. u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
  61513. int nRet = 0;
  61514. int i;
  61515. int iEnd = iFirst + nCell;
  61516. u8 *pFree = 0;
  61517. int szFree = 0;
  61518. for(i=iFirst; i<iEnd; i++){
  61519. u8 *pCell = pCArray->apCell[i];
  61520. if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
  61521. int sz;
  61522. /* No need to use cachedCellSize() here. The sizes of all cells that
  61523. ** are to be freed have already been computing while deciding which
  61524. ** cells need freeing */
  61525. sz = pCArray->szCell[i]; assert( sz>0 );
  61526. if( pFree!=(pCell + sz) ){
  61527. if( pFree ){
  61528. assert( pFree>aData && (pFree - aData)<65536 );
  61529. freeSpace(pPg, (u16)(pFree - aData), szFree);
  61530. }
  61531. pFree = pCell;
  61532. szFree = sz;
  61533. if( pFree+sz>pEnd ) return 0;
  61534. }else{
  61535. pFree = pCell;
  61536. szFree += sz;
  61537. }
  61538. nRet++;
  61539. }
  61540. }
  61541. if( pFree ){
  61542. assert( pFree>aData && (pFree - aData)<65536 );
  61543. freeSpace(pPg, (u16)(pFree - aData), szFree);
  61544. }
  61545. return nRet;
  61546. }
  61547. /*
  61548. ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
  61549. ** pages being balanced. The current page, pPg, has pPg->nCell cells starting
  61550. ** with apCell[iOld]. After balancing, this page should hold nNew cells
  61551. ** starting at apCell[iNew].
  61552. **
  61553. ** This routine makes the necessary adjustments to pPg so that it contains
  61554. ** the correct cells after being balanced.
  61555. **
  61556. ** The pPg->nFree field is invalid when this function returns. It is the
  61557. ** responsibility of the caller to set it correctly.
  61558. */
  61559. static int editPage(
  61560. MemPage *pPg, /* Edit this page */
  61561. int iOld, /* Index of first cell currently on page */
  61562. int iNew, /* Index of new first cell on page */
  61563. int nNew, /* Final number of cells on page */
  61564. CellArray *pCArray /* Array of cells and sizes */
  61565. ){
  61566. u8 * const aData = pPg->aData;
  61567. const int hdr = pPg->hdrOffset;
  61568. u8 *pBegin = &pPg->aCellIdx[nNew * 2];
  61569. int nCell = pPg->nCell; /* Cells stored on pPg */
  61570. u8 *pData;
  61571. u8 *pCellptr;
  61572. int i;
  61573. int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
  61574. int iNewEnd = iNew + nNew;
  61575. #ifdef SQLITE_DEBUG
  61576. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  61577. memcpy(pTmp, aData, pPg->pBt->usableSize);
  61578. #endif
  61579. /* Remove cells from the start and end of the page */
  61580. if( iOld<iNew ){
  61581. int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
  61582. memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
  61583. nCell -= nShift;
  61584. }
  61585. if( iNewEnd < iOldEnd ){
  61586. nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
  61587. }
  61588. pData = &aData[get2byteNotZero(&aData[hdr+5])];
  61589. if( pData<pBegin ) goto editpage_fail;
  61590. /* Add cells to the start of the page */
  61591. if( iNew<iOld ){
  61592. int nAdd = MIN(nNew,iOld-iNew);
  61593. assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
  61594. pCellptr = pPg->aCellIdx;
  61595. memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
  61596. if( pageInsertArray(
  61597. pPg, pBegin, &pData, pCellptr,
  61598. iNew, nAdd, pCArray
  61599. ) ) goto editpage_fail;
  61600. nCell += nAdd;
  61601. }
  61602. /* Add any overflow cells */
  61603. for(i=0; i<pPg->nOverflow; i++){
  61604. int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
  61605. if( iCell>=0 && iCell<nNew ){
  61606. pCellptr = &pPg->aCellIdx[iCell * 2];
  61607. memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
  61608. nCell++;
  61609. if( pageInsertArray(
  61610. pPg, pBegin, &pData, pCellptr,
  61611. iCell+iNew, 1, pCArray
  61612. ) ) goto editpage_fail;
  61613. }
  61614. }
  61615. /* Append cells to the end of the page */
  61616. pCellptr = &pPg->aCellIdx[nCell*2];
  61617. if( pageInsertArray(
  61618. pPg, pBegin, &pData, pCellptr,
  61619. iNew+nCell, nNew-nCell, pCArray
  61620. ) ) goto editpage_fail;
  61621. pPg->nCell = nNew;
  61622. pPg->nOverflow = 0;
  61623. put2byte(&aData[hdr+3], pPg->nCell);
  61624. put2byte(&aData[hdr+5], pData - aData);
  61625. #ifdef SQLITE_DEBUG
  61626. for(i=0; i<nNew && !CORRUPT_DB; i++){
  61627. u8 *pCell = pCArray->apCell[i+iNew];
  61628. int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
  61629. if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
  61630. pCell = &pTmp[pCell - aData];
  61631. }
  61632. assert( 0==memcmp(pCell, &aData[iOff],
  61633. pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
  61634. }
  61635. #endif
  61636. return SQLITE_OK;
  61637. editpage_fail:
  61638. /* Unable to edit this page. Rebuild it from scratch instead. */
  61639. populateCellCache(pCArray, iNew, nNew);
  61640. return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
  61641. }
  61642. /*
  61643. ** The following parameters determine how many adjacent pages get involved
  61644. ** in a balancing operation. NN is the number of neighbors on either side
  61645. ** of the page that participate in the balancing operation. NB is the
  61646. ** total number of pages that participate, including the target page and
  61647. ** NN neighbors on either side.
  61648. **
  61649. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  61650. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  61651. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  61652. ** The value of NN appears to give the best results overall.
  61653. */
  61654. #define NN 1 /* Number of neighbors on either side of pPage */
  61655. #define NB (NN*2+1) /* Total pages involved in the balance */
  61656. #ifndef SQLITE_OMIT_QUICKBALANCE
  61657. /*
  61658. ** This version of balance() handles the common special case where
  61659. ** a new entry is being inserted on the extreme right-end of the
  61660. ** tree, in other words, when the new entry will become the largest
  61661. ** entry in the tree.
  61662. **
  61663. ** Instead of trying to balance the 3 right-most leaf pages, just add
  61664. ** a new page to the right-hand side and put the one new entry in
  61665. ** that page. This leaves the right side of the tree somewhat
  61666. ** unbalanced. But odds are that we will be inserting new entries
  61667. ** at the end soon afterwards so the nearly empty page will quickly
  61668. ** fill up. On average.
  61669. **
  61670. ** pPage is the leaf page which is the right-most page in the tree.
  61671. ** pParent is its parent. pPage must have a single overflow entry
  61672. ** which is also the right-most entry on the page.
  61673. **
  61674. ** The pSpace buffer is used to store a temporary copy of the divider
  61675. ** cell that will be inserted into pParent. Such a cell consists of a 4
  61676. ** byte page number followed by a variable length integer. In other
  61677. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  61678. ** least 13 bytes in size.
  61679. */
  61680. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  61681. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  61682. MemPage *pNew; /* Newly allocated page */
  61683. int rc; /* Return Code */
  61684. Pgno pgnoNew; /* Page number of pNew */
  61685. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61686. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  61687. assert( pPage->nOverflow==1 );
  61688. /* This error condition is now caught prior to reaching this function */
  61689. if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
  61690. /* Allocate a new page. This page will become the right-sibling of
  61691. ** pPage. Make the parent page writable, so that the new divider cell
  61692. ** may be inserted. If both these operations are successful, proceed.
  61693. */
  61694. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  61695. if( rc==SQLITE_OK ){
  61696. u8 *pOut = &pSpace[4];
  61697. u8 *pCell = pPage->apOvfl[0];
  61698. u16 szCell = pPage->xCellSize(pPage, pCell);
  61699. u8 *pStop;
  61700. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  61701. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  61702. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  61703. rc = rebuildPage(pNew, 1, &pCell, &szCell);
  61704. if( NEVER(rc) ) return rc;
  61705. pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
  61706. /* If this is an auto-vacuum database, update the pointer map
  61707. ** with entries for the new page, and any pointer from the
  61708. ** cell on the page to an overflow page. If either of these
  61709. ** operations fails, the return code is set, but the contents
  61710. ** of the parent page are still manipulated by thh code below.
  61711. ** That is Ok, at this point the parent page is guaranteed to
  61712. ** be marked as dirty. Returning an error code will cause a
  61713. ** rollback, undoing any changes made to the parent page.
  61714. */
  61715. if( ISAUTOVACUUM ){
  61716. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  61717. if( szCell>pNew->minLocal ){
  61718. ptrmapPutOvflPtr(pNew, pCell, &rc);
  61719. }
  61720. }
  61721. /* Create a divider cell to insert into pParent. The divider cell
  61722. ** consists of a 4-byte page number (the page number of pPage) and
  61723. ** a variable length key value (which must be the same value as the
  61724. ** largest key on pPage).
  61725. **
  61726. ** To find the largest key value on pPage, first find the right-most
  61727. ** cell on pPage. The first two fields of this cell are the
  61728. ** record-length (a variable length integer at most 32-bits in size)
  61729. ** and the key value (a variable length integer, may have any value).
  61730. ** The first of the while(...) loops below skips over the record-length
  61731. ** field. The second while(...) loop copies the key value from the
  61732. ** cell on pPage into the pSpace buffer.
  61733. */
  61734. pCell = findCell(pPage, pPage->nCell-1);
  61735. pStop = &pCell[9];
  61736. while( (*(pCell++)&0x80) && pCell<pStop );
  61737. pStop = &pCell[9];
  61738. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  61739. /* Insert the new divider cell into pParent. */
  61740. if( rc==SQLITE_OK ){
  61741. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  61742. 0, pPage->pgno, &rc);
  61743. }
  61744. /* Set the right-child pointer of pParent to point to the new page. */
  61745. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  61746. /* Release the reference to the new page. */
  61747. releasePage(pNew);
  61748. }
  61749. return rc;
  61750. }
  61751. #endif /* SQLITE_OMIT_QUICKBALANCE */
  61752. #if 0
  61753. /*
  61754. ** This function does not contribute anything to the operation of SQLite.
  61755. ** it is sometimes activated temporarily while debugging code responsible
  61756. ** for setting pointer-map entries.
  61757. */
  61758. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  61759. int i, j;
  61760. for(i=0; i<nPage; i++){
  61761. Pgno n;
  61762. u8 e;
  61763. MemPage *pPage = apPage[i];
  61764. BtShared *pBt = pPage->pBt;
  61765. assert( pPage->isInit );
  61766. for(j=0; j<pPage->nCell; j++){
  61767. CellInfo info;
  61768. u8 *z;
  61769. z = findCell(pPage, j);
  61770. pPage->xParseCell(pPage, z, &info);
  61771. if( info.nLocal<info.nPayload ){
  61772. Pgno ovfl = get4byte(&z[info.nSize-4]);
  61773. ptrmapGet(pBt, ovfl, &e, &n);
  61774. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  61775. }
  61776. if( !pPage->leaf ){
  61777. Pgno child = get4byte(z);
  61778. ptrmapGet(pBt, child, &e, &n);
  61779. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  61780. }
  61781. }
  61782. if( !pPage->leaf ){
  61783. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  61784. ptrmapGet(pBt, child, &e, &n);
  61785. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  61786. }
  61787. }
  61788. return 1;
  61789. }
  61790. #endif
  61791. /*
  61792. ** This function is used to copy the contents of the b-tree node stored
  61793. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  61794. ** the pointer-map entries for each child page are updated so that the
  61795. ** parent page stored in the pointer map is page pTo. If pFrom contained
  61796. ** any cells with overflow page pointers, then the corresponding pointer
  61797. ** map entries are also updated so that the parent page is page pTo.
  61798. **
  61799. ** If pFrom is currently carrying any overflow cells (entries in the
  61800. ** MemPage.apOvfl[] array), they are not copied to pTo.
  61801. **
  61802. ** Before returning, page pTo is reinitialized using btreeInitPage().
  61803. **
  61804. ** The performance of this function is not critical. It is only used by
  61805. ** the balance_shallower() and balance_deeper() procedures, neither of
  61806. ** which are called often under normal circumstances.
  61807. */
  61808. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  61809. if( (*pRC)==SQLITE_OK ){
  61810. BtShared * const pBt = pFrom->pBt;
  61811. u8 * const aFrom = pFrom->aData;
  61812. u8 * const aTo = pTo->aData;
  61813. int const iFromHdr = pFrom->hdrOffset;
  61814. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  61815. int rc;
  61816. int iData;
  61817. assert( pFrom->isInit );
  61818. assert( pFrom->nFree>=iToHdr );
  61819. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  61820. /* Copy the b-tree node content from page pFrom to page pTo. */
  61821. iData = get2byte(&aFrom[iFromHdr+5]);
  61822. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  61823. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  61824. /* Reinitialize page pTo so that the contents of the MemPage structure
  61825. ** match the new data. The initialization of pTo can actually fail under
  61826. ** fairly obscure circumstances, even though it is a copy of initialized
  61827. ** page pFrom.
  61828. */
  61829. pTo->isInit = 0;
  61830. rc = btreeInitPage(pTo);
  61831. if( rc!=SQLITE_OK ){
  61832. *pRC = rc;
  61833. return;
  61834. }
  61835. /* If this is an auto-vacuum database, update the pointer-map entries
  61836. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  61837. */
  61838. if( ISAUTOVACUUM ){
  61839. *pRC = setChildPtrmaps(pTo);
  61840. }
  61841. }
  61842. }
  61843. /*
  61844. ** This routine redistributes cells on the iParentIdx'th child of pParent
  61845. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  61846. ** same amount of free space. Usually a single sibling on either side of the
  61847. ** page are used in the balancing, though both siblings might come from one
  61848. ** side if the page is the first or last child of its parent. If the page
  61849. ** has fewer than 2 siblings (something which can only happen if the page
  61850. ** is a root page or a child of a root page) then all available siblings
  61851. ** participate in the balancing.
  61852. **
  61853. ** The number of siblings of the page might be increased or decreased by
  61854. ** one or two in an effort to keep pages nearly full but not over full.
  61855. **
  61856. ** Note that when this routine is called, some of the cells on the page
  61857. ** might not actually be stored in MemPage.aData[]. This can happen
  61858. ** if the page is overfull. This routine ensures that all cells allocated
  61859. ** to the page and its siblings fit into MemPage.aData[] before returning.
  61860. **
  61861. ** In the course of balancing the page and its siblings, cells may be
  61862. ** inserted into or removed from the parent page (pParent). Doing so
  61863. ** may cause the parent page to become overfull or underfull. If this
  61864. ** happens, it is the responsibility of the caller to invoke the correct
  61865. ** balancing routine to fix this problem (see the balance() routine).
  61866. **
  61867. ** If this routine fails for any reason, it might leave the database
  61868. ** in a corrupted state. So if this routine fails, the database should
  61869. ** be rolled back.
  61870. **
  61871. ** The third argument to this function, aOvflSpace, is a pointer to a
  61872. ** buffer big enough to hold one page. If while inserting cells into the parent
  61873. ** page (pParent) the parent page becomes overfull, this buffer is
  61874. ** used to store the parent's overflow cells. Because this function inserts
  61875. ** a maximum of four divider cells into the parent page, and the maximum
  61876. ** size of a cell stored within an internal node is always less than 1/4
  61877. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  61878. ** enough for all overflow cells.
  61879. **
  61880. ** If aOvflSpace is set to a null pointer, this function returns
  61881. ** SQLITE_NOMEM.
  61882. */
  61883. static int balance_nonroot(
  61884. MemPage *pParent, /* Parent page of siblings being balanced */
  61885. int iParentIdx, /* Index of "the page" in pParent */
  61886. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  61887. int isRoot, /* True if pParent is a root-page */
  61888. int bBulk /* True if this call is part of a bulk load */
  61889. ){
  61890. BtShared *pBt; /* The whole database */
  61891. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  61892. int nNew = 0; /* Number of pages in apNew[] */
  61893. int nOld; /* Number of pages in apOld[] */
  61894. int i, j, k; /* Loop counters */
  61895. int nxDiv; /* Next divider slot in pParent->aCell[] */
  61896. int rc = SQLITE_OK; /* The return code */
  61897. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  61898. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  61899. int usableSpace; /* Bytes in pPage beyond the header */
  61900. int pageFlags; /* Value of pPage->aData[0] */
  61901. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  61902. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  61903. int szScratch; /* Size of scratch memory requested */
  61904. MemPage *apOld[NB]; /* pPage and up to two siblings */
  61905. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  61906. u8 *pRight; /* Location in parent of right-sibling pointer */
  61907. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  61908. int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
  61909. int cntOld[NB+2]; /* Old index in b.apCell[] */
  61910. int szNew[NB+2]; /* Combined size of cells placed on i-th page */
  61911. u8 *aSpace1; /* Space for copies of dividers cells */
  61912. Pgno pgno; /* Temp var to store a page number in */
  61913. u8 abDone[NB+2]; /* True after i'th new page is populated */
  61914. Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
  61915. Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
  61916. u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
  61917. CellArray b; /* Parsed information on cells being balanced */
  61918. memset(abDone, 0, sizeof(abDone));
  61919. b.nCell = 0;
  61920. b.apCell = 0;
  61921. pBt = pParent->pBt;
  61922. assert( sqlite3_mutex_held(pBt->mutex) );
  61923. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  61924. #if 0
  61925. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  61926. #endif
  61927. /* At this point pParent may have at most one overflow cell. And if
  61928. ** this overflow cell is present, it must be the cell with
  61929. ** index iParentIdx. This scenario comes about when this function
  61930. ** is called (indirectly) from sqlite3BtreeDelete().
  61931. */
  61932. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  61933. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  61934. if( !aOvflSpace ){
  61935. return SQLITE_NOMEM_BKPT;
  61936. }
  61937. /* Find the sibling pages to balance. Also locate the cells in pParent
  61938. ** that divide the siblings. An attempt is made to find NN siblings on
  61939. ** either side of pPage. More siblings are taken from one side, however,
  61940. ** if there are fewer than NN siblings on the other side. If pParent
  61941. ** has NB or fewer children then all children of pParent are taken.
  61942. **
  61943. ** This loop also drops the divider cells from the parent page. This
  61944. ** way, the remainder of the function does not have to deal with any
  61945. ** overflow cells in the parent page, since if any existed they will
  61946. ** have already been removed.
  61947. */
  61948. i = pParent->nOverflow + pParent->nCell;
  61949. if( i<2 ){
  61950. nxDiv = 0;
  61951. }else{
  61952. assert( bBulk==0 || bBulk==1 );
  61953. if( iParentIdx==0 ){
  61954. nxDiv = 0;
  61955. }else if( iParentIdx==i ){
  61956. nxDiv = i-2+bBulk;
  61957. }else{
  61958. nxDiv = iParentIdx-1;
  61959. }
  61960. i = 2-bBulk;
  61961. }
  61962. nOld = i+1;
  61963. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  61964. pRight = &pParent->aData[pParent->hdrOffset+8];
  61965. }else{
  61966. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  61967. }
  61968. pgno = get4byte(pRight);
  61969. while( 1 ){
  61970. rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
  61971. if( rc ){
  61972. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  61973. goto balance_cleanup;
  61974. }
  61975. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  61976. if( (i--)==0 ) break;
  61977. if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
  61978. apDiv[i] = pParent->apOvfl[0];
  61979. pgno = get4byte(apDiv[i]);
  61980. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  61981. pParent->nOverflow = 0;
  61982. }else{
  61983. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  61984. pgno = get4byte(apDiv[i]);
  61985. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  61986. /* Drop the cell from the parent page. apDiv[i] still points to
  61987. ** the cell within the parent, even though it has been dropped.
  61988. ** This is safe because dropping a cell only overwrites the first
  61989. ** four bytes of it, and this function does not need the first
  61990. ** four bytes of the divider cell. So the pointer is safe to use
  61991. ** later on.
  61992. **
  61993. ** But not if we are in secure-delete mode. In secure-delete mode,
  61994. ** the dropCell() routine will overwrite the entire cell with zeroes.
  61995. ** In this case, temporarily copy the cell into the aOvflSpace[]
  61996. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  61997. ** is allocated. */
  61998. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  61999. int iOff;
  62000. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  62001. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  62002. rc = SQLITE_CORRUPT_BKPT;
  62003. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  62004. goto balance_cleanup;
  62005. }else{
  62006. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  62007. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  62008. }
  62009. }
  62010. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  62011. }
  62012. }
  62013. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  62014. ** alignment */
  62015. nMaxCells = (nMaxCells + 3)&~3;
  62016. /*
  62017. ** Allocate space for memory structures
  62018. */
  62019. szScratch =
  62020. nMaxCells*sizeof(u8*) /* b.apCell */
  62021. + nMaxCells*sizeof(u16) /* b.szCell */
  62022. + pBt->pageSize; /* aSpace1 */
  62023. /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
  62024. ** that is more than 6 times the database page size. */
  62025. assert( szScratch<=6*(int)pBt->pageSize );
  62026. b.apCell = sqlite3ScratchMalloc( szScratch );
  62027. if( b.apCell==0 ){
  62028. rc = SQLITE_NOMEM_BKPT;
  62029. goto balance_cleanup;
  62030. }
  62031. b.szCell = (u16*)&b.apCell[nMaxCells];
  62032. aSpace1 = (u8*)&b.szCell[nMaxCells];
  62033. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  62034. /*
  62035. ** Load pointers to all cells on sibling pages and the divider cells
  62036. ** into the local b.apCell[] array. Make copies of the divider cells
  62037. ** into space obtained from aSpace1[]. The divider cells have already
  62038. ** been removed from pParent.
  62039. **
  62040. ** If the siblings are on leaf pages, then the child pointers of the
  62041. ** divider cells are stripped from the cells before they are copied
  62042. ** into aSpace1[]. In this way, all cells in b.apCell[] are without
  62043. ** child pointers. If siblings are not leaves, then all cell in
  62044. ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
  62045. ** are alike.
  62046. **
  62047. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  62048. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  62049. */
  62050. b.pRef = apOld[0];
  62051. leafCorrection = b.pRef->leaf*4;
  62052. leafData = b.pRef->intKeyLeaf;
  62053. for(i=0; i<nOld; i++){
  62054. MemPage *pOld = apOld[i];
  62055. int limit = pOld->nCell;
  62056. u8 *aData = pOld->aData;
  62057. u16 maskPage = pOld->maskPage;
  62058. u8 *piCell = aData + pOld->cellOffset;
  62059. u8 *piEnd;
  62060. /* Verify that all sibling pages are of the same "type" (table-leaf,
  62061. ** table-interior, index-leaf, or index-interior).
  62062. */
  62063. if( pOld->aData[0]!=apOld[0]->aData[0] ){
  62064. rc = SQLITE_CORRUPT_BKPT;
  62065. goto balance_cleanup;
  62066. }
  62067. /* Load b.apCell[] with pointers to all cells in pOld. If pOld
  62068. ** constains overflow cells, include them in the b.apCell[] array
  62069. ** in the correct spot.
  62070. **
  62071. ** Note that when there are multiple overflow cells, it is always the
  62072. ** case that they are sequential and adjacent. This invariant arises
  62073. ** because multiple overflows can only occurs when inserting divider
  62074. ** cells into a parent on a prior balance, and divider cells are always
  62075. ** adjacent and are inserted in order. There is an assert() tagged
  62076. ** with "NOTE 1" in the overflow cell insertion loop to prove this
  62077. ** invariant.
  62078. **
  62079. ** This must be done in advance. Once the balance starts, the cell
  62080. ** offset section of the btree page will be overwritten and we will no
  62081. ** long be able to find the cells if a pointer to each cell is not saved
  62082. ** first.
  62083. */
  62084. memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
  62085. if( pOld->nOverflow>0 ){
  62086. limit = pOld->aiOvfl[0];
  62087. for(j=0; j<limit; j++){
  62088. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  62089. piCell += 2;
  62090. b.nCell++;
  62091. }
  62092. for(k=0; k<pOld->nOverflow; k++){
  62093. assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
  62094. b.apCell[b.nCell] = pOld->apOvfl[k];
  62095. b.nCell++;
  62096. }
  62097. }
  62098. piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
  62099. while( piCell<piEnd ){
  62100. assert( b.nCell<nMaxCells );
  62101. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  62102. piCell += 2;
  62103. b.nCell++;
  62104. }
  62105. cntOld[i] = b.nCell;
  62106. if( i<nOld-1 && !leafData){
  62107. u16 sz = (u16)szNew[i];
  62108. u8 *pTemp;
  62109. assert( b.nCell<nMaxCells );
  62110. b.szCell[b.nCell] = sz;
  62111. pTemp = &aSpace1[iSpace1];
  62112. iSpace1 += sz;
  62113. assert( sz<=pBt->maxLocal+23 );
  62114. assert( iSpace1 <= (int)pBt->pageSize );
  62115. memcpy(pTemp, apDiv[i], sz);
  62116. b.apCell[b.nCell] = pTemp+leafCorrection;
  62117. assert( leafCorrection==0 || leafCorrection==4 );
  62118. b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
  62119. if( !pOld->leaf ){
  62120. assert( leafCorrection==0 );
  62121. assert( pOld->hdrOffset==0 );
  62122. /* The right pointer of the child page pOld becomes the left
  62123. ** pointer of the divider cell */
  62124. memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
  62125. }else{
  62126. assert( leafCorrection==4 );
  62127. while( b.szCell[b.nCell]<4 ){
  62128. /* Do not allow any cells smaller than 4 bytes. If a smaller cell
  62129. ** does exist, pad it with 0x00 bytes. */
  62130. assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
  62131. assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
  62132. aSpace1[iSpace1++] = 0x00;
  62133. b.szCell[b.nCell]++;
  62134. }
  62135. }
  62136. b.nCell++;
  62137. }
  62138. }
  62139. /*
  62140. ** Figure out the number of pages needed to hold all b.nCell cells.
  62141. ** Store this number in "k". Also compute szNew[] which is the total
  62142. ** size of all cells on the i-th page and cntNew[] which is the index
  62143. ** in b.apCell[] of the cell that divides page i from page i+1.
  62144. ** cntNew[k] should equal b.nCell.
  62145. **
  62146. ** Values computed by this block:
  62147. **
  62148. ** k: The total number of sibling pages
  62149. ** szNew[i]: Spaced used on the i-th sibling page.
  62150. ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
  62151. ** the right of the i-th sibling page.
  62152. ** usableSpace: Number of bytes of space available on each sibling.
  62153. **
  62154. */
  62155. usableSpace = pBt->usableSize - 12 + leafCorrection;
  62156. for(i=0; i<nOld; i++){
  62157. MemPage *p = apOld[i];
  62158. szNew[i] = usableSpace - p->nFree;
  62159. for(j=0; j<p->nOverflow; j++){
  62160. szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
  62161. }
  62162. cntNew[i] = cntOld[i];
  62163. }
  62164. k = nOld;
  62165. for(i=0; i<k; i++){
  62166. int sz;
  62167. while( szNew[i]>usableSpace ){
  62168. if( i+1>=k ){
  62169. k = i+2;
  62170. if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  62171. szNew[k-1] = 0;
  62172. cntNew[k-1] = b.nCell;
  62173. }
  62174. sz = 2 + cachedCellSize(&b, cntNew[i]-1);
  62175. szNew[i] -= sz;
  62176. if( !leafData ){
  62177. if( cntNew[i]<b.nCell ){
  62178. sz = 2 + cachedCellSize(&b, cntNew[i]);
  62179. }else{
  62180. sz = 0;
  62181. }
  62182. }
  62183. szNew[i+1] += sz;
  62184. cntNew[i]--;
  62185. }
  62186. while( cntNew[i]<b.nCell ){
  62187. sz = 2 + cachedCellSize(&b, cntNew[i]);
  62188. if( szNew[i]+sz>usableSpace ) break;
  62189. szNew[i] += sz;
  62190. cntNew[i]++;
  62191. if( !leafData ){
  62192. if( cntNew[i]<b.nCell ){
  62193. sz = 2 + cachedCellSize(&b, cntNew[i]);
  62194. }else{
  62195. sz = 0;
  62196. }
  62197. }
  62198. szNew[i+1] -= sz;
  62199. }
  62200. if( cntNew[i]>=b.nCell ){
  62201. k = i+1;
  62202. }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
  62203. rc = SQLITE_CORRUPT_BKPT;
  62204. goto balance_cleanup;
  62205. }
  62206. }
  62207. /*
  62208. ** The packing computed by the previous block is biased toward the siblings
  62209. ** on the left side (siblings with smaller keys). The left siblings are
  62210. ** always nearly full, while the right-most sibling might be nearly empty.
  62211. ** The next block of code attempts to adjust the packing of siblings to
  62212. ** get a better balance.
  62213. **
  62214. ** This adjustment is more than an optimization. The packing above might
  62215. ** be so out of balance as to be illegal. For example, the right-most
  62216. ** sibling might be completely empty. This adjustment is not optional.
  62217. */
  62218. for(i=k-1; i>0; i--){
  62219. int szRight = szNew[i]; /* Size of sibling on the right */
  62220. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  62221. int r; /* Index of right-most cell in left sibling */
  62222. int d; /* Index of first cell to the left of right sibling */
  62223. r = cntNew[i-1] - 1;
  62224. d = r + 1 - leafData;
  62225. (void)cachedCellSize(&b, d);
  62226. do{
  62227. assert( d<nMaxCells );
  62228. assert( r<nMaxCells );
  62229. (void)cachedCellSize(&b, r);
  62230. if( szRight!=0
  62231. && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
  62232. break;
  62233. }
  62234. szRight += b.szCell[d] + 2;
  62235. szLeft -= b.szCell[r] + 2;
  62236. cntNew[i-1] = r;
  62237. r--;
  62238. d--;
  62239. }while( r>=0 );
  62240. szNew[i] = szRight;
  62241. szNew[i-1] = szLeft;
  62242. if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
  62243. rc = SQLITE_CORRUPT_BKPT;
  62244. goto balance_cleanup;
  62245. }
  62246. }
  62247. /* Sanity check: For a non-corrupt database file one of the follwing
  62248. ** must be true:
  62249. ** (1) We found one or more cells (cntNew[0])>0), or
  62250. ** (2) pPage is a virtual root page. A virtual root page is when
  62251. ** the real root page is page 1 and we are the only child of
  62252. ** that page.
  62253. */
  62254. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
  62255. TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
  62256. apOld[0]->pgno, apOld[0]->nCell,
  62257. nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
  62258. nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
  62259. ));
  62260. /*
  62261. ** Allocate k new pages. Reuse old pages where possible.
  62262. */
  62263. pageFlags = apOld[0]->aData[0];
  62264. for(i=0; i<k; i++){
  62265. MemPage *pNew;
  62266. if( i<nOld ){
  62267. pNew = apNew[i] = apOld[i];
  62268. apOld[i] = 0;
  62269. rc = sqlite3PagerWrite(pNew->pDbPage);
  62270. nNew++;
  62271. if( rc ) goto balance_cleanup;
  62272. }else{
  62273. assert( i>0 );
  62274. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  62275. if( rc ) goto balance_cleanup;
  62276. zeroPage(pNew, pageFlags);
  62277. apNew[i] = pNew;
  62278. nNew++;
  62279. cntOld[i] = b.nCell;
  62280. /* Set the pointer-map entry for the new sibling page. */
  62281. if( ISAUTOVACUUM ){
  62282. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  62283. if( rc!=SQLITE_OK ){
  62284. goto balance_cleanup;
  62285. }
  62286. }
  62287. }
  62288. }
  62289. /*
  62290. ** Reassign page numbers so that the new pages are in ascending order.
  62291. ** This helps to keep entries in the disk file in order so that a scan
  62292. ** of the table is closer to a linear scan through the file. That in turn
  62293. ** helps the operating system to deliver pages from the disk more rapidly.
  62294. **
  62295. ** An O(n^2) insertion sort algorithm is used, but since n is never more
  62296. ** than (NB+2) (a small constant), that should not be a problem.
  62297. **
  62298. ** When NB==3, this one optimization makes the database about 25% faster
  62299. ** for large insertions and deletions.
  62300. */
  62301. for(i=0; i<nNew; i++){
  62302. aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
  62303. aPgFlags[i] = apNew[i]->pDbPage->flags;
  62304. for(j=0; j<i; j++){
  62305. if( aPgno[j]==aPgno[i] ){
  62306. /* This branch is taken if the set of sibling pages somehow contains
  62307. ** duplicate entries. This can happen if the database is corrupt.
  62308. ** It would be simpler to detect this as part of the loop below, but
  62309. ** we do the detection here in order to avoid populating the pager
  62310. ** cache with two separate objects associated with the same
  62311. ** page number. */
  62312. assert( CORRUPT_DB );
  62313. rc = SQLITE_CORRUPT_BKPT;
  62314. goto balance_cleanup;
  62315. }
  62316. }
  62317. }
  62318. for(i=0; i<nNew; i++){
  62319. int iBest = 0; /* aPgno[] index of page number to use */
  62320. for(j=1; j<nNew; j++){
  62321. if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
  62322. }
  62323. pgno = aPgOrder[iBest];
  62324. aPgOrder[iBest] = 0xffffffff;
  62325. if( iBest!=i ){
  62326. if( iBest>i ){
  62327. sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
  62328. }
  62329. sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
  62330. apNew[i]->pgno = pgno;
  62331. }
  62332. }
  62333. TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
  62334. "%d(%d nc=%d) %d(%d nc=%d)\n",
  62335. apNew[0]->pgno, szNew[0], cntNew[0],
  62336. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  62337. nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
  62338. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  62339. nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
  62340. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  62341. nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
  62342. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
  62343. nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
  62344. ));
  62345. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  62346. put4byte(pRight, apNew[nNew-1]->pgno);
  62347. /* If the sibling pages are not leaves, ensure that the right-child pointer
  62348. ** of the right-most new sibling page is set to the value that was
  62349. ** originally in the same field of the right-most old sibling page. */
  62350. if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
  62351. MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
  62352. memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
  62353. }
  62354. /* Make any required updates to pointer map entries associated with
  62355. ** cells stored on sibling pages following the balance operation. Pointer
  62356. ** map entries associated with divider cells are set by the insertCell()
  62357. ** routine. The associated pointer map entries are:
  62358. **
  62359. ** a) if the cell contains a reference to an overflow chain, the
  62360. ** entry associated with the first page in the overflow chain, and
  62361. **
  62362. ** b) if the sibling pages are not leaves, the child page associated
  62363. ** with the cell.
  62364. **
  62365. ** If the sibling pages are not leaves, then the pointer map entry
  62366. ** associated with the right-child of each sibling may also need to be
  62367. ** updated. This happens below, after the sibling pages have been
  62368. ** populated, not here.
  62369. */
  62370. if( ISAUTOVACUUM ){
  62371. MemPage *pNew = apNew[0];
  62372. u8 *aOld = pNew->aData;
  62373. int cntOldNext = pNew->nCell + pNew->nOverflow;
  62374. int usableSize = pBt->usableSize;
  62375. int iNew = 0;
  62376. int iOld = 0;
  62377. for(i=0; i<b.nCell; i++){
  62378. u8 *pCell = b.apCell[i];
  62379. if( i==cntOldNext ){
  62380. MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
  62381. cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
  62382. aOld = pOld->aData;
  62383. }
  62384. if( i==cntNew[iNew] ){
  62385. pNew = apNew[++iNew];
  62386. if( !leafData ) continue;
  62387. }
  62388. /* Cell pCell is destined for new sibling page pNew. Originally, it
  62389. ** was either part of sibling page iOld (possibly an overflow cell),
  62390. ** or else the divider cell to the left of sibling page iOld. So,
  62391. ** if sibling page iOld had the same page number as pNew, and if
  62392. ** pCell really was a part of sibling page iOld (not a divider or
  62393. ** overflow cell), we can skip updating the pointer map entries. */
  62394. if( iOld>=nNew
  62395. || pNew->pgno!=aPgno[iOld]
  62396. || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
  62397. ){
  62398. if( !leafCorrection ){
  62399. ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
  62400. }
  62401. if( cachedCellSize(&b,i)>pNew->minLocal ){
  62402. ptrmapPutOvflPtr(pNew, pCell, &rc);
  62403. }
  62404. if( rc ) goto balance_cleanup;
  62405. }
  62406. }
  62407. }
  62408. /* Insert new divider cells into pParent. */
  62409. for(i=0; i<nNew-1; i++){
  62410. u8 *pCell;
  62411. u8 *pTemp;
  62412. int sz;
  62413. MemPage *pNew = apNew[i];
  62414. j = cntNew[i];
  62415. assert( j<nMaxCells );
  62416. assert( b.apCell[j]!=0 );
  62417. pCell = b.apCell[j];
  62418. sz = b.szCell[j] + leafCorrection;
  62419. pTemp = &aOvflSpace[iOvflSpace];
  62420. if( !pNew->leaf ){
  62421. memcpy(&pNew->aData[8], pCell, 4);
  62422. }else if( leafData ){
  62423. /* If the tree is a leaf-data tree, and the siblings are leaves,
  62424. ** then there is no divider cell in b.apCell[]. Instead, the divider
  62425. ** cell consists of the integer key for the right-most cell of
  62426. ** the sibling-page assembled above only.
  62427. */
  62428. CellInfo info;
  62429. j--;
  62430. pNew->xParseCell(pNew, b.apCell[j], &info);
  62431. pCell = pTemp;
  62432. sz = 4 + putVarint(&pCell[4], info.nKey);
  62433. pTemp = 0;
  62434. }else{
  62435. pCell -= 4;
  62436. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  62437. ** previously stored on a leaf node, and its reported size was 4
  62438. ** bytes, then it may actually be smaller than this
  62439. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  62440. ** any cell). But it is important to pass the correct size to
  62441. ** insertCell(), so reparse the cell now.
  62442. **
  62443. ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
  62444. ** and WITHOUT ROWID tables with exactly one column which is the
  62445. ** primary key.
  62446. */
  62447. if( b.szCell[j]==4 ){
  62448. assert(leafCorrection==4);
  62449. sz = pParent->xCellSize(pParent, pCell);
  62450. }
  62451. }
  62452. iOvflSpace += sz;
  62453. assert( sz<=pBt->maxLocal+23 );
  62454. assert( iOvflSpace <= (int)pBt->pageSize );
  62455. insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
  62456. if( rc!=SQLITE_OK ) goto balance_cleanup;
  62457. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  62458. }
  62459. /* Now update the actual sibling pages. The order in which they are updated
  62460. ** is important, as this code needs to avoid disrupting any page from which
  62461. ** cells may still to be read. In practice, this means:
  62462. **
  62463. ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
  62464. ** then it is not safe to update page apNew[iPg] until after
  62465. ** the left-hand sibling apNew[iPg-1] has been updated.
  62466. **
  62467. ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
  62468. ** then it is not safe to update page apNew[iPg] until after
  62469. ** the right-hand sibling apNew[iPg+1] has been updated.
  62470. **
  62471. ** If neither of the above apply, the page is safe to update.
  62472. **
  62473. ** The iPg value in the following loop starts at nNew-1 goes down
  62474. ** to 0, then back up to nNew-1 again, thus making two passes over
  62475. ** the pages. On the initial downward pass, only condition (1) above
  62476. ** needs to be tested because (2) will always be true from the previous
  62477. ** step. On the upward pass, both conditions are always true, so the
  62478. ** upwards pass simply processes pages that were missed on the downward
  62479. ** pass.
  62480. */
  62481. for(i=1-nNew; i<nNew; i++){
  62482. int iPg = i<0 ? -i : i;
  62483. assert( iPg>=0 && iPg<nNew );
  62484. if( abDone[iPg] ) continue; /* Skip pages already processed */
  62485. if( i>=0 /* On the upwards pass, or... */
  62486. || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
  62487. ){
  62488. int iNew;
  62489. int iOld;
  62490. int nNewCell;
  62491. /* Verify condition (1): If cells are moving left, update iPg
  62492. ** only after iPg-1 has already been updated. */
  62493. assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
  62494. /* Verify condition (2): If cells are moving right, update iPg
  62495. ** only after iPg+1 has already been updated. */
  62496. assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
  62497. if( iPg==0 ){
  62498. iNew = iOld = 0;
  62499. nNewCell = cntNew[0];
  62500. }else{
  62501. iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
  62502. iNew = cntNew[iPg-1] + !leafData;
  62503. nNewCell = cntNew[iPg] - iNew;
  62504. }
  62505. rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
  62506. if( rc ) goto balance_cleanup;
  62507. abDone[iPg]++;
  62508. apNew[iPg]->nFree = usableSpace-szNew[iPg];
  62509. assert( apNew[iPg]->nOverflow==0 );
  62510. assert( apNew[iPg]->nCell==nNewCell );
  62511. }
  62512. }
  62513. /* All pages have been processed exactly once */
  62514. assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
  62515. assert( nOld>0 );
  62516. assert( nNew>0 );
  62517. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  62518. /* The root page of the b-tree now contains no cells. The only sibling
  62519. ** page is the right-child of the parent. Copy the contents of the
  62520. ** child page into the parent, decreasing the overall height of the
  62521. ** b-tree structure by one. This is described as the "balance-shallower"
  62522. ** sub-algorithm in some documentation.
  62523. **
  62524. ** If this is an auto-vacuum database, the call to copyNodeContent()
  62525. ** sets all pointer-map entries corresponding to database image pages
  62526. ** for which the pointer is stored within the content being copied.
  62527. **
  62528. ** It is critical that the child page be defragmented before being
  62529. ** copied into the parent, because if the parent is page 1 then it will
  62530. ** by smaller than the child due to the database header, and so all the
  62531. ** free space needs to be up front.
  62532. */
  62533. assert( nNew==1 || CORRUPT_DB );
  62534. rc = defragmentPage(apNew[0], -1);
  62535. testcase( rc!=SQLITE_OK );
  62536. assert( apNew[0]->nFree ==
  62537. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  62538. || rc!=SQLITE_OK
  62539. );
  62540. copyNodeContent(apNew[0], pParent, &rc);
  62541. freePage(apNew[0], &rc);
  62542. }else if( ISAUTOVACUUM && !leafCorrection ){
  62543. /* Fix the pointer map entries associated with the right-child of each
  62544. ** sibling page. All other pointer map entries have already been taken
  62545. ** care of. */
  62546. for(i=0; i<nNew; i++){
  62547. u32 key = get4byte(&apNew[i]->aData[8]);
  62548. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  62549. }
  62550. }
  62551. assert( pParent->isInit );
  62552. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  62553. nOld, nNew, b.nCell));
  62554. /* Free any old pages that were not reused as new pages.
  62555. */
  62556. for(i=nNew; i<nOld; i++){
  62557. freePage(apOld[i], &rc);
  62558. }
  62559. #if 0
  62560. if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
  62561. /* The ptrmapCheckPages() contains assert() statements that verify that
  62562. ** all pointer map pages are set correctly. This is helpful while
  62563. ** debugging. This is usually disabled because a corrupt database may
  62564. ** cause an assert() statement to fail. */
  62565. ptrmapCheckPages(apNew, nNew);
  62566. ptrmapCheckPages(&pParent, 1);
  62567. }
  62568. #endif
  62569. /*
  62570. ** Cleanup before returning.
  62571. */
  62572. balance_cleanup:
  62573. sqlite3ScratchFree(b.apCell);
  62574. for(i=0; i<nOld; i++){
  62575. releasePage(apOld[i]);
  62576. }
  62577. for(i=0; i<nNew; i++){
  62578. releasePage(apNew[i]);
  62579. }
  62580. return rc;
  62581. }
  62582. /*
  62583. ** This function is called when the root page of a b-tree structure is
  62584. ** overfull (has one or more overflow pages).
  62585. **
  62586. ** A new child page is allocated and the contents of the current root
  62587. ** page, including overflow cells, are copied into the child. The root
  62588. ** page is then overwritten to make it an empty page with the right-child
  62589. ** pointer pointing to the new page.
  62590. **
  62591. ** Before returning, all pointer-map entries corresponding to pages
  62592. ** that the new child-page now contains pointers to are updated. The
  62593. ** entry corresponding to the new right-child pointer of the root
  62594. ** page is also updated.
  62595. **
  62596. ** If successful, *ppChild is set to contain a reference to the child
  62597. ** page and SQLITE_OK is returned. In this case the caller is required
  62598. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  62599. ** an error code is returned and *ppChild is set to 0.
  62600. */
  62601. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  62602. int rc; /* Return value from subprocedures */
  62603. MemPage *pChild = 0; /* Pointer to a new child page */
  62604. Pgno pgnoChild = 0; /* Page number of the new child page */
  62605. BtShared *pBt = pRoot->pBt; /* The BTree */
  62606. assert( pRoot->nOverflow>0 );
  62607. assert( sqlite3_mutex_held(pBt->mutex) );
  62608. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  62609. ** page that will become the new right-child of pPage. Copy the contents
  62610. ** of the node stored on pRoot into the new child page.
  62611. */
  62612. rc = sqlite3PagerWrite(pRoot->pDbPage);
  62613. if( rc==SQLITE_OK ){
  62614. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  62615. copyNodeContent(pRoot, pChild, &rc);
  62616. if( ISAUTOVACUUM ){
  62617. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  62618. }
  62619. }
  62620. if( rc ){
  62621. *ppChild = 0;
  62622. releasePage(pChild);
  62623. return rc;
  62624. }
  62625. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  62626. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  62627. assert( pChild->nCell==pRoot->nCell );
  62628. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  62629. /* Copy the overflow cells from pRoot to pChild */
  62630. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  62631. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  62632. memcpy(pChild->apOvfl, pRoot->apOvfl,
  62633. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  62634. pChild->nOverflow = pRoot->nOverflow;
  62635. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  62636. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  62637. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  62638. *ppChild = pChild;
  62639. return SQLITE_OK;
  62640. }
  62641. /*
  62642. ** The page that pCur currently points to has just been modified in
  62643. ** some way. This function figures out if this modification means the
  62644. ** tree needs to be balanced, and if so calls the appropriate balancing
  62645. ** routine. Balancing routines are:
  62646. **
  62647. ** balance_quick()
  62648. ** balance_deeper()
  62649. ** balance_nonroot()
  62650. */
  62651. static int balance(BtCursor *pCur){
  62652. int rc = SQLITE_OK;
  62653. const int nMin = pCur->pBt->usableSize * 2 / 3;
  62654. u8 aBalanceQuickSpace[13];
  62655. u8 *pFree = 0;
  62656. VVA_ONLY( int balance_quick_called = 0 );
  62657. VVA_ONLY( int balance_deeper_called = 0 );
  62658. do {
  62659. int iPage = pCur->iPage;
  62660. MemPage *pPage = pCur->apPage[iPage];
  62661. if( iPage==0 ){
  62662. if( pPage->nOverflow ){
  62663. /* The root page of the b-tree is overfull. In this case call the
  62664. ** balance_deeper() function to create a new child for the root-page
  62665. ** and copy the current contents of the root-page to it. The
  62666. ** next iteration of the do-loop will balance the child page.
  62667. */
  62668. assert( balance_deeper_called==0 );
  62669. VVA_ONLY( balance_deeper_called++ );
  62670. rc = balance_deeper(pPage, &pCur->apPage[1]);
  62671. if( rc==SQLITE_OK ){
  62672. pCur->iPage = 1;
  62673. pCur->ix = 0;
  62674. pCur->aiIdx[0] = 0;
  62675. assert( pCur->apPage[1]->nOverflow );
  62676. }
  62677. }else{
  62678. break;
  62679. }
  62680. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  62681. break;
  62682. }else{
  62683. MemPage * const pParent = pCur->apPage[iPage-1];
  62684. int const iIdx = pCur->aiIdx[iPage-1];
  62685. rc = sqlite3PagerWrite(pParent->pDbPage);
  62686. if( rc==SQLITE_OK ){
  62687. #ifndef SQLITE_OMIT_QUICKBALANCE
  62688. if( pPage->intKeyLeaf
  62689. && pPage->nOverflow==1
  62690. && pPage->aiOvfl[0]==pPage->nCell
  62691. && pParent->pgno!=1
  62692. && pParent->nCell==iIdx
  62693. ){
  62694. /* Call balance_quick() to create a new sibling of pPage on which
  62695. ** to store the overflow cell. balance_quick() inserts a new cell
  62696. ** into pParent, which may cause pParent overflow. If this
  62697. ** happens, the next iteration of the do-loop will balance pParent
  62698. ** use either balance_nonroot() or balance_deeper(). Until this
  62699. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  62700. ** buffer.
  62701. **
  62702. ** The purpose of the following assert() is to check that only a
  62703. ** single call to balance_quick() is made for each call to this
  62704. ** function. If this were not verified, a subtle bug involving reuse
  62705. ** of the aBalanceQuickSpace[] might sneak in.
  62706. */
  62707. assert( balance_quick_called==0 );
  62708. VVA_ONLY( balance_quick_called++ );
  62709. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  62710. }else
  62711. #endif
  62712. {
  62713. /* In this case, call balance_nonroot() to redistribute cells
  62714. ** between pPage and up to 2 of its sibling pages. This involves
  62715. ** modifying the contents of pParent, which may cause pParent to
  62716. ** become overfull or underfull. The next iteration of the do-loop
  62717. ** will balance the parent page to correct this.
  62718. **
  62719. ** If the parent page becomes overfull, the overflow cell or cells
  62720. ** are stored in the pSpace buffer allocated immediately below.
  62721. ** A subsequent iteration of the do-loop will deal with this by
  62722. ** calling balance_nonroot() (balance_deeper() may be called first,
  62723. ** but it doesn't deal with overflow cells - just moves them to a
  62724. ** different page). Once this subsequent call to balance_nonroot()
  62725. ** has completed, it is safe to release the pSpace buffer used by
  62726. ** the previous call, as the overflow cell data will have been
  62727. ** copied either into the body of a database page or into the new
  62728. ** pSpace buffer passed to the latter call to balance_nonroot().
  62729. */
  62730. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  62731. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
  62732. pCur->hints&BTREE_BULKLOAD);
  62733. if( pFree ){
  62734. /* If pFree is not NULL, it points to the pSpace buffer used
  62735. ** by a previous call to balance_nonroot(). Its contents are
  62736. ** now stored either on real database pages or within the
  62737. ** new pSpace buffer, so it may be safely freed here. */
  62738. sqlite3PageFree(pFree);
  62739. }
  62740. /* The pSpace buffer will be freed after the next call to
  62741. ** balance_nonroot(), or just before this function returns, whichever
  62742. ** comes first. */
  62743. pFree = pSpace;
  62744. }
  62745. }
  62746. pPage->nOverflow = 0;
  62747. /* The next iteration of the do-loop balances the parent page. */
  62748. releasePage(pPage);
  62749. pCur->iPage--;
  62750. assert( pCur->iPage>=0 );
  62751. }
  62752. }while( rc==SQLITE_OK );
  62753. if( pFree ){
  62754. sqlite3PageFree(pFree);
  62755. }
  62756. return rc;
  62757. }
  62758. /*
  62759. ** Insert a new record into the BTree. The content of the new record
  62760. ** is described by the pX object. The pCur cursor is used only to
  62761. ** define what table the record should be inserted into, and is left
  62762. ** pointing at a random location.
  62763. **
  62764. ** For a table btree (used for rowid tables), only the pX.nKey value of
  62765. ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
  62766. ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
  62767. ** hold the content of the row.
  62768. **
  62769. ** For an index btree (used for indexes and WITHOUT ROWID tables), the
  62770. ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
  62771. ** pX.pData,nData,nZero fields must be zero.
  62772. **
  62773. ** If the seekResult parameter is non-zero, then a successful call to
  62774. ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
  62775. ** been performed. In other words, if seekResult!=0 then the cursor
  62776. ** is currently pointing to a cell that will be adjacent to the cell
  62777. ** to be inserted. If seekResult<0 then pCur points to a cell that is
  62778. ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
  62779. ** that is larger than (pKey,nKey).
  62780. **
  62781. ** If seekResult==0, that means pCur is pointing at some unknown location.
  62782. ** In that case, this routine must seek the cursor to the correct insertion
  62783. ** point for (pKey,nKey) before doing the insertion. For index btrees,
  62784. ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
  62785. ** key values and pX->aMem can be used instead of pX->pKey to avoid having
  62786. ** to decode the key.
  62787. */
  62788. SQLITE_PRIVATE int sqlite3BtreeInsert(
  62789. BtCursor *pCur, /* Insert data into the table of this cursor */
  62790. const BtreePayload *pX, /* Content of the row to be inserted */
  62791. int flags, /* True if this is likely an append */
  62792. int seekResult /* Result of prior MovetoUnpacked() call */
  62793. ){
  62794. int rc;
  62795. int loc = seekResult; /* -1: before desired location +1: after */
  62796. int szNew = 0;
  62797. int idx;
  62798. MemPage *pPage;
  62799. Btree *p = pCur->pBtree;
  62800. BtShared *pBt = p->pBt;
  62801. unsigned char *oldCell;
  62802. unsigned char *newCell = 0;
  62803. assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
  62804. if( pCur->eState==CURSOR_FAULT ){
  62805. assert( pCur->skipNext!=SQLITE_OK );
  62806. return pCur->skipNext;
  62807. }
  62808. assert( cursorOwnsBtShared(pCur) );
  62809. assert( (pCur->curFlags & BTCF_WriteFlag)!=0
  62810. && pBt->inTransaction==TRANS_WRITE
  62811. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  62812. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  62813. /* Assert that the caller has been consistent. If this cursor was opened
  62814. ** expecting an index b-tree, then the caller should be inserting blob
  62815. ** keys with no associated data. If the cursor was opened expecting an
  62816. ** intkey table, the caller should be inserting integer keys with a
  62817. ** blob of associated data. */
  62818. assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
  62819. /* Save the positions of any other cursors open on this table.
  62820. **
  62821. ** In some cases, the call to btreeMoveto() below is a no-op. For
  62822. ** example, when inserting data into a table with auto-generated integer
  62823. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  62824. ** integer key to use. It then calls this function to actually insert the
  62825. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  62826. ** that the cursor is already where it needs to be and returns without
  62827. ** doing any work. To avoid thwarting these optimizations, it is important
  62828. ** not to clear the cursor here.
  62829. */
  62830. if( pCur->curFlags & BTCF_Multiple ){
  62831. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  62832. if( rc ) return rc;
  62833. }
  62834. if( pCur->pKeyInfo==0 ){
  62835. assert( pX->pKey==0 );
  62836. /* If this is an insert into a table b-tree, invalidate any incrblob
  62837. ** cursors open on the row being replaced */
  62838. invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
  62839. /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
  62840. ** to a row with the same key as the new entry being inserted. */
  62841. assert( (flags & BTREE_SAVEPOSITION)==0 ||
  62842. ((pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey) );
  62843. /* If the cursor is currently on the last row and we are appending a
  62844. ** new row onto the end, set the "loc" to avoid an unnecessary
  62845. ** btreeMoveto() call */
  62846. if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
  62847. loc = 0;
  62848. }else if( loc==0 ){
  62849. rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
  62850. if( rc ) return rc;
  62851. }
  62852. }else if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
  62853. if( pX->nMem ){
  62854. UnpackedRecord r;
  62855. r.pKeyInfo = pCur->pKeyInfo;
  62856. r.aMem = pX->aMem;
  62857. r.nField = pX->nMem;
  62858. r.default_rc = 0;
  62859. r.errCode = 0;
  62860. r.r1 = 0;
  62861. r.r2 = 0;
  62862. r.eqSeen = 0;
  62863. rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
  62864. }else{
  62865. rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
  62866. }
  62867. if( rc ) return rc;
  62868. }
  62869. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  62870. pPage = pCur->apPage[pCur->iPage];
  62871. assert( pPage->intKey || pX->nKey>=0 );
  62872. assert( pPage->leaf || !pPage->intKey );
  62873. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  62874. pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
  62875. loc==0 ? "overwrite" : "new entry"));
  62876. assert( pPage->isInit );
  62877. newCell = pBt->pTmpSpace;
  62878. assert( newCell!=0 );
  62879. rc = fillInCell(pPage, newCell, pX, &szNew);
  62880. if( rc ) goto end_insert;
  62881. assert( szNew==pPage->xCellSize(pPage, newCell) );
  62882. assert( szNew <= MX_CELL_SIZE(pBt) );
  62883. idx = pCur->ix;
  62884. if( loc==0 ){
  62885. CellInfo info;
  62886. assert( idx<pPage->nCell );
  62887. rc = sqlite3PagerWrite(pPage->pDbPage);
  62888. if( rc ){
  62889. goto end_insert;
  62890. }
  62891. oldCell = findCell(pPage, idx);
  62892. if( !pPage->leaf ){
  62893. memcpy(newCell, oldCell, 4);
  62894. }
  62895. rc = clearCell(pPage, oldCell, &info);
  62896. if( info.nSize==szNew && info.nLocal==info.nPayload
  62897. && (!ISAUTOVACUUM || szNew<pPage->minLocal)
  62898. ){
  62899. /* Overwrite the old cell with the new if they are the same size.
  62900. ** We could also try to do this if the old cell is smaller, then add
  62901. ** the leftover space to the free list. But experiments show that
  62902. ** doing that is no faster then skipping this optimization and just
  62903. ** calling dropCell() and insertCell().
  62904. **
  62905. ** This optimization cannot be used on an autovacuum database if the
  62906. ** new entry uses overflow pages, as the insertCell() call below is
  62907. ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
  62908. assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
  62909. if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
  62910. memcpy(oldCell, newCell, szNew);
  62911. return SQLITE_OK;
  62912. }
  62913. dropCell(pPage, idx, info.nSize, &rc);
  62914. if( rc ) goto end_insert;
  62915. }else if( loc<0 && pPage->nCell>0 ){
  62916. assert( pPage->leaf );
  62917. idx = ++pCur->ix;
  62918. pCur->curFlags &= ~BTCF_ValidNKey;
  62919. }else{
  62920. assert( pPage->leaf );
  62921. }
  62922. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  62923. assert( pPage->nOverflow==0 || rc==SQLITE_OK );
  62924. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  62925. /* If no error has occurred and pPage has an overflow cell, call balance()
  62926. ** to redistribute the cells within the tree. Since balance() may move
  62927. ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
  62928. ** variables.
  62929. **
  62930. ** Previous versions of SQLite called moveToRoot() to move the cursor
  62931. ** back to the root page as balance() used to invalidate the contents
  62932. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  62933. ** set the cursor state to "invalid". This makes common insert operations
  62934. ** slightly faster.
  62935. **
  62936. ** There is a subtle but important optimization here too. When inserting
  62937. ** multiple records into an intkey b-tree using a single cursor (as can
  62938. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  62939. ** is advantageous to leave the cursor pointing to the last entry in
  62940. ** the b-tree if possible. If the cursor is left pointing to the last
  62941. ** entry in the table, and the next row inserted has an integer key
  62942. ** larger than the largest existing key, it is possible to insert the
  62943. ** row without seeking the cursor. This can be a big performance boost.
  62944. */
  62945. pCur->info.nSize = 0;
  62946. if( pPage->nOverflow ){
  62947. assert( rc==SQLITE_OK );
  62948. pCur->curFlags &= ~(BTCF_ValidNKey);
  62949. rc = balance(pCur);
  62950. /* Must make sure nOverflow is reset to zero even if the balance()
  62951. ** fails. Internal data structure corruption will result otherwise.
  62952. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  62953. ** from trying to save the current position of the cursor. */
  62954. pCur->apPage[pCur->iPage]->nOverflow = 0;
  62955. pCur->eState = CURSOR_INVALID;
  62956. if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
  62957. rc = moveToRoot(pCur);
  62958. if( pCur->pKeyInfo ){
  62959. assert( pCur->pKey==0 );
  62960. pCur->pKey = sqlite3Malloc( pX->nKey );
  62961. if( pCur->pKey==0 ){
  62962. rc = SQLITE_NOMEM;
  62963. }else{
  62964. memcpy(pCur->pKey, pX->pKey, pX->nKey);
  62965. }
  62966. }
  62967. pCur->eState = CURSOR_REQUIRESEEK;
  62968. pCur->nKey = pX->nKey;
  62969. }
  62970. }
  62971. assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
  62972. end_insert:
  62973. return rc;
  62974. }
  62975. /*
  62976. ** Delete the entry that the cursor is pointing to.
  62977. **
  62978. ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
  62979. ** the cursor is left pointing at an arbitrary location after the delete.
  62980. ** But if that bit is set, then the cursor is left in a state such that
  62981. ** the next call to BtreeNext() or BtreePrev() moves it to the same row
  62982. ** as it would have been on if the call to BtreeDelete() had been omitted.
  62983. **
  62984. ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
  62985. ** associated with a single table entry and its indexes. Only one of those
  62986. ** deletes is considered the "primary" delete. The primary delete occurs
  62987. ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
  62988. ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
  62989. ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
  62990. ** but which might be used by alternative storage engines.
  62991. */
  62992. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
  62993. Btree *p = pCur->pBtree;
  62994. BtShared *pBt = p->pBt;
  62995. int rc; /* Return code */
  62996. MemPage *pPage; /* Page to delete cell from */
  62997. unsigned char *pCell; /* Pointer to cell to delete */
  62998. int iCellIdx; /* Index of cell to delete */
  62999. int iCellDepth; /* Depth of node containing pCell */
  63000. CellInfo info; /* Size of the cell being deleted */
  63001. int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
  63002. u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
  63003. assert( cursorOwnsBtShared(pCur) );
  63004. assert( pBt->inTransaction==TRANS_WRITE );
  63005. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  63006. assert( pCur->curFlags & BTCF_WriteFlag );
  63007. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  63008. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  63009. assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
  63010. assert( pCur->eState==CURSOR_VALID );
  63011. assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
  63012. iCellDepth = pCur->iPage;
  63013. iCellIdx = pCur->ix;
  63014. pPage = pCur->apPage[iCellDepth];
  63015. pCell = findCell(pPage, iCellIdx);
  63016. /* If the bPreserve flag is set to true, then the cursor position must
  63017. ** be preserved following this delete operation. If the current delete
  63018. ** will cause a b-tree rebalance, then this is done by saving the cursor
  63019. ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
  63020. ** returning.
  63021. **
  63022. ** Or, if the current delete will not cause a rebalance, then the cursor
  63023. ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
  63024. ** before or after the deleted entry. In this case set bSkipnext to true. */
  63025. if( bPreserve ){
  63026. if( !pPage->leaf
  63027. || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
  63028. ){
  63029. /* A b-tree rebalance will be required after deleting this entry.
  63030. ** Save the cursor key. */
  63031. rc = saveCursorKey(pCur);
  63032. if( rc ) return rc;
  63033. }else{
  63034. bSkipnext = 1;
  63035. }
  63036. }
  63037. /* If the page containing the entry to delete is not a leaf page, move
  63038. ** the cursor to the largest entry in the tree that is smaller than
  63039. ** the entry being deleted. This cell will replace the cell being deleted
  63040. ** from the internal node. The 'previous' entry is used for this instead
  63041. ** of the 'next' entry, as the previous entry is always a part of the
  63042. ** sub-tree headed by the child page of the cell being deleted. This makes
  63043. ** balancing the tree following the delete operation easier. */
  63044. if( !pPage->leaf ){
  63045. int notUsed = 0;
  63046. rc = sqlite3BtreePrevious(pCur, &notUsed);
  63047. if( rc ) return rc;
  63048. }
  63049. /* Save the positions of any other cursors open on this table before
  63050. ** making any modifications. */
  63051. if( pCur->curFlags & BTCF_Multiple ){
  63052. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  63053. if( rc ) return rc;
  63054. }
  63055. /* If this is a delete operation to remove a row from a table b-tree,
  63056. ** invalidate any incrblob cursors open on the row being deleted. */
  63057. if( pCur->pKeyInfo==0 ){
  63058. invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
  63059. }
  63060. /* Make the page containing the entry to be deleted writable. Then free any
  63061. ** overflow pages associated with the entry and finally remove the cell
  63062. ** itself from within the page. */
  63063. rc = sqlite3PagerWrite(pPage->pDbPage);
  63064. if( rc ) return rc;
  63065. rc = clearCell(pPage, pCell, &info);
  63066. dropCell(pPage, iCellIdx, info.nSize, &rc);
  63067. if( rc ) return rc;
  63068. /* If the cell deleted was not located on a leaf page, then the cursor
  63069. ** is currently pointing to the largest entry in the sub-tree headed
  63070. ** by the child-page of the cell that was just deleted from an internal
  63071. ** node. The cell from the leaf node needs to be moved to the internal
  63072. ** node to replace the deleted cell. */
  63073. if( !pPage->leaf ){
  63074. MemPage *pLeaf = pCur->apPage[pCur->iPage];
  63075. int nCell;
  63076. Pgno n = pCur->apPage[iCellDepth+1]->pgno;
  63077. unsigned char *pTmp;
  63078. pCell = findCell(pLeaf, pLeaf->nCell-1);
  63079. if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
  63080. nCell = pLeaf->xCellSize(pLeaf, pCell);
  63081. assert( MX_CELL_SIZE(pBt) >= nCell );
  63082. pTmp = pBt->pTmpSpace;
  63083. assert( pTmp!=0 );
  63084. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  63085. if( rc==SQLITE_OK ){
  63086. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  63087. }
  63088. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  63089. if( rc ) return rc;
  63090. }
  63091. /* Balance the tree. If the entry deleted was located on a leaf page,
  63092. ** then the cursor still points to that page. In this case the first
  63093. ** call to balance() repairs the tree, and the if(...) condition is
  63094. ** never true.
  63095. **
  63096. ** Otherwise, if the entry deleted was on an internal node page, then
  63097. ** pCur is pointing to the leaf page from which a cell was removed to
  63098. ** replace the cell deleted from the internal node. This is slightly
  63099. ** tricky as the leaf node may be underfull, and the internal node may
  63100. ** be either under or overfull. In this case run the balancing algorithm
  63101. ** on the leaf node first. If the balance proceeds far enough up the
  63102. ** tree that we can be sure that any problem in the internal node has
  63103. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  63104. ** walk the cursor up the tree to the internal node and balance it as
  63105. ** well. */
  63106. rc = balance(pCur);
  63107. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  63108. while( pCur->iPage>iCellDepth ){
  63109. releasePage(pCur->apPage[pCur->iPage--]);
  63110. }
  63111. rc = balance(pCur);
  63112. }
  63113. if( rc==SQLITE_OK ){
  63114. if( bSkipnext ){
  63115. assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
  63116. assert( pPage==pCur->apPage[pCur->iPage] || CORRUPT_DB );
  63117. assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
  63118. pCur->eState = CURSOR_SKIPNEXT;
  63119. if( iCellIdx>=pPage->nCell ){
  63120. pCur->skipNext = -1;
  63121. pCur->ix = pPage->nCell-1;
  63122. }else{
  63123. pCur->skipNext = 1;
  63124. }
  63125. }else{
  63126. rc = moveToRoot(pCur);
  63127. if( bPreserve ){
  63128. pCur->eState = CURSOR_REQUIRESEEK;
  63129. }
  63130. }
  63131. }
  63132. return rc;
  63133. }
  63134. /*
  63135. ** Create a new BTree table. Write into *piTable the page
  63136. ** number for the root page of the new table.
  63137. **
  63138. ** The type of type is determined by the flags parameter. Only the
  63139. ** following values of flags are currently in use. Other values for
  63140. ** flags might not work:
  63141. **
  63142. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  63143. ** BTREE_ZERODATA Used for SQL indices
  63144. */
  63145. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  63146. BtShared *pBt = p->pBt;
  63147. MemPage *pRoot;
  63148. Pgno pgnoRoot;
  63149. int rc;
  63150. int ptfFlags; /* Page-type flage for the root page of new table */
  63151. assert( sqlite3BtreeHoldsMutex(p) );
  63152. assert( pBt->inTransaction==TRANS_WRITE );
  63153. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  63154. #ifdef SQLITE_OMIT_AUTOVACUUM
  63155. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  63156. if( rc ){
  63157. return rc;
  63158. }
  63159. #else
  63160. if( pBt->autoVacuum ){
  63161. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  63162. MemPage *pPageMove; /* The page to move to. */
  63163. /* Creating a new table may probably require moving an existing database
  63164. ** to make room for the new tables root page. In case this page turns
  63165. ** out to be an overflow page, delete all overflow page-map caches
  63166. ** held by open cursors.
  63167. */
  63168. invalidateAllOverflowCache(pBt);
  63169. /* Read the value of meta[3] from the database to determine where the
  63170. ** root page of the new table should go. meta[3] is the largest root-page
  63171. ** created so far, so the new root-page is (meta[3]+1).
  63172. */
  63173. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  63174. pgnoRoot++;
  63175. /* The new root-page may not be allocated on a pointer-map page, or the
  63176. ** PENDING_BYTE page.
  63177. */
  63178. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  63179. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  63180. pgnoRoot++;
  63181. }
  63182. assert( pgnoRoot>=3 || CORRUPT_DB );
  63183. testcase( pgnoRoot<3 );
  63184. /* Allocate a page. The page that currently resides at pgnoRoot will
  63185. ** be moved to the allocated page (unless the allocated page happens
  63186. ** to reside at pgnoRoot).
  63187. */
  63188. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  63189. if( rc!=SQLITE_OK ){
  63190. return rc;
  63191. }
  63192. if( pgnoMove!=pgnoRoot ){
  63193. /* pgnoRoot is the page that will be used for the root-page of
  63194. ** the new table (assuming an error did not occur). But we were
  63195. ** allocated pgnoMove. If required (i.e. if it was not allocated
  63196. ** by extending the file), the current page at position pgnoMove
  63197. ** is already journaled.
  63198. */
  63199. u8 eType = 0;
  63200. Pgno iPtrPage = 0;
  63201. /* Save the positions of any open cursors. This is required in
  63202. ** case they are holding a reference to an xFetch reference
  63203. ** corresponding to page pgnoRoot. */
  63204. rc = saveAllCursors(pBt, 0, 0);
  63205. releasePage(pPageMove);
  63206. if( rc!=SQLITE_OK ){
  63207. return rc;
  63208. }
  63209. /* Move the page currently at pgnoRoot to pgnoMove. */
  63210. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  63211. if( rc!=SQLITE_OK ){
  63212. return rc;
  63213. }
  63214. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  63215. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  63216. rc = SQLITE_CORRUPT_BKPT;
  63217. }
  63218. if( rc!=SQLITE_OK ){
  63219. releasePage(pRoot);
  63220. return rc;
  63221. }
  63222. assert( eType!=PTRMAP_ROOTPAGE );
  63223. assert( eType!=PTRMAP_FREEPAGE );
  63224. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  63225. releasePage(pRoot);
  63226. /* Obtain the page at pgnoRoot */
  63227. if( rc!=SQLITE_OK ){
  63228. return rc;
  63229. }
  63230. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  63231. if( rc!=SQLITE_OK ){
  63232. return rc;
  63233. }
  63234. rc = sqlite3PagerWrite(pRoot->pDbPage);
  63235. if( rc!=SQLITE_OK ){
  63236. releasePage(pRoot);
  63237. return rc;
  63238. }
  63239. }else{
  63240. pRoot = pPageMove;
  63241. }
  63242. /* Update the pointer-map and meta-data with the new root-page number. */
  63243. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  63244. if( rc ){
  63245. releasePage(pRoot);
  63246. return rc;
  63247. }
  63248. /* When the new root page was allocated, page 1 was made writable in
  63249. ** order either to increase the database filesize, or to decrement the
  63250. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  63251. */
  63252. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  63253. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  63254. if( NEVER(rc) ){
  63255. releasePage(pRoot);
  63256. return rc;
  63257. }
  63258. }else{
  63259. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  63260. if( rc ) return rc;
  63261. }
  63262. #endif
  63263. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  63264. if( createTabFlags & BTREE_INTKEY ){
  63265. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  63266. }else{
  63267. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  63268. }
  63269. zeroPage(pRoot, ptfFlags);
  63270. sqlite3PagerUnref(pRoot->pDbPage);
  63271. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  63272. *piTable = (int)pgnoRoot;
  63273. return SQLITE_OK;
  63274. }
  63275. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  63276. int rc;
  63277. sqlite3BtreeEnter(p);
  63278. rc = btreeCreateTable(p, piTable, flags);
  63279. sqlite3BtreeLeave(p);
  63280. return rc;
  63281. }
  63282. /*
  63283. ** Erase the given database page and all its children. Return
  63284. ** the page to the freelist.
  63285. */
  63286. static int clearDatabasePage(
  63287. BtShared *pBt, /* The BTree that contains the table */
  63288. Pgno pgno, /* Page number to clear */
  63289. int freePageFlag, /* Deallocate page if true */
  63290. int *pnChange /* Add number of Cells freed to this counter */
  63291. ){
  63292. MemPage *pPage;
  63293. int rc;
  63294. unsigned char *pCell;
  63295. int i;
  63296. int hdr;
  63297. CellInfo info;
  63298. assert( sqlite3_mutex_held(pBt->mutex) );
  63299. if( pgno>btreePagecount(pBt) ){
  63300. return SQLITE_CORRUPT_BKPT;
  63301. }
  63302. rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
  63303. if( rc ) return rc;
  63304. if( pPage->bBusy ){
  63305. rc = SQLITE_CORRUPT_BKPT;
  63306. goto cleardatabasepage_out;
  63307. }
  63308. pPage->bBusy = 1;
  63309. hdr = pPage->hdrOffset;
  63310. for(i=0; i<pPage->nCell; i++){
  63311. pCell = findCell(pPage, i);
  63312. if( !pPage->leaf ){
  63313. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  63314. if( rc ) goto cleardatabasepage_out;
  63315. }
  63316. rc = clearCell(pPage, pCell, &info);
  63317. if( rc ) goto cleardatabasepage_out;
  63318. }
  63319. if( !pPage->leaf ){
  63320. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
  63321. if( rc ) goto cleardatabasepage_out;
  63322. }else if( pnChange ){
  63323. assert( pPage->intKey || CORRUPT_DB );
  63324. testcase( !pPage->intKey );
  63325. *pnChange += pPage->nCell;
  63326. }
  63327. if( freePageFlag ){
  63328. freePage(pPage, &rc);
  63329. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  63330. zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
  63331. }
  63332. cleardatabasepage_out:
  63333. pPage->bBusy = 0;
  63334. releasePage(pPage);
  63335. return rc;
  63336. }
  63337. /*
  63338. ** Delete all information from a single table in the database. iTable is
  63339. ** the page number of the root of the table. After this routine returns,
  63340. ** the root page is empty, but still exists.
  63341. **
  63342. ** This routine will fail with SQLITE_LOCKED if there are any open
  63343. ** read cursors on the table. Open write cursors are moved to the
  63344. ** root of the table.
  63345. **
  63346. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  63347. ** integer value pointed to by pnChange is incremented by the number of
  63348. ** entries in the table.
  63349. */
  63350. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  63351. int rc;
  63352. BtShared *pBt = p->pBt;
  63353. sqlite3BtreeEnter(p);
  63354. assert( p->inTrans==TRANS_WRITE );
  63355. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  63356. if( SQLITE_OK==rc ){
  63357. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  63358. ** is the root of a table b-tree - if it is not, the following call is
  63359. ** a no-op). */
  63360. invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
  63361. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  63362. }
  63363. sqlite3BtreeLeave(p);
  63364. return rc;
  63365. }
  63366. /*
  63367. ** Delete all information from the single table that pCur is open on.
  63368. **
  63369. ** This routine only work for pCur on an ephemeral table.
  63370. */
  63371. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
  63372. return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
  63373. }
  63374. /*
  63375. ** Erase all information in a table and add the root of the table to
  63376. ** the freelist. Except, the root of the principle table (the one on
  63377. ** page 1) is never added to the freelist.
  63378. **
  63379. ** This routine will fail with SQLITE_LOCKED if there are any open
  63380. ** cursors on the table.
  63381. **
  63382. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  63383. ** root page in the database file, then the last root page
  63384. ** in the database file is moved into the slot formerly occupied by
  63385. ** iTable and that last slot formerly occupied by the last root page
  63386. ** is added to the freelist instead of iTable. In this say, all
  63387. ** root pages are kept at the beginning of the database file, which
  63388. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  63389. ** page number that used to be the last root page in the file before
  63390. ** the move. If no page gets moved, *piMoved is set to 0.
  63391. ** The last root page is recorded in meta[3] and the value of
  63392. ** meta[3] is updated by this procedure.
  63393. */
  63394. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  63395. int rc;
  63396. MemPage *pPage = 0;
  63397. BtShared *pBt = p->pBt;
  63398. assert( sqlite3BtreeHoldsMutex(p) );
  63399. assert( p->inTrans==TRANS_WRITE );
  63400. assert( iTable>=2 );
  63401. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  63402. if( rc ) return rc;
  63403. rc = sqlite3BtreeClearTable(p, iTable, 0);
  63404. if( rc ){
  63405. releasePage(pPage);
  63406. return rc;
  63407. }
  63408. *piMoved = 0;
  63409. #ifdef SQLITE_OMIT_AUTOVACUUM
  63410. freePage(pPage, &rc);
  63411. releasePage(pPage);
  63412. #else
  63413. if( pBt->autoVacuum ){
  63414. Pgno maxRootPgno;
  63415. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  63416. if( iTable==maxRootPgno ){
  63417. /* If the table being dropped is the table with the largest root-page
  63418. ** number in the database, put the root page on the free list.
  63419. */
  63420. freePage(pPage, &rc);
  63421. releasePage(pPage);
  63422. if( rc!=SQLITE_OK ){
  63423. return rc;
  63424. }
  63425. }else{
  63426. /* The table being dropped does not have the largest root-page
  63427. ** number in the database. So move the page that does into the
  63428. ** gap left by the deleted root-page.
  63429. */
  63430. MemPage *pMove;
  63431. releasePage(pPage);
  63432. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  63433. if( rc!=SQLITE_OK ){
  63434. return rc;
  63435. }
  63436. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  63437. releasePage(pMove);
  63438. if( rc!=SQLITE_OK ){
  63439. return rc;
  63440. }
  63441. pMove = 0;
  63442. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  63443. freePage(pMove, &rc);
  63444. releasePage(pMove);
  63445. if( rc!=SQLITE_OK ){
  63446. return rc;
  63447. }
  63448. *piMoved = maxRootPgno;
  63449. }
  63450. /* Set the new 'max-root-page' value in the database header. This
  63451. ** is the old value less one, less one more if that happens to
  63452. ** be a root-page number, less one again if that is the
  63453. ** PENDING_BYTE_PAGE.
  63454. */
  63455. maxRootPgno--;
  63456. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  63457. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  63458. maxRootPgno--;
  63459. }
  63460. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  63461. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  63462. }else{
  63463. freePage(pPage, &rc);
  63464. releasePage(pPage);
  63465. }
  63466. #endif
  63467. return rc;
  63468. }
  63469. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  63470. int rc;
  63471. sqlite3BtreeEnter(p);
  63472. rc = btreeDropTable(p, iTable, piMoved);
  63473. sqlite3BtreeLeave(p);
  63474. return rc;
  63475. }
  63476. /*
  63477. ** This function may only be called if the b-tree connection already
  63478. ** has a read or write transaction open on the database.
  63479. **
  63480. ** Read the meta-information out of a database file. Meta[0]
  63481. ** is the number of free pages currently in the database. Meta[1]
  63482. ** through meta[15] are available for use by higher layers. Meta[0]
  63483. ** is read-only, the others are read/write.
  63484. **
  63485. ** The schema layer numbers meta values differently. At the schema
  63486. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  63487. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  63488. **
  63489. ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
  63490. ** of reading the value out of the header, it instead loads the "DataVersion"
  63491. ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
  63492. ** database file. It is a number computed by the pager. But its access
  63493. ** pattern is the same as header meta values, and so it is convenient to
  63494. ** read it from this routine.
  63495. */
  63496. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  63497. BtShared *pBt = p->pBt;
  63498. sqlite3BtreeEnter(p);
  63499. assert( p->inTrans>TRANS_NONE );
  63500. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  63501. assert( pBt->pPage1 );
  63502. assert( idx>=0 && idx<=15 );
  63503. if( idx==BTREE_DATA_VERSION ){
  63504. *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
  63505. }else{
  63506. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  63507. }
  63508. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  63509. ** database, mark the database as read-only. */
  63510. #ifdef SQLITE_OMIT_AUTOVACUUM
  63511. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  63512. pBt->btsFlags |= BTS_READ_ONLY;
  63513. }
  63514. #endif
  63515. sqlite3BtreeLeave(p);
  63516. }
  63517. /*
  63518. ** Write meta-information back into the database. Meta[0] is
  63519. ** read-only and may not be written.
  63520. */
  63521. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  63522. BtShared *pBt = p->pBt;
  63523. unsigned char *pP1;
  63524. int rc;
  63525. assert( idx>=1 && idx<=15 );
  63526. sqlite3BtreeEnter(p);
  63527. assert( p->inTrans==TRANS_WRITE );
  63528. assert( pBt->pPage1!=0 );
  63529. pP1 = pBt->pPage1->aData;
  63530. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  63531. if( rc==SQLITE_OK ){
  63532. put4byte(&pP1[36 + idx*4], iMeta);
  63533. #ifndef SQLITE_OMIT_AUTOVACUUM
  63534. if( idx==BTREE_INCR_VACUUM ){
  63535. assert( pBt->autoVacuum || iMeta==0 );
  63536. assert( iMeta==0 || iMeta==1 );
  63537. pBt->incrVacuum = (u8)iMeta;
  63538. }
  63539. #endif
  63540. }
  63541. sqlite3BtreeLeave(p);
  63542. return rc;
  63543. }
  63544. #ifndef SQLITE_OMIT_BTREECOUNT
  63545. /*
  63546. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  63547. ** number of entries in the b-tree and write the result to *pnEntry.
  63548. **
  63549. ** SQLITE_OK is returned if the operation is successfully executed.
  63550. ** Otherwise, if an error is encountered (i.e. an IO error or database
  63551. ** corruption) an SQLite error code is returned.
  63552. */
  63553. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  63554. i64 nEntry = 0; /* Value to return in *pnEntry */
  63555. int rc; /* Return code */
  63556. if( pCur->pgnoRoot==0 ){
  63557. *pnEntry = 0;
  63558. return SQLITE_OK;
  63559. }
  63560. rc = moveToRoot(pCur);
  63561. /* Unless an error occurs, the following loop runs one iteration for each
  63562. ** page in the B-Tree structure (not including overflow pages).
  63563. */
  63564. while( rc==SQLITE_OK ){
  63565. int iIdx; /* Index of child node in parent */
  63566. MemPage *pPage; /* Current page of the b-tree */
  63567. /* If this is a leaf page or the tree is not an int-key tree, then
  63568. ** this page contains countable entries. Increment the entry counter
  63569. ** accordingly.
  63570. */
  63571. pPage = pCur->apPage[pCur->iPage];
  63572. if( pPage->leaf || !pPage->intKey ){
  63573. nEntry += pPage->nCell;
  63574. }
  63575. /* pPage is a leaf node. This loop navigates the cursor so that it
  63576. ** points to the first interior cell that it points to the parent of
  63577. ** the next page in the tree that has not yet been visited. The
  63578. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  63579. ** of the page, or to the number of cells in the page if the next page
  63580. ** to visit is the right-child of its parent.
  63581. **
  63582. ** If all pages in the tree have been visited, return SQLITE_OK to the
  63583. ** caller.
  63584. */
  63585. if( pPage->leaf ){
  63586. do {
  63587. if( pCur->iPage==0 ){
  63588. /* All pages of the b-tree have been visited. Return successfully. */
  63589. *pnEntry = nEntry;
  63590. return moveToRoot(pCur);
  63591. }
  63592. moveToParent(pCur);
  63593. }while ( pCur->ix>=pCur->apPage[pCur->iPage]->nCell );
  63594. pCur->ix++;
  63595. pPage = pCur->apPage[pCur->iPage];
  63596. }
  63597. /* Descend to the child node of the cell that the cursor currently
  63598. ** points at. This is the right-child if (iIdx==pPage->nCell).
  63599. */
  63600. iIdx = pCur->ix;
  63601. if( iIdx==pPage->nCell ){
  63602. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  63603. }else{
  63604. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  63605. }
  63606. }
  63607. /* An error has occurred. Return an error code. */
  63608. return rc;
  63609. }
  63610. #endif
  63611. /*
  63612. ** Return the pager associated with a BTree. This routine is used for
  63613. ** testing and debugging only.
  63614. */
  63615. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  63616. return p->pBt->pPager;
  63617. }
  63618. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  63619. /*
  63620. ** Append a message to the error message string.
  63621. */
  63622. static void checkAppendMsg(
  63623. IntegrityCk *pCheck,
  63624. const char *zFormat,
  63625. ...
  63626. ){
  63627. va_list ap;
  63628. if( !pCheck->mxErr ) return;
  63629. pCheck->mxErr--;
  63630. pCheck->nErr++;
  63631. va_start(ap, zFormat);
  63632. if( pCheck->errMsg.nChar ){
  63633. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  63634. }
  63635. if( pCheck->zPfx ){
  63636. sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
  63637. }
  63638. sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
  63639. va_end(ap);
  63640. if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
  63641. pCheck->mallocFailed = 1;
  63642. }
  63643. }
  63644. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  63645. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  63646. /*
  63647. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  63648. ** corresponds to page iPg is already set.
  63649. */
  63650. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  63651. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  63652. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  63653. }
  63654. /*
  63655. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  63656. */
  63657. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  63658. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  63659. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  63660. }
  63661. /*
  63662. ** Add 1 to the reference count for page iPage. If this is the second
  63663. ** reference to the page, add an error message to pCheck->zErrMsg.
  63664. ** Return 1 if there are 2 or more references to the page and 0 if
  63665. ** if this is the first reference to the page.
  63666. **
  63667. ** Also check that the page number is in bounds.
  63668. */
  63669. static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  63670. if( iPage==0 ) return 1;
  63671. if( iPage>pCheck->nPage ){
  63672. checkAppendMsg(pCheck, "invalid page number %d", iPage);
  63673. return 1;
  63674. }
  63675. if( getPageReferenced(pCheck, iPage) ){
  63676. checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
  63677. return 1;
  63678. }
  63679. setPageReferenced(pCheck, iPage);
  63680. return 0;
  63681. }
  63682. #ifndef SQLITE_OMIT_AUTOVACUUM
  63683. /*
  63684. ** Check that the entry in the pointer-map for page iChild maps to
  63685. ** page iParent, pointer type ptrType. If not, append an error message
  63686. ** to pCheck.
  63687. */
  63688. static void checkPtrmap(
  63689. IntegrityCk *pCheck, /* Integrity check context */
  63690. Pgno iChild, /* Child page number */
  63691. u8 eType, /* Expected pointer map type */
  63692. Pgno iParent /* Expected pointer map parent page number */
  63693. ){
  63694. int rc;
  63695. u8 ePtrmapType;
  63696. Pgno iPtrmapParent;
  63697. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  63698. if( rc!=SQLITE_OK ){
  63699. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  63700. checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
  63701. return;
  63702. }
  63703. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  63704. checkAppendMsg(pCheck,
  63705. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  63706. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  63707. }
  63708. }
  63709. #endif
  63710. /*
  63711. ** Check the integrity of the freelist or of an overflow page list.
  63712. ** Verify that the number of pages on the list is N.
  63713. */
  63714. static void checkList(
  63715. IntegrityCk *pCheck, /* Integrity checking context */
  63716. int isFreeList, /* True for a freelist. False for overflow page list */
  63717. int iPage, /* Page number for first page in the list */
  63718. int N /* Expected number of pages in the list */
  63719. ){
  63720. int i;
  63721. int expected = N;
  63722. int iFirst = iPage;
  63723. while( N-- > 0 && pCheck->mxErr ){
  63724. DbPage *pOvflPage;
  63725. unsigned char *pOvflData;
  63726. if( iPage<1 ){
  63727. checkAppendMsg(pCheck,
  63728. "%d of %d pages missing from overflow list starting at %d",
  63729. N+1, expected, iFirst);
  63730. break;
  63731. }
  63732. if( checkRef(pCheck, iPage) ) break;
  63733. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
  63734. checkAppendMsg(pCheck, "failed to get page %d", iPage);
  63735. break;
  63736. }
  63737. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  63738. if( isFreeList ){
  63739. int n = get4byte(&pOvflData[4]);
  63740. #ifndef SQLITE_OMIT_AUTOVACUUM
  63741. if( pCheck->pBt->autoVacuum ){
  63742. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
  63743. }
  63744. #endif
  63745. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  63746. checkAppendMsg(pCheck,
  63747. "freelist leaf count too big on page %d", iPage);
  63748. N--;
  63749. }else{
  63750. for(i=0; i<n; i++){
  63751. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  63752. #ifndef SQLITE_OMIT_AUTOVACUUM
  63753. if( pCheck->pBt->autoVacuum ){
  63754. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
  63755. }
  63756. #endif
  63757. checkRef(pCheck, iFreePage);
  63758. }
  63759. N -= n;
  63760. }
  63761. }
  63762. #ifndef SQLITE_OMIT_AUTOVACUUM
  63763. else{
  63764. /* If this database supports auto-vacuum and iPage is not the last
  63765. ** page in this overflow list, check that the pointer-map entry for
  63766. ** the following page matches iPage.
  63767. */
  63768. if( pCheck->pBt->autoVacuum && N>0 ){
  63769. i = get4byte(pOvflData);
  63770. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
  63771. }
  63772. }
  63773. #endif
  63774. iPage = get4byte(pOvflData);
  63775. sqlite3PagerUnref(pOvflPage);
  63776. if( isFreeList && N<(iPage!=0) ){
  63777. checkAppendMsg(pCheck, "free-page count in header is too small");
  63778. }
  63779. }
  63780. }
  63781. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  63782. /*
  63783. ** An implementation of a min-heap.
  63784. **
  63785. ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
  63786. ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
  63787. ** and aHeap[N*2+1].
  63788. **
  63789. ** The heap property is this: Every node is less than or equal to both
  63790. ** of its daughter nodes. A consequence of the heap property is that the
  63791. ** root node aHeap[1] is always the minimum value currently in the heap.
  63792. **
  63793. ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
  63794. ** the heap, preserving the heap property. The btreeHeapPull() routine
  63795. ** removes the root element from the heap (the minimum value in the heap)
  63796. ** and then moves other nodes around as necessary to preserve the heap
  63797. ** property.
  63798. **
  63799. ** This heap is used for cell overlap and coverage testing. Each u32
  63800. ** entry represents the span of a cell or freeblock on a btree page.
  63801. ** The upper 16 bits are the index of the first byte of a range and the
  63802. ** lower 16 bits are the index of the last byte of that range.
  63803. */
  63804. static void btreeHeapInsert(u32 *aHeap, u32 x){
  63805. u32 j, i = ++aHeap[0];
  63806. aHeap[i] = x;
  63807. while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
  63808. x = aHeap[j];
  63809. aHeap[j] = aHeap[i];
  63810. aHeap[i] = x;
  63811. i = j;
  63812. }
  63813. }
  63814. static int btreeHeapPull(u32 *aHeap, u32 *pOut){
  63815. u32 j, i, x;
  63816. if( (x = aHeap[0])==0 ) return 0;
  63817. *pOut = aHeap[1];
  63818. aHeap[1] = aHeap[x];
  63819. aHeap[x] = 0xffffffff;
  63820. aHeap[0]--;
  63821. i = 1;
  63822. while( (j = i*2)<=aHeap[0] ){
  63823. if( aHeap[j]>aHeap[j+1] ) j++;
  63824. if( aHeap[i]<aHeap[j] ) break;
  63825. x = aHeap[i];
  63826. aHeap[i] = aHeap[j];
  63827. aHeap[j] = x;
  63828. i = j;
  63829. }
  63830. return 1;
  63831. }
  63832. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  63833. /*
  63834. ** Do various sanity checks on a single page of a tree. Return
  63835. ** the tree depth. Root pages return 0. Parents of root pages
  63836. ** return 1, and so forth.
  63837. **
  63838. ** These checks are done:
  63839. **
  63840. ** 1. Make sure that cells and freeblocks do not overlap
  63841. ** but combine to completely cover the page.
  63842. ** 2. Make sure integer cell keys are in order.
  63843. ** 3. Check the integrity of overflow pages.
  63844. ** 4. Recursively call checkTreePage on all children.
  63845. ** 5. Verify that the depth of all children is the same.
  63846. */
  63847. static int checkTreePage(
  63848. IntegrityCk *pCheck, /* Context for the sanity check */
  63849. int iPage, /* Page number of the page to check */
  63850. i64 *piMinKey, /* Write minimum integer primary key here */
  63851. i64 maxKey /* Error if integer primary key greater than this */
  63852. ){
  63853. MemPage *pPage = 0; /* The page being analyzed */
  63854. int i; /* Loop counter */
  63855. int rc; /* Result code from subroutine call */
  63856. int depth = -1, d2; /* Depth of a subtree */
  63857. int pgno; /* Page number */
  63858. int nFrag; /* Number of fragmented bytes on the page */
  63859. int hdr; /* Offset to the page header */
  63860. int cellStart; /* Offset to the start of the cell pointer array */
  63861. int nCell; /* Number of cells */
  63862. int doCoverageCheck = 1; /* True if cell coverage checking should be done */
  63863. int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
  63864. ** False if IPK must be strictly less than maxKey */
  63865. u8 *data; /* Page content */
  63866. u8 *pCell; /* Cell content */
  63867. u8 *pCellIdx; /* Next element of the cell pointer array */
  63868. BtShared *pBt; /* The BtShared object that owns pPage */
  63869. u32 pc; /* Address of a cell */
  63870. u32 usableSize; /* Usable size of the page */
  63871. u32 contentOffset; /* Offset to the start of the cell content area */
  63872. u32 *heap = 0; /* Min-heap used for checking cell coverage */
  63873. u32 x, prev = 0; /* Next and previous entry on the min-heap */
  63874. const char *saved_zPfx = pCheck->zPfx;
  63875. int saved_v1 = pCheck->v1;
  63876. int saved_v2 = pCheck->v2;
  63877. u8 savedIsInit = 0;
  63878. /* Check that the page exists
  63879. */
  63880. pBt = pCheck->pBt;
  63881. usableSize = pBt->usableSize;
  63882. if( iPage==0 ) return 0;
  63883. if( checkRef(pCheck, iPage) ) return 0;
  63884. pCheck->zPfx = "Page %d: ";
  63885. pCheck->v1 = iPage;
  63886. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  63887. checkAppendMsg(pCheck,
  63888. "unable to get the page. error code=%d", rc);
  63889. goto end_of_check;
  63890. }
  63891. /* Clear MemPage.isInit to make sure the corruption detection code in
  63892. ** btreeInitPage() is executed. */
  63893. savedIsInit = pPage->isInit;
  63894. pPage->isInit = 0;
  63895. if( (rc = btreeInitPage(pPage))!=0 ){
  63896. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  63897. checkAppendMsg(pCheck,
  63898. "btreeInitPage() returns error code %d", rc);
  63899. goto end_of_check;
  63900. }
  63901. data = pPage->aData;
  63902. hdr = pPage->hdrOffset;
  63903. /* Set up for cell analysis */
  63904. pCheck->zPfx = "On tree page %d cell %d: ";
  63905. contentOffset = get2byteNotZero(&data[hdr+5]);
  63906. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  63907. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  63908. ** number of cells on the page. */
  63909. nCell = get2byte(&data[hdr+3]);
  63910. assert( pPage->nCell==nCell );
  63911. /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
  63912. ** immediately follows the b-tree page header. */
  63913. cellStart = hdr + 12 - 4*pPage->leaf;
  63914. assert( pPage->aCellIdx==&data[cellStart] );
  63915. pCellIdx = &data[cellStart + 2*(nCell-1)];
  63916. if( !pPage->leaf ){
  63917. /* Analyze the right-child page of internal pages */
  63918. pgno = get4byte(&data[hdr+8]);
  63919. #ifndef SQLITE_OMIT_AUTOVACUUM
  63920. if( pBt->autoVacuum ){
  63921. pCheck->zPfx = "On page %d at right child: ";
  63922. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  63923. }
  63924. #endif
  63925. depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  63926. keyCanBeEqual = 0;
  63927. }else{
  63928. /* For leaf pages, the coverage check will occur in the same loop
  63929. ** as the other cell checks, so initialize the heap. */
  63930. heap = pCheck->heap;
  63931. heap[0] = 0;
  63932. }
  63933. /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
  63934. ** integer offsets to the cell contents. */
  63935. for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
  63936. CellInfo info;
  63937. /* Check cell size */
  63938. pCheck->v2 = i;
  63939. assert( pCellIdx==&data[cellStart + i*2] );
  63940. pc = get2byteAligned(pCellIdx);
  63941. pCellIdx -= 2;
  63942. if( pc<contentOffset || pc>usableSize-4 ){
  63943. checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
  63944. pc, contentOffset, usableSize-4);
  63945. doCoverageCheck = 0;
  63946. continue;
  63947. }
  63948. pCell = &data[pc];
  63949. pPage->xParseCell(pPage, pCell, &info);
  63950. if( pc+info.nSize>usableSize ){
  63951. checkAppendMsg(pCheck, "Extends off end of page");
  63952. doCoverageCheck = 0;
  63953. continue;
  63954. }
  63955. /* Check for integer primary key out of range */
  63956. if( pPage->intKey ){
  63957. if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
  63958. checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
  63959. }
  63960. maxKey = info.nKey;
  63961. keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
  63962. }
  63963. /* Check the content overflow list */
  63964. if( info.nPayload>info.nLocal ){
  63965. int nPage; /* Number of pages on the overflow chain */
  63966. Pgno pgnoOvfl; /* First page of the overflow chain */
  63967. assert( pc + info.nSize - 4 <= usableSize );
  63968. nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
  63969. pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
  63970. #ifndef SQLITE_OMIT_AUTOVACUUM
  63971. if( pBt->autoVacuum ){
  63972. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
  63973. }
  63974. #endif
  63975. checkList(pCheck, 0, pgnoOvfl, nPage);
  63976. }
  63977. if( !pPage->leaf ){
  63978. /* Check sanity of left child page for internal pages */
  63979. pgno = get4byte(pCell);
  63980. #ifndef SQLITE_OMIT_AUTOVACUUM
  63981. if( pBt->autoVacuum ){
  63982. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  63983. }
  63984. #endif
  63985. d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  63986. keyCanBeEqual = 0;
  63987. if( d2!=depth ){
  63988. checkAppendMsg(pCheck, "Child page depth differs");
  63989. depth = d2;
  63990. }
  63991. }else{
  63992. /* Populate the coverage-checking heap for leaf pages */
  63993. btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
  63994. }
  63995. }
  63996. *piMinKey = maxKey;
  63997. /* Check for complete coverage of the page
  63998. */
  63999. pCheck->zPfx = 0;
  64000. if( doCoverageCheck && pCheck->mxErr>0 ){
  64001. /* For leaf pages, the min-heap has already been initialized and the
  64002. ** cells have already been inserted. But for internal pages, that has
  64003. ** not yet been done, so do it now */
  64004. if( !pPage->leaf ){
  64005. heap = pCheck->heap;
  64006. heap[0] = 0;
  64007. for(i=nCell-1; i>=0; i--){
  64008. u32 size;
  64009. pc = get2byteAligned(&data[cellStart+i*2]);
  64010. size = pPage->xCellSize(pPage, &data[pc]);
  64011. btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
  64012. }
  64013. }
  64014. /* Add the freeblocks to the min-heap
  64015. **
  64016. ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
  64017. ** is the offset of the first freeblock, or zero if there are no
  64018. ** freeblocks on the page.
  64019. */
  64020. i = get2byte(&data[hdr+1]);
  64021. while( i>0 ){
  64022. int size, j;
  64023. assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  64024. size = get2byte(&data[i+2]);
  64025. assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
  64026. btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
  64027. /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
  64028. ** big-endian integer which is the offset in the b-tree page of the next
  64029. ** freeblock in the chain, or zero if the freeblock is the last on the
  64030. ** chain. */
  64031. j = get2byte(&data[i]);
  64032. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  64033. ** increasing offset. */
  64034. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  64035. assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  64036. i = j;
  64037. }
  64038. /* Analyze the min-heap looking for overlap between cells and/or
  64039. ** freeblocks, and counting the number of untracked bytes in nFrag.
  64040. **
  64041. ** Each min-heap entry is of the form: (start_address<<16)|end_address.
  64042. ** There is an implied first entry the covers the page header, the cell
  64043. ** pointer index, and the gap between the cell pointer index and the start
  64044. ** of cell content.
  64045. **
  64046. ** The loop below pulls entries from the min-heap in order and compares
  64047. ** the start_address against the previous end_address. If there is an
  64048. ** overlap, that means bytes are used multiple times. If there is a gap,
  64049. ** that gap is added to the fragmentation count.
  64050. */
  64051. nFrag = 0;
  64052. prev = contentOffset - 1; /* Implied first min-heap entry */
  64053. while( btreeHeapPull(heap,&x) ){
  64054. if( (prev&0xffff)>=(x>>16) ){
  64055. checkAppendMsg(pCheck,
  64056. "Multiple uses for byte %u of page %d", x>>16, iPage);
  64057. break;
  64058. }else{
  64059. nFrag += (x>>16) - (prev&0xffff) - 1;
  64060. prev = x;
  64061. }
  64062. }
  64063. nFrag += usableSize - (prev&0xffff) - 1;
  64064. /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
  64065. ** is stored in the fifth field of the b-tree page header.
  64066. ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
  64067. ** number of fragmented free bytes within the cell content area.
  64068. */
  64069. if( heap[0]==0 && nFrag!=data[hdr+7] ){
  64070. checkAppendMsg(pCheck,
  64071. "Fragmentation of %d bytes reported as %d on page %d",
  64072. nFrag, data[hdr+7], iPage);
  64073. }
  64074. }
  64075. end_of_check:
  64076. if( !doCoverageCheck ) pPage->isInit = savedIsInit;
  64077. releasePage(pPage);
  64078. pCheck->zPfx = saved_zPfx;
  64079. pCheck->v1 = saved_v1;
  64080. pCheck->v2 = saved_v2;
  64081. return depth+1;
  64082. }
  64083. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  64084. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  64085. /*
  64086. ** This routine does a complete check of the given BTree file. aRoot[] is
  64087. ** an array of pages numbers were each page number is the root page of
  64088. ** a table. nRoot is the number of entries in aRoot.
  64089. **
  64090. ** A read-only or read-write transaction must be opened before calling
  64091. ** this function.
  64092. **
  64093. ** Write the number of error seen in *pnErr. Except for some memory
  64094. ** allocation errors, an error message held in memory obtained from
  64095. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  64096. ** returned. If a memory allocation error occurs, NULL is returned.
  64097. */
  64098. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  64099. Btree *p, /* The btree to be checked */
  64100. int *aRoot, /* An array of root pages numbers for individual trees */
  64101. int nRoot, /* Number of entries in aRoot[] */
  64102. int mxErr, /* Stop reporting errors after this many */
  64103. int *pnErr /* Write number of errors seen to this variable */
  64104. ){
  64105. Pgno i;
  64106. IntegrityCk sCheck;
  64107. BtShared *pBt = p->pBt;
  64108. int savedDbFlags = pBt->db->flags;
  64109. char zErr[100];
  64110. VVA_ONLY( int nRef );
  64111. sqlite3BtreeEnter(p);
  64112. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  64113. VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
  64114. assert( nRef>=0 );
  64115. sCheck.pBt = pBt;
  64116. sCheck.pPager = pBt->pPager;
  64117. sCheck.nPage = btreePagecount(sCheck.pBt);
  64118. sCheck.mxErr = mxErr;
  64119. sCheck.nErr = 0;
  64120. sCheck.mallocFailed = 0;
  64121. sCheck.zPfx = 0;
  64122. sCheck.v1 = 0;
  64123. sCheck.v2 = 0;
  64124. sCheck.aPgRef = 0;
  64125. sCheck.heap = 0;
  64126. sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  64127. sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
  64128. if( sCheck.nPage==0 ){
  64129. goto integrity_ck_cleanup;
  64130. }
  64131. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  64132. if( !sCheck.aPgRef ){
  64133. sCheck.mallocFailed = 1;
  64134. goto integrity_ck_cleanup;
  64135. }
  64136. sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
  64137. if( sCheck.heap==0 ){
  64138. sCheck.mallocFailed = 1;
  64139. goto integrity_ck_cleanup;
  64140. }
  64141. i = PENDING_BYTE_PAGE(pBt);
  64142. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  64143. /* Check the integrity of the freelist
  64144. */
  64145. sCheck.zPfx = "Main freelist: ";
  64146. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  64147. get4byte(&pBt->pPage1->aData[36]));
  64148. sCheck.zPfx = 0;
  64149. /* Check all the tables.
  64150. */
  64151. testcase( pBt->db->flags & SQLITE_CellSizeCk );
  64152. pBt->db->flags &= ~SQLITE_CellSizeCk;
  64153. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  64154. i64 notUsed;
  64155. if( aRoot[i]==0 ) continue;
  64156. #ifndef SQLITE_OMIT_AUTOVACUUM
  64157. if( pBt->autoVacuum && aRoot[i]>1 ){
  64158. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
  64159. }
  64160. #endif
  64161. checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
  64162. }
  64163. pBt->db->flags = savedDbFlags;
  64164. /* Make sure every page in the file is referenced
  64165. */
  64166. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  64167. #ifdef SQLITE_OMIT_AUTOVACUUM
  64168. if( getPageReferenced(&sCheck, i)==0 ){
  64169. checkAppendMsg(&sCheck, "Page %d is never used", i);
  64170. }
  64171. #else
  64172. /* If the database supports auto-vacuum, make sure no tables contain
  64173. ** references to pointer-map pages.
  64174. */
  64175. if( getPageReferenced(&sCheck, i)==0 &&
  64176. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  64177. checkAppendMsg(&sCheck, "Page %d is never used", i);
  64178. }
  64179. if( getPageReferenced(&sCheck, i)!=0 &&
  64180. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  64181. checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
  64182. }
  64183. #endif
  64184. }
  64185. /* Clean up and report errors.
  64186. */
  64187. integrity_ck_cleanup:
  64188. sqlite3PageFree(sCheck.heap);
  64189. sqlite3_free(sCheck.aPgRef);
  64190. if( sCheck.mallocFailed ){
  64191. sqlite3StrAccumReset(&sCheck.errMsg);
  64192. sCheck.nErr++;
  64193. }
  64194. *pnErr = sCheck.nErr;
  64195. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  64196. /* Make sure this analysis did not leave any unref() pages. */
  64197. assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
  64198. sqlite3BtreeLeave(p);
  64199. return sqlite3StrAccumFinish(&sCheck.errMsg);
  64200. }
  64201. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  64202. /*
  64203. ** Return the full pathname of the underlying database file. Return
  64204. ** an empty string if the database is in-memory or a TEMP database.
  64205. **
  64206. ** The pager filename is invariant as long as the pager is
  64207. ** open so it is safe to access without the BtShared mutex.
  64208. */
  64209. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  64210. assert( p->pBt->pPager!=0 );
  64211. return sqlite3PagerFilename(p->pBt->pPager, 1);
  64212. }
  64213. /*
  64214. ** Return the pathname of the journal file for this database. The return
  64215. ** value of this routine is the same regardless of whether the journal file
  64216. ** has been created or not.
  64217. **
  64218. ** The pager journal filename is invariant as long as the pager is
  64219. ** open so it is safe to access without the BtShared mutex.
  64220. */
  64221. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  64222. assert( p->pBt->pPager!=0 );
  64223. return sqlite3PagerJournalname(p->pBt->pPager);
  64224. }
  64225. /*
  64226. ** Return non-zero if a transaction is active.
  64227. */
  64228. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  64229. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  64230. return (p && (p->inTrans==TRANS_WRITE));
  64231. }
  64232. #ifndef SQLITE_OMIT_WAL
  64233. /*
  64234. ** Run a checkpoint on the Btree passed as the first argument.
  64235. **
  64236. ** Return SQLITE_LOCKED if this or any other connection has an open
  64237. ** transaction on the shared-cache the argument Btree is connected to.
  64238. **
  64239. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  64240. */
  64241. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  64242. int rc = SQLITE_OK;
  64243. if( p ){
  64244. BtShared *pBt = p->pBt;
  64245. sqlite3BtreeEnter(p);
  64246. if( pBt->inTransaction!=TRANS_NONE ){
  64247. rc = SQLITE_LOCKED;
  64248. }else{
  64249. rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
  64250. }
  64251. sqlite3BtreeLeave(p);
  64252. }
  64253. return rc;
  64254. }
  64255. #endif
  64256. /*
  64257. ** Return non-zero if a read (or write) transaction is active.
  64258. */
  64259. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  64260. assert( p );
  64261. assert( sqlite3_mutex_held(p->db->mutex) );
  64262. return p->inTrans!=TRANS_NONE;
  64263. }
  64264. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  64265. assert( p );
  64266. assert( sqlite3_mutex_held(p->db->mutex) );
  64267. return p->nBackup!=0;
  64268. }
  64269. /*
  64270. ** This function returns a pointer to a blob of memory associated with
  64271. ** a single shared-btree. The memory is used by client code for its own
  64272. ** purposes (for example, to store a high-level schema associated with
  64273. ** the shared-btree). The btree layer manages reference counting issues.
  64274. **
  64275. ** The first time this is called on a shared-btree, nBytes bytes of memory
  64276. ** are allocated, zeroed, and returned to the caller. For each subsequent
  64277. ** call the nBytes parameter is ignored and a pointer to the same blob
  64278. ** of memory returned.
  64279. **
  64280. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  64281. ** allocated, a null pointer is returned. If the blob has already been
  64282. ** allocated, it is returned as normal.
  64283. **
  64284. ** Just before the shared-btree is closed, the function passed as the
  64285. ** xFree argument when the memory allocation was made is invoked on the
  64286. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  64287. ** on the memory, the btree layer does that.
  64288. */
  64289. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  64290. BtShared *pBt = p->pBt;
  64291. sqlite3BtreeEnter(p);
  64292. if( !pBt->pSchema && nBytes ){
  64293. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  64294. pBt->xFreeSchema = xFree;
  64295. }
  64296. sqlite3BtreeLeave(p);
  64297. return pBt->pSchema;
  64298. }
  64299. /*
  64300. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  64301. ** btree as the argument handle holds an exclusive lock on the
  64302. ** sqlite_master table. Otherwise SQLITE_OK.
  64303. */
  64304. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  64305. int rc;
  64306. assert( sqlite3_mutex_held(p->db->mutex) );
  64307. sqlite3BtreeEnter(p);
  64308. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  64309. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  64310. sqlite3BtreeLeave(p);
  64311. return rc;
  64312. }
  64313. #ifndef SQLITE_OMIT_SHARED_CACHE
  64314. /*
  64315. ** Obtain a lock on the table whose root page is iTab. The
  64316. ** lock is a write lock if isWritelock is true or a read lock
  64317. ** if it is false.
  64318. */
  64319. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  64320. int rc = SQLITE_OK;
  64321. assert( p->inTrans!=TRANS_NONE );
  64322. if( p->sharable ){
  64323. u8 lockType = READ_LOCK + isWriteLock;
  64324. assert( READ_LOCK+1==WRITE_LOCK );
  64325. assert( isWriteLock==0 || isWriteLock==1 );
  64326. sqlite3BtreeEnter(p);
  64327. rc = querySharedCacheTableLock(p, iTab, lockType);
  64328. if( rc==SQLITE_OK ){
  64329. rc = setSharedCacheTableLock(p, iTab, lockType);
  64330. }
  64331. sqlite3BtreeLeave(p);
  64332. }
  64333. return rc;
  64334. }
  64335. #endif
  64336. #ifndef SQLITE_OMIT_INCRBLOB
  64337. /*
  64338. ** Argument pCsr must be a cursor opened for writing on an
  64339. ** INTKEY table currently pointing at a valid table entry.
  64340. ** This function modifies the data stored as part of that entry.
  64341. **
  64342. ** Only the data content may only be modified, it is not possible to
  64343. ** change the length of the data stored. If this function is called with
  64344. ** parameters that attempt to write past the end of the existing data,
  64345. ** no modifications are made and SQLITE_CORRUPT is returned.
  64346. */
  64347. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  64348. int rc;
  64349. assert( cursorOwnsBtShared(pCsr) );
  64350. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  64351. assert( pCsr->curFlags & BTCF_Incrblob );
  64352. rc = restoreCursorPosition(pCsr);
  64353. if( rc!=SQLITE_OK ){
  64354. return rc;
  64355. }
  64356. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  64357. if( pCsr->eState!=CURSOR_VALID ){
  64358. return SQLITE_ABORT;
  64359. }
  64360. /* Save the positions of all other cursors open on this table. This is
  64361. ** required in case any of them are holding references to an xFetch
  64362. ** version of the b-tree page modified by the accessPayload call below.
  64363. **
  64364. ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
  64365. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  64366. ** saveAllCursors can only return SQLITE_OK.
  64367. */
  64368. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  64369. assert( rc==SQLITE_OK );
  64370. /* Check some assumptions:
  64371. ** (a) the cursor is open for writing,
  64372. ** (b) there is a read/write transaction open,
  64373. ** (c) the connection holds a write-lock on the table (if required),
  64374. ** (d) there are no conflicting read-locks, and
  64375. ** (e) the cursor points at a valid row of an intKey table.
  64376. */
  64377. if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
  64378. return SQLITE_READONLY;
  64379. }
  64380. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  64381. && pCsr->pBt->inTransaction==TRANS_WRITE );
  64382. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  64383. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  64384. assert( pCsr->apPage[pCsr->iPage]->intKey );
  64385. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  64386. }
  64387. /*
  64388. ** Mark this cursor as an incremental blob cursor.
  64389. */
  64390. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
  64391. pCur->curFlags |= BTCF_Incrblob;
  64392. pCur->pBtree->hasIncrblobCur = 1;
  64393. }
  64394. #endif
  64395. /*
  64396. ** Set both the "read version" (single byte at byte offset 18) and
  64397. ** "write version" (single byte at byte offset 19) fields in the database
  64398. ** header to iVersion.
  64399. */
  64400. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  64401. BtShared *pBt = pBtree->pBt;
  64402. int rc; /* Return code */
  64403. assert( iVersion==1 || iVersion==2 );
  64404. /* If setting the version fields to 1, do not automatically open the
  64405. ** WAL connection, even if the version fields are currently set to 2.
  64406. */
  64407. pBt->btsFlags &= ~BTS_NO_WAL;
  64408. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  64409. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  64410. if( rc==SQLITE_OK ){
  64411. u8 *aData = pBt->pPage1->aData;
  64412. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  64413. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  64414. if( rc==SQLITE_OK ){
  64415. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  64416. if( rc==SQLITE_OK ){
  64417. aData[18] = (u8)iVersion;
  64418. aData[19] = (u8)iVersion;
  64419. }
  64420. }
  64421. }
  64422. }
  64423. pBt->btsFlags &= ~BTS_NO_WAL;
  64424. return rc;
  64425. }
  64426. /*
  64427. ** Return true if the cursor has a hint specified. This routine is
  64428. ** only used from within assert() statements
  64429. */
  64430. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
  64431. return (pCsr->hints & mask)!=0;
  64432. }
  64433. /*
  64434. ** Return true if the given Btree is read-only.
  64435. */
  64436. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
  64437. return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
  64438. }
  64439. /*
  64440. ** Return the size of the header added to each page by this module.
  64441. */
  64442. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
  64443. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  64444. /*
  64445. ** Return true if the Btree passed as the only argument is sharable.
  64446. */
  64447. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  64448. return p->sharable;
  64449. }
  64450. /*
  64451. ** Return the number of connections to the BtShared object accessed by
  64452. ** the Btree handle passed as the only argument. For private caches
  64453. ** this is always 1. For shared caches it may be 1 or greater.
  64454. */
  64455. SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
  64456. testcase( p->sharable );
  64457. return p->pBt->nRef;
  64458. }
  64459. #endif
  64460. /************** End of btree.c ***********************************************/
  64461. /************** Begin file backup.c ******************************************/
  64462. /*
  64463. ** 2009 January 28
  64464. **
  64465. ** The author disclaims copyright to this source code. In place of
  64466. ** a legal notice, here is a blessing:
  64467. **
  64468. ** May you do good and not evil.
  64469. ** May you find forgiveness for yourself and forgive others.
  64470. ** May you share freely, never taking more than you give.
  64471. **
  64472. *************************************************************************
  64473. ** This file contains the implementation of the sqlite3_backup_XXX()
  64474. ** API functions and the related features.
  64475. */
  64476. /* #include "sqliteInt.h" */
  64477. /* #include "btreeInt.h" */
  64478. /*
  64479. ** Structure allocated for each backup operation.
  64480. */
  64481. struct sqlite3_backup {
  64482. sqlite3* pDestDb; /* Destination database handle */
  64483. Btree *pDest; /* Destination b-tree file */
  64484. u32 iDestSchema; /* Original schema cookie in destination */
  64485. int bDestLocked; /* True once a write-transaction is open on pDest */
  64486. Pgno iNext; /* Page number of the next source page to copy */
  64487. sqlite3* pSrcDb; /* Source database handle */
  64488. Btree *pSrc; /* Source b-tree file */
  64489. int rc; /* Backup process error code */
  64490. /* These two variables are set by every call to backup_step(). They are
  64491. ** read by calls to backup_remaining() and backup_pagecount().
  64492. */
  64493. Pgno nRemaining; /* Number of pages left to copy */
  64494. Pgno nPagecount; /* Total number of pages to copy */
  64495. int isAttached; /* True once backup has been registered with pager */
  64496. sqlite3_backup *pNext; /* Next backup associated with source pager */
  64497. };
  64498. /*
  64499. ** THREAD SAFETY NOTES:
  64500. **
  64501. ** Once it has been created using backup_init(), a single sqlite3_backup
  64502. ** structure may be accessed via two groups of thread-safe entry points:
  64503. **
  64504. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  64505. ** backup_finish(). Both these functions obtain the source database
  64506. ** handle mutex and the mutex associated with the source BtShared
  64507. ** structure, in that order.
  64508. **
  64509. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  64510. ** invoked by the pager layer to report various state changes in
  64511. ** the page cache associated with the source database. The mutex
  64512. ** associated with the source database BtShared structure will always
  64513. ** be held when either of these functions are invoked.
  64514. **
  64515. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  64516. ** backup_pagecount() are not thread-safe functions. If they are called
  64517. ** while some other thread is calling backup_step() or backup_finish(),
  64518. ** the values returned may be invalid. There is no way for a call to
  64519. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  64520. ** or backup_pagecount().
  64521. **
  64522. ** Depending on the SQLite configuration, the database handles and/or
  64523. ** the Btree objects may have their own mutexes that require locking.
  64524. ** Non-sharable Btrees (in-memory databases for example), do not have
  64525. ** associated mutexes.
  64526. */
  64527. /*
  64528. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  64529. ** in connection handle pDb. If such a database cannot be found, return
  64530. ** a NULL pointer and write an error message to pErrorDb.
  64531. **
  64532. ** If the "temp" database is requested, it may need to be opened by this
  64533. ** function. If an error occurs while doing so, return 0 and write an
  64534. ** error message to pErrorDb.
  64535. */
  64536. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  64537. int i = sqlite3FindDbName(pDb, zDb);
  64538. if( i==1 ){
  64539. Parse sParse;
  64540. int rc = 0;
  64541. memset(&sParse, 0, sizeof(sParse));
  64542. sParse.db = pDb;
  64543. if( sqlite3OpenTempDatabase(&sParse) ){
  64544. sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
  64545. rc = SQLITE_ERROR;
  64546. }
  64547. sqlite3DbFree(pErrorDb, sParse.zErrMsg);
  64548. sqlite3ParserReset(&sParse);
  64549. if( rc ){
  64550. return 0;
  64551. }
  64552. }
  64553. if( i<0 ){
  64554. sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  64555. return 0;
  64556. }
  64557. return pDb->aDb[i].pBt;
  64558. }
  64559. /*
  64560. ** Attempt to set the page size of the destination to match the page size
  64561. ** of the source.
  64562. */
  64563. static int setDestPgsz(sqlite3_backup *p){
  64564. int rc;
  64565. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  64566. return rc;
  64567. }
  64568. /*
  64569. ** Check that there is no open read-transaction on the b-tree passed as the
  64570. ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
  64571. ** is an open read-transaction, return SQLITE_ERROR and leave an error
  64572. ** message in database handle db.
  64573. */
  64574. static int checkReadTransaction(sqlite3 *db, Btree *p){
  64575. if( sqlite3BtreeIsInReadTrans(p) ){
  64576. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
  64577. return SQLITE_ERROR;
  64578. }
  64579. return SQLITE_OK;
  64580. }
  64581. /*
  64582. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  64583. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  64584. ** a pointer to the new sqlite3_backup object.
  64585. **
  64586. ** If an error occurs, NULL is returned and an error code and error message
  64587. ** stored in database handle pDestDb.
  64588. */
  64589. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  64590. sqlite3* pDestDb, /* Database to write to */
  64591. const char *zDestDb, /* Name of database within pDestDb */
  64592. sqlite3* pSrcDb, /* Database connection to read from */
  64593. const char *zSrcDb /* Name of database within pSrcDb */
  64594. ){
  64595. sqlite3_backup *p; /* Value to return */
  64596. #ifdef SQLITE_ENABLE_API_ARMOR
  64597. if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
  64598. (void)SQLITE_MISUSE_BKPT;
  64599. return 0;
  64600. }
  64601. #endif
  64602. /* Lock the source database handle. The destination database
  64603. ** handle is not locked in this routine, but it is locked in
  64604. ** sqlite3_backup_step(). The user is required to ensure that no
  64605. ** other thread accesses the destination handle for the duration
  64606. ** of the backup operation. Any attempt to use the destination
  64607. ** database connection while a backup is in progress may cause
  64608. ** a malfunction or a deadlock.
  64609. */
  64610. sqlite3_mutex_enter(pSrcDb->mutex);
  64611. sqlite3_mutex_enter(pDestDb->mutex);
  64612. if( pSrcDb==pDestDb ){
  64613. sqlite3ErrorWithMsg(
  64614. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  64615. );
  64616. p = 0;
  64617. }else {
  64618. /* Allocate space for a new sqlite3_backup object...
  64619. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  64620. ** call to sqlite3_backup_init() and is destroyed by a call to
  64621. ** sqlite3_backup_finish(). */
  64622. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  64623. if( !p ){
  64624. sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
  64625. }
  64626. }
  64627. /* If the allocation succeeded, populate the new object. */
  64628. if( p ){
  64629. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  64630. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  64631. p->pDestDb = pDestDb;
  64632. p->pSrcDb = pSrcDb;
  64633. p->iNext = 1;
  64634. p->isAttached = 0;
  64635. if( 0==p->pSrc || 0==p->pDest
  64636. || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
  64637. ){
  64638. /* One (or both) of the named databases did not exist or an OOM
  64639. ** error was hit. Or there is a transaction open on the destination
  64640. ** database. The error has already been written into the pDestDb
  64641. ** handle. All that is left to do here is free the sqlite3_backup
  64642. ** structure. */
  64643. sqlite3_free(p);
  64644. p = 0;
  64645. }
  64646. }
  64647. if( p ){
  64648. p->pSrc->nBackup++;
  64649. }
  64650. sqlite3_mutex_leave(pDestDb->mutex);
  64651. sqlite3_mutex_leave(pSrcDb->mutex);
  64652. return p;
  64653. }
  64654. /*
  64655. ** Argument rc is an SQLite error code. Return true if this error is
  64656. ** considered fatal if encountered during a backup operation. All errors
  64657. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  64658. */
  64659. static int isFatalError(int rc){
  64660. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  64661. }
  64662. /*
  64663. ** Parameter zSrcData points to a buffer containing the data for
  64664. ** page iSrcPg from the source database. Copy this data into the
  64665. ** destination database.
  64666. */
  64667. static int backupOnePage(
  64668. sqlite3_backup *p, /* Backup handle */
  64669. Pgno iSrcPg, /* Source database page to backup */
  64670. const u8 *zSrcData, /* Source database page data */
  64671. int bUpdate /* True for an update, false otherwise */
  64672. ){
  64673. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  64674. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  64675. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  64676. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  64677. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  64678. #ifdef SQLITE_HAS_CODEC
  64679. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  64680. ** guaranteed that the shared-mutex is held by this thread, handle
  64681. ** p->pSrc may not actually be the owner. */
  64682. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  64683. int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
  64684. #endif
  64685. int rc = SQLITE_OK;
  64686. i64 iOff;
  64687. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  64688. assert( p->bDestLocked );
  64689. assert( !isFatalError(p->rc) );
  64690. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  64691. assert( zSrcData );
  64692. /* Catch the case where the destination is an in-memory database and the
  64693. ** page sizes of the source and destination differ.
  64694. */
  64695. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  64696. rc = SQLITE_READONLY;
  64697. }
  64698. #ifdef SQLITE_HAS_CODEC
  64699. /* Backup is not possible if the page size of the destination is changing
  64700. ** and a codec is in use.
  64701. */
  64702. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  64703. rc = SQLITE_READONLY;
  64704. }
  64705. /* Backup is not possible if the number of bytes of reserve space differ
  64706. ** between source and destination. If there is a difference, try to
  64707. ** fix the destination to agree with the source. If that is not possible,
  64708. ** then the backup cannot proceed.
  64709. */
  64710. if( nSrcReserve!=nDestReserve ){
  64711. u32 newPgsz = nSrcPgsz;
  64712. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  64713. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  64714. }
  64715. #endif
  64716. /* This loop runs once for each destination page spanned by the source
  64717. ** page. For each iteration, variable iOff is set to the byte offset
  64718. ** of the destination page.
  64719. */
  64720. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  64721. DbPage *pDestPg = 0;
  64722. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  64723. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  64724. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
  64725. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  64726. ){
  64727. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  64728. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  64729. u8 *zOut = &zDestData[iOff%nDestPgsz];
  64730. /* Copy the data from the source page into the destination page.
  64731. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  64732. ** and the pager code use this trick (clearing the first byte
  64733. ** of the page 'extra' space to invalidate the Btree layers
  64734. ** cached parse of the page). MemPage.isInit is marked
  64735. ** "MUST BE FIRST" for this purpose.
  64736. */
  64737. memcpy(zOut, zIn, nCopy);
  64738. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  64739. if( iOff==0 && bUpdate==0 ){
  64740. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  64741. }
  64742. }
  64743. sqlite3PagerUnref(pDestPg);
  64744. }
  64745. return rc;
  64746. }
  64747. /*
  64748. ** If pFile is currently larger than iSize bytes, then truncate it to
  64749. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  64750. ** this function is a no-op.
  64751. **
  64752. ** Return SQLITE_OK if everything is successful, or an SQLite error
  64753. ** code if an error occurs.
  64754. */
  64755. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  64756. i64 iCurrent;
  64757. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  64758. if( rc==SQLITE_OK && iCurrent>iSize ){
  64759. rc = sqlite3OsTruncate(pFile, iSize);
  64760. }
  64761. return rc;
  64762. }
  64763. /*
  64764. ** Register this backup object with the associated source pager for
  64765. ** callbacks when pages are changed or the cache invalidated.
  64766. */
  64767. static void attachBackupObject(sqlite3_backup *p){
  64768. sqlite3_backup **pp;
  64769. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  64770. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  64771. p->pNext = *pp;
  64772. *pp = p;
  64773. p->isAttached = 1;
  64774. }
  64775. /*
  64776. ** Copy nPage pages from the source b-tree to the destination.
  64777. */
  64778. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  64779. int rc;
  64780. int destMode; /* Destination journal mode */
  64781. int pgszSrc = 0; /* Source page size */
  64782. int pgszDest = 0; /* Destination page size */
  64783. #ifdef SQLITE_ENABLE_API_ARMOR
  64784. if( p==0 ) return SQLITE_MISUSE_BKPT;
  64785. #endif
  64786. sqlite3_mutex_enter(p->pSrcDb->mutex);
  64787. sqlite3BtreeEnter(p->pSrc);
  64788. if( p->pDestDb ){
  64789. sqlite3_mutex_enter(p->pDestDb->mutex);
  64790. }
  64791. rc = p->rc;
  64792. if( !isFatalError(rc) ){
  64793. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  64794. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  64795. int ii; /* Iterator variable */
  64796. int nSrcPage = -1; /* Size of source db in pages */
  64797. int bCloseTrans = 0; /* True if src db requires unlocking */
  64798. /* If the source pager is currently in a write-transaction, return
  64799. ** SQLITE_BUSY immediately.
  64800. */
  64801. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  64802. rc = SQLITE_BUSY;
  64803. }else{
  64804. rc = SQLITE_OK;
  64805. }
  64806. /* If there is no open read-transaction on the source database, open
  64807. ** one now. If a transaction is opened here, then it will be closed
  64808. ** before this function exits.
  64809. */
  64810. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  64811. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  64812. bCloseTrans = 1;
  64813. }
  64814. /* If the destination database has not yet been locked (i.e. if this
  64815. ** is the first call to backup_step() for the current backup operation),
  64816. ** try to set its page size to the same as the source database. This
  64817. ** is especially important on ZipVFS systems, as in that case it is
  64818. ** not possible to create a database file that uses one page size by
  64819. ** writing to it with another. */
  64820. if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
  64821. rc = SQLITE_NOMEM;
  64822. }
  64823. /* Lock the destination database, if it is not locked already. */
  64824. if( SQLITE_OK==rc && p->bDestLocked==0
  64825. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  64826. ){
  64827. p->bDestLocked = 1;
  64828. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  64829. }
  64830. /* Do not allow backup if the destination database is in WAL mode
  64831. ** and the page sizes are different between source and destination */
  64832. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  64833. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  64834. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  64835. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  64836. rc = SQLITE_READONLY;
  64837. }
  64838. /* Now that there is a read-lock on the source database, query the
  64839. ** source pager for the number of pages in the database.
  64840. */
  64841. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  64842. assert( nSrcPage>=0 );
  64843. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  64844. const Pgno iSrcPg = p->iNext; /* Source page number */
  64845. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  64846. DbPage *pSrcPg; /* Source page object */
  64847. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
  64848. if( rc==SQLITE_OK ){
  64849. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  64850. sqlite3PagerUnref(pSrcPg);
  64851. }
  64852. }
  64853. p->iNext++;
  64854. }
  64855. if( rc==SQLITE_OK ){
  64856. p->nPagecount = nSrcPage;
  64857. p->nRemaining = nSrcPage+1-p->iNext;
  64858. if( p->iNext>(Pgno)nSrcPage ){
  64859. rc = SQLITE_DONE;
  64860. }else if( !p->isAttached ){
  64861. attachBackupObject(p);
  64862. }
  64863. }
  64864. /* Update the schema version field in the destination database. This
  64865. ** is to make sure that the schema-version really does change in
  64866. ** the case where the source and destination databases have the
  64867. ** same schema version.
  64868. */
  64869. if( rc==SQLITE_DONE ){
  64870. if( nSrcPage==0 ){
  64871. rc = sqlite3BtreeNewDb(p->pDest);
  64872. nSrcPage = 1;
  64873. }
  64874. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  64875. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  64876. }
  64877. if( rc==SQLITE_OK ){
  64878. if( p->pDestDb ){
  64879. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  64880. }
  64881. if( destMode==PAGER_JOURNALMODE_WAL ){
  64882. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  64883. }
  64884. }
  64885. if( rc==SQLITE_OK ){
  64886. int nDestTruncate;
  64887. /* Set nDestTruncate to the final number of pages in the destination
  64888. ** database. The complication here is that the destination page
  64889. ** size may be different to the source page size.
  64890. **
  64891. ** If the source page size is smaller than the destination page size,
  64892. ** round up. In this case the call to sqlite3OsTruncate() below will
  64893. ** fix the size of the file. However it is important to call
  64894. ** sqlite3PagerTruncateImage() here so that any pages in the
  64895. ** destination file that lie beyond the nDestTruncate page mark are
  64896. ** journalled by PagerCommitPhaseOne() before they are destroyed
  64897. ** by the file truncation.
  64898. */
  64899. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  64900. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  64901. if( pgszSrc<pgszDest ){
  64902. int ratio = pgszDest/pgszSrc;
  64903. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  64904. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  64905. nDestTruncate--;
  64906. }
  64907. }else{
  64908. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  64909. }
  64910. assert( nDestTruncate>0 );
  64911. if( pgszSrc<pgszDest ){
  64912. /* If the source page-size is smaller than the destination page-size,
  64913. ** two extra things may need to happen:
  64914. **
  64915. ** * The destination may need to be truncated, and
  64916. **
  64917. ** * Data stored on the pages immediately following the
  64918. ** pending-byte page in the source database may need to be
  64919. ** copied into the destination database.
  64920. */
  64921. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  64922. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  64923. Pgno iPg;
  64924. int nDstPage;
  64925. i64 iOff;
  64926. i64 iEnd;
  64927. assert( pFile );
  64928. assert( nDestTruncate==0
  64929. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  64930. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  64931. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  64932. ));
  64933. /* This block ensures that all data required to recreate the original
  64934. ** database has been stored in the journal for pDestPager and the
  64935. ** journal synced to disk. So at this point we may safely modify
  64936. ** the database file in any way, knowing that if a power failure
  64937. ** occurs, the original database will be reconstructed from the
  64938. ** journal file. */
  64939. sqlite3PagerPagecount(pDestPager, &nDstPage);
  64940. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  64941. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  64942. DbPage *pPg;
  64943. rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
  64944. if( rc==SQLITE_OK ){
  64945. rc = sqlite3PagerWrite(pPg);
  64946. sqlite3PagerUnref(pPg);
  64947. }
  64948. }
  64949. }
  64950. if( rc==SQLITE_OK ){
  64951. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  64952. }
  64953. /* Write the extra pages and truncate the database file as required */
  64954. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  64955. for(
  64956. iOff=PENDING_BYTE+pgszSrc;
  64957. rc==SQLITE_OK && iOff<iEnd;
  64958. iOff+=pgszSrc
  64959. ){
  64960. PgHdr *pSrcPg = 0;
  64961. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  64962. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
  64963. if( rc==SQLITE_OK ){
  64964. u8 *zData = sqlite3PagerGetData(pSrcPg);
  64965. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  64966. }
  64967. sqlite3PagerUnref(pSrcPg);
  64968. }
  64969. if( rc==SQLITE_OK ){
  64970. rc = backupTruncateFile(pFile, iSize);
  64971. }
  64972. /* Sync the database file to disk. */
  64973. if( rc==SQLITE_OK ){
  64974. rc = sqlite3PagerSync(pDestPager, 0);
  64975. }
  64976. }else{
  64977. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  64978. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  64979. }
  64980. /* Finish committing the transaction to the destination database. */
  64981. if( SQLITE_OK==rc
  64982. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  64983. ){
  64984. rc = SQLITE_DONE;
  64985. }
  64986. }
  64987. }
  64988. /* If bCloseTrans is true, then this function opened a read transaction
  64989. ** on the source database. Close the read transaction here. There is
  64990. ** no need to check the return values of the btree methods here, as
  64991. ** "committing" a read-only transaction cannot fail.
  64992. */
  64993. if( bCloseTrans ){
  64994. TESTONLY( int rc2 );
  64995. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  64996. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  64997. assert( rc2==SQLITE_OK );
  64998. }
  64999. if( rc==SQLITE_IOERR_NOMEM ){
  65000. rc = SQLITE_NOMEM_BKPT;
  65001. }
  65002. p->rc = rc;
  65003. }
  65004. if( p->pDestDb ){
  65005. sqlite3_mutex_leave(p->pDestDb->mutex);
  65006. }
  65007. sqlite3BtreeLeave(p->pSrc);
  65008. sqlite3_mutex_leave(p->pSrcDb->mutex);
  65009. return rc;
  65010. }
  65011. /*
  65012. ** Release all resources associated with an sqlite3_backup* handle.
  65013. */
  65014. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  65015. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  65016. sqlite3 *pSrcDb; /* Source database connection */
  65017. int rc; /* Value to return */
  65018. /* Enter the mutexes */
  65019. if( p==0 ) return SQLITE_OK;
  65020. pSrcDb = p->pSrcDb;
  65021. sqlite3_mutex_enter(pSrcDb->mutex);
  65022. sqlite3BtreeEnter(p->pSrc);
  65023. if( p->pDestDb ){
  65024. sqlite3_mutex_enter(p->pDestDb->mutex);
  65025. }
  65026. /* Detach this backup from the source pager. */
  65027. if( p->pDestDb ){
  65028. p->pSrc->nBackup--;
  65029. }
  65030. if( p->isAttached ){
  65031. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  65032. while( *pp!=p ){
  65033. pp = &(*pp)->pNext;
  65034. }
  65035. *pp = p->pNext;
  65036. }
  65037. /* If a transaction is still open on the Btree, roll it back. */
  65038. sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
  65039. /* Set the error code of the destination database handle. */
  65040. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  65041. if( p->pDestDb ){
  65042. sqlite3Error(p->pDestDb, rc);
  65043. /* Exit the mutexes and free the backup context structure. */
  65044. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  65045. }
  65046. sqlite3BtreeLeave(p->pSrc);
  65047. if( p->pDestDb ){
  65048. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  65049. ** call to sqlite3_backup_init() and is destroyed by a call to
  65050. ** sqlite3_backup_finish(). */
  65051. sqlite3_free(p);
  65052. }
  65053. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  65054. return rc;
  65055. }
  65056. /*
  65057. ** Return the number of pages still to be backed up as of the most recent
  65058. ** call to sqlite3_backup_step().
  65059. */
  65060. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  65061. #ifdef SQLITE_ENABLE_API_ARMOR
  65062. if( p==0 ){
  65063. (void)SQLITE_MISUSE_BKPT;
  65064. return 0;
  65065. }
  65066. #endif
  65067. return p->nRemaining;
  65068. }
  65069. /*
  65070. ** Return the total number of pages in the source database as of the most
  65071. ** recent call to sqlite3_backup_step().
  65072. */
  65073. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  65074. #ifdef SQLITE_ENABLE_API_ARMOR
  65075. if( p==0 ){
  65076. (void)SQLITE_MISUSE_BKPT;
  65077. return 0;
  65078. }
  65079. #endif
  65080. return p->nPagecount;
  65081. }
  65082. /*
  65083. ** This function is called after the contents of page iPage of the
  65084. ** source database have been modified. If page iPage has already been
  65085. ** copied into the destination database, then the data written to the
  65086. ** destination is now invalidated. The destination copy of iPage needs
  65087. ** to be updated with the new data before the backup operation is
  65088. ** complete.
  65089. **
  65090. ** It is assumed that the mutex associated with the BtShared object
  65091. ** corresponding to the source database is held when this function is
  65092. ** called.
  65093. */
  65094. static SQLITE_NOINLINE void backupUpdate(
  65095. sqlite3_backup *p,
  65096. Pgno iPage,
  65097. const u8 *aData
  65098. ){
  65099. assert( p!=0 );
  65100. do{
  65101. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  65102. if( !isFatalError(p->rc) && iPage<p->iNext ){
  65103. /* The backup process p has already copied page iPage. But now it
  65104. ** has been modified by a transaction on the source pager. Copy
  65105. ** the new data into the backup.
  65106. */
  65107. int rc;
  65108. assert( p->pDestDb );
  65109. sqlite3_mutex_enter(p->pDestDb->mutex);
  65110. rc = backupOnePage(p, iPage, aData, 1);
  65111. sqlite3_mutex_leave(p->pDestDb->mutex);
  65112. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  65113. if( rc!=SQLITE_OK ){
  65114. p->rc = rc;
  65115. }
  65116. }
  65117. }while( (p = p->pNext)!=0 );
  65118. }
  65119. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  65120. if( pBackup ) backupUpdate(pBackup, iPage, aData);
  65121. }
  65122. /*
  65123. ** Restart the backup process. This is called when the pager layer
  65124. ** detects that the database has been modified by an external database
  65125. ** connection. In this case there is no way of knowing which of the
  65126. ** pages that have been copied into the destination database are still
  65127. ** valid and which are not, so the entire process needs to be restarted.
  65128. **
  65129. ** It is assumed that the mutex associated with the BtShared object
  65130. ** corresponding to the source database is held when this function is
  65131. ** called.
  65132. */
  65133. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  65134. sqlite3_backup *p; /* Iterator variable */
  65135. for(p=pBackup; p; p=p->pNext){
  65136. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  65137. p->iNext = 1;
  65138. }
  65139. }
  65140. #ifndef SQLITE_OMIT_VACUUM
  65141. /*
  65142. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  65143. ** must be active for both files.
  65144. **
  65145. ** The size of file pTo may be reduced by this operation. If anything
  65146. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  65147. ** transaction is committed before returning.
  65148. */
  65149. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  65150. int rc;
  65151. sqlite3_file *pFd; /* File descriptor for database pTo */
  65152. sqlite3_backup b;
  65153. sqlite3BtreeEnter(pTo);
  65154. sqlite3BtreeEnter(pFrom);
  65155. assert( sqlite3BtreeIsInTrans(pTo) );
  65156. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  65157. if( pFd->pMethods ){
  65158. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  65159. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  65160. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  65161. if( rc ) goto copy_finished;
  65162. }
  65163. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  65164. ** to 0. This is used by the implementations of sqlite3_backup_step()
  65165. ** and sqlite3_backup_finish() to detect that they are being called
  65166. ** from this function, not directly by the user.
  65167. */
  65168. memset(&b, 0, sizeof(b));
  65169. b.pSrcDb = pFrom->db;
  65170. b.pSrc = pFrom;
  65171. b.pDest = pTo;
  65172. b.iNext = 1;
  65173. #ifdef SQLITE_HAS_CODEC
  65174. sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
  65175. #endif
  65176. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  65177. ** file. By passing this as the number of pages to copy to
  65178. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  65179. ** within a single call (unless an error occurs). The assert() statement
  65180. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  65181. ** or an error code. */
  65182. sqlite3_backup_step(&b, 0x7FFFFFFF);
  65183. assert( b.rc!=SQLITE_OK );
  65184. rc = sqlite3_backup_finish(&b);
  65185. if( rc==SQLITE_OK ){
  65186. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  65187. }else{
  65188. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  65189. }
  65190. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  65191. copy_finished:
  65192. sqlite3BtreeLeave(pFrom);
  65193. sqlite3BtreeLeave(pTo);
  65194. return rc;
  65195. }
  65196. #endif /* SQLITE_OMIT_VACUUM */
  65197. /************** End of backup.c **********************************************/
  65198. /************** Begin file vdbemem.c *****************************************/
  65199. /*
  65200. ** 2004 May 26
  65201. **
  65202. ** The author disclaims copyright to this source code. In place of
  65203. ** a legal notice, here is a blessing:
  65204. **
  65205. ** May you do good and not evil.
  65206. ** May you find forgiveness for yourself and forgive others.
  65207. ** May you share freely, never taking more than you give.
  65208. **
  65209. *************************************************************************
  65210. **
  65211. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  65212. ** stores a single value in the VDBE. Mem is an opaque structure visible
  65213. ** only within the VDBE. Interface routines refer to a Mem using the
  65214. ** name sqlite_value
  65215. */
  65216. /* #include "sqliteInt.h" */
  65217. /* #include "vdbeInt.h" */
  65218. #ifdef SQLITE_DEBUG
  65219. /*
  65220. ** Check invariants on a Mem object.
  65221. **
  65222. ** This routine is intended for use inside of assert() statements, like
  65223. ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
  65224. */
  65225. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
  65226. /* If MEM_Dyn is set then Mem.xDel!=0.
  65227. ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
  65228. */
  65229. assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
  65230. /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
  65231. ** ensure that if Mem.szMalloc>0 then it is safe to do
  65232. ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
  65233. ** That saves a few cycles in inner loops. */
  65234. assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
  65235. /* Cannot be both MEM_Int and MEM_Real at the same time */
  65236. assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
  65237. /* Cannot be both MEM_Null and some other type */
  65238. assert( (p->flags & MEM_Null)==0 ||
  65239. (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob))==0 );
  65240. /* The szMalloc field holds the correct memory allocation size */
  65241. assert( p->szMalloc==0
  65242. || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
  65243. /* If p holds a string or blob, the Mem.z must point to exactly
  65244. ** one of the following:
  65245. **
  65246. ** (1) Memory in Mem.zMalloc and managed by the Mem object
  65247. ** (2) Memory to be freed using Mem.xDel
  65248. ** (3) An ephemeral string or blob
  65249. ** (4) A static string or blob
  65250. */
  65251. if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
  65252. assert(
  65253. ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
  65254. ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  65255. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  65256. ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
  65257. );
  65258. }
  65259. return 1;
  65260. }
  65261. #endif
  65262. /*
  65263. ** If pMem is an object with a valid string representation, this routine
  65264. ** ensures the internal encoding for the string representation is
  65265. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  65266. **
  65267. ** If pMem is not a string object, or the encoding of the string
  65268. ** representation is already stored using the requested encoding, then this
  65269. ** routine is a no-op.
  65270. **
  65271. ** SQLITE_OK is returned if the conversion is successful (or not required).
  65272. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  65273. ** between formats.
  65274. */
  65275. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  65276. #ifndef SQLITE_OMIT_UTF16
  65277. int rc;
  65278. #endif
  65279. assert( (pMem->flags&MEM_RowSet)==0 );
  65280. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  65281. || desiredEnc==SQLITE_UTF16BE );
  65282. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  65283. return SQLITE_OK;
  65284. }
  65285. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65286. #ifdef SQLITE_OMIT_UTF16
  65287. return SQLITE_ERROR;
  65288. #else
  65289. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  65290. ** then the encoding of the value may not have changed.
  65291. */
  65292. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  65293. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  65294. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  65295. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  65296. return rc;
  65297. #endif
  65298. }
  65299. /*
  65300. ** Make sure pMem->z points to a writable allocation of at least
  65301. ** min(n,32) bytes.
  65302. **
  65303. ** If the bPreserve argument is true, then copy of the content of
  65304. ** pMem->z into the new allocation. pMem must be either a string or
  65305. ** blob if bPreserve is true. If bPreserve is false, any prior content
  65306. ** in pMem->z is discarded.
  65307. */
  65308. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
  65309. assert( sqlite3VdbeCheckMemInvariants(pMem) );
  65310. assert( (pMem->flags&MEM_RowSet)==0 );
  65311. testcase( pMem->db==0 );
  65312. /* If the bPreserve flag is set to true, then the memory cell must already
  65313. ** contain a valid string or blob value. */
  65314. assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  65315. testcase( bPreserve && pMem->z==0 );
  65316. assert( pMem->szMalloc==0
  65317. || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
  65318. if( n<32 ) n = 32;
  65319. if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
  65320. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  65321. bPreserve = 0;
  65322. }else{
  65323. if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
  65324. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  65325. }
  65326. if( pMem->zMalloc==0 ){
  65327. sqlite3VdbeMemSetNull(pMem);
  65328. pMem->z = 0;
  65329. pMem->szMalloc = 0;
  65330. return SQLITE_NOMEM_BKPT;
  65331. }else{
  65332. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  65333. }
  65334. if( bPreserve && pMem->z && ALWAYS(pMem->z!=pMem->zMalloc) ){
  65335. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  65336. }
  65337. if( (pMem->flags&MEM_Dyn)!=0 ){
  65338. assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
  65339. pMem->xDel((void *)(pMem->z));
  65340. }
  65341. pMem->z = pMem->zMalloc;
  65342. pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
  65343. return SQLITE_OK;
  65344. }
  65345. /*
  65346. ** Change the pMem->zMalloc allocation to be at least szNew bytes.
  65347. ** If pMem->zMalloc already meets or exceeds the requested size, this
  65348. ** routine is a no-op.
  65349. **
  65350. ** Any prior string or blob content in the pMem object may be discarded.
  65351. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
  65352. ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
  65353. ** values are preserved.
  65354. **
  65355. ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
  65356. ** if unable to complete the resizing.
  65357. */
  65358. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
  65359. assert( szNew>0 );
  65360. assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
  65361. if( pMem->szMalloc<szNew ){
  65362. return sqlite3VdbeMemGrow(pMem, szNew, 0);
  65363. }
  65364. assert( (pMem->flags & MEM_Dyn)==0 );
  65365. pMem->z = pMem->zMalloc;
  65366. pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
  65367. return SQLITE_OK;
  65368. }
  65369. /*
  65370. ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
  65371. ** MEM.zMalloc, where it can be safely written.
  65372. **
  65373. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  65374. */
  65375. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  65376. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65377. assert( (pMem->flags&MEM_RowSet)==0 );
  65378. if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
  65379. if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
  65380. if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
  65381. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  65382. return SQLITE_NOMEM_BKPT;
  65383. }
  65384. pMem->z[pMem->n] = 0;
  65385. pMem->z[pMem->n+1] = 0;
  65386. pMem->flags |= MEM_Term;
  65387. }
  65388. }
  65389. pMem->flags &= ~MEM_Ephem;
  65390. #ifdef SQLITE_DEBUG
  65391. pMem->pScopyFrom = 0;
  65392. #endif
  65393. return SQLITE_OK;
  65394. }
  65395. /*
  65396. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  65397. ** blob stored in dynamically allocated space.
  65398. */
  65399. #ifndef SQLITE_OMIT_INCRBLOB
  65400. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  65401. int nByte;
  65402. assert( pMem->flags & MEM_Zero );
  65403. assert( pMem->flags&MEM_Blob );
  65404. assert( (pMem->flags&MEM_RowSet)==0 );
  65405. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65406. /* Set nByte to the number of bytes required to store the expanded blob. */
  65407. nByte = pMem->n + pMem->u.nZero;
  65408. if( nByte<=0 ){
  65409. nByte = 1;
  65410. }
  65411. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  65412. return SQLITE_NOMEM_BKPT;
  65413. }
  65414. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  65415. pMem->n += pMem->u.nZero;
  65416. pMem->flags &= ~(MEM_Zero|MEM_Term);
  65417. return SQLITE_OK;
  65418. }
  65419. #endif
  65420. /*
  65421. ** It is already known that pMem contains an unterminated string.
  65422. ** Add the zero terminator.
  65423. */
  65424. static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
  65425. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  65426. return SQLITE_NOMEM_BKPT;
  65427. }
  65428. pMem->z[pMem->n] = 0;
  65429. pMem->z[pMem->n+1] = 0;
  65430. pMem->flags |= MEM_Term;
  65431. return SQLITE_OK;
  65432. }
  65433. /*
  65434. ** Make sure the given Mem is \u0000 terminated.
  65435. */
  65436. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  65437. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65438. testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
  65439. testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
  65440. if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
  65441. return SQLITE_OK; /* Nothing to do */
  65442. }else{
  65443. return vdbeMemAddTerminator(pMem);
  65444. }
  65445. }
  65446. /*
  65447. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  65448. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  65449. ** is a no-op.
  65450. **
  65451. ** Existing representations MEM_Int and MEM_Real are invalidated if
  65452. ** bForce is true but are retained if bForce is false.
  65453. **
  65454. ** A MEM_Null value will never be passed to this function. This function is
  65455. ** used for converting values to text for returning to the user (i.e. via
  65456. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  65457. ** keys are strings. In the former case a NULL pointer is returned the
  65458. ** user and the latter is an internal programming error.
  65459. */
  65460. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
  65461. int fg = pMem->flags;
  65462. const int nByte = 32;
  65463. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65464. assert( !(fg&MEM_Zero) );
  65465. assert( !(fg&(MEM_Str|MEM_Blob)) );
  65466. assert( fg&(MEM_Int|MEM_Real) );
  65467. assert( (pMem->flags&MEM_RowSet)==0 );
  65468. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  65469. if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  65470. pMem->enc = 0;
  65471. return SQLITE_NOMEM_BKPT;
  65472. }
  65473. /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
  65474. ** string representation of the value. Then, if the required encoding
  65475. ** is UTF-16le or UTF-16be do a translation.
  65476. **
  65477. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  65478. */
  65479. if( fg & MEM_Int ){
  65480. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  65481. }else{
  65482. assert( fg & MEM_Real );
  65483. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
  65484. }
  65485. pMem->n = sqlite3Strlen30(pMem->z);
  65486. pMem->enc = SQLITE_UTF8;
  65487. pMem->flags |= MEM_Str|MEM_Term;
  65488. if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
  65489. sqlite3VdbeChangeEncoding(pMem, enc);
  65490. return SQLITE_OK;
  65491. }
  65492. /*
  65493. ** Memory cell pMem contains the context of an aggregate function.
  65494. ** This routine calls the finalize method for that function. The
  65495. ** result of the aggregate is stored back into pMem.
  65496. **
  65497. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  65498. ** otherwise.
  65499. */
  65500. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  65501. int rc = SQLITE_OK;
  65502. if( ALWAYS(pFunc && pFunc->xFinalize) ){
  65503. sqlite3_context ctx;
  65504. Mem t;
  65505. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  65506. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65507. memset(&ctx, 0, sizeof(ctx));
  65508. memset(&t, 0, sizeof(t));
  65509. t.flags = MEM_Null;
  65510. t.db = pMem->db;
  65511. ctx.pOut = &t;
  65512. ctx.pMem = pMem;
  65513. ctx.pFunc = pFunc;
  65514. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  65515. assert( (pMem->flags & MEM_Dyn)==0 );
  65516. if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
  65517. memcpy(pMem, &t, sizeof(t));
  65518. rc = ctx.isError;
  65519. }
  65520. return rc;
  65521. }
  65522. /*
  65523. ** If the memory cell contains a value that must be freed by
  65524. ** invoking the external callback in Mem.xDel, then this routine
  65525. ** will free that value. It also sets Mem.flags to MEM_Null.
  65526. **
  65527. ** This is a helper routine for sqlite3VdbeMemSetNull() and
  65528. ** for sqlite3VdbeMemRelease(). Use those other routines as the
  65529. ** entry point for releasing Mem resources.
  65530. */
  65531. static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
  65532. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  65533. assert( VdbeMemDynamic(p) );
  65534. if( p->flags&MEM_Agg ){
  65535. sqlite3VdbeMemFinalize(p, p->u.pDef);
  65536. assert( (p->flags & MEM_Agg)==0 );
  65537. testcase( p->flags & MEM_Dyn );
  65538. }
  65539. if( p->flags&MEM_Dyn ){
  65540. assert( (p->flags&MEM_RowSet)==0 );
  65541. assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
  65542. p->xDel((void *)p->z);
  65543. }else if( p->flags&MEM_RowSet ){
  65544. sqlite3RowSetClear(p->u.pRowSet);
  65545. }else if( p->flags&MEM_Frame ){
  65546. VdbeFrame *pFrame = p->u.pFrame;
  65547. pFrame->pParent = pFrame->v->pDelFrame;
  65548. pFrame->v->pDelFrame = pFrame;
  65549. }
  65550. p->flags = MEM_Null;
  65551. }
  65552. /*
  65553. ** Release memory held by the Mem p, both external memory cleared
  65554. ** by p->xDel and memory in p->zMalloc.
  65555. **
  65556. ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
  65557. ** the unusual case where there really is memory in p that needs
  65558. ** to be freed.
  65559. */
  65560. static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
  65561. if( VdbeMemDynamic(p) ){
  65562. vdbeMemClearExternAndSetNull(p);
  65563. }
  65564. if( p->szMalloc ){
  65565. sqlite3DbFreeNN(p->db, p->zMalloc);
  65566. p->szMalloc = 0;
  65567. }
  65568. p->z = 0;
  65569. }
  65570. /*
  65571. ** Release any memory resources held by the Mem. Both the memory that is
  65572. ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
  65573. **
  65574. ** Use this routine prior to clean up prior to abandoning a Mem, or to
  65575. ** reset a Mem back to its minimum memory utilization.
  65576. **
  65577. ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
  65578. ** prior to inserting new content into the Mem.
  65579. */
  65580. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  65581. assert( sqlite3VdbeCheckMemInvariants(p) );
  65582. if( VdbeMemDynamic(p) || p->szMalloc ){
  65583. vdbeMemClear(p);
  65584. }
  65585. }
  65586. /*
  65587. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  65588. ** If the double is out of range of a 64-bit signed integer then
  65589. ** return the closest available 64-bit signed integer.
  65590. */
  65591. static SQLITE_NOINLINE i64 doubleToInt64(double r){
  65592. #ifdef SQLITE_OMIT_FLOATING_POINT
  65593. /* When floating-point is omitted, double and int64 are the same thing */
  65594. return r;
  65595. #else
  65596. /*
  65597. ** Many compilers we encounter do not define constants for the
  65598. ** minimum and maximum 64-bit integers, or they define them
  65599. ** inconsistently. And many do not understand the "LL" notation.
  65600. ** So we define our own static constants here using nothing
  65601. ** larger than a 32-bit integer constant.
  65602. */
  65603. static const i64 maxInt = LARGEST_INT64;
  65604. static const i64 minInt = SMALLEST_INT64;
  65605. if( r<=(double)minInt ){
  65606. return minInt;
  65607. }else if( r>=(double)maxInt ){
  65608. return maxInt;
  65609. }else{
  65610. return (i64)r;
  65611. }
  65612. #endif
  65613. }
  65614. /*
  65615. ** Return some kind of integer value which is the best we can do
  65616. ** at representing the value that *pMem describes as an integer.
  65617. ** If pMem is an integer, then the value is exact. If pMem is
  65618. ** a floating-point then the value returned is the integer part.
  65619. ** If pMem is a string or blob, then we make an attempt to convert
  65620. ** it into an integer and return that. If pMem represents an
  65621. ** an SQL-NULL value, return 0.
  65622. **
  65623. ** If pMem represents a string value, its encoding might be changed.
  65624. */
  65625. static SQLITE_NOINLINE i64 memIntValue(Mem *pMem){
  65626. i64 value = 0;
  65627. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  65628. return value;
  65629. }
  65630. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  65631. int flags;
  65632. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65633. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  65634. flags = pMem->flags;
  65635. if( flags & MEM_Int ){
  65636. return pMem->u.i;
  65637. }else if( flags & MEM_Real ){
  65638. return doubleToInt64(pMem->u.r);
  65639. }else if( flags & (MEM_Str|MEM_Blob) ){
  65640. assert( pMem->z || pMem->n==0 );
  65641. return memIntValue(pMem);
  65642. }else{
  65643. return 0;
  65644. }
  65645. }
  65646. /*
  65647. ** Return the best representation of pMem that we can get into a
  65648. ** double. If pMem is already a double or an integer, return its
  65649. ** value. If it is a string or blob, try to convert it to a double.
  65650. ** If it is a NULL, return 0.0.
  65651. */
  65652. static SQLITE_NOINLINE double memRealValue(Mem *pMem){
  65653. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  65654. double val = (double)0;
  65655. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  65656. return val;
  65657. }
  65658. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  65659. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65660. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  65661. if( pMem->flags & MEM_Real ){
  65662. return pMem->u.r;
  65663. }else if( pMem->flags & MEM_Int ){
  65664. return (double)pMem->u.i;
  65665. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  65666. return memRealValue(pMem);
  65667. }else{
  65668. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  65669. return (double)0;
  65670. }
  65671. }
  65672. /*
  65673. ** The MEM structure is already a MEM_Real. Try to also make it a
  65674. ** MEM_Int if we can.
  65675. */
  65676. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  65677. i64 ix;
  65678. assert( pMem->flags & MEM_Real );
  65679. assert( (pMem->flags & MEM_RowSet)==0 );
  65680. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65681. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  65682. ix = doubleToInt64(pMem->u.r);
  65683. /* Only mark the value as an integer if
  65684. **
  65685. ** (1) the round-trip conversion real->int->real is a no-op, and
  65686. ** (2) The integer is neither the largest nor the smallest
  65687. ** possible integer (ticket #3922)
  65688. **
  65689. ** The second and third terms in the following conditional enforces
  65690. ** the second condition under the assumption that addition overflow causes
  65691. ** values to wrap around.
  65692. */
  65693. if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
  65694. pMem->u.i = ix;
  65695. MemSetTypeFlag(pMem, MEM_Int);
  65696. }
  65697. }
  65698. /*
  65699. ** Convert pMem to type integer. Invalidate any prior representations.
  65700. */
  65701. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  65702. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65703. assert( (pMem->flags & MEM_RowSet)==0 );
  65704. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  65705. pMem->u.i = sqlite3VdbeIntValue(pMem);
  65706. MemSetTypeFlag(pMem, MEM_Int);
  65707. return SQLITE_OK;
  65708. }
  65709. /*
  65710. ** Convert pMem so that it is of type MEM_Real.
  65711. ** Invalidate any prior representations.
  65712. */
  65713. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  65714. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65715. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  65716. pMem->u.r = sqlite3VdbeRealValue(pMem);
  65717. MemSetTypeFlag(pMem, MEM_Real);
  65718. return SQLITE_OK;
  65719. }
  65720. /*
  65721. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  65722. ** Invalidate any prior representations.
  65723. **
  65724. ** Every effort is made to force the conversion, even if the input
  65725. ** is a string that does not look completely like a number. Convert
  65726. ** as much of the string as we can and ignore the rest.
  65727. */
  65728. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  65729. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  65730. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  65731. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  65732. if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
  65733. MemSetTypeFlag(pMem, MEM_Int);
  65734. }else{
  65735. pMem->u.r = sqlite3VdbeRealValue(pMem);
  65736. MemSetTypeFlag(pMem, MEM_Real);
  65737. sqlite3VdbeIntegerAffinity(pMem);
  65738. }
  65739. }
  65740. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  65741. pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
  65742. return SQLITE_OK;
  65743. }
  65744. /*
  65745. ** Cast the datatype of the value in pMem according to the affinity
  65746. ** "aff". Casting is different from applying affinity in that a cast
  65747. ** is forced. In other words, the value is converted into the desired
  65748. ** affinity even if that results in loss of data. This routine is
  65749. ** used (for example) to implement the SQL "cast()" operator.
  65750. */
  65751. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
  65752. if( pMem->flags & MEM_Null ) return;
  65753. switch( aff ){
  65754. case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
  65755. if( (pMem->flags & MEM_Blob)==0 ){
  65756. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  65757. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  65758. if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
  65759. }else{
  65760. pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
  65761. }
  65762. break;
  65763. }
  65764. case SQLITE_AFF_NUMERIC: {
  65765. sqlite3VdbeMemNumerify(pMem);
  65766. break;
  65767. }
  65768. case SQLITE_AFF_INTEGER: {
  65769. sqlite3VdbeMemIntegerify(pMem);
  65770. break;
  65771. }
  65772. case SQLITE_AFF_REAL: {
  65773. sqlite3VdbeMemRealify(pMem);
  65774. break;
  65775. }
  65776. default: {
  65777. assert( aff==SQLITE_AFF_TEXT );
  65778. assert( MEM_Str==(MEM_Blob>>3) );
  65779. pMem->flags |= (pMem->flags&MEM_Blob)>>3;
  65780. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  65781. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  65782. pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  65783. break;
  65784. }
  65785. }
  65786. }
  65787. /*
  65788. ** Initialize bulk memory to be a consistent Mem object.
  65789. **
  65790. ** The minimum amount of initialization feasible is performed.
  65791. */
  65792. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
  65793. assert( (flags & ~MEM_TypeMask)==0 );
  65794. pMem->flags = flags;
  65795. pMem->db = db;
  65796. pMem->szMalloc = 0;
  65797. }
  65798. /*
  65799. ** Delete any previous value and set the value stored in *pMem to NULL.
  65800. **
  65801. ** This routine calls the Mem.xDel destructor to dispose of values that
  65802. ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
  65803. ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
  65804. ** routine to invoke the destructor and deallocates Mem.zMalloc.
  65805. **
  65806. ** Use this routine to reset the Mem prior to insert a new value.
  65807. **
  65808. ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
  65809. */
  65810. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  65811. if( VdbeMemDynamic(pMem) ){
  65812. vdbeMemClearExternAndSetNull(pMem);
  65813. }else{
  65814. pMem->flags = MEM_Null;
  65815. }
  65816. }
  65817. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
  65818. sqlite3VdbeMemSetNull((Mem*)p);
  65819. }
  65820. /*
  65821. ** Delete any previous value and set the value to be a BLOB of length
  65822. ** n containing all zeros.
  65823. */
  65824. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  65825. sqlite3VdbeMemRelease(pMem);
  65826. pMem->flags = MEM_Blob|MEM_Zero;
  65827. pMem->n = 0;
  65828. if( n<0 ) n = 0;
  65829. pMem->u.nZero = n;
  65830. pMem->enc = SQLITE_UTF8;
  65831. pMem->z = 0;
  65832. }
  65833. /*
  65834. ** The pMem is known to contain content that needs to be destroyed prior
  65835. ** to a value change. So invoke the destructor, then set the value to
  65836. ** a 64-bit integer.
  65837. */
  65838. static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
  65839. sqlite3VdbeMemSetNull(pMem);
  65840. pMem->u.i = val;
  65841. pMem->flags = MEM_Int;
  65842. }
  65843. /*
  65844. ** Delete any previous value and set the value stored in *pMem to val,
  65845. ** manifest type INTEGER.
  65846. */
  65847. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  65848. if( VdbeMemDynamic(pMem) ){
  65849. vdbeReleaseAndSetInt64(pMem, val);
  65850. }else{
  65851. pMem->u.i = val;
  65852. pMem->flags = MEM_Int;
  65853. }
  65854. }
  65855. #ifndef SQLITE_OMIT_FLOATING_POINT
  65856. /*
  65857. ** Delete any previous value and set the value stored in *pMem to val,
  65858. ** manifest type REAL.
  65859. */
  65860. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  65861. sqlite3VdbeMemSetNull(pMem);
  65862. if( !sqlite3IsNaN(val) ){
  65863. pMem->u.r = val;
  65864. pMem->flags = MEM_Real;
  65865. }
  65866. }
  65867. #endif
  65868. /*
  65869. ** Delete any previous value and set the value of pMem to be an
  65870. ** empty boolean index.
  65871. */
  65872. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  65873. sqlite3 *db = pMem->db;
  65874. assert( db!=0 );
  65875. assert( (pMem->flags & MEM_RowSet)==0 );
  65876. sqlite3VdbeMemRelease(pMem);
  65877. pMem->zMalloc = sqlite3DbMallocRawNN(db, 64);
  65878. if( db->mallocFailed ){
  65879. pMem->flags = MEM_Null;
  65880. pMem->szMalloc = 0;
  65881. }else{
  65882. assert( pMem->zMalloc );
  65883. pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
  65884. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
  65885. assert( pMem->u.pRowSet!=0 );
  65886. pMem->flags = MEM_RowSet;
  65887. }
  65888. }
  65889. /*
  65890. ** Return true if the Mem object contains a TEXT or BLOB that is
  65891. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  65892. */
  65893. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  65894. assert( p->db!=0 );
  65895. if( p->flags & (MEM_Str|MEM_Blob) ){
  65896. int n = p->n;
  65897. if( p->flags & MEM_Zero ){
  65898. n += p->u.nZero;
  65899. }
  65900. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  65901. }
  65902. return 0;
  65903. }
  65904. #ifdef SQLITE_DEBUG
  65905. /*
  65906. ** This routine prepares a memory cell for modification by breaking
  65907. ** its link to a shallow copy and by marking any current shallow
  65908. ** copies of this cell as invalid.
  65909. **
  65910. ** This is used for testing and debugging only - to make sure shallow
  65911. ** copies are not misused.
  65912. */
  65913. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  65914. int i;
  65915. Mem *pX;
  65916. for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
  65917. if( pX->pScopyFrom==pMem ){
  65918. pX->flags |= MEM_Undefined;
  65919. pX->pScopyFrom = 0;
  65920. }
  65921. }
  65922. pMem->pScopyFrom = 0;
  65923. }
  65924. #endif /* SQLITE_DEBUG */
  65925. /*
  65926. ** Make an shallow copy of pFrom into pTo. Prior contents of
  65927. ** pTo are freed. The pFrom->z field is not duplicated. If
  65928. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  65929. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  65930. */
  65931. static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
  65932. vdbeMemClearExternAndSetNull(pTo);
  65933. assert( !VdbeMemDynamic(pTo) );
  65934. sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
  65935. }
  65936. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  65937. assert( (pFrom->flags & MEM_RowSet)==0 );
  65938. assert( pTo->db==pFrom->db );
  65939. if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
  65940. memcpy(pTo, pFrom, MEMCELLSIZE);
  65941. if( (pFrom->flags&MEM_Static)==0 ){
  65942. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  65943. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  65944. pTo->flags |= srcType;
  65945. }
  65946. }
  65947. /*
  65948. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  65949. ** freed before the copy is made.
  65950. */
  65951. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  65952. int rc = SQLITE_OK;
  65953. assert( (pFrom->flags & MEM_RowSet)==0 );
  65954. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  65955. memcpy(pTo, pFrom, MEMCELLSIZE);
  65956. pTo->flags &= ~MEM_Dyn;
  65957. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  65958. if( 0==(pFrom->flags&MEM_Static) ){
  65959. pTo->flags |= MEM_Ephem;
  65960. rc = sqlite3VdbeMemMakeWriteable(pTo);
  65961. }
  65962. }
  65963. return rc;
  65964. }
  65965. /*
  65966. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  65967. ** freed. If pFrom contains ephemeral data, a copy is made.
  65968. **
  65969. ** pFrom contains an SQL NULL when this routine returns.
  65970. */
  65971. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  65972. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  65973. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  65974. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  65975. sqlite3VdbeMemRelease(pTo);
  65976. memcpy(pTo, pFrom, sizeof(Mem));
  65977. pFrom->flags = MEM_Null;
  65978. pFrom->szMalloc = 0;
  65979. }
  65980. /*
  65981. ** Change the value of a Mem to be a string or a BLOB.
  65982. **
  65983. ** The memory management strategy depends on the value of the xDel
  65984. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  65985. ** string is copied into a (possibly existing) buffer managed by the
  65986. ** Mem structure. Otherwise, any existing buffer is freed and the
  65987. ** pointer copied.
  65988. **
  65989. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  65990. ** size limit) then no memory allocation occurs. If the string can be
  65991. ** stored without allocating memory, then it is. If a memory allocation
  65992. ** is required to store the string, then value of pMem is unchanged. In
  65993. ** either case, SQLITE_TOOBIG is returned.
  65994. */
  65995. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  65996. Mem *pMem, /* Memory cell to set to string value */
  65997. const char *z, /* String pointer */
  65998. int n, /* Bytes in string, or negative */
  65999. u8 enc, /* Encoding of z. 0 for BLOBs */
  66000. void (*xDel)(void*) /* Destructor function */
  66001. ){
  66002. int nByte = n; /* New value for pMem->n */
  66003. int iLimit; /* Maximum allowed string or blob size */
  66004. u16 flags = 0; /* New value for pMem->flags */
  66005. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  66006. assert( (pMem->flags & MEM_RowSet)==0 );
  66007. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  66008. if( !z ){
  66009. sqlite3VdbeMemSetNull(pMem);
  66010. return SQLITE_OK;
  66011. }
  66012. if( pMem->db ){
  66013. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  66014. }else{
  66015. iLimit = SQLITE_MAX_LENGTH;
  66016. }
  66017. flags = (enc==0?MEM_Blob:MEM_Str);
  66018. if( nByte<0 ){
  66019. assert( enc!=0 );
  66020. if( enc==SQLITE_UTF8 ){
  66021. nByte = sqlite3Strlen30(z);
  66022. if( nByte>iLimit ) nByte = iLimit+1;
  66023. }else{
  66024. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  66025. }
  66026. flags |= MEM_Term;
  66027. }
  66028. /* The following block sets the new values of Mem.z and Mem.xDel. It
  66029. ** also sets a flag in local variable "flags" to indicate the memory
  66030. ** management (one of MEM_Dyn or MEM_Static).
  66031. */
  66032. if( xDel==SQLITE_TRANSIENT ){
  66033. int nAlloc = nByte;
  66034. if( flags&MEM_Term ){
  66035. nAlloc += (enc==SQLITE_UTF8?1:2);
  66036. }
  66037. if( nByte>iLimit ){
  66038. return SQLITE_TOOBIG;
  66039. }
  66040. testcase( nAlloc==0 );
  66041. testcase( nAlloc==31 );
  66042. testcase( nAlloc==32 );
  66043. if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
  66044. return SQLITE_NOMEM_BKPT;
  66045. }
  66046. memcpy(pMem->z, z, nAlloc);
  66047. }else if( xDel==SQLITE_DYNAMIC ){
  66048. sqlite3VdbeMemRelease(pMem);
  66049. pMem->zMalloc = pMem->z = (char *)z;
  66050. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  66051. }else{
  66052. sqlite3VdbeMemRelease(pMem);
  66053. pMem->z = (char *)z;
  66054. pMem->xDel = xDel;
  66055. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  66056. }
  66057. pMem->n = nByte;
  66058. pMem->flags = flags;
  66059. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  66060. #ifndef SQLITE_OMIT_UTF16
  66061. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  66062. return SQLITE_NOMEM_BKPT;
  66063. }
  66064. #endif
  66065. if( nByte>iLimit ){
  66066. return SQLITE_TOOBIG;
  66067. }
  66068. return SQLITE_OK;
  66069. }
  66070. /*
  66071. ** Move data out of a btree key or data field and into a Mem structure.
  66072. ** The data is payload from the entry that pCur is currently pointing
  66073. ** to. offset and amt determine what portion of the data or key to retrieve.
  66074. ** The result is written into the pMem element.
  66075. **
  66076. ** The pMem object must have been initialized. This routine will use
  66077. ** pMem->zMalloc to hold the content from the btree, if possible. New
  66078. ** pMem->zMalloc space will be allocated if necessary. The calling routine
  66079. ** is responsible for making sure that the pMem object is eventually
  66080. ** destroyed.
  66081. **
  66082. ** If this routine fails for any reason (malloc returns NULL or unable
  66083. ** to read from the disk) then the pMem is left in an inconsistent state.
  66084. */
  66085. static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
  66086. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  66087. u32 offset, /* Offset from the start of data to return bytes from. */
  66088. u32 amt, /* Number of bytes to return. */
  66089. Mem *pMem /* OUT: Return data in this Mem structure. */
  66090. ){
  66091. int rc;
  66092. pMem->flags = MEM_Null;
  66093. if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
  66094. rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
  66095. if( rc==SQLITE_OK ){
  66096. pMem->z[amt] = 0;
  66097. pMem->z[amt+1] = 0;
  66098. pMem->flags = MEM_Blob|MEM_Term;
  66099. pMem->n = (int)amt;
  66100. }else{
  66101. sqlite3VdbeMemRelease(pMem);
  66102. }
  66103. }
  66104. return rc;
  66105. }
  66106. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  66107. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  66108. u32 offset, /* Offset from the start of data to return bytes from. */
  66109. u32 amt, /* Number of bytes to return. */
  66110. Mem *pMem /* OUT: Return data in this Mem structure. */
  66111. ){
  66112. char *zData; /* Data from the btree layer */
  66113. u32 available = 0; /* Number of bytes available on the local btree page */
  66114. int rc = SQLITE_OK; /* Return code */
  66115. assert( sqlite3BtreeCursorIsValid(pCur) );
  66116. assert( !VdbeMemDynamic(pMem) );
  66117. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  66118. ** that both the BtShared and database handle mutexes are held. */
  66119. assert( (pMem->flags & MEM_RowSet)==0 );
  66120. zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
  66121. assert( zData!=0 );
  66122. if( offset+amt<=available ){
  66123. pMem->z = &zData[offset];
  66124. pMem->flags = MEM_Blob|MEM_Ephem;
  66125. pMem->n = (int)amt;
  66126. }else{
  66127. rc = vdbeMemFromBtreeResize(pCur, offset, amt, pMem);
  66128. }
  66129. return rc;
  66130. }
  66131. /*
  66132. ** The pVal argument is known to be a value other than NULL.
  66133. ** Convert it into a string with encoding enc and return a pointer
  66134. ** to a zero-terminated version of that string.
  66135. */
  66136. static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
  66137. assert( pVal!=0 );
  66138. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  66139. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  66140. assert( (pVal->flags & MEM_RowSet)==0 );
  66141. assert( (pVal->flags & (MEM_Null))==0 );
  66142. if( pVal->flags & (MEM_Blob|MEM_Str) ){
  66143. if( ExpandBlob(pVal) ) return 0;
  66144. pVal->flags |= MEM_Str;
  66145. if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
  66146. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  66147. }
  66148. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  66149. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  66150. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  66151. return 0;
  66152. }
  66153. }
  66154. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  66155. }else{
  66156. sqlite3VdbeMemStringify(pVal, enc, 0);
  66157. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  66158. }
  66159. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  66160. || pVal->db->mallocFailed );
  66161. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  66162. return pVal->z;
  66163. }else{
  66164. return 0;
  66165. }
  66166. }
  66167. /* This function is only available internally, it is not part of the
  66168. ** external API. It works in a similar way to sqlite3_value_text(),
  66169. ** except the data returned is in the encoding specified by the second
  66170. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  66171. ** SQLITE_UTF8.
  66172. **
  66173. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  66174. ** If that is the case, then the result must be aligned on an even byte
  66175. ** boundary.
  66176. */
  66177. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  66178. if( !pVal ) return 0;
  66179. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  66180. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  66181. assert( (pVal->flags & MEM_RowSet)==0 );
  66182. if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
  66183. return pVal->z;
  66184. }
  66185. if( pVal->flags&MEM_Null ){
  66186. return 0;
  66187. }
  66188. return valueToText(pVal, enc);
  66189. }
  66190. /*
  66191. ** Create a new sqlite3_value object.
  66192. */
  66193. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  66194. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  66195. if( p ){
  66196. p->flags = MEM_Null;
  66197. p->db = db;
  66198. }
  66199. return p;
  66200. }
  66201. /*
  66202. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  66203. ** valueNew(). See comments above valueNew() for details.
  66204. */
  66205. struct ValueNewStat4Ctx {
  66206. Parse *pParse;
  66207. Index *pIdx;
  66208. UnpackedRecord **ppRec;
  66209. int iVal;
  66210. };
  66211. /*
  66212. ** Allocate and return a pointer to a new sqlite3_value object. If
  66213. ** the second argument to this function is NULL, the object is allocated
  66214. ** by calling sqlite3ValueNew().
  66215. **
  66216. ** Otherwise, if the second argument is non-zero, then this function is
  66217. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  66218. ** already been allocated, allocate the UnpackedRecord structure that
  66219. ** that function will return to its caller here. Then return a pointer to
  66220. ** an sqlite3_value within the UnpackedRecord.a[] array.
  66221. */
  66222. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  66223. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66224. if( p ){
  66225. UnpackedRecord *pRec = p->ppRec[0];
  66226. if( pRec==0 ){
  66227. Index *pIdx = p->pIdx; /* Index being probed */
  66228. int nByte; /* Bytes of space to allocate */
  66229. int i; /* Counter variable */
  66230. int nCol = pIdx->nColumn; /* Number of index columns including rowid */
  66231. nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
  66232. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  66233. if( pRec ){
  66234. pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
  66235. if( pRec->pKeyInfo ){
  66236. assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
  66237. assert( pRec->pKeyInfo->enc==ENC(db) );
  66238. pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
  66239. for(i=0; i<nCol; i++){
  66240. pRec->aMem[i].flags = MEM_Null;
  66241. pRec->aMem[i].db = db;
  66242. }
  66243. }else{
  66244. sqlite3DbFreeNN(db, pRec);
  66245. pRec = 0;
  66246. }
  66247. }
  66248. if( pRec==0 ) return 0;
  66249. p->ppRec[0] = pRec;
  66250. }
  66251. pRec->nField = p->iVal+1;
  66252. return &pRec->aMem[p->iVal];
  66253. }
  66254. #else
  66255. UNUSED_PARAMETER(p);
  66256. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  66257. return sqlite3ValueNew(db);
  66258. }
  66259. /*
  66260. ** The expression object indicated by the second argument is guaranteed
  66261. ** to be a scalar SQL function. If
  66262. **
  66263. ** * all function arguments are SQL literals,
  66264. ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
  66265. ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
  66266. **
  66267. ** then this routine attempts to invoke the SQL function. Assuming no
  66268. ** error occurs, output parameter (*ppVal) is set to point to a value
  66269. ** object containing the result before returning SQLITE_OK.
  66270. **
  66271. ** Affinity aff is applied to the result of the function before returning.
  66272. ** If the result is a text value, the sqlite3_value object uses encoding
  66273. ** enc.
  66274. **
  66275. ** If the conditions above are not met, this function returns SQLITE_OK
  66276. ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
  66277. ** NULL and an SQLite error code returned.
  66278. */
  66279. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66280. static int valueFromFunction(
  66281. sqlite3 *db, /* The database connection */
  66282. Expr *p, /* The expression to evaluate */
  66283. u8 enc, /* Encoding to use */
  66284. u8 aff, /* Affinity to use */
  66285. sqlite3_value **ppVal, /* Write the new value here */
  66286. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  66287. ){
  66288. sqlite3_context ctx; /* Context object for function invocation */
  66289. sqlite3_value **apVal = 0; /* Function arguments */
  66290. int nVal = 0; /* Size of apVal[] array */
  66291. FuncDef *pFunc = 0; /* Function definition */
  66292. sqlite3_value *pVal = 0; /* New value */
  66293. int rc = SQLITE_OK; /* Return code */
  66294. ExprList *pList = 0; /* Function arguments */
  66295. int i; /* Iterator variable */
  66296. assert( pCtx!=0 );
  66297. assert( (p->flags & EP_TokenOnly)==0 );
  66298. pList = p->x.pList;
  66299. if( pList ) nVal = pList->nExpr;
  66300. pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
  66301. assert( pFunc );
  66302. if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
  66303. || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
  66304. ){
  66305. return SQLITE_OK;
  66306. }
  66307. if( pList ){
  66308. apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
  66309. if( apVal==0 ){
  66310. rc = SQLITE_NOMEM_BKPT;
  66311. goto value_from_function_out;
  66312. }
  66313. for(i=0; i<nVal; i++){
  66314. rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
  66315. if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
  66316. }
  66317. }
  66318. pVal = valueNew(db, pCtx);
  66319. if( pVal==0 ){
  66320. rc = SQLITE_NOMEM_BKPT;
  66321. goto value_from_function_out;
  66322. }
  66323. assert( pCtx->pParse->rc==SQLITE_OK );
  66324. memset(&ctx, 0, sizeof(ctx));
  66325. ctx.pOut = pVal;
  66326. ctx.pFunc = pFunc;
  66327. pFunc->xSFunc(&ctx, nVal, apVal);
  66328. if( ctx.isError ){
  66329. rc = ctx.isError;
  66330. sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
  66331. }else{
  66332. sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
  66333. assert( rc==SQLITE_OK );
  66334. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  66335. if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
  66336. rc = SQLITE_TOOBIG;
  66337. pCtx->pParse->nErr++;
  66338. }
  66339. }
  66340. pCtx->pParse->rc = rc;
  66341. value_from_function_out:
  66342. if( rc!=SQLITE_OK ){
  66343. pVal = 0;
  66344. }
  66345. if( apVal ){
  66346. for(i=0; i<nVal; i++){
  66347. sqlite3ValueFree(apVal[i]);
  66348. }
  66349. sqlite3DbFreeNN(db, apVal);
  66350. }
  66351. *ppVal = pVal;
  66352. return rc;
  66353. }
  66354. #else
  66355. # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
  66356. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  66357. /*
  66358. ** Extract a value from the supplied expression in the manner described
  66359. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  66360. ** using valueNew().
  66361. **
  66362. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  66363. ** has been allocated, it is freed before returning. Or, if pCtx is not
  66364. ** NULL, it is assumed that the caller will free any allocated object
  66365. ** in all cases.
  66366. */
  66367. static int valueFromExpr(
  66368. sqlite3 *db, /* The database connection */
  66369. Expr *pExpr, /* The expression to evaluate */
  66370. u8 enc, /* Encoding to use */
  66371. u8 affinity, /* Affinity to use */
  66372. sqlite3_value **ppVal, /* Write the new value here */
  66373. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  66374. ){
  66375. int op;
  66376. char *zVal = 0;
  66377. sqlite3_value *pVal = 0;
  66378. int negInt = 1;
  66379. const char *zNeg = "";
  66380. int rc = SQLITE_OK;
  66381. assert( pExpr!=0 );
  66382. while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
  66383. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  66384. /* Compressed expressions only appear when parsing the DEFAULT clause
  66385. ** on a table column definition, and hence only when pCtx==0. This
  66386. ** check ensures that an EP_TokenOnly expression is never passed down
  66387. ** into valueFromFunction(). */
  66388. assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
  66389. if( op==TK_CAST ){
  66390. u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
  66391. rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
  66392. testcase( rc!=SQLITE_OK );
  66393. if( *ppVal ){
  66394. sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
  66395. sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
  66396. }
  66397. return rc;
  66398. }
  66399. /* Handle negative integers in a single step. This is needed in the
  66400. ** case when the value is -9223372036854775808.
  66401. */
  66402. if( op==TK_UMINUS
  66403. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  66404. pExpr = pExpr->pLeft;
  66405. op = pExpr->op;
  66406. negInt = -1;
  66407. zNeg = "-";
  66408. }
  66409. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  66410. pVal = valueNew(db, pCtx);
  66411. if( pVal==0 ) goto no_mem;
  66412. if( ExprHasProperty(pExpr, EP_IntValue) ){
  66413. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  66414. }else{
  66415. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  66416. if( zVal==0 ) goto no_mem;
  66417. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  66418. }
  66419. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
  66420. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  66421. }else{
  66422. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  66423. }
  66424. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  66425. if( enc!=SQLITE_UTF8 ){
  66426. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  66427. }
  66428. }else if( op==TK_UMINUS ) {
  66429. /* This branch happens for multiple negative signs. Ex: -(-5) */
  66430. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
  66431. && pVal!=0
  66432. ){
  66433. sqlite3VdbeMemNumerify(pVal);
  66434. if( pVal->flags & MEM_Real ){
  66435. pVal->u.r = -pVal->u.r;
  66436. }else if( pVal->u.i==SMALLEST_INT64 ){
  66437. pVal->u.r = -(double)SMALLEST_INT64;
  66438. MemSetTypeFlag(pVal, MEM_Real);
  66439. }else{
  66440. pVal->u.i = -pVal->u.i;
  66441. }
  66442. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  66443. }
  66444. }else if( op==TK_NULL ){
  66445. pVal = valueNew(db, pCtx);
  66446. if( pVal==0 ) goto no_mem;
  66447. sqlite3VdbeMemNumerify(pVal);
  66448. }
  66449. #ifndef SQLITE_OMIT_BLOB_LITERAL
  66450. else if( op==TK_BLOB ){
  66451. int nVal;
  66452. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  66453. assert( pExpr->u.zToken[1]=='\'' );
  66454. pVal = valueNew(db, pCtx);
  66455. if( !pVal ) goto no_mem;
  66456. zVal = &pExpr->u.zToken[2];
  66457. nVal = sqlite3Strlen30(zVal)-1;
  66458. assert( zVal[nVal]=='\'' );
  66459. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  66460. 0, SQLITE_DYNAMIC);
  66461. }
  66462. #endif
  66463. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66464. else if( op==TK_FUNCTION && pCtx!=0 ){
  66465. rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
  66466. }
  66467. #endif
  66468. *ppVal = pVal;
  66469. return rc;
  66470. no_mem:
  66471. sqlite3OomFault(db);
  66472. sqlite3DbFree(db, zVal);
  66473. assert( *ppVal==0 );
  66474. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66475. if( pCtx==0 ) sqlite3ValueFree(pVal);
  66476. #else
  66477. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  66478. #endif
  66479. return SQLITE_NOMEM_BKPT;
  66480. }
  66481. /*
  66482. ** Create a new sqlite3_value object, containing the value of pExpr.
  66483. **
  66484. ** This only works for very simple expressions that consist of one constant
  66485. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  66486. ** be converted directly into a value, then the value is allocated and
  66487. ** a pointer written to *ppVal. The caller is responsible for deallocating
  66488. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  66489. ** cannot be converted to a value, then *ppVal is set to NULL.
  66490. */
  66491. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  66492. sqlite3 *db, /* The database connection */
  66493. Expr *pExpr, /* The expression to evaluate */
  66494. u8 enc, /* Encoding to use */
  66495. u8 affinity, /* Affinity to use */
  66496. sqlite3_value **ppVal /* Write the new value here */
  66497. ){
  66498. return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
  66499. }
  66500. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66501. /*
  66502. ** The implementation of the sqlite_record() function. This function accepts
  66503. ** a single argument of any type. The return value is a formatted database
  66504. ** record (a blob) containing the argument value.
  66505. **
  66506. ** This is used to convert the value stored in the 'sample' column of the
  66507. ** sqlite_stat3 table to the record format SQLite uses internally.
  66508. */
  66509. static void recordFunc(
  66510. sqlite3_context *context,
  66511. int argc,
  66512. sqlite3_value **argv
  66513. ){
  66514. const int file_format = 1;
  66515. u32 iSerial; /* Serial type */
  66516. int nSerial; /* Bytes of space for iSerial as varint */
  66517. u32 nVal; /* Bytes of space required for argv[0] */
  66518. int nRet;
  66519. sqlite3 *db;
  66520. u8 *aRet;
  66521. UNUSED_PARAMETER( argc );
  66522. iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
  66523. nSerial = sqlite3VarintLen(iSerial);
  66524. db = sqlite3_context_db_handle(context);
  66525. nRet = 1 + nSerial + nVal;
  66526. aRet = sqlite3DbMallocRawNN(db, nRet);
  66527. if( aRet==0 ){
  66528. sqlite3_result_error_nomem(context);
  66529. }else{
  66530. aRet[0] = nSerial+1;
  66531. putVarint32(&aRet[1], iSerial);
  66532. sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
  66533. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  66534. sqlite3DbFreeNN(db, aRet);
  66535. }
  66536. }
  66537. /*
  66538. ** Register built-in functions used to help read ANALYZE data.
  66539. */
  66540. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  66541. static FuncDef aAnalyzeTableFuncs[] = {
  66542. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  66543. };
  66544. sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
  66545. }
  66546. /*
  66547. ** Attempt to extract a value from pExpr and use it to construct *ppVal.
  66548. **
  66549. ** If pAlloc is not NULL, then an UnpackedRecord object is created for
  66550. ** pAlloc if one does not exist and the new value is added to the
  66551. ** UnpackedRecord object.
  66552. **
  66553. ** A value is extracted in the following cases:
  66554. **
  66555. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  66556. **
  66557. ** * The expression is a bound variable, and this is a reprepare, or
  66558. **
  66559. ** * The expression is a literal value.
  66560. **
  66561. ** On success, *ppVal is made to point to the extracted value. The caller
  66562. ** is responsible for ensuring that the value is eventually freed.
  66563. */
  66564. static int stat4ValueFromExpr(
  66565. Parse *pParse, /* Parse context */
  66566. Expr *pExpr, /* The expression to extract a value from */
  66567. u8 affinity, /* Affinity to use */
  66568. struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
  66569. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  66570. ){
  66571. int rc = SQLITE_OK;
  66572. sqlite3_value *pVal = 0;
  66573. sqlite3 *db = pParse->db;
  66574. /* Skip over any TK_COLLATE nodes */
  66575. pExpr = sqlite3ExprSkipCollate(pExpr);
  66576. if( !pExpr ){
  66577. pVal = valueNew(db, pAlloc);
  66578. if( pVal ){
  66579. sqlite3VdbeMemSetNull((Mem*)pVal);
  66580. }
  66581. }else if( pExpr->op==TK_VARIABLE
  66582. || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
  66583. ){
  66584. Vdbe *v;
  66585. int iBindVar = pExpr->iColumn;
  66586. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  66587. if( (v = pParse->pReprepare)!=0 ){
  66588. pVal = valueNew(db, pAlloc);
  66589. if( pVal ){
  66590. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  66591. if( rc==SQLITE_OK ){
  66592. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  66593. }
  66594. pVal->db = pParse->db;
  66595. }
  66596. }
  66597. }else{
  66598. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
  66599. }
  66600. assert( pVal==0 || pVal->db==db );
  66601. *ppVal = pVal;
  66602. return rc;
  66603. }
  66604. /*
  66605. ** This function is used to allocate and populate UnpackedRecord
  66606. ** structures intended to be compared against sample index keys stored
  66607. ** in the sqlite_stat4 table.
  66608. **
  66609. ** A single call to this function populates zero or more fields of the
  66610. ** record starting with field iVal (fields are numbered from left to
  66611. ** right starting with 0). A single field is populated if:
  66612. **
  66613. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  66614. **
  66615. ** * The expression is a bound variable, and this is a reprepare, or
  66616. **
  66617. ** * The sqlite3ValueFromExpr() function is able to extract a value
  66618. ** from the expression (i.e. the expression is a literal value).
  66619. **
  66620. ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
  66621. ** vector components that match either of the two latter criteria listed
  66622. ** above.
  66623. **
  66624. ** Before any value is appended to the record, the affinity of the
  66625. ** corresponding column within index pIdx is applied to it. Before
  66626. ** this function returns, output parameter *pnExtract is set to the
  66627. ** number of values appended to the record.
  66628. **
  66629. ** When this function is called, *ppRec must either point to an object
  66630. ** allocated by an earlier call to this function, or must be NULL. If it
  66631. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  66632. ** is allocated (and *ppRec set to point to it) before returning.
  66633. **
  66634. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  66635. ** error if a value cannot be extracted from pExpr. If an error does
  66636. ** occur, an SQLite error code is returned.
  66637. */
  66638. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  66639. Parse *pParse, /* Parse context */
  66640. Index *pIdx, /* Index being probed */
  66641. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  66642. Expr *pExpr, /* The expression to extract a value from */
  66643. int nElem, /* Maximum number of values to append */
  66644. int iVal, /* Array element to populate */
  66645. int *pnExtract /* OUT: Values appended to the record */
  66646. ){
  66647. int rc = SQLITE_OK;
  66648. int nExtract = 0;
  66649. if( pExpr==0 || pExpr->op!=TK_SELECT ){
  66650. int i;
  66651. struct ValueNewStat4Ctx alloc;
  66652. alloc.pParse = pParse;
  66653. alloc.pIdx = pIdx;
  66654. alloc.ppRec = ppRec;
  66655. for(i=0; i<nElem; i++){
  66656. sqlite3_value *pVal = 0;
  66657. Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
  66658. u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
  66659. alloc.iVal = iVal+i;
  66660. rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
  66661. if( !pVal ) break;
  66662. nExtract++;
  66663. }
  66664. }
  66665. *pnExtract = nExtract;
  66666. return rc;
  66667. }
  66668. /*
  66669. ** Attempt to extract a value from expression pExpr using the methods
  66670. ** as described for sqlite3Stat4ProbeSetValue() above.
  66671. **
  66672. ** If successful, set *ppVal to point to a new value object and return
  66673. ** SQLITE_OK. If no value can be extracted, but no other error occurs
  66674. ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
  66675. ** does occur, return an SQLite error code. The final value of *ppVal
  66676. ** is undefined in this case.
  66677. */
  66678. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
  66679. Parse *pParse, /* Parse context */
  66680. Expr *pExpr, /* The expression to extract a value from */
  66681. u8 affinity, /* Affinity to use */
  66682. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  66683. ){
  66684. return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
  66685. }
  66686. /*
  66687. ** Extract the iCol-th column from the nRec-byte record in pRec. Write
  66688. ** the column value into *ppVal. If *ppVal is initially NULL then a new
  66689. ** sqlite3_value object is allocated.
  66690. **
  66691. ** If *ppVal is initially NULL then the caller is responsible for
  66692. ** ensuring that the value written into *ppVal is eventually freed.
  66693. */
  66694. SQLITE_PRIVATE int sqlite3Stat4Column(
  66695. sqlite3 *db, /* Database handle */
  66696. const void *pRec, /* Pointer to buffer containing record */
  66697. int nRec, /* Size of buffer pRec in bytes */
  66698. int iCol, /* Column to extract */
  66699. sqlite3_value **ppVal /* OUT: Extracted value */
  66700. ){
  66701. u32 t; /* a column type code */
  66702. int nHdr; /* Size of the header in the record */
  66703. int iHdr; /* Next unread header byte */
  66704. int iField; /* Next unread data byte */
  66705. int szField; /* Size of the current data field */
  66706. int i; /* Column index */
  66707. u8 *a = (u8*)pRec; /* Typecast byte array */
  66708. Mem *pMem = *ppVal; /* Write result into this Mem object */
  66709. assert( iCol>0 );
  66710. iHdr = getVarint32(a, nHdr);
  66711. if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
  66712. iField = nHdr;
  66713. for(i=0; i<=iCol; i++){
  66714. iHdr += getVarint32(&a[iHdr], t);
  66715. testcase( iHdr==nHdr );
  66716. testcase( iHdr==nHdr+1 );
  66717. if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
  66718. szField = sqlite3VdbeSerialTypeLen(t);
  66719. iField += szField;
  66720. }
  66721. testcase( iField==nRec );
  66722. testcase( iField==nRec+1 );
  66723. if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
  66724. if( pMem==0 ){
  66725. pMem = *ppVal = sqlite3ValueNew(db);
  66726. if( pMem==0 ) return SQLITE_NOMEM_BKPT;
  66727. }
  66728. sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
  66729. pMem->enc = ENC(db);
  66730. return SQLITE_OK;
  66731. }
  66732. /*
  66733. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  66734. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  66735. ** the object.
  66736. */
  66737. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  66738. if( pRec ){
  66739. int i;
  66740. int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
  66741. Mem *aMem = pRec->aMem;
  66742. sqlite3 *db = aMem[0].db;
  66743. for(i=0; i<nCol; i++){
  66744. sqlite3VdbeMemRelease(&aMem[i]);
  66745. }
  66746. sqlite3KeyInfoUnref(pRec->pKeyInfo);
  66747. sqlite3DbFreeNN(db, pRec);
  66748. }
  66749. }
  66750. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  66751. /*
  66752. ** Change the string value of an sqlite3_value object
  66753. */
  66754. SQLITE_PRIVATE void sqlite3ValueSetStr(
  66755. sqlite3_value *v, /* Value to be set */
  66756. int n, /* Length of string z */
  66757. const void *z, /* Text of the new string */
  66758. u8 enc, /* Encoding to use */
  66759. void (*xDel)(void*) /* Destructor for the string */
  66760. ){
  66761. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  66762. }
  66763. /*
  66764. ** Free an sqlite3_value object
  66765. */
  66766. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  66767. if( !v ) return;
  66768. sqlite3VdbeMemRelease((Mem *)v);
  66769. sqlite3DbFreeNN(((Mem*)v)->db, v);
  66770. }
  66771. /*
  66772. ** The sqlite3ValueBytes() routine returns the number of bytes in the
  66773. ** sqlite3_value object assuming that it uses the encoding "enc".
  66774. ** The valueBytes() routine is a helper function.
  66775. */
  66776. static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
  66777. return valueToText(pVal, enc)!=0 ? pVal->n : 0;
  66778. }
  66779. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  66780. Mem *p = (Mem*)pVal;
  66781. assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
  66782. if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
  66783. return p->n;
  66784. }
  66785. if( (p->flags & MEM_Blob)!=0 ){
  66786. if( p->flags & MEM_Zero ){
  66787. return p->n + p->u.nZero;
  66788. }else{
  66789. return p->n;
  66790. }
  66791. }
  66792. if( p->flags & MEM_Null ) return 0;
  66793. return valueBytes(pVal, enc);
  66794. }
  66795. /************** End of vdbemem.c *********************************************/
  66796. /************** Begin file vdbeaux.c *****************************************/
  66797. /*
  66798. ** 2003 September 6
  66799. **
  66800. ** The author disclaims copyright to this source code. In place of
  66801. ** a legal notice, here is a blessing:
  66802. **
  66803. ** May you do good and not evil.
  66804. ** May you find forgiveness for yourself and forgive others.
  66805. ** May you share freely, never taking more than you give.
  66806. **
  66807. *************************************************************************
  66808. ** This file contains code used for creating, destroying, and populating
  66809. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
  66810. */
  66811. /* #include "sqliteInt.h" */
  66812. /* #include "vdbeInt.h" */
  66813. /*
  66814. ** Create a new virtual database engine.
  66815. */
  66816. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
  66817. sqlite3 *db = pParse->db;
  66818. Vdbe *p;
  66819. p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
  66820. if( p==0 ) return 0;
  66821. memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
  66822. p->db = db;
  66823. if( db->pVdbe ){
  66824. db->pVdbe->pPrev = p;
  66825. }
  66826. p->pNext = db->pVdbe;
  66827. p->pPrev = 0;
  66828. db->pVdbe = p;
  66829. p->magic = VDBE_MAGIC_INIT;
  66830. p->pParse = pParse;
  66831. assert( pParse->aLabel==0 );
  66832. assert( pParse->nLabel==0 );
  66833. assert( pParse->nOpAlloc==0 );
  66834. assert( pParse->szOpAlloc==0 );
  66835. return p;
  66836. }
  66837. /*
  66838. ** Change the error string stored in Vdbe.zErrMsg
  66839. */
  66840. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
  66841. va_list ap;
  66842. sqlite3DbFree(p->db, p->zErrMsg);
  66843. va_start(ap, zFormat);
  66844. p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
  66845. va_end(ap);
  66846. }
  66847. /*
  66848. ** Remember the SQL string for a prepared statement.
  66849. */
  66850. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  66851. assert( isPrepareV2==1 || isPrepareV2==0 );
  66852. if( p==0 ) return;
  66853. if( !isPrepareV2 ) p->expmask = 0;
  66854. #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
  66855. if( !isPrepareV2 ) return;
  66856. #endif
  66857. assert( p->zSql==0 );
  66858. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  66859. p->isPrepareV2 = (u8)isPrepareV2;
  66860. }
  66861. /*
  66862. ** Swap all content between two VDBE structures.
  66863. */
  66864. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  66865. Vdbe tmp, *pTmp;
  66866. char *zTmp;
  66867. assert( pA->db==pB->db );
  66868. tmp = *pA;
  66869. *pA = *pB;
  66870. *pB = tmp;
  66871. pTmp = pA->pNext;
  66872. pA->pNext = pB->pNext;
  66873. pB->pNext = pTmp;
  66874. pTmp = pA->pPrev;
  66875. pA->pPrev = pB->pPrev;
  66876. pB->pPrev = pTmp;
  66877. zTmp = pA->zSql;
  66878. pA->zSql = pB->zSql;
  66879. pB->zSql = zTmp;
  66880. pB->isPrepareV2 = pA->isPrepareV2;
  66881. pB->expmask = pA->expmask;
  66882. }
  66883. /*
  66884. ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
  66885. ** than its current size. nOp is guaranteed to be less than or equal
  66886. ** to 1024/sizeof(Op).
  66887. **
  66888. ** If an out-of-memory error occurs while resizing the array, return
  66889. ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
  66890. ** unchanged (this is so that any opcodes already allocated can be
  66891. ** correctly deallocated along with the rest of the Vdbe).
  66892. */
  66893. static int growOpArray(Vdbe *v, int nOp){
  66894. VdbeOp *pNew;
  66895. Parse *p = v->pParse;
  66896. /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
  66897. ** more frequent reallocs and hence provide more opportunities for
  66898. ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
  66899. ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
  66900. ** by the minimum* amount required until the size reaches 512. Normal
  66901. ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
  66902. ** size of the op array or add 1KB of space, whichever is smaller. */
  66903. #ifdef SQLITE_TEST_REALLOC_STRESS
  66904. int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
  66905. #else
  66906. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  66907. UNUSED_PARAMETER(nOp);
  66908. #endif
  66909. /* Ensure that the size of a VDBE does not grow too large */
  66910. if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
  66911. sqlite3OomFault(p->db);
  66912. return SQLITE_NOMEM;
  66913. }
  66914. assert( nOp<=(1024/sizeof(Op)) );
  66915. assert( nNew>=(p->nOpAlloc+nOp) );
  66916. pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
  66917. if( pNew ){
  66918. p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
  66919. p->nOpAlloc = p->szOpAlloc/sizeof(Op);
  66920. v->aOp = pNew;
  66921. }
  66922. return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
  66923. }
  66924. #ifdef SQLITE_DEBUG
  66925. /* This routine is just a convenient place to set a breakpoint that will
  66926. ** fire after each opcode is inserted and displayed using
  66927. ** "PRAGMA vdbe_addoptrace=on".
  66928. */
  66929. static void test_addop_breakpoint(void){
  66930. static int n = 0;
  66931. n++;
  66932. }
  66933. #endif
  66934. /*
  66935. ** Add a new instruction to the list of instructions current in the
  66936. ** VDBE. Return the address of the new instruction.
  66937. **
  66938. ** Parameters:
  66939. **
  66940. ** p Pointer to the VDBE
  66941. **
  66942. ** op The opcode for this instruction
  66943. **
  66944. ** p1, p2, p3 Operands
  66945. **
  66946. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  66947. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  66948. ** operand.
  66949. */
  66950. static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
  66951. assert( p->pParse->nOpAlloc<=p->nOp );
  66952. if( growOpArray(p, 1) ) return 1;
  66953. assert( p->pParse->nOpAlloc>p->nOp );
  66954. return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  66955. }
  66956. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  66957. int i;
  66958. VdbeOp *pOp;
  66959. i = p->nOp;
  66960. assert( p->magic==VDBE_MAGIC_INIT );
  66961. assert( op>=0 && op<0xff );
  66962. if( p->pParse->nOpAlloc<=i ){
  66963. return growOp3(p, op, p1, p2, p3);
  66964. }
  66965. p->nOp++;
  66966. pOp = &p->aOp[i];
  66967. pOp->opcode = (u8)op;
  66968. pOp->p5 = 0;
  66969. pOp->p1 = p1;
  66970. pOp->p2 = p2;
  66971. pOp->p3 = p3;
  66972. pOp->p4.p = 0;
  66973. pOp->p4type = P4_NOTUSED;
  66974. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  66975. pOp->zComment = 0;
  66976. #endif
  66977. #ifdef SQLITE_DEBUG
  66978. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  66979. int jj, kk;
  66980. Parse *pParse = p->pParse;
  66981. for(jj=kk=0; jj<pParse->nColCache; jj++){
  66982. struct yColCache *x = pParse->aColCache + jj;
  66983. printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
  66984. kk++;
  66985. }
  66986. if( kk ) printf("\n");
  66987. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  66988. test_addop_breakpoint();
  66989. }
  66990. #endif
  66991. #ifdef VDBE_PROFILE
  66992. pOp->cycles = 0;
  66993. pOp->cnt = 0;
  66994. #endif
  66995. #ifdef SQLITE_VDBE_COVERAGE
  66996. pOp->iSrcLine = 0;
  66997. #endif
  66998. return i;
  66999. }
  67000. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  67001. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  67002. }
  67003. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  67004. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  67005. }
  67006. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  67007. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  67008. }
  67009. /* Generate code for an unconditional jump to instruction iDest
  67010. */
  67011. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
  67012. return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
  67013. }
  67014. /* Generate code to cause the string zStr to be loaded into
  67015. ** register iDest
  67016. */
  67017. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
  67018. return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
  67019. }
  67020. /*
  67021. ** Generate code that initializes multiple registers to string or integer
  67022. ** constants. The registers begin with iDest and increase consecutively.
  67023. ** One register is initialized for each characgter in zTypes[]. For each
  67024. ** "s" character in zTypes[], the register is a string if the argument is
  67025. ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
  67026. ** in zTypes[], the register is initialized to an integer.
  67027. */
  67028. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
  67029. va_list ap;
  67030. int i;
  67031. char c;
  67032. va_start(ap, zTypes);
  67033. for(i=0; (c = zTypes[i])!=0; i++){
  67034. if( c=='s' ){
  67035. const char *z = va_arg(ap, const char*);
  67036. sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest++, 0, z, 0);
  67037. }else{
  67038. assert( c=='i' );
  67039. sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest++);
  67040. }
  67041. }
  67042. va_end(ap);
  67043. }
  67044. /*
  67045. ** Add an opcode that includes the p4 value as a pointer.
  67046. */
  67047. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  67048. Vdbe *p, /* Add the opcode to this VM */
  67049. int op, /* The new opcode */
  67050. int p1, /* The P1 operand */
  67051. int p2, /* The P2 operand */
  67052. int p3, /* The P3 operand */
  67053. const char *zP4, /* The P4 operand */
  67054. int p4type /* P4 operand type */
  67055. ){
  67056. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  67057. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  67058. return addr;
  67059. }
  67060. /*
  67061. ** Add an opcode that includes the p4 value with a P4_INT64 or
  67062. ** P4_REAL type.
  67063. */
  67064. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
  67065. Vdbe *p, /* Add the opcode to this VM */
  67066. int op, /* The new opcode */
  67067. int p1, /* The P1 operand */
  67068. int p2, /* The P2 operand */
  67069. int p3, /* The P3 operand */
  67070. const u8 *zP4, /* The P4 operand */
  67071. int p4type /* P4 operand type */
  67072. ){
  67073. char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
  67074. if( p4copy ) memcpy(p4copy, zP4, 8);
  67075. return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
  67076. }
  67077. /*
  67078. ** Add an OP_ParseSchema opcode. This routine is broken out from
  67079. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  67080. ** as having been used.
  67081. **
  67082. ** The zWhere string must have been obtained from sqlite3_malloc().
  67083. ** This routine will take ownership of the allocated memory.
  67084. */
  67085. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  67086. int j;
  67087. sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
  67088. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  67089. }
  67090. /*
  67091. ** Add an opcode that includes the p4 value as an integer.
  67092. */
  67093. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  67094. Vdbe *p, /* Add the opcode to this VM */
  67095. int op, /* The new opcode */
  67096. int p1, /* The P1 operand */
  67097. int p2, /* The P2 operand */
  67098. int p3, /* The P3 operand */
  67099. int p4 /* The P4 operand as an integer */
  67100. ){
  67101. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  67102. if( p->db->mallocFailed==0 ){
  67103. VdbeOp *pOp = &p->aOp[addr];
  67104. pOp->p4type = P4_INT32;
  67105. pOp->p4.i = p4;
  67106. }
  67107. return addr;
  67108. }
  67109. /* Insert the end of a co-routine
  67110. */
  67111. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
  67112. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  67113. /* Clear the temporary register cache, thereby ensuring that each
  67114. ** co-routine has its own independent set of registers, because co-routines
  67115. ** might expect their registers to be preserved across an OP_Yield, and
  67116. ** that could cause problems if two or more co-routines are using the same
  67117. ** temporary register.
  67118. */
  67119. v->pParse->nTempReg = 0;
  67120. v->pParse->nRangeReg = 0;
  67121. }
  67122. /*
  67123. ** Create a new symbolic label for an instruction that has yet to be
  67124. ** coded. The symbolic label is really just a negative number. The
  67125. ** label can be used as the P2 value of an operation. Later, when
  67126. ** the label is resolved to a specific address, the VDBE will scan
  67127. ** through its operation list and change all values of P2 which match
  67128. ** the label into the resolved address.
  67129. **
  67130. ** The VDBE knows that a P2 value is a label because labels are
  67131. ** always negative and P2 values are suppose to be non-negative.
  67132. ** Hence, a negative P2 value is a label that has yet to be resolved.
  67133. **
  67134. ** Zero is returned if a malloc() fails.
  67135. */
  67136. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
  67137. Parse *p = v->pParse;
  67138. int i = p->nLabel++;
  67139. assert( v->magic==VDBE_MAGIC_INIT );
  67140. if( (i & (i-1))==0 ){
  67141. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  67142. (i*2+1)*sizeof(p->aLabel[0]));
  67143. }
  67144. if( p->aLabel ){
  67145. p->aLabel[i] = -1;
  67146. }
  67147. return ADDR(i);
  67148. }
  67149. /*
  67150. ** Resolve label "x" to be the address of the next instruction to
  67151. ** be inserted. The parameter "x" must have been obtained from
  67152. ** a prior call to sqlite3VdbeMakeLabel().
  67153. */
  67154. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
  67155. Parse *p = v->pParse;
  67156. int j = ADDR(x);
  67157. assert( v->magic==VDBE_MAGIC_INIT );
  67158. assert( j<p->nLabel );
  67159. assert( j>=0 );
  67160. if( p->aLabel ){
  67161. p->aLabel[j] = v->nOp;
  67162. }
  67163. }
  67164. /*
  67165. ** Mark the VDBE as one that can only be run one time.
  67166. */
  67167. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  67168. p->runOnlyOnce = 1;
  67169. }
  67170. /*
  67171. ** Mark the VDBE as one that can only be run multiple times.
  67172. */
  67173. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
  67174. p->runOnlyOnce = 0;
  67175. }
  67176. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  67177. /*
  67178. ** The following type and function are used to iterate through all opcodes
  67179. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  67180. ** invoke directly or indirectly. It should be used as follows:
  67181. **
  67182. ** Op *pOp;
  67183. ** VdbeOpIter sIter;
  67184. **
  67185. ** memset(&sIter, 0, sizeof(sIter));
  67186. ** sIter.v = v; // v is of type Vdbe*
  67187. ** while( (pOp = opIterNext(&sIter)) ){
  67188. ** // Do something with pOp
  67189. ** }
  67190. ** sqlite3DbFree(v->db, sIter.apSub);
  67191. **
  67192. */
  67193. typedef struct VdbeOpIter VdbeOpIter;
  67194. struct VdbeOpIter {
  67195. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  67196. SubProgram **apSub; /* Array of subprograms */
  67197. int nSub; /* Number of entries in apSub */
  67198. int iAddr; /* Address of next instruction to return */
  67199. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  67200. };
  67201. static Op *opIterNext(VdbeOpIter *p){
  67202. Vdbe *v = p->v;
  67203. Op *pRet = 0;
  67204. Op *aOp;
  67205. int nOp;
  67206. if( p->iSub<=p->nSub ){
  67207. if( p->iSub==0 ){
  67208. aOp = v->aOp;
  67209. nOp = v->nOp;
  67210. }else{
  67211. aOp = p->apSub[p->iSub-1]->aOp;
  67212. nOp = p->apSub[p->iSub-1]->nOp;
  67213. }
  67214. assert( p->iAddr<nOp );
  67215. pRet = &aOp[p->iAddr];
  67216. p->iAddr++;
  67217. if( p->iAddr==nOp ){
  67218. p->iSub++;
  67219. p->iAddr = 0;
  67220. }
  67221. if( pRet->p4type==P4_SUBPROGRAM ){
  67222. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  67223. int j;
  67224. for(j=0; j<p->nSub; j++){
  67225. if( p->apSub[j]==pRet->p4.pProgram ) break;
  67226. }
  67227. if( j==p->nSub ){
  67228. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  67229. if( !p->apSub ){
  67230. pRet = 0;
  67231. }else{
  67232. p->apSub[p->nSub++] = pRet->p4.pProgram;
  67233. }
  67234. }
  67235. }
  67236. }
  67237. return pRet;
  67238. }
  67239. /*
  67240. ** Check if the program stored in the VM associated with pParse may
  67241. ** throw an ABORT exception (causing the statement, but not entire transaction
  67242. ** to be rolled back). This condition is true if the main program or any
  67243. ** sub-programs contains any of the following:
  67244. **
  67245. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  67246. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  67247. ** * OP_Destroy
  67248. ** * OP_VUpdate
  67249. ** * OP_VRename
  67250. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  67251. ** * OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...)
  67252. **
  67253. ** Then check that the value of Parse.mayAbort is true if an
  67254. ** ABORT may be thrown, or false otherwise. Return true if it does
  67255. ** match, or false otherwise. This function is intended to be used as
  67256. ** part of an assert statement in the compiler. Similar to:
  67257. **
  67258. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  67259. */
  67260. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  67261. int hasAbort = 0;
  67262. int hasFkCounter = 0;
  67263. int hasCreateTable = 0;
  67264. int hasInitCoroutine = 0;
  67265. Op *pOp;
  67266. VdbeOpIter sIter;
  67267. memset(&sIter, 0, sizeof(sIter));
  67268. sIter.v = v;
  67269. while( (pOp = opIterNext(&sIter))!=0 ){
  67270. int opcode = pOp->opcode;
  67271. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  67272. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  67273. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  67274. ){
  67275. hasAbort = 1;
  67276. break;
  67277. }
  67278. if( opcode==OP_CreateTable ) hasCreateTable = 1;
  67279. if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
  67280. #ifndef SQLITE_OMIT_FOREIGN_KEY
  67281. if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
  67282. hasFkCounter = 1;
  67283. }
  67284. #endif
  67285. }
  67286. sqlite3DbFree(v->db, sIter.apSub);
  67287. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  67288. ** If malloc failed, then the while() loop above may not have iterated
  67289. ** through all opcodes and hasAbort may be set incorrectly. Return
  67290. ** true for this case to prevent the assert() in the callers frame
  67291. ** from failing. */
  67292. return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
  67293. || (hasCreateTable && hasInitCoroutine) );
  67294. }
  67295. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  67296. /*
  67297. ** This routine is called after all opcodes have been inserted. It loops
  67298. ** through all the opcodes and fixes up some details.
  67299. **
  67300. ** (1) For each jump instruction with a negative P2 value (a label)
  67301. ** resolve the P2 value to an actual address.
  67302. **
  67303. ** (2) Compute the maximum number of arguments used by any SQL function
  67304. ** and store that value in *pMaxFuncArgs.
  67305. **
  67306. ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
  67307. ** indicate what the prepared statement actually does.
  67308. **
  67309. ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
  67310. **
  67311. ** (5) Reclaim the memory allocated for storing labels.
  67312. **
  67313. ** This routine will only function correctly if the mkopcodeh.tcl generator
  67314. ** script numbers the opcodes correctly. Changes to this routine must be
  67315. ** coordinated with changes to mkopcodeh.tcl.
  67316. */
  67317. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  67318. int nMaxArgs = *pMaxFuncArgs;
  67319. Op *pOp;
  67320. Parse *pParse = p->pParse;
  67321. int *aLabel = pParse->aLabel;
  67322. p->readOnly = 1;
  67323. p->bIsReader = 0;
  67324. pOp = &p->aOp[p->nOp-1];
  67325. while(1){
  67326. /* Only JUMP opcodes and the short list of special opcodes in the switch
  67327. ** below need to be considered. The mkopcodeh.tcl generator script groups
  67328. ** all these opcodes together near the front of the opcode list. Skip
  67329. ** any opcode that does not need processing by virtual of the fact that
  67330. ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
  67331. */
  67332. if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
  67333. /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
  67334. ** cases from this switch! */
  67335. switch( pOp->opcode ){
  67336. case OP_Transaction: {
  67337. if( pOp->p2!=0 ) p->readOnly = 0;
  67338. /* fall thru */
  67339. }
  67340. case OP_AutoCommit:
  67341. case OP_Savepoint: {
  67342. p->bIsReader = 1;
  67343. break;
  67344. }
  67345. #ifndef SQLITE_OMIT_WAL
  67346. case OP_Checkpoint:
  67347. #endif
  67348. case OP_Vacuum:
  67349. case OP_JournalMode: {
  67350. p->readOnly = 0;
  67351. p->bIsReader = 1;
  67352. break;
  67353. }
  67354. #ifndef SQLITE_OMIT_VIRTUALTABLE
  67355. case OP_VUpdate: {
  67356. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  67357. break;
  67358. }
  67359. case OP_VFilter: {
  67360. int n;
  67361. assert( (pOp - p->aOp) >= 3 );
  67362. assert( pOp[-1].opcode==OP_Integer );
  67363. n = pOp[-1].p1;
  67364. if( n>nMaxArgs ) nMaxArgs = n;
  67365. break;
  67366. }
  67367. #endif
  67368. case OP_Next:
  67369. case OP_NextIfOpen:
  67370. case OP_SorterNext: {
  67371. pOp->p4.xAdvance = sqlite3BtreeNext;
  67372. pOp->p4type = P4_ADVANCE;
  67373. break;
  67374. }
  67375. case OP_Prev:
  67376. case OP_PrevIfOpen: {
  67377. pOp->p4.xAdvance = sqlite3BtreePrevious;
  67378. pOp->p4type = P4_ADVANCE;
  67379. break;
  67380. }
  67381. }
  67382. if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 && pOp->p2<0 ){
  67383. assert( ADDR(pOp->p2)<pParse->nLabel );
  67384. pOp->p2 = aLabel[ADDR(pOp->p2)];
  67385. }
  67386. }
  67387. if( pOp==p->aOp ) break;
  67388. pOp--;
  67389. }
  67390. sqlite3DbFree(p->db, pParse->aLabel);
  67391. pParse->aLabel = 0;
  67392. pParse->nLabel = 0;
  67393. *pMaxFuncArgs = nMaxArgs;
  67394. assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
  67395. }
  67396. /*
  67397. ** Return the address of the next instruction to be inserted.
  67398. */
  67399. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  67400. assert( p->magic==VDBE_MAGIC_INIT );
  67401. return p->nOp;
  67402. }
  67403. /*
  67404. ** Verify that at least N opcode slots are available in p without
  67405. ** having to malloc for more space (except when compiled using
  67406. ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
  67407. ** to verify that certain calls to sqlite3VdbeAddOpList() can never
  67408. ** fail due to a OOM fault and hence that the return value from
  67409. ** sqlite3VdbeAddOpList() will always be non-NULL.
  67410. */
  67411. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  67412. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
  67413. assert( p->nOp + N <= p->pParse->nOpAlloc );
  67414. }
  67415. #endif
  67416. /*
  67417. ** Verify that the VM passed as the only argument does not contain
  67418. ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
  67419. ** by code in pragma.c to ensure that the implementation of certain
  67420. ** pragmas comports with the flags specified in the mkpragmatab.tcl
  67421. ** script.
  67422. */
  67423. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  67424. SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
  67425. int i;
  67426. for(i=0; i<p->nOp; i++){
  67427. assert( p->aOp[i].opcode!=OP_ResultRow );
  67428. }
  67429. }
  67430. #endif
  67431. /*
  67432. ** This function returns a pointer to the array of opcodes associated with
  67433. ** the Vdbe passed as the first argument. It is the callers responsibility
  67434. ** to arrange for the returned array to be eventually freed using the
  67435. ** vdbeFreeOpArray() function.
  67436. **
  67437. ** Before returning, *pnOp is set to the number of entries in the returned
  67438. ** array. Also, *pnMaxArg is set to the larger of its current value and
  67439. ** the number of entries in the Vdbe.apArg[] array required to execute the
  67440. ** returned program.
  67441. */
  67442. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  67443. VdbeOp *aOp = p->aOp;
  67444. assert( aOp && !p->db->mallocFailed );
  67445. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  67446. assert( DbMaskAllZero(p->btreeMask) );
  67447. resolveP2Values(p, pnMaxArg);
  67448. *pnOp = p->nOp;
  67449. p->aOp = 0;
  67450. return aOp;
  67451. }
  67452. /*
  67453. ** Add a whole list of operations to the operation stack. Return a
  67454. ** pointer to the first operation inserted.
  67455. **
  67456. ** Non-zero P2 arguments to jump instructions are automatically adjusted
  67457. ** so that the jump target is relative to the first operation inserted.
  67458. */
  67459. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
  67460. Vdbe *p, /* Add opcodes to the prepared statement */
  67461. int nOp, /* Number of opcodes to add */
  67462. VdbeOpList const *aOp, /* The opcodes to be added */
  67463. int iLineno /* Source-file line number of first opcode */
  67464. ){
  67465. int i;
  67466. VdbeOp *pOut, *pFirst;
  67467. assert( nOp>0 );
  67468. assert( p->magic==VDBE_MAGIC_INIT );
  67469. if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
  67470. return 0;
  67471. }
  67472. pFirst = pOut = &p->aOp[p->nOp];
  67473. for(i=0; i<nOp; i++, aOp++, pOut++){
  67474. pOut->opcode = aOp->opcode;
  67475. pOut->p1 = aOp->p1;
  67476. pOut->p2 = aOp->p2;
  67477. assert( aOp->p2>=0 );
  67478. if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
  67479. pOut->p2 += p->nOp;
  67480. }
  67481. pOut->p3 = aOp->p3;
  67482. pOut->p4type = P4_NOTUSED;
  67483. pOut->p4.p = 0;
  67484. pOut->p5 = 0;
  67485. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  67486. pOut->zComment = 0;
  67487. #endif
  67488. #ifdef SQLITE_VDBE_COVERAGE
  67489. pOut->iSrcLine = iLineno+i;
  67490. #else
  67491. (void)iLineno;
  67492. #endif
  67493. #ifdef SQLITE_DEBUG
  67494. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  67495. sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
  67496. }
  67497. #endif
  67498. }
  67499. p->nOp += nOp;
  67500. return pFirst;
  67501. }
  67502. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  67503. /*
  67504. ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
  67505. */
  67506. SQLITE_PRIVATE void sqlite3VdbeScanStatus(
  67507. Vdbe *p, /* VM to add scanstatus() to */
  67508. int addrExplain, /* Address of OP_Explain (or 0) */
  67509. int addrLoop, /* Address of loop counter */
  67510. int addrVisit, /* Address of rows visited counter */
  67511. LogEst nEst, /* Estimated number of output rows */
  67512. const char *zName /* Name of table or index being scanned */
  67513. ){
  67514. int nByte = (p->nScan+1) * sizeof(ScanStatus);
  67515. ScanStatus *aNew;
  67516. aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
  67517. if( aNew ){
  67518. ScanStatus *pNew = &aNew[p->nScan++];
  67519. pNew->addrExplain = addrExplain;
  67520. pNew->addrLoop = addrLoop;
  67521. pNew->addrVisit = addrVisit;
  67522. pNew->nEst = nEst;
  67523. pNew->zName = sqlite3DbStrDup(p->db, zName);
  67524. p->aScan = aNew;
  67525. }
  67526. }
  67527. #endif
  67528. /*
  67529. ** Change the value of the opcode, or P1, P2, P3, or P5 operands
  67530. ** for a specific instruction.
  67531. */
  67532. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
  67533. sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
  67534. }
  67535. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  67536. sqlite3VdbeGetOp(p,addr)->p1 = val;
  67537. }
  67538. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  67539. sqlite3VdbeGetOp(p,addr)->p2 = val;
  67540. }
  67541. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  67542. sqlite3VdbeGetOp(p,addr)->p3 = val;
  67543. }
  67544. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
  67545. assert( p->nOp>0 || p->db->mallocFailed );
  67546. if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
  67547. }
  67548. /*
  67549. ** Change the P2 operand of instruction addr so that it points to
  67550. ** the address of the next instruction to be coded.
  67551. */
  67552. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  67553. sqlite3VdbeChangeP2(p, addr, p->nOp);
  67554. }
  67555. /*
  67556. ** If the input FuncDef structure is ephemeral, then free it. If
  67557. ** the FuncDef is not ephermal, then do nothing.
  67558. */
  67559. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  67560. if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  67561. sqlite3DbFreeNN(db, pDef);
  67562. }
  67563. }
  67564. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  67565. /*
  67566. ** Delete a P4 value if necessary.
  67567. */
  67568. static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
  67569. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  67570. sqlite3DbFreeNN(db, p);
  67571. }
  67572. static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
  67573. freeEphemeralFunction(db, p->pFunc);
  67574. sqlite3DbFreeNN(db, p);
  67575. }
  67576. static void freeP4(sqlite3 *db, int p4type, void *p4){
  67577. assert( db );
  67578. switch( p4type ){
  67579. case P4_FUNCCTX: {
  67580. freeP4FuncCtx(db, (sqlite3_context*)p4);
  67581. break;
  67582. }
  67583. case P4_REAL:
  67584. case P4_INT64:
  67585. case P4_DYNAMIC:
  67586. case P4_INTARRAY: {
  67587. sqlite3DbFree(db, p4);
  67588. break;
  67589. }
  67590. case P4_KEYINFO: {
  67591. if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
  67592. break;
  67593. }
  67594. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  67595. case P4_EXPR: {
  67596. sqlite3ExprDelete(db, (Expr*)p4);
  67597. break;
  67598. }
  67599. #endif
  67600. case P4_FUNCDEF: {
  67601. freeEphemeralFunction(db, (FuncDef*)p4);
  67602. break;
  67603. }
  67604. case P4_MEM: {
  67605. if( db->pnBytesFreed==0 ){
  67606. sqlite3ValueFree((sqlite3_value*)p4);
  67607. }else{
  67608. freeP4Mem(db, (Mem*)p4);
  67609. }
  67610. break;
  67611. }
  67612. case P4_VTAB : {
  67613. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  67614. break;
  67615. }
  67616. }
  67617. }
  67618. /*
  67619. ** Free the space allocated for aOp and any p4 values allocated for the
  67620. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  67621. ** nOp entries.
  67622. */
  67623. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  67624. if( aOp ){
  67625. Op *pOp;
  67626. for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
  67627. if( pOp->p4type ) freeP4(db, pOp->p4type, pOp->p4.p);
  67628. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  67629. sqlite3DbFree(db, pOp->zComment);
  67630. #endif
  67631. }
  67632. sqlite3DbFreeNN(db, aOp);
  67633. }
  67634. }
  67635. /*
  67636. ** Link the SubProgram object passed as the second argument into the linked
  67637. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  67638. ** objects when the VM is no longer required.
  67639. */
  67640. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  67641. p->pNext = pVdbe->pProgram;
  67642. pVdbe->pProgram = p;
  67643. }
  67644. /*
  67645. ** Change the opcode at addr into OP_Noop
  67646. */
  67647. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  67648. VdbeOp *pOp;
  67649. if( p->db->mallocFailed ) return 0;
  67650. assert( addr>=0 && addr<p->nOp );
  67651. pOp = &p->aOp[addr];
  67652. freeP4(p->db, pOp->p4type, pOp->p4.p);
  67653. pOp->p4type = P4_NOTUSED;
  67654. pOp->p4.z = 0;
  67655. pOp->opcode = OP_Noop;
  67656. return 1;
  67657. }
  67658. /*
  67659. ** If the last opcode is "op" and it is not a jump destination,
  67660. ** then remove it. Return true if and only if an opcode was removed.
  67661. */
  67662. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
  67663. if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
  67664. return sqlite3VdbeChangeToNoop(p, p->nOp-1);
  67665. }else{
  67666. return 0;
  67667. }
  67668. }
  67669. /*
  67670. ** Change the value of the P4 operand for a specific instruction.
  67671. ** This routine is useful when a large program is loaded from a
  67672. ** static array using sqlite3VdbeAddOpList but we want to make a
  67673. ** few minor changes to the program.
  67674. **
  67675. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  67676. ** the string is made into memory obtained from sqlite3_malloc().
  67677. ** A value of n==0 means copy bytes of zP4 up to and including the
  67678. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  67679. **
  67680. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  67681. ** to a string or structure that is guaranteed to exist for the lifetime of
  67682. ** the Vdbe. In these cases we can just copy the pointer.
  67683. **
  67684. ** If addr<0 then change P4 on the most recently inserted instruction.
  67685. */
  67686. static void SQLITE_NOINLINE vdbeChangeP4Full(
  67687. Vdbe *p,
  67688. Op *pOp,
  67689. const char *zP4,
  67690. int n
  67691. ){
  67692. if( pOp->p4type ){
  67693. freeP4(p->db, pOp->p4type, pOp->p4.p);
  67694. pOp->p4type = 0;
  67695. pOp->p4.p = 0;
  67696. }
  67697. if( n<0 ){
  67698. sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
  67699. }else{
  67700. if( n==0 ) n = sqlite3Strlen30(zP4);
  67701. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  67702. pOp->p4type = P4_DYNAMIC;
  67703. }
  67704. }
  67705. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  67706. Op *pOp;
  67707. sqlite3 *db;
  67708. assert( p!=0 );
  67709. db = p->db;
  67710. assert( p->magic==VDBE_MAGIC_INIT );
  67711. assert( p->aOp!=0 || db->mallocFailed );
  67712. if( db->mallocFailed ){
  67713. if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
  67714. return;
  67715. }
  67716. assert( p->nOp>0 );
  67717. assert( addr<p->nOp );
  67718. if( addr<0 ){
  67719. addr = p->nOp - 1;
  67720. }
  67721. pOp = &p->aOp[addr];
  67722. if( n>=0 || pOp->p4type ){
  67723. vdbeChangeP4Full(p, pOp, zP4, n);
  67724. return;
  67725. }
  67726. if( n==P4_INT32 ){
  67727. /* Note: this cast is safe, because the origin data point was an int
  67728. ** that was cast to a (const char *). */
  67729. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  67730. pOp->p4type = P4_INT32;
  67731. }else if( zP4!=0 ){
  67732. assert( n<0 );
  67733. pOp->p4.p = (void*)zP4;
  67734. pOp->p4type = (signed char)n;
  67735. if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
  67736. }
  67737. }
  67738. /*
  67739. ** Change the P4 operand of the most recently coded instruction
  67740. ** to the value defined by the arguments. This is a high-speed
  67741. ** version of sqlite3VdbeChangeP4().
  67742. **
  67743. ** The P4 operand must not have been previously defined. And the new
  67744. ** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of
  67745. ** those cases.
  67746. */
  67747. SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
  67748. VdbeOp *pOp;
  67749. assert( n!=P4_INT32 && n!=P4_VTAB );
  67750. assert( n<=0 );
  67751. if( p->db->mallocFailed ){
  67752. freeP4(p->db, n, pP4);
  67753. }else{
  67754. assert( pP4!=0 );
  67755. assert( p->nOp>0 );
  67756. pOp = &p->aOp[p->nOp-1];
  67757. assert( pOp->p4type==P4_NOTUSED );
  67758. pOp->p4type = n;
  67759. pOp->p4.p = pP4;
  67760. }
  67761. }
  67762. /*
  67763. ** Set the P4 on the most recently added opcode to the KeyInfo for the
  67764. ** index given.
  67765. */
  67766. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
  67767. Vdbe *v = pParse->pVdbe;
  67768. KeyInfo *pKeyInfo;
  67769. assert( v!=0 );
  67770. assert( pIdx!=0 );
  67771. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
  67772. if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
  67773. }
  67774. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  67775. /*
  67776. ** Change the comment on the most recently coded instruction. Or
  67777. ** insert a No-op and add the comment to that new instruction. This
  67778. ** makes the code easier to read during debugging. None of this happens
  67779. ** in a production build.
  67780. */
  67781. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  67782. assert( p->nOp>0 || p->aOp==0 );
  67783. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  67784. if( p->nOp ){
  67785. assert( p->aOp );
  67786. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  67787. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  67788. }
  67789. }
  67790. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  67791. va_list ap;
  67792. if( p ){
  67793. va_start(ap, zFormat);
  67794. vdbeVComment(p, zFormat, ap);
  67795. va_end(ap);
  67796. }
  67797. }
  67798. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  67799. va_list ap;
  67800. if( p ){
  67801. sqlite3VdbeAddOp0(p, OP_Noop);
  67802. va_start(ap, zFormat);
  67803. vdbeVComment(p, zFormat, ap);
  67804. va_end(ap);
  67805. }
  67806. }
  67807. #endif /* NDEBUG */
  67808. #ifdef SQLITE_VDBE_COVERAGE
  67809. /*
  67810. ** Set the value if the iSrcLine field for the previously coded instruction.
  67811. */
  67812. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
  67813. sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
  67814. }
  67815. #endif /* SQLITE_VDBE_COVERAGE */
  67816. /*
  67817. ** Return the opcode for a given address. If the address is -1, then
  67818. ** return the most recently inserted opcode.
  67819. **
  67820. ** If a memory allocation error has occurred prior to the calling of this
  67821. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  67822. ** is readable but not writable, though it is cast to a writable value.
  67823. ** The return of a dummy opcode allows the call to continue functioning
  67824. ** after an OOM fault without having to check to see if the return from
  67825. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  67826. ** dummy will never be written to. This is verified by code inspection and
  67827. ** by running with Valgrind.
  67828. */
  67829. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  67830. /* C89 specifies that the constant "dummy" will be initialized to all
  67831. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  67832. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  67833. assert( p->magic==VDBE_MAGIC_INIT );
  67834. if( addr<0 ){
  67835. addr = p->nOp - 1;
  67836. }
  67837. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  67838. if( p->db->mallocFailed ){
  67839. return (VdbeOp*)&dummy;
  67840. }else{
  67841. return &p->aOp[addr];
  67842. }
  67843. }
  67844. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
  67845. /*
  67846. ** Return an integer value for one of the parameters to the opcode pOp
  67847. ** determined by character c.
  67848. */
  67849. static int translateP(char c, const Op *pOp){
  67850. if( c=='1' ) return pOp->p1;
  67851. if( c=='2' ) return pOp->p2;
  67852. if( c=='3' ) return pOp->p3;
  67853. if( c=='4' ) return pOp->p4.i;
  67854. return pOp->p5;
  67855. }
  67856. /*
  67857. ** Compute a string for the "comment" field of a VDBE opcode listing.
  67858. **
  67859. ** The Synopsis: field in comments in the vdbe.c source file gets converted
  67860. ** to an extra string that is appended to the sqlite3OpcodeName(). In the
  67861. ** absence of other comments, this synopsis becomes the comment on the opcode.
  67862. ** Some translation occurs:
  67863. **
  67864. ** "PX" -> "r[X]"
  67865. ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
  67866. ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
  67867. ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
  67868. */
  67869. static int displayComment(
  67870. const Op *pOp, /* The opcode to be commented */
  67871. const char *zP4, /* Previously obtained value for P4 */
  67872. char *zTemp, /* Write result here */
  67873. int nTemp /* Space available in zTemp[] */
  67874. ){
  67875. const char *zOpName;
  67876. const char *zSynopsis;
  67877. int nOpName;
  67878. int ii, jj;
  67879. char zAlt[50];
  67880. zOpName = sqlite3OpcodeName(pOp->opcode);
  67881. nOpName = sqlite3Strlen30(zOpName);
  67882. if( zOpName[nOpName+1] ){
  67883. int seenCom = 0;
  67884. char c;
  67885. zSynopsis = zOpName += nOpName + 1;
  67886. if( strncmp(zSynopsis,"IF ",3)==0 ){
  67887. if( pOp->p5 & SQLITE_STOREP2 ){
  67888. sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
  67889. }else{
  67890. sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
  67891. }
  67892. zSynopsis = zAlt;
  67893. }
  67894. for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
  67895. if( c=='P' ){
  67896. c = zSynopsis[++ii];
  67897. if( c=='4' ){
  67898. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
  67899. }else if( c=='X' ){
  67900. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
  67901. seenCom = 1;
  67902. }else{
  67903. int v1 = translateP(c, pOp);
  67904. int v2;
  67905. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
  67906. if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
  67907. ii += 3;
  67908. jj += sqlite3Strlen30(zTemp+jj);
  67909. v2 = translateP(zSynopsis[ii], pOp);
  67910. if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
  67911. ii += 2;
  67912. v2++;
  67913. }
  67914. if( v2>1 ){
  67915. sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
  67916. }
  67917. }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
  67918. ii += 4;
  67919. }
  67920. }
  67921. jj += sqlite3Strlen30(zTemp+jj);
  67922. }else{
  67923. zTemp[jj++] = c;
  67924. }
  67925. }
  67926. if( !seenCom && jj<nTemp-5 && pOp->zComment ){
  67927. sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
  67928. jj += sqlite3Strlen30(zTemp+jj);
  67929. }
  67930. if( jj<nTemp ) zTemp[jj] = 0;
  67931. }else if( pOp->zComment ){
  67932. sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
  67933. jj = sqlite3Strlen30(zTemp);
  67934. }else{
  67935. zTemp[0] = 0;
  67936. jj = 0;
  67937. }
  67938. return jj;
  67939. }
  67940. #endif /* SQLITE_DEBUG */
  67941. #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
  67942. /*
  67943. ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
  67944. ** that can be displayed in the P4 column of EXPLAIN output.
  67945. */
  67946. static void displayP4Expr(StrAccum *p, Expr *pExpr){
  67947. const char *zOp = 0;
  67948. switch( pExpr->op ){
  67949. case TK_STRING:
  67950. sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
  67951. break;
  67952. case TK_INTEGER:
  67953. sqlite3XPrintf(p, "%d", pExpr->u.iValue);
  67954. break;
  67955. case TK_NULL:
  67956. sqlite3XPrintf(p, "NULL");
  67957. break;
  67958. case TK_REGISTER: {
  67959. sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
  67960. break;
  67961. }
  67962. case TK_COLUMN: {
  67963. if( pExpr->iColumn<0 ){
  67964. sqlite3XPrintf(p, "rowid");
  67965. }else{
  67966. sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
  67967. }
  67968. break;
  67969. }
  67970. case TK_LT: zOp = "LT"; break;
  67971. case TK_LE: zOp = "LE"; break;
  67972. case TK_GT: zOp = "GT"; break;
  67973. case TK_GE: zOp = "GE"; break;
  67974. case TK_NE: zOp = "NE"; break;
  67975. case TK_EQ: zOp = "EQ"; break;
  67976. case TK_IS: zOp = "IS"; break;
  67977. case TK_ISNOT: zOp = "ISNOT"; break;
  67978. case TK_AND: zOp = "AND"; break;
  67979. case TK_OR: zOp = "OR"; break;
  67980. case TK_PLUS: zOp = "ADD"; break;
  67981. case TK_STAR: zOp = "MUL"; break;
  67982. case TK_MINUS: zOp = "SUB"; break;
  67983. case TK_REM: zOp = "REM"; break;
  67984. case TK_BITAND: zOp = "BITAND"; break;
  67985. case TK_BITOR: zOp = "BITOR"; break;
  67986. case TK_SLASH: zOp = "DIV"; break;
  67987. case TK_LSHIFT: zOp = "LSHIFT"; break;
  67988. case TK_RSHIFT: zOp = "RSHIFT"; break;
  67989. case TK_CONCAT: zOp = "CONCAT"; break;
  67990. case TK_UMINUS: zOp = "MINUS"; break;
  67991. case TK_UPLUS: zOp = "PLUS"; break;
  67992. case TK_BITNOT: zOp = "BITNOT"; break;
  67993. case TK_NOT: zOp = "NOT"; break;
  67994. case TK_ISNULL: zOp = "ISNULL"; break;
  67995. case TK_NOTNULL: zOp = "NOTNULL"; break;
  67996. default:
  67997. sqlite3XPrintf(p, "%s", "expr");
  67998. break;
  67999. }
  68000. if( zOp ){
  68001. sqlite3XPrintf(p, "%s(", zOp);
  68002. displayP4Expr(p, pExpr->pLeft);
  68003. if( pExpr->pRight ){
  68004. sqlite3StrAccumAppend(p, ",", 1);
  68005. displayP4Expr(p, pExpr->pRight);
  68006. }
  68007. sqlite3StrAccumAppend(p, ")", 1);
  68008. }
  68009. }
  68010. #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
  68011. #if VDBE_DISPLAY_P4
  68012. /*
  68013. ** Compute a string that describes the P4 parameter for an opcode.
  68014. ** Use zTemp for any required temporary buffer space.
  68015. */
  68016. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  68017. char *zP4 = zTemp;
  68018. StrAccum x;
  68019. assert( nTemp>=20 );
  68020. sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
  68021. switch( pOp->p4type ){
  68022. case P4_KEYINFO: {
  68023. int j;
  68024. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  68025. assert( pKeyInfo->aSortOrder!=0 );
  68026. sqlite3XPrintf(&x, "k(%d", pKeyInfo->nField);
  68027. for(j=0; j<pKeyInfo->nField; j++){
  68028. CollSeq *pColl = pKeyInfo->aColl[j];
  68029. const char *zColl = pColl ? pColl->zName : "";
  68030. if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
  68031. sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
  68032. }
  68033. sqlite3StrAccumAppend(&x, ")", 1);
  68034. break;
  68035. }
  68036. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  68037. case P4_EXPR: {
  68038. displayP4Expr(&x, pOp->p4.pExpr);
  68039. break;
  68040. }
  68041. #endif
  68042. case P4_COLLSEQ: {
  68043. CollSeq *pColl = pOp->p4.pColl;
  68044. sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
  68045. break;
  68046. }
  68047. case P4_FUNCDEF: {
  68048. FuncDef *pDef = pOp->p4.pFunc;
  68049. sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  68050. break;
  68051. }
  68052. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  68053. case P4_FUNCCTX: {
  68054. FuncDef *pDef = pOp->p4.pCtx->pFunc;
  68055. sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  68056. break;
  68057. }
  68058. #endif
  68059. case P4_INT64: {
  68060. sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
  68061. break;
  68062. }
  68063. case P4_INT32: {
  68064. sqlite3XPrintf(&x, "%d", pOp->p4.i);
  68065. break;
  68066. }
  68067. case P4_REAL: {
  68068. sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
  68069. break;
  68070. }
  68071. case P4_MEM: {
  68072. Mem *pMem = pOp->p4.pMem;
  68073. if( pMem->flags & MEM_Str ){
  68074. zP4 = pMem->z;
  68075. }else if( pMem->flags & MEM_Int ){
  68076. sqlite3XPrintf(&x, "%lld", pMem->u.i);
  68077. }else if( pMem->flags & MEM_Real ){
  68078. sqlite3XPrintf(&x, "%.16g", pMem->u.r);
  68079. }else if( pMem->flags & MEM_Null ){
  68080. zP4 = "NULL";
  68081. }else{
  68082. assert( pMem->flags & MEM_Blob );
  68083. zP4 = "(blob)";
  68084. }
  68085. break;
  68086. }
  68087. #ifndef SQLITE_OMIT_VIRTUALTABLE
  68088. case P4_VTAB: {
  68089. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  68090. sqlite3XPrintf(&x, "vtab:%p", pVtab);
  68091. break;
  68092. }
  68093. #endif
  68094. case P4_INTARRAY: {
  68095. int i;
  68096. int *ai = pOp->p4.ai;
  68097. int n = ai[0]; /* The first element of an INTARRAY is always the
  68098. ** count of the number of elements to follow */
  68099. for(i=1; i<n; i++){
  68100. sqlite3XPrintf(&x, ",%d", ai[i]);
  68101. }
  68102. zTemp[0] = '[';
  68103. sqlite3StrAccumAppend(&x, "]", 1);
  68104. break;
  68105. }
  68106. case P4_SUBPROGRAM: {
  68107. sqlite3XPrintf(&x, "program");
  68108. break;
  68109. }
  68110. case P4_ADVANCE: {
  68111. zTemp[0] = 0;
  68112. break;
  68113. }
  68114. case P4_TABLE: {
  68115. sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
  68116. break;
  68117. }
  68118. default: {
  68119. zP4 = pOp->p4.z;
  68120. if( zP4==0 ){
  68121. zP4 = zTemp;
  68122. zTemp[0] = 0;
  68123. }
  68124. }
  68125. }
  68126. sqlite3StrAccumFinish(&x);
  68127. assert( zP4!=0 );
  68128. return zP4;
  68129. }
  68130. #endif /* VDBE_DISPLAY_P4 */
  68131. /*
  68132. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  68133. **
  68134. ** The prepared statements need to know in advance the complete set of
  68135. ** attached databases that will be use. A mask of these databases
  68136. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  68137. ** p->btreeMask of databases that will require a lock.
  68138. */
  68139. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  68140. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  68141. assert( i<(int)sizeof(p->btreeMask)*8 );
  68142. DbMaskSet(p->btreeMask, i);
  68143. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  68144. DbMaskSet(p->lockMask, i);
  68145. }
  68146. }
  68147. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  68148. /*
  68149. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  68150. ** this routine obtains the mutex associated with each BtShared structure
  68151. ** that may be accessed by the VM passed as an argument. In doing so it also
  68152. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  68153. ** that the correct busy-handler callback is invoked if required.
  68154. **
  68155. ** If SQLite is not threadsafe but does support shared-cache mode, then
  68156. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  68157. ** of all of BtShared structures accessible via the database handle
  68158. ** associated with the VM.
  68159. **
  68160. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  68161. ** function is a no-op.
  68162. **
  68163. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  68164. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  68165. ** corresponding to btrees that use shared cache. Then the runtime of
  68166. ** this routine is N*N. But as N is rarely more than 1, this should not
  68167. ** be a problem.
  68168. */
  68169. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  68170. int i;
  68171. sqlite3 *db;
  68172. Db *aDb;
  68173. int nDb;
  68174. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  68175. db = p->db;
  68176. aDb = db->aDb;
  68177. nDb = db->nDb;
  68178. for(i=0; i<nDb; i++){
  68179. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  68180. sqlite3BtreeEnter(aDb[i].pBt);
  68181. }
  68182. }
  68183. }
  68184. #endif
  68185. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  68186. /*
  68187. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  68188. */
  68189. static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
  68190. int i;
  68191. sqlite3 *db;
  68192. Db *aDb;
  68193. int nDb;
  68194. db = p->db;
  68195. aDb = db->aDb;
  68196. nDb = db->nDb;
  68197. for(i=0; i<nDb; i++){
  68198. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  68199. sqlite3BtreeLeave(aDb[i].pBt);
  68200. }
  68201. }
  68202. }
  68203. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  68204. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  68205. vdbeLeave(p);
  68206. }
  68207. #endif
  68208. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  68209. /*
  68210. ** Print a single opcode. This routine is used for debugging only.
  68211. */
  68212. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  68213. char *zP4;
  68214. char zPtr[50];
  68215. char zCom[100];
  68216. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
  68217. if( pOut==0 ) pOut = stdout;
  68218. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  68219. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  68220. displayComment(pOp, zP4, zCom, sizeof(zCom));
  68221. #else
  68222. zCom[0] = 0;
  68223. #endif
  68224. /* NB: The sqlite3OpcodeName() function is implemented by code created
  68225. ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
  68226. ** information from the vdbe.c source text */
  68227. fprintf(pOut, zFormat1, pc,
  68228. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  68229. zCom
  68230. );
  68231. fflush(pOut);
  68232. }
  68233. #endif
  68234. /*
  68235. ** Initialize an array of N Mem element.
  68236. */
  68237. static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
  68238. while( (N--)>0 ){
  68239. p->db = db;
  68240. p->flags = flags;
  68241. p->szMalloc = 0;
  68242. #ifdef SQLITE_DEBUG
  68243. p->pScopyFrom = 0;
  68244. #endif
  68245. p++;
  68246. }
  68247. }
  68248. /*
  68249. ** Release an array of N Mem elements
  68250. */
  68251. static void releaseMemArray(Mem *p, int N){
  68252. if( p && N ){
  68253. Mem *pEnd = &p[N];
  68254. sqlite3 *db = p->db;
  68255. if( db->pnBytesFreed ){
  68256. do{
  68257. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  68258. }while( (++p)<pEnd );
  68259. return;
  68260. }
  68261. do{
  68262. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  68263. assert( sqlite3VdbeCheckMemInvariants(p) );
  68264. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  68265. ** that takes advantage of the fact that the memory cell value is
  68266. ** being set to NULL after releasing any dynamic resources.
  68267. **
  68268. ** The justification for duplicating code is that according to
  68269. ** callgrind, this causes a certain test case to hit the CPU 4.7
  68270. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  68271. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  68272. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  68273. ** with no indexes using a single prepared INSERT statement, bind()
  68274. ** and reset(). Inserts are grouped into a transaction.
  68275. */
  68276. testcase( p->flags & MEM_Agg );
  68277. testcase( p->flags & MEM_Dyn );
  68278. testcase( p->flags & MEM_Frame );
  68279. testcase( p->flags & MEM_RowSet );
  68280. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  68281. sqlite3VdbeMemRelease(p);
  68282. }else if( p->szMalloc ){
  68283. sqlite3DbFreeNN(db, p->zMalloc);
  68284. p->szMalloc = 0;
  68285. }
  68286. p->flags = MEM_Undefined;
  68287. }while( (++p)<pEnd );
  68288. }
  68289. }
  68290. /*
  68291. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  68292. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  68293. */
  68294. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  68295. int i;
  68296. Mem *aMem = VdbeFrameMem(p);
  68297. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  68298. for(i=0; i<p->nChildCsr; i++){
  68299. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  68300. }
  68301. releaseMemArray(aMem, p->nChildMem);
  68302. sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
  68303. sqlite3DbFree(p->v->db, p);
  68304. }
  68305. #ifndef SQLITE_OMIT_EXPLAIN
  68306. /*
  68307. ** Give a listing of the program in the virtual machine.
  68308. **
  68309. ** The interface is the same as sqlite3VdbeExec(). But instead of
  68310. ** running the code, it invokes the callback once for each instruction.
  68311. ** This feature is used to implement "EXPLAIN".
  68312. **
  68313. ** When p->explain==1, each instruction is listed. When
  68314. ** p->explain==2, only OP_Explain instructions are listed and these
  68315. ** are shown in a different format. p->explain==2 is used to implement
  68316. ** EXPLAIN QUERY PLAN.
  68317. **
  68318. ** When p->explain==1, first the main program is listed, then each of
  68319. ** the trigger subprograms are listed one by one.
  68320. */
  68321. SQLITE_PRIVATE int sqlite3VdbeList(
  68322. Vdbe *p /* The VDBE */
  68323. ){
  68324. int nRow; /* Stop when row count reaches this */
  68325. int nSub = 0; /* Number of sub-vdbes seen so far */
  68326. SubProgram **apSub = 0; /* Array of sub-vdbes */
  68327. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  68328. sqlite3 *db = p->db; /* The database connection */
  68329. int i; /* Loop counter */
  68330. int rc = SQLITE_OK; /* Return code */
  68331. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  68332. assert( p->explain );
  68333. assert( p->magic==VDBE_MAGIC_RUN );
  68334. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  68335. /* Even though this opcode does not use dynamic strings for
  68336. ** the result, result columns may become dynamic if the user calls
  68337. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  68338. */
  68339. releaseMemArray(pMem, 8);
  68340. p->pResultSet = 0;
  68341. if( p->rc==SQLITE_NOMEM_BKPT ){
  68342. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  68343. ** sqlite3_column_text16() failed. */
  68344. sqlite3OomFault(db);
  68345. return SQLITE_ERROR;
  68346. }
  68347. /* When the number of output rows reaches nRow, that means the
  68348. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  68349. ** nRow is the sum of the number of rows in the main program, plus
  68350. ** the sum of the number of rows in all trigger subprograms encountered
  68351. ** so far. The nRow value will increase as new trigger subprograms are
  68352. ** encountered, but p->pc will eventually catch up to nRow.
  68353. */
  68354. nRow = p->nOp;
  68355. if( p->explain==1 ){
  68356. /* The first 8 memory cells are used for the result set. So we will
  68357. ** commandeer the 9th cell to use as storage for an array of pointers
  68358. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  68359. ** cells. */
  68360. assert( p->nMem>9 );
  68361. pSub = &p->aMem[9];
  68362. if( pSub->flags&MEM_Blob ){
  68363. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  68364. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  68365. nSub = pSub->n/sizeof(Vdbe*);
  68366. apSub = (SubProgram **)pSub->z;
  68367. }
  68368. for(i=0; i<nSub; i++){
  68369. nRow += apSub[i]->nOp;
  68370. }
  68371. }
  68372. do{
  68373. i = p->pc++;
  68374. }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  68375. if( i>=nRow ){
  68376. p->rc = SQLITE_OK;
  68377. rc = SQLITE_DONE;
  68378. }else if( db->u1.isInterrupted ){
  68379. p->rc = SQLITE_INTERRUPT;
  68380. rc = SQLITE_ERROR;
  68381. sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
  68382. }else{
  68383. char *zP4;
  68384. Op *pOp;
  68385. if( i<p->nOp ){
  68386. /* The output line number is small enough that we are still in the
  68387. ** main program. */
  68388. pOp = &p->aOp[i];
  68389. }else{
  68390. /* We are currently listing subprograms. Figure out which one and
  68391. ** pick up the appropriate opcode. */
  68392. int j;
  68393. i -= p->nOp;
  68394. for(j=0; i>=apSub[j]->nOp; j++){
  68395. i -= apSub[j]->nOp;
  68396. }
  68397. pOp = &apSub[j]->aOp[i];
  68398. }
  68399. if( p->explain==1 ){
  68400. pMem->flags = MEM_Int;
  68401. pMem->u.i = i; /* Program counter */
  68402. pMem++;
  68403. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  68404. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  68405. assert( pMem->z!=0 );
  68406. pMem->n = sqlite3Strlen30(pMem->z);
  68407. pMem->enc = SQLITE_UTF8;
  68408. pMem++;
  68409. /* When an OP_Program opcode is encounter (the only opcode that has
  68410. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  68411. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  68412. ** has not already been seen.
  68413. */
  68414. if( pOp->p4type==P4_SUBPROGRAM ){
  68415. int nByte = (nSub+1)*sizeof(SubProgram*);
  68416. int j;
  68417. for(j=0; j<nSub; j++){
  68418. if( apSub[j]==pOp->p4.pProgram ) break;
  68419. }
  68420. if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
  68421. apSub = (SubProgram **)pSub->z;
  68422. apSub[nSub++] = pOp->p4.pProgram;
  68423. pSub->flags |= MEM_Blob;
  68424. pSub->n = nSub*sizeof(SubProgram*);
  68425. }
  68426. }
  68427. }
  68428. pMem->flags = MEM_Int;
  68429. pMem->u.i = pOp->p1; /* P1 */
  68430. pMem++;
  68431. pMem->flags = MEM_Int;
  68432. pMem->u.i = pOp->p2; /* P2 */
  68433. pMem++;
  68434. pMem->flags = MEM_Int;
  68435. pMem->u.i = pOp->p3; /* P3 */
  68436. pMem++;
  68437. if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
  68438. assert( p->db->mallocFailed );
  68439. return SQLITE_ERROR;
  68440. }
  68441. pMem->flags = MEM_Str|MEM_Term;
  68442. zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
  68443. if( zP4!=pMem->z ){
  68444. pMem->n = 0;
  68445. sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
  68446. }else{
  68447. assert( pMem->z!=0 );
  68448. pMem->n = sqlite3Strlen30(pMem->z);
  68449. pMem->enc = SQLITE_UTF8;
  68450. }
  68451. pMem++;
  68452. if( p->explain==1 ){
  68453. if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
  68454. assert( p->db->mallocFailed );
  68455. return SQLITE_ERROR;
  68456. }
  68457. pMem->flags = MEM_Str|MEM_Term;
  68458. pMem->n = 2;
  68459. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  68460. pMem->enc = SQLITE_UTF8;
  68461. pMem++;
  68462. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  68463. if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
  68464. assert( p->db->mallocFailed );
  68465. return SQLITE_ERROR;
  68466. }
  68467. pMem->flags = MEM_Str|MEM_Term;
  68468. pMem->n = displayComment(pOp, zP4, pMem->z, 500);
  68469. pMem->enc = SQLITE_UTF8;
  68470. #else
  68471. pMem->flags = MEM_Null; /* Comment */
  68472. #endif
  68473. }
  68474. p->nResColumn = 8 - 4*(p->explain-1);
  68475. p->pResultSet = &p->aMem[1];
  68476. p->rc = SQLITE_OK;
  68477. rc = SQLITE_ROW;
  68478. }
  68479. return rc;
  68480. }
  68481. #endif /* SQLITE_OMIT_EXPLAIN */
  68482. #ifdef SQLITE_DEBUG
  68483. /*
  68484. ** Print the SQL that was used to generate a VDBE program.
  68485. */
  68486. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  68487. const char *z = 0;
  68488. if( p->zSql ){
  68489. z = p->zSql;
  68490. }else if( p->nOp>=1 ){
  68491. const VdbeOp *pOp = &p->aOp[0];
  68492. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  68493. z = pOp->p4.z;
  68494. while( sqlite3Isspace(*z) ) z++;
  68495. }
  68496. }
  68497. if( z ) printf("SQL: [%s]\n", z);
  68498. }
  68499. #endif
  68500. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  68501. /*
  68502. ** Print an IOTRACE message showing SQL content.
  68503. */
  68504. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  68505. int nOp = p->nOp;
  68506. VdbeOp *pOp;
  68507. if( sqlite3IoTrace==0 ) return;
  68508. if( nOp<1 ) return;
  68509. pOp = &p->aOp[0];
  68510. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  68511. int i, j;
  68512. char z[1000];
  68513. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  68514. for(i=0; sqlite3Isspace(z[i]); i++){}
  68515. for(j=0; z[i]; i++){
  68516. if( sqlite3Isspace(z[i]) ){
  68517. if( z[i-1]!=' ' ){
  68518. z[j++] = ' ';
  68519. }
  68520. }else{
  68521. z[j++] = z[i];
  68522. }
  68523. }
  68524. z[j] = 0;
  68525. sqlite3IoTrace("SQL %s\n", z);
  68526. }
  68527. }
  68528. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  68529. /* An instance of this object describes bulk memory available for use
  68530. ** by subcomponents of a prepared statement. Space is allocated out
  68531. ** of a ReusableSpace object by the allocSpace() routine below.
  68532. */
  68533. struct ReusableSpace {
  68534. u8 *pSpace; /* Available memory */
  68535. int nFree; /* Bytes of available memory */
  68536. int nNeeded; /* Total bytes that could not be allocated */
  68537. };
  68538. /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
  68539. ** from the ReusableSpace object. Return a pointer to the allocated
  68540. ** memory on success. If insufficient memory is available in the
  68541. ** ReusableSpace object, increase the ReusableSpace.nNeeded
  68542. ** value by the amount needed and return NULL.
  68543. **
  68544. ** If pBuf is not initially NULL, that means that the memory has already
  68545. ** been allocated by a prior call to this routine, so just return a copy
  68546. ** of pBuf and leave ReusableSpace unchanged.
  68547. **
  68548. ** This allocator is employed to repurpose unused slots at the end of the
  68549. ** opcode array of prepared state for other memory needs of the prepared
  68550. ** statement.
  68551. */
  68552. static void *allocSpace(
  68553. struct ReusableSpace *p, /* Bulk memory available for allocation */
  68554. void *pBuf, /* Pointer to a prior allocation */
  68555. int nByte /* Bytes of memory needed */
  68556. ){
  68557. assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
  68558. if( pBuf==0 ){
  68559. nByte = ROUND8(nByte);
  68560. if( nByte <= p->nFree ){
  68561. p->nFree -= nByte;
  68562. pBuf = &p->pSpace[p->nFree];
  68563. }else{
  68564. p->nNeeded += nByte;
  68565. }
  68566. }
  68567. assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
  68568. return pBuf;
  68569. }
  68570. /*
  68571. ** Rewind the VDBE back to the beginning in preparation for
  68572. ** running it.
  68573. */
  68574. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  68575. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  68576. int i;
  68577. #endif
  68578. assert( p!=0 );
  68579. assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
  68580. /* There should be at least one opcode.
  68581. */
  68582. assert( p->nOp>0 );
  68583. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  68584. p->magic = VDBE_MAGIC_RUN;
  68585. #ifdef SQLITE_DEBUG
  68586. for(i=0; i<p->nMem; i++){
  68587. assert( p->aMem[i].db==p->db );
  68588. }
  68589. #endif
  68590. p->pc = -1;
  68591. p->rc = SQLITE_OK;
  68592. p->errorAction = OE_Abort;
  68593. p->nChange = 0;
  68594. p->cacheCtr = 1;
  68595. p->minWriteFileFormat = 255;
  68596. p->iStatement = 0;
  68597. p->nFkConstraint = 0;
  68598. #ifdef VDBE_PROFILE
  68599. for(i=0; i<p->nOp; i++){
  68600. p->aOp[i].cnt = 0;
  68601. p->aOp[i].cycles = 0;
  68602. }
  68603. #endif
  68604. }
  68605. /*
  68606. ** Prepare a virtual machine for execution for the first time after
  68607. ** creating the virtual machine. This involves things such
  68608. ** as allocating registers and initializing the program counter.
  68609. ** After the VDBE has be prepped, it can be executed by one or more
  68610. ** calls to sqlite3VdbeExec().
  68611. **
  68612. ** This function may be called exactly once on each virtual machine.
  68613. ** After this routine is called the VM has been "packaged" and is ready
  68614. ** to run. After this routine is called, further calls to
  68615. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  68616. ** the Vdbe from the Parse object that helped generate it so that the
  68617. ** the Vdbe becomes an independent entity and the Parse object can be
  68618. ** destroyed.
  68619. **
  68620. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  68621. ** to its initial state after it has been run.
  68622. */
  68623. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  68624. Vdbe *p, /* The VDBE */
  68625. Parse *pParse /* Parsing context */
  68626. ){
  68627. sqlite3 *db; /* The database connection */
  68628. int nVar; /* Number of parameters */
  68629. int nMem; /* Number of VM memory registers */
  68630. int nCursor; /* Number of cursors required */
  68631. int nArg; /* Number of arguments in subprograms */
  68632. int n; /* Loop counter */
  68633. struct ReusableSpace x; /* Reusable bulk memory */
  68634. assert( p!=0 );
  68635. assert( p->nOp>0 );
  68636. assert( pParse!=0 );
  68637. assert( p->magic==VDBE_MAGIC_INIT );
  68638. assert( pParse==p->pParse );
  68639. db = p->db;
  68640. assert( db->mallocFailed==0 );
  68641. nVar = pParse->nVar;
  68642. nMem = pParse->nMem;
  68643. nCursor = pParse->nTab;
  68644. nArg = pParse->nMaxArg;
  68645. /* Each cursor uses a memory cell. The first cursor (cursor 0) can
  68646. ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
  68647. ** space at the end of aMem[] for cursors 1 and greater.
  68648. ** See also: allocateCursor().
  68649. */
  68650. nMem += nCursor;
  68651. if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
  68652. /* Figure out how much reusable memory is available at the end of the
  68653. ** opcode array. This extra memory will be reallocated for other elements
  68654. ** of the prepared statement.
  68655. */
  68656. n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
  68657. x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
  68658. assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
  68659. x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
  68660. assert( x.nFree>=0 );
  68661. assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
  68662. resolveP2Values(p, &nArg);
  68663. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  68664. if( pParse->explain && nMem<10 ){
  68665. nMem = 10;
  68666. }
  68667. p->expired = 0;
  68668. /* Memory for registers, parameters, cursor, etc, is allocated in one or two
  68669. ** passes. On the first pass, we try to reuse unused memory at the
  68670. ** end of the opcode array. If we are unable to satisfy all memory
  68671. ** requirements by reusing the opcode array tail, then the second
  68672. ** pass will fill in the remainder using a fresh memory allocation.
  68673. **
  68674. ** This two-pass approach that reuses as much memory as possible from
  68675. ** the leftover memory at the end of the opcode array. This can significantly
  68676. ** reduce the amount of memory held by a prepared statement.
  68677. */
  68678. do {
  68679. x.nNeeded = 0;
  68680. p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
  68681. p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
  68682. p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
  68683. p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
  68684. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  68685. p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
  68686. #endif
  68687. if( x.nNeeded==0 ) break;
  68688. x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
  68689. x.nFree = x.nNeeded;
  68690. }while( !db->mallocFailed );
  68691. p->pVList = pParse->pVList;
  68692. pParse->pVList = 0;
  68693. p->explain = pParse->explain;
  68694. if( db->mallocFailed ){
  68695. p->nVar = 0;
  68696. p->nCursor = 0;
  68697. p->nMem = 0;
  68698. }else{
  68699. p->nCursor = nCursor;
  68700. p->nVar = (ynVar)nVar;
  68701. initMemArray(p->aVar, nVar, db, MEM_Null);
  68702. p->nMem = nMem;
  68703. initMemArray(p->aMem, nMem, db, MEM_Undefined);
  68704. memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
  68705. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  68706. memset(p->anExec, 0, p->nOp*sizeof(i64));
  68707. #endif
  68708. }
  68709. sqlite3VdbeRewind(p);
  68710. }
  68711. /*
  68712. ** Close a VDBE cursor and release all the resources that cursor
  68713. ** happens to hold.
  68714. */
  68715. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  68716. if( pCx==0 ){
  68717. return;
  68718. }
  68719. assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
  68720. switch( pCx->eCurType ){
  68721. case CURTYPE_SORTER: {
  68722. sqlite3VdbeSorterClose(p->db, pCx);
  68723. break;
  68724. }
  68725. case CURTYPE_BTREE: {
  68726. if( pCx->isEphemeral ){
  68727. if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
  68728. /* The pCx->pCursor will be close automatically, if it exists, by
  68729. ** the call above. */
  68730. }else{
  68731. assert( pCx->uc.pCursor!=0 );
  68732. sqlite3BtreeCloseCursor(pCx->uc.pCursor);
  68733. }
  68734. break;
  68735. }
  68736. #ifndef SQLITE_OMIT_VIRTUALTABLE
  68737. case CURTYPE_VTAB: {
  68738. sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
  68739. const sqlite3_module *pModule = pVCur->pVtab->pModule;
  68740. assert( pVCur->pVtab->nRef>0 );
  68741. pVCur->pVtab->nRef--;
  68742. pModule->xClose(pVCur);
  68743. break;
  68744. }
  68745. #endif
  68746. }
  68747. }
  68748. /*
  68749. ** Close all cursors in the current frame.
  68750. */
  68751. static void closeCursorsInFrame(Vdbe *p){
  68752. if( p->apCsr ){
  68753. int i;
  68754. for(i=0; i<p->nCursor; i++){
  68755. VdbeCursor *pC = p->apCsr[i];
  68756. if( pC ){
  68757. sqlite3VdbeFreeCursor(p, pC);
  68758. p->apCsr[i] = 0;
  68759. }
  68760. }
  68761. }
  68762. }
  68763. /*
  68764. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  68765. ** is used, for example, when a trigger sub-program is halted to restore
  68766. ** control to the main program.
  68767. */
  68768. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  68769. Vdbe *v = pFrame->v;
  68770. closeCursorsInFrame(v);
  68771. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  68772. v->anExec = pFrame->anExec;
  68773. #endif
  68774. v->aOp = pFrame->aOp;
  68775. v->nOp = pFrame->nOp;
  68776. v->aMem = pFrame->aMem;
  68777. v->nMem = pFrame->nMem;
  68778. v->apCsr = pFrame->apCsr;
  68779. v->nCursor = pFrame->nCursor;
  68780. v->db->lastRowid = pFrame->lastRowid;
  68781. v->nChange = pFrame->nChange;
  68782. v->db->nChange = pFrame->nDbChange;
  68783. sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
  68784. v->pAuxData = pFrame->pAuxData;
  68785. pFrame->pAuxData = 0;
  68786. return pFrame->pc;
  68787. }
  68788. /*
  68789. ** Close all cursors.
  68790. **
  68791. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  68792. ** cell array. This is necessary as the memory cell array may contain
  68793. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  68794. ** open cursors.
  68795. */
  68796. static void closeAllCursors(Vdbe *p){
  68797. if( p->pFrame ){
  68798. VdbeFrame *pFrame;
  68799. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  68800. sqlite3VdbeFrameRestore(pFrame);
  68801. p->pFrame = 0;
  68802. p->nFrame = 0;
  68803. }
  68804. assert( p->nFrame==0 );
  68805. closeCursorsInFrame(p);
  68806. if( p->aMem ){
  68807. releaseMemArray(p->aMem, p->nMem);
  68808. }
  68809. while( p->pDelFrame ){
  68810. VdbeFrame *pDel = p->pDelFrame;
  68811. p->pDelFrame = pDel->pParent;
  68812. sqlite3VdbeFrameDelete(pDel);
  68813. }
  68814. /* Delete any auxdata allocations made by the VM */
  68815. if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
  68816. assert( p->pAuxData==0 );
  68817. }
  68818. /*
  68819. ** Clean up the VM after a single run.
  68820. */
  68821. static void Cleanup(Vdbe *p){
  68822. sqlite3 *db = p->db;
  68823. #ifdef SQLITE_DEBUG
  68824. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  68825. ** Vdbe.aMem[] arrays have already been cleaned up. */
  68826. int i;
  68827. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  68828. if( p->aMem ){
  68829. for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
  68830. }
  68831. #endif
  68832. sqlite3DbFree(db, p->zErrMsg);
  68833. p->zErrMsg = 0;
  68834. p->pResultSet = 0;
  68835. }
  68836. /*
  68837. ** Set the number of result columns that will be returned by this SQL
  68838. ** statement. This is now set at compile time, rather than during
  68839. ** execution of the vdbe program so that sqlite3_column_count() can
  68840. ** be called on an SQL statement before sqlite3_step().
  68841. */
  68842. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  68843. Mem *pColName;
  68844. int n;
  68845. sqlite3 *db = p->db;
  68846. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  68847. sqlite3DbFree(db, p->aColName);
  68848. n = nResColumn*COLNAME_N;
  68849. p->nResColumn = (u16)nResColumn;
  68850. p->aColName = pColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
  68851. if( p->aColName==0 ) return;
  68852. initMemArray(p->aColName, n, p->db, MEM_Null);
  68853. }
  68854. /*
  68855. ** Set the name of the idx'th column to be returned by the SQL statement.
  68856. ** zName must be a pointer to a nul terminated string.
  68857. **
  68858. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  68859. **
  68860. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  68861. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  68862. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  68863. */
  68864. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  68865. Vdbe *p, /* Vdbe being configured */
  68866. int idx, /* Index of column zName applies to */
  68867. int var, /* One of the COLNAME_* constants */
  68868. const char *zName, /* Pointer to buffer containing name */
  68869. void (*xDel)(void*) /* Memory management strategy for zName */
  68870. ){
  68871. int rc;
  68872. Mem *pColName;
  68873. assert( idx<p->nResColumn );
  68874. assert( var<COLNAME_N );
  68875. if( p->db->mallocFailed ){
  68876. assert( !zName || xDel!=SQLITE_DYNAMIC );
  68877. return SQLITE_NOMEM_BKPT;
  68878. }
  68879. assert( p->aColName!=0 );
  68880. pColName = &(p->aColName[idx+var*p->nResColumn]);
  68881. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  68882. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  68883. return rc;
  68884. }
  68885. /*
  68886. ** A read or write transaction may or may not be active on database handle
  68887. ** db. If a transaction is active, commit it. If there is a
  68888. ** write-transaction spanning more than one database file, this routine
  68889. ** takes care of the master journal trickery.
  68890. */
  68891. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  68892. int i;
  68893. int nTrans = 0; /* Number of databases with an active write-transaction
  68894. ** that are candidates for a two-phase commit using a
  68895. ** master-journal */
  68896. int rc = SQLITE_OK;
  68897. int needXcommit = 0;
  68898. #ifdef SQLITE_OMIT_VIRTUALTABLE
  68899. /* With this option, sqlite3VtabSync() is defined to be simply
  68900. ** SQLITE_OK so p is not used.
  68901. */
  68902. UNUSED_PARAMETER(p);
  68903. #endif
  68904. /* Before doing anything else, call the xSync() callback for any
  68905. ** virtual module tables written in this transaction. This has to
  68906. ** be done before determining whether a master journal file is
  68907. ** required, as an xSync() callback may add an attached database
  68908. ** to the transaction.
  68909. */
  68910. rc = sqlite3VtabSync(db, p);
  68911. /* This loop determines (a) if the commit hook should be invoked and
  68912. ** (b) how many database files have open write transactions, not
  68913. ** including the temp database. (b) is important because if more than
  68914. ** one database file has an open write transaction, a master journal
  68915. ** file is required for an atomic commit.
  68916. */
  68917. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  68918. Btree *pBt = db->aDb[i].pBt;
  68919. if( sqlite3BtreeIsInTrans(pBt) ){
  68920. /* Whether or not a database might need a master journal depends upon
  68921. ** its journal mode (among other things). This matrix determines which
  68922. ** journal modes use a master journal and which do not */
  68923. static const u8 aMJNeeded[] = {
  68924. /* DELETE */ 1,
  68925. /* PERSIST */ 1,
  68926. /* OFF */ 0,
  68927. /* TRUNCATE */ 1,
  68928. /* MEMORY */ 0,
  68929. /* WAL */ 0
  68930. };
  68931. Pager *pPager; /* Pager associated with pBt */
  68932. needXcommit = 1;
  68933. sqlite3BtreeEnter(pBt);
  68934. pPager = sqlite3BtreePager(pBt);
  68935. if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
  68936. && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
  68937. ){
  68938. assert( i!=1 );
  68939. nTrans++;
  68940. }
  68941. rc = sqlite3PagerExclusiveLock(pPager);
  68942. sqlite3BtreeLeave(pBt);
  68943. }
  68944. }
  68945. if( rc!=SQLITE_OK ){
  68946. return rc;
  68947. }
  68948. /* If there are any write-transactions at all, invoke the commit hook */
  68949. if( needXcommit && db->xCommitCallback ){
  68950. rc = db->xCommitCallback(db->pCommitArg);
  68951. if( rc ){
  68952. return SQLITE_CONSTRAINT_COMMITHOOK;
  68953. }
  68954. }
  68955. /* The simple case - no more than one database file (not counting the
  68956. ** TEMP database) has a transaction active. There is no need for the
  68957. ** master-journal.
  68958. **
  68959. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  68960. ** string, it means the main database is :memory: or a temp file. In
  68961. ** that case we do not support atomic multi-file commits, so use the
  68962. ** simple case then too.
  68963. */
  68964. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  68965. || nTrans<=1
  68966. ){
  68967. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  68968. Btree *pBt = db->aDb[i].pBt;
  68969. if( pBt ){
  68970. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  68971. }
  68972. }
  68973. /* Do the commit only if all databases successfully complete phase 1.
  68974. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  68975. ** IO error while deleting or truncating a journal file. It is unlikely,
  68976. ** but could happen. In this case abandon processing and return the error.
  68977. */
  68978. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  68979. Btree *pBt = db->aDb[i].pBt;
  68980. if( pBt ){
  68981. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  68982. }
  68983. }
  68984. if( rc==SQLITE_OK ){
  68985. sqlite3VtabCommit(db);
  68986. }
  68987. }
  68988. /* The complex case - There is a multi-file write-transaction active.
  68989. ** This requires a master journal file to ensure the transaction is
  68990. ** committed atomically.
  68991. */
  68992. #ifndef SQLITE_OMIT_DISKIO
  68993. else{
  68994. sqlite3_vfs *pVfs = db->pVfs;
  68995. char *zMaster = 0; /* File-name for the master journal */
  68996. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  68997. sqlite3_file *pMaster = 0;
  68998. i64 offset = 0;
  68999. int res;
  69000. int retryCount = 0;
  69001. int nMainFile;
  69002. /* Select a master journal file name */
  69003. nMainFile = sqlite3Strlen30(zMainFile);
  69004. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  69005. if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
  69006. do {
  69007. u32 iRandom;
  69008. if( retryCount ){
  69009. if( retryCount>100 ){
  69010. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  69011. sqlite3OsDelete(pVfs, zMaster, 0);
  69012. break;
  69013. }else if( retryCount==1 ){
  69014. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  69015. }
  69016. }
  69017. retryCount++;
  69018. sqlite3_randomness(sizeof(iRandom), &iRandom);
  69019. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  69020. (iRandom>>8)&0xffffff, iRandom&0xff);
  69021. /* The antipenultimate character of the master journal name must
  69022. ** be "9" to avoid name collisions when using 8+3 filenames. */
  69023. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  69024. sqlite3FileSuffix3(zMainFile, zMaster);
  69025. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  69026. }while( rc==SQLITE_OK && res );
  69027. if( rc==SQLITE_OK ){
  69028. /* Open the master journal. */
  69029. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  69030. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  69031. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  69032. );
  69033. }
  69034. if( rc!=SQLITE_OK ){
  69035. sqlite3DbFree(db, zMaster);
  69036. return rc;
  69037. }
  69038. /* Write the name of each database file in the transaction into the new
  69039. ** master journal file. If an error occurs at this point close
  69040. ** and delete the master journal file. All the individual journal files
  69041. ** still have 'null' as the master journal pointer, so they will roll
  69042. ** back independently if a failure occurs.
  69043. */
  69044. for(i=0; i<db->nDb; i++){
  69045. Btree *pBt = db->aDb[i].pBt;
  69046. if( sqlite3BtreeIsInTrans(pBt) ){
  69047. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  69048. if( zFile==0 ){
  69049. continue; /* Ignore TEMP and :memory: databases */
  69050. }
  69051. assert( zFile[0]!=0 );
  69052. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  69053. offset += sqlite3Strlen30(zFile)+1;
  69054. if( rc!=SQLITE_OK ){
  69055. sqlite3OsCloseFree(pMaster);
  69056. sqlite3OsDelete(pVfs, zMaster, 0);
  69057. sqlite3DbFree(db, zMaster);
  69058. return rc;
  69059. }
  69060. }
  69061. }
  69062. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  69063. ** flag is set this is not required.
  69064. */
  69065. if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  69066. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  69067. ){
  69068. sqlite3OsCloseFree(pMaster);
  69069. sqlite3OsDelete(pVfs, zMaster, 0);
  69070. sqlite3DbFree(db, zMaster);
  69071. return rc;
  69072. }
  69073. /* Sync all the db files involved in the transaction. The same call
  69074. ** sets the master journal pointer in each individual journal. If
  69075. ** an error occurs here, do not delete the master journal file.
  69076. **
  69077. ** If the error occurs during the first call to
  69078. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  69079. ** master journal file will be orphaned. But we cannot delete it,
  69080. ** in case the master journal file name was written into the journal
  69081. ** file before the failure occurred.
  69082. */
  69083. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  69084. Btree *pBt = db->aDb[i].pBt;
  69085. if( pBt ){
  69086. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  69087. }
  69088. }
  69089. sqlite3OsCloseFree(pMaster);
  69090. assert( rc!=SQLITE_BUSY );
  69091. if( rc!=SQLITE_OK ){
  69092. sqlite3DbFree(db, zMaster);
  69093. return rc;
  69094. }
  69095. /* Delete the master journal file. This commits the transaction. After
  69096. ** doing this the directory is synced again before any individual
  69097. ** transaction files are deleted.
  69098. */
  69099. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  69100. sqlite3DbFree(db, zMaster);
  69101. zMaster = 0;
  69102. if( rc ){
  69103. return rc;
  69104. }
  69105. /* All files and directories have already been synced, so the following
  69106. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  69107. ** deleting or truncating journals. If something goes wrong while
  69108. ** this is happening we don't really care. The integrity of the
  69109. ** transaction is already guaranteed, but some stray 'cold' journals
  69110. ** may be lying around. Returning an error code won't help matters.
  69111. */
  69112. disable_simulated_io_errors();
  69113. sqlite3BeginBenignMalloc();
  69114. for(i=0; i<db->nDb; i++){
  69115. Btree *pBt = db->aDb[i].pBt;
  69116. if( pBt ){
  69117. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  69118. }
  69119. }
  69120. sqlite3EndBenignMalloc();
  69121. enable_simulated_io_errors();
  69122. sqlite3VtabCommit(db);
  69123. }
  69124. #endif
  69125. return rc;
  69126. }
  69127. /*
  69128. ** This routine checks that the sqlite3.nVdbeActive count variable
  69129. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  69130. ** currently active. An assertion fails if the two counts do not match.
  69131. ** This is an internal self-check only - it is not an essential processing
  69132. ** step.
  69133. **
  69134. ** This is a no-op if NDEBUG is defined.
  69135. */
  69136. #ifndef NDEBUG
  69137. static void checkActiveVdbeCnt(sqlite3 *db){
  69138. Vdbe *p;
  69139. int cnt = 0;
  69140. int nWrite = 0;
  69141. int nRead = 0;
  69142. p = db->pVdbe;
  69143. while( p ){
  69144. if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
  69145. cnt++;
  69146. if( p->readOnly==0 ) nWrite++;
  69147. if( p->bIsReader ) nRead++;
  69148. }
  69149. p = p->pNext;
  69150. }
  69151. assert( cnt==db->nVdbeActive );
  69152. assert( nWrite==db->nVdbeWrite );
  69153. assert( nRead==db->nVdbeRead );
  69154. }
  69155. #else
  69156. #define checkActiveVdbeCnt(x)
  69157. #endif
  69158. /*
  69159. ** If the Vdbe passed as the first argument opened a statement-transaction,
  69160. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  69161. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  69162. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  69163. ** statement transaction is committed.
  69164. **
  69165. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  69166. ** Otherwise SQLITE_OK.
  69167. */
  69168. static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
  69169. sqlite3 *const db = p->db;
  69170. int rc = SQLITE_OK;
  69171. int i;
  69172. const int iSavepoint = p->iStatement-1;
  69173. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  69174. assert( db->nStatement>0 );
  69175. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  69176. for(i=0; i<db->nDb; i++){
  69177. int rc2 = SQLITE_OK;
  69178. Btree *pBt = db->aDb[i].pBt;
  69179. if( pBt ){
  69180. if( eOp==SAVEPOINT_ROLLBACK ){
  69181. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  69182. }
  69183. if( rc2==SQLITE_OK ){
  69184. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  69185. }
  69186. if( rc==SQLITE_OK ){
  69187. rc = rc2;
  69188. }
  69189. }
  69190. }
  69191. db->nStatement--;
  69192. p->iStatement = 0;
  69193. if( rc==SQLITE_OK ){
  69194. if( eOp==SAVEPOINT_ROLLBACK ){
  69195. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  69196. }
  69197. if( rc==SQLITE_OK ){
  69198. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  69199. }
  69200. }
  69201. /* If the statement transaction is being rolled back, also restore the
  69202. ** database handles deferred constraint counter to the value it had when
  69203. ** the statement transaction was opened. */
  69204. if( eOp==SAVEPOINT_ROLLBACK ){
  69205. db->nDeferredCons = p->nStmtDefCons;
  69206. db->nDeferredImmCons = p->nStmtDefImmCons;
  69207. }
  69208. return rc;
  69209. }
  69210. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  69211. if( p->db->nStatement && p->iStatement ){
  69212. return vdbeCloseStatement(p, eOp);
  69213. }
  69214. return SQLITE_OK;
  69215. }
  69216. /*
  69217. ** This function is called when a transaction opened by the database
  69218. ** handle associated with the VM passed as an argument is about to be
  69219. ** committed. If there are outstanding deferred foreign key constraint
  69220. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  69221. **
  69222. ** If there are outstanding FK violations and this function returns
  69223. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  69224. ** and write an error message to it. Then return SQLITE_ERROR.
  69225. */
  69226. #ifndef SQLITE_OMIT_FOREIGN_KEY
  69227. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  69228. sqlite3 *db = p->db;
  69229. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  69230. || (!deferred && p->nFkConstraint>0)
  69231. ){
  69232. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  69233. p->errorAction = OE_Abort;
  69234. sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
  69235. return SQLITE_ERROR;
  69236. }
  69237. return SQLITE_OK;
  69238. }
  69239. #endif
  69240. /*
  69241. ** This routine is called the when a VDBE tries to halt. If the VDBE
  69242. ** has made changes and is in autocommit mode, then commit those
  69243. ** changes. If a rollback is needed, then do the rollback.
  69244. **
  69245. ** This routine is the only way to move the state of a VM from
  69246. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  69247. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  69248. **
  69249. ** Return an error code. If the commit could not complete because of
  69250. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  69251. ** means the close did not happen and needs to be repeated.
  69252. */
  69253. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  69254. int rc; /* Used to store transient return codes */
  69255. sqlite3 *db = p->db;
  69256. /* This function contains the logic that determines if a statement or
  69257. ** transaction will be committed or rolled back as a result of the
  69258. ** execution of this virtual machine.
  69259. **
  69260. ** If any of the following errors occur:
  69261. **
  69262. ** SQLITE_NOMEM
  69263. ** SQLITE_IOERR
  69264. ** SQLITE_FULL
  69265. ** SQLITE_INTERRUPT
  69266. **
  69267. ** Then the internal cache might have been left in an inconsistent
  69268. ** state. We need to rollback the statement transaction, if there is
  69269. ** one, or the complete transaction if there is no statement transaction.
  69270. */
  69271. if( p->magic!=VDBE_MAGIC_RUN ){
  69272. return SQLITE_OK;
  69273. }
  69274. if( db->mallocFailed ){
  69275. p->rc = SQLITE_NOMEM_BKPT;
  69276. }
  69277. closeAllCursors(p);
  69278. checkActiveVdbeCnt(db);
  69279. /* No commit or rollback needed if the program never started or if the
  69280. ** SQL statement does not read or write a database file. */
  69281. if( p->pc>=0 && p->bIsReader ){
  69282. int mrc; /* Primary error code from p->rc */
  69283. int eStatementOp = 0;
  69284. int isSpecialError; /* Set to true if a 'special' error */
  69285. /* Lock all btrees used by the statement */
  69286. sqlite3VdbeEnter(p);
  69287. /* Check for one of the special errors */
  69288. mrc = p->rc & 0xff;
  69289. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  69290. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  69291. if( isSpecialError ){
  69292. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  69293. ** no rollback is necessary. Otherwise, at least a savepoint
  69294. ** transaction must be rolled back to restore the database to a
  69295. ** consistent state.
  69296. **
  69297. ** Even if the statement is read-only, it is important to perform
  69298. ** a statement or transaction rollback operation. If the error
  69299. ** occurred while writing to the journal, sub-journal or database
  69300. ** file as part of an effort to free up cache space (see function
  69301. ** pagerStress() in pager.c), the rollback is required to restore
  69302. ** the pager to a consistent state.
  69303. */
  69304. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  69305. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  69306. eStatementOp = SAVEPOINT_ROLLBACK;
  69307. }else{
  69308. /* We are forced to roll back the active transaction. Before doing
  69309. ** so, abort any other statements this handle currently has active.
  69310. */
  69311. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  69312. sqlite3CloseSavepoints(db);
  69313. db->autoCommit = 1;
  69314. p->nChange = 0;
  69315. }
  69316. }
  69317. }
  69318. /* Check for immediate foreign key violations. */
  69319. if( p->rc==SQLITE_OK ){
  69320. sqlite3VdbeCheckFk(p, 0);
  69321. }
  69322. /* If the auto-commit flag is set and this is the only active writer
  69323. ** VM, then we do either a commit or rollback of the current transaction.
  69324. **
  69325. ** Note: This block also runs if one of the special errors handled
  69326. ** above has occurred.
  69327. */
  69328. if( !sqlite3VtabInSync(db)
  69329. && db->autoCommit
  69330. && db->nVdbeWrite==(p->readOnly==0)
  69331. ){
  69332. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  69333. rc = sqlite3VdbeCheckFk(p, 1);
  69334. if( rc!=SQLITE_OK ){
  69335. if( NEVER(p->readOnly) ){
  69336. sqlite3VdbeLeave(p);
  69337. return SQLITE_ERROR;
  69338. }
  69339. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  69340. }else{
  69341. /* The auto-commit flag is true, the vdbe program was successful
  69342. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  69343. ** key constraints to hold up the transaction. This means a commit
  69344. ** is required. */
  69345. rc = vdbeCommit(db, p);
  69346. }
  69347. if( rc==SQLITE_BUSY && p->readOnly ){
  69348. sqlite3VdbeLeave(p);
  69349. return SQLITE_BUSY;
  69350. }else if( rc!=SQLITE_OK ){
  69351. p->rc = rc;
  69352. sqlite3RollbackAll(db, SQLITE_OK);
  69353. p->nChange = 0;
  69354. }else{
  69355. db->nDeferredCons = 0;
  69356. db->nDeferredImmCons = 0;
  69357. db->flags &= ~SQLITE_DeferFKs;
  69358. sqlite3CommitInternalChanges(db);
  69359. }
  69360. }else{
  69361. sqlite3RollbackAll(db, SQLITE_OK);
  69362. p->nChange = 0;
  69363. }
  69364. db->nStatement = 0;
  69365. }else if( eStatementOp==0 ){
  69366. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  69367. eStatementOp = SAVEPOINT_RELEASE;
  69368. }else if( p->errorAction==OE_Abort ){
  69369. eStatementOp = SAVEPOINT_ROLLBACK;
  69370. }else{
  69371. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  69372. sqlite3CloseSavepoints(db);
  69373. db->autoCommit = 1;
  69374. p->nChange = 0;
  69375. }
  69376. }
  69377. /* If eStatementOp is non-zero, then a statement transaction needs to
  69378. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  69379. ** do so. If this operation returns an error, and the current statement
  69380. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  69381. ** current statement error code.
  69382. */
  69383. if( eStatementOp ){
  69384. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  69385. if( rc ){
  69386. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  69387. p->rc = rc;
  69388. sqlite3DbFree(db, p->zErrMsg);
  69389. p->zErrMsg = 0;
  69390. }
  69391. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  69392. sqlite3CloseSavepoints(db);
  69393. db->autoCommit = 1;
  69394. p->nChange = 0;
  69395. }
  69396. }
  69397. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  69398. ** has been rolled back, update the database connection change-counter.
  69399. */
  69400. if( p->changeCntOn ){
  69401. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  69402. sqlite3VdbeSetChanges(db, p->nChange);
  69403. }else{
  69404. sqlite3VdbeSetChanges(db, 0);
  69405. }
  69406. p->nChange = 0;
  69407. }
  69408. /* Release the locks */
  69409. sqlite3VdbeLeave(p);
  69410. }
  69411. /* We have successfully halted and closed the VM. Record this fact. */
  69412. if( p->pc>=0 ){
  69413. db->nVdbeActive--;
  69414. if( !p->readOnly ) db->nVdbeWrite--;
  69415. if( p->bIsReader ) db->nVdbeRead--;
  69416. assert( db->nVdbeActive>=db->nVdbeRead );
  69417. assert( db->nVdbeRead>=db->nVdbeWrite );
  69418. assert( db->nVdbeWrite>=0 );
  69419. }
  69420. p->magic = VDBE_MAGIC_HALT;
  69421. checkActiveVdbeCnt(db);
  69422. if( db->mallocFailed ){
  69423. p->rc = SQLITE_NOMEM_BKPT;
  69424. }
  69425. /* If the auto-commit flag is set to true, then any locks that were held
  69426. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  69427. ** to invoke any required unlock-notify callbacks.
  69428. */
  69429. if( db->autoCommit ){
  69430. sqlite3ConnectionUnlocked(db);
  69431. }
  69432. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  69433. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  69434. }
  69435. /*
  69436. ** Each VDBE holds the result of the most recent sqlite3_step() call
  69437. ** in p->rc. This routine sets that result back to SQLITE_OK.
  69438. */
  69439. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  69440. p->rc = SQLITE_OK;
  69441. }
  69442. /*
  69443. ** Copy the error code and error message belonging to the VDBE passed
  69444. ** as the first argument to its database handle (so that they will be
  69445. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  69446. **
  69447. ** This function does not clear the VDBE error code or message, just
  69448. ** copies them to the database handle.
  69449. */
  69450. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  69451. sqlite3 *db = p->db;
  69452. int rc = p->rc;
  69453. if( p->zErrMsg ){
  69454. db->bBenignMalloc++;
  69455. sqlite3BeginBenignMalloc();
  69456. if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
  69457. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  69458. sqlite3EndBenignMalloc();
  69459. db->bBenignMalloc--;
  69460. db->errCode = rc;
  69461. }else{
  69462. sqlite3Error(db, rc);
  69463. }
  69464. return rc;
  69465. }
  69466. #ifdef SQLITE_ENABLE_SQLLOG
  69467. /*
  69468. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  69469. ** invoke it.
  69470. */
  69471. static void vdbeInvokeSqllog(Vdbe *v){
  69472. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  69473. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  69474. assert( v->db->init.busy==0 );
  69475. if( zExpanded ){
  69476. sqlite3GlobalConfig.xSqllog(
  69477. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  69478. );
  69479. sqlite3DbFree(v->db, zExpanded);
  69480. }
  69481. }
  69482. }
  69483. #else
  69484. # define vdbeInvokeSqllog(x)
  69485. #endif
  69486. /*
  69487. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  69488. ** Write any error messages into *pzErrMsg. Return the result code.
  69489. **
  69490. ** After this routine is run, the VDBE should be ready to be executed
  69491. ** again.
  69492. **
  69493. ** To look at it another way, this routine resets the state of the
  69494. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  69495. ** VDBE_MAGIC_INIT.
  69496. */
  69497. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  69498. sqlite3 *db;
  69499. db = p->db;
  69500. /* If the VM did not run to completion or if it encountered an
  69501. ** error, then it might not have been halted properly. So halt
  69502. ** it now.
  69503. */
  69504. sqlite3VdbeHalt(p);
  69505. /* If the VDBE has be run even partially, then transfer the error code
  69506. ** and error message from the VDBE into the main database structure. But
  69507. ** if the VDBE has just been set to run but has not actually executed any
  69508. ** instructions yet, leave the main database error information unchanged.
  69509. */
  69510. if( p->pc>=0 ){
  69511. vdbeInvokeSqllog(p);
  69512. sqlite3VdbeTransferError(p);
  69513. sqlite3DbFree(db, p->zErrMsg);
  69514. p->zErrMsg = 0;
  69515. if( p->runOnlyOnce ) p->expired = 1;
  69516. }else if( p->rc && p->expired ){
  69517. /* The expired flag was set on the VDBE before the first call
  69518. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  69519. ** called), set the database error in this case as well.
  69520. */
  69521. sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
  69522. sqlite3DbFree(db, p->zErrMsg);
  69523. p->zErrMsg = 0;
  69524. }
  69525. /* Reclaim all memory used by the VDBE
  69526. */
  69527. Cleanup(p);
  69528. /* Save profiling information from this VDBE run.
  69529. */
  69530. #ifdef VDBE_PROFILE
  69531. {
  69532. FILE *out = fopen("vdbe_profile.out", "a");
  69533. if( out ){
  69534. int i;
  69535. fprintf(out, "---- ");
  69536. for(i=0; i<p->nOp; i++){
  69537. fprintf(out, "%02x", p->aOp[i].opcode);
  69538. }
  69539. fprintf(out, "\n");
  69540. if( p->zSql ){
  69541. char c, pc = 0;
  69542. fprintf(out, "-- ");
  69543. for(i=0; (c = p->zSql[i])!=0; i++){
  69544. if( pc=='\n' ) fprintf(out, "-- ");
  69545. putc(c, out);
  69546. pc = c;
  69547. }
  69548. if( pc!='\n' ) fprintf(out, "\n");
  69549. }
  69550. for(i=0; i<p->nOp; i++){
  69551. char zHdr[100];
  69552. sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
  69553. p->aOp[i].cnt,
  69554. p->aOp[i].cycles,
  69555. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  69556. );
  69557. fprintf(out, "%s", zHdr);
  69558. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  69559. }
  69560. fclose(out);
  69561. }
  69562. }
  69563. #endif
  69564. p->magic = VDBE_MAGIC_RESET;
  69565. return p->rc & db->errMask;
  69566. }
  69567. /*
  69568. ** Clean up and delete a VDBE after execution. Return an integer which is
  69569. ** the result code. Write any error message text into *pzErrMsg.
  69570. */
  69571. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  69572. int rc = SQLITE_OK;
  69573. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  69574. rc = sqlite3VdbeReset(p);
  69575. assert( (rc & p->db->errMask)==rc );
  69576. }
  69577. sqlite3VdbeDelete(p);
  69578. return rc;
  69579. }
  69580. /*
  69581. ** If parameter iOp is less than zero, then invoke the destructor for
  69582. ** all auxiliary data pointers currently cached by the VM passed as
  69583. ** the first argument.
  69584. **
  69585. ** Or, if iOp is greater than or equal to zero, then the destructor is
  69586. ** only invoked for those auxiliary data pointers created by the user
  69587. ** function invoked by the OP_Function opcode at instruction iOp of
  69588. ** VM pVdbe, and only then if:
  69589. **
  69590. ** * the associated function parameter is the 32nd or later (counting
  69591. ** from left to right), or
  69592. **
  69593. ** * the corresponding bit in argument mask is clear (where the first
  69594. ** function parameter corresponds to bit 0 etc.).
  69595. */
  69596. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
  69597. while( *pp ){
  69598. AuxData *pAux = *pp;
  69599. if( (iOp<0)
  69600. || (pAux->iAuxOp==iOp
  69601. && pAux->iAuxArg>=0
  69602. && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
  69603. ){
  69604. testcase( pAux->iAuxArg==31 );
  69605. if( pAux->xDeleteAux ){
  69606. pAux->xDeleteAux(pAux->pAux);
  69607. }
  69608. *pp = pAux->pNextAux;
  69609. sqlite3DbFree(db, pAux);
  69610. }else{
  69611. pp= &pAux->pNextAux;
  69612. }
  69613. }
  69614. }
  69615. /*
  69616. ** Free all memory associated with the Vdbe passed as the second argument,
  69617. ** except for object itself, which is preserved.
  69618. **
  69619. ** The difference between this function and sqlite3VdbeDelete() is that
  69620. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  69621. ** the database connection and frees the object itself.
  69622. */
  69623. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  69624. SubProgram *pSub, *pNext;
  69625. assert( p->db==0 || p->db==db );
  69626. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  69627. for(pSub=p->pProgram; pSub; pSub=pNext){
  69628. pNext = pSub->pNext;
  69629. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  69630. sqlite3DbFree(db, pSub);
  69631. }
  69632. if( p->magic!=VDBE_MAGIC_INIT ){
  69633. releaseMemArray(p->aVar, p->nVar);
  69634. sqlite3DbFree(db, p->pVList);
  69635. sqlite3DbFree(db, p->pFree);
  69636. }
  69637. vdbeFreeOpArray(db, p->aOp, p->nOp);
  69638. sqlite3DbFree(db, p->aColName);
  69639. sqlite3DbFree(db, p->zSql);
  69640. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  69641. {
  69642. int i;
  69643. for(i=0; i<p->nScan; i++){
  69644. sqlite3DbFree(db, p->aScan[i].zName);
  69645. }
  69646. sqlite3DbFree(db, p->aScan);
  69647. }
  69648. #endif
  69649. }
  69650. /*
  69651. ** Delete an entire VDBE.
  69652. */
  69653. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  69654. sqlite3 *db;
  69655. if( NEVER(p==0) ) return;
  69656. db = p->db;
  69657. assert( sqlite3_mutex_held(db->mutex) );
  69658. sqlite3VdbeClearObject(db, p);
  69659. if( p->pPrev ){
  69660. p->pPrev->pNext = p->pNext;
  69661. }else{
  69662. assert( db->pVdbe==p );
  69663. db->pVdbe = p->pNext;
  69664. }
  69665. if( p->pNext ){
  69666. p->pNext->pPrev = p->pPrev;
  69667. }
  69668. p->magic = VDBE_MAGIC_DEAD;
  69669. p->db = 0;
  69670. sqlite3DbFreeNN(db, p);
  69671. }
  69672. /*
  69673. ** The cursor "p" has a pending seek operation that has not yet been
  69674. ** carried out. Seek the cursor now. If an error occurs, return
  69675. ** the appropriate error code.
  69676. */
  69677. static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
  69678. int res, rc;
  69679. #ifdef SQLITE_TEST
  69680. extern int sqlite3_search_count;
  69681. #endif
  69682. assert( p->deferredMoveto );
  69683. assert( p->isTable );
  69684. assert( p->eCurType==CURTYPE_BTREE );
  69685. rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
  69686. if( rc ) return rc;
  69687. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  69688. #ifdef SQLITE_TEST
  69689. sqlite3_search_count++;
  69690. #endif
  69691. p->deferredMoveto = 0;
  69692. p->cacheStatus = CACHE_STALE;
  69693. return SQLITE_OK;
  69694. }
  69695. /*
  69696. ** Something has moved cursor "p" out of place. Maybe the row it was
  69697. ** pointed to was deleted out from under it. Or maybe the btree was
  69698. ** rebalanced. Whatever the cause, try to restore "p" to the place it
  69699. ** is supposed to be pointing. If the row was deleted out from under the
  69700. ** cursor, set the cursor to point to a NULL row.
  69701. */
  69702. static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
  69703. int isDifferentRow, rc;
  69704. assert( p->eCurType==CURTYPE_BTREE );
  69705. assert( p->uc.pCursor!=0 );
  69706. assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
  69707. rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
  69708. p->cacheStatus = CACHE_STALE;
  69709. if( isDifferentRow ) p->nullRow = 1;
  69710. return rc;
  69711. }
  69712. /*
  69713. ** Check to ensure that the cursor is valid. Restore the cursor
  69714. ** if need be. Return any I/O error from the restore operation.
  69715. */
  69716. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
  69717. assert( p->eCurType==CURTYPE_BTREE );
  69718. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  69719. return handleMovedCursor(p);
  69720. }
  69721. return SQLITE_OK;
  69722. }
  69723. /*
  69724. ** Make sure the cursor p is ready to read or write the row to which it
  69725. ** was last positioned. Return an error code if an OOM fault or I/O error
  69726. ** prevents us from positioning the cursor to its correct position.
  69727. **
  69728. ** If a MoveTo operation is pending on the given cursor, then do that
  69729. ** MoveTo now. If no move is pending, check to see if the row has been
  69730. ** deleted out from under the cursor and if it has, mark the row as
  69731. ** a NULL row.
  69732. **
  69733. ** If the cursor is already pointing to the correct row and that row has
  69734. ** not been deleted out from under the cursor, then this routine is a no-op.
  69735. */
  69736. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
  69737. VdbeCursor *p = *pp;
  69738. if( p->eCurType==CURTYPE_BTREE ){
  69739. if( p->deferredMoveto ){
  69740. int iMap;
  69741. if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
  69742. *pp = p->pAltCursor;
  69743. *piCol = iMap - 1;
  69744. return SQLITE_OK;
  69745. }
  69746. return handleDeferredMoveto(p);
  69747. }
  69748. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  69749. return handleMovedCursor(p);
  69750. }
  69751. }
  69752. return SQLITE_OK;
  69753. }
  69754. /*
  69755. ** The following functions:
  69756. **
  69757. ** sqlite3VdbeSerialType()
  69758. ** sqlite3VdbeSerialTypeLen()
  69759. ** sqlite3VdbeSerialLen()
  69760. ** sqlite3VdbeSerialPut()
  69761. ** sqlite3VdbeSerialGet()
  69762. **
  69763. ** encapsulate the code that serializes values for storage in SQLite
  69764. ** data and index records. Each serialized value consists of a
  69765. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  69766. ** integer, stored as a varint.
  69767. **
  69768. ** In an SQLite index record, the serial type is stored directly before
  69769. ** the blob of data that it corresponds to. In a table record, all serial
  69770. ** types are stored at the start of the record, and the blobs of data at
  69771. ** the end. Hence these functions allow the caller to handle the
  69772. ** serial-type and data blob separately.
  69773. **
  69774. ** The following table describes the various storage classes for data:
  69775. **
  69776. ** serial type bytes of data type
  69777. ** -------------- --------------- ---------------
  69778. ** 0 0 NULL
  69779. ** 1 1 signed integer
  69780. ** 2 2 signed integer
  69781. ** 3 3 signed integer
  69782. ** 4 4 signed integer
  69783. ** 5 6 signed integer
  69784. ** 6 8 signed integer
  69785. ** 7 8 IEEE float
  69786. ** 8 0 Integer constant 0
  69787. ** 9 0 Integer constant 1
  69788. ** 10,11 reserved for expansion
  69789. ** N>=12 and even (N-12)/2 BLOB
  69790. ** N>=13 and odd (N-13)/2 text
  69791. **
  69792. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  69793. ** of SQLite will not understand those serial types.
  69794. */
  69795. /*
  69796. ** Return the serial-type for the value stored in pMem.
  69797. */
  69798. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
  69799. int flags = pMem->flags;
  69800. u32 n;
  69801. assert( pLen!=0 );
  69802. if( flags&MEM_Null ){
  69803. *pLen = 0;
  69804. return 0;
  69805. }
  69806. if( flags&MEM_Int ){
  69807. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  69808. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  69809. i64 i = pMem->u.i;
  69810. u64 u;
  69811. if( i<0 ){
  69812. u = ~i;
  69813. }else{
  69814. u = i;
  69815. }
  69816. if( u<=127 ){
  69817. if( (i&1)==i && file_format>=4 ){
  69818. *pLen = 0;
  69819. return 8+(u32)u;
  69820. }else{
  69821. *pLen = 1;
  69822. return 1;
  69823. }
  69824. }
  69825. if( u<=32767 ){ *pLen = 2; return 2; }
  69826. if( u<=8388607 ){ *pLen = 3; return 3; }
  69827. if( u<=2147483647 ){ *pLen = 4; return 4; }
  69828. if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
  69829. *pLen = 8;
  69830. return 6;
  69831. }
  69832. if( flags&MEM_Real ){
  69833. *pLen = 8;
  69834. return 7;
  69835. }
  69836. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  69837. assert( pMem->n>=0 );
  69838. n = (u32)pMem->n;
  69839. if( flags & MEM_Zero ){
  69840. n += pMem->u.nZero;
  69841. }
  69842. *pLen = n;
  69843. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  69844. }
  69845. /*
  69846. ** The sizes for serial types less than 128
  69847. */
  69848. static const u8 sqlite3SmallTypeSizes[] = {
  69849. /* 0 1 2 3 4 5 6 7 8 9 */
  69850. /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
  69851. /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  69852. /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  69853. /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
  69854. /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
  69855. /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
  69856. /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
  69857. /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
  69858. /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
  69859. /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
  69860. /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
  69861. /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
  69862. /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
  69863. };
  69864. /*
  69865. ** Return the length of the data corresponding to the supplied serial-type.
  69866. */
  69867. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  69868. if( serial_type>=128 ){
  69869. return (serial_type-12)/2;
  69870. }else{
  69871. assert( serial_type<12
  69872. || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
  69873. return sqlite3SmallTypeSizes[serial_type];
  69874. }
  69875. }
  69876. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
  69877. assert( serial_type<128 );
  69878. return sqlite3SmallTypeSizes[serial_type];
  69879. }
  69880. /*
  69881. ** If we are on an architecture with mixed-endian floating
  69882. ** points (ex: ARM7) then swap the lower 4 bytes with the
  69883. ** upper 4 bytes. Return the result.
  69884. **
  69885. ** For most architectures, this is a no-op.
  69886. **
  69887. ** (later): It is reported to me that the mixed-endian problem
  69888. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  69889. ** that early versions of GCC stored the two words of a 64-bit
  69890. ** float in the wrong order. And that error has been propagated
  69891. ** ever since. The blame is not necessarily with GCC, though.
  69892. ** GCC might have just copying the problem from a prior compiler.
  69893. ** I am also told that newer versions of GCC that follow a different
  69894. ** ABI get the byte order right.
  69895. **
  69896. ** Developers using SQLite on an ARM7 should compile and run their
  69897. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  69898. ** enabled, some asserts below will ensure that the byte order of
  69899. ** floating point values is correct.
  69900. **
  69901. ** (2007-08-30) Frank van Vugt has studied this problem closely
  69902. ** and has send his findings to the SQLite developers. Frank
  69903. ** writes that some Linux kernels offer floating point hardware
  69904. ** emulation that uses only 32-bit mantissas instead of a full
  69905. ** 48-bits as required by the IEEE standard. (This is the
  69906. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  69907. ** byte swapping becomes very complicated. To avoid problems,
  69908. ** the necessary byte swapping is carried out using a 64-bit integer
  69909. ** rather than a 64-bit float. Frank assures us that the code here
  69910. ** works for him. We, the developers, have no way to independently
  69911. ** verify this, but Frank seems to know what he is talking about
  69912. ** so we trust him.
  69913. */
  69914. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  69915. static u64 floatSwap(u64 in){
  69916. union {
  69917. u64 r;
  69918. u32 i[2];
  69919. } u;
  69920. u32 t;
  69921. u.r = in;
  69922. t = u.i[0];
  69923. u.i[0] = u.i[1];
  69924. u.i[1] = t;
  69925. return u.r;
  69926. }
  69927. # define swapMixedEndianFloat(X) X = floatSwap(X)
  69928. #else
  69929. # define swapMixedEndianFloat(X)
  69930. #endif
  69931. /*
  69932. ** Write the serialized data blob for the value stored in pMem into
  69933. ** buf. It is assumed that the caller has allocated sufficient space.
  69934. ** Return the number of bytes written.
  69935. **
  69936. ** nBuf is the amount of space left in buf[]. The caller is responsible
  69937. ** for allocating enough space to buf[] to hold the entire field, exclusive
  69938. ** of the pMem->u.nZero bytes for a MEM_Zero value.
  69939. **
  69940. ** Return the number of bytes actually written into buf[]. The number
  69941. ** of bytes in the zero-filled tail is included in the return value only
  69942. ** if those bytes were zeroed in buf[].
  69943. */
  69944. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
  69945. u32 len;
  69946. /* Integer and Real */
  69947. if( serial_type<=7 && serial_type>0 ){
  69948. u64 v;
  69949. u32 i;
  69950. if( serial_type==7 ){
  69951. assert( sizeof(v)==sizeof(pMem->u.r) );
  69952. memcpy(&v, &pMem->u.r, sizeof(v));
  69953. swapMixedEndianFloat(v);
  69954. }else{
  69955. v = pMem->u.i;
  69956. }
  69957. len = i = sqlite3SmallTypeSizes[serial_type];
  69958. assert( i>0 );
  69959. do{
  69960. buf[--i] = (u8)(v&0xFF);
  69961. v >>= 8;
  69962. }while( i );
  69963. return len;
  69964. }
  69965. /* String or blob */
  69966. if( serial_type>=12 ){
  69967. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  69968. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  69969. len = pMem->n;
  69970. if( len>0 ) memcpy(buf, pMem->z, len);
  69971. return len;
  69972. }
  69973. /* NULL or constants 0 or 1 */
  69974. return 0;
  69975. }
  69976. /* Input "x" is a sequence of unsigned characters that represent a
  69977. ** big-endian integer. Return the equivalent native integer
  69978. */
  69979. #define ONE_BYTE_INT(x) ((i8)(x)[0])
  69980. #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
  69981. #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
  69982. #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  69983. #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  69984. /*
  69985. ** Deserialize the data blob pointed to by buf as serial type serial_type
  69986. ** and store the result in pMem. Return the number of bytes read.
  69987. **
  69988. ** This function is implemented as two separate routines for performance.
  69989. ** The few cases that require local variables are broken out into a separate
  69990. ** routine so that in most cases the overhead of moving the stack pointer
  69991. ** is avoided.
  69992. */
  69993. static u32 SQLITE_NOINLINE serialGet(
  69994. const unsigned char *buf, /* Buffer to deserialize from */
  69995. u32 serial_type, /* Serial type to deserialize */
  69996. Mem *pMem /* Memory cell to write value into */
  69997. ){
  69998. u64 x = FOUR_BYTE_UINT(buf);
  69999. u32 y = FOUR_BYTE_UINT(buf+4);
  70000. x = (x<<32) + y;
  70001. if( serial_type==6 ){
  70002. /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
  70003. ** twos-complement integer. */
  70004. pMem->u.i = *(i64*)&x;
  70005. pMem->flags = MEM_Int;
  70006. testcase( pMem->u.i<0 );
  70007. }else{
  70008. /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
  70009. ** floating point number. */
  70010. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  70011. /* Verify that integers and floating point values use the same
  70012. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  70013. ** defined that 64-bit floating point values really are mixed
  70014. ** endian.
  70015. */
  70016. static const u64 t1 = ((u64)0x3ff00000)<<32;
  70017. static const double r1 = 1.0;
  70018. u64 t2 = t1;
  70019. swapMixedEndianFloat(t2);
  70020. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  70021. #endif
  70022. assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
  70023. swapMixedEndianFloat(x);
  70024. memcpy(&pMem->u.r, &x, sizeof(x));
  70025. pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
  70026. }
  70027. return 8;
  70028. }
  70029. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  70030. const unsigned char *buf, /* Buffer to deserialize from */
  70031. u32 serial_type, /* Serial type to deserialize */
  70032. Mem *pMem /* Memory cell to write value into */
  70033. ){
  70034. switch( serial_type ){
  70035. case 10: /* Reserved for future use */
  70036. case 11: /* Reserved for future use */
  70037. case 0: { /* Null */
  70038. /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
  70039. pMem->flags = MEM_Null;
  70040. break;
  70041. }
  70042. case 1: {
  70043. /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
  70044. ** integer. */
  70045. pMem->u.i = ONE_BYTE_INT(buf);
  70046. pMem->flags = MEM_Int;
  70047. testcase( pMem->u.i<0 );
  70048. return 1;
  70049. }
  70050. case 2: { /* 2-byte signed integer */
  70051. /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
  70052. ** twos-complement integer. */
  70053. pMem->u.i = TWO_BYTE_INT(buf);
  70054. pMem->flags = MEM_Int;
  70055. testcase( pMem->u.i<0 );
  70056. return 2;
  70057. }
  70058. case 3: { /* 3-byte signed integer */
  70059. /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
  70060. ** twos-complement integer. */
  70061. pMem->u.i = THREE_BYTE_INT(buf);
  70062. pMem->flags = MEM_Int;
  70063. testcase( pMem->u.i<0 );
  70064. return 3;
  70065. }
  70066. case 4: { /* 4-byte signed integer */
  70067. /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
  70068. ** twos-complement integer. */
  70069. pMem->u.i = FOUR_BYTE_INT(buf);
  70070. #ifdef __HP_cc
  70071. /* Work around a sign-extension bug in the HP compiler for HP/UX */
  70072. if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
  70073. #endif
  70074. pMem->flags = MEM_Int;
  70075. testcase( pMem->u.i<0 );
  70076. return 4;
  70077. }
  70078. case 5: { /* 6-byte signed integer */
  70079. /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
  70080. ** twos-complement integer. */
  70081. pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
  70082. pMem->flags = MEM_Int;
  70083. testcase( pMem->u.i<0 );
  70084. return 6;
  70085. }
  70086. case 6: /* 8-byte signed integer */
  70087. case 7: { /* IEEE floating point */
  70088. /* These use local variables, so do them in a separate routine
  70089. ** to avoid having to move the frame pointer in the common case */
  70090. return serialGet(buf,serial_type,pMem);
  70091. }
  70092. case 8: /* Integer 0 */
  70093. case 9: { /* Integer 1 */
  70094. /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
  70095. /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
  70096. pMem->u.i = serial_type-8;
  70097. pMem->flags = MEM_Int;
  70098. return 0;
  70099. }
  70100. default: {
  70101. /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
  70102. ** length.
  70103. ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
  70104. ** (N-13)/2 bytes in length. */
  70105. static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
  70106. pMem->z = (char *)buf;
  70107. pMem->n = (serial_type-12)/2;
  70108. pMem->flags = aFlag[serial_type&1];
  70109. return pMem->n;
  70110. }
  70111. }
  70112. return 0;
  70113. }
  70114. /*
  70115. ** This routine is used to allocate sufficient space for an UnpackedRecord
  70116. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  70117. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  70118. **
  70119. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  70120. ** the unaligned buffer passed via the second and third arguments (presumably
  70121. ** stack space). If the former, then *ppFree is set to a pointer that should
  70122. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  70123. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  70124. ** before returning.
  70125. **
  70126. ** If an OOM error occurs, NULL is returned.
  70127. */
  70128. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  70129. KeyInfo *pKeyInfo /* Description of the record */
  70130. ){
  70131. UnpackedRecord *p; /* Unpacked record to return */
  70132. int nByte; /* Number of bytes required for *p */
  70133. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  70134. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  70135. if( !p ) return 0;
  70136. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  70137. assert( pKeyInfo->aSortOrder!=0 );
  70138. p->pKeyInfo = pKeyInfo;
  70139. p->nField = pKeyInfo->nField + 1;
  70140. return p;
  70141. }
  70142. /*
  70143. ** Given the nKey-byte encoding of a record in pKey[], populate the
  70144. ** UnpackedRecord structure indicated by the fourth argument with the
  70145. ** contents of the decoded record.
  70146. */
  70147. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  70148. KeyInfo *pKeyInfo, /* Information about the record format */
  70149. int nKey, /* Size of the binary record */
  70150. const void *pKey, /* The binary record */
  70151. UnpackedRecord *p /* Populate this structure before returning. */
  70152. ){
  70153. const unsigned char *aKey = (const unsigned char *)pKey;
  70154. int d;
  70155. u32 idx; /* Offset in aKey[] to read from */
  70156. u16 u; /* Unsigned loop counter */
  70157. u32 szHdr;
  70158. Mem *pMem = p->aMem;
  70159. p->default_rc = 0;
  70160. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  70161. idx = getVarint32(aKey, szHdr);
  70162. d = szHdr;
  70163. u = 0;
  70164. while( idx<szHdr && d<=nKey ){
  70165. u32 serial_type;
  70166. idx += getVarint32(&aKey[idx], serial_type);
  70167. pMem->enc = pKeyInfo->enc;
  70168. pMem->db = pKeyInfo->db;
  70169. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  70170. pMem->szMalloc = 0;
  70171. pMem->z = 0;
  70172. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  70173. pMem++;
  70174. if( (++u)>=p->nField ) break;
  70175. }
  70176. assert( u<=pKeyInfo->nField + 1 );
  70177. p->nField = u;
  70178. }
  70179. #ifdef SQLITE_DEBUG
  70180. /*
  70181. ** This function compares two index or table record keys in the same way
  70182. ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
  70183. ** this function deserializes and compares values using the
  70184. ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
  70185. ** in assert() statements to ensure that the optimized code in
  70186. ** sqlite3VdbeRecordCompare() returns results with these two primitives.
  70187. **
  70188. ** Return true if the result of comparison is equivalent to desiredResult.
  70189. ** Return false if there is a disagreement.
  70190. */
  70191. static int vdbeRecordCompareDebug(
  70192. int nKey1, const void *pKey1, /* Left key */
  70193. const UnpackedRecord *pPKey2, /* Right key */
  70194. int desiredResult /* Correct answer */
  70195. ){
  70196. u32 d1; /* Offset into aKey[] of next data element */
  70197. u32 idx1; /* Offset into aKey[] of next header element */
  70198. u32 szHdr1; /* Number of bytes in header */
  70199. int i = 0;
  70200. int rc = 0;
  70201. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  70202. KeyInfo *pKeyInfo;
  70203. Mem mem1;
  70204. pKeyInfo = pPKey2->pKeyInfo;
  70205. if( pKeyInfo->db==0 ) return 1;
  70206. mem1.enc = pKeyInfo->enc;
  70207. mem1.db = pKeyInfo->db;
  70208. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  70209. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  70210. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  70211. ** We could initialize it, as shown here, to silence those complaints.
  70212. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  70213. ** the unnecessary initialization has a measurable negative performance
  70214. ** impact, since this routine is a very high runner. And so, we choose
  70215. ** to ignore the compiler warnings and leave this variable uninitialized.
  70216. */
  70217. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  70218. idx1 = getVarint32(aKey1, szHdr1);
  70219. if( szHdr1>98307 ) return SQLITE_CORRUPT;
  70220. d1 = szHdr1;
  70221. assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
  70222. assert( pKeyInfo->aSortOrder!=0 );
  70223. assert( pKeyInfo->nField>0 );
  70224. assert( idx1<=szHdr1 || CORRUPT_DB );
  70225. do{
  70226. u32 serial_type1;
  70227. /* Read the serial types for the next element in each key. */
  70228. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  70229. /* Verify that there is enough key space remaining to avoid
  70230. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  70231. ** always be greater than or equal to the amount of required key space.
  70232. ** Use that approximation to avoid the more expensive call to
  70233. ** sqlite3VdbeSerialTypeLen() in the common case.
  70234. */
  70235. if( d1+serial_type1+2>(u32)nKey1
  70236. && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
  70237. ){
  70238. break;
  70239. }
  70240. /* Extract the values to be compared.
  70241. */
  70242. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  70243. /* Do the comparison
  70244. */
  70245. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  70246. if( rc!=0 ){
  70247. assert( mem1.szMalloc==0 ); /* See comment below */
  70248. if( pKeyInfo->aSortOrder[i] ){
  70249. rc = -rc; /* Invert the result for DESC sort order. */
  70250. }
  70251. goto debugCompareEnd;
  70252. }
  70253. i++;
  70254. }while( idx1<szHdr1 && i<pPKey2->nField );
  70255. /* No memory allocation is ever used on mem1. Prove this using
  70256. ** the following assert(). If the assert() fails, it indicates a
  70257. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  70258. */
  70259. assert( mem1.szMalloc==0 );
  70260. /* rc==0 here means that one of the keys ran out of fields and
  70261. ** all the fields up to that point were equal. Return the default_rc
  70262. ** value. */
  70263. rc = pPKey2->default_rc;
  70264. debugCompareEnd:
  70265. if( desiredResult==0 && rc==0 ) return 1;
  70266. if( desiredResult<0 && rc<0 ) return 1;
  70267. if( desiredResult>0 && rc>0 ) return 1;
  70268. if( CORRUPT_DB ) return 1;
  70269. if( pKeyInfo->db->mallocFailed ) return 1;
  70270. return 0;
  70271. }
  70272. #endif
  70273. #ifdef SQLITE_DEBUG
  70274. /*
  70275. ** Count the number of fields (a.k.a. columns) in the record given by
  70276. ** pKey,nKey. The verify that this count is less than or equal to the
  70277. ** limit given by pKeyInfo->nField + pKeyInfo->nXField.
  70278. **
  70279. ** If this constraint is not satisfied, it means that the high-speed
  70280. ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
  70281. ** not work correctly. If this assert() ever fires, it probably means
  70282. ** that the KeyInfo.nField or KeyInfo.nXField values were computed
  70283. ** incorrectly.
  70284. */
  70285. static void vdbeAssertFieldCountWithinLimits(
  70286. int nKey, const void *pKey, /* The record to verify */
  70287. const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
  70288. ){
  70289. int nField = 0;
  70290. u32 szHdr;
  70291. u32 idx;
  70292. u32 notUsed;
  70293. const unsigned char *aKey = (const unsigned char*)pKey;
  70294. if( CORRUPT_DB ) return;
  70295. idx = getVarint32(aKey, szHdr);
  70296. assert( nKey>=0 );
  70297. assert( szHdr<=(u32)nKey );
  70298. while( idx<szHdr ){
  70299. idx += getVarint32(aKey+idx, notUsed);
  70300. nField++;
  70301. }
  70302. assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
  70303. }
  70304. #else
  70305. # define vdbeAssertFieldCountWithinLimits(A,B,C)
  70306. #endif
  70307. /*
  70308. ** Both *pMem1 and *pMem2 contain string values. Compare the two values
  70309. ** using the collation sequence pColl. As usual, return a negative , zero
  70310. ** or positive value if *pMem1 is less than, equal to or greater than
  70311. ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
  70312. */
  70313. static int vdbeCompareMemString(
  70314. const Mem *pMem1,
  70315. const Mem *pMem2,
  70316. const CollSeq *pColl,
  70317. u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
  70318. ){
  70319. if( pMem1->enc==pColl->enc ){
  70320. /* The strings are already in the correct encoding. Call the
  70321. ** comparison function directly */
  70322. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  70323. }else{
  70324. int rc;
  70325. const void *v1, *v2;
  70326. int n1, n2;
  70327. Mem c1;
  70328. Mem c2;
  70329. sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
  70330. sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
  70331. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  70332. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  70333. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  70334. n1 = v1==0 ? 0 : c1.n;
  70335. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  70336. n2 = v2==0 ? 0 : c2.n;
  70337. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  70338. if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
  70339. sqlite3VdbeMemRelease(&c1);
  70340. sqlite3VdbeMemRelease(&c2);
  70341. return rc;
  70342. }
  70343. }
  70344. /*
  70345. ** The input pBlob is guaranteed to be a Blob that is not marked
  70346. ** with MEM_Zero. Return true if it could be a zero-blob.
  70347. */
  70348. static int isAllZero(const char *z, int n){
  70349. int i;
  70350. for(i=0; i<n; i++){
  70351. if( z[i] ) return 0;
  70352. }
  70353. return 1;
  70354. }
  70355. /*
  70356. ** Compare two blobs. Return negative, zero, or positive if the first
  70357. ** is less than, equal to, or greater than the second, respectively.
  70358. ** If one blob is a prefix of the other, then the shorter is the lessor.
  70359. */
  70360. static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
  70361. int c;
  70362. int n1 = pB1->n;
  70363. int n2 = pB2->n;
  70364. /* It is possible to have a Blob value that has some non-zero content
  70365. ** followed by zero content. But that only comes up for Blobs formed
  70366. ** by the OP_MakeRecord opcode, and such Blobs never get passed into
  70367. ** sqlite3MemCompare(). */
  70368. assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
  70369. assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
  70370. if( (pB1->flags|pB2->flags) & MEM_Zero ){
  70371. if( pB1->flags & pB2->flags & MEM_Zero ){
  70372. return pB1->u.nZero - pB2->u.nZero;
  70373. }else if( pB1->flags & MEM_Zero ){
  70374. if( !isAllZero(pB2->z, pB2->n) ) return -1;
  70375. return pB1->u.nZero - n2;
  70376. }else{
  70377. if( !isAllZero(pB1->z, pB1->n) ) return +1;
  70378. return n1 - pB2->u.nZero;
  70379. }
  70380. }
  70381. c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
  70382. if( c ) return c;
  70383. return n1 - n2;
  70384. }
  70385. /*
  70386. ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
  70387. ** number. Return negative, zero, or positive if the first (i64) is less than,
  70388. ** equal to, or greater than the second (double).
  70389. */
  70390. static int sqlite3IntFloatCompare(i64 i, double r){
  70391. if( sizeof(LONGDOUBLE_TYPE)>8 ){
  70392. LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
  70393. if( x<r ) return -1;
  70394. if( x>r ) return +1;
  70395. return 0;
  70396. }else{
  70397. i64 y;
  70398. double s;
  70399. if( r<-9223372036854775808.0 ) return +1;
  70400. if( r>9223372036854775807.0 ) return -1;
  70401. y = (i64)r;
  70402. if( i<y ) return -1;
  70403. if( i>y ){
  70404. if( y==SMALLEST_INT64 && r>0.0 ) return -1;
  70405. return +1;
  70406. }
  70407. s = (double)i;
  70408. if( s<r ) return -1;
  70409. if( s>r ) return +1;
  70410. return 0;
  70411. }
  70412. }
  70413. /*
  70414. ** Compare the values contained by the two memory cells, returning
  70415. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  70416. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  70417. ** and reals) sorted numerically, followed by text ordered by the collating
  70418. ** sequence pColl and finally blob's ordered by memcmp().
  70419. **
  70420. ** Two NULL values are considered equal by this function.
  70421. */
  70422. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  70423. int f1, f2;
  70424. int combined_flags;
  70425. f1 = pMem1->flags;
  70426. f2 = pMem2->flags;
  70427. combined_flags = f1|f2;
  70428. assert( (combined_flags & MEM_RowSet)==0 );
  70429. /* If one value is NULL, it is less than the other. If both values
  70430. ** are NULL, return 0.
  70431. */
  70432. if( combined_flags&MEM_Null ){
  70433. return (f2&MEM_Null) - (f1&MEM_Null);
  70434. }
  70435. /* At least one of the two values is a number
  70436. */
  70437. if( combined_flags&(MEM_Int|MEM_Real) ){
  70438. if( (f1 & f2 & MEM_Int)!=0 ){
  70439. if( pMem1->u.i < pMem2->u.i ) return -1;
  70440. if( pMem1->u.i > pMem2->u.i ) return +1;
  70441. return 0;
  70442. }
  70443. if( (f1 & f2 & MEM_Real)!=0 ){
  70444. if( pMem1->u.r < pMem2->u.r ) return -1;
  70445. if( pMem1->u.r > pMem2->u.r ) return +1;
  70446. return 0;
  70447. }
  70448. if( (f1&MEM_Int)!=0 ){
  70449. if( (f2&MEM_Real)!=0 ){
  70450. return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
  70451. }else{
  70452. return -1;
  70453. }
  70454. }
  70455. if( (f1&MEM_Real)!=0 ){
  70456. if( (f2&MEM_Int)!=0 ){
  70457. return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
  70458. }else{
  70459. return -1;
  70460. }
  70461. }
  70462. return +1;
  70463. }
  70464. /* If one value is a string and the other is a blob, the string is less.
  70465. ** If both are strings, compare using the collating functions.
  70466. */
  70467. if( combined_flags&MEM_Str ){
  70468. if( (f1 & MEM_Str)==0 ){
  70469. return 1;
  70470. }
  70471. if( (f2 & MEM_Str)==0 ){
  70472. return -1;
  70473. }
  70474. assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
  70475. assert( pMem1->enc==SQLITE_UTF8 ||
  70476. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  70477. /* The collation sequence must be defined at this point, even if
  70478. ** the user deletes the collation sequence after the vdbe program is
  70479. ** compiled (this was not always the case).
  70480. */
  70481. assert( !pColl || pColl->xCmp );
  70482. if( pColl ){
  70483. return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
  70484. }
  70485. /* If a NULL pointer was passed as the collate function, fall through
  70486. ** to the blob case and use memcmp(). */
  70487. }
  70488. /* Both values must be blobs. Compare using memcmp(). */
  70489. return sqlite3BlobCompare(pMem1, pMem2);
  70490. }
  70491. /*
  70492. ** The first argument passed to this function is a serial-type that
  70493. ** corresponds to an integer - all values between 1 and 9 inclusive
  70494. ** except 7. The second points to a buffer containing an integer value
  70495. ** serialized according to serial_type. This function deserializes
  70496. ** and returns the value.
  70497. */
  70498. static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
  70499. u32 y;
  70500. assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
  70501. switch( serial_type ){
  70502. case 0:
  70503. case 1:
  70504. testcase( aKey[0]&0x80 );
  70505. return ONE_BYTE_INT(aKey);
  70506. case 2:
  70507. testcase( aKey[0]&0x80 );
  70508. return TWO_BYTE_INT(aKey);
  70509. case 3:
  70510. testcase( aKey[0]&0x80 );
  70511. return THREE_BYTE_INT(aKey);
  70512. case 4: {
  70513. testcase( aKey[0]&0x80 );
  70514. y = FOUR_BYTE_UINT(aKey);
  70515. return (i64)*(int*)&y;
  70516. }
  70517. case 5: {
  70518. testcase( aKey[0]&0x80 );
  70519. return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  70520. }
  70521. case 6: {
  70522. u64 x = FOUR_BYTE_UINT(aKey);
  70523. testcase( aKey[0]&0x80 );
  70524. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  70525. return (i64)*(i64*)&x;
  70526. }
  70527. }
  70528. return (serial_type - 8);
  70529. }
  70530. /*
  70531. ** This function compares the two table rows or index records
  70532. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  70533. ** or positive integer if key1 is less than, equal to or
  70534. ** greater than key2. The {nKey1, pKey1} key must be a blob
  70535. ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
  70536. ** key must be a parsed key such as obtained from
  70537. ** sqlite3VdbeParseRecord.
  70538. **
  70539. ** If argument bSkip is non-zero, it is assumed that the caller has already
  70540. ** determined that the first fields of the keys are equal.
  70541. **
  70542. ** Key1 and Key2 do not have to contain the same number of fields. If all
  70543. ** fields that appear in both keys are equal, then pPKey2->default_rc is
  70544. ** returned.
  70545. **
  70546. ** If database corruption is discovered, set pPKey2->errCode to
  70547. ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
  70548. ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
  70549. ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
  70550. */
  70551. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
  70552. int nKey1, const void *pKey1, /* Left key */
  70553. UnpackedRecord *pPKey2, /* Right key */
  70554. int bSkip /* If true, skip the first field */
  70555. ){
  70556. u32 d1; /* Offset into aKey[] of next data element */
  70557. int i; /* Index of next field to compare */
  70558. u32 szHdr1; /* Size of record header in bytes */
  70559. u32 idx1; /* Offset of first type in header */
  70560. int rc = 0; /* Return value */
  70561. Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
  70562. KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
  70563. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  70564. Mem mem1;
  70565. /* If bSkip is true, then the caller has already determined that the first
  70566. ** two elements in the keys are equal. Fix the various stack variables so
  70567. ** that this routine begins comparing at the second field. */
  70568. if( bSkip ){
  70569. u32 s1;
  70570. idx1 = 1 + getVarint32(&aKey1[1], s1);
  70571. szHdr1 = aKey1[0];
  70572. d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
  70573. i = 1;
  70574. pRhs++;
  70575. }else{
  70576. idx1 = getVarint32(aKey1, szHdr1);
  70577. d1 = szHdr1;
  70578. if( d1>(unsigned)nKey1 ){
  70579. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  70580. return 0; /* Corruption */
  70581. }
  70582. i = 0;
  70583. }
  70584. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  70585. assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
  70586. || CORRUPT_DB );
  70587. assert( pPKey2->pKeyInfo->aSortOrder!=0 );
  70588. assert( pPKey2->pKeyInfo->nField>0 );
  70589. assert( idx1<=szHdr1 || CORRUPT_DB );
  70590. do{
  70591. u32 serial_type;
  70592. /* RHS is an integer */
  70593. if( pRhs->flags & MEM_Int ){
  70594. serial_type = aKey1[idx1];
  70595. testcase( serial_type==12 );
  70596. if( serial_type>=10 ){
  70597. rc = +1;
  70598. }else if( serial_type==0 ){
  70599. rc = -1;
  70600. }else if( serial_type==7 ){
  70601. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  70602. rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
  70603. }else{
  70604. i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
  70605. i64 rhs = pRhs->u.i;
  70606. if( lhs<rhs ){
  70607. rc = -1;
  70608. }else if( lhs>rhs ){
  70609. rc = +1;
  70610. }
  70611. }
  70612. }
  70613. /* RHS is real */
  70614. else if( pRhs->flags & MEM_Real ){
  70615. serial_type = aKey1[idx1];
  70616. if( serial_type>=10 ){
  70617. /* Serial types 12 or greater are strings and blobs (greater than
  70618. ** numbers). Types 10 and 11 are currently "reserved for future
  70619. ** use", so it doesn't really matter what the results of comparing
  70620. ** them to numberic values are. */
  70621. rc = +1;
  70622. }else if( serial_type==0 ){
  70623. rc = -1;
  70624. }else{
  70625. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  70626. if( serial_type==7 ){
  70627. if( mem1.u.r<pRhs->u.r ){
  70628. rc = -1;
  70629. }else if( mem1.u.r>pRhs->u.r ){
  70630. rc = +1;
  70631. }
  70632. }else{
  70633. rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
  70634. }
  70635. }
  70636. }
  70637. /* RHS is a string */
  70638. else if( pRhs->flags & MEM_Str ){
  70639. getVarint32(&aKey1[idx1], serial_type);
  70640. testcase( serial_type==12 );
  70641. if( serial_type<12 ){
  70642. rc = -1;
  70643. }else if( !(serial_type & 0x01) ){
  70644. rc = +1;
  70645. }else{
  70646. mem1.n = (serial_type - 12) / 2;
  70647. testcase( (d1+mem1.n)==(unsigned)nKey1 );
  70648. testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
  70649. if( (d1+mem1.n) > (unsigned)nKey1 ){
  70650. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  70651. return 0; /* Corruption */
  70652. }else if( pKeyInfo->aColl[i] ){
  70653. mem1.enc = pKeyInfo->enc;
  70654. mem1.db = pKeyInfo->db;
  70655. mem1.flags = MEM_Str;
  70656. mem1.z = (char*)&aKey1[d1];
  70657. rc = vdbeCompareMemString(
  70658. &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
  70659. );
  70660. }else{
  70661. int nCmp = MIN(mem1.n, pRhs->n);
  70662. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  70663. if( rc==0 ) rc = mem1.n - pRhs->n;
  70664. }
  70665. }
  70666. }
  70667. /* RHS is a blob */
  70668. else if( pRhs->flags & MEM_Blob ){
  70669. assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
  70670. getVarint32(&aKey1[idx1], serial_type);
  70671. testcase( serial_type==12 );
  70672. if( serial_type<12 || (serial_type & 0x01) ){
  70673. rc = -1;
  70674. }else{
  70675. int nStr = (serial_type - 12) / 2;
  70676. testcase( (d1+nStr)==(unsigned)nKey1 );
  70677. testcase( (d1+nStr+1)==(unsigned)nKey1 );
  70678. if( (d1+nStr) > (unsigned)nKey1 ){
  70679. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  70680. return 0; /* Corruption */
  70681. }else if( pRhs->flags & MEM_Zero ){
  70682. if( !isAllZero((const char*)&aKey1[d1],nStr) ){
  70683. rc = 1;
  70684. }else{
  70685. rc = nStr - pRhs->u.nZero;
  70686. }
  70687. }else{
  70688. int nCmp = MIN(nStr, pRhs->n);
  70689. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  70690. if( rc==0 ) rc = nStr - pRhs->n;
  70691. }
  70692. }
  70693. }
  70694. /* RHS is null */
  70695. else{
  70696. serial_type = aKey1[idx1];
  70697. rc = (serial_type!=0);
  70698. }
  70699. if( rc!=0 ){
  70700. if( pKeyInfo->aSortOrder[i] ){
  70701. rc = -rc;
  70702. }
  70703. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
  70704. assert( mem1.szMalloc==0 ); /* See comment below */
  70705. return rc;
  70706. }
  70707. i++;
  70708. pRhs++;
  70709. d1 += sqlite3VdbeSerialTypeLen(serial_type);
  70710. idx1 += sqlite3VarintLen(serial_type);
  70711. }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
  70712. /* No memory allocation is ever used on mem1. Prove this using
  70713. ** the following assert(). If the assert() fails, it indicates a
  70714. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
  70715. assert( mem1.szMalloc==0 );
  70716. /* rc==0 here means that one or both of the keys ran out of fields and
  70717. ** all the fields up to that point were equal. Return the default_rc
  70718. ** value. */
  70719. assert( CORRUPT_DB
  70720. || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
  70721. || pKeyInfo->db->mallocFailed
  70722. );
  70723. pPKey2->eqSeen = 1;
  70724. return pPKey2->default_rc;
  70725. }
  70726. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  70727. int nKey1, const void *pKey1, /* Left key */
  70728. UnpackedRecord *pPKey2 /* Right key */
  70729. ){
  70730. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
  70731. }
  70732. /*
  70733. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  70734. ** that (a) the first field of pPKey2 is an integer, and (b) the
  70735. ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
  70736. ** byte (i.e. is less than 128).
  70737. **
  70738. ** To avoid concerns about buffer overreads, this routine is only used
  70739. ** on schemas where the maximum valid header size is 63 bytes or less.
  70740. */
  70741. static int vdbeRecordCompareInt(
  70742. int nKey1, const void *pKey1, /* Left key */
  70743. UnpackedRecord *pPKey2 /* Right key */
  70744. ){
  70745. const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
  70746. int serial_type = ((const u8*)pKey1)[1];
  70747. int res;
  70748. u32 y;
  70749. u64 x;
  70750. i64 v;
  70751. i64 lhs;
  70752. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  70753. assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
  70754. switch( serial_type ){
  70755. case 1: { /* 1-byte signed integer */
  70756. lhs = ONE_BYTE_INT(aKey);
  70757. testcase( lhs<0 );
  70758. break;
  70759. }
  70760. case 2: { /* 2-byte signed integer */
  70761. lhs = TWO_BYTE_INT(aKey);
  70762. testcase( lhs<0 );
  70763. break;
  70764. }
  70765. case 3: { /* 3-byte signed integer */
  70766. lhs = THREE_BYTE_INT(aKey);
  70767. testcase( lhs<0 );
  70768. break;
  70769. }
  70770. case 4: { /* 4-byte signed integer */
  70771. y = FOUR_BYTE_UINT(aKey);
  70772. lhs = (i64)*(int*)&y;
  70773. testcase( lhs<0 );
  70774. break;
  70775. }
  70776. case 5: { /* 6-byte signed integer */
  70777. lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  70778. testcase( lhs<0 );
  70779. break;
  70780. }
  70781. case 6: { /* 8-byte signed integer */
  70782. x = FOUR_BYTE_UINT(aKey);
  70783. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  70784. lhs = *(i64*)&x;
  70785. testcase( lhs<0 );
  70786. break;
  70787. }
  70788. case 8:
  70789. lhs = 0;
  70790. break;
  70791. case 9:
  70792. lhs = 1;
  70793. break;
  70794. /* This case could be removed without changing the results of running
  70795. ** this code. Including it causes gcc to generate a faster switch
  70796. ** statement (since the range of switch targets now starts at zero and
  70797. ** is contiguous) but does not cause any duplicate code to be generated
  70798. ** (as gcc is clever enough to combine the two like cases). Other
  70799. ** compilers might be similar. */
  70800. case 0: case 7:
  70801. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  70802. default:
  70803. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  70804. }
  70805. v = pPKey2->aMem[0].u.i;
  70806. if( v>lhs ){
  70807. res = pPKey2->r1;
  70808. }else if( v<lhs ){
  70809. res = pPKey2->r2;
  70810. }else if( pPKey2->nField>1 ){
  70811. /* The first fields of the two keys are equal. Compare the trailing
  70812. ** fields. */
  70813. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  70814. }else{
  70815. /* The first fields of the two keys are equal and there are no trailing
  70816. ** fields. Return pPKey2->default_rc in this case. */
  70817. res = pPKey2->default_rc;
  70818. pPKey2->eqSeen = 1;
  70819. }
  70820. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
  70821. return res;
  70822. }
  70823. /*
  70824. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  70825. ** that (a) the first field of pPKey2 is a string, that (b) the first field
  70826. ** uses the collation sequence BINARY and (c) that the size-of-header varint
  70827. ** at the start of (pKey1/nKey1) fits in a single byte.
  70828. */
  70829. static int vdbeRecordCompareString(
  70830. int nKey1, const void *pKey1, /* Left key */
  70831. UnpackedRecord *pPKey2 /* Right key */
  70832. ){
  70833. const u8 *aKey1 = (const u8*)pKey1;
  70834. int serial_type;
  70835. int res;
  70836. assert( pPKey2->aMem[0].flags & MEM_Str );
  70837. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  70838. getVarint32(&aKey1[1], serial_type);
  70839. if( serial_type<12 ){
  70840. res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
  70841. }else if( !(serial_type & 0x01) ){
  70842. res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
  70843. }else{
  70844. int nCmp;
  70845. int nStr;
  70846. int szHdr = aKey1[0];
  70847. nStr = (serial_type-12) / 2;
  70848. if( (szHdr + nStr) > nKey1 ){
  70849. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  70850. return 0; /* Corruption */
  70851. }
  70852. nCmp = MIN( pPKey2->aMem[0].n, nStr );
  70853. res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
  70854. if( res==0 ){
  70855. res = nStr - pPKey2->aMem[0].n;
  70856. if( res==0 ){
  70857. if( pPKey2->nField>1 ){
  70858. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  70859. }else{
  70860. res = pPKey2->default_rc;
  70861. pPKey2->eqSeen = 1;
  70862. }
  70863. }else if( res>0 ){
  70864. res = pPKey2->r2;
  70865. }else{
  70866. res = pPKey2->r1;
  70867. }
  70868. }else if( res>0 ){
  70869. res = pPKey2->r2;
  70870. }else{
  70871. res = pPKey2->r1;
  70872. }
  70873. }
  70874. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
  70875. || CORRUPT_DB
  70876. || pPKey2->pKeyInfo->db->mallocFailed
  70877. );
  70878. return res;
  70879. }
  70880. /*
  70881. ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
  70882. ** suitable for comparing serialized records to the unpacked record passed
  70883. ** as the only argument.
  70884. */
  70885. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
  70886. /* varintRecordCompareInt() and varintRecordCompareString() both assume
  70887. ** that the size-of-header varint that occurs at the start of each record
  70888. ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
  70889. ** also assumes that it is safe to overread a buffer by at least the
  70890. ** maximum possible legal header size plus 8 bytes. Because there is
  70891. ** guaranteed to be at least 74 (but not 136) bytes of padding following each
  70892. ** buffer passed to varintRecordCompareInt() this makes it convenient to
  70893. ** limit the size of the header to 64 bytes in cases where the first field
  70894. ** is an integer.
  70895. **
  70896. ** The easiest way to enforce this limit is to consider only records with
  70897. ** 13 fields or less. If the first field is an integer, the maximum legal
  70898. ** header size is (12*5 + 1 + 1) bytes. */
  70899. if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
  70900. int flags = p->aMem[0].flags;
  70901. if( p->pKeyInfo->aSortOrder[0] ){
  70902. p->r1 = 1;
  70903. p->r2 = -1;
  70904. }else{
  70905. p->r1 = -1;
  70906. p->r2 = 1;
  70907. }
  70908. if( (flags & MEM_Int) ){
  70909. return vdbeRecordCompareInt;
  70910. }
  70911. testcase( flags & MEM_Real );
  70912. testcase( flags & MEM_Null );
  70913. testcase( flags & MEM_Blob );
  70914. if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
  70915. assert( flags & MEM_Str );
  70916. return vdbeRecordCompareString;
  70917. }
  70918. }
  70919. return sqlite3VdbeRecordCompare;
  70920. }
  70921. /*
  70922. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  70923. ** Read the rowid (the last field in the record) and store it in *rowid.
  70924. ** Return SQLITE_OK if everything works, or an error code otherwise.
  70925. **
  70926. ** pCur might be pointing to text obtained from a corrupt database file.
  70927. ** So the content cannot be trusted. Do appropriate checks on the content.
  70928. */
  70929. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  70930. i64 nCellKey = 0;
  70931. int rc;
  70932. u32 szHdr; /* Size of the header */
  70933. u32 typeRowid; /* Serial type of the rowid */
  70934. u32 lenRowid; /* Size of the rowid */
  70935. Mem m, v;
  70936. /* Get the size of the index entry. Only indices entries of less
  70937. ** than 2GiB are support - anything large must be database corruption.
  70938. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  70939. ** this code can safely assume that nCellKey is 32-bits
  70940. */
  70941. assert( sqlite3BtreeCursorIsValid(pCur) );
  70942. nCellKey = sqlite3BtreePayloadSize(pCur);
  70943. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  70944. /* Read in the complete content of the index entry */
  70945. sqlite3VdbeMemInit(&m, db, 0);
  70946. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
  70947. if( rc ){
  70948. return rc;
  70949. }
  70950. /* The index entry must begin with a header size */
  70951. (void)getVarint32((u8*)m.z, szHdr);
  70952. testcase( szHdr==3 );
  70953. testcase( szHdr==m.n );
  70954. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  70955. goto idx_rowid_corruption;
  70956. }
  70957. /* The last field of the index should be an integer - the ROWID.
  70958. ** Verify that the last entry really is an integer. */
  70959. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  70960. testcase( typeRowid==1 );
  70961. testcase( typeRowid==2 );
  70962. testcase( typeRowid==3 );
  70963. testcase( typeRowid==4 );
  70964. testcase( typeRowid==5 );
  70965. testcase( typeRowid==6 );
  70966. testcase( typeRowid==8 );
  70967. testcase( typeRowid==9 );
  70968. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  70969. goto idx_rowid_corruption;
  70970. }
  70971. lenRowid = sqlite3SmallTypeSizes[typeRowid];
  70972. testcase( (u32)m.n==szHdr+lenRowid );
  70973. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  70974. goto idx_rowid_corruption;
  70975. }
  70976. /* Fetch the integer off the end of the index record */
  70977. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  70978. *rowid = v.u.i;
  70979. sqlite3VdbeMemRelease(&m);
  70980. return SQLITE_OK;
  70981. /* Jump here if database corruption is detected after m has been
  70982. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  70983. idx_rowid_corruption:
  70984. testcase( m.szMalloc!=0 );
  70985. sqlite3VdbeMemRelease(&m);
  70986. return SQLITE_CORRUPT_BKPT;
  70987. }
  70988. /*
  70989. ** Compare the key of the index entry that cursor pC is pointing to against
  70990. ** the key string in pUnpacked. Write into *pRes a number
  70991. ** that is negative, zero, or positive if pC is less than, equal to,
  70992. ** or greater than pUnpacked. Return SQLITE_OK on success.
  70993. **
  70994. ** pUnpacked is either created without a rowid or is truncated so that it
  70995. ** omits the rowid at the end. The rowid at the end of the index entry
  70996. ** is ignored as well. Hence, this routine only compares the prefixes
  70997. ** of the keys prior to the final rowid, not the entire key.
  70998. */
  70999. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  71000. sqlite3 *db, /* Database connection */
  71001. VdbeCursor *pC, /* The cursor to compare against */
  71002. UnpackedRecord *pUnpacked, /* Unpacked version of key */
  71003. int *res /* Write the comparison result here */
  71004. ){
  71005. i64 nCellKey = 0;
  71006. int rc;
  71007. BtCursor *pCur;
  71008. Mem m;
  71009. assert( pC->eCurType==CURTYPE_BTREE );
  71010. pCur = pC->uc.pCursor;
  71011. assert( sqlite3BtreeCursorIsValid(pCur) );
  71012. nCellKey = sqlite3BtreePayloadSize(pCur);
  71013. /* nCellKey will always be between 0 and 0xffffffff because of the way
  71014. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  71015. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  71016. *res = 0;
  71017. return SQLITE_CORRUPT_BKPT;
  71018. }
  71019. sqlite3VdbeMemInit(&m, db, 0);
  71020. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
  71021. if( rc ){
  71022. return rc;
  71023. }
  71024. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  71025. sqlite3VdbeMemRelease(&m);
  71026. return SQLITE_OK;
  71027. }
  71028. /*
  71029. ** This routine sets the value to be returned by subsequent calls to
  71030. ** sqlite3_changes() on the database handle 'db'.
  71031. */
  71032. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  71033. assert( sqlite3_mutex_held(db->mutex) );
  71034. db->nChange = nChange;
  71035. db->nTotalChange += nChange;
  71036. }
  71037. /*
  71038. ** Set a flag in the vdbe to update the change counter when it is finalised
  71039. ** or reset.
  71040. */
  71041. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  71042. v->changeCntOn = 1;
  71043. }
  71044. /*
  71045. ** Mark every prepared statement associated with a database connection
  71046. ** as expired.
  71047. **
  71048. ** An expired statement means that recompilation of the statement is
  71049. ** recommend. Statements expire when things happen that make their
  71050. ** programs obsolete. Removing user-defined functions or collating
  71051. ** sequences, or changing an authorization function are the types of
  71052. ** things that make prepared statements obsolete.
  71053. */
  71054. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  71055. Vdbe *p;
  71056. for(p = db->pVdbe; p; p=p->pNext){
  71057. p->expired = 1;
  71058. }
  71059. }
  71060. /*
  71061. ** Return the database associated with the Vdbe.
  71062. */
  71063. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  71064. return v->db;
  71065. }
  71066. /*
  71067. ** Return a pointer to an sqlite3_value structure containing the value bound
  71068. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  71069. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  71070. ** constants) to the value before returning it.
  71071. **
  71072. ** The returned value must be freed by the caller using sqlite3ValueFree().
  71073. */
  71074. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  71075. assert( iVar>0 );
  71076. if( v ){
  71077. Mem *pMem = &v->aVar[iVar-1];
  71078. if( 0==(pMem->flags & MEM_Null) ){
  71079. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  71080. if( pRet ){
  71081. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  71082. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  71083. }
  71084. return pRet;
  71085. }
  71086. }
  71087. return 0;
  71088. }
  71089. /*
  71090. ** Configure SQL variable iVar so that binding a new value to it signals
  71091. ** to sqlite3_reoptimize() that re-preparing the statement may result
  71092. ** in a better query plan.
  71093. */
  71094. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  71095. assert( iVar>0 );
  71096. if( iVar>=32 ){
  71097. v->expmask |= 0x80000000;
  71098. }else{
  71099. v->expmask |= ((u32)1 << (iVar-1));
  71100. }
  71101. }
  71102. #ifndef SQLITE_OMIT_VIRTUALTABLE
  71103. /*
  71104. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  71105. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  71106. ** in memory obtained from sqlite3DbMalloc).
  71107. */
  71108. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  71109. if( pVtab->zErrMsg ){
  71110. sqlite3 *db = p->db;
  71111. sqlite3DbFree(db, p->zErrMsg);
  71112. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  71113. sqlite3_free(pVtab->zErrMsg);
  71114. pVtab->zErrMsg = 0;
  71115. }
  71116. }
  71117. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  71118. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  71119. /*
  71120. ** If the second argument is not NULL, release any allocations associated
  71121. ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
  71122. ** structure itself, using sqlite3DbFree().
  71123. **
  71124. ** This function is used to free UnpackedRecord structures allocated by
  71125. ** the vdbeUnpackRecord() function found in vdbeapi.c.
  71126. */
  71127. static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
  71128. if( p ){
  71129. int i;
  71130. for(i=0; i<nField; i++){
  71131. Mem *pMem = &p->aMem[i];
  71132. if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
  71133. }
  71134. sqlite3DbFreeNN(db, p);
  71135. }
  71136. }
  71137. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  71138. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  71139. /*
  71140. ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
  71141. ** then cursor passed as the second argument should point to the row about
  71142. ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
  71143. ** the required value will be read from the row the cursor points to.
  71144. */
  71145. SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
  71146. Vdbe *v, /* Vdbe pre-update hook is invoked by */
  71147. VdbeCursor *pCsr, /* Cursor to grab old.* values from */
  71148. int op, /* SQLITE_INSERT, UPDATE or DELETE */
  71149. const char *zDb, /* Database name */
  71150. Table *pTab, /* Modified table */
  71151. i64 iKey1, /* Initial key value */
  71152. int iReg /* Register for new.* record */
  71153. ){
  71154. sqlite3 *db = v->db;
  71155. i64 iKey2;
  71156. PreUpdate preupdate;
  71157. const char *zTbl = pTab->zName;
  71158. static const u8 fakeSortOrder = 0;
  71159. assert( db->pPreUpdate==0 );
  71160. memset(&preupdate, 0, sizeof(PreUpdate));
  71161. if( HasRowid(pTab)==0 ){
  71162. iKey1 = iKey2 = 0;
  71163. preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
  71164. }else{
  71165. if( op==SQLITE_UPDATE ){
  71166. iKey2 = v->aMem[iReg].u.i;
  71167. }else{
  71168. iKey2 = iKey1;
  71169. }
  71170. }
  71171. assert( pCsr->nField==pTab->nCol
  71172. || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
  71173. );
  71174. preupdate.v = v;
  71175. preupdate.pCsr = pCsr;
  71176. preupdate.op = op;
  71177. preupdate.iNewReg = iReg;
  71178. preupdate.keyinfo.db = db;
  71179. preupdate.keyinfo.enc = ENC(db);
  71180. preupdate.keyinfo.nField = pTab->nCol;
  71181. preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
  71182. preupdate.iKey1 = iKey1;
  71183. preupdate.iKey2 = iKey2;
  71184. preupdate.pTab = pTab;
  71185. db->pPreUpdate = &preupdate;
  71186. db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
  71187. db->pPreUpdate = 0;
  71188. sqlite3DbFree(db, preupdate.aRecord);
  71189. vdbeFreeUnpacked(db, preupdate.keyinfo.nField+1, preupdate.pUnpacked);
  71190. vdbeFreeUnpacked(db, preupdate.keyinfo.nField+1, preupdate.pNewUnpacked);
  71191. if( preupdate.aNew ){
  71192. int i;
  71193. for(i=0; i<pCsr->nField; i++){
  71194. sqlite3VdbeMemRelease(&preupdate.aNew[i]);
  71195. }
  71196. sqlite3DbFreeNN(db, preupdate.aNew);
  71197. }
  71198. }
  71199. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  71200. /************** End of vdbeaux.c *********************************************/
  71201. /************** Begin file vdbeapi.c *****************************************/
  71202. /*
  71203. ** 2004 May 26
  71204. **
  71205. ** The author disclaims copyright to this source code. In place of
  71206. ** a legal notice, here is a blessing:
  71207. **
  71208. ** May you do good and not evil.
  71209. ** May you find forgiveness for yourself and forgive others.
  71210. ** May you share freely, never taking more than you give.
  71211. **
  71212. *************************************************************************
  71213. **
  71214. ** This file contains code use to implement APIs that are part of the
  71215. ** VDBE.
  71216. */
  71217. /* #include "sqliteInt.h" */
  71218. /* #include "vdbeInt.h" */
  71219. #ifndef SQLITE_OMIT_DEPRECATED
  71220. /*
  71221. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  71222. ** to be recompiled. A statement needs to be recompiled whenever the
  71223. ** execution environment changes in a way that would alter the program
  71224. ** that sqlite3_prepare() generates. For example, if new functions or
  71225. ** collating sequences are registered or if an authorizer function is
  71226. ** added or changed.
  71227. */
  71228. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  71229. Vdbe *p = (Vdbe*)pStmt;
  71230. return p==0 || p->expired;
  71231. }
  71232. #endif
  71233. /*
  71234. ** Check on a Vdbe to make sure it has not been finalized. Log
  71235. ** an error and return true if it has been finalized (or is otherwise
  71236. ** invalid). Return false if it is ok.
  71237. */
  71238. static int vdbeSafety(Vdbe *p){
  71239. if( p->db==0 ){
  71240. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  71241. return 1;
  71242. }else{
  71243. return 0;
  71244. }
  71245. }
  71246. static int vdbeSafetyNotNull(Vdbe *p){
  71247. if( p==0 ){
  71248. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  71249. return 1;
  71250. }else{
  71251. return vdbeSafety(p);
  71252. }
  71253. }
  71254. #ifndef SQLITE_OMIT_TRACE
  71255. /*
  71256. ** Invoke the profile callback. This routine is only called if we already
  71257. ** know that the profile callback is defined and needs to be invoked.
  71258. */
  71259. static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
  71260. sqlite3_int64 iNow;
  71261. sqlite3_int64 iElapse;
  71262. assert( p->startTime>0 );
  71263. assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 );
  71264. assert( db->init.busy==0 );
  71265. assert( p->zSql!=0 );
  71266. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  71267. iElapse = (iNow - p->startTime)*1000000;
  71268. if( db->xProfile ){
  71269. db->xProfile(db->pProfileArg, p->zSql, iElapse);
  71270. }
  71271. if( db->mTrace & SQLITE_TRACE_PROFILE ){
  71272. db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
  71273. }
  71274. p->startTime = 0;
  71275. }
  71276. /*
  71277. ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
  71278. ** is needed, and it invokes the callback if it is needed.
  71279. */
  71280. # define checkProfileCallback(DB,P) \
  71281. if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
  71282. #else
  71283. # define checkProfileCallback(DB,P) /*no-op*/
  71284. #endif
  71285. /*
  71286. ** The following routine destroys a virtual machine that is created by
  71287. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  71288. ** success/failure code that describes the result of executing the virtual
  71289. ** machine.
  71290. **
  71291. ** This routine sets the error code and string returned by
  71292. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  71293. */
  71294. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  71295. int rc;
  71296. if( pStmt==0 ){
  71297. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  71298. ** pointer is a harmless no-op. */
  71299. rc = SQLITE_OK;
  71300. }else{
  71301. Vdbe *v = (Vdbe*)pStmt;
  71302. sqlite3 *db = v->db;
  71303. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  71304. sqlite3_mutex_enter(db->mutex);
  71305. checkProfileCallback(db, v);
  71306. rc = sqlite3VdbeFinalize(v);
  71307. rc = sqlite3ApiExit(db, rc);
  71308. sqlite3LeaveMutexAndCloseZombie(db);
  71309. }
  71310. return rc;
  71311. }
  71312. /*
  71313. ** Terminate the current execution of an SQL statement and reset it
  71314. ** back to its starting state so that it can be reused. A success code from
  71315. ** the prior execution is returned.
  71316. **
  71317. ** This routine sets the error code and string returned by
  71318. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  71319. */
  71320. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  71321. int rc;
  71322. if( pStmt==0 ){
  71323. rc = SQLITE_OK;
  71324. }else{
  71325. Vdbe *v = (Vdbe*)pStmt;
  71326. sqlite3 *db = v->db;
  71327. sqlite3_mutex_enter(db->mutex);
  71328. checkProfileCallback(db, v);
  71329. rc = sqlite3VdbeReset(v);
  71330. sqlite3VdbeRewind(v);
  71331. assert( (rc & (db->errMask))==rc );
  71332. rc = sqlite3ApiExit(db, rc);
  71333. sqlite3_mutex_leave(db->mutex);
  71334. }
  71335. return rc;
  71336. }
  71337. /*
  71338. ** Set all the parameters in the compiled SQL statement to NULL.
  71339. */
  71340. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  71341. int i;
  71342. int rc = SQLITE_OK;
  71343. Vdbe *p = (Vdbe*)pStmt;
  71344. #if SQLITE_THREADSAFE
  71345. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  71346. #endif
  71347. sqlite3_mutex_enter(mutex);
  71348. for(i=0; i<p->nVar; i++){
  71349. sqlite3VdbeMemRelease(&p->aVar[i]);
  71350. p->aVar[i].flags = MEM_Null;
  71351. }
  71352. assert( p->isPrepareV2 || p->expmask==0 );
  71353. if( p->expmask ){
  71354. p->expired = 1;
  71355. }
  71356. sqlite3_mutex_leave(mutex);
  71357. return rc;
  71358. }
  71359. /**************************** sqlite3_value_ *******************************
  71360. ** The following routines extract information from a Mem or sqlite3_value
  71361. ** structure.
  71362. */
  71363. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  71364. Mem *p = (Mem*)pVal;
  71365. if( p->flags & (MEM_Blob|MEM_Str) ){
  71366. if( ExpandBlob(p)!=SQLITE_OK ){
  71367. assert( p->flags==MEM_Null && p->z==0 );
  71368. return 0;
  71369. }
  71370. p->flags |= MEM_Blob;
  71371. return p->n ? p->z : 0;
  71372. }else{
  71373. return sqlite3_value_text(pVal);
  71374. }
  71375. }
  71376. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  71377. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  71378. }
  71379. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  71380. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  71381. }
  71382. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  71383. return sqlite3VdbeRealValue((Mem*)pVal);
  71384. }
  71385. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  71386. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  71387. }
  71388. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  71389. return sqlite3VdbeIntValue((Mem*)pVal);
  71390. }
  71391. SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
  71392. Mem *pMem = (Mem*)pVal;
  71393. return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
  71394. }
  71395. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  71396. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  71397. }
  71398. #ifndef SQLITE_OMIT_UTF16
  71399. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  71400. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  71401. }
  71402. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  71403. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  71404. }
  71405. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  71406. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  71407. }
  71408. #endif /* SQLITE_OMIT_UTF16 */
  71409. /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
  71410. ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
  71411. ** point number string BLOB NULL
  71412. */
  71413. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  71414. static const u8 aType[] = {
  71415. SQLITE_BLOB, /* 0x00 */
  71416. SQLITE_NULL, /* 0x01 */
  71417. SQLITE_TEXT, /* 0x02 */
  71418. SQLITE_NULL, /* 0x03 */
  71419. SQLITE_INTEGER, /* 0x04 */
  71420. SQLITE_NULL, /* 0x05 */
  71421. SQLITE_INTEGER, /* 0x06 */
  71422. SQLITE_NULL, /* 0x07 */
  71423. SQLITE_FLOAT, /* 0x08 */
  71424. SQLITE_NULL, /* 0x09 */
  71425. SQLITE_FLOAT, /* 0x0a */
  71426. SQLITE_NULL, /* 0x0b */
  71427. SQLITE_INTEGER, /* 0x0c */
  71428. SQLITE_NULL, /* 0x0d */
  71429. SQLITE_INTEGER, /* 0x0e */
  71430. SQLITE_NULL, /* 0x0f */
  71431. SQLITE_BLOB, /* 0x10 */
  71432. SQLITE_NULL, /* 0x11 */
  71433. SQLITE_TEXT, /* 0x12 */
  71434. SQLITE_NULL, /* 0x13 */
  71435. SQLITE_INTEGER, /* 0x14 */
  71436. SQLITE_NULL, /* 0x15 */
  71437. SQLITE_INTEGER, /* 0x16 */
  71438. SQLITE_NULL, /* 0x17 */
  71439. SQLITE_FLOAT, /* 0x18 */
  71440. SQLITE_NULL, /* 0x19 */
  71441. SQLITE_FLOAT, /* 0x1a */
  71442. SQLITE_NULL, /* 0x1b */
  71443. SQLITE_INTEGER, /* 0x1c */
  71444. SQLITE_NULL, /* 0x1d */
  71445. SQLITE_INTEGER, /* 0x1e */
  71446. SQLITE_NULL, /* 0x1f */
  71447. };
  71448. return aType[pVal->flags&MEM_AffMask];
  71449. }
  71450. /* Make a copy of an sqlite3_value object
  71451. */
  71452. SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
  71453. sqlite3_value *pNew;
  71454. if( pOrig==0 ) return 0;
  71455. pNew = sqlite3_malloc( sizeof(*pNew) );
  71456. if( pNew==0 ) return 0;
  71457. memset(pNew, 0, sizeof(*pNew));
  71458. memcpy(pNew, pOrig, MEMCELLSIZE);
  71459. pNew->flags &= ~MEM_Dyn;
  71460. pNew->db = 0;
  71461. if( pNew->flags&(MEM_Str|MEM_Blob) ){
  71462. pNew->flags &= ~(MEM_Static|MEM_Dyn);
  71463. pNew->flags |= MEM_Ephem;
  71464. if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
  71465. sqlite3ValueFree(pNew);
  71466. pNew = 0;
  71467. }
  71468. }
  71469. return pNew;
  71470. }
  71471. /* Destroy an sqlite3_value object previously obtained from
  71472. ** sqlite3_value_dup().
  71473. */
  71474. SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
  71475. sqlite3ValueFree(pOld);
  71476. }
  71477. /**************************** sqlite3_result_ *******************************
  71478. ** The following routines are used by user-defined functions to specify
  71479. ** the function result.
  71480. **
  71481. ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
  71482. ** result as a string or blob but if the string or blob is too large, it
  71483. ** then sets the error code to SQLITE_TOOBIG
  71484. **
  71485. ** The invokeValueDestructor(P,X) routine invokes destructor function X()
  71486. ** on value P is not going to be used and need to be destroyed.
  71487. */
  71488. static void setResultStrOrError(
  71489. sqlite3_context *pCtx, /* Function context */
  71490. const char *z, /* String pointer */
  71491. int n, /* Bytes in string, or negative */
  71492. u8 enc, /* Encoding of z. 0 for BLOBs */
  71493. void (*xDel)(void*) /* Destructor function */
  71494. ){
  71495. if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
  71496. sqlite3_result_error_toobig(pCtx);
  71497. }
  71498. }
  71499. static int invokeValueDestructor(
  71500. const void *p, /* Value to destroy */
  71501. void (*xDel)(void*), /* The destructor */
  71502. sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
  71503. ){
  71504. assert( xDel!=SQLITE_DYNAMIC );
  71505. if( xDel==0 ){
  71506. /* noop */
  71507. }else if( xDel==SQLITE_TRANSIENT ){
  71508. /* noop */
  71509. }else{
  71510. xDel((void*)p);
  71511. }
  71512. if( pCtx ) sqlite3_result_error_toobig(pCtx);
  71513. return SQLITE_TOOBIG;
  71514. }
  71515. SQLITE_API void sqlite3_result_blob(
  71516. sqlite3_context *pCtx,
  71517. const void *z,
  71518. int n,
  71519. void (*xDel)(void *)
  71520. ){
  71521. assert( n>=0 );
  71522. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71523. setResultStrOrError(pCtx, z, n, 0, xDel);
  71524. }
  71525. SQLITE_API void sqlite3_result_blob64(
  71526. sqlite3_context *pCtx,
  71527. const void *z,
  71528. sqlite3_uint64 n,
  71529. void (*xDel)(void *)
  71530. ){
  71531. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71532. assert( xDel!=SQLITE_DYNAMIC );
  71533. if( n>0x7fffffff ){
  71534. (void)invokeValueDestructor(z, xDel, pCtx);
  71535. }else{
  71536. setResultStrOrError(pCtx, z, (int)n, 0, xDel);
  71537. }
  71538. }
  71539. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  71540. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71541. sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
  71542. }
  71543. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  71544. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71545. pCtx->isError = SQLITE_ERROR;
  71546. pCtx->fErrorOrAux = 1;
  71547. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  71548. }
  71549. #ifndef SQLITE_OMIT_UTF16
  71550. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  71551. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71552. pCtx->isError = SQLITE_ERROR;
  71553. pCtx->fErrorOrAux = 1;
  71554. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  71555. }
  71556. #endif
  71557. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  71558. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71559. sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
  71560. }
  71561. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  71562. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71563. sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
  71564. }
  71565. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  71566. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71567. sqlite3VdbeMemSetNull(pCtx->pOut);
  71568. }
  71569. SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
  71570. Mem *pOut = pCtx->pOut;
  71571. assert( sqlite3_mutex_held(pOut->db->mutex) );
  71572. pOut->eSubtype = eSubtype & 0xff;
  71573. pOut->flags |= MEM_Subtype;
  71574. }
  71575. SQLITE_API void sqlite3_result_text(
  71576. sqlite3_context *pCtx,
  71577. const char *z,
  71578. int n,
  71579. void (*xDel)(void *)
  71580. ){
  71581. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71582. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  71583. }
  71584. SQLITE_API void sqlite3_result_text64(
  71585. sqlite3_context *pCtx,
  71586. const char *z,
  71587. sqlite3_uint64 n,
  71588. void (*xDel)(void *),
  71589. unsigned char enc
  71590. ){
  71591. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71592. assert( xDel!=SQLITE_DYNAMIC );
  71593. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  71594. if( n>0x7fffffff ){
  71595. (void)invokeValueDestructor(z, xDel, pCtx);
  71596. }else{
  71597. setResultStrOrError(pCtx, z, (int)n, enc, xDel);
  71598. }
  71599. }
  71600. #ifndef SQLITE_OMIT_UTF16
  71601. SQLITE_API void sqlite3_result_text16(
  71602. sqlite3_context *pCtx,
  71603. const void *z,
  71604. int n,
  71605. void (*xDel)(void *)
  71606. ){
  71607. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71608. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  71609. }
  71610. SQLITE_API void sqlite3_result_text16be(
  71611. sqlite3_context *pCtx,
  71612. const void *z,
  71613. int n,
  71614. void (*xDel)(void *)
  71615. ){
  71616. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71617. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  71618. }
  71619. SQLITE_API void sqlite3_result_text16le(
  71620. sqlite3_context *pCtx,
  71621. const void *z,
  71622. int n,
  71623. void (*xDel)(void *)
  71624. ){
  71625. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71626. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  71627. }
  71628. #endif /* SQLITE_OMIT_UTF16 */
  71629. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  71630. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71631. sqlite3VdbeMemCopy(pCtx->pOut, pValue);
  71632. }
  71633. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  71634. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71635. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
  71636. }
  71637. SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
  71638. Mem *pOut = pCtx->pOut;
  71639. assert( sqlite3_mutex_held(pOut->db->mutex) );
  71640. if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  71641. return SQLITE_TOOBIG;
  71642. }
  71643. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
  71644. return SQLITE_OK;
  71645. }
  71646. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  71647. pCtx->isError = errCode;
  71648. pCtx->fErrorOrAux = 1;
  71649. #ifdef SQLITE_DEBUG
  71650. if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
  71651. #endif
  71652. if( pCtx->pOut->flags & MEM_Null ){
  71653. sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
  71654. SQLITE_UTF8, SQLITE_STATIC);
  71655. }
  71656. }
  71657. /* Force an SQLITE_TOOBIG error. */
  71658. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  71659. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71660. pCtx->isError = SQLITE_TOOBIG;
  71661. pCtx->fErrorOrAux = 1;
  71662. sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
  71663. SQLITE_UTF8, SQLITE_STATIC);
  71664. }
  71665. /* An SQLITE_NOMEM error. */
  71666. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  71667. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71668. sqlite3VdbeMemSetNull(pCtx->pOut);
  71669. pCtx->isError = SQLITE_NOMEM_BKPT;
  71670. pCtx->fErrorOrAux = 1;
  71671. sqlite3OomFault(pCtx->pOut->db);
  71672. }
  71673. /*
  71674. ** This function is called after a transaction has been committed. It
  71675. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  71676. */
  71677. static int doWalCallbacks(sqlite3 *db){
  71678. int rc = SQLITE_OK;
  71679. #ifndef SQLITE_OMIT_WAL
  71680. int i;
  71681. for(i=0; i<db->nDb; i++){
  71682. Btree *pBt = db->aDb[i].pBt;
  71683. if( pBt ){
  71684. int nEntry;
  71685. sqlite3BtreeEnter(pBt);
  71686. nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  71687. sqlite3BtreeLeave(pBt);
  71688. if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
  71689. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
  71690. }
  71691. }
  71692. }
  71693. #endif
  71694. return rc;
  71695. }
  71696. /*
  71697. ** Execute the statement pStmt, either until a row of data is ready, the
  71698. ** statement is completely executed or an error occurs.
  71699. **
  71700. ** This routine implements the bulk of the logic behind the sqlite_step()
  71701. ** API. The only thing omitted is the automatic recompile if a
  71702. ** schema change has occurred. That detail is handled by the
  71703. ** outer sqlite3_step() wrapper procedure.
  71704. */
  71705. static int sqlite3Step(Vdbe *p){
  71706. sqlite3 *db;
  71707. int rc;
  71708. assert(p);
  71709. if( p->magic!=VDBE_MAGIC_RUN ){
  71710. /* We used to require that sqlite3_reset() be called before retrying
  71711. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  71712. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  71713. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  71714. ** This "automatic-reset" change is not technically an incompatibility,
  71715. ** since any application that receives an SQLITE_MISUSE is broken by
  71716. ** definition.
  71717. **
  71718. ** Nevertheless, some published applications that were originally written
  71719. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  71720. ** returns, and those were broken by the automatic-reset change. As a
  71721. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  71722. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  71723. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  71724. ** or SQLITE_BUSY error.
  71725. */
  71726. #ifdef SQLITE_OMIT_AUTORESET
  71727. if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  71728. sqlite3_reset((sqlite3_stmt*)p);
  71729. }else{
  71730. return SQLITE_MISUSE_BKPT;
  71731. }
  71732. #else
  71733. sqlite3_reset((sqlite3_stmt*)p);
  71734. #endif
  71735. }
  71736. /* Check that malloc() has not failed. If it has, return early. */
  71737. db = p->db;
  71738. if( db->mallocFailed ){
  71739. p->rc = SQLITE_NOMEM;
  71740. return SQLITE_NOMEM_BKPT;
  71741. }
  71742. if( p->pc<=0 && p->expired ){
  71743. p->rc = SQLITE_SCHEMA;
  71744. rc = SQLITE_ERROR;
  71745. goto end_of_step;
  71746. }
  71747. if( p->pc<0 ){
  71748. /* If there are no other statements currently running, then
  71749. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  71750. ** from interrupting a statement that has not yet started.
  71751. */
  71752. if( db->nVdbeActive==0 ){
  71753. db->u1.isInterrupted = 0;
  71754. }
  71755. assert( db->nVdbeWrite>0 || db->autoCommit==0
  71756. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  71757. );
  71758. #ifndef SQLITE_OMIT_TRACE
  71759. if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0)
  71760. && !db->init.busy && p->zSql ){
  71761. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  71762. }else{
  71763. assert( p->startTime==0 );
  71764. }
  71765. #endif
  71766. db->nVdbeActive++;
  71767. if( p->readOnly==0 ) db->nVdbeWrite++;
  71768. if( p->bIsReader ) db->nVdbeRead++;
  71769. p->pc = 0;
  71770. }
  71771. #ifdef SQLITE_DEBUG
  71772. p->rcApp = SQLITE_OK;
  71773. #endif
  71774. #ifndef SQLITE_OMIT_EXPLAIN
  71775. if( p->explain ){
  71776. rc = sqlite3VdbeList(p);
  71777. }else
  71778. #endif /* SQLITE_OMIT_EXPLAIN */
  71779. {
  71780. db->nVdbeExec++;
  71781. rc = sqlite3VdbeExec(p);
  71782. db->nVdbeExec--;
  71783. }
  71784. #ifndef SQLITE_OMIT_TRACE
  71785. /* If the statement completed successfully, invoke the profile callback */
  71786. if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
  71787. #endif
  71788. if( rc==SQLITE_DONE ){
  71789. assert( p->rc==SQLITE_OK );
  71790. p->rc = doWalCallbacks(db);
  71791. if( p->rc!=SQLITE_OK ){
  71792. rc = SQLITE_ERROR;
  71793. }
  71794. }
  71795. db->errCode = rc;
  71796. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  71797. p->rc = SQLITE_NOMEM_BKPT;
  71798. }
  71799. end_of_step:
  71800. /* At this point local variable rc holds the value that should be
  71801. ** returned if this statement was compiled using the legacy
  71802. ** sqlite3_prepare() interface. According to the docs, this can only
  71803. ** be one of the values in the first assert() below. Variable p->rc
  71804. ** contains the value that would be returned if sqlite3_finalize()
  71805. ** were called on statement p.
  71806. */
  71807. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  71808. || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
  71809. );
  71810. assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
  71811. if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  71812. /* If this statement was prepared using sqlite3_prepare_v2(), and an
  71813. ** error has occurred, then return the error code in p->rc to the
  71814. ** caller. Set the error code in the database handle to the same value.
  71815. */
  71816. rc = sqlite3VdbeTransferError(p);
  71817. }
  71818. return (rc&db->errMask);
  71819. }
  71820. /*
  71821. ** This is the top-level implementation of sqlite3_step(). Call
  71822. ** sqlite3Step() to do most of the work. If a schema error occurs,
  71823. ** call sqlite3Reprepare() and try again.
  71824. */
  71825. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  71826. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  71827. int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
  71828. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  71829. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  71830. sqlite3 *db; /* The database connection */
  71831. if( vdbeSafetyNotNull(v) ){
  71832. return SQLITE_MISUSE_BKPT;
  71833. }
  71834. db = v->db;
  71835. sqlite3_mutex_enter(db->mutex);
  71836. v->doingRerun = 0;
  71837. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  71838. && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
  71839. int savedPc = v->pc;
  71840. rc2 = rc = sqlite3Reprepare(v);
  71841. if( rc!=SQLITE_OK) break;
  71842. sqlite3_reset(pStmt);
  71843. if( savedPc>=0 ) v->doingRerun = 1;
  71844. assert( v->expired==0 );
  71845. }
  71846. if( rc2!=SQLITE_OK ){
  71847. /* This case occurs after failing to recompile an sql statement.
  71848. ** The error message from the SQL compiler has already been loaded
  71849. ** into the database handle. This block copies the error message
  71850. ** from the database handle into the statement and sets the statement
  71851. ** program counter to 0 to ensure that when the statement is
  71852. ** finalized or reset the parser error message is available via
  71853. ** sqlite3_errmsg() and sqlite3_errcode().
  71854. */
  71855. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  71856. sqlite3DbFree(db, v->zErrMsg);
  71857. if( !db->mallocFailed ){
  71858. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  71859. v->rc = rc2;
  71860. } else {
  71861. v->zErrMsg = 0;
  71862. v->rc = rc = SQLITE_NOMEM_BKPT;
  71863. }
  71864. }
  71865. rc = sqlite3ApiExit(db, rc);
  71866. sqlite3_mutex_leave(db->mutex);
  71867. return rc;
  71868. }
  71869. /*
  71870. ** Extract the user data from a sqlite3_context structure and return a
  71871. ** pointer to it.
  71872. */
  71873. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  71874. assert( p && p->pFunc );
  71875. return p->pFunc->pUserData;
  71876. }
  71877. /*
  71878. ** Extract the user data from a sqlite3_context structure and return a
  71879. ** pointer to it.
  71880. **
  71881. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  71882. ** returns a copy of the pointer to the database connection (the 1st
  71883. ** parameter) of the sqlite3_create_function() and
  71884. ** sqlite3_create_function16() routines that originally registered the
  71885. ** application defined function.
  71886. */
  71887. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  71888. assert( p && p->pOut );
  71889. return p->pOut->db;
  71890. }
  71891. /*
  71892. ** Return the current time for a statement. If the current time
  71893. ** is requested more than once within the same run of a single prepared
  71894. ** statement, the exact same time is returned for each invocation regardless
  71895. ** of the amount of time that elapses between invocations. In other words,
  71896. ** the time returned is always the time of the first call.
  71897. */
  71898. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  71899. int rc;
  71900. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  71901. sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
  71902. assert( p->pVdbe!=0 );
  71903. #else
  71904. sqlite3_int64 iTime = 0;
  71905. sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
  71906. #endif
  71907. if( *piTime==0 ){
  71908. rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
  71909. if( rc ) *piTime = 0;
  71910. }
  71911. return *piTime;
  71912. }
  71913. /*
  71914. ** The following is the implementation of an SQL function that always
  71915. ** fails with an error message stating that the function is used in the
  71916. ** wrong context. The sqlite3_overload_function() API might construct
  71917. ** SQL function that use this routine so that the functions will exist
  71918. ** for name resolution but are actually overloaded by the xFindFunction
  71919. ** method of virtual tables.
  71920. */
  71921. SQLITE_PRIVATE void sqlite3InvalidFunction(
  71922. sqlite3_context *context, /* The function calling context */
  71923. int NotUsed, /* Number of arguments to the function */
  71924. sqlite3_value **NotUsed2 /* Value of each argument */
  71925. ){
  71926. const char *zName = context->pFunc->zName;
  71927. char *zErr;
  71928. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  71929. zErr = sqlite3_mprintf(
  71930. "unable to use function %s in the requested context", zName);
  71931. sqlite3_result_error(context, zErr, -1);
  71932. sqlite3_free(zErr);
  71933. }
  71934. /*
  71935. ** Create a new aggregate context for p and return a pointer to
  71936. ** its pMem->z element.
  71937. */
  71938. static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
  71939. Mem *pMem = p->pMem;
  71940. assert( (pMem->flags & MEM_Agg)==0 );
  71941. if( nByte<=0 ){
  71942. sqlite3VdbeMemSetNull(pMem);
  71943. pMem->z = 0;
  71944. }else{
  71945. sqlite3VdbeMemClearAndResize(pMem, nByte);
  71946. pMem->flags = MEM_Agg;
  71947. pMem->u.pDef = p->pFunc;
  71948. if( pMem->z ){
  71949. memset(pMem->z, 0, nByte);
  71950. }
  71951. }
  71952. return (void*)pMem->z;
  71953. }
  71954. /*
  71955. ** Allocate or return the aggregate context for a user function. A new
  71956. ** context is allocated on the first call. Subsequent calls return the
  71957. ** same context that was returned on prior calls.
  71958. */
  71959. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  71960. assert( p && p->pFunc && p->pFunc->xFinalize );
  71961. assert( sqlite3_mutex_held(p->pOut->db->mutex) );
  71962. testcase( nByte<0 );
  71963. if( (p->pMem->flags & MEM_Agg)==0 ){
  71964. return createAggContext(p, nByte);
  71965. }else{
  71966. return (void*)p->pMem->z;
  71967. }
  71968. }
  71969. /*
  71970. ** Return the auxiliary data pointer, if any, for the iArg'th argument to
  71971. ** the user-function defined by pCtx.
  71972. **
  71973. ** The left-most argument is 0.
  71974. **
  71975. ** Undocumented behavior: If iArg is negative then access a cache of
  71976. ** auxiliary data pointers that is available to all functions within a
  71977. ** single prepared statement. The iArg values must match.
  71978. */
  71979. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  71980. AuxData *pAuxData;
  71981. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  71982. #if SQLITE_ENABLE_STAT3_OR_STAT4
  71983. if( pCtx->pVdbe==0 ) return 0;
  71984. #else
  71985. assert( pCtx->pVdbe!=0 );
  71986. #endif
  71987. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
  71988. if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
  71989. return pAuxData->pAux;
  71990. }
  71991. }
  71992. return 0;
  71993. }
  71994. /*
  71995. ** Set the auxiliary data pointer and delete function, for the iArg'th
  71996. ** argument to the user-function defined by pCtx. Any previous value is
  71997. ** deleted by calling the delete function specified when it was set.
  71998. **
  71999. ** The left-most argument is 0.
  72000. **
  72001. ** Undocumented behavior: If iArg is negative then make the data available
  72002. ** to all functions within the current prepared statement using iArg as an
  72003. ** access code.
  72004. */
  72005. SQLITE_API void sqlite3_set_auxdata(
  72006. sqlite3_context *pCtx,
  72007. int iArg,
  72008. void *pAux,
  72009. void (*xDelete)(void*)
  72010. ){
  72011. AuxData *pAuxData;
  72012. Vdbe *pVdbe = pCtx->pVdbe;
  72013. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  72014. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  72015. if( pVdbe==0 ) goto failed;
  72016. #else
  72017. assert( pVdbe!=0 );
  72018. #endif
  72019. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
  72020. if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
  72021. break;
  72022. }
  72023. }
  72024. if( pAuxData==0 ){
  72025. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  72026. if( !pAuxData ) goto failed;
  72027. pAuxData->iAuxOp = pCtx->iOp;
  72028. pAuxData->iAuxArg = iArg;
  72029. pAuxData->pNextAux = pVdbe->pAuxData;
  72030. pVdbe->pAuxData = pAuxData;
  72031. if( pCtx->fErrorOrAux==0 ){
  72032. pCtx->isError = 0;
  72033. pCtx->fErrorOrAux = 1;
  72034. }
  72035. }else if( pAuxData->xDeleteAux ){
  72036. pAuxData->xDeleteAux(pAuxData->pAux);
  72037. }
  72038. pAuxData->pAux = pAux;
  72039. pAuxData->xDeleteAux = xDelete;
  72040. return;
  72041. failed:
  72042. if( xDelete ){
  72043. xDelete(pAux);
  72044. }
  72045. }
  72046. #ifndef SQLITE_OMIT_DEPRECATED
  72047. /*
  72048. ** Return the number of times the Step function of an aggregate has been
  72049. ** called.
  72050. **
  72051. ** This function is deprecated. Do not use it for new code. It is
  72052. ** provide only to avoid breaking legacy code. New aggregate function
  72053. ** implementations should keep their own counts within their aggregate
  72054. ** context.
  72055. */
  72056. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  72057. assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
  72058. return p->pMem->n;
  72059. }
  72060. #endif
  72061. /*
  72062. ** Return the number of columns in the result set for the statement pStmt.
  72063. */
  72064. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  72065. Vdbe *pVm = (Vdbe *)pStmt;
  72066. return pVm ? pVm->nResColumn : 0;
  72067. }
  72068. /*
  72069. ** Return the number of values available from the current row of the
  72070. ** currently executing statement pStmt.
  72071. */
  72072. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  72073. Vdbe *pVm = (Vdbe *)pStmt;
  72074. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  72075. return pVm->nResColumn;
  72076. }
  72077. /*
  72078. ** Return a pointer to static memory containing an SQL NULL value.
  72079. */
  72080. static const Mem *columnNullValue(void){
  72081. /* Even though the Mem structure contains an element
  72082. ** of type i64, on certain architectures (x86) with certain compiler
  72083. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  72084. ** instead of an 8-byte one. This all works fine, except that when
  72085. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  72086. ** that a Mem structure is located on an 8-byte boundary. To prevent
  72087. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  72088. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  72089. ** __attribute__((aligned(8))) macro. */
  72090. static const Mem nullMem
  72091. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  72092. __attribute__((aligned(8)))
  72093. #endif
  72094. = {
  72095. /* .u = */ {0},
  72096. /* .flags = */ (u16)MEM_Null,
  72097. /* .enc = */ (u8)0,
  72098. /* .eSubtype = */ (u8)0,
  72099. /* .n = */ (int)0,
  72100. /* .z = */ (char*)0,
  72101. /* .zMalloc = */ (char*)0,
  72102. /* .szMalloc = */ (int)0,
  72103. /* .uTemp = */ (u32)0,
  72104. /* .db = */ (sqlite3*)0,
  72105. /* .xDel = */ (void(*)(void*))0,
  72106. #ifdef SQLITE_DEBUG
  72107. /* .pScopyFrom = */ (Mem*)0,
  72108. /* .pFiller = */ (void*)0,
  72109. #endif
  72110. };
  72111. return &nullMem;
  72112. }
  72113. /*
  72114. ** Check to see if column iCol of the given statement is valid. If
  72115. ** it is, return a pointer to the Mem for the value of that column.
  72116. ** If iCol is not valid, return a pointer to a Mem which has a value
  72117. ** of NULL.
  72118. */
  72119. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  72120. Vdbe *pVm;
  72121. Mem *pOut;
  72122. pVm = (Vdbe *)pStmt;
  72123. if( pVm==0 ) return (Mem*)columnNullValue();
  72124. assert( pVm->db );
  72125. sqlite3_mutex_enter(pVm->db->mutex);
  72126. if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  72127. pOut = &pVm->pResultSet[i];
  72128. }else{
  72129. sqlite3Error(pVm->db, SQLITE_RANGE);
  72130. pOut = (Mem*)columnNullValue();
  72131. }
  72132. return pOut;
  72133. }
  72134. /*
  72135. ** This function is called after invoking an sqlite3_value_XXX function on a
  72136. ** column value (i.e. a value returned by evaluating an SQL expression in the
  72137. ** select list of a SELECT statement) that may cause a malloc() failure. If
  72138. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  72139. ** code of statement pStmt set to SQLITE_NOMEM.
  72140. **
  72141. ** Specifically, this is called from within:
  72142. **
  72143. ** sqlite3_column_int()
  72144. ** sqlite3_column_int64()
  72145. ** sqlite3_column_text()
  72146. ** sqlite3_column_text16()
  72147. ** sqlite3_column_real()
  72148. ** sqlite3_column_bytes()
  72149. ** sqlite3_column_bytes16()
  72150. ** sqiite3_column_blob()
  72151. */
  72152. static void columnMallocFailure(sqlite3_stmt *pStmt)
  72153. {
  72154. /* If malloc() failed during an encoding conversion within an
  72155. ** sqlite3_column_XXX API, then set the return code of the statement to
  72156. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  72157. ** and _finalize() will return NOMEM.
  72158. */
  72159. Vdbe *p = (Vdbe *)pStmt;
  72160. if( p ){
  72161. assert( p->db!=0 );
  72162. assert( sqlite3_mutex_held(p->db->mutex) );
  72163. p->rc = sqlite3ApiExit(p->db, p->rc);
  72164. sqlite3_mutex_leave(p->db->mutex);
  72165. }
  72166. }
  72167. /**************************** sqlite3_column_ *******************************
  72168. ** The following routines are used to access elements of the current row
  72169. ** in the result set.
  72170. */
  72171. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  72172. const void *val;
  72173. val = sqlite3_value_blob( columnMem(pStmt,i) );
  72174. /* Even though there is no encoding conversion, value_blob() might
  72175. ** need to call malloc() to expand the result of a zeroblob()
  72176. ** expression.
  72177. */
  72178. columnMallocFailure(pStmt);
  72179. return val;
  72180. }
  72181. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  72182. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  72183. columnMallocFailure(pStmt);
  72184. return val;
  72185. }
  72186. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  72187. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  72188. columnMallocFailure(pStmt);
  72189. return val;
  72190. }
  72191. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  72192. double val = sqlite3_value_double( columnMem(pStmt,i) );
  72193. columnMallocFailure(pStmt);
  72194. return val;
  72195. }
  72196. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  72197. int val = sqlite3_value_int( columnMem(pStmt,i) );
  72198. columnMallocFailure(pStmt);
  72199. return val;
  72200. }
  72201. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  72202. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  72203. columnMallocFailure(pStmt);
  72204. return val;
  72205. }
  72206. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  72207. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  72208. columnMallocFailure(pStmt);
  72209. return val;
  72210. }
  72211. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  72212. Mem *pOut = columnMem(pStmt, i);
  72213. if( pOut->flags&MEM_Static ){
  72214. pOut->flags &= ~MEM_Static;
  72215. pOut->flags |= MEM_Ephem;
  72216. }
  72217. columnMallocFailure(pStmt);
  72218. return (sqlite3_value *)pOut;
  72219. }
  72220. #ifndef SQLITE_OMIT_UTF16
  72221. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  72222. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  72223. columnMallocFailure(pStmt);
  72224. return val;
  72225. }
  72226. #endif /* SQLITE_OMIT_UTF16 */
  72227. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  72228. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  72229. columnMallocFailure(pStmt);
  72230. return iType;
  72231. }
  72232. /*
  72233. ** Convert the N-th element of pStmt->pColName[] into a string using
  72234. ** xFunc() then return that string. If N is out of range, return 0.
  72235. **
  72236. ** There are up to 5 names for each column. useType determines which
  72237. ** name is returned. Here are the names:
  72238. **
  72239. ** 0 The column name as it should be displayed for output
  72240. ** 1 The datatype name for the column
  72241. ** 2 The name of the database that the column derives from
  72242. ** 3 The name of the table that the column derives from
  72243. ** 4 The name of the table column that the result column derives from
  72244. **
  72245. ** If the result is not a simple column reference (if it is an expression
  72246. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  72247. */
  72248. static const void *columnName(
  72249. sqlite3_stmt *pStmt,
  72250. int N,
  72251. const void *(*xFunc)(Mem*),
  72252. int useType
  72253. ){
  72254. const void *ret;
  72255. Vdbe *p;
  72256. int n;
  72257. sqlite3 *db;
  72258. #ifdef SQLITE_ENABLE_API_ARMOR
  72259. if( pStmt==0 ){
  72260. (void)SQLITE_MISUSE_BKPT;
  72261. return 0;
  72262. }
  72263. #endif
  72264. ret = 0;
  72265. p = (Vdbe *)pStmt;
  72266. db = p->db;
  72267. assert( db!=0 );
  72268. n = sqlite3_column_count(pStmt);
  72269. if( N<n && N>=0 ){
  72270. N += useType*n;
  72271. sqlite3_mutex_enter(db->mutex);
  72272. assert( db->mallocFailed==0 );
  72273. ret = xFunc(&p->aColName[N]);
  72274. /* A malloc may have failed inside of the xFunc() call. If this
  72275. ** is the case, clear the mallocFailed flag and return NULL.
  72276. */
  72277. if( db->mallocFailed ){
  72278. sqlite3OomClear(db);
  72279. ret = 0;
  72280. }
  72281. sqlite3_mutex_leave(db->mutex);
  72282. }
  72283. return ret;
  72284. }
  72285. /*
  72286. ** Return the name of the Nth column of the result set returned by SQL
  72287. ** statement pStmt.
  72288. */
  72289. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  72290. return columnName(
  72291. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  72292. }
  72293. #ifndef SQLITE_OMIT_UTF16
  72294. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  72295. return columnName(
  72296. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  72297. }
  72298. #endif
  72299. /*
  72300. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  72301. ** not define OMIT_DECLTYPE.
  72302. */
  72303. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  72304. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  72305. and SQLITE_ENABLE_COLUMN_METADATA"
  72306. #endif
  72307. #ifndef SQLITE_OMIT_DECLTYPE
  72308. /*
  72309. ** Return the column declaration type (if applicable) of the 'i'th column
  72310. ** of the result set of SQL statement pStmt.
  72311. */
  72312. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  72313. return columnName(
  72314. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  72315. }
  72316. #ifndef SQLITE_OMIT_UTF16
  72317. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  72318. return columnName(
  72319. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  72320. }
  72321. #endif /* SQLITE_OMIT_UTF16 */
  72322. #endif /* SQLITE_OMIT_DECLTYPE */
  72323. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  72324. /*
  72325. ** Return the name of the database from which a result column derives.
  72326. ** NULL is returned if the result column is an expression or constant or
  72327. ** anything else which is not an unambiguous reference to a database column.
  72328. */
  72329. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  72330. return columnName(
  72331. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  72332. }
  72333. #ifndef SQLITE_OMIT_UTF16
  72334. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  72335. return columnName(
  72336. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  72337. }
  72338. #endif /* SQLITE_OMIT_UTF16 */
  72339. /*
  72340. ** Return the name of the table from which a result column derives.
  72341. ** NULL is returned if the result column is an expression or constant or
  72342. ** anything else which is not an unambiguous reference to a database column.
  72343. */
  72344. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  72345. return columnName(
  72346. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  72347. }
  72348. #ifndef SQLITE_OMIT_UTF16
  72349. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  72350. return columnName(
  72351. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  72352. }
  72353. #endif /* SQLITE_OMIT_UTF16 */
  72354. /*
  72355. ** Return the name of the table column from which a result column derives.
  72356. ** NULL is returned if the result column is an expression or constant or
  72357. ** anything else which is not an unambiguous reference to a database column.
  72358. */
  72359. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  72360. return columnName(
  72361. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  72362. }
  72363. #ifndef SQLITE_OMIT_UTF16
  72364. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  72365. return columnName(
  72366. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  72367. }
  72368. #endif /* SQLITE_OMIT_UTF16 */
  72369. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  72370. /******************************* sqlite3_bind_ ***************************
  72371. **
  72372. ** Routines used to attach values to wildcards in a compiled SQL statement.
  72373. */
  72374. /*
  72375. ** Unbind the value bound to variable i in virtual machine p. This is the
  72376. ** the same as binding a NULL value to the column. If the "i" parameter is
  72377. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  72378. **
  72379. ** A successful evaluation of this routine acquires the mutex on p.
  72380. ** the mutex is released if any kind of error occurs.
  72381. **
  72382. ** The error code stored in database p->db is overwritten with the return
  72383. ** value in any case.
  72384. */
  72385. static int vdbeUnbind(Vdbe *p, int i){
  72386. Mem *pVar;
  72387. if( vdbeSafetyNotNull(p) ){
  72388. return SQLITE_MISUSE_BKPT;
  72389. }
  72390. sqlite3_mutex_enter(p->db->mutex);
  72391. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  72392. sqlite3Error(p->db, SQLITE_MISUSE);
  72393. sqlite3_mutex_leave(p->db->mutex);
  72394. sqlite3_log(SQLITE_MISUSE,
  72395. "bind on a busy prepared statement: [%s]", p->zSql);
  72396. return SQLITE_MISUSE_BKPT;
  72397. }
  72398. if( i<1 || i>p->nVar ){
  72399. sqlite3Error(p->db, SQLITE_RANGE);
  72400. sqlite3_mutex_leave(p->db->mutex);
  72401. return SQLITE_RANGE;
  72402. }
  72403. i--;
  72404. pVar = &p->aVar[i];
  72405. sqlite3VdbeMemRelease(pVar);
  72406. pVar->flags = MEM_Null;
  72407. sqlite3Error(p->db, SQLITE_OK);
  72408. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  72409. ** binding a new value to this variable invalidates the current query plan.
  72410. **
  72411. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  72412. ** parameter in the WHERE clause might influence the choice of query plan
  72413. ** for a statement, then the statement will be automatically recompiled,
  72414. ** as if there had been a schema change, on the first sqlite3_step() call
  72415. ** following any change to the bindings of that parameter.
  72416. */
  72417. assert( p->isPrepareV2 || p->expmask==0 );
  72418. if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
  72419. p->expired = 1;
  72420. }
  72421. return SQLITE_OK;
  72422. }
  72423. /*
  72424. ** Bind a text or BLOB value.
  72425. */
  72426. static int bindText(
  72427. sqlite3_stmt *pStmt, /* The statement to bind against */
  72428. int i, /* Index of the parameter to bind */
  72429. const void *zData, /* Pointer to the data to be bound */
  72430. int nData, /* Number of bytes of data to be bound */
  72431. void (*xDel)(void*), /* Destructor for the data */
  72432. u8 encoding /* Encoding for the data */
  72433. ){
  72434. Vdbe *p = (Vdbe *)pStmt;
  72435. Mem *pVar;
  72436. int rc;
  72437. rc = vdbeUnbind(p, i);
  72438. if( rc==SQLITE_OK ){
  72439. if( zData!=0 ){
  72440. pVar = &p->aVar[i-1];
  72441. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  72442. if( rc==SQLITE_OK && encoding!=0 ){
  72443. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  72444. }
  72445. sqlite3Error(p->db, rc);
  72446. rc = sqlite3ApiExit(p->db, rc);
  72447. }
  72448. sqlite3_mutex_leave(p->db->mutex);
  72449. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  72450. xDel((void*)zData);
  72451. }
  72452. return rc;
  72453. }
  72454. /*
  72455. ** Bind a blob value to an SQL statement variable.
  72456. */
  72457. SQLITE_API int sqlite3_bind_blob(
  72458. sqlite3_stmt *pStmt,
  72459. int i,
  72460. const void *zData,
  72461. int nData,
  72462. void (*xDel)(void*)
  72463. ){
  72464. #ifdef SQLITE_ENABLE_API_ARMOR
  72465. if( nData<0 ) return SQLITE_MISUSE_BKPT;
  72466. #endif
  72467. return bindText(pStmt, i, zData, nData, xDel, 0);
  72468. }
  72469. SQLITE_API int sqlite3_bind_blob64(
  72470. sqlite3_stmt *pStmt,
  72471. int i,
  72472. const void *zData,
  72473. sqlite3_uint64 nData,
  72474. void (*xDel)(void*)
  72475. ){
  72476. assert( xDel!=SQLITE_DYNAMIC );
  72477. if( nData>0x7fffffff ){
  72478. return invokeValueDestructor(zData, xDel, 0);
  72479. }else{
  72480. return bindText(pStmt, i, zData, (int)nData, xDel, 0);
  72481. }
  72482. }
  72483. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  72484. int rc;
  72485. Vdbe *p = (Vdbe *)pStmt;
  72486. rc = vdbeUnbind(p, i);
  72487. if( rc==SQLITE_OK ){
  72488. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  72489. sqlite3_mutex_leave(p->db->mutex);
  72490. }
  72491. return rc;
  72492. }
  72493. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  72494. return sqlite3_bind_int64(p, i, (i64)iValue);
  72495. }
  72496. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  72497. int rc;
  72498. Vdbe *p = (Vdbe *)pStmt;
  72499. rc = vdbeUnbind(p, i);
  72500. if( rc==SQLITE_OK ){
  72501. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  72502. sqlite3_mutex_leave(p->db->mutex);
  72503. }
  72504. return rc;
  72505. }
  72506. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  72507. int rc;
  72508. Vdbe *p = (Vdbe*)pStmt;
  72509. rc = vdbeUnbind(p, i);
  72510. if( rc==SQLITE_OK ){
  72511. sqlite3_mutex_leave(p->db->mutex);
  72512. }
  72513. return rc;
  72514. }
  72515. SQLITE_API int sqlite3_bind_text(
  72516. sqlite3_stmt *pStmt,
  72517. int i,
  72518. const char *zData,
  72519. int nData,
  72520. void (*xDel)(void*)
  72521. ){
  72522. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  72523. }
  72524. SQLITE_API int sqlite3_bind_text64(
  72525. sqlite3_stmt *pStmt,
  72526. int i,
  72527. const char *zData,
  72528. sqlite3_uint64 nData,
  72529. void (*xDel)(void*),
  72530. unsigned char enc
  72531. ){
  72532. assert( xDel!=SQLITE_DYNAMIC );
  72533. if( nData>0x7fffffff ){
  72534. return invokeValueDestructor(zData, xDel, 0);
  72535. }else{
  72536. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  72537. return bindText(pStmt, i, zData, (int)nData, xDel, enc);
  72538. }
  72539. }
  72540. #ifndef SQLITE_OMIT_UTF16
  72541. SQLITE_API int sqlite3_bind_text16(
  72542. sqlite3_stmt *pStmt,
  72543. int i,
  72544. const void *zData,
  72545. int nData,
  72546. void (*xDel)(void*)
  72547. ){
  72548. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  72549. }
  72550. #endif /* SQLITE_OMIT_UTF16 */
  72551. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  72552. int rc;
  72553. switch( sqlite3_value_type((sqlite3_value*)pValue) ){
  72554. case SQLITE_INTEGER: {
  72555. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  72556. break;
  72557. }
  72558. case SQLITE_FLOAT: {
  72559. rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
  72560. break;
  72561. }
  72562. case SQLITE_BLOB: {
  72563. if( pValue->flags & MEM_Zero ){
  72564. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  72565. }else{
  72566. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  72567. }
  72568. break;
  72569. }
  72570. case SQLITE_TEXT: {
  72571. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  72572. pValue->enc);
  72573. break;
  72574. }
  72575. default: {
  72576. rc = sqlite3_bind_null(pStmt, i);
  72577. break;
  72578. }
  72579. }
  72580. return rc;
  72581. }
  72582. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  72583. int rc;
  72584. Vdbe *p = (Vdbe *)pStmt;
  72585. rc = vdbeUnbind(p, i);
  72586. if( rc==SQLITE_OK ){
  72587. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  72588. sqlite3_mutex_leave(p->db->mutex);
  72589. }
  72590. return rc;
  72591. }
  72592. SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
  72593. int rc;
  72594. Vdbe *p = (Vdbe *)pStmt;
  72595. sqlite3_mutex_enter(p->db->mutex);
  72596. if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  72597. rc = SQLITE_TOOBIG;
  72598. }else{
  72599. assert( (n & 0x7FFFFFFF)==n );
  72600. rc = sqlite3_bind_zeroblob(pStmt, i, n);
  72601. }
  72602. rc = sqlite3ApiExit(p->db, rc);
  72603. sqlite3_mutex_leave(p->db->mutex);
  72604. return rc;
  72605. }
  72606. /*
  72607. ** Return the number of wildcards that can be potentially bound to.
  72608. ** This routine is added to support DBD::SQLite.
  72609. */
  72610. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  72611. Vdbe *p = (Vdbe*)pStmt;
  72612. return p ? p->nVar : 0;
  72613. }
  72614. /*
  72615. ** Return the name of a wildcard parameter. Return NULL if the index
  72616. ** is out of range or if the wildcard is unnamed.
  72617. **
  72618. ** The result is always UTF-8.
  72619. */
  72620. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  72621. Vdbe *p = (Vdbe*)pStmt;
  72622. if( p==0 ) return 0;
  72623. return sqlite3VListNumToName(p->pVList, i);
  72624. }
  72625. /*
  72626. ** Given a wildcard parameter name, return the index of the variable
  72627. ** with that name. If there is no variable with the given name,
  72628. ** return 0.
  72629. */
  72630. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  72631. if( p==0 || zName==0 ) return 0;
  72632. return sqlite3VListNameToNum(p->pVList, zName, nName);
  72633. }
  72634. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  72635. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  72636. }
  72637. /*
  72638. ** Transfer all bindings from the first statement over to the second.
  72639. */
  72640. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  72641. Vdbe *pFrom = (Vdbe*)pFromStmt;
  72642. Vdbe *pTo = (Vdbe*)pToStmt;
  72643. int i;
  72644. assert( pTo->db==pFrom->db );
  72645. assert( pTo->nVar==pFrom->nVar );
  72646. sqlite3_mutex_enter(pTo->db->mutex);
  72647. for(i=0; i<pFrom->nVar; i++){
  72648. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  72649. }
  72650. sqlite3_mutex_leave(pTo->db->mutex);
  72651. return SQLITE_OK;
  72652. }
  72653. #ifndef SQLITE_OMIT_DEPRECATED
  72654. /*
  72655. ** Deprecated external interface. Internal/core SQLite code
  72656. ** should call sqlite3TransferBindings.
  72657. **
  72658. ** It is misuse to call this routine with statements from different
  72659. ** database connections. But as this is a deprecated interface, we
  72660. ** will not bother to check for that condition.
  72661. **
  72662. ** If the two statements contain a different number of bindings, then
  72663. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  72664. ** SQLITE_OK is returned.
  72665. */
  72666. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  72667. Vdbe *pFrom = (Vdbe*)pFromStmt;
  72668. Vdbe *pTo = (Vdbe*)pToStmt;
  72669. if( pFrom->nVar!=pTo->nVar ){
  72670. return SQLITE_ERROR;
  72671. }
  72672. assert( pTo->isPrepareV2 || pTo->expmask==0 );
  72673. if( pTo->expmask ){
  72674. pTo->expired = 1;
  72675. }
  72676. assert( pFrom->isPrepareV2 || pFrom->expmask==0 );
  72677. if( pFrom->expmask ){
  72678. pFrom->expired = 1;
  72679. }
  72680. return sqlite3TransferBindings(pFromStmt, pToStmt);
  72681. }
  72682. #endif
  72683. /*
  72684. ** Return the sqlite3* database handle to which the prepared statement given
  72685. ** in the argument belongs. This is the same database handle that was
  72686. ** the first argument to the sqlite3_prepare() that was used to create
  72687. ** the statement in the first place.
  72688. */
  72689. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  72690. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  72691. }
  72692. /*
  72693. ** Return true if the prepared statement is guaranteed to not modify the
  72694. ** database.
  72695. */
  72696. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  72697. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  72698. }
  72699. /*
  72700. ** Return true if the prepared statement is in need of being reset.
  72701. */
  72702. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  72703. Vdbe *v = (Vdbe*)pStmt;
  72704. return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
  72705. }
  72706. /*
  72707. ** Return a pointer to the next prepared statement after pStmt associated
  72708. ** with database connection pDb. If pStmt is NULL, return the first
  72709. ** prepared statement for the database connection. Return NULL if there
  72710. ** are no more.
  72711. */
  72712. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  72713. sqlite3_stmt *pNext;
  72714. #ifdef SQLITE_ENABLE_API_ARMOR
  72715. if( !sqlite3SafetyCheckOk(pDb) ){
  72716. (void)SQLITE_MISUSE_BKPT;
  72717. return 0;
  72718. }
  72719. #endif
  72720. sqlite3_mutex_enter(pDb->mutex);
  72721. if( pStmt==0 ){
  72722. pNext = (sqlite3_stmt*)pDb->pVdbe;
  72723. }else{
  72724. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  72725. }
  72726. sqlite3_mutex_leave(pDb->mutex);
  72727. return pNext;
  72728. }
  72729. /*
  72730. ** Return the value of a status counter for a prepared statement
  72731. */
  72732. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  72733. Vdbe *pVdbe = (Vdbe*)pStmt;
  72734. u32 v;
  72735. #ifdef SQLITE_ENABLE_API_ARMOR
  72736. if( !pStmt ){
  72737. (void)SQLITE_MISUSE_BKPT;
  72738. return 0;
  72739. }
  72740. #endif
  72741. v = pVdbe->aCounter[op];
  72742. if( resetFlag ) pVdbe->aCounter[op] = 0;
  72743. return (int)v;
  72744. }
  72745. /*
  72746. ** Return the SQL associated with a prepared statement
  72747. */
  72748. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  72749. Vdbe *p = (Vdbe *)pStmt;
  72750. return p ? p->zSql : 0;
  72751. }
  72752. /*
  72753. ** Return the SQL associated with a prepared statement with
  72754. ** bound parameters expanded. Space to hold the returned string is
  72755. ** obtained from sqlite3_malloc(). The caller is responsible for
  72756. ** freeing the returned string by passing it to sqlite3_free().
  72757. **
  72758. ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
  72759. ** expanded bound parameters.
  72760. */
  72761. SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
  72762. #ifdef SQLITE_OMIT_TRACE
  72763. return 0;
  72764. #else
  72765. char *z = 0;
  72766. const char *zSql = sqlite3_sql(pStmt);
  72767. if( zSql ){
  72768. Vdbe *p = (Vdbe *)pStmt;
  72769. sqlite3_mutex_enter(p->db->mutex);
  72770. z = sqlite3VdbeExpandSql(p, zSql);
  72771. sqlite3_mutex_leave(p->db->mutex);
  72772. }
  72773. return z;
  72774. #endif
  72775. }
  72776. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  72777. /*
  72778. ** Allocate and populate an UnpackedRecord structure based on the serialized
  72779. ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
  72780. ** if successful, or a NULL pointer if an OOM error is encountered.
  72781. */
  72782. static UnpackedRecord *vdbeUnpackRecord(
  72783. KeyInfo *pKeyInfo,
  72784. int nKey,
  72785. const void *pKey
  72786. ){
  72787. UnpackedRecord *pRet; /* Return value */
  72788. pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  72789. if( pRet ){
  72790. memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nField+1));
  72791. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
  72792. }
  72793. return pRet;
  72794. }
  72795. /*
  72796. ** This function is called from within a pre-update callback to retrieve
  72797. ** a field of the row currently being updated or deleted.
  72798. */
  72799. SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
  72800. PreUpdate *p = db->pPreUpdate;
  72801. Mem *pMem;
  72802. int rc = SQLITE_OK;
  72803. /* Test that this call is being made from within an SQLITE_DELETE or
  72804. ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
  72805. if( !p || p->op==SQLITE_INSERT ){
  72806. rc = SQLITE_MISUSE_BKPT;
  72807. goto preupdate_old_out;
  72808. }
  72809. if( p->pPk ){
  72810. iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
  72811. }
  72812. if( iIdx>=p->pCsr->nField || iIdx<0 ){
  72813. rc = SQLITE_RANGE;
  72814. goto preupdate_old_out;
  72815. }
  72816. /* If the old.* record has not yet been loaded into memory, do so now. */
  72817. if( p->pUnpacked==0 ){
  72818. u32 nRec;
  72819. u8 *aRec;
  72820. nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
  72821. aRec = sqlite3DbMallocRaw(db, nRec);
  72822. if( !aRec ) goto preupdate_old_out;
  72823. rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
  72824. if( rc==SQLITE_OK ){
  72825. p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
  72826. if( !p->pUnpacked ) rc = SQLITE_NOMEM;
  72827. }
  72828. if( rc!=SQLITE_OK ){
  72829. sqlite3DbFree(db, aRec);
  72830. goto preupdate_old_out;
  72831. }
  72832. p->aRecord = aRec;
  72833. }
  72834. pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
  72835. if( iIdx==p->pTab->iPKey ){
  72836. sqlite3VdbeMemSetInt64(pMem, p->iKey1);
  72837. }else if( iIdx>=p->pUnpacked->nField ){
  72838. *ppValue = (sqlite3_value *)columnNullValue();
  72839. }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
  72840. if( pMem->flags & MEM_Int ){
  72841. sqlite3VdbeMemRealify(pMem);
  72842. }
  72843. }
  72844. preupdate_old_out:
  72845. sqlite3Error(db, rc);
  72846. return sqlite3ApiExit(db, rc);
  72847. }
  72848. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  72849. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  72850. /*
  72851. ** This function is called from within a pre-update callback to retrieve
  72852. ** the number of columns in the row being updated, deleted or inserted.
  72853. */
  72854. SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
  72855. PreUpdate *p = db->pPreUpdate;
  72856. return (p ? p->keyinfo.nField : 0);
  72857. }
  72858. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  72859. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  72860. /*
  72861. ** This function is designed to be called from within a pre-update callback
  72862. ** only. It returns zero if the change that caused the callback was made
  72863. ** immediately by a user SQL statement. Or, if the change was made by a
  72864. ** trigger program, it returns the number of trigger programs currently
  72865. ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
  72866. ** top-level trigger etc.).
  72867. **
  72868. ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
  72869. ** or SET DEFAULT action is considered a trigger.
  72870. */
  72871. SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
  72872. PreUpdate *p = db->pPreUpdate;
  72873. return (p ? p->v->nFrame : 0);
  72874. }
  72875. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  72876. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  72877. /*
  72878. ** This function is called from within a pre-update callback to retrieve
  72879. ** a field of the row currently being updated or inserted.
  72880. */
  72881. SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
  72882. PreUpdate *p = db->pPreUpdate;
  72883. int rc = SQLITE_OK;
  72884. Mem *pMem;
  72885. if( !p || p->op==SQLITE_DELETE ){
  72886. rc = SQLITE_MISUSE_BKPT;
  72887. goto preupdate_new_out;
  72888. }
  72889. if( p->pPk && p->op!=SQLITE_UPDATE ){
  72890. iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
  72891. }
  72892. if( iIdx>=p->pCsr->nField || iIdx<0 ){
  72893. rc = SQLITE_RANGE;
  72894. goto preupdate_new_out;
  72895. }
  72896. if( p->op==SQLITE_INSERT ){
  72897. /* For an INSERT, memory cell p->iNewReg contains the serialized record
  72898. ** that is being inserted. Deserialize it. */
  72899. UnpackedRecord *pUnpack = p->pNewUnpacked;
  72900. if( !pUnpack ){
  72901. Mem *pData = &p->v->aMem[p->iNewReg];
  72902. rc = ExpandBlob(pData);
  72903. if( rc!=SQLITE_OK ) goto preupdate_new_out;
  72904. pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
  72905. if( !pUnpack ){
  72906. rc = SQLITE_NOMEM;
  72907. goto preupdate_new_out;
  72908. }
  72909. p->pNewUnpacked = pUnpack;
  72910. }
  72911. pMem = &pUnpack->aMem[iIdx];
  72912. if( iIdx==p->pTab->iPKey ){
  72913. sqlite3VdbeMemSetInt64(pMem, p->iKey2);
  72914. }else if( iIdx>=pUnpack->nField ){
  72915. pMem = (sqlite3_value *)columnNullValue();
  72916. }
  72917. }else{
  72918. /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
  72919. ** value. Make a copy of the cell contents and return a pointer to it.
  72920. ** It is not safe to return a pointer to the memory cell itself as the
  72921. ** caller may modify the value text encoding.
  72922. */
  72923. assert( p->op==SQLITE_UPDATE );
  72924. if( !p->aNew ){
  72925. p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
  72926. if( !p->aNew ){
  72927. rc = SQLITE_NOMEM;
  72928. goto preupdate_new_out;
  72929. }
  72930. }
  72931. assert( iIdx>=0 && iIdx<p->pCsr->nField );
  72932. pMem = &p->aNew[iIdx];
  72933. if( pMem->flags==0 ){
  72934. if( iIdx==p->pTab->iPKey ){
  72935. sqlite3VdbeMemSetInt64(pMem, p->iKey2);
  72936. }else{
  72937. rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
  72938. if( rc!=SQLITE_OK ) goto preupdate_new_out;
  72939. }
  72940. }
  72941. }
  72942. *ppValue = pMem;
  72943. preupdate_new_out:
  72944. sqlite3Error(db, rc);
  72945. return sqlite3ApiExit(db, rc);
  72946. }
  72947. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  72948. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  72949. /*
  72950. ** Return status data for a single loop within query pStmt.
  72951. */
  72952. SQLITE_API int sqlite3_stmt_scanstatus(
  72953. sqlite3_stmt *pStmt, /* Prepared statement being queried */
  72954. int idx, /* Index of loop to report on */
  72955. int iScanStatusOp, /* Which metric to return */
  72956. void *pOut /* OUT: Write the answer here */
  72957. ){
  72958. Vdbe *p = (Vdbe*)pStmt;
  72959. ScanStatus *pScan;
  72960. if( idx<0 || idx>=p->nScan ) return 1;
  72961. pScan = &p->aScan[idx];
  72962. switch( iScanStatusOp ){
  72963. case SQLITE_SCANSTAT_NLOOP: {
  72964. *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
  72965. break;
  72966. }
  72967. case SQLITE_SCANSTAT_NVISIT: {
  72968. *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
  72969. break;
  72970. }
  72971. case SQLITE_SCANSTAT_EST: {
  72972. double r = 1.0;
  72973. LogEst x = pScan->nEst;
  72974. while( x<100 ){
  72975. x += 10;
  72976. r *= 0.5;
  72977. }
  72978. *(double*)pOut = r*sqlite3LogEstToInt(x);
  72979. break;
  72980. }
  72981. case SQLITE_SCANSTAT_NAME: {
  72982. *(const char**)pOut = pScan->zName;
  72983. break;
  72984. }
  72985. case SQLITE_SCANSTAT_EXPLAIN: {
  72986. if( pScan->addrExplain ){
  72987. *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
  72988. }else{
  72989. *(const char**)pOut = 0;
  72990. }
  72991. break;
  72992. }
  72993. case SQLITE_SCANSTAT_SELECTID: {
  72994. if( pScan->addrExplain ){
  72995. *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
  72996. }else{
  72997. *(int*)pOut = -1;
  72998. }
  72999. break;
  73000. }
  73001. default: {
  73002. return 1;
  73003. }
  73004. }
  73005. return 0;
  73006. }
  73007. /*
  73008. ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
  73009. */
  73010. SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
  73011. Vdbe *p = (Vdbe*)pStmt;
  73012. memset(p->anExec, 0, p->nOp * sizeof(i64));
  73013. }
  73014. #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
  73015. /************** End of vdbeapi.c *********************************************/
  73016. /************** Begin file vdbetrace.c ***************************************/
  73017. /*
  73018. ** 2009 November 25
  73019. **
  73020. ** The author disclaims copyright to this source code. In place of
  73021. ** a legal notice, here is a blessing:
  73022. **
  73023. ** May you do good and not evil.
  73024. ** May you find forgiveness for yourself and forgive others.
  73025. ** May you share freely, never taking more than you give.
  73026. **
  73027. *************************************************************************
  73028. **
  73029. ** This file contains code used to insert the values of host parameters
  73030. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  73031. **
  73032. ** The Vdbe parse-tree explainer is also found here.
  73033. */
  73034. /* #include "sqliteInt.h" */
  73035. /* #include "vdbeInt.h" */
  73036. #ifndef SQLITE_OMIT_TRACE
  73037. /*
  73038. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  73039. ** bytes in this text up to but excluding the first character in
  73040. ** a host parameter. If the text contains no host parameters, return
  73041. ** the total number of bytes in the text.
  73042. */
  73043. static int findNextHostParameter(const char *zSql, int *pnToken){
  73044. int tokenType;
  73045. int nTotal = 0;
  73046. int n;
  73047. *pnToken = 0;
  73048. while( zSql[0] ){
  73049. n = sqlite3GetToken((u8*)zSql, &tokenType);
  73050. assert( n>0 && tokenType!=TK_ILLEGAL );
  73051. if( tokenType==TK_VARIABLE ){
  73052. *pnToken = n;
  73053. break;
  73054. }
  73055. nTotal += n;
  73056. zSql += n;
  73057. }
  73058. return nTotal;
  73059. }
  73060. /*
  73061. ** This function returns a pointer to a nul-terminated string in memory
  73062. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  73063. ** string contains a copy of zRawSql but with host parameters expanded to
  73064. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  73065. ** then the returned string holds a copy of zRawSql with "-- " prepended
  73066. ** to each line of text.
  73067. **
  73068. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  73069. ** then long strings and blobs are truncated to that many bytes. This
  73070. ** can be used to prevent unreasonably large trace strings when dealing
  73071. ** with large (multi-megabyte) strings and blobs.
  73072. **
  73073. ** The calling function is responsible for making sure the memory returned
  73074. ** is eventually freed.
  73075. **
  73076. ** ALGORITHM: Scan the input string looking for host parameters in any of
  73077. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  73078. ** string literals, quoted identifier names, and comments. For text forms,
  73079. ** the host parameter index is found by scanning the prepared
  73080. ** statement for the corresponding OP_Variable opcode. Once the host
  73081. ** parameter index is known, locate the value in p->aVar[]. Then render
  73082. ** the value as a literal in place of the host parameter name.
  73083. */
  73084. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  73085. Vdbe *p, /* The prepared statement being evaluated */
  73086. const char *zRawSql /* Raw text of the SQL statement */
  73087. ){
  73088. sqlite3 *db; /* The database connection */
  73089. int idx = 0; /* Index of a host parameter */
  73090. int nextIndex = 1; /* Index of next ? host parameter */
  73091. int n; /* Length of a token prefix */
  73092. int nToken; /* Length of the parameter token */
  73093. int i; /* Loop counter */
  73094. Mem *pVar; /* Value of a host parameter */
  73095. StrAccum out; /* Accumulate the output here */
  73096. #ifndef SQLITE_OMIT_UTF16
  73097. Mem utf8; /* Used to convert UTF16 parameters into UTF8 for display */
  73098. #endif
  73099. char zBase[100]; /* Initial working space */
  73100. db = p->db;
  73101. sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
  73102. db->aLimit[SQLITE_LIMIT_LENGTH]);
  73103. if( db->nVdbeExec>1 ){
  73104. while( *zRawSql ){
  73105. const char *zStart = zRawSql;
  73106. while( *(zRawSql++)!='\n' && *zRawSql );
  73107. sqlite3StrAccumAppend(&out, "-- ", 3);
  73108. assert( (zRawSql - zStart) > 0 );
  73109. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  73110. }
  73111. }else if( p->nVar==0 ){
  73112. sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
  73113. }else{
  73114. while( zRawSql[0] ){
  73115. n = findNextHostParameter(zRawSql, &nToken);
  73116. assert( n>0 );
  73117. sqlite3StrAccumAppend(&out, zRawSql, n);
  73118. zRawSql += n;
  73119. assert( zRawSql[0] || nToken==0 );
  73120. if( nToken==0 ) break;
  73121. if( zRawSql[0]=='?' ){
  73122. if( nToken>1 ){
  73123. assert( sqlite3Isdigit(zRawSql[1]) );
  73124. sqlite3GetInt32(&zRawSql[1], &idx);
  73125. }else{
  73126. idx = nextIndex;
  73127. }
  73128. }else{
  73129. assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
  73130. zRawSql[0]=='@' || zRawSql[0]=='#' );
  73131. testcase( zRawSql[0]==':' );
  73132. testcase( zRawSql[0]=='$' );
  73133. testcase( zRawSql[0]=='@' );
  73134. testcase( zRawSql[0]=='#' );
  73135. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  73136. assert( idx>0 );
  73137. }
  73138. zRawSql += nToken;
  73139. nextIndex = idx + 1;
  73140. assert( idx>0 && idx<=p->nVar );
  73141. pVar = &p->aVar[idx-1];
  73142. if( pVar->flags & MEM_Null ){
  73143. sqlite3StrAccumAppend(&out, "NULL", 4);
  73144. }else if( pVar->flags & MEM_Int ){
  73145. sqlite3XPrintf(&out, "%lld", pVar->u.i);
  73146. }else if( pVar->flags & MEM_Real ){
  73147. sqlite3XPrintf(&out, "%!.15g", pVar->u.r);
  73148. }else if( pVar->flags & MEM_Str ){
  73149. int nOut; /* Number of bytes of the string text to include in output */
  73150. #ifndef SQLITE_OMIT_UTF16
  73151. u8 enc = ENC(db);
  73152. if( enc!=SQLITE_UTF8 ){
  73153. memset(&utf8, 0, sizeof(utf8));
  73154. utf8.db = db;
  73155. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  73156. if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
  73157. out.accError = STRACCUM_NOMEM;
  73158. out.nAlloc = 0;
  73159. }
  73160. pVar = &utf8;
  73161. }
  73162. #endif
  73163. nOut = pVar->n;
  73164. #ifdef SQLITE_TRACE_SIZE_LIMIT
  73165. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  73166. nOut = SQLITE_TRACE_SIZE_LIMIT;
  73167. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  73168. }
  73169. #endif
  73170. sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
  73171. #ifdef SQLITE_TRACE_SIZE_LIMIT
  73172. if( nOut<pVar->n ){
  73173. sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  73174. }
  73175. #endif
  73176. #ifndef SQLITE_OMIT_UTF16
  73177. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  73178. #endif
  73179. }else if( pVar->flags & MEM_Zero ){
  73180. sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
  73181. }else{
  73182. int nOut; /* Number of bytes of the blob to include in output */
  73183. assert( pVar->flags & MEM_Blob );
  73184. sqlite3StrAccumAppend(&out, "x'", 2);
  73185. nOut = pVar->n;
  73186. #ifdef SQLITE_TRACE_SIZE_LIMIT
  73187. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  73188. #endif
  73189. for(i=0; i<nOut; i++){
  73190. sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
  73191. }
  73192. sqlite3StrAccumAppend(&out, "'", 1);
  73193. #ifdef SQLITE_TRACE_SIZE_LIMIT
  73194. if( nOut<pVar->n ){
  73195. sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  73196. }
  73197. #endif
  73198. }
  73199. }
  73200. }
  73201. if( out.accError ) sqlite3StrAccumReset(&out);
  73202. return sqlite3StrAccumFinish(&out);
  73203. }
  73204. #endif /* #ifndef SQLITE_OMIT_TRACE */
  73205. /************** End of vdbetrace.c *******************************************/
  73206. /************** Begin file vdbe.c ********************************************/
  73207. /*
  73208. ** 2001 September 15
  73209. **
  73210. ** The author disclaims copyright to this source code. In place of
  73211. ** a legal notice, here is a blessing:
  73212. **
  73213. ** May you do good and not evil.
  73214. ** May you find forgiveness for yourself and forgive others.
  73215. ** May you share freely, never taking more than you give.
  73216. **
  73217. *************************************************************************
  73218. ** The code in this file implements the function that runs the
  73219. ** bytecode of a prepared statement.
  73220. **
  73221. ** Various scripts scan this source file in order to generate HTML
  73222. ** documentation, headers files, or other derived files. The formatting
  73223. ** of the code in this file is, therefore, important. See other comments
  73224. ** in this file for details. If in doubt, do not deviate from existing
  73225. ** commenting and indentation practices when changing or adding code.
  73226. */
  73227. /* #include "sqliteInt.h" */
  73228. /* #include "vdbeInt.h" */
  73229. /*
  73230. ** Invoke this macro on memory cells just prior to changing the
  73231. ** value of the cell. This macro verifies that shallow copies are
  73232. ** not misused. A shallow copy of a string or blob just copies a
  73233. ** pointer to the string or blob, not the content. If the original
  73234. ** is changed while the copy is still in use, the string or blob might
  73235. ** be changed out from under the copy. This macro verifies that nothing
  73236. ** like that ever happens.
  73237. */
  73238. #ifdef SQLITE_DEBUG
  73239. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  73240. #else
  73241. # define memAboutToChange(P,M)
  73242. #endif
  73243. /*
  73244. ** The following global variable is incremented every time a cursor
  73245. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  73246. ** procedures use this information to make sure that indices are
  73247. ** working correctly. This variable has no function other than to
  73248. ** help verify the correct operation of the library.
  73249. */
  73250. #ifdef SQLITE_TEST
  73251. SQLITE_API int sqlite3_search_count = 0;
  73252. #endif
  73253. /*
  73254. ** When this global variable is positive, it gets decremented once before
  73255. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  73256. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  73257. **
  73258. ** This facility is used for testing purposes only. It does not function
  73259. ** in an ordinary build.
  73260. */
  73261. #ifdef SQLITE_TEST
  73262. SQLITE_API int sqlite3_interrupt_count = 0;
  73263. #endif
  73264. /*
  73265. ** The next global variable is incremented each type the OP_Sort opcode
  73266. ** is executed. The test procedures use this information to make sure that
  73267. ** sorting is occurring or not occurring at appropriate times. This variable
  73268. ** has no function other than to help verify the correct operation of the
  73269. ** library.
  73270. */
  73271. #ifdef SQLITE_TEST
  73272. SQLITE_API int sqlite3_sort_count = 0;
  73273. #endif
  73274. /*
  73275. ** The next global variable records the size of the largest MEM_Blob
  73276. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  73277. ** use this information to make sure that the zero-blob functionality
  73278. ** is working correctly. This variable has no function other than to
  73279. ** help verify the correct operation of the library.
  73280. */
  73281. #ifdef SQLITE_TEST
  73282. SQLITE_API int sqlite3_max_blobsize = 0;
  73283. static void updateMaxBlobsize(Mem *p){
  73284. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  73285. sqlite3_max_blobsize = p->n;
  73286. }
  73287. }
  73288. #endif
  73289. /*
  73290. ** This macro evaluates to true if either the update hook or the preupdate
  73291. ** hook are enabled for database connect DB.
  73292. */
  73293. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  73294. # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
  73295. #else
  73296. # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
  73297. #endif
  73298. /*
  73299. ** The next global variable is incremented each time the OP_Found opcode
  73300. ** is executed. This is used to test whether or not the foreign key
  73301. ** operation implemented using OP_FkIsZero is working. This variable
  73302. ** has no function other than to help verify the correct operation of the
  73303. ** library.
  73304. */
  73305. #ifdef SQLITE_TEST
  73306. SQLITE_API int sqlite3_found_count = 0;
  73307. #endif
  73308. /*
  73309. ** Test a register to see if it exceeds the current maximum blob size.
  73310. ** If it does, record the new maximum blob size.
  73311. */
  73312. #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
  73313. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  73314. #else
  73315. # define UPDATE_MAX_BLOBSIZE(P)
  73316. #endif
  73317. /*
  73318. ** Invoke the VDBE coverage callback, if that callback is defined. This
  73319. ** feature is used for test suite validation only and does not appear an
  73320. ** production builds.
  73321. **
  73322. ** M is an integer, 2 or 3, that indices how many different ways the
  73323. ** branch can go. It is usually 2. "I" is the direction the branch
  73324. ** goes. 0 means falls through. 1 means branch is taken. 2 means the
  73325. ** second alternative branch is taken.
  73326. **
  73327. ** iSrcLine is the source code line (from the __LINE__ macro) that
  73328. ** generated the VDBE instruction. This instrumentation assumes that all
  73329. ** source code is in a single file (the amalgamation). Special values 1
  73330. ** and 2 for the iSrcLine parameter mean that this particular branch is
  73331. ** always taken or never taken, respectively.
  73332. */
  73333. #if !defined(SQLITE_VDBE_COVERAGE)
  73334. # define VdbeBranchTaken(I,M)
  73335. #else
  73336. # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
  73337. static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
  73338. if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
  73339. M = iSrcLine;
  73340. /* Assert the truth of VdbeCoverageAlwaysTaken() and
  73341. ** VdbeCoverageNeverTaken() */
  73342. assert( (M & I)==I );
  73343. }else{
  73344. if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
  73345. sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
  73346. iSrcLine,I,M);
  73347. }
  73348. }
  73349. #endif
  73350. /*
  73351. ** Convert the given register into a string if it isn't one
  73352. ** already. Return non-zero if a malloc() fails.
  73353. */
  73354. #define Stringify(P, enc) \
  73355. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
  73356. { goto no_mem; }
  73357. /*
  73358. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  73359. ** a pointer to a dynamically allocated string where some other entity
  73360. ** is responsible for deallocating that string. Because the register
  73361. ** does not control the string, it might be deleted without the register
  73362. ** knowing it.
  73363. **
  73364. ** This routine converts an ephemeral string into a dynamically allocated
  73365. ** string that the register itself controls. In other words, it
  73366. ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
  73367. */
  73368. #define Deephemeralize(P) \
  73369. if( ((P)->flags&MEM_Ephem)!=0 \
  73370. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  73371. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  73372. #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
  73373. /*
  73374. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  73375. ** if we run out of memory.
  73376. */
  73377. static VdbeCursor *allocateCursor(
  73378. Vdbe *p, /* The virtual machine */
  73379. int iCur, /* Index of the new VdbeCursor */
  73380. int nField, /* Number of fields in the table or index */
  73381. int iDb, /* Database the cursor belongs to, or -1 */
  73382. u8 eCurType /* Type of the new cursor */
  73383. ){
  73384. /* Find the memory cell that will be used to store the blob of memory
  73385. ** required for this VdbeCursor structure. It is convenient to use a
  73386. ** vdbe memory cell to manage the memory allocation required for a
  73387. ** VdbeCursor structure for the following reasons:
  73388. **
  73389. ** * Sometimes cursor numbers are used for a couple of different
  73390. ** purposes in a vdbe program. The different uses might require
  73391. ** different sized allocations. Memory cells provide growable
  73392. ** allocations.
  73393. **
  73394. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  73395. ** be freed lazily via the sqlite3_release_memory() API. This
  73396. ** minimizes the number of malloc calls made by the system.
  73397. **
  73398. ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
  73399. ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
  73400. ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
  73401. */
  73402. Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
  73403. int nByte;
  73404. VdbeCursor *pCx = 0;
  73405. nByte =
  73406. ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
  73407. (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
  73408. assert( iCur>=0 && iCur<p->nCursor );
  73409. if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
  73410. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  73411. p->apCsr[iCur] = 0;
  73412. }
  73413. if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  73414. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  73415. memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
  73416. pCx->eCurType = eCurType;
  73417. pCx->iDb = iDb;
  73418. pCx->nField = nField;
  73419. pCx->aOffset = &pCx->aType[nField];
  73420. if( eCurType==CURTYPE_BTREE ){
  73421. pCx->uc.pCursor = (BtCursor*)
  73422. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
  73423. sqlite3BtreeCursorZero(pCx->uc.pCursor);
  73424. }
  73425. }
  73426. return pCx;
  73427. }
  73428. /*
  73429. ** Try to convert a value into a numeric representation if we can
  73430. ** do so without loss of information. In other words, if the string
  73431. ** looks like a number, convert it into a number. If it does not
  73432. ** look like a number, leave it alone.
  73433. **
  73434. ** If the bTryForInt flag is true, then extra effort is made to give
  73435. ** an integer representation. Strings that look like floating point
  73436. ** values but which have no fractional component (example: '48.00')
  73437. ** will have a MEM_Int representation when bTryForInt is true.
  73438. **
  73439. ** If bTryForInt is false, then if the input string contains a decimal
  73440. ** point or exponential notation, the result is only MEM_Real, even
  73441. ** if there is an exact integer representation of the quantity.
  73442. */
  73443. static void applyNumericAffinity(Mem *pRec, int bTryForInt){
  73444. double rValue;
  73445. i64 iValue;
  73446. u8 enc = pRec->enc;
  73447. assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
  73448. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  73449. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  73450. pRec->u.i = iValue;
  73451. pRec->flags |= MEM_Int;
  73452. }else{
  73453. pRec->u.r = rValue;
  73454. pRec->flags |= MEM_Real;
  73455. if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
  73456. }
  73457. }
  73458. /*
  73459. ** Processing is determine by the affinity parameter:
  73460. **
  73461. ** SQLITE_AFF_INTEGER:
  73462. ** SQLITE_AFF_REAL:
  73463. ** SQLITE_AFF_NUMERIC:
  73464. ** Try to convert pRec to an integer representation or a
  73465. ** floating-point representation if an integer representation
  73466. ** is not possible. Note that the integer representation is
  73467. ** always preferred, even if the affinity is REAL, because
  73468. ** an integer representation is more space efficient on disk.
  73469. **
  73470. ** SQLITE_AFF_TEXT:
  73471. ** Convert pRec to a text representation.
  73472. **
  73473. ** SQLITE_AFF_BLOB:
  73474. ** No-op. pRec is unchanged.
  73475. */
  73476. static void applyAffinity(
  73477. Mem *pRec, /* The value to apply affinity to */
  73478. char affinity, /* The affinity to be applied */
  73479. u8 enc /* Use this text encoding */
  73480. ){
  73481. if( affinity>=SQLITE_AFF_NUMERIC ){
  73482. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  73483. || affinity==SQLITE_AFF_NUMERIC );
  73484. if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  73485. if( (pRec->flags & MEM_Real)==0 ){
  73486. if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
  73487. }else{
  73488. sqlite3VdbeIntegerAffinity(pRec);
  73489. }
  73490. }
  73491. }else if( affinity==SQLITE_AFF_TEXT ){
  73492. /* Only attempt the conversion to TEXT if there is an integer or real
  73493. ** representation (blob and NULL do not get converted) but no string
  73494. ** representation. It would be harmless to repeat the conversion if
  73495. ** there is already a string rep, but it is pointless to waste those
  73496. ** CPU cycles. */
  73497. if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
  73498. if( (pRec->flags&(MEM_Real|MEM_Int)) ){
  73499. sqlite3VdbeMemStringify(pRec, enc, 1);
  73500. }
  73501. }
  73502. pRec->flags &= ~(MEM_Real|MEM_Int);
  73503. }
  73504. }
  73505. /*
  73506. ** Try to convert the type of a function argument or a result column
  73507. ** into a numeric representation. Use either INTEGER or REAL whichever
  73508. ** is appropriate. But only do the conversion if it is possible without
  73509. ** loss of information and return the revised type of the argument.
  73510. */
  73511. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  73512. int eType = sqlite3_value_type(pVal);
  73513. if( eType==SQLITE_TEXT ){
  73514. Mem *pMem = (Mem*)pVal;
  73515. applyNumericAffinity(pMem, 0);
  73516. eType = sqlite3_value_type(pVal);
  73517. }
  73518. return eType;
  73519. }
  73520. /*
  73521. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  73522. ** not the internal Mem* type.
  73523. */
  73524. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  73525. sqlite3_value *pVal,
  73526. u8 affinity,
  73527. u8 enc
  73528. ){
  73529. applyAffinity((Mem *)pVal, affinity, enc);
  73530. }
  73531. /*
  73532. ** pMem currently only holds a string type (or maybe a BLOB that we can
  73533. ** interpret as a string if we want to). Compute its corresponding
  73534. ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
  73535. ** accordingly.
  73536. */
  73537. static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
  73538. assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
  73539. assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
  73540. if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
  73541. return 0;
  73542. }
  73543. if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
  73544. return MEM_Int;
  73545. }
  73546. return MEM_Real;
  73547. }
  73548. /*
  73549. ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
  73550. ** none.
  73551. **
  73552. ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
  73553. ** But it does set pMem->u.r and pMem->u.i appropriately.
  73554. */
  73555. static u16 numericType(Mem *pMem){
  73556. if( pMem->flags & (MEM_Int|MEM_Real) ){
  73557. return pMem->flags & (MEM_Int|MEM_Real);
  73558. }
  73559. if( pMem->flags & (MEM_Str|MEM_Blob) ){
  73560. return computeNumericType(pMem);
  73561. }
  73562. return 0;
  73563. }
  73564. #ifdef SQLITE_DEBUG
  73565. /*
  73566. ** Write a nice string representation of the contents of cell pMem
  73567. ** into buffer zBuf, length nBuf.
  73568. */
  73569. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  73570. char *zCsr = zBuf;
  73571. int f = pMem->flags;
  73572. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  73573. if( f&MEM_Blob ){
  73574. int i;
  73575. char c;
  73576. if( f & MEM_Dyn ){
  73577. c = 'z';
  73578. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  73579. }else if( f & MEM_Static ){
  73580. c = 't';
  73581. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  73582. }else if( f & MEM_Ephem ){
  73583. c = 'e';
  73584. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  73585. }else{
  73586. c = 's';
  73587. }
  73588. *(zCsr++) = c;
  73589. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  73590. zCsr += sqlite3Strlen30(zCsr);
  73591. for(i=0; i<16 && i<pMem->n; i++){
  73592. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  73593. zCsr += sqlite3Strlen30(zCsr);
  73594. }
  73595. for(i=0; i<16 && i<pMem->n; i++){
  73596. char z = pMem->z[i];
  73597. if( z<32 || z>126 ) *zCsr++ = '.';
  73598. else *zCsr++ = z;
  73599. }
  73600. *(zCsr++) = ']';
  73601. if( f & MEM_Zero ){
  73602. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  73603. zCsr += sqlite3Strlen30(zCsr);
  73604. }
  73605. *zCsr = '\0';
  73606. }else if( f & MEM_Str ){
  73607. int j, k;
  73608. zBuf[0] = ' ';
  73609. if( f & MEM_Dyn ){
  73610. zBuf[1] = 'z';
  73611. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  73612. }else if( f & MEM_Static ){
  73613. zBuf[1] = 't';
  73614. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  73615. }else if( f & MEM_Ephem ){
  73616. zBuf[1] = 'e';
  73617. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  73618. }else{
  73619. zBuf[1] = 's';
  73620. }
  73621. k = 2;
  73622. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  73623. k += sqlite3Strlen30(&zBuf[k]);
  73624. zBuf[k++] = '[';
  73625. for(j=0; j<15 && j<pMem->n; j++){
  73626. u8 c = pMem->z[j];
  73627. if( c>=0x20 && c<0x7f ){
  73628. zBuf[k++] = c;
  73629. }else{
  73630. zBuf[k++] = '.';
  73631. }
  73632. }
  73633. zBuf[k++] = ']';
  73634. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  73635. k += sqlite3Strlen30(&zBuf[k]);
  73636. zBuf[k++] = 0;
  73637. }
  73638. }
  73639. #endif
  73640. #ifdef SQLITE_DEBUG
  73641. /*
  73642. ** Print the value of a register for tracing purposes:
  73643. */
  73644. static void memTracePrint(Mem *p){
  73645. if( p->flags & MEM_Undefined ){
  73646. printf(" undefined");
  73647. }else if( p->flags & MEM_Null ){
  73648. printf(" NULL");
  73649. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  73650. printf(" si:%lld", p->u.i);
  73651. }else if( p->flags & MEM_Int ){
  73652. printf(" i:%lld", p->u.i);
  73653. #ifndef SQLITE_OMIT_FLOATING_POINT
  73654. }else if( p->flags & MEM_Real ){
  73655. printf(" r:%g", p->u.r);
  73656. #endif
  73657. }else if( p->flags & MEM_RowSet ){
  73658. printf(" (rowset)");
  73659. }else{
  73660. char zBuf[200];
  73661. sqlite3VdbeMemPrettyPrint(p, zBuf);
  73662. printf(" %s", zBuf);
  73663. }
  73664. if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
  73665. }
  73666. static void registerTrace(int iReg, Mem *p){
  73667. printf("REG[%d] = ", iReg);
  73668. memTracePrint(p);
  73669. printf("\n");
  73670. sqlite3VdbeCheckMemInvariants(p);
  73671. }
  73672. #endif
  73673. #ifdef SQLITE_DEBUG
  73674. # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
  73675. #else
  73676. # define REGISTER_TRACE(R,M)
  73677. #endif
  73678. #ifdef VDBE_PROFILE
  73679. /*
  73680. ** hwtime.h contains inline assembler code for implementing
  73681. ** high-performance timing routines.
  73682. */
  73683. /************** Include hwtime.h in the middle of vdbe.c *********************/
  73684. /************** Begin file hwtime.h ******************************************/
  73685. /*
  73686. ** 2008 May 27
  73687. **
  73688. ** The author disclaims copyright to this source code. In place of
  73689. ** a legal notice, here is a blessing:
  73690. **
  73691. ** May you do good and not evil.
  73692. ** May you find forgiveness for yourself and forgive others.
  73693. ** May you share freely, never taking more than you give.
  73694. **
  73695. ******************************************************************************
  73696. **
  73697. ** This file contains inline asm code for retrieving "high-performance"
  73698. ** counters for x86 class CPUs.
  73699. */
  73700. #ifndef SQLITE_HWTIME_H
  73701. #define SQLITE_HWTIME_H
  73702. /*
  73703. ** The following routine only works on pentium-class (or newer) processors.
  73704. ** It uses the RDTSC opcode to read the cycle count value out of the
  73705. ** processor and returns that value. This can be used for high-res
  73706. ** profiling.
  73707. */
  73708. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  73709. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  73710. #if defined(__GNUC__)
  73711. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  73712. unsigned int lo, hi;
  73713. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  73714. return (sqlite_uint64)hi << 32 | lo;
  73715. }
  73716. #elif defined(_MSC_VER)
  73717. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  73718. __asm {
  73719. rdtsc
  73720. ret ; return value at EDX:EAX
  73721. }
  73722. }
  73723. #endif
  73724. #elif (defined(__GNUC__) && defined(__x86_64__))
  73725. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  73726. unsigned long val;
  73727. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  73728. return val;
  73729. }
  73730. #elif (defined(__GNUC__) && defined(__ppc__))
  73731. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  73732. unsigned long long retval;
  73733. unsigned long junk;
  73734. __asm__ __volatile__ ("\n\
  73735. 1: mftbu %1\n\
  73736. mftb %L0\n\
  73737. mftbu %0\n\
  73738. cmpw %0,%1\n\
  73739. bne 1b"
  73740. : "=r" (retval), "=r" (junk));
  73741. return retval;
  73742. }
  73743. #else
  73744. #error Need implementation of sqlite3Hwtime() for your platform.
  73745. /*
  73746. ** To compile without implementing sqlite3Hwtime() for your platform,
  73747. ** you can remove the above #error and use the following
  73748. ** stub function. You will lose timing support for many
  73749. ** of the debugging and testing utilities, but it should at
  73750. ** least compile and run.
  73751. */
  73752. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  73753. #endif
  73754. #endif /* !defined(SQLITE_HWTIME_H) */
  73755. /************** End of hwtime.h **********************************************/
  73756. /************** Continuing where we left off in vdbe.c ***********************/
  73757. #endif
  73758. #ifndef NDEBUG
  73759. /*
  73760. ** This function is only called from within an assert() expression. It
  73761. ** checks that the sqlite3.nTransaction variable is correctly set to
  73762. ** the number of non-transaction savepoints currently in the
  73763. ** linked list starting at sqlite3.pSavepoint.
  73764. **
  73765. ** Usage:
  73766. **
  73767. ** assert( checkSavepointCount(db) );
  73768. */
  73769. static int checkSavepointCount(sqlite3 *db){
  73770. int n = 0;
  73771. Savepoint *p;
  73772. for(p=db->pSavepoint; p; p=p->pNext) n++;
  73773. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  73774. return 1;
  73775. }
  73776. #endif
  73777. /*
  73778. ** Return the register of pOp->p2 after first preparing it to be
  73779. ** overwritten with an integer value.
  73780. */
  73781. static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
  73782. sqlite3VdbeMemSetNull(pOut);
  73783. pOut->flags = MEM_Int;
  73784. return pOut;
  73785. }
  73786. static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
  73787. Mem *pOut;
  73788. assert( pOp->p2>0 );
  73789. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  73790. pOut = &p->aMem[pOp->p2];
  73791. memAboutToChange(p, pOut);
  73792. if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
  73793. return out2PrereleaseWithClear(pOut);
  73794. }else{
  73795. pOut->flags = MEM_Int;
  73796. return pOut;
  73797. }
  73798. }
  73799. /*
  73800. ** Execute as much of a VDBE program as we can.
  73801. ** This is the core of sqlite3_step().
  73802. */
  73803. SQLITE_PRIVATE int sqlite3VdbeExec(
  73804. Vdbe *p /* The VDBE */
  73805. ){
  73806. Op *aOp = p->aOp; /* Copy of p->aOp */
  73807. Op *pOp = aOp; /* Current operation */
  73808. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  73809. Op *pOrigOp; /* Value of pOp at the top of the loop */
  73810. #endif
  73811. #ifdef SQLITE_DEBUG
  73812. int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
  73813. #endif
  73814. int rc = SQLITE_OK; /* Value to return */
  73815. sqlite3 *db = p->db; /* The database */
  73816. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  73817. u8 encoding = ENC(db); /* The database encoding */
  73818. int iCompare = 0; /* Result of last comparison */
  73819. unsigned nVmStep = 0; /* Number of virtual machine steps */
  73820. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  73821. unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
  73822. #endif
  73823. Mem *aMem = p->aMem; /* Copy of p->aMem */
  73824. Mem *pIn1 = 0; /* 1st input operand */
  73825. Mem *pIn2 = 0; /* 2nd input operand */
  73826. Mem *pIn3 = 0; /* 3rd input operand */
  73827. Mem *pOut = 0; /* Output operand */
  73828. #ifdef VDBE_PROFILE
  73829. u64 start; /* CPU clock count at start of opcode */
  73830. #endif
  73831. /*** INSERT STACK UNION HERE ***/
  73832. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  73833. sqlite3VdbeEnter(p);
  73834. if( p->rc==SQLITE_NOMEM ){
  73835. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  73836. ** sqlite3_column_text16() failed. */
  73837. goto no_mem;
  73838. }
  73839. assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
  73840. assert( p->bIsReader || p->readOnly!=0 );
  73841. p->iCurrentTime = 0;
  73842. assert( p->explain==0 );
  73843. p->pResultSet = 0;
  73844. db->busyHandler.nBusy = 0;
  73845. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  73846. sqlite3VdbeIOTraceSql(p);
  73847. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  73848. if( db->xProgress ){
  73849. u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  73850. assert( 0 < db->nProgressOps );
  73851. nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
  73852. }
  73853. #endif
  73854. #ifdef SQLITE_DEBUG
  73855. sqlite3BeginBenignMalloc();
  73856. if( p->pc==0
  73857. && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
  73858. ){
  73859. int i;
  73860. int once = 1;
  73861. sqlite3VdbePrintSql(p);
  73862. if( p->db->flags & SQLITE_VdbeListing ){
  73863. printf("VDBE Program Listing:\n");
  73864. for(i=0; i<p->nOp; i++){
  73865. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  73866. }
  73867. }
  73868. if( p->db->flags & SQLITE_VdbeEQP ){
  73869. for(i=0; i<p->nOp; i++){
  73870. if( aOp[i].opcode==OP_Explain ){
  73871. if( once ) printf("VDBE Query Plan:\n");
  73872. printf("%s\n", aOp[i].p4.z);
  73873. once = 0;
  73874. }
  73875. }
  73876. }
  73877. if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
  73878. }
  73879. sqlite3EndBenignMalloc();
  73880. #endif
  73881. for(pOp=&aOp[p->pc]; 1; pOp++){
  73882. /* Errors are detected by individual opcodes, with an immediate
  73883. ** jumps to abort_due_to_error. */
  73884. assert( rc==SQLITE_OK );
  73885. assert( pOp>=aOp && pOp<&aOp[p->nOp]);
  73886. #ifdef VDBE_PROFILE
  73887. start = sqlite3Hwtime();
  73888. #endif
  73889. nVmStep++;
  73890. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  73891. if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
  73892. #endif
  73893. /* Only allow tracing if SQLITE_DEBUG is defined.
  73894. */
  73895. #ifdef SQLITE_DEBUG
  73896. if( db->flags & SQLITE_VdbeTrace ){
  73897. sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
  73898. }
  73899. #endif
  73900. /* Check to see if we need to simulate an interrupt. This only happens
  73901. ** if we have a special test build.
  73902. */
  73903. #ifdef SQLITE_TEST
  73904. if( sqlite3_interrupt_count>0 ){
  73905. sqlite3_interrupt_count--;
  73906. if( sqlite3_interrupt_count==0 ){
  73907. sqlite3_interrupt(db);
  73908. }
  73909. }
  73910. #endif
  73911. /* Sanity checking on other operands */
  73912. #ifdef SQLITE_DEBUG
  73913. {
  73914. u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
  73915. if( (opProperty & OPFLG_IN1)!=0 ){
  73916. assert( pOp->p1>0 );
  73917. assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
  73918. assert( memIsValid(&aMem[pOp->p1]) );
  73919. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
  73920. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  73921. }
  73922. if( (opProperty & OPFLG_IN2)!=0 ){
  73923. assert( pOp->p2>0 );
  73924. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  73925. assert( memIsValid(&aMem[pOp->p2]) );
  73926. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
  73927. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  73928. }
  73929. if( (opProperty & OPFLG_IN3)!=0 ){
  73930. assert( pOp->p3>0 );
  73931. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  73932. assert( memIsValid(&aMem[pOp->p3]) );
  73933. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
  73934. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  73935. }
  73936. if( (opProperty & OPFLG_OUT2)!=0 ){
  73937. assert( pOp->p2>0 );
  73938. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  73939. memAboutToChange(p, &aMem[pOp->p2]);
  73940. }
  73941. if( (opProperty & OPFLG_OUT3)!=0 ){
  73942. assert( pOp->p3>0 );
  73943. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  73944. memAboutToChange(p, &aMem[pOp->p3]);
  73945. }
  73946. }
  73947. #endif
  73948. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  73949. pOrigOp = pOp;
  73950. #endif
  73951. switch( pOp->opcode ){
  73952. /*****************************************************************************
  73953. ** What follows is a massive switch statement where each case implements a
  73954. ** separate instruction in the virtual machine. If we follow the usual
  73955. ** indentation conventions, each case should be indented by 6 spaces. But
  73956. ** that is a lot of wasted space on the left margin. So the code within
  73957. ** the switch statement will break with convention and be flush-left. Another
  73958. ** big comment (similar to this one) will mark the point in the code where
  73959. ** we transition back to normal indentation.
  73960. **
  73961. ** The formatting of each case is important. The makefile for SQLite
  73962. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  73963. ** file looking for lines that begin with "case OP_". The opcodes.h files
  73964. ** will be filled with #defines that give unique integer values to each
  73965. ** opcode and the opcodes.c file is filled with an array of strings where
  73966. ** each string is the symbolic name for the corresponding opcode. If the
  73967. ** case statement is followed by a comment of the form "/# same as ... #/"
  73968. ** that comment is used to determine the particular value of the opcode.
  73969. **
  73970. ** Other keywords in the comment that follows each case are used to
  73971. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  73972. ** Keywords include: in1, in2, in3, out2, out3. See
  73973. ** the mkopcodeh.awk script for additional information.
  73974. **
  73975. ** Documentation about VDBE opcodes is generated by scanning this file
  73976. ** for lines of that contain "Opcode:". That line and all subsequent
  73977. ** comment lines are used in the generation of the opcode.html documentation
  73978. ** file.
  73979. **
  73980. ** SUMMARY:
  73981. **
  73982. ** Formatting is important to scripts that scan this file.
  73983. ** Do not deviate from the formatting style currently in use.
  73984. **
  73985. *****************************************************************************/
  73986. /* Opcode: Goto * P2 * * *
  73987. **
  73988. ** An unconditional jump to address P2.
  73989. ** The next instruction executed will be
  73990. ** the one at index P2 from the beginning of
  73991. ** the program.
  73992. **
  73993. ** The P1 parameter is not actually used by this opcode. However, it
  73994. ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
  73995. ** that this Goto is the bottom of a loop and that the lines from P2 down
  73996. ** to the current line should be indented for EXPLAIN output.
  73997. */
  73998. case OP_Goto: { /* jump */
  73999. jump_to_p2_and_check_for_interrupt:
  74000. pOp = &aOp[pOp->p2 - 1];
  74001. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  74002. ** OP_VNext, or OP_SorterNext) all jump here upon
  74003. ** completion. Check to see if sqlite3_interrupt() has been called
  74004. ** or if the progress callback needs to be invoked.
  74005. **
  74006. ** This code uses unstructured "goto" statements and does not look clean.
  74007. ** But that is not due to sloppy coding habits. The code is written this
  74008. ** way for performance, to avoid having to run the interrupt and progress
  74009. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  74010. ** faster according to "valgrind --tool=cachegrind" */
  74011. check_for_interrupt:
  74012. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  74013. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  74014. /* Call the progress callback if it is configured and the required number
  74015. ** of VDBE ops have been executed (either since this invocation of
  74016. ** sqlite3VdbeExec() or since last time the progress callback was called).
  74017. ** If the progress callback returns non-zero, exit the virtual machine with
  74018. ** a return code SQLITE_ABORT.
  74019. */
  74020. if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
  74021. assert( db->nProgressOps!=0 );
  74022. nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
  74023. if( db->xProgress(db->pProgressArg) ){
  74024. rc = SQLITE_INTERRUPT;
  74025. goto abort_due_to_error;
  74026. }
  74027. }
  74028. #endif
  74029. break;
  74030. }
  74031. /* Opcode: Gosub P1 P2 * * *
  74032. **
  74033. ** Write the current address onto register P1
  74034. ** and then jump to address P2.
  74035. */
  74036. case OP_Gosub: { /* jump */
  74037. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  74038. pIn1 = &aMem[pOp->p1];
  74039. assert( VdbeMemDynamic(pIn1)==0 );
  74040. memAboutToChange(p, pIn1);
  74041. pIn1->flags = MEM_Int;
  74042. pIn1->u.i = (int)(pOp-aOp);
  74043. REGISTER_TRACE(pOp->p1, pIn1);
  74044. /* Most jump operations do a goto to this spot in order to update
  74045. ** the pOp pointer. */
  74046. jump_to_p2:
  74047. pOp = &aOp[pOp->p2 - 1];
  74048. break;
  74049. }
  74050. /* Opcode: Return P1 * * * *
  74051. **
  74052. ** Jump to the next instruction after the address in register P1. After
  74053. ** the jump, register P1 becomes undefined.
  74054. */
  74055. case OP_Return: { /* in1 */
  74056. pIn1 = &aMem[pOp->p1];
  74057. assert( pIn1->flags==MEM_Int );
  74058. pOp = &aOp[pIn1->u.i];
  74059. pIn1->flags = MEM_Undefined;
  74060. break;
  74061. }
  74062. /* Opcode: InitCoroutine P1 P2 P3 * *
  74063. **
  74064. ** Set up register P1 so that it will Yield to the coroutine
  74065. ** located at address P3.
  74066. **
  74067. ** If P2!=0 then the coroutine implementation immediately follows
  74068. ** this opcode. So jump over the coroutine implementation to
  74069. ** address P2.
  74070. **
  74071. ** See also: EndCoroutine
  74072. */
  74073. case OP_InitCoroutine: { /* jump */
  74074. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  74075. assert( pOp->p2>=0 && pOp->p2<p->nOp );
  74076. assert( pOp->p3>=0 && pOp->p3<p->nOp );
  74077. pOut = &aMem[pOp->p1];
  74078. assert( !VdbeMemDynamic(pOut) );
  74079. pOut->u.i = pOp->p3 - 1;
  74080. pOut->flags = MEM_Int;
  74081. if( pOp->p2 ) goto jump_to_p2;
  74082. break;
  74083. }
  74084. /* Opcode: EndCoroutine P1 * * * *
  74085. **
  74086. ** The instruction at the address in register P1 is a Yield.
  74087. ** Jump to the P2 parameter of that Yield.
  74088. ** After the jump, register P1 becomes undefined.
  74089. **
  74090. ** See also: InitCoroutine
  74091. */
  74092. case OP_EndCoroutine: { /* in1 */
  74093. VdbeOp *pCaller;
  74094. pIn1 = &aMem[pOp->p1];
  74095. assert( pIn1->flags==MEM_Int );
  74096. assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
  74097. pCaller = &aOp[pIn1->u.i];
  74098. assert( pCaller->opcode==OP_Yield );
  74099. assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
  74100. pOp = &aOp[pCaller->p2 - 1];
  74101. pIn1->flags = MEM_Undefined;
  74102. break;
  74103. }
  74104. /* Opcode: Yield P1 P2 * * *
  74105. **
  74106. ** Swap the program counter with the value in register P1. This
  74107. ** has the effect of yielding to a coroutine.
  74108. **
  74109. ** If the coroutine that is launched by this instruction ends with
  74110. ** Yield or Return then continue to the next instruction. But if
  74111. ** the coroutine launched by this instruction ends with
  74112. ** EndCoroutine, then jump to P2 rather than continuing with the
  74113. ** next instruction.
  74114. **
  74115. ** See also: InitCoroutine
  74116. */
  74117. case OP_Yield: { /* in1, jump */
  74118. int pcDest;
  74119. pIn1 = &aMem[pOp->p1];
  74120. assert( VdbeMemDynamic(pIn1)==0 );
  74121. pIn1->flags = MEM_Int;
  74122. pcDest = (int)pIn1->u.i;
  74123. pIn1->u.i = (int)(pOp - aOp);
  74124. REGISTER_TRACE(pOp->p1, pIn1);
  74125. pOp = &aOp[pcDest];
  74126. break;
  74127. }
  74128. /* Opcode: HaltIfNull P1 P2 P3 P4 P5
  74129. ** Synopsis: if r[P3]=null halt
  74130. **
  74131. ** Check the value in register P3. If it is NULL then Halt using
  74132. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  74133. ** value in register P3 is not NULL, then this routine is a no-op.
  74134. ** The P5 parameter should be 1.
  74135. */
  74136. case OP_HaltIfNull: { /* in3 */
  74137. pIn3 = &aMem[pOp->p3];
  74138. if( (pIn3->flags & MEM_Null)==0 ) break;
  74139. /* Fall through into OP_Halt */
  74140. }
  74141. /* Opcode: Halt P1 P2 * P4 P5
  74142. **
  74143. ** Exit immediately. All open cursors, etc are closed
  74144. ** automatically.
  74145. **
  74146. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  74147. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  74148. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  74149. ** whether or not to rollback the current transaction. Do not rollback
  74150. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  74151. ** then back out all changes that have occurred during this execution of the
  74152. ** VDBE, but do not rollback the transaction.
  74153. **
  74154. ** If P4 is not null then it is an error message string.
  74155. **
  74156. ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
  74157. **
  74158. ** 0: (no change)
  74159. ** 1: NOT NULL contraint failed: P4
  74160. ** 2: UNIQUE constraint failed: P4
  74161. ** 3: CHECK constraint failed: P4
  74162. ** 4: FOREIGN KEY constraint failed: P4
  74163. **
  74164. ** If P5 is not zero and P4 is NULL, then everything after the ":" is
  74165. ** omitted.
  74166. **
  74167. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  74168. ** every program. So a jump past the last instruction of the program
  74169. ** is the same as executing Halt.
  74170. */
  74171. case OP_Halt: {
  74172. VdbeFrame *pFrame;
  74173. int pcx;
  74174. pcx = (int)(pOp - aOp);
  74175. if( pOp->p1==SQLITE_OK && p->pFrame ){
  74176. /* Halt the sub-program. Return control to the parent frame. */
  74177. pFrame = p->pFrame;
  74178. p->pFrame = pFrame->pParent;
  74179. p->nFrame--;
  74180. sqlite3VdbeSetChanges(db, p->nChange);
  74181. pcx = sqlite3VdbeFrameRestore(pFrame);
  74182. if( pOp->p2==OE_Ignore ){
  74183. /* Instruction pcx is the OP_Program that invoked the sub-program
  74184. ** currently being halted. If the p2 instruction of this OP_Halt
  74185. ** instruction is set to OE_Ignore, then the sub-program is throwing
  74186. ** an IGNORE exception. In this case jump to the address specified
  74187. ** as the p2 of the calling OP_Program. */
  74188. pcx = p->aOp[pcx].p2-1;
  74189. }
  74190. aOp = p->aOp;
  74191. aMem = p->aMem;
  74192. pOp = &aOp[pcx];
  74193. break;
  74194. }
  74195. p->rc = pOp->p1;
  74196. p->errorAction = (u8)pOp->p2;
  74197. p->pc = pcx;
  74198. assert( pOp->p5<=4 );
  74199. if( p->rc ){
  74200. if( pOp->p5 ){
  74201. static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
  74202. "FOREIGN KEY" };
  74203. testcase( pOp->p5==1 );
  74204. testcase( pOp->p5==2 );
  74205. testcase( pOp->p5==3 );
  74206. testcase( pOp->p5==4 );
  74207. sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
  74208. if( pOp->p4.z ){
  74209. p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
  74210. }
  74211. }else{
  74212. sqlite3VdbeError(p, "%s", pOp->p4.z);
  74213. }
  74214. sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
  74215. }
  74216. rc = sqlite3VdbeHalt(p);
  74217. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  74218. if( rc==SQLITE_BUSY ){
  74219. p->rc = SQLITE_BUSY;
  74220. }else{
  74221. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  74222. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  74223. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  74224. }
  74225. goto vdbe_return;
  74226. }
  74227. /* Opcode: Integer P1 P2 * * *
  74228. ** Synopsis: r[P2]=P1
  74229. **
  74230. ** The 32-bit integer value P1 is written into register P2.
  74231. */
  74232. case OP_Integer: { /* out2 */
  74233. pOut = out2Prerelease(p, pOp);
  74234. pOut->u.i = pOp->p1;
  74235. break;
  74236. }
  74237. /* Opcode: Int64 * P2 * P4 *
  74238. ** Synopsis: r[P2]=P4
  74239. **
  74240. ** P4 is a pointer to a 64-bit integer value.
  74241. ** Write that value into register P2.
  74242. */
  74243. case OP_Int64: { /* out2 */
  74244. pOut = out2Prerelease(p, pOp);
  74245. assert( pOp->p4.pI64!=0 );
  74246. pOut->u.i = *pOp->p4.pI64;
  74247. break;
  74248. }
  74249. #ifndef SQLITE_OMIT_FLOATING_POINT
  74250. /* Opcode: Real * P2 * P4 *
  74251. ** Synopsis: r[P2]=P4
  74252. **
  74253. ** P4 is a pointer to a 64-bit floating point value.
  74254. ** Write that value into register P2.
  74255. */
  74256. case OP_Real: { /* same as TK_FLOAT, out2 */
  74257. pOut = out2Prerelease(p, pOp);
  74258. pOut->flags = MEM_Real;
  74259. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  74260. pOut->u.r = *pOp->p4.pReal;
  74261. break;
  74262. }
  74263. #endif
  74264. /* Opcode: String8 * P2 * P4 *
  74265. ** Synopsis: r[P2]='P4'
  74266. **
  74267. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  74268. ** into a String opcode before it is executed for the first time. During
  74269. ** this transformation, the length of string P4 is computed and stored
  74270. ** as the P1 parameter.
  74271. */
  74272. case OP_String8: { /* same as TK_STRING, out2 */
  74273. assert( pOp->p4.z!=0 );
  74274. pOut = out2Prerelease(p, pOp);
  74275. pOp->opcode = OP_String;
  74276. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  74277. #ifndef SQLITE_OMIT_UTF16
  74278. if( encoding!=SQLITE_UTF8 ){
  74279. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  74280. assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
  74281. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  74282. assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
  74283. assert( VdbeMemDynamic(pOut)==0 );
  74284. pOut->szMalloc = 0;
  74285. pOut->flags |= MEM_Static;
  74286. if( pOp->p4type==P4_DYNAMIC ){
  74287. sqlite3DbFree(db, pOp->p4.z);
  74288. }
  74289. pOp->p4type = P4_DYNAMIC;
  74290. pOp->p4.z = pOut->z;
  74291. pOp->p1 = pOut->n;
  74292. }
  74293. testcase( rc==SQLITE_TOOBIG );
  74294. #endif
  74295. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  74296. goto too_big;
  74297. }
  74298. assert( rc==SQLITE_OK );
  74299. /* Fall through to the next case, OP_String */
  74300. }
  74301. /* Opcode: String P1 P2 P3 P4 P5
  74302. ** Synopsis: r[P2]='P4' (len=P1)
  74303. **
  74304. ** The string value P4 of length P1 (bytes) is stored in register P2.
  74305. **
  74306. ** If P3 is not zero and the content of register P3 is equal to P5, then
  74307. ** the datatype of the register P2 is converted to BLOB. The content is
  74308. ** the same sequence of bytes, it is merely interpreted as a BLOB instead
  74309. ** of a string, as if it had been CAST. In other words:
  74310. **
  74311. ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
  74312. */
  74313. case OP_String: { /* out2 */
  74314. assert( pOp->p4.z!=0 );
  74315. pOut = out2Prerelease(p, pOp);
  74316. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  74317. pOut->z = pOp->p4.z;
  74318. pOut->n = pOp->p1;
  74319. pOut->enc = encoding;
  74320. UPDATE_MAX_BLOBSIZE(pOut);
  74321. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  74322. if( pOp->p3>0 ){
  74323. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  74324. pIn3 = &aMem[pOp->p3];
  74325. assert( pIn3->flags & MEM_Int );
  74326. if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
  74327. }
  74328. #endif
  74329. break;
  74330. }
  74331. /* Opcode: Null P1 P2 P3 * *
  74332. ** Synopsis: r[P2..P3]=NULL
  74333. **
  74334. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  74335. ** NULL into register P3 and every register in between P2 and P3. If P3
  74336. ** is less than P2 (typically P3 is zero) then only register P2 is
  74337. ** set to NULL.
  74338. **
  74339. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  74340. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  74341. ** OP_Ne or OP_Eq.
  74342. */
  74343. case OP_Null: { /* out2 */
  74344. int cnt;
  74345. u16 nullFlag;
  74346. pOut = out2Prerelease(p, pOp);
  74347. cnt = pOp->p3-pOp->p2;
  74348. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  74349. pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  74350. pOut->n = 0;
  74351. while( cnt>0 ){
  74352. pOut++;
  74353. memAboutToChange(p, pOut);
  74354. sqlite3VdbeMemSetNull(pOut);
  74355. pOut->flags = nullFlag;
  74356. pOut->n = 0;
  74357. cnt--;
  74358. }
  74359. break;
  74360. }
  74361. /* Opcode: SoftNull P1 * * * *
  74362. ** Synopsis: r[P1]=NULL
  74363. **
  74364. ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
  74365. ** instruction, but do not free any string or blob memory associated with
  74366. ** the register, so that if the value was a string or blob that was
  74367. ** previously copied using OP_SCopy, the copies will continue to be valid.
  74368. */
  74369. case OP_SoftNull: {
  74370. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  74371. pOut = &aMem[pOp->p1];
  74372. pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
  74373. break;
  74374. }
  74375. /* Opcode: Blob P1 P2 * P4 *
  74376. ** Synopsis: r[P2]=P4 (len=P1)
  74377. **
  74378. ** P4 points to a blob of data P1 bytes long. Store this
  74379. ** blob in register P2.
  74380. */
  74381. case OP_Blob: { /* out2 */
  74382. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  74383. pOut = out2Prerelease(p, pOp);
  74384. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  74385. pOut->enc = encoding;
  74386. UPDATE_MAX_BLOBSIZE(pOut);
  74387. break;
  74388. }
  74389. /* Opcode: Variable P1 P2 * P4 *
  74390. ** Synopsis: r[P2]=parameter(P1,P4)
  74391. **
  74392. ** Transfer the values of bound parameter P1 into register P2
  74393. **
  74394. ** If the parameter is named, then its name appears in P4.
  74395. ** The P4 value is used by sqlite3_bind_parameter_name().
  74396. */
  74397. case OP_Variable: { /* out2 */
  74398. Mem *pVar; /* Value being transferred */
  74399. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  74400. assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
  74401. pVar = &p->aVar[pOp->p1 - 1];
  74402. if( sqlite3VdbeMemTooBig(pVar) ){
  74403. goto too_big;
  74404. }
  74405. pOut = &aMem[pOp->p2];
  74406. sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
  74407. UPDATE_MAX_BLOBSIZE(pOut);
  74408. break;
  74409. }
  74410. /* Opcode: Move P1 P2 P3 * *
  74411. ** Synopsis: r[P2@P3]=r[P1@P3]
  74412. **
  74413. ** Move the P3 values in register P1..P1+P3-1 over into
  74414. ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
  74415. ** left holding a NULL. It is an error for register ranges
  74416. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
  74417. ** for P3 to be less than 1.
  74418. */
  74419. case OP_Move: {
  74420. int n; /* Number of registers left to copy */
  74421. int p1; /* Register to copy from */
  74422. int p2; /* Register to copy to */
  74423. n = pOp->p3;
  74424. p1 = pOp->p1;
  74425. p2 = pOp->p2;
  74426. assert( n>0 && p1>0 && p2>0 );
  74427. assert( p1+n<=p2 || p2+n<=p1 );
  74428. pIn1 = &aMem[p1];
  74429. pOut = &aMem[p2];
  74430. do{
  74431. assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
  74432. assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
  74433. assert( memIsValid(pIn1) );
  74434. memAboutToChange(p, pOut);
  74435. sqlite3VdbeMemMove(pOut, pIn1);
  74436. #ifdef SQLITE_DEBUG
  74437. if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
  74438. pOut->pScopyFrom += pOp->p2 - p1;
  74439. }
  74440. #endif
  74441. Deephemeralize(pOut);
  74442. REGISTER_TRACE(p2++, pOut);
  74443. pIn1++;
  74444. pOut++;
  74445. }while( --n );
  74446. break;
  74447. }
  74448. /* Opcode: Copy P1 P2 P3 * *
  74449. ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
  74450. **
  74451. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  74452. **
  74453. ** This instruction makes a deep copy of the value. A duplicate
  74454. ** is made of any string or blob constant. See also OP_SCopy.
  74455. */
  74456. case OP_Copy: {
  74457. int n;
  74458. n = pOp->p3;
  74459. pIn1 = &aMem[pOp->p1];
  74460. pOut = &aMem[pOp->p2];
  74461. assert( pOut!=pIn1 );
  74462. while( 1 ){
  74463. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  74464. Deephemeralize(pOut);
  74465. #ifdef SQLITE_DEBUG
  74466. pOut->pScopyFrom = 0;
  74467. #endif
  74468. REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
  74469. if( (n--)==0 ) break;
  74470. pOut++;
  74471. pIn1++;
  74472. }
  74473. break;
  74474. }
  74475. /* Opcode: SCopy P1 P2 * * *
  74476. ** Synopsis: r[P2]=r[P1]
  74477. **
  74478. ** Make a shallow copy of register P1 into register P2.
  74479. **
  74480. ** This instruction makes a shallow copy of the value. If the value
  74481. ** is a string or blob, then the copy is only a pointer to the
  74482. ** original and hence if the original changes so will the copy.
  74483. ** Worse, if the original is deallocated, the copy becomes invalid.
  74484. ** Thus the program must guarantee that the original will not change
  74485. ** during the lifetime of the copy. Use OP_Copy to make a complete
  74486. ** copy.
  74487. */
  74488. case OP_SCopy: { /* out2 */
  74489. pIn1 = &aMem[pOp->p1];
  74490. pOut = &aMem[pOp->p2];
  74491. assert( pOut!=pIn1 );
  74492. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  74493. #ifdef SQLITE_DEBUG
  74494. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  74495. #endif
  74496. break;
  74497. }
  74498. /* Opcode: IntCopy P1 P2 * * *
  74499. ** Synopsis: r[P2]=r[P1]
  74500. **
  74501. ** Transfer the integer value held in register P1 into register P2.
  74502. **
  74503. ** This is an optimized version of SCopy that works only for integer
  74504. ** values.
  74505. */
  74506. case OP_IntCopy: { /* out2 */
  74507. pIn1 = &aMem[pOp->p1];
  74508. assert( (pIn1->flags & MEM_Int)!=0 );
  74509. pOut = &aMem[pOp->p2];
  74510. sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
  74511. break;
  74512. }
  74513. /* Opcode: ResultRow P1 P2 * * *
  74514. ** Synopsis: output=r[P1@P2]
  74515. **
  74516. ** The registers P1 through P1+P2-1 contain a single row of
  74517. ** results. This opcode causes the sqlite3_step() call to terminate
  74518. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  74519. ** structure to provide access to the r(P1)..r(P1+P2-1) values as
  74520. ** the result row.
  74521. */
  74522. case OP_ResultRow: {
  74523. Mem *pMem;
  74524. int i;
  74525. assert( p->nResColumn==pOp->p2 );
  74526. assert( pOp->p1>0 );
  74527. assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
  74528. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  74529. /* Run the progress counter just before returning.
  74530. */
  74531. if( db->xProgress!=0
  74532. && nVmStep>=nProgressLimit
  74533. && db->xProgress(db->pProgressArg)!=0
  74534. ){
  74535. rc = SQLITE_INTERRUPT;
  74536. goto abort_due_to_error;
  74537. }
  74538. #endif
  74539. /* If this statement has violated immediate foreign key constraints, do
  74540. ** not return the number of rows modified. And do not RELEASE the statement
  74541. ** transaction. It needs to be rolled back. */
  74542. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  74543. assert( db->flags&SQLITE_CountRows );
  74544. assert( p->usesStmtJournal );
  74545. goto abort_due_to_error;
  74546. }
  74547. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  74548. ** DML statements invoke this opcode to return the number of rows
  74549. ** modified to the user. This is the only way that a VM that
  74550. ** opens a statement transaction may invoke this opcode.
  74551. **
  74552. ** In case this is such a statement, close any statement transaction
  74553. ** opened by this VM before returning control to the user. This is to
  74554. ** ensure that statement-transactions are always nested, not overlapping.
  74555. ** If the open statement-transaction is not closed here, then the user
  74556. ** may step another VM that opens its own statement transaction. This
  74557. ** may lead to overlapping statement transactions.
  74558. **
  74559. ** The statement transaction is never a top-level transaction. Hence
  74560. ** the RELEASE call below can never fail.
  74561. */
  74562. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  74563. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  74564. assert( rc==SQLITE_OK );
  74565. /* Invalidate all ephemeral cursor row caches */
  74566. p->cacheCtr = (p->cacheCtr + 2)|1;
  74567. /* Make sure the results of the current row are \000 terminated
  74568. ** and have an assigned type. The results are de-ephemeralized as
  74569. ** a side effect.
  74570. */
  74571. pMem = p->pResultSet = &aMem[pOp->p1];
  74572. for(i=0; i<pOp->p2; i++){
  74573. assert( memIsValid(&pMem[i]) );
  74574. Deephemeralize(&pMem[i]);
  74575. assert( (pMem[i].flags & MEM_Ephem)==0
  74576. || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
  74577. sqlite3VdbeMemNulTerminate(&pMem[i]);
  74578. REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  74579. }
  74580. if( db->mallocFailed ) goto no_mem;
  74581. if( db->mTrace & SQLITE_TRACE_ROW ){
  74582. db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
  74583. }
  74584. /* Return SQLITE_ROW
  74585. */
  74586. p->pc = (int)(pOp - aOp) + 1;
  74587. rc = SQLITE_ROW;
  74588. goto vdbe_return;
  74589. }
  74590. /* Opcode: Concat P1 P2 P3 * *
  74591. ** Synopsis: r[P3]=r[P2]+r[P1]
  74592. **
  74593. ** Add the text in register P1 onto the end of the text in
  74594. ** register P2 and store the result in register P3.
  74595. ** If either the P1 or P2 text are NULL then store NULL in P3.
  74596. **
  74597. ** P3 = P2 || P1
  74598. **
  74599. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  74600. ** if P3 is the same register as P2, the implementation is able
  74601. ** to avoid a memcpy().
  74602. */
  74603. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  74604. i64 nByte;
  74605. pIn1 = &aMem[pOp->p1];
  74606. pIn2 = &aMem[pOp->p2];
  74607. pOut = &aMem[pOp->p3];
  74608. assert( pIn1!=pOut );
  74609. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  74610. sqlite3VdbeMemSetNull(pOut);
  74611. break;
  74612. }
  74613. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  74614. Stringify(pIn1, encoding);
  74615. Stringify(pIn2, encoding);
  74616. nByte = pIn1->n + pIn2->n;
  74617. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  74618. goto too_big;
  74619. }
  74620. if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
  74621. goto no_mem;
  74622. }
  74623. MemSetTypeFlag(pOut, MEM_Str);
  74624. if( pOut!=pIn2 ){
  74625. memcpy(pOut->z, pIn2->z, pIn2->n);
  74626. }
  74627. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  74628. pOut->z[nByte]=0;
  74629. pOut->z[nByte+1] = 0;
  74630. pOut->flags |= MEM_Term;
  74631. pOut->n = (int)nByte;
  74632. pOut->enc = encoding;
  74633. UPDATE_MAX_BLOBSIZE(pOut);
  74634. break;
  74635. }
  74636. /* Opcode: Add P1 P2 P3 * *
  74637. ** Synopsis: r[P3]=r[P1]+r[P2]
  74638. **
  74639. ** Add the value in register P1 to the value in register P2
  74640. ** and store the result in register P3.
  74641. ** If either input is NULL, the result is NULL.
  74642. */
  74643. /* Opcode: Multiply P1 P2 P3 * *
  74644. ** Synopsis: r[P3]=r[P1]*r[P2]
  74645. **
  74646. **
  74647. ** Multiply the value in register P1 by the value in register P2
  74648. ** and store the result in register P3.
  74649. ** If either input is NULL, the result is NULL.
  74650. */
  74651. /* Opcode: Subtract P1 P2 P3 * *
  74652. ** Synopsis: r[P3]=r[P2]-r[P1]
  74653. **
  74654. ** Subtract the value in register P1 from the value in register P2
  74655. ** and store the result in register P3.
  74656. ** If either input is NULL, the result is NULL.
  74657. */
  74658. /* Opcode: Divide P1 P2 P3 * *
  74659. ** Synopsis: r[P3]=r[P2]/r[P1]
  74660. **
  74661. ** Divide the value in register P1 by the value in register P2
  74662. ** and store the result in register P3 (P3=P2/P1). If the value in
  74663. ** register P1 is zero, then the result is NULL. If either input is
  74664. ** NULL, the result is NULL.
  74665. */
  74666. /* Opcode: Remainder P1 P2 P3 * *
  74667. ** Synopsis: r[P3]=r[P2]%r[P1]
  74668. **
  74669. ** Compute the remainder after integer register P2 is divided by
  74670. ** register P1 and store the result in register P3.
  74671. ** If the value in register P1 is zero the result is NULL.
  74672. ** If either operand is NULL, the result is NULL.
  74673. */
  74674. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  74675. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  74676. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  74677. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  74678. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  74679. char bIntint; /* Started out as two integer operands */
  74680. u16 flags; /* Combined MEM_* flags from both inputs */
  74681. u16 type1; /* Numeric type of left operand */
  74682. u16 type2; /* Numeric type of right operand */
  74683. i64 iA; /* Integer value of left operand */
  74684. i64 iB; /* Integer value of right operand */
  74685. double rA; /* Real value of left operand */
  74686. double rB; /* Real value of right operand */
  74687. pIn1 = &aMem[pOp->p1];
  74688. type1 = numericType(pIn1);
  74689. pIn2 = &aMem[pOp->p2];
  74690. type2 = numericType(pIn2);
  74691. pOut = &aMem[pOp->p3];
  74692. flags = pIn1->flags | pIn2->flags;
  74693. if( (type1 & type2 & MEM_Int)!=0 ){
  74694. iA = pIn1->u.i;
  74695. iB = pIn2->u.i;
  74696. bIntint = 1;
  74697. switch( pOp->opcode ){
  74698. case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
  74699. case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
  74700. case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
  74701. case OP_Divide: {
  74702. if( iA==0 ) goto arithmetic_result_is_null;
  74703. if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
  74704. iB /= iA;
  74705. break;
  74706. }
  74707. default: {
  74708. if( iA==0 ) goto arithmetic_result_is_null;
  74709. if( iA==-1 ) iA = 1;
  74710. iB %= iA;
  74711. break;
  74712. }
  74713. }
  74714. pOut->u.i = iB;
  74715. MemSetTypeFlag(pOut, MEM_Int);
  74716. }else if( (flags & MEM_Null)!=0 ){
  74717. goto arithmetic_result_is_null;
  74718. }else{
  74719. bIntint = 0;
  74720. fp_math:
  74721. rA = sqlite3VdbeRealValue(pIn1);
  74722. rB = sqlite3VdbeRealValue(pIn2);
  74723. switch( pOp->opcode ){
  74724. case OP_Add: rB += rA; break;
  74725. case OP_Subtract: rB -= rA; break;
  74726. case OP_Multiply: rB *= rA; break;
  74727. case OP_Divide: {
  74728. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  74729. if( rA==(double)0 ) goto arithmetic_result_is_null;
  74730. rB /= rA;
  74731. break;
  74732. }
  74733. default: {
  74734. iA = (i64)rA;
  74735. iB = (i64)rB;
  74736. if( iA==0 ) goto arithmetic_result_is_null;
  74737. if( iA==-1 ) iA = 1;
  74738. rB = (double)(iB % iA);
  74739. break;
  74740. }
  74741. }
  74742. #ifdef SQLITE_OMIT_FLOATING_POINT
  74743. pOut->u.i = rB;
  74744. MemSetTypeFlag(pOut, MEM_Int);
  74745. #else
  74746. if( sqlite3IsNaN(rB) ){
  74747. goto arithmetic_result_is_null;
  74748. }
  74749. pOut->u.r = rB;
  74750. MemSetTypeFlag(pOut, MEM_Real);
  74751. if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
  74752. sqlite3VdbeIntegerAffinity(pOut);
  74753. }
  74754. #endif
  74755. }
  74756. break;
  74757. arithmetic_result_is_null:
  74758. sqlite3VdbeMemSetNull(pOut);
  74759. break;
  74760. }
  74761. /* Opcode: CollSeq P1 * * P4
  74762. **
  74763. ** P4 is a pointer to a CollSeq object. If the next call to a user function
  74764. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  74765. ** be returned. This is used by the built-in min(), max() and nullif()
  74766. ** functions.
  74767. **
  74768. ** If P1 is not zero, then it is a register that a subsequent min() or
  74769. ** max() aggregate will set to 1 if the current row is not the minimum or
  74770. ** maximum. The P1 register is initialized to 0 by this instruction.
  74771. **
  74772. ** The interface used by the implementation of the aforementioned functions
  74773. ** to retrieve the collation sequence set by this opcode is not available
  74774. ** publicly. Only built-in functions have access to this feature.
  74775. */
  74776. case OP_CollSeq: {
  74777. assert( pOp->p4type==P4_COLLSEQ );
  74778. if( pOp->p1 ){
  74779. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  74780. }
  74781. break;
  74782. }
  74783. /* Opcode: Function0 P1 P2 P3 P4 P5
  74784. ** Synopsis: r[P3]=func(r[P2@P5])
  74785. **
  74786. ** Invoke a user function (P4 is a pointer to a FuncDef object that
  74787. ** defines the function) with P5 arguments taken from register P2 and
  74788. ** successors. The result of the function is stored in register P3.
  74789. ** Register P3 must not be one of the function inputs.
  74790. **
  74791. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  74792. ** function was determined to be constant at compile time. If the first
  74793. ** argument was constant then bit 0 of P1 is set. This is used to determine
  74794. ** whether meta data associated with a user function argument using the
  74795. ** sqlite3_set_auxdata() API may be safely retained until the next
  74796. ** invocation of this opcode.
  74797. **
  74798. ** See also: Function, AggStep, AggFinal
  74799. */
  74800. /* Opcode: Function P1 P2 P3 P4 P5
  74801. ** Synopsis: r[P3]=func(r[P2@P5])
  74802. **
  74803. ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
  74804. ** contains a pointer to the function to be run) with P5 arguments taken
  74805. ** from register P2 and successors. The result of the function is stored
  74806. ** in register P3. Register P3 must not be one of the function inputs.
  74807. **
  74808. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  74809. ** function was determined to be constant at compile time. If the first
  74810. ** argument was constant then bit 0 of P1 is set. This is used to determine
  74811. ** whether meta data associated with a user function argument using the
  74812. ** sqlite3_set_auxdata() API may be safely retained until the next
  74813. ** invocation of this opcode.
  74814. **
  74815. ** SQL functions are initially coded as OP_Function0 with P4 pointing
  74816. ** to a FuncDef object. But on first evaluation, the P4 operand is
  74817. ** automatically converted into an sqlite3_context object and the operation
  74818. ** changed to this OP_Function opcode. In this way, the initialization of
  74819. ** the sqlite3_context object occurs only once, rather than once for each
  74820. ** evaluation of the function.
  74821. **
  74822. ** See also: Function0, AggStep, AggFinal
  74823. */
  74824. case OP_Function0: {
  74825. int n;
  74826. sqlite3_context *pCtx;
  74827. assert( pOp->p4type==P4_FUNCDEF );
  74828. n = pOp->p5;
  74829. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  74830. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  74831. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  74832. pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  74833. if( pCtx==0 ) goto no_mem;
  74834. pCtx->pOut = 0;
  74835. pCtx->pFunc = pOp->p4.pFunc;
  74836. pCtx->iOp = (int)(pOp - aOp);
  74837. pCtx->pVdbe = p;
  74838. pCtx->argc = n;
  74839. pOp->p4type = P4_FUNCCTX;
  74840. pOp->p4.pCtx = pCtx;
  74841. pOp->opcode = OP_Function;
  74842. /* Fall through into OP_Function */
  74843. }
  74844. case OP_Function: {
  74845. int i;
  74846. sqlite3_context *pCtx;
  74847. assert( pOp->p4type==P4_FUNCCTX );
  74848. pCtx = pOp->p4.pCtx;
  74849. /* If this function is inside of a trigger, the register array in aMem[]
  74850. ** might change from one evaluation to the next. The next block of code
  74851. ** checks to see if the register array has changed, and if so it
  74852. ** reinitializes the relavant parts of the sqlite3_context object */
  74853. pOut = &aMem[pOp->p3];
  74854. if( pCtx->pOut != pOut ){
  74855. pCtx->pOut = pOut;
  74856. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  74857. }
  74858. memAboutToChange(p, pOut);
  74859. #ifdef SQLITE_DEBUG
  74860. for(i=0; i<pCtx->argc; i++){
  74861. assert( memIsValid(pCtx->argv[i]) );
  74862. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  74863. }
  74864. #endif
  74865. MemSetTypeFlag(pOut, MEM_Null);
  74866. pCtx->fErrorOrAux = 0;
  74867. (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
  74868. /* If the function returned an error, throw an exception */
  74869. if( pCtx->fErrorOrAux ){
  74870. if( pCtx->isError ){
  74871. sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
  74872. rc = pCtx->isError;
  74873. }
  74874. sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
  74875. if( rc ) goto abort_due_to_error;
  74876. }
  74877. /* Copy the result of the function into register P3 */
  74878. if( pOut->flags & (MEM_Str|MEM_Blob) ){
  74879. sqlite3VdbeChangeEncoding(pOut, encoding);
  74880. if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
  74881. }
  74882. REGISTER_TRACE(pOp->p3, pOut);
  74883. UPDATE_MAX_BLOBSIZE(pOut);
  74884. break;
  74885. }
  74886. /* Opcode: BitAnd P1 P2 P3 * *
  74887. ** Synopsis: r[P3]=r[P1]&r[P2]
  74888. **
  74889. ** Take the bit-wise AND of the values in register P1 and P2 and
  74890. ** store the result in register P3.
  74891. ** If either input is NULL, the result is NULL.
  74892. */
  74893. /* Opcode: BitOr P1 P2 P3 * *
  74894. ** Synopsis: r[P3]=r[P1]|r[P2]
  74895. **
  74896. ** Take the bit-wise OR of the values in register P1 and P2 and
  74897. ** store the result in register P3.
  74898. ** If either input is NULL, the result is NULL.
  74899. */
  74900. /* Opcode: ShiftLeft P1 P2 P3 * *
  74901. ** Synopsis: r[P3]=r[P2]<<r[P1]
  74902. **
  74903. ** Shift the integer value in register P2 to the left by the
  74904. ** number of bits specified by the integer in register P1.
  74905. ** Store the result in register P3.
  74906. ** If either input is NULL, the result is NULL.
  74907. */
  74908. /* Opcode: ShiftRight P1 P2 P3 * *
  74909. ** Synopsis: r[P3]=r[P2]>>r[P1]
  74910. **
  74911. ** Shift the integer value in register P2 to the right by the
  74912. ** number of bits specified by the integer in register P1.
  74913. ** Store the result in register P3.
  74914. ** If either input is NULL, the result is NULL.
  74915. */
  74916. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  74917. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  74918. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  74919. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  74920. i64 iA;
  74921. u64 uA;
  74922. i64 iB;
  74923. u8 op;
  74924. pIn1 = &aMem[pOp->p1];
  74925. pIn2 = &aMem[pOp->p2];
  74926. pOut = &aMem[pOp->p3];
  74927. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  74928. sqlite3VdbeMemSetNull(pOut);
  74929. break;
  74930. }
  74931. iA = sqlite3VdbeIntValue(pIn2);
  74932. iB = sqlite3VdbeIntValue(pIn1);
  74933. op = pOp->opcode;
  74934. if( op==OP_BitAnd ){
  74935. iA &= iB;
  74936. }else if( op==OP_BitOr ){
  74937. iA |= iB;
  74938. }else if( iB!=0 ){
  74939. assert( op==OP_ShiftRight || op==OP_ShiftLeft );
  74940. /* If shifting by a negative amount, shift in the other direction */
  74941. if( iB<0 ){
  74942. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  74943. op = 2*OP_ShiftLeft + 1 - op;
  74944. iB = iB>(-64) ? -iB : 64;
  74945. }
  74946. if( iB>=64 ){
  74947. iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
  74948. }else{
  74949. memcpy(&uA, &iA, sizeof(uA));
  74950. if( op==OP_ShiftLeft ){
  74951. uA <<= iB;
  74952. }else{
  74953. uA >>= iB;
  74954. /* Sign-extend on a right shift of a negative number */
  74955. if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
  74956. }
  74957. memcpy(&iA, &uA, sizeof(iA));
  74958. }
  74959. }
  74960. pOut->u.i = iA;
  74961. MemSetTypeFlag(pOut, MEM_Int);
  74962. break;
  74963. }
  74964. /* Opcode: AddImm P1 P2 * * *
  74965. ** Synopsis: r[P1]=r[P1]+P2
  74966. **
  74967. ** Add the constant P2 to the value in register P1.
  74968. ** The result is always an integer.
  74969. **
  74970. ** To force any register to be an integer, just add 0.
  74971. */
  74972. case OP_AddImm: { /* in1 */
  74973. pIn1 = &aMem[pOp->p1];
  74974. memAboutToChange(p, pIn1);
  74975. sqlite3VdbeMemIntegerify(pIn1);
  74976. pIn1->u.i += pOp->p2;
  74977. break;
  74978. }
  74979. /* Opcode: MustBeInt P1 P2 * * *
  74980. **
  74981. ** Force the value in register P1 to be an integer. If the value
  74982. ** in P1 is not an integer and cannot be converted into an integer
  74983. ** without data loss, then jump immediately to P2, or if P2==0
  74984. ** raise an SQLITE_MISMATCH exception.
  74985. */
  74986. case OP_MustBeInt: { /* jump, in1 */
  74987. pIn1 = &aMem[pOp->p1];
  74988. if( (pIn1->flags & MEM_Int)==0 ){
  74989. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  74990. VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
  74991. if( (pIn1->flags & MEM_Int)==0 ){
  74992. if( pOp->p2==0 ){
  74993. rc = SQLITE_MISMATCH;
  74994. goto abort_due_to_error;
  74995. }else{
  74996. goto jump_to_p2;
  74997. }
  74998. }
  74999. }
  75000. MemSetTypeFlag(pIn1, MEM_Int);
  75001. break;
  75002. }
  75003. #ifndef SQLITE_OMIT_FLOATING_POINT
  75004. /* Opcode: RealAffinity P1 * * * *
  75005. **
  75006. ** If register P1 holds an integer convert it to a real value.
  75007. **
  75008. ** This opcode is used when extracting information from a column that
  75009. ** has REAL affinity. Such column values may still be stored as
  75010. ** integers, for space efficiency, but after extraction we want them
  75011. ** to have only a real value.
  75012. */
  75013. case OP_RealAffinity: { /* in1 */
  75014. pIn1 = &aMem[pOp->p1];
  75015. if( pIn1->flags & MEM_Int ){
  75016. sqlite3VdbeMemRealify(pIn1);
  75017. }
  75018. break;
  75019. }
  75020. #endif
  75021. #ifndef SQLITE_OMIT_CAST
  75022. /* Opcode: Cast P1 P2 * * *
  75023. ** Synopsis: affinity(r[P1])
  75024. **
  75025. ** Force the value in register P1 to be the type defined by P2.
  75026. **
  75027. ** <ul>
  75028. ** <li> P2=='A' &rarr; BLOB
  75029. ** <li> P2=='B' &rarr; TEXT
  75030. ** <li> P2=='C' &rarr; NUMERIC
  75031. ** <li> P2=='D' &rarr; INTEGER
  75032. ** <li> P2=='E' &rarr; REAL
  75033. ** </ul>
  75034. **
  75035. ** A NULL value is not changed by this routine. It remains NULL.
  75036. */
  75037. case OP_Cast: { /* in1 */
  75038. assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
  75039. testcase( pOp->p2==SQLITE_AFF_TEXT );
  75040. testcase( pOp->p2==SQLITE_AFF_BLOB );
  75041. testcase( pOp->p2==SQLITE_AFF_NUMERIC );
  75042. testcase( pOp->p2==SQLITE_AFF_INTEGER );
  75043. testcase( pOp->p2==SQLITE_AFF_REAL );
  75044. pIn1 = &aMem[pOp->p1];
  75045. memAboutToChange(p, pIn1);
  75046. rc = ExpandBlob(pIn1);
  75047. sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
  75048. UPDATE_MAX_BLOBSIZE(pIn1);
  75049. if( rc ) goto abort_due_to_error;
  75050. break;
  75051. }
  75052. #endif /* SQLITE_OMIT_CAST */
  75053. /* Opcode: Eq P1 P2 P3 P4 P5
  75054. ** Synopsis: IF r[P3]==r[P1]
  75055. **
  75056. ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
  75057. ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
  75058. ** store the result of comparison in register P2.
  75059. **
  75060. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  75061. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  75062. ** to coerce both inputs according to this affinity before the
  75063. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  75064. ** affinity is used. Note that the affinity conversions are stored
  75065. ** back into the input registers P1 and P3. So this opcode can cause
  75066. ** persistent changes to registers P1 and P3.
  75067. **
  75068. ** Once any conversions have taken place, and neither value is NULL,
  75069. ** the values are compared. If both values are blobs then memcmp() is
  75070. ** used to determine the results of the comparison. If both values
  75071. ** are text, then the appropriate collating function specified in
  75072. ** P4 is used to do the comparison. If P4 is not specified then
  75073. ** memcmp() is used to compare text string. If both values are
  75074. ** numeric, then a numeric comparison is used. If the two values
  75075. ** are of different types, then numbers are considered less than
  75076. ** strings and strings are considered less than blobs.
  75077. **
  75078. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  75079. ** true or false and is never NULL. If both operands are NULL then the result
  75080. ** of comparison is true. If either operand is NULL then the result is false.
  75081. ** If neither operand is NULL the result is the same as it would be if
  75082. ** the SQLITE_NULLEQ flag were omitted from P5.
  75083. **
  75084. ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
  75085. ** content of r[P2] is only changed if the new value is NULL or 0 (false).
  75086. ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
  75087. */
  75088. /* Opcode: Ne P1 P2 P3 P4 P5
  75089. ** Synopsis: IF r[P3]!=r[P1]
  75090. **
  75091. ** This works just like the Eq opcode except that the jump is taken if
  75092. ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
  75093. ** additional information.
  75094. **
  75095. ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
  75096. ** content of r[P2] is only changed if the new value is NULL or 1 (true).
  75097. ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
  75098. */
  75099. /* Opcode: Lt P1 P2 P3 P4 P5
  75100. ** Synopsis: IF r[P3]<r[P1]
  75101. **
  75102. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  75103. ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
  75104. ** the result of comparison (0 or 1 or NULL) into register P2.
  75105. **
  75106. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  75107. ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
  75108. ** bit is clear then fall through if either operand is NULL.
  75109. **
  75110. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  75111. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  75112. ** to coerce both inputs according to this affinity before the
  75113. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  75114. ** affinity is used. Note that the affinity conversions are stored
  75115. ** back into the input registers P1 and P3. So this opcode can cause
  75116. ** persistent changes to registers P1 and P3.
  75117. **
  75118. ** Once any conversions have taken place, and neither value is NULL,
  75119. ** the values are compared. If both values are blobs then memcmp() is
  75120. ** used to determine the results of the comparison. If both values
  75121. ** are text, then the appropriate collating function specified in
  75122. ** P4 is used to do the comparison. If P4 is not specified then
  75123. ** memcmp() is used to compare text string. If both values are
  75124. ** numeric, then a numeric comparison is used. If the two values
  75125. ** are of different types, then numbers are considered less than
  75126. ** strings and strings are considered less than blobs.
  75127. */
  75128. /* Opcode: Le P1 P2 P3 P4 P5
  75129. ** Synopsis: IF r[P3]<=r[P1]
  75130. **
  75131. ** This works just like the Lt opcode except that the jump is taken if
  75132. ** the content of register P3 is less than or equal to the content of
  75133. ** register P1. See the Lt opcode for additional information.
  75134. */
  75135. /* Opcode: Gt P1 P2 P3 P4 P5
  75136. ** Synopsis: IF r[P3]>r[P1]
  75137. **
  75138. ** This works just like the Lt opcode except that the jump is taken if
  75139. ** the content of register P3 is greater than the content of
  75140. ** register P1. See the Lt opcode for additional information.
  75141. */
  75142. /* Opcode: Ge P1 P2 P3 P4 P5
  75143. ** Synopsis: IF r[P3]>=r[P1]
  75144. **
  75145. ** This works just like the Lt opcode except that the jump is taken if
  75146. ** the content of register P3 is greater than or equal to the content of
  75147. ** register P1. See the Lt opcode for additional information.
  75148. */
  75149. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  75150. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  75151. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  75152. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  75153. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  75154. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  75155. int res, res2; /* Result of the comparison of pIn1 against pIn3 */
  75156. char affinity; /* Affinity to use for comparison */
  75157. u16 flags1; /* Copy of initial value of pIn1->flags */
  75158. u16 flags3; /* Copy of initial value of pIn3->flags */
  75159. pIn1 = &aMem[pOp->p1];
  75160. pIn3 = &aMem[pOp->p3];
  75161. flags1 = pIn1->flags;
  75162. flags3 = pIn3->flags;
  75163. if( (flags1 | flags3)&MEM_Null ){
  75164. /* One or both operands are NULL */
  75165. if( pOp->p5 & SQLITE_NULLEQ ){
  75166. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  75167. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  75168. ** or not both operands are null.
  75169. */
  75170. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  75171. assert( (flags1 & MEM_Cleared)==0 );
  75172. assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
  75173. if( (flags1&flags3&MEM_Null)!=0
  75174. && (flags3&MEM_Cleared)==0
  75175. ){
  75176. res = 0; /* Operands are equal */
  75177. }else{
  75178. res = 1; /* Operands are not equal */
  75179. }
  75180. }else{
  75181. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  75182. ** then the result is always NULL.
  75183. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  75184. */
  75185. if( pOp->p5 & SQLITE_STOREP2 ){
  75186. pOut = &aMem[pOp->p2];
  75187. iCompare = 1; /* Operands are not equal */
  75188. memAboutToChange(p, pOut);
  75189. MemSetTypeFlag(pOut, MEM_Null);
  75190. REGISTER_TRACE(pOp->p2, pOut);
  75191. }else{
  75192. VdbeBranchTaken(2,3);
  75193. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  75194. goto jump_to_p2;
  75195. }
  75196. }
  75197. break;
  75198. }
  75199. }else{
  75200. /* Neither operand is NULL. Do a comparison. */
  75201. affinity = pOp->p5 & SQLITE_AFF_MASK;
  75202. if( affinity>=SQLITE_AFF_NUMERIC ){
  75203. if( (flags1 | flags3)&MEM_Str ){
  75204. if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  75205. applyNumericAffinity(pIn1,0);
  75206. testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */
  75207. flags3 = pIn3->flags;
  75208. }
  75209. if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  75210. applyNumericAffinity(pIn3,0);
  75211. }
  75212. }
  75213. /* Handle the common case of integer comparison here, as an
  75214. ** optimization, to avoid a call to sqlite3MemCompare() */
  75215. if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
  75216. if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
  75217. if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
  75218. res = 0;
  75219. goto compare_op;
  75220. }
  75221. }else if( affinity==SQLITE_AFF_TEXT ){
  75222. if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
  75223. testcase( pIn1->flags & MEM_Int );
  75224. testcase( pIn1->flags & MEM_Real );
  75225. sqlite3VdbeMemStringify(pIn1, encoding, 1);
  75226. testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
  75227. flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
  75228. assert( pIn1!=pIn3 );
  75229. }
  75230. if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
  75231. testcase( pIn3->flags & MEM_Int );
  75232. testcase( pIn3->flags & MEM_Real );
  75233. sqlite3VdbeMemStringify(pIn3, encoding, 1);
  75234. testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
  75235. flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
  75236. }
  75237. }
  75238. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  75239. res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  75240. }
  75241. compare_op:
  75242. switch( pOp->opcode ){
  75243. case OP_Eq: res2 = res==0; break;
  75244. case OP_Ne: res2 = res; break;
  75245. case OP_Lt: res2 = res<0; break;
  75246. case OP_Le: res2 = res<=0; break;
  75247. case OP_Gt: res2 = res>0; break;
  75248. default: res2 = res>=0; break;
  75249. }
  75250. /* Undo any changes made by applyAffinity() to the input registers. */
  75251. assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
  75252. pIn1->flags = flags1;
  75253. assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
  75254. pIn3->flags = flags3;
  75255. if( pOp->p5 & SQLITE_STOREP2 ){
  75256. pOut = &aMem[pOp->p2];
  75257. iCompare = res;
  75258. res2 = res2!=0; /* For this path res2 must be exactly 0 or 1 */
  75259. if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
  75260. /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
  75261. ** and prevents OP_Ne from overwriting NULL with 0. This flag
  75262. ** is only used in contexts where either:
  75263. ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
  75264. ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
  75265. ** Therefore it is not necessary to check the content of r[P2] for
  75266. ** NULL. */
  75267. assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
  75268. assert( res2==0 || res2==1 );
  75269. testcase( res2==0 && pOp->opcode==OP_Eq );
  75270. testcase( res2==1 && pOp->opcode==OP_Eq );
  75271. testcase( res2==0 && pOp->opcode==OP_Ne );
  75272. testcase( res2==1 && pOp->opcode==OP_Ne );
  75273. if( (pOp->opcode==OP_Eq)==res2 ) break;
  75274. }
  75275. memAboutToChange(p, pOut);
  75276. MemSetTypeFlag(pOut, MEM_Int);
  75277. pOut->u.i = res2;
  75278. REGISTER_TRACE(pOp->p2, pOut);
  75279. }else{
  75280. VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
  75281. if( res2 ){
  75282. goto jump_to_p2;
  75283. }
  75284. }
  75285. break;
  75286. }
  75287. /* Opcode: ElseNotEq * P2 * * *
  75288. **
  75289. ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
  75290. ** If result of an OP_Eq comparison on the same two operands
  75291. ** would have be NULL or false (0), then then jump to P2.
  75292. ** If the result of an OP_Eq comparison on the two previous operands
  75293. ** would have been true (1), then fall through.
  75294. */
  75295. case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
  75296. assert( pOp>aOp );
  75297. assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
  75298. assert( pOp[-1].p5 & SQLITE_STOREP2 );
  75299. VdbeBranchTaken(iCompare!=0, 2);
  75300. if( iCompare!=0 ) goto jump_to_p2;
  75301. break;
  75302. }
  75303. /* Opcode: Permutation * * * P4 *
  75304. **
  75305. ** Set the permutation used by the OP_Compare operator in the next
  75306. ** instruction. The permutation is stored in the P4 operand.
  75307. **
  75308. ** The permutation is only valid until the next OP_Compare that has
  75309. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  75310. ** occur immediately prior to the OP_Compare.
  75311. **
  75312. ** The first integer in the P4 integer array is the length of the array
  75313. ** and does not become part of the permutation.
  75314. */
  75315. case OP_Permutation: {
  75316. assert( pOp->p4type==P4_INTARRAY );
  75317. assert( pOp->p4.ai );
  75318. assert( pOp[1].opcode==OP_Compare );
  75319. assert( pOp[1].p5 & OPFLAG_PERMUTE );
  75320. break;
  75321. }
  75322. /* Opcode: Compare P1 P2 P3 P4 P5
  75323. ** Synopsis: r[P1@P3] <-> r[P2@P3]
  75324. **
  75325. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  75326. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  75327. ** the comparison for use by the next OP_Jump instruct.
  75328. **
  75329. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  75330. ** determined by the most recent OP_Permutation operator. If the
  75331. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  75332. ** order.
  75333. **
  75334. ** P4 is a KeyInfo structure that defines collating sequences and sort
  75335. ** orders for the comparison. The permutation applies to registers
  75336. ** only. The KeyInfo elements are used sequentially.
  75337. **
  75338. ** The comparison is a sort comparison, so NULLs compare equal,
  75339. ** NULLs are less than numbers, numbers are less than strings,
  75340. ** and strings are less than blobs.
  75341. */
  75342. case OP_Compare: {
  75343. int n;
  75344. int i;
  75345. int p1;
  75346. int p2;
  75347. const KeyInfo *pKeyInfo;
  75348. int idx;
  75349. CollSeq *pColl; /* Collating sequence to use on this term */
  75350. int bRev; /* True for DESCENDING sort order */
  75351. int *aPermute; /* The permutation */
  75352. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
  75353. aPermute = 0;
  75354. }else{
  75355. assert( pOp>aOp );
  75356. assert( pOp[-1].opcode==OP_Permutation );
  75357. assert( pOp[-1].p4type==P4_INTARRAY );
  75358. aPermute = pOp[-1].p4.ai + 1;
  75359. assert( aPermute!=0 );
  75360. }
  75361. n = pOp->p3;
  75362. pKeyInfo = pOp->p4.pKeyInfo;
  75363. assert( n>0 );
  75364. assert( pKeyInfo!=0 );
  75365. p1 = pOp->p1;
  75366. p2 = pOp->p2;
  75367. #ifdef SQLITE_DEBUG
  75368. if( aPermute ){
  75369. int k, mx = 0;
  75370. for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  75371. assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
  75372. assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
  75373. }else{
  75374. assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
  75375. assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
  75376. }
  75377. #endif /* SQLITE_DEBUG */
  75378. for(i=0; i<n; i++){
  75379. idx = aPermute ? aPermute[i] : i;
  75380. assert( memIsValid(&aMem[p1+idx]) );
  75381. assert( memIsValid(&aMem[p2+idx]) );
  75382. REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
  75383. REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
  75384. assert( i<pKeyInfo->nField );
  75385. pColl = pKeyInfo->aColl[i];
  75386. bRev = pKeyInfo->aSortOrder[i];
  75387. iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
  75388. if( iCompare ){
  75389. if( bRev ) iCompare = -iCompare;
  75390. break;
  75391. }
  75392. }
  75393. break;
  75394. }
  75395. /* Opcode: Jump P1 P2 P3 * *
  75396. **
  75397. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  75398. ** in the most recent OP_Compare instruction the P1 vector was less than
  75399. ** equal to, or greater than the P2 vector, respectively.
  75400. */
  75401. case OP_Jump: { /* jump */
  75402. if( iCompare<0 ){
  75403. VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
  75404. }else if( iCompare==0 ){
  75405. VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
  75406. }else{
  75407. VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
  75408. }
  75409. break;
  75410. }
  75411. /* Opcode: And P1 P2 P3 * *
  75412. ** Synopsis: r[P3]=(r[P1] && r[P2])
  75413. **
  75414. ** Take the logical AND of the values in registers P1 and P2 and
  75415. ** write the result into register P3.
  75416. **
  75417. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  75418. ** the other input is NULL. A NULL and true or two NULLs give
  75419. ** a NULL output.
  75420. */
  75421. /* Opcode: Or P1 P2 P3 * *
  75422. ** Synopsis: r[P3]=(r[P1] || r[P2])
  75423. **
  75424. ** Take the logical OR of the values in register P1 and P2 and
  75425. ** store the answer in register P3.
  75426. **
  75427. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  75428. ** even if the other input is NULL. A NULL and false or two NULLs
  75429. ** give a NULL output.
  75430. */
  75431. case OP_And: /* same as TK_AND, in1, in2, out3 */
  75432. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  75433. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  75434. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  75435. pIn1 = &aMem[pOp->p1];
  75436. if( pIn1->flags & MEM_Null ){
  75437. v1 = 2;
  75438. }else{
  75439. v1 = sqlite3VdbeIntValue(pIn1)!=0;
  75440. }
  75441. pIn2 = &aMem[pOp->p2];
  75442. if( pIn2->flags & MEM_Null ){
  75443. v2 = 2;
  75444. }else{
  75445. v2 = sqlite3VdbeIntValue(pIn2)!=0;
  75446. }
  75447. if( pOp->opcode==OP_And ){
  75448. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  75449. v1 = and_logic[v1*3+v2];
  75450. }else{
  75451. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  75452. v1 = or_logic[v1*3+v2];
  75453. }
  75454. pOut = &aMem[pOp->p3];
  75455. if( v1==2 ){
  75456. MemSetTypeFlag(pOut, MEM_Null);
  75457. }else{
  75458. pOut->u.i = v1;
  75459. MemSetTypeFlag(pOut, MEM_Int);
  75460. }
  75461. break;
  75462. }
  75463. /* Opcode: Not P1 P2 * * *
  75464. ** Synopsis: r[P2]= !r[P1]
  75465. **
  75466. ** Interpret the value in register P1 as a boolean value. Store the
  75467. ** boolean complement in register P2. If the value in register P1 is
  75468. ** NULL, then a NULL is stored in P2.
  75469. */
  75470. case OP_Not: { /* same as TK_NOT, in1, out2 */
  75471. pIn1 = &aMem[pOp->p1];
  75472. pOut = &aMem[pOp->p2];
  75473. sqlite3VdbeMemSetNull(pOut);
  75474. if( (pIn1->flags & MEM_Null)==0 ){
  75475. pOut->flags = MEM_Int;
  75476. pOut->u.i = !sqlite3VdbeIntValue(pIn1);
  75477. }
  75478. break;
  75479. }
  75480. /* Opcode: BitNot P1 P2 * * *
  75481. ** Synopsis: r[P1]= ~r[P1]
  75482. **
  75483. ** Interpret the content of register P1 as an integer. Store the
  75484. ** ones-complement of the P1 value into register P2. If P1 holds
  75485. ** a NULL then store a NULL in P2.
  75486. */
  75487. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  75488. pIn1 = &aMem[pOp->p1];
  75489. pOut = &aMem[pOp->p2];
  75490. sqlite3VdbeMemSetNull(pOut);
  75491. if( (pIn1->flags & MEM_Null)==0 ){
  75492. pOut->flags = MEM_Int;
  75493. pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
  75494. }
  75495. break;
  75496. }
  75497. /* Opcode: Once P1 P2 * * *
  75498. **
  75499. ** Fall through to the next instruction the first time this opcode is
  75500. ** encountered on each invocation of the byte-code program. Jump to P2
  75501. ** on the second and all subsequent encounters during the same invocation.
  75502. **
  75503. ** Top-level programs determine first invocation by comparing the P1
  75504. ** operand against the P1 operand on the OP_Init opcode at the beginning
  75505. ** of the program. If the P1 values differ, then fall through and make
  75506. ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
  75507. ** the same then take the jump.
  75508. **
  75509. ** For subprograms, there is a bitmask in the VdbeFrame that determines
  75510. ** whether or not the jump should be taken. The bitmask is necessary
  75511. ** because the self-altering code trick does not work for recursive
  75512. ** triggers.
  75513. */
  75514. case OP_Once: { /* jump */
  75515. u32 iAddr; /* Address of this instruction */
  75516. assert( p->aOp[0].opcode==OP_Init );
  75517. if( p->pFrame ){
  75518. iAddr = (int)(pOp - p->aOp);
  75519. if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
  75520. VdbeBranchTaken(1, 2);
  75521. goto jump_to_p2;
  75522. }
  75523. p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
  75524. }else{
  75525. if( p->aOp[0].p1==pOp->p1 ){
  75526. VdbeBranchTaken(1, 2);
  75527. goto jump_to_p2;
  75528. }
  75529. }
  75530. VdbeBranchTaken(0, 2);
  75531. pOp->p1 = p->aOp[0].p1;
  75532. break;
  75533. }
  75534. /* Opcode: If P1 P2 P3 * *
  75535. **
  75536. ** Jump to P2 if the value in register P1 is true. The value
  75537. ** is considered true if it is numeric and non-zero. If the value
  75538. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  75539. */
  75540. /* Opcode: IfNot P1 P2 P3 * *
  75541. **
  75542. ** Jump to P2 if the value in register P1 is False. The value
  75543. ** is considered false if it has a numeric value of zero. If the value
  75544. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  75545. */
  75546. case OP_If: /* jump, in1 */
  75547. case OP_IfNot: { /* jump, in1 */
  75548. int c;
  75549. pIn1 = &aMem[pOp->p1];
  75550. if( pIn1->flags & MEM_Null ){
  75551. c = pOp->p3;
  75552. }else{
  75553. #ifdef SQLITE_OMIT_FLOATING_POINT
  75554. c = sqlite3VdbeIntValue(pIn1)!=0;
  75555. #else
  75556. c = sqlite3VdbeRealValue(pIn1)!=0.0;
  75557. #endif
  75558. if( pOp->opcode==OP_IfNot ) c = !c;
  75559. }
  75560. VdbeBranchTaken(c!=0, 2);
  75561. if( c ){
  75562. goto jump_to_p2;
  75563. }
  75564. break;
  75565. }
  75566. /* Opcode: IsNull P1 P2 * * *
  75567. ** Synopsis: if r[P1]==NULL goto P2
  75568. **
  75569. ** Jump to P2 if the value in register P1 is NULL.
  75570. */
  75571. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  75572. pIn1 = &aMem[pOp->p1];
  75573. VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
  75574. if( (pIn1->flags & MEM_Null)!=0 ){
  75575. goto jump_to_p2;
  75576. }
  75577. break;
  75578. }
  75579. /* Opcode: NotNull P1 P2 * * *
  75580. ** Synopsis: if r[P1]!=NULL goto P2
  75581. **
  75582. ** Jump to P2 if the value in register P1 is not NULL.
  75583. */
  75584. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  75585. pIn1 = &aMem[pOp->p1];
  75586. VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
  75587. if( (pIn1->flags & MEM_Null)==0 ){
  75588. goto jump_to_p2;
  75589. }
  75590. break;
  75591. }
  75592. /* Opcode: IfNullRow P1 P2 P3 * *
  75593. ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
  75594. **
  75595. ** Check the cursor P1 to see if it is currently pointing at a NULL row.
  75596. ** If it is, then set register P3 to NULL and jump immediately to P2.
  75597. ** If P1 is not on a NULL row, then fall through without making any
  75598. ** changes.
  75599. */
  75600. case OP_IfNullRow: { /* jump */
  75601. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  75602. assert( p->apCsr[pOp->p1]!=0 );
  75603. if( p->apCsr[pOp->p1]->nullRow ){
  75604. sqlite3VdbeMemSetNull(aMem + pOp->p3);
  75605. goto jump_to_p2;
  75606. }
  75607. break;
  75608. }
  75609. /* Opcode: Column P1 P2 P3 P4 P5
  75610. ** Synopsis: r[P3]=PX
  75611. **
  75612. ** Interpret the data that cursor P1 points to as a structure built using
  75613. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  75614. ** information about the format of the data.) Extract the P2-th column
  75615. ** from this record. If there are less that (P2+1)
  75616. ** values in the record, extract a NULL.
  75617. **
  75618. ** The value extracted is stored in register P3.
  75619. **
  75620. ** If the record contains fewer than P2 fields, then extract a NULL. Or,
  75621. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  75622. ** the result.
  75623. **
  75624. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  75625. ** then the cache of the cursor is reset prior to extracting the column.
  75626. ** The first OP_Column against a pseudo-table after the value of the content
  75627. ** register has changed should have this bit set.
  75628. **
  75629. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
  75630. ** the result is guaranteed to only be used as the argument of a length()
  75631. ** or typeof() function, respectively. The loading of large blobs can be
  75632. ** skipped for length() and all content loading can be skipped for typeof().
  75633. */
  75634. case OP_Column: {
  75635. int p2; /* column number to retrieve */
  75636. VdbeCursor *pC; /* The VDBE cursor */
  75637. BtCursor *pCrsr; /* The BTree cursor */
  75638. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  75639. int len; /* The length of the serialized data for the column */
  75640. int i; /* Loop counter */
  75641. Mem *pDest; /* Where to write the extracted value */
  75642. Mem sMem; /* For storing the record being decoded */
  75643. const u8 *zData; /* Part of the record being decoded */
  75644. const u8 *zHdr; /* Next unparsed byte of the header */
  75645. const u8 *zEndHdr; /* Pointer to first byte after the header */
  75646. u32 offset; /* Offset into the data */
  75647. u64 offset64; /* 64-bit offset */
  75648. u32 avail; /* Number of bytes of available data */
  75649. u32 t; /* A type code from the record header */
  75650. Mem *pReg; /* PseudoTable input register */
  75651. pC = p->apCsr[pOp->p1];
  75652. p2 = pOp->p2;
  75653. /* If the cursor cache is stale, bring it up-to-date */
  75654. rc = sqlite3VdbeCursorMoveto(&pC, &p2);
  75655. if( rc ) goto abort_due_to_error;
  75656. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  75657. pDest = &aMem[pOp->p3];
  75658. memAboutToChange(p, pDest);
  75659. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  75660. assert( pC!=0 );
  75661. assert( p2<pC->nField );
  75662. aOffset = pC->aOffset;
  75663. assert( pC->eCurType!=CURTYPE_VTAB );
  75664. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  75665. assert( pC->eCurType!=CURTYPE_SORTER );
  75666. if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
  75667. if( pC->nullRow ){
  75668. if( pC->eCurType==CURTYPE_PSEUDO ){
  75669. assert( pC->uc.pseudoTableReg>0 );
  75670. pReg = &aMem[pC->uc.pseudoTableReg];
  75671. assert( pReg->flags & MEM_Blob );
  75672. assert( memIsValid(pReg) );
  75673. pC->payloadSize = pC->szRow = avail = pReg->n;
  75674. pC->aRow = (u8*)pReg->z;
  75675. }else{
  75676. sqlite3VdbeMemSetNull(pDest);
  75677. goto op_column_out;
  75678. }
  75679. }else{
  75680. pCrsr = pC->uc.pCursor;
  75681. assert( pC->eCurType==CURTYPE_BTREE );
  75682. assert( pCrsr );
  75683. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  75684. pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
  75685. pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &avail);
  75686. assert( avail<=65536 ); /* Maximum page size is 64KiB */
  75687. if( pC->payloadSize <= (u32)avail ){
  75688. pC->szRow = pC->payloadSize;
  75689. }else if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  75690. goto too_big;
  75691. }else{
  75692. pC->szRow = avail;
  75693. }
  75694. }
  75695. pC->cacheStatus = p->cacheCtr;
  75696. pC->iHdrOffset = getVarint32(pC->aRow, offset);
  75697. pC->nHdrParsed = 0;
  75698. aOffset[0] = offset;
  75699. if( avail<offset ){ /*OPTIMIZATION-IF-FALSE*/
  75700. /* pC->aRow does not have to hold the entire row, but it does at least
  75701. ** need to cover the header of the record. If pC->aRow does not contain
  75702. ** the complete header, then set it to zero, forcing the header to be
  75703. ** dynamically allocated. */
  75704. pC->aRow = 0;
  75705. pC->szRow = 0;
  75706. /* Make sure a corrupt database has not given us an oversize header.
  75707. ** Do this now to avoid an oversize memory allocation.
  75708. **
  75709. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  75710. ** types use so much data space that there can only be 4096 and 32 of
  75711. ** them, respectively. So the maximum header length results from a
  75712. ** 3-byte type for each of the maximum of 32768 columns plus three
  75713. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  75714. */
  75715. if( offset > 98307 || offset > pC->payloadSize ){
  75716. rc = SQLITE_CORRUPT_BKPT;
  75717. goto abort_due_to_error;
  75718. }
  75719. }else if( offset>0 ){ /*OPTIMIZATION-IF-TRUE*/
  75720. /* The following goto is an optimization. It can be omitted and
  75721. ** everything will still work. But OP_Column is measurably faster
  75722. ** by skipping the subsequent conditional, which is always true.
  75723. */
  75724. zData = pC->aRow;
  75725. assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
  75726. goto op_column_read_header;
  75727. }
  75728. }
  75729. /* Make sure at least the first p2+1 entries of the header have been
  75730. ** parsed and valid information is in aOffset[] and pC->aType[].
  75731. */
  75732. if( pC->nHdrParsed<=p2 ){
  75733. /* If there is more header available for parsing in the record, try
  75734. ** to extract additional fields up through the p2+1-th field
  75735. */
  75736. if( pC->iHdrOffset<aOffset[0] ){
  75737. /* Make sure zData points to enough of the record to cover the header. */
  75738. if( pC->aRow==0 ){
  75739. memset(&sMem, 0, sizeof(sMem));
  75740. rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
  75741. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  75742. zData = (u8*)sMem.z;
  75743. }else{
  75744. zData = pC->aRow;
  75745. }
  75746. /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
  75747. op_column_read_header:
  75748. i = pC->nHdrParsed;
  75749. offset64 = aOffset[i];
  75750. zHdr = zData + pC->iHdrOffset;
  75751. zEndHdr = zData + aOffset[0];
  75752. do{
  75753. if( (t = zHdr[0])<0x80 ){
  75754. zHdr++;
  75755. offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
  75756. }else{
  75757. zHdr += sqlite3GetVarint32(zHdr, &t);
  75758. offset64 += sqlite3VdbeSerialTypeLen(t);
  75759. }
  75760. pC->aType[i++] = t;
  75761. aOffset[i] = (u32)(offset64 & 0xffffffff);
  75762. }while( i<=p2 && zHdr<zEndHdr );
  75763. /* The record is corrupt if any of the following are true:
  75764. ** (1) the bytes of the header extend past the declared header size
  75765. ** (2) the entire header was used but not all data was used
  75766. ** (3) the end of the data extends beyond the end of the record.
  75767. */
  75768. if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
  75769. || (offset64 > pC->payloadSize)
  75770. ){
  75771. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  75772. rc = SQLITE_CORRUPT_BKPT;
  75773. goto abort_due_to_error;
  75774. }
  75775. pC->nHdrParsed = i;
  75776. pC->iHdrOffset = (u32)(zHdr - zData);
  75777. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  75778. }else{
  75779. t = 0;
  75780. }
  75781. /* If after trying to extract new entries from the header, nHdrParsed is
  75782. ** still not up to p2, that means that the record has fewer than p2
  75783. ** columns. So the result will be either the default value or a NULL.
  75784. */
  75785. if( pC->nHdrParsed<=p2 ){
  75786. if( pOp->p4type==P4_MEM ){
  75787. sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
  75788. }else{
  75789. sqlite3VdbeMemSetNull(pDest);
  75790. }
  75791. goto op_column_out;
  75792. }
  75793. }else{
  75794. t = pC->aType[p2];
  75795. }
  75796. /* Extract the content for the p2+1-th column. Control can only
  75797. ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
  75798. ** all valid.
  75799. */
  75800. assert( p2<pC->nHdrParsed );
  75801. assert( rc==SQLITE_OK );
  75802. assert( sqlite3VdbeCheckMemInvariants(pDest) );
  75803. if( VdbeMemDynamic(pDest) ){
  75804. sqlite3VdbeMemSetNull(pDest);
  75805. }
  75806. assert( t==pC->aType[p2] );
  75807. if( pC->szRow>=aOffset[p2+1] ){
  75808. /* This is the common case where the desired content fits on the original
  75809. ** page - where the content is not on an overflow page */
  75810. zData = pC->aRow + aOffset[p2];
  75811. if( t<12 ){
  75812. sqlite3VdbeSerialGet(zData, t, pDest);
  75813. }else{
  75814. /* If the column value is a string, we need a persistent value, not
  75815. ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
  75816. ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
  75817. */
  75818. static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
  75819. pDest->n = len = (t-12)/2;
  75820. pDest->enc = encoding;
  75821. if( pDest->szMalloc < len+2 ){
  75822. pDest->flags = MEM_Null;
  75823. if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
  75824. }else{
  75825. pDest->z = pDest->zMalloc;
  75826. }
  75827. memcpy(pDest->z, zData, len);
  75828. pDest->z[len] = 0;
  75829. pDest->z[len+1] = 0;
  75830. pDest->flags = aFlag[t&1];
  75831. }
  75832. }else{
  75833. pDest->enc = encoding;
  75834. /* This branch happens only when content is on overflow pages */
  75835. if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  75836. && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
  75837. || (len = sqlite3VdbeSerialTypeLen(t))==0
  75838. ){
  75839. /* Content is irrelevant for
  75840. ** 1. the typeof() function,
  75841. ** 2. the length(X) function if X is a blob, and
  75842. ** 3. if the content length is zero.
  75843. ** So we might as well use bogus content rather than reading
  75844. ** content from disk.
  75845. **
  75846. ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
  75847. ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
  75848. ** read up to 16. So 16 bytes of bogus content is supplied.
  75849. */
  75850. static u8 aZero[16]; /* This is the bogus content */
  75851. sqlite3VdbeSerialGet(aZero, t, pDest);
  75852. }else{
  75853. rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
  75854. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  75855. sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
  75856. pDest->flags &= ~MEM_Ephem;
  75857. }
  75858. }
  75859. op_column_out:
  75860. UPDATE_MAX_BLOBSIZE(pDest);
  75861. REGISTER_TRACE(pOp->p3, pDest);
  75862. break;
  75863. }
  75864. /* Opcode: Affinity P1 P2 * P4 *
  75865. ** Synopsis: affinity(r[P1@P2])
  75866. **
  75867. ** Apply affinities to a range of P2 registers starting with P1.
  75868. **
  75869. ** P4 is a string that is P2 characters long. The N-th character of the
  75870. ** string indicates the column affinity that should be used for the N-th
  75871. ** memory cell in the range.
  75872. */
  75873. case OP_Affinity: {
  75874. const char *zAffinity; /* The affinity to be applied */
  75875. zAffinity = pOp->p4.z;
  75876. assert( zAffinity!=0 );
  75877. assert( pOp->p2>0 );
  75878. assert( zAffinity[pOp->p2]==0 );
  75879. pIn1 = &aMem[pOp->p1];
  75880. do{
  75881. assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
  75882. assert( memIsValid(pIn1) );
  75883. applyAffinity(pIn1, *(zAffinity++), encoding);
  75884. pIn1++;
  75885. }while( zAffinity[0] );
  75886. break;
  75887. }
  75888. /* Opcode: MakeRecord P1 P2 P3 P4 *
  75889. ** Synopsis: r[P3]=mkrec(r[P1@P2])
  75890. **
  75891. ** Convert P2 registers beginning with P1 into the [record format]
  75892. ** use as a data record in a database table or as a key
  75893. ** in an index. The OP_Column opcode can decode the record later.
  75894. **
  75895. ** P4 may be a string that is P2 characters long. The N-th character of the
  75896. ** string indicates the column affinity that should be used for the N-th
  75897. ** field of the index key.
  75898. **
  75899. ** The mapping from character to affinity is given by the SQLITE_AFF_
  75900. ** macros defined in sqliteInt.h.
  75901. **
  75902. ** If P4 is NULL then all index fields have the affinity BLOB.
  75903. */
  75904. case OP_MakeRecord: {
  75905. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  75906. Mem *pRec; /* The new record */
  75907. u64 nData; /* Number of bytes of data space */
  75908. int nHdr; /* Number of bytes of header space */
  75909. i64 nByte; /* Data space required for this record */
  75910. i64 nZero; /* Number of zero bytes at the end of the record */
  75911. int nVarint; /* Number of bytes in a varint */
  75912. u32 serial_type; /* Type field */
  75913. Mem *pData0; /* First field to be combined into the record */
  75914. Mem *pLast; /* Last field of the record */
  75915. int nField; /* Number of fields in the record */
  75916. char *zAffinity; /* The affinity string for the record */
  75917. int file_format; /* File format to use for encoding */
  75918. int i; /* Space used in zNewRecord[] header */
  75919. int j; /* Space used in zNewRecord[] content */
  75920. u32 len; /* Length of a field */
  75921. /* Assuming the record contains N fields, the record format looks
  75922. ** like this:
  75923. **
  75924. ** ------------------------------------------------------------------------
  75925. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  75926. ** ------------------------------------------------------------------------
  75927. **
  75928. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  75929. ** and so forth.
  75930. **
  75931. ** Each type field is a varint representing the serial type of the
  75932. ** corresponding data element (see sqlite3VdbeSerialType()). The
  75933. ** hdr-size field is also a varint which is the offset from the beginning
  75934. ** of the record to data0.
  75935. */
  75936. nData = 0; /* Number of bytes of data space */
  75937. nHdr = 0; /* Number of bytes of header space */
  75938. nZero = 0; /* Number of zero bytes at the end of the record */
  75939. nField = pOp->p1;
  75940. zAffinity = pOp->p4.z;
  75941. assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
  75942. pData0 = &aMem[nField];
  75943. nField = pOp->p2;
  75944. pLast = &pData0[nField-1];
  75945. file_format = p->minWriteFileFormat;
  75946. /* Identify the output register */
  75947. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  75948. pOut = &aMem[pOp->p3];
  75949. memAboutToChange(p, pOut);
  75950. /* Apply the requested affinity to all inputs
  75951. */
  75952. assert( pData0<=pLast );
  75953. if( zAffinity ){
  75954. pRec = pData0;
  75955. do{
  75956. applyAffinity(pRec++, *(zAffinity++), encoding);
  75957. assert( zAffinity[0]==0 || pRec<=pLast );
  75958. }while( zAffinity[0] );
  75959. }
  75960. #ifdef SQLITE_ENABLE_NULL_TRIM
  75961. /* NULLs can be safely trimmed from the end of the record, as long as
  75962. ** as the schema format is 2 or more and none of the omitted columns
  75963. ** have a non-NULL default value. Also, the record must be left with
  75964. ** at least one field. If P5>0 then it will be one more than the
  75965. ** index of the right-most column with a non-NULL default value */
  75966. if( pOp->p5 ){
  75967. while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
  75968. pLast--;
  75969. nField--;
  75970. }
  75971. }
  75972. #endif
  75973. /* Loop through the elements that will make up the record to figure
  75974. ** out how much space is required for the new record.
  75975. */
  75976. pRec = pLast;
  75977. do{
  75978. assert( memIsValid(pRec) );
  75979. pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
  75980. if( pRec->flags & MEM_Zero ){
  75981. if( nData ){
  75982. if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
  75983. }else{
  75984. nZero += pRec->u.nZero;
  75985. len -= pRec->u.nZero;
  75986. }
  75987. }
  75988. nData += len;
  75989. testcase( serial_type==127 );
  75990. testcase( serial_type==128 );
  75991. nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
  75992. if( pRec==pData0 ) break;
  75993. pRec--;
  75994. }while(1);
  75995. /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
  75996. ** which determines the total number of bytes in the header. The varint
  75997. ** value is the size of the header in bytes including the size varint
  75998. ** itself. */
  75999. testcase( nHdr==126 );
  76000. testcase( nHdr==127 );
  76001. if( nHdr<=126 ){
  76002. /* The common case */
  76003. nHdr += 1;
  76004. }else{
  76005. /* Rare case of a really large header */
  76006. nVarint = sqlite3VarintLen(nHdr);
  76007. nHdr += nVarint;
  76008. if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
  76009. }
  76010. nByte = nHdr+nData;
  76011. if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  76012. goto too_big;
  76013. }
  76014. /* Make sure the output register has a buffer large enough to store
  76015. ** the new record. The output register (pOp->p3) is not allowed to
  76016. ** be one of the input registers (because the following call to
  76017. ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
  76018. */
  76019. if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
  76020. goto no_mem;
  76021. }
  76022. zNewRecord = (u8 *)pOut->z;
  76023. /* Write the record */
  76024. i = putVarint32(zNewRecord, nHdr);
  76025. j = nHdr;
  76026. assert( pData0<=pLast );
  76027. pRec = pData0;
  76028. do{
  76029. serial_type = pRec->uTemp;
  76030. /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
  76031. ** additional varints, one per column. */
  76032. i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
  76033. /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
  76034. ** immediately follow the header. */
  76035. j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
  76036. }while( (++pRec)<=pLast );
  76037. assert( i==nHdr );
  76038. assert( j==nByte );
  76039. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  76040. pOut->n = (int)nByte;
  76041. pOut->flags = MEM_Blob;
  76042. if( nZero ){
  76043. pOut->u.nZero = nZero;
  76044. pOut->flags |= MEM_Zero;
  76045. }
  76046. REGISTER_TRACE(pOp->p3, pOut);
  76047. UPDATE_MAX_BLOBSIZE(pOut);
  76048. break;
  76049. }
  76050. /* Opcode: Count P1 P2 * * *
  76051. ** Synopsis: r[P2]=count()
  76052. **
  76053. ** Store the number of entries (an integer value) in the table or index
  76054. ** opened by cursor P1 in register P2
  76055. */
  76056. #ifndef SQLITE_OMIT_BTREECOUNT
  76057. case OP_Count: { /* out2 */
  76058. i64 nEntry;
  76059. BtCursor *pCrsr;
  76060. assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
  76061. pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
  76062. assert( pCrsr );
  76063. nEntry = 0; /* Not needed. Only used to silence a warning. */
  76064. rc = sqlite3BtreeCount(pCrsr, &nEntry);
  76065. if( rc ) goto abort_due_to_error;
  76066. pOut = out2Prerelease(p, pOp);
  76067. pOut->u.i = nEntry;
  76068. break;
  76069. }
  76070. #endif
  76071. /* Opcode: Savepoint P1 * * P4 *
  76072. **
  76073. ** Open, release or rollback the savepoint named by parameter P4, depending
  76074. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  76075. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  76076. */
  76077. case OP_Savepoint: {
  76078. int p1; /* Value of P1 operand */
  76079. char *zName; /* Name of savepoint */
  76080. int nName;
  76081. Savepoint *pNew;
  76082. Savepoint *pSavepoint;
  76083. Savepoint *pTmp;
  76084. int iSavepoint;
  76085. int ii;
  76086. p1 = pOp->p1;
  76087. zName = pOp->p4.z;
  76088. /* Assert that the p1 parameter is valid. Also that if there is no open
  76089. ** transaction, then there cannot be any savepoints.
  76090. */
  76091. assert( db->pSavepoint==0 || db->autoCommit==0 );
  76092. assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  76093. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  76094. assert( checkSavepointCount(db) );
  76095. assert( p->bIsReader );
  76096. if( p1==SAVEPOINT_BEGIN ){
  76097. if( db->nVdbeWrite>0 ){
  76098. /* A new savepoint cannot be created if there are active write
  76099. ** statements (i.e. open read/write incremental blob handles).
  76100. */
  76101. sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
  76102. rc = SQLITE_BUSY;
  76103. }else{
  76104. nName = sqlite3Strlen30(zName);
  76105. #ifndef SQLITE_OMIT_VIRTUALTABLE
  76106. /* This call is Ok even if this savepoint is actually a transaction
  76107. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  76108. ** If this is a transaction savepoint being opened, it is guaranteed
  76109. ** that the db->aVTrans[] array is empty. */
  76110. assert( db->autoCommit==0 || db->nVTrans==0 );
  76111. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  76112. db->nStatement+db->nSavepoint);
  76113. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  76114. #endif
  76115. /* Create a new savepoint structure. */
  76116. pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
  76117. if( pNew ){
  76118. pNew->zName = (char *)&pNew[1];
  76119. memcpy(pNew->zName, zName, nName+1);
  76120. /* If there is no open transaction, then mark this as a special
  76121. ** "transaction savepoint". */
  76122. if( db->autoCommit ){
  76123. db->autoCommit = 0;
  76124. db->isTransactionSavepoint = 1;
  76125. }else{
  76126. db->nSavepoint++;
  76127. }
  76128. /* Link the new savepoint into the database handle's list. */
  76129. pNew->pNext = db->pSavepoint;
  76130. db->pSavepoint = pNew;
  76131. pNew->nDeferredCons = db->nDeferredCons;
  76132. pNew->nDeferredImmCons = db->nDeferredImmCons;
  76133. }
  76134. }
  76135. }else{
  76136. iSavepoint = 0;
  76137. /* Find the named savepoint. If there is no such savepoint, then an
  76138. ** an error is returned to the user. */
  76139. for(
  76140. pSavepoint = db->pSavepoint;
  76141. pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
  76142. pSavepoint = pSavepoint->pNext
  76143. ){
  76144. iSavepoint++;
  76145. }
  76146. if( !pSavepoint ){
  76147. sqlite3VdbeError(p, "no such savepoint: %s", zName);
  76148. rc = SQLITE_ERROR;
  76149. }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
  76150. /* It is not possible to release (commit) a savepoint if there are
  76151. ** active write statements.
  76152. */
  76153. sqlite3VdbeError(p, "cannot release savepoint - "
  76154. "SQL statements in progress");
  76155. rc = SQLITE_BUSY;
  76156. }else{
  76157. /* Determine whether or not this is a transaction savepoint. If so,
  76158. ** and this is a RELEASE command, then the current transaction
  76159. ** is committed.
  76160. */
  76161. int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
  76162. if( isTransaction && p1==SAVEPOINT_RELEASE ){
  76163. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  76164. goto vdbe_return;
  76165. }
  76166. db->autoCommit = 1;
  76167. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  76168. p->pc = (int)(pOp - aOp);
  76169. db->autoCommit = 0;
  76170. p->rc = rc = SQLITE_BUSY;
  76171. goto vdbe_return;
  76172. }
  76173. db->isTransactionSavepoint = 0;
  76174. rc = p->rc;
  76175. }else{
  76176. int isSchemaChange;
  76177. iSavepoint = db->nSavepoint - iSavepoint - 1;
  76178. if( p1==SAVEPOINT_ROLLBACK ){
  76179. isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
  76180. for(ii=0; ii<db->nDb; ii++){
  76181. rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
  76182. SQLITE_ABORT_ROLLBACK,
  76183. isSchemaChange==0);
  76184. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  76185. }
  76186. }else{
  76187. isSchemaChange = 0;
  76188. }
  76189. for(ii=0; ii<db->nDb; ii++){
  76190. rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
  76191. if( rc!=SQLITE_OK ){
  76192. goto abort_due_to_error;
  76193. }
  76194. }
  76195. if( isSchemaChange ){
  76196. sqlite3ExpirePreparedStatements(db);
  76197. sqlite3ResetAllSchemasOfConnection(db);
  76198. db->flags = (db->flags | SQLITE_InternChanges);
  76199. }
  76200. }
  76201. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  76202. ** savepoints nested inside of the savepoint being operated on. */
  76203. while( db->pSavepoint!=pSavepoint ){
  76204. pTmp = db->pSavepoint;
  76205. db->pSavepoint = pTmp->pNext;
  76206. sqlite3DbFree(db, pTmp);
  76207. db->nSavepoint--;
  76208. }
  76209. /* If it is a RELEASE, then destroy the savepoint being operated on
  76210. ** too. If it is a ROLLBACK TO, then set the number of deferred
  76211. ** constraint violations present in the database to the value stored
  76212. ** when the savepoint was created. */
  76213. if( p1==SAVEPOINT_RELEASE ){
  76214. assert( pSavepoint==db->pSavepoint );
  76215. db->pSavepoint = pSavepoint->pNext;
  76216. sqlite3DbFree(db, pSavepoint);
  76217. if( !isTransaction ){
  76218. db->nSavepoint--;
  76219. }
  76220. }else{
  76221. db->nDeferredCons = pSavepoint->nDeferredCons;
  76222. db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
  76223. }
  76224. if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
  76225. rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
  76226. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  76227. }
  76228. }
  76229. }
  76230. if( rc ) goto abort_due_to_error;
  76231. break;
  76232. }
  76233. /* Opcode: AutoCommit P1 P2 * * *
  76234. **
  76235. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  76236. ** back any currently active btree transactions. If there are any active
  76237. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  76238. ** there are active writing VMs or active VMs that use shared cache.
  76239. **
  76240. ** This instruction causes the VM to halt.
  76241. */
  76242. case OP_AutoCommit: {
  76243. int desiredAutoCommit;
  76244. int iRollback;
  76245. desiredAutoCommit = pOp->p1;
  76246. iRollback = pOp->p2;
  76247. assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  76248. assert( desiredAutoCommit==1 || iRollback==0 );
  76249. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  76250. assert( p->bIsReader );
  76251. if( desiredAutoCommit!=db->autoCommit ){
  76252. if( iRollback ){
  76253. assert( desiredAutoCommit==1 );
  76254. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  76255. db->autoCommit = 1;
  76256. }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
  76257. /* If this instruction implements a COMMIT and other VMs are writing
  76258. ** return an error indicating that the other VMs must complete first.
  76259. */
  76260. sqlite3VdbeError(p, "cannot commit transaction - "
  76261. "SQL statements in progress");
  76262. rc = SQLITE_BUSY;
  76263. goto abort_due_to_error;
  76264. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  76265. goto vdbe_return;
  76266. }else{
  76267. db->autoCommit = (u8)desiredAutoCommit;
  76268. }
  76269. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  76270. p->pc = (int)(pOp - aOp);
  76271. db->autoCommit = (u8)(1-desiredAutoCommit);
  76272. p->rc = rc = SQLITE_BUSY;
  76273. goto vdbe_return;
  76274. }
  76275. assert( db->nStatement==0 );
  76276. sqlite3CloseSavepoints(db);
  76277. if( p->rc==SQLITE_OK ){
  76278. rc = SQLITE_DONE;
  76279. }else{
  76280. rc = SQLITE_ERROR;
  76281. }
  76282. goto vdbe_return;
  76283. }else{
  76284. sqlite3VdbeError(p,
  76285. (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
  76286. (iRollback)?"cannot rollback - no transaction is active":
  76287. "cannot commit - no transaction is active"));
  76288. rc = SQLITE_ERROR;
  76289. goto abort_due_to_error;
  76290. }
  76291. break;
  76292. }
  76293. /* Opcode: Transaction P1 P2 P3 P4 P5
  76294. **
  76295. ** Begin a transaction on database P1 if a transaction is not already
  76296. ** active.
  76297. ** If P2 is non-zero, then a write-transaction is started, or if a
  76298. ** read-transaction is already active, it is upgraded to a write-transaction.
  76299. ** If P2 is zero, then a read-transaction is started.
  76300. **
  76301. ** P1 is the index of the database file on which the transaction is
  76302. ** started. Index 0 is the main database file and index 1 is the
  76303. ** file used for temporary tables. Indices of 2 or more are used for
  76304. ** attached databases.
  76305. **
  76306. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  76307. ** true (this flag is set if the Vdbe may modify more than one row and may
  76308. ** throw an ABORT exception), a statement transaction may also be opened.
  76309. ** More specifically, a statement transaction is opened iff the database
  76310. ** connection is currently not in autocommit mode, or if there are other
  76311. ** active statements. A statement transaction allows the changes made by this
  76312. ** VDBE to be rolled back after an error without having to roll back the
  76313. ** entire transaction. If no error is encountered, the statement transaction
  76314. ** will automatically commit when the VDBE halts.
  76315. **
  76316. ** If P5!=0 then this opcode also checks the schema cookie against P3
  76317. ** and the schema generation counter against P4.
  76318. ** The cookie changes its value whenever the database schema changes.
  76319. ** This operation is used to detect when that the cookie has changed
  76320. ** and that the current process needs to reread the schema. If the schema
  76321. ** cookie in P3 differs from the schema cookie in the database header or
  76322. ** if the schema generation counter in P4 differs from the current
  76323. ** generation counter, then an SQLITE_SCHEMA error is raised and execution
  76324. ** halts. The sqlite3_step() wrapper function might then reprepare the
  76325. ** statement and rerun it from the beginning.
  76326. */
  76327. case OP_Transaction: {
  76328. Btree *pBt;
  76329. int iMeta;
  76330. int iGen;
  76331. assert( p->bIsReader );
  76332. assert( p->readOnly==0 || pOp->p2==0 );
  76333. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  76334. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  76335. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  76336. rc = SQLITE_READONLY;
  76337. goto abort_due_to_error;
  76338. }
  76339. pBt = db->aDb[pOp->p1].pBt;
  76340. if( pBt ){
  76341. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
  76342. testcase( rc==SQLITE_BUSY_SNAPSHOT );
  76343. testcase( rc==SQLITE_BUSY_RECOVERY );
  76344. if( rc!=SQLITE_OK ){
  76345. if( (rc&0xff)==SQLITE_BUSY ){
  76346. p->pc = (int)(pOp - aOp);
  76347. p->rc = rc;
  76348. goto vdbe_return;
  76349. }
  76350. goto abort_due_to_error;
  76351. }
  76352. if( pOp->p2 && p->usesStmtJournal
  76353. && (db->autoCommit==0 || db->nVdbeRead>1)
  76354. ){
  76355. assert( sqlite3BtreeIsInTrans(pBt) );
  76356. if( p->iStatement==0 ){
  76357. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  76358. db->nStatement++;
  76359. p->iStatement = db->nSavepoint + db->nStatement;
  76360. }
  76361. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  76362. if( rc==SQLITE_OK ){
  76363. rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
  76364. }
  76365. /* Store the current value of the database handles deferred constraint
  76366. ** counter. If the statement transaction needs to be rolled back,
  76367. ** the value of this counter needs to be restored too. */
  76368. p->nStmtDefCons = db->nDeferredCons;
  76369. p->nStmtDefImmCons = db->nDeferredImmCons;
  76370. }
  76371. /* Gather the schema version number for checking:
  76372. ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
  76373. ** version is checked to ensure that the schema has not changed since the
  76374. ** SQL statement was prepared.
  76375. */
  76376. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
  76377. iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  76378. }else{
  76379. iGen = iMeta = 0;
  76380. }
  76381. assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
  76382. if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
  76383. sqlite3DbFree(db, p->zErrMsg);
  76384. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  76385. /* If the schema-cookie from the database file matches the cookie
  76386. ** stored with the in-memory representation of the schema, do
  76387. ** not reload the schema from the database file.
  76388. **
  76389. ** If virtual-tables are in use, this is not just an optimization.
  76390. ** Often, v-tables store their data in other SQLite tables, which
  76391. ** are queried from within xNext() and other v-table methods using
  76392. ** prepared queries. If such a query is out-of-date, we do not want to
  76393. ** discard the database schema, as the user code implementing the
  76394. ** v-table would have to be ready for the sqlite3_vtab structure itself
  76395. ** to be invalidated whenever sqlite3_step() is called from within
  76396. ** a v-table method.
  76397. */
  76398. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  76399. sqlite3ResetOneSchema(db, pOp->p1);
  76400. }
  76401. p->expired = 1;
  76402. rc = SQLITE_SCHEMA;
  76403. }
  76404. if( rc ) goto abort_due_to_error;
  76405. break;
  76406. }
  76407. /* Opcode: ReadCookie P1 P2 P3 * *
  76408. **
  76409. ** Read cookie number P3 from database P1 and write it into register P2.
  76410. ** P3==1 is the schema version. P3==2 is the database format.
  76411. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  76412. ** the main database file and P1==1 is the database file used to store
  76413. ** temporary tables.
  76414. **
  76415. ** There must be a read-lock on the database (either a transaction
  76416. ** must be started or there must be an open cursor) before
  76417. ** executing this instruction.
  76418. */
  76419. case OP_ReadCookie: { /* out2 */
  76420. int iMeta;
  76421. int iDb;
  76422. int iCookie;
  76423. assert( p->bIsReader );
  76424. iDb = pOp->p1;
  76425. iCookie = pOp->p3;
  76426. assert( pOp->p3<SQLITE_N_BTREE_META );
  76427. assert( iDb>=0 && iDb<db->nDb );
  76428. assert( db->aDb[iDb].pBt!=0 );
  76429. assert( DbMaskTest(p->btreeMask, iDb) );
  76430. sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
  76431. pOut = out2Prerelease(p, pOp);
  76432. pOut->u.i = iMeta;
  76433. break;
  76434. }
  76435. /* Opcode: SetCookie P1 P2 P3 * *
  76436. **
  76437. ** Write the integer value P3 into cookie number P2 of database P1.
  76438. ** P2==1 is the schema version. P2==2 is the database format.
  76439. ** P2==3 is the recommended pager cache
  76440. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  76441. ** database file used to store temporary tables.
  76442. **
  76443. ** A transaction must be started before executing this opcode.
  76444. */
  76445. case OP_SetCookie: {
  76446. Db *pDb;
  76447. assert( pOp->p2<SQLITE_N_BTREE_META );
  76448. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  76449. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  76450. assert( p->readOnly==0 );
  76451. pDb = &db->aDb[pOp->p1];
  76452. assert( pDb->pBt!=0 );
  76453. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  76454. /* See note about index shifting on OP_ReadCookie */
  76455. rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
  76456. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  76457. /* When the schema cookie changes, record the new cookie internally */
  76458. pDb->pSchema->schema_cookie = pOp->p3;
  76459. db->flags |= SQLITE_InternChanges;
  76460. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  76461. /* Record changes in the file format */
  76462. pDb->pSchema->file_format = pOp->p3;
  76463. }
  76464. if( pOp->p1==1 ){
  76465. /* Invalidate all prepared statements whenever the TEMP database
  76466. ** schema is changed. Ticket #1644 */
  76467. sqlite3ExpirePreparedStatements(db);
  76468. p->expired = 0;
  76469. }
  76470. if( rc ) goto abort_due_to_error;
  76471. break;
  76472. }
  76473. /* Opcode: OpenRead P1 P2 P3 P4 P5
  76474. ** Synopsis: root=P2 iDb=P3
  76475. **
  76476. ** Open a read-only cursor for the database table whose root page is
  76477. ** P2 in a database file. The database file is determined by P3.
  76478. ** P3==0 means the main database, P3==1 means the database used for
  76479. ** temporary tables, and P3>1 means used the corresponding attached
  76480. ** database. Give the new cursor an identifier of P1. The P1
  76481. ** values need not be contiguous but all P1 values should be small integers.
  76482. ** It is an error for P1 to be negative.
  76483. **
  76484. ** If P5!=0 then use the content of register P2 as the root page, not
  76485. ** the value of P2 itself.
  76486. **
  76487. ** There will be a read lock on the database whenever there is an
  76488. ** open cursor. If the database was unlocked prior to this instruction
  76489. ** then a read lock is acquired as part of this instruction. A read
  76490. ** lock allows other processes to read the database but prohibits
  76491. ** any other process from modifying the database. The read lock is
  76492. ** released when all cursors are closed. If this instruction attempts
  76493. ** to get a read lock but fails, the script terminates with an
  76494. ** SQLITE_BUSY error code.
  76495. **
  76496. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  76497. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  76498. ** structure, then said structure defines the content and collating
  76499. ** sequence of the index being opened. Otherwise, if P4 is an integer
  76500. ** value, it is set to the number of columns in the table.
  76501. **
  76502. ** See also: OpenWrite, ReopenIdx
  76503. */
  76504. /* Opcode: ReopenIdx P1 P2 P3 P4 P5
  76505. ** Synopsis: root=P2 iDb=P3
  76506. **
  76507. ** The ReopenIdx opcode works exactly like ReadOpen except that it first
  76508. ** checks to see if the cursor on P1 is already open with a root page
  76509. ** number of P2 and if it is this opcode becomes a no-op. In other words,
  76510. ** if the cursor is already open, do not reopen it.
  76511. **
  76512. ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
  76513. ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
  76514. ** every other ReopenIdx or OpenRead for the same cursor number.
  76515. **
  76516. ** See the OpenRead opcode documentation for additional information.
  76517. */
  76518. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  76519. ** Synopsis: root=P2 iDb=P3
  76520. **
  76521. ** Open a read/write cursor named P1 on the table or index whose root
  76522. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  76523. ** root page.
  76524. **
  76525. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  76526. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  76527. ** structure, then said structure defines the content and collating
  76528. ** sequence of the index being opened. Otherwise, if P4 is an integer
  76529. ** value, it is set to the number of columns in the table, or to the
  76530. ** largest index of any column of the table that is actually used.
  76531. **
  76532. ** This instruction works just like OpenRead except that it opens the cursor
  76533. ** in read/write mode. For a given table, there can be one or more read-only
  76534. ** cursors or a single read/write cursor but not both.
  76535. **
  76536. ** See also OpenRead.
  76537. */
  76538. case OP_ReopenIdx: {
  76539. int nField;
  76540. KeyInfo *pKeyInfo;
  76541. int p2;
  76542. int iDb;
  76543. int wrFlag;
  76544. Btree *pX;
  76545. VdbeCursor *pCur;
  76546. Db *pDb;
  76547. assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  76548. assert( pOp->p4type==P4_KEYINFO );
  76549. pCur = p->apCsr[pOp->p1];
  76550. if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
  76551. assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
  76552. goto open_cursor_set_hints;
  76553. }
  76554. /* If the cursor is not currently open or is open on a different
  76555. ** index, then fall through into OP_OpenRead to force a reopen */
  76556. case OP_OpenRead:
  76557. case OP_OpenWrite:
  76558. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  76559. assert( p->bIsReader );
  76560. assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
  76561. || p->readOnly==0 );
  76562. if( p->expired ){
  76563. rc = SQLITE_ABORT_ROLLBACK;
  76564. goto abort_due_to_error;
  76565. }
  76566. nField = 0;
  76567. pKeyInfo = 0;
  76568. p2 = pOp->p2;
  76569. iDb = pOp->p3;
  76570. assert( iDb>=0 && iDb<db->nDb );
  76571. assert( DbMaskTest(p->btreeMask, iDb) );
  76572. pDb = &db->aDb[iDb];
  76573. pX = pDb->pBt;
  76574. assert( pX!=0 );
  76575. if( pOp->opcode==OP_OpenWrite ){
  76576. assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
  76577. wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
  76578. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  76579. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  76580. p->minWriteFileFormat = pDb->pSchema->file_format;
  76581. }
  76582. }else{
  76583. wrFlag = 0;
  76584. }
  76585. if( pOp->p5 & OPFLAG_P2ISREG ){
  76586. assert( p2>0 );
  76587. assert( p2<=(p->nMem+1 - p->nCursor) );
  76588. pIn2 = &aMem[p2];
  76589. assert( memIsValid(pIn2) );
  76590. assert( (pIn2->flags & MEM_Int)!=0 );
  76591. sqlite3VdbeMemIntegerify(pIn2);
  76592. p2 = (int)pIn2->u.i;
  76593. /* The p2 value always comes from a prior OP_CreateTable opcode and
  76594. ** that opcode will always set the p2 value to 2 or more or else fail.
  76595. ** If there were a failure, the prepared statement would have halted
  76596. ** before reaching this instruction. */
  76597. assert( p2>=2 );
  76598. }
  76599. if( pOp->p4type==P4_KEYINFO ){
  76600. pKeyInfo = pOp->p4.pKeyInfo;
  76601. assert( pKeyInfo->enc==ENC(db) );
  76602. assert( pKeyInfo->db==db );
  76603. nField = pKeyInfo->nField+pKeyInfo->nXField;
  76604. }else if( pOp->p4type==P4_INT32 ){
  76605. nField = pOp->p4.i;
  76606. }
  76607. assert( pOp->p1>=0 );
  76608. assert( nField>=0 );
  76609. testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
  76610. pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
  76611. if( pCur==0 ) goto no_mem;
  76612. pCur->nullRow = 1;
  76613. pCur->isOrdered = 1;
  76614. pCur->pgnoRoot = p2;
  76615. #ifdef SQLITE_DEBUG
  76616. pCur->wrFlag = wrFlag;
  76617. #endif
  76618. rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
  76619. pCur->pKeyInfo = pKeyInfo;
  76620. /* Set the VdbeCursor.isTable variable. Previous versions of
  76621. ** SQLite used to check if the root-page flags were sane at this point
  76622. ** and report database corruption if they were not, but this check has
  76623. ** since moved into the btree layer. */
  76624. pCur->isTable = pOp->p4type!=P4_KEYINFO;
  76625. open_cursor_set_hints:
  76626. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  76627. assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
  76628. testcase( pOp->p5 & OPFLAG_BULKCSR );
  76629. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  76630. testcase( pOp->p2 & OPFLAG_SEEKEQ );
  76631. #endif
  76632. sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
  76633. (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
  76634. if( rc ) goto abort_due_to_error;
  76635. break;
  76636. }
  76637. /* Opcode: OpenDup P1 P2 * * *
  76638. **
  76639. ** Open a new cursor P1 that points to the same ephemeral table as
  76640. ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
  76641. ** opcode. Only ephemeral cursors may be duplicated.
  76642. **
  76643. ** Duplicate ephemeral cursors are used for self-joins of materialized views.
  76644. */
  76645. case OP_OpenDup: {
  76646. VdbeCursor *pOrig; /* The original cursor to be duplicated */
  76647. VdbeCursor *pCx; /* The new cursor */
  76648. pOrig = p->apCsr[pOp->p2];
  76649. assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */
  76650. pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
  76651. if( pCx==0 ) goto no_mem;
  76652. pCx->nullRow = 1;
  76653. pCx->isEphemeral = 1;
  76654. pCx->pKeyInfo = pOrig->pKeyInfo;
  76655. pCx->isTable = pOrig->isTable;
  76656. rc = sqlite3BtreeCursor(pOrig->pBtx, MASTER_ROOT, BTREE_WRCSR,
  76657. pCx->pKeyInfo, pCx->uc.pCursor);
  76658. /* The sqlite3BtreeCursor() routine can only fail for the first cursor
  76659. ** opened for a database. Since there is already an open cursor when this
  76660. ** opcode is run, the sqlite3BtreeCursor() cannot fail */
  76661. assert( rc==SQLITE_OK );
  76662. break;
  76663. }
  76664. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  76665. ** Synopsis: nColumn=P2
  76666. **
  76667. ** Open a new cursor P1 to a transient table.
  76668. ** The cursor is always opened read/write even if
  76669. ** the main database is read-only. The ephemeral
  76670. ** table is deleted automatically when the cursor is closed.
  76671. **
  76672. ** P2 is the number of columns in the ephemeral table.
  76673. ** The cursor points to a BTree table if P4==0 and to a BTree index
  76674. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  76675. ** that defines the format of keys in the index.
  76676. **
  76677. ** The P5 parameter can be a mask of the BTREE_* flags defined
  76678. ** in btree.h. These flags control aspects of the operation of
  76679. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  76680. ** added automatically.
  76681. */
  76682. /* Opcode: OpenAutoindex P1 P2 * P4 *
  76683. ** Synopsis: nColumn=P2
  76684. **
  76685. ** This opcode works the same as OP_OpenEphemeral. It has a
  76686. ** different name to distinguish its use. Tables created using
  76687. ** by this opcode will be used for automatically created transient
  76688. ** indices in joins.
  76689. */
  76690. case OP_OpenAutoindex:
  76691. case OP_OpenEphemeral: {
  76692. VdbeCursor *pCx;
  76693. KeyInfo *pKeyInfo;
  76694. static const int vfsFlags =
  76695. SQLITE_OPEN_READWRITE |
  76696. SQLITE_OPEN_CREATE |
  76697. SQLITE_OPEN_EXCLUSIVE |
  76698. SQLITE_OPEN_DELETEONCLOSE |
  76699. SQLITE_OPEN_TRANSIENT_DB;
  76700. assert( pOp->p1>=0 );
  76701. assert( pOp->p2>=0 );
  76702. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
  76703. if( pCx==0 ) goto no_mem;
  76704. pCx->nullRow = 1;
  76705. pCx->isEphemeral = 1;
  76706. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
  76707. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  76708. if( rc==SQLITE_OK ){
  76709. rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1);
  76710. }
  76711. if( rc==SQLITE_OK ){
  76712. /* If a transient index is required, create it by calling
  76713. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  76714. ** opening it. If a transient table is required, just use the
  76715. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  76716. */
  76717. if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
  76718. int pgno;
  76719. assert( pOp->p4type==P4_KEYINFO );
  76720. rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5);
  76721. if( rc==SQLITE_OK ){
  76722. assert( pgno==MASTER_ROOT+1 );
  76723. assert( pKeyInfo->db==db );
  76724. assert( pKeyInfo->enc==ENC(db) );
  76725. rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR,
  76726. pKeyInfo, pCx->uc.pCursor);
  76727. }
  76728. pCx->isTable = 0;
  76729. }else{
  76730. rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
  76731. 0, pCx->uc.pCursor);
  76732. pCx->isTable = 1;
  76733. }
  76734. }
  76735. if( rc ) goto abort_due_to_error;
  76736. pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  76737. break;
  76738. }
  76739. /* Opcode: SorterOpen P1 P2 P3 P4 *
  76740. **
  76741. ** This opcode works like OP_OpenEphemeral except that it opens
  76742. ** a transient index that is specifically designed to sort large
  76743. ** tables using an external merge-sort algorithm.
  76744. **
  76745. ** If argument P3 is non-zero, then it indicates that the sorter may
  76746. ** assume that a stable sort considering the first P3 fields of each
  76747. ** key is sufficient to produce the required results.
  76748. */
  76749. case OP_SorterOpen: {
  76750. VdbeCursor *pCx;
  76751. assert( pOp->p1>=0 );
  76752. assert( pOp->p2>=0 );
  76753. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
  76754. if( pCx==0 ) goto no_mem;
  76755. pCx->pKeyInfo = pOp->p4.pKeyInfo;
  76756. assert( pCx->pKeyInfo->db==db );
  76757. assert( pCx->pKeyInfo->enc==ENC(db) );
  76758. rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
  76759. if( rc ) goto abort_due_to_error;
  76760. break;
  76761. }
  76762. /* Opcode: SequenceTest P1 P2 * * *
  76763. ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
  76764. **
  76765. ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
  76766. ** to P2. Regardless of whether or not the jump is taken, increment the
  76767. ** the sequence value.
  76768. */
  76769. case OP_SequenceTest: {
  76770. VdbeCursor *pC;
  76771. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  76772. pC = p->apCsr[pOp->p1];
  76773. assert( isSorter(pC) );
  76774. if( (pC->seqCount++)==0 ){
  76775. goto jump_to_p2;
  76776. }
  76777. break;
  76778. }
  76779. /* Opcode: OpenPseudo P1 P2 P3 * *
  76780. ** Synopsis: P3 columns in r[P2]
  76781. **
  76782. ** Open a new cursor that points to a fake table that contains a single
  76783. ** row of data. The content of that one row is the content of memory
  76784. ** register P2. In other words, cursor P1 becomes an alias for the
  76785. ** MEM_Blob content contained in register P2.
  76786. **
  76787. ** A pseudo-table created by this opcode is used to hold a single
  76788. ** row output from the sorter so that the row can be decomposed into
  76789. ** individual columns using the OP_Column opcode. The OP_Column opcode
  76790. ** is the only cursor opcode that works with a pseudo-table.
  76791. **
  76792. ** P3 is the number of fields in the records that will be stored by
  76793. ** the pseudo-table.
  76794. */
  76795. case OP_OpenPseudo: {
  76796. VdbeCursor *pCx;
  76797. assert( pOp->p1>=0 );
  76798. assert( pOp->p3>=0 );
  76799. pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
  76800. if( pCx==0 ) goto no_mem;
  76801. pCx->nullRow = 1;
  76802. pCx->uc.pseudoTableReg = pOp->p2;
  76803. pCx->isTable = 1;
  76804. assert( pOp->p5==0 );
  76805. break;
  76806. }
  76807. /* Opcode: Close P1 * * * *
  76808. **
  76809. ** Close a cursor previously opened as P1. If P1 is not
  76810. ** currently open, this instruction is a no-op.
  76811. */
  76812. case OP_Close: {
  76813. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  76814. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  76815. p->apCsr[pOp->p1] = 0;
  76816. break;
  76817. }
  76818. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  76819. /* Opcode: ColumnsUsed P1 * * P4 *
  76820. **
  76821. ** This opcode (which only exists if SQLite was compiled with
  76822. ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
  76823. ** table or index for cursor P1 are used. P4 is a 64-bit integer
  76824. ** (P4_INT64) in which the first 63 bits are one for each of the
  76825. ** first 63 columns of the table or index that are actually used
  76826. ** by the cursor. The high-order bit is set if any column after
  76827. ** the 64th is used.
  76828. */
  76829. case OP_ColumnsUsed: {
  76830. VdbeCursor *pC;
  76831. pC = p->apCsr[pOp->p1];
  76832. assert( pC->eCurType==CURTYPE_BTREE );
  76833. pC->maskUsed = *(u64*)pOp->p4.pI64;
  76834. break;
  76835. }
  76836. #endif
  76837. /* Opcode: SeekGE P1 P2 P3 P4 *
  76838. ** Synopsis: key=r[P3@P4]
  76839. **
  76840. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  76841. ** use the value in register P3 as the key. If cursor P1 refers
  76842. ** to an SQL index, then P3 is the first in an array of P4 registers
  76843. ** that are used as an unpacked index key.
  76844. **
  76845. ** Reposition cursor P1 so that it points to the smallest entry that
  76846. ** is greater than or equal to the key value. If there are no records
  76847. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  76848. **
  76849. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  76850. ** opcode will always land on a record that equally equals the key, or
  76851. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  76852. ** opcode must be followed by an IdxLE opcode with the same arguments.
  76853. ** The IdxLE opcode will be skipped if this opcode succeeds, but the
  76854. ** IdxLE opcode will be used on subsequent loop iterations.
  76855. **
  76856. ** This opcode leaves the cursor configured to move in forward order,
  76857. ** from the beginning toward the end. In other words, the cursor is
  76858. ** configured to use Next, not Prev.
  76859. **
  76860. ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
  76861. */
  76862. /* Opcode: SeekGT P1 P2 P3 P4 *
  76863. ** Synopsis: key=r[P3@P4]
  76864. **
  76865. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  76866. ** use the value in register P3 as a key. If cursor P1 refers
  76867. ** to an SQL index, then P3 is the first in an array of P4 registers
  76868. ** that are used as an unpacked index key.
  76869. **
  76870. ** Reposition cursor P1 so that it points to the smallest entry that
  76871. ** is greater than the key value. If there are no records greater than
  76872. ** the key and P2 is not zero, then jump to P2.
  76873. **
  76874. ** This opcode leaves the cursor configured to move in forward order,
  76875. ** from the beginning toward the end. In other words, the cursor is
  76876. ** configured to use Next, not Prev.
  76877. **
  76878. ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
  76879. */
  76880. /* Opcode: SeekLT P1 P2 P3 P4 *
  76881. ** Synopsis: key=r[P3@P4]
  76882. **
  76883. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  76884. ** use the value in register P3 as a key. If cursor P1 refers
  76885. ** to an SQL index, then P3 is the first in an array of P4 registers
  76886. ** that are used as an unpacked index key.
  76887. **
  76888. ** Reposition cursor P1 so that it points to the largest entry that
  76889. ** is less than the key value. If there are no records less than
  76890. ** the key and P2 is not zero, then jump to P2.
  76891. **
  76892. ** This opcode leaves the cursor configured to move in reverse order,
  76893. ** from the end toward the beginning. In other words, the cursor is
  76894. ** configured to use Prev, not Next.
  76895. **
  76896. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
  76897. */
  76898. /* Opcode: SeekLE P1 P2 P3 P4 *
  76899. ** Synopsis: key=r[P3@P4]
  76900. **
  76901. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  76902. ** use the value in register P3 as a key. If cursor P1 refers
  76903. ** to an SQL index, then P3 is the first in an array of P4 registers
  76904. ** that are used as an unpacked index key.
  76905. **
  76906. ** Reposition cursor P1 so that it points to the largest entry that
  76907. ** is less than or equal to the key value. If there are no records
  76908. ** less than or equal to the key and P2 is not zero, then jump to P2.
  76909. **
  76910. ** This opcode leaves the cursor configured to move in reverse order,
  76911. ** from the end toward the beginning. In other words, the cursor is
  76912. ** configured to use Prev, not Next.
  76913. **
  76914. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  76915. ** opcode will always land on a record that equally equals the key, or
  76916. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  76917. ** opcode must be followed by an IdxGE opcode with the same arguments.
  76918. ** The IdxGE opcode will be skipped if this opcode succeeds, but the
  76919. ** IdxGE opcode will be used on subsequent loop iterations.
  76920. **
  76921. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
  76922. */
  76923. case OP_SeekLT: /* jump, in3 */
  76924. case OP_SeekLE: /* jump, in3 */
  76925. case OP_SeekGE: /* jump, in3 */
  76926. case OP_SeekGT: { /* jump, in3 */
  76927. int res; /* Comparison result */
  76928. int oc; /* Opcode */
  76929. VdbeCursor *pC; /* The cursor to seek */
  76930. UnpackedRecord r; /* The key to seek for */
  76931. int nField; /* Number of columns or fields in the key */
  76932. i64 iKey; /* The rowid we are to seek to */
  76933. int eqOnly; /* Only interested in == results */
  76934. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  76935. assert( pOp->p2!=0 );
  76936. pC = p->apCsr[pOp->p1];
  76937. assert( pC!=0 );
  76938. assert( pC->eCurType==CURTYPE_BTREE );
  76939. assert( OP_SeekLE == OP_SeekLT+1 );
  76940. assert( OP_SeekGE == OP_SeekLT+2 );
  76941. assert( OP_SeekGT == OP_SeekLT+3 );
  76942. assert( pC->isOrdered );
  76943. assert( pC->uc.pCursor!=0 );
  76944. oc = pOp->opcode;
  76945. eqOnly = 0;
  76946. pC->nullRow = 0;
  76947. #ifdef SQLITE_DEBUG
  76948. pC->seekOp = pOp->opcode;
  76949. #endif
  76950. if( pC->isTable ){
  76951. /* The BTREE_SEEK_EQ flag is only set on index cursors */
  76952. assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
  76953. || CORRUPT_DB );
  76954. /* The input value in P3 might be of any type: integer, real, string,
  76955. ** blob, or NULL. But it needs to be an integer before we can do
  76956. ** the seek, so convert it. */
  76957. pIn3 = &aMem[pOp->p3];
  76958. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  76959. applyNumericAffinity(pIn3, 0);
  76960. }
  76961. iKey = sqlite3VdbeIntValue(pIn3);
  76962. /* If the P3 value could not be converted into an integer without
  76963. ** loss of information, then special processing is required... */
  76964. if( (pIn3->flags & MEM_Int)==0 ){
  76965. if( (pIn3->flags & MEM_Real)==0 ){
  76966. /* If the P3 value cannot be converted into any kind of a number,
  76967. ** then the seek is not possible, so jump to P2 */
  76968. VdbeBranchTaken(1,2); goto jump_to_p2;
  76969. break;
  76970. }
  76971. /* If the approximation iKey is larger than the actual real search
  76972. ** term, substitute >= for > and < for <=. e.g. if the search term
  76973. ** is 4.9 and the integer approximation 5:
  76974. **
  76975. ** (x > 4.9) -> (x >= 5)
  76976. ** (x <= 4.9) -> (x < 5)
  76977. */
  76978. if( pIn3->u.r<(double)iKey ){
  76979. assert( OP_SeekGE==(OP_SeekGT-1) );
  76980. assert( OP_SeekLT==(OP_SeekLE-1) );
  76981. assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
  76982. if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
  76983. }
  76984. /* If the approximation iKey is smaller than the actual real search
  76985. ** term, substitute <= for < and > for >=. */
  76986. else if( pIn3->u.r>(double)iKey ){
  76987. assert( OP_SeekLE==(OP_SeekLT+1) );
  76988. assert( OP_SeekGT==(OP_SeekGE+1) );
  76989. assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
  76990. if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
  76991. }
  76992. }
  76993. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
  76994. pC->movetoTarget = iKey; /* Used by OP_Delete */
  76995. if( rc!=SQLITE_OK ){
  76996. goto abort_due_to_error;
  76997. }
  76998. }else{
  76999. /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
  77000. ** OP_SeekLE opcodes are allowed, and these must be immediately followed
  77001. ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
  77002. */
  77003. if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
  77004. eqOnly = 1;
  77005. assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
  77006. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  77007. assert( pOp[1].p1==pOp[0].p1 );
  77008. assert( pOp[1].p2==pOp[0].p2 );
  77009. assert( pOp[1].p3==pOp[0].p3 );
  77010. assert( pOp[1].p4.i==pOp[0].p4.i );
  77011. }
  77012. nField = pOp->p4.i;
  77013. assert( pOp->p4type==P4_INT32 );
  77014. assert( nField>0 );
  77015. r.pKeyInfo = pC->pKeyInfo;
  77016. r.nField = (u16)nField;
  77017. /* The next line of code computes as follows, only faster:
  77018. ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
  77019. ** r.default_rc = -1;
  77020. ** }else{
  77021. ** r.default_rc = +1;
  77022. ** }
  77023. */
  77024. r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
  77025. assert( oc!=OP_SeekGT || r.default_rc==-1 );
  77026. assert( oc!=OP_SeekLE || r.default_rc==-1 );
  77027. assert( oc!=OP_SeekGE || r.default_rc==+1 );
  77028. assert( oc!=OP_SeekLT || r.default_rc==+1 );
  77029. r.aMem = &aMem[pOp->p3];
  77030. #ifdef SQLITE_DEBUG
  77031. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  77032. #endif
  77033. r.eqSeen = 0;
  77034. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
  77035. if( rc!=SQLITE_OK ){
  77036. goto abort_due_to_error;
  77037. }
  77038. if( eqOnly && r.eqSeen==0 ){
  77039. assert( res!=0 );
  77040. goto seek_not_found;
  77041. }
  77042. }
  77043. pC->deferredMoveto = 0;
  77044. pC->cacheStatus = CACHE_STALE;
  77045. #ifdef SQLITE_TEST
  77046. sqlite3_search_count++;
  77047. #endif
  77048. if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
  77049. if( res<0 || (res==0 && oc==OP_SeekGT) ){
  77050. res = 0;
  77051. rc = sqlite3BtreeNext(pC->uc.pCursor, &res);
  77052. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  77053. }else{
  77054. res = 0;
  77055. }
  77056. }else{
  77057. assert( oc==OP_SeekLT || oc==OP_SeekLE );
  77058. if( res>0 || (res==0 && oc==OP_SeekLT) ){
  77059. res = 0;
  77060. rc = sqlite3BtreePrevious(pC->uc.pCursor, &res);
  77061. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  77062. }else{
  77063. /* res might be negative because the table is empty. Check to
  77064. ** see if this is the case.
  77065. */
  77066. res = sqlite3BtreeEof(pC->uc.pCursor);
  77067. }
  77068. }
  77069. seek_not_found:
  77070. assert( pOp->p2>0 );
  77071. VdbeBranchTaken(res!=0,2);
  77072. if( res ){
  77073. goto jump_to_p2;
  77074. }else if( eqOnly ){
  77075. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  77076. pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
  77077. }
  77078. break;
  77079. }
  77080. /* Opcode: Found P1 P2 P3 P4 *
  77081. ** Synopsis: key=r[P3@P4]
  77082. **
  77083. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  77084. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  77085. ** record.
  77086. **
  77087. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  77088. ** is a prefix of any entry in P1 then a jump is made to P2 and
  77089. ** P1 is left pointing at the matching entry.
  77090. **
  77091. ** This operation leaves the cursor in a state where it can be
  77092. ** advanced in the forward direction. The Next instruction will work,
  77093. ** but not the Prev instruction.
  77094. **
  77095. ** See also: NotFound, NoConflict, NotExists. SeekGe
  77096. */
  77097. /* Opcode: NotFound P1 P2 P3 P4 *
  77098. ** Synopsis: key=r[P3@P4]
  77099. **
  77100. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  77101. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  77102. ** record.
  77103. **
  77104. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  77105. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  77106. ** does contain an entry whose prefix matches the P3/P4 record then control
  77107. ** falls through to the next instruction and P1 is left pointing at the
  77108. ** matching entry.
  77109. **
  77110. ** This operation leaves the cursor in a state where it cannot be
  77111. ** advanced in either direction. In other words, the Next and Prev
  77112. ** opcodes do not work after this operation.
  77113. **
  77114. ** See also: Found, NotExists, NoConflict
  77115. */
  77116. /* Opcode: NoConflict P1 P2 P3 P4 *
  77117. ** Synopsis: key=r[P3@P4]
  77118. **
  77119. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  77120. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  77121. ** record.
  77122. **
  77123. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  77124. ** contains any NULL value, jump immediately to P2. If all terms of the
  77125. ** record are not-NULL then a check is done to determine if any row in the
  77126. ** P1 index btree has a matching key prefix. If there are no matches, jump
  77127. ** immediately to P2. If there is a match, fall through and leave the P1
  77128. ** cursor pointing to the matching row.
  77129. **
  77130. ** This opcode is similar to OP_NotFound with the exceptions that the
  77131. ** branch is always taken if any part of the search key input is NULL.
  77132. **
  77133. ** This operation leaves the cursor in a state where it cannot be
  77134. ** advanced in either direction. In other words, the Next and Prev
  77135. ** opcodes do not work after this operation.
  77136. **
  77137. ** See also: NotFound, Found, NotExists
  77138. */
  77139. case OP_NoConflict: /* jump, in3 */
  77140. case OP_NotFound: /* jump, in3 */
  77141. case OP_Found: { /* jump, in3 */
  77142. int alreadyExists;
  77143. int takeJump;
  77144. int ii;
  77145. VdbeCursor *pC;
  77146. int res;
  77147. UnpackedRecord *pFree;
  77148. UnpackedRecord *pIdxKey;
  77149. UnpackedRecord r;
  77150. #ifdef SQLITE_TEST
  77151. if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
  77152. #endif
  77153. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77154. assert( pOp->p4type==P4_INT32 );
  77155. pC = p->apCsr[pOp->p1];
  77156. assert( pC!=0 );
  77157. #ifdef SQLITE_DEBUG
  77158. pC->seekOp = pOp->opcode;
  77159. #endif
  77160. pIn3 = &aMem[pOp->p3];
  77161. assert( pC->eCurType==CURTYPE_BTREE );
  77162. assert( pC->uc.pCursor!=0 );
  77163. assert( pC->isTable==0 );
  77164. if( pOp->p4.i>0 ){
  77165. r.pKeyInfo = pC->pKeyInfo;
  77166. r.nField = (u16)pOp->p4.i;
  77167. r.aMem = pIn3;
  77168. #ifdef SQLITE_DEBUG
  77169. for(ii=0; ii<r.nField; ii++){
  77170. assert( memIsValid(&r.aMem[ii]) );
  77171. assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
  77172. if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
  77173. }
  77174. #endif
  77175. pIdxKey = &r;
  77176. pFree = 0;
  77177. }else{
  77178. assert( pIn3->flags & MEM_Blob );
  77179. rc = ExpandBlob(pIn3);
  77180. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  77181. if( rc ) goto no_mem;
  77182. pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
  77183. if( pIdxKey==0 ) goto no_mem;
  77184. sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
  77185. }
  77186. pIdxKey->default_rc = 0;
  77187. takeJump = 0;
  77188. if( pOp->opcode==OP_NoConflict ){
  77189. /* For the OP_NoConflict opcode, take the jump if any of the
  77190. ** input fields are NULL, since any key with a NULL will not
  77191. ** conflict */
  77192. for(ii=0; ii<pIdxKey->nField; ii++){
  77193. if( pIdxKey->aMem[ii].flags & MEM_Null ){
  77194. takeJump = 1;
  77195. break;
  77196. }
  77197. }
  77198. }
  77199. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
  77200. if( pFree ) sqlite3DbFreeNN(db, pFree);
  77201. if( rc!=SQLITE_OK ){
  77202. goto abort_due_to_error;
  77203. }
  77204. pC->seekResult = res;
  77205. alreadyExists = (res==0);
  77206. pC->nullRow = 1-alreadyExists;
  77207. pC->deferredMoveto = 0;
  77208. pC->cacheStatus = CACHE_STALE;
  77209. if( pOp->opcode==OP_Found ){
  77210. VdbeBranchTaken(alreadyExists!=0,2);
  77211. if( alreadyExists ) goto jump_to_p2;
  77212. }else{
  77213. VdbeBranchTaken(takeJump||alreadyExists==0,2);
  77214. if( takeJump || !alreadyExists ) goto jump_to_p2;
  77215. }
  77216. break;
  77217. }
  77218. /* Opcode: SeekRowid P1 P2 P3 * *
  77219. ** Synopsis: intkey=r[P3]
  77220. **
  77221. ** P1 is the index of a cursor open on an SQL table btree (with integer
  77222. ** keys). If register P3 does not contain an integer or if P1 does not
  77223. ** contain a record with rowid P3 then jump immediately to P2.
  77224. ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
  77225. ** a record with rowid P3 then
  77226. ** leave the cursor pointing at that record and fall through to the next
  77227. ** instruction.
  77228. **
  77229. ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
  77230. ** the P3 register must be guaranteed to contain an integer value. With this
  77231. ** opcode, register P3 might not contain an integer.
  77232. **
  77233. ** The OP_NotFound opcode performs the same operation on index btrees
  77234. ** (with arbitrary multi-value keys).
  77235. **
  77236. ** This opcode leaves the cursor in a state where it cannot be advanced
  77237. ** in either direction. In other words, the Next and Prev opcodes will
  77238. ** not work following this opcode.
  77239. **
  77240. ** See also: Found, NotFound, NoConflict, SeekRowid
  77241. */
  77242. /* Opcode: NotExists P1 P2 P3 * *
  77243. ** Synopsis: intkey=r[P3]
  77244. **
  77245. ** P1 is the index of a cursor open on an SQL table btree (with integer
  77246. ** keys). P3 is an integer rowid. If P1 does not contain a record with
  77247. ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
  77248. ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
  77249. ** leave the cursor pointing at that record and fall through to the next
  77250. ** instruction.
  77251. **
  77252. ** The OP_SeekRowid opcode performs the same operation but also allows the
  77253. ** P3 register to contain a non-integer value, in which case the jump is
  77254. ** always taken. This opcode requires that P3 always contain an integer.
  77255. **
  77256. ** The OP_NotFound opcode performs the same operation on index btrees
  77257. ** (with arbitrary multi-value keys).
  77258. **
  77259. ** This opcode leaves the cursor in a state where it cannot be advanced
  77260. ** in either direction. In other words, the Next and Prev opcodes will
  77261. ** not work following this opcode.
  77262. **
  77263. ** See also: Found, NotFound, NoConflict, SeekRowid
  77264. */
  77265. case OP_SeekRowid: { /* jump, in3 */
  77266. VdbeCursor *pC;
  77267. BtCursor *pCrsr;
  77268. int res;
  77269. u64 iKey;
  77270. pIn3 = &aMem[pOp->p3];
  77271. if( (pIn3->flags & MEM_Int)==0 ){
  77272. applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
  77273. if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
  77274. }
  77275. /* Fall through into OP_NotExists */
  77276. case OP_NotExists: /* jump, in3 */
  77277. pIn3 = &aMem[pOp->p3];
  77278. assert( pIn3->flags & MEM_Int );
  77279. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77280. pC = p->apCsr[pOp->p1];
  77281. assert( pC!=0 );
  77282. #ifdef SQLITE_DEBUG
  77283. pC->seekOp = 0;
  77284. #endif
  77285. assert( pC->isTable );
  77286. assert( pC->eCurType==CURTYPE_BTREE );
  77287. pCrsr = pC->uc.pCursor;
  77288. assert( pCrsr!=0 );
  77289. res = 0;
  77290. iKey = pIn3->u.i;
  77291. rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
  77292. assert( rc==SQLITE_OK || res==0 );
  77293. pC->movetoTarget = iKey; /* Used by OP_Delete */
  77294. pC->nullRow = 0;
  77295. pC->cacheStatus = CACHE_STALE;
  77296. pC->deferredMoveto = 0;
  77297. VdbeBranchTaken(res!=0,2);
  77298. pC->seekResult = res;
  77299. if( res!=0 ){
  77300. assert( rc==SQLITE_OK );
  77301. if( pOp->p2==0 ){
  77302. rc = SQLITE_CORRUPT_BKPT;
  77303. }else{
  77304. goto jump_to_p2;
  77305. }
  77306. }
  77307. if( rc ) goto abort_due_to_error;
  77308. break;
  77309. }
  77310. /* Opcode: Sequence P1 P2 * * *
  77311. ** Synopsis: r[P2]=cursor[P1].ctr++
  77312. **
  77313. ** Find the next available sequence number for cursor P1.
  77314. ** Write the sequence number into register P2.
  77315. ** The sequence number on the cursor is incremented after this
  77316. ** instruction.
  77317. */
  77318. case OP_Sequence: { /* out2 */
  77319. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77320. assert( p->apCsr[pOp->p1]!=0 );
  77321. assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
  77322. pOut = out2Prerelease(p, pOp);
  77323. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  77324. break;
  77325. }
  77326. /* Opcode: NewRowid P1 P2 P3 * *
  77327. ** Synopsis: r[P2]=rowid
  77328. **
  77329. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  77330. ** The record number is not previously used as a key in the database
  77331. ** table that cursor P1 points to. The new record number is written
  77332. ** written to register P2.
  77333. **
  77334. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  77335. ** the largest previously generated record number. No new record numbers are
  77336. ** allowed to be less than this value. When this value reaches its maximum,
  77337. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  77338. ** generated record number. This P3 mechanism is used to help implement the
  77339. ** AUTOINCREMENT feature.
  77340. */
  77341. case OP_NewRowid: { /* out2 */
  77342. i64 v; /* The new rowid */
  77343. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  77344. int res; /* Result of an sqlite3BtreeLast() */
  77345. int cnt; /* Counter to limit the number of searches */
  77346. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  77347. VdbeFrame *pFrame; /* Root frame of VDBE */
  77348. v = 0;
  77349. res = 0;
  77350. pOut = out2Prerelease(p, pOp);
  77351. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77352. pC = p->apCsr[pOp->p1];
  77353. assert( pC!=0 );
  77354. assert( pC->eCurType==CURTYPE_BTREE );
  77355. assert( pC->uc.pCursor!=0 );
  77356. {
  77357. /* The next rowid or record number (different terms for the same
  77358. ** thing) is obtained in a two-step algorithm.
  77359. **
  77360. ** First we attempt to find the largest existing rowid and add one
  77361. ** to that. But if the largest existing rowid is already the maximum
  77362. ** positive integer, we have to fall through to the second
  77363. ** probabilistic algorithm
  77364. **
  77365. ** The second algorithm is to select a rowid at random and see if
  77366. ** it already exists in the table. If it does not exist, we have
  77367. ** succeeded. If the random rowid does exist, we select a new one
  77368. ** and try again, up to 100 times.
  77369. */
  77370. assert( pC->isTable );
  77371. #ifdef SQLITE_32BIT_ROWID
  77372. # define MAX_ROWID 0x7fffffff
  77373. #else
  77374. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  77375. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  77376. ** to provide the constant while making all compilers happy.
  77377. */
  77378. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  77379. #endif
  77380. if( !pC->useRandomRowid ){
  77381. rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
  77382. if( rc!=SQLITE_OK ){
  77383. goto abort_due_to_error;
  77384. }
  77385. if( res ){
  77386. v = 1; /* IMP: R-61914-48074 */
  77387. }else{
  77388. assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
  77389. v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  77390. if( v>=MAX_ROWID ){
  77391. pC->useRandomRowid = 1;
  77392. }else{
  77393. v++; /* IMP: R-29538-34987 */
  77394. }
  77395. }
  77396. }
  77397. #ifndef SQLITE_OMIT_AUTOINCREMENT
  77398. if( pOp->p3 ){
  77399. /* Assert that P3 is a valid memory cell. */
  77400. assert( pOp->p3>0 );
  77401. if( p->pFrame ){
  77402. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  77403. /* Assert that P3 is a valid memory cell. */
  77404. assert( pOp->p3<=pFrame->nMem );
  77405. pMem = &pFrame->aMem[pOp->p3];
  77406. }else{
  77407. /* Assert that P3 is a valid memory cell. */
  77408. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  77409. pMem = &aMem[pOp->p3];
  77410. memAboutToChange(p, pMem);
  77411. }
  77412. assert( memIsValid(pMem) );
  77413. REGISTER_TRACE(pOp->p3, pMem);
  77414. sqlite3VdbeMemIntegerify(pMem);
  77415. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  77416. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  77417. rc = SQLITE_FULL; /* IMP: R-17817-00630 */
  77418. goto abort_due_to_error;
  77419. }
  77420. if( v<pMem->u.i+1 ){
  77421. v = pMem->u.i + 1;
  77422. }
  77423. pMem->u.i = v;
  77424. }
  77425. #endif
  77426. if( pC->useRandomRowid ){
  77427. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  77428. ** largest possible integer (9223372036854775807) then the database
  77429. ** engine starts picking positive candidate ROWIDs at random until
  77430. ** it finds one that is not previously used. */
  77431. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  77432. ** an AUTOINCREMENT table. */
  77433. cnt = 0;
  77434. do{
  77435. sqlite3_randomness(sizeof(v), &v);
  77436. v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
  77437. }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
  77438. 0, &res))==SQLITE_OK)
  77439. && (res==0)
  77440. && (++cnt<100));
  77441. if( rc ) goto abort_due_to_error;
  77442. if( res==0 ){
  77443. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  77444. goto abort_due_to_error;
  77445. }
  77446. assert( v>0 ); /* EV: R-40812-03570 */
  77447. }
  77448. pC->deferredMoveto = 0;
  77449. pC->cacheStatus = CACHE_STALE;
  77450. }
  77451. pOut->u.i = v;
  77452. break;
  77453. }
  77454. /* Opcode: Insert P1 P2 P3 P4 P5
  77455. ** Synopsis: intkey=r[P3] data=r[P2]
  77456. **
  77457. ** Write an entry into the table of cursor P1. A new entry is
  77458. ** created if it doesn't already exist or the data for an existing
  77459. ** entry is overwritten. The data is the value MEM_Blob stored in register
  77460. ** number P2. The key is stored in register P3. The key must
  77461. ** be a MEM_Int.
  77462. **
  77463. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  77464. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  77465. ** then rowid is stored for subsequent return by the
  77466. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  77467. **
  77468. ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
  77469. ** run faster by avoiding an unnecessary seek on cursor P1. However,
  77470. ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
  77471. ** seeks on the cursor or if the most recent seek used a key equal to P3.
  77472. **
  77473. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  77474. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  77475. ** is part of an INSERT operation. The difference is only important to
  77476. ** the update hook.
  77477. **
  77478. ** Parameter P4 may point to a Table structure, or may be NULL. If it is
  77479. ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
  77480. ** following a successful insert.
  77481. **
  77482. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  77483. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  77484. ** and register P2 becomes ephemeral. If the cursor is changed, the
  77485. ** value of register P2 will then change. Make sure this does not
  77486. ** cause any problems.)
  77487. **
  77488. ** This instruction only works on tables. The equivalent instruction
  77489. ** for indices is OP_IdxInsert.
  77490. */
  77491. /* Opcode: InsertInt P1 P2 P3 P4 P5
  77492. ** Synopsis: intkey=P3 data=r[P2]
  77493. **
  77494. ** This works exactly like OP_Insert except that the key is the
  77495. ** integer value P3, not the value of the integer stored in register P3.
  77496. */
  77497. case OP_Insert:
  77498. case OP_InsertInt: {
  77499. Mem *pData; /* MEM cell holding data for the record to be inserted */
  77500. Mem *pKey; /* MEM cell holding key for the record */
  77501. VdbeCursor *pC; /* Cursor to table into which insert is written */
  77502. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  77503. const char *zDb; /* database name - used by the update hook */
  77504. Table *pTab; /* Table structure - used by update and pre-update hooks */
  77505. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  77506. BtreePayload x; /* Payload to be inserted */
  77507. op = 0;
  77508. pData = &aMem[pOp->p2];
  77509. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77510. assert( memIsValid(pData) );
  77511. pC = p->apCsr[pOp->p1];
  77512. assert( pC!=0 );
  77513. assert( pC->eCurType==CURTYPE_BTREE );
  77514. assert( pC->uc.pCursor!=0 );
  77515. assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
  77516. assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
  77517. REGISTER_TRACE(pOp->p2, pData);
  77518. if( pOp->opcode==OP_Insert ){
  77519. pKey = &aMem[pOp->p3];
  77520. assert( pKey->flags & MEM_Int );
  77521. assert( memIsValid(pKey) );
  77522. REGISTER_TRACE(pOp->p3, pKey);
  77523. x.nKey = pKey->u.i;
  77524. }else{
  77525. assert( pOp->opcode==OP_InsertInt );
  77526. x.nKey = pOp->p3;
  77527. }
  77528. if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  77529. assert( pC->iDb>=0 );
  77530. zDb = db->aDb[pC->iDb].zDbSName;
  77531. pTab = pOp->p4.pTab;
  77532. assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
  77533. op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  77534. }else{
  77535. pTab = 0; /* Not needed. Silence a compiler warning. */
  77536. zDb = 0; /* Not needed. Silence a compiler warning. */
  77537. }
  77538. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  77539. /* Invoke the pre-update hook, if any */
  77540. if( db->xPreUpdateCallback
  77541. && pOp->p4type==P4_TABLE
  77542. && !(pOp->p5 & OPFLAG_ISUPDATE)
  77543. ){
  77544. sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey, pOp->p2);
  77545. }
  77546. if( pOp->p5 & OPFLAG_ISNOOP ) break;
  77547. #endif
  77548. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  77549. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
  77550. if( pData->flags & MEM_Null ){
  77551. x.pData = 0;
  77552. x.nData = 0;
  77553. }else{
  77554. assert( pData->flags & (MEM_Blob|MEM_Str) );
  77555. x.pData = pData->z;
  77556. x.nData = pData->n;
  77557. }
  77558. seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
  77559. if( pData->flags & MEM_Zero ){
  77560. x.nZero = pData->u.nZero;
  77561. }else{
  77562. x.nZero = 0;
  77563. }
  77564. x.pKey = 0;
  77565. rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
  77566. (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
  77567. );
  77568. pC->deferredMoveto = 0;
  77569. pC->cacheStatus = CACHE_STALE;
  77570. /* Invoke the update-hook if required. */
  77571. if( rc ) goto abort_due_to_error;
  77572. if( db->xUpdateCallback && op ){
  77573. db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, x.nKey);
  77574. }
  77575. break;
  77576. }
  77577. /* Opcode: Delete P1 P2 P3 P4 P5
  77578. **
  77579. ** Delete the record at which the P1 cursor is currently pointing.
  77580. **
  77581. ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
  77582. ** the cursor will be left pointing at either the next or the previous
  77583. ** record in the table. If it is left pointing at the next record, then
  77584. ** the next Next instruction will be a no-op. As a result, in this case
  77585. ** it is ok to delete a record from within a Next loop. If
  77586. ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
  77587. ** left in an undefined state.
  77588. **
  77589. ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
  77590. ** delete one of several associated with deleting a table row and all its
  77591. ** associated index entries. Exactly one of those deletes is the "primary"
  77592. ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
  77593. ** marked with the AUXDELETE flag.
  77594. **
  77595. ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
  77596. ** change count is incremented (otherwise not).
  77597. **
  77598. ** P1 must not be pseudo-table. It has to be a real table with
  77599. ** multiple rows.
  77600. **
  77601. ** If P4 is not NULL then it points to a Table object. In this case either
  77602. ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
  77603. ** have been positioned using OP_NotFound prior to invoking this opcode in
  77604. ** this case. Specifically, if one is configured, the pre-update hook is
  77605. ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
  77606. ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
  77607. **
  77608. ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
  77609. ** of the memory cell that contains the value that the rowid of the row will
  77610. ** be set to by the update.
  77611. */
  77612. case OP_Delete: {
  77613. VdbeCursor *pC;
  77614. const char *zDb;
  77615. Table *pTab;
  77616. int opflags;
  77617. opflags = pOp->p2;
  77618. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77619. pC = p->apCsr[pOp->p1];
  77620. assert( pC!=0 );
  77621. assert( pC->eCurType==CURTYPE_BTREE );
  77622. assert( pC->uc.pCursor!=0 );
  77623. assert( pC->deferredMoveto==0 );
  77624. #ifdef SQLITE_DEBUG
  77625. if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
  77626. /* If p5 is zero, the seek operation that positioned the cursor prior to
  77627. ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
  77628. ** the row that is being deleted */
  77629. i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  77630. assert( pC->movetoTarget==iKey );
  77631. }
  77632. #endif
  77633. /* If the update-hook or pre-update-hook will be invoked, set zDb to
  77634. ** the name of the db to pass as to it. Also set local pTab to a copy
  77635. ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
  77636. ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
  77637. ** VdbeCursor.movetoTarget to the current rowid. */
  77638. if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  77639. assert( pC->iDb>=0 );
  77640. assert( pOp->p4.pTab!=0 );
  77641. zDb = db->aDb[pC->iDb].zDbSName;
  77642. pTab = pOp->p4.pTab;
  77643. if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
  77644. pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  77645. }
  77646. }else{
  77647. zDb = 0; /* Not needed. Silence a compiler warning. */
  77648. pTab = 0; /* Not needed. Silence a compiler warning. */
  77649. }
  77650. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  77651. /* Invoke the pre-update-hook if required. */
  77652. if( db->xPreUpdateCallback && pOp->p4.pTab ){
  77653. assert( !(opflags & OPFLAG_ISUPDATE)
  77654. || HasRowid(pTab)==0
  77655. || (aMem[pOp->p3].flags & MEM_Int)
  77656. );
  77657. sqlite3VdbePreUpdateHook(p, pC,
  77658. (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
  77659. zDb, pTab, pC->movetoTarget,
  77660. pOp->p3
  77661. );
  77662. }
  77663. if( opflags & OPFLAG_ISNOOP ) break;
  77664. #endif
  77665. /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
  77666. assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
  77667. assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
  77668. assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
  77669. #ifdef SQLITE_DEBUG
  77670. if( p->pFrame==0 ){
  77671. if( pC->isEphemeral==0
  77672. && (pOp->p5 & OPFLAG_AUXDELETE)==0
  77673. && (pC->wrFlag & OPFLAG_FORDELETE)==0
  77674. ){
  77675. nExtraDelete++;
  77676. }
  77677. if( pOp->p2 & OPFLAG_NCHANGE ){
  77678. nExtraDelete--;
  77679. }
  77680. }
  77681. #endif
  77682. rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
  77683. pC->cacheStatus = CACHE_STALE;
  77684. pC->seekResult = 0;
  77685. if( rc ) goto abort_due_to_error;
  77686. /* Invoke the update-hook if required. */
  77687. if( opflags & OPFLAG_NCHANGE ){
  77688. p->nChange++;
  77689. if( db->xUpdateCallback && HasRowid(pTab) ){
  77690. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
  77691. pC->movetoTarget);
  77692. assert( pC->iDb>=0 );
  77693. }
  77694. }
  77695. break;
  77696. }
  77697. /* Opcode: ResetCount * * * * *
  77698. **
  77699. ** The value of the change counter is copied to the database handle
  77700. ** change counter (returned by subsequent calls to sqlite3_changes()).
  77701. ** Then the VMs internal change counter resets to 0.
  77702. ** This is used by trigger programs.
  77703. */
  77704. case OP_ResetCount: {
  77705. sqlite3VdbeSetChanges(db, p->nChange);
  77706. p->nChange = 0;
  77707. break;
  77708. }
  77709. /* Opcode: SorterCompare P1 P2 P3 P4
  77710. ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
  77711. **
  77712. ** P1 is a sorter cursor. This instruction compares a prefix of the
  77713. ** record blob in register P3 against a prefix of the entry that
  77714. ** the sorter cursor currently points to. Only the first P4 fields
  77715. ** of r[P3] and the sorter record are compared.
  77716. **
  77717. ** If either P3 or the sorter contains a NULL in one of their significant
  77718. ** fields (not counting the P4 fields at the end which are ignored) then
  77719. ** the comparison is assumed to be equal.
  77720. **
  77721. ** Fall through to next instruction if the two records compare equal to
  77722. ** each other. Jump to P2 if they are different.
  77723. */
  77724. case OP_SorterCompare: {
  77725. VdbeCursor *pC;
  77726. int res;
  77727. int nKeyCol;
  77728. pC = p->apCsr[pOp->p1];
  77729. assert( isSorter(pC) );
  77730. assert( pOp->p4type==P4_INT32 );
  77731. pIn3 = &aMem[pOp->p3];
  77732. nKeyCol = pOp->p4.i;
  77733. res = 0;
  77734. rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
  77735. VdbeBranchTaken(res!=0,2);
  77736. if( rc ) goto abort_due_to_error;
  77737. if( res ) goto jump_to_p2;
  77738. break;
  77739. };
  77740. /* Opcode: SorterData P1 P2 P3 * *
  77741. ** Synopsis: r[P2]=data
  77742. **
  77743. ** Write into register P2 the current sorter data for sorter cursor P1.
  77744. ** Then clear the column header cache on cursor P3.
  77745. **
  77746. ** This opcode is normally use to move a record out of the sorter and into
  77747. ** a register that is the source for a pseudo-table cursor created using
  77748. ** OpenPseudo. That pseudo-table cursor is the one that is identified by
  77749. ** parameter P3. Clearing the P3 column cache as part of this opcode saves
  77750. ** us from having to issue a separate NullRow instruction to clear that cache.
  77751. */
  77752. case OP_SorterData: {
  77753. VdbeCursor *pC;
  77754. pOut = &aMem[pOp->p2];
  77755. pC = p->apCsr[pOp->p1];
  77756. assert( isSorter(pC) );
  77757. rc = sqlite3VdbeSorterRowkey(pC, pOut);
  77758. assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
  77759. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77760. if( rc ) goto abort_due_to_error;
  77761. p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
  77762. break;
  77763. }
  77764. /* Opcode: RowData P1 P2 P3 * *
  77765. ** Synopsis: r[P2]=data
  77766. **
  77767. ** Write into register P2 the complete row content for the row at
  77768. ** which cursor P1 is currently pointing.
  77769. ** There is no interpretation of the data.
  77770. ** It is just copied onto the P2 register exactly as
  77771. ** it is found in the database file.
  77772. **
  77773. ** If cursor P1 is an index, then the content is the key of the row.
  77774. ** If cursor P2 is a table, then the content extracted is the data.
  77775. **
  77776. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  77777. ** of a real table, not a pseudo-table.
  77778. **
  77779. ** If P3!=0 then this opcode is allowed to make an ephermeral pointer
  77780. ** into the database page. That means that the content of the output
  77781. ** register will be invalidated as soon as the cursor moves - including
  77782. ** moves caused by other cursors that "save" the the current cursors
  77783. ** position in order that they can write to the same table. If P3==0
  77784. ** then a copy of the data is made into memory. P3!=0 is faster, but
  77785. ** P3==0 is safer.
  77786. **
  77787. ** If P3!=0 then the content of the P2 register is unsuitable for use
  77788. ** in OP_Result and any OP_Result will invalidate the P2 register content.
  77789. ** The P2 register content is invalidated by opcodes like OP_Function or
  77790. ** by any use of another cursor pointing to the same table.
  77791. */
  77792. case OP_RowData: {
  77793. VdbeCursor *pC;
  77794. BtCursor *pCrsr;
  77795. u32 n;
  77796. pOut = out2Prerelease(p, pOp);
  77797. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77798. pC = p->apCsr[pOp->p1];
  77799. assert( pC!=0 );
  77800. assert( pC->eCurType==CURTYPE_BTREE );
  77801. assert( isSorter(pC)==0 );
  77802. assert( pC->nullRow==0 );
  77803. assert( pC->uc.pCursor!=0 );
  77804. pCrsr = pC->uc.pCursor;
  77805. /* The OP_RowData opcodes always follow OP_NotExists or
  77806. ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
  77807. ** that might invalidate the cursor.
  77808. ** If this where not the case, on of the following assert()s
  77809. ** would fail. Should this ever change (because of changes in the code
  77810. ** generator) then the fix would be to insert a call to
  77811. ** sqlite3VdbeCursorMoveto().
  77812. */
  77813. assert( pC->deferredMoveto==0 );
  77814. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  77815. #if 0 /* Not required due to the previous to assert() statements */
  77816. rc = sqlite3VdbeCursorMoveto(pC);
  77817. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  77818. #endif
  77819. n = sqlite3BtreePayloadSize(pCrsr);
  77820. if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  77821. goto too_big;
  77822. }
  77823. testcase( n==0 );
  77824. rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
  77825. if( rc ) goto abort_due_to_error;
  77826. if( !pOp->p3 ) Deephemeralize(pOut);
  77827. UPDATE_MAX_BLOBSIZE(pOut);
  77828. REGISTER_TRACE(pOp->p2, pOut);
  77829. break;
  77830. }
  77831. /* Opcode: Rowid P1 P2 * * *
  77832. ** Synopsis: r[P2]=rowid
  77833. **
  77834. ** Store in register P2 an integer which is the key of the table entry that
  77835. ** P1 is currently point to.
  77836. **
  77837. ** P1 can be either an ordinary table or a virtual table. There used to
  77838. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  77839. ** one opcode now works for both table types.
  77840. */
  77841. case OP_Rowid: { /* out2 */
  77842. VdbeCursor *pC;
  77843. i64 v;
  77844. sqlite3_vtab *pVtab;
  77845. const sqlite3_module *pModule;
  77846. pOut = out2Prerelease(p, pOp);
  77847. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77848. pC = p->apCsr[pOp->p1];
  77849. assert( pC!=0 );
  77850. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  77851. if( pC->nullRow ){
  77852. pOut->flags = MEM_Null;
  77853. break;
  77854. }else if( pC->deferredMoveto ){
  77855. v = pC->movetoTarget;
  77856. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77857. }else if( pC->eCurType==CURTYPE_VTAB ){
  77858. assert( pC->uc.pVCur!=0 );
  77859. pVtab = pC->uc.pVCur->pVtab;
  77860. pModule = pVtab->pModule;
  77861. assert( pModule->xRowid );
  77862. rc = pModule->xRowid(pC->uc.pVCur, &v);
  77863. sqlite3VtabImportErrmsg(p, pVtab);
  77864. if( rc ) goto abort_due_to_error;
  77865. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  77866. }else{
  77867. assert( pC->eCurType==CURTYPE_BTREE );
  77868. assert( pC->uc.pCursor!=0 );
  77869. rc = sqlite3VdbeCursorRestore(pC);
  77870. if( rc ) goto abort_due_to_error;
  77871. if( pC->nullRow ){
  77872. pOut->flags = MEM_Null;
  77873. break;
  77874. }
  77875. v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  77876. }
  77877. pOut->u.i = v;
  77878. break;
  77879. }
  77880. /* Opcode: NullRow P1 * * * *
  77881. **
  77882. ** Move the cursor P1 to a null row. Any OP_Column operations
  77883. ** that occur while the cursor is on the null row will always
  77884. ** write a NULL.
  77885. */
  77886. case OP_NullRow: {
  77887. VdbeCursor *pC;
  77888. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77889. pC = p->apCsr[pOp->p1];
  77890. assert( pC!=0 );
  77891. pC->nullRow = 1;
  77892. pC->cacheStatus = CACHE_STALE;
  77893. if( pC->eCurType==CURTYPE_BTREE ){
  77894. assert( pC->uc.pCursor!=0 );
  77895. sqlite3BtreeClearCursor(pC->uc.pCursor);
  77896. }
  77897. break;
  77898. }
  77899. /* Opcode: Last P1 P2 P3 * *
  77900. **
  77901. ** The next use of the Rowid or Column or Prev instruction for P1
  77902. ** will refer to the last entry in the database table or index.
  77903. ** If the table or index is empty and P2>0, then jump immediately to P2.
  77904. ** If P2 is 0 or if the table or index is not empty, fall through
  77905. ** to the following instruction.
  77906. **
  77907. ** This opcode leaves the cursor configured to move in reverse order,
  77908. ** from the end toward the beginning. In other words, the cursor is
  77909. ** configured to use Prev, not Next.
  77910. **
  77911. ** If P3 is -1, then the cursor is positioned at the end of the btree
  77912. ** for the purpose of appending a new entry onto the btree. In that
  77913. ** case P2 must be 0. It is assumed that the cursor is used only for
  77914. ** appending and so if the cursor is valid, then the cursor must already
  77915. ** be pointing at the end of the btree and so no changes are made to
  77916. ** the cursor.
  77917. */
  77918. case OP_Last: { /* jump */
  77919. VdbeCursor *pC;
  77920. BtCursor *pCrsr;
  77921. int res;
  77922. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77923. pC = p->apCsr[pOp->p1];
  77924. assert( pC!=0 );
  77925. assert( pC->eCurType==CURTYPE_BTREE );
  77926. pCrsr = pC->uc.pCursor;
  77927. res = 0;
  77928. assert( pCrsr!=0 );
  77929. pC->seekResult = pOp->p3;
  77930. #ifdef SQLITE_DEBUG
  77931. pC->seekOp = OP_Last;
  77932. #endif
  77933. if( pOp->p3==0 || !sqlite3BtreeCursorIsValidNN(pCrsr) ){
  77934. rc = sqlite3BtreeLast(pCrsr, &res);
  77935. pC->nullRow = (u8)res;
  77936. pC->deferredMoveto = 0;
  77937. pC->cacheStatus = CACHE_STALE;
  77938. if( rc ) goto abort_due_to_error;
  77939. if( pOp->p2>0 ){
  77940. VdbeBranchTaken(res!=0,2);
  77941. if( res ) goto jump_to_p2;
  77942. }
  77943. }else{
  77944. assert( pOp->p2==0 );
  77945. }
  77946. break;
  77947. }
  77948. /* Opcode: IfSmaller P1 P2 P3 * *
  77949. **
  77950. ** Estimate the number of rows in the table P1. Jump to P2 if that
  77951. ** estimate is less than approximately 2**(0.1*P3).
  77952. */
  77953. case OP_IfSmaller: { /* jump */
  77954. VdbeCursor *pC;
  77955. BtCursor *pCrsr;
  77956. int res;
  77957. i64 sz;
  77958. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  77959. pC = p->apCsr[pOp->p1];
  77960. assert( pC!=0 );
  77961. pCrsr = pC->uc.pCursor;
  77962. assert( pCrsr );
  77963. rc = sqlite3BtreeFirst(pCrsr, &res);
  77964. if( rc ) goto abort_due_to_error;
  77965. if( res==0 ){
  77966. sz = sqlite3BtreeRowCountEst(pCrsr);
  77967. if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
  77968. }
  77969. VdbeBranchTaken(res!=0,2);
  77970. if( res ) goto jump_to_p2;
  77971. break;
  77972. }
  77973. /* Opcode: SorterSort P1 P2 * * *
  77974. **
  77975. ** After all records have been inserted into the Sorter object
  77976. ** identified by P1, invoke this opcode to actually do the sorting.
  77977. ** Jump to P2 if there are no records to be sorted.
  77978. **
  77979. ** This opcode is an alias for OP_Sort and OP_Rewind that is used
  77980. ** for Sorter objects.
  77981. */
  77982. /* Opcode: Sort P1 P2 * * *
  77983. **
  77984. ** This opcode does exactly the same thing as OP_Rewind except that
  77985. ** it increments an undocumented global variable used for testing.
  77986. **
  77987. ** Sorting is accomplished by writing records into a sorting index,
  77988. ** then rewinding that index and playing it back from beginning to
  77989. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  77990. ** rewinding so that the global variable will be incremented and
  77991. ** regression tests can determine whether or not the optimizer is
  77992. ** correctly optimizing out sorts.
  77993. */
  77994. case OP_SorterSort: /* jump */
  77995. case OP_Sort: { /* jump */
  77996. #ifdef SQLITE_TEST
  77997. sqlite3_sort_count++;
  77998. sqlite3_search_count--;
  77999. #endif
  78000. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  78001. /* Fall through into OP_Rewind */
  78002. }
  78003. /* Opcode: Rewind P1 P2 * * *
  78004. **
  78005. ** The next use of the Rowid or Column or Next instruction for P1
  78006. ** will refer to the first entry in the database table or index.
  78007. ** If the table or index is empty, jump immediately to P2.
  78008. ** If the table or index is not empty, fall through to the following
  78009. ** instruction.
  78010. **
  78011. ** This opcode leaves the cursor configured to move in forward order,
  78012. ** from the beginning toward the end. In other words, the cursor is
  78013. ** configured to use Next, not Prev.
  78014. */
  78015. case OP_Rewind: { /* jump */
  78016. VdbeCursor *pC;
  78017. BtCursor *pCrsr;
  78018. int res;
  78019. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78020. pC = p->apCsr[pOp->p1];
  78021. assert( pC!=0 );
  78022. assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
  78023. res = 1;
  78024. #ifdef SQLITE_DEBUG
  78025. pC->seekOp = OP_Rewind;
  78026. #endif
  78027. if( isSorter(pC) ){
  78028. rc = sqlite3VdbeSorterRewind(pC, &res);
  78029. }else{
  78030. assert( pC->eCurType==CURTYPE_BTREE );
  78031. pCrsr = pC->uc.pCursor;
  78032. assert( pCrsr );
  78033. rc = sqlite3BtreeFirst(pCrsr, &res);
  78034. pC->deferredMoveto = 0;
  78035. pC->cacheStatus = CACHE_STALE;
  78036. }
  78037. if( rc ) goto abort_due_to_error;
  78038. pC->nullRow = (u8)res;
  78039. assert( pOp->p2>0 && pOp->p2<p->nOp );
  78040. VdbeBranchTaken(res!=0,2);
  78041. if( res ) goto jump_to_p2;
  78042. break;
  78043. }
  78044. /* Opcode: Next P1 P2 P3 P4 P5
  78045. **
  78046. ** Advance cursor P1 so that it points to the next key/data pair in its
  78047. ** table or index. If there are no more key/value pairs then fall through
  78048. ** to the following instruction. But if the cursor advance was successful,
  78049. ** jump immediately to P2.
  78050. **
  78051. ** The Next opcode is only valid following an SeekGT, SeekGE, or
  78052. ** OP_Rewind opcode used to position the cursor. Next is not allowed
  78053. ** to follow SeekLT, SeekLE, or OP_Last.
  78054. **
  78055. ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
  78056. ** been opened prior to this opcode or the program will segfault.
  78057. **
  78058. ** The P3 value is a hint to the btree implementation. If P3==1, that
  78059. ** means P1 is an SQL index and that this instruction could have been
  78060. ** omitted if that index had been unique. P3 is usually 0. P3 is
  78061. ** always either 0 or 1.
  78062. **
  78063. ** P4 is always of type P4_ADVANCE. The function pointer points to
  78064. ** sqlite3BtreeNext().
  78065. **
  78066. ** If P5 is positive and the jump is taken, then event counter
  78067. ** number P5-1 in the prepared statement is incremented.
  78068. **
  78069. ** See also: Prev, NextIfOpen
  78070. */
  78071. /* Opcode: NextIfOpen P1 P2 P3 P4 P5
  78072. **
  78073. ** This opcode works just like Next except that if cursor P1 is not
  78074. ** open it behaves a no-op.
  78075. */
  78076. /* Opcode: Prev P1 P2 P3 P4 P5
  78077. **
  78078. ** Back up cursor P1 so that it points to the previous key/data pair in its
  78079. ** table or index. If there is no previous key/value pairs then fall through
  78080. ** to the following instruction. But if the cursor backup was successful,
  78081. ** jump immediately to P2.
  78082. **
  78083. **
  78084. ** The Prev opcode is only valid following an SeekLT, SeekLE, or
  78085. ** OP_Last opcode used to position the cursor. Prev is not allowed
  78086. ** to follow SeekGT, SeekGE, or OP_Rewind.
  78087. **
  78088. ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
  78089. ** not open then the behavior is undefined.
  78090. **
  78091. ** The P3 value is a hint to the btree implementation. If P3==1, that
  78092. ** means P1 is an SQL index and that this instruction could have been
  78093. ** omitted if that index had been unique. P3 is usually 0. P3 is
  78094. ** always either 0 or 1.
  78095. **
  78096. ** P4 is always of type P4_ADVANCE. The function pointer points to
  78097. ** sqlite3BtreePrevious().
  78098. **
  78099. ** If P5 is positive and the jump is taken, then event counter
  78100. ** number P5-1 in the prepared statement is incremented.
  78101. */
  78102. /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
  78103. **
  78104. ** This opcode works just like Prev except that if cursor P1 is not
  78105. ** open it behaves a no-op.
  78106. */
  78107. /* Opcode: SorterNext P1 P2 * * P5
  78108. **
  78109. ** This opcode works just like OP_Next except that P1 must be a
  78110. ** sorter object for which the OP_SorterSort opcode has been
  78111. ** invoked. This opcode advances the cursor to the next sorted
  78112. ** record, or jumps to P2 if there are no more sorted records.
  78113. */
  78114. case OP_SorterNext: { /* jump */
  78115. VdbeCursor *pC;
  78116. int res;
  78117. pC = p->apCsr[pOp->p1];
  78118. assert( isSorter(pC) );
  78119. res = 0;
  78120. rc = sqlite3VdbeSorterNext(db, pC, &res);
  78121. goto next_tail;
  78122. case OP_PrevIfOpen: /* jump */
  78123. case OP_NextIfOpen: /* jump */
  78124. if( p->apCsr[pOp->p1]==0 ) break;
  78125. /* Fall through */
  78126. case OP_Prev: /* jump */
  78127. case OP_Next: /* jump */
  78128. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78129. assert( pOp->p5<ArraySize(p->aCounter) );
  78130. pC = p->apCsr[pOp->p1];
  78131. res = pOp->p3;
  78132. assert( pC!=0 );
  78133. assert( pC->deferredMoveto==0 );
  78134. assert( pC->eCurType==CURTYPE_BTREE );
  78135. assert( res==0 || (res==1 && pC->isTable==0) );
  78136. testcase( res==1 );
  78137. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  78138. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  78139. assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
  78140. assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
  78141. /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
  78142. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
  78143. assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
  78144. || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
  78145. || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
  78146. assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
  78147. || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
  78148. || pC->seekOp==OP_Last );
  78149. rc = pOp->p4.xAdvance(pC->uc.pCursor, &res);
  78150. next_tail:
  78151. pC->cacheStatus = CACHE_STALE;
  78152. VdbeBranchTaken(res==0,2);
  78153. if( rc ) goto abort_due_to_error;
  78154. if( res==0 ){
  78155. pC->nullRow = 0;
  78156. p->aCounter[pOp->p5]++;
  78157. #ifdef SQLITE_TEST
  78158. sqlite3_search_count++;
  78159. #endif
  78160. goto jump_to_p2_and_check_for_interrupt;
  78161. }else{
  78162. pC->nullRow = 1;
  78163. }
  78164. goto check_for_interrupt;
  78165. }
  78166. /* Opcode: IdxInsert P1 P2 P3 P4 P5
  78167. ** Synopsis: key=r[P2]
  78168. **
  78169. ** Register P2 holds an SQL index key made using the
  78170. ** MakeRecord instructions. This opcode writes that key
  78171. ** into the index P1. Data for the entry is nil.
  78172. **
  78173. ** If P4 is not zero, then it is the number of values in the unpacked
  78174. ** key of reg(P2). In that case, P3 is the index of the first register
  78175. ** for the unpacked key. The availability of the unpacked key can sometimes
  78176. ** be an optimization.
  78177. **
  78178. ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
  78179. ** that this insert is likely to be an append.
  78180. **
  78181. ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
  78182. ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
  78183. ** then the change counter is unchanged.
  78184. **
  78185. ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
  78186. ** run faster by avoiding an unnecessary seek on cursor P1. However,
  78187. ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
  78188. ** seeks on the cursor or if the most recent seek used a key equivalent
  78189. ** to P2.
  78190. **
  78191. ** This instruction only works for indices. The equivalent instruction
  78192. ** for tables is OP_Insert.
  78193. */
  78194. /* Opcode: SorterInsert P1 P2 * * *
  78195. ** Synopsis: key=r[P2]
  78196. **
  78197. ** Register P2 holds an SQL index key made using the
  78198. ** MakeRecord instructions. This opcode writes that key
  78199. ** into the sorter P1. Data for the entry is nil.
  78200. */
  78201. case OP_SorterInsert: /* in2 */
  78202. case OP_IdxInsert: { /* in2 */
  78203. VdbeCursor *pC;
  78204. BtreePayload x;
  78205. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78206. pC = p->apCsr[pOp->p1];
  78207. assert( pC!=0 );
  78208. assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
  78209. pIn2 = &aMem[pOp->p2];
  78210. assert( pIn2->flags & MEM_Blob );
  78211. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  78212. assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
  78213. assert( pC->isTable==0 );
  78214. rc = ExpandBlob(pIn2);
  78215. if( rc ) goto abort_due_to_error;
  78216. if( pOp->opcode==OP_SorterInsert ){
  78217. rc = sqlite3VdbeSorterWrite(pC, pIn2);
  78218. }else{
  78219. x.nKey = pIn2->n;
  78220. x.pKey = pIn2->z;
  78221. x.aMem = aMem + pOp->p3;
  78222. x.nMem = (u16)pOp->p4.i;
  78223. rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
  78224. (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
  78225. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
  78226. );
  78227. assert( pC->deferredMoveto==0 );
  78228. pC->cacheStatus = CACHE_STALE;
  78229. }
  78230. if( rc) goto abort_due_to_error;
  78231. break;
  78232. }
  78233. /* Opcode: IdxDelete P1 P2 P3 * *
  78234. ** Synopsis: key=r[P2@P3]
  78235. **
  78236. ** The content of P3 registers starting at register P2 form
  78237. ** an unpacked index key. This opcode removes that entry from the
  78238. ** index opened by cursor P1.
  78239. */
  78240. case OP_IdxDelete: {
  78241. VdbeCursor *pC;
  78242. BtCursor *pCrsr;
  78243. int res;
  78244. UnpackedRecord r;
  78245. assert( pOp->p3>0 );
  78246. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
  78247. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78248. pC = p->apCsr[pOp->p1];
  78249. assert( pC!=0 );
  78250. assert( pC->eCurType==CURTYPE_BTREE );
  78251. pCrsr = pC->uc.pCursor;
  78252. assert( pCrsr!=0 );
  78253. assert( pOp->p5==0 );
  78254. r.pKeyInfo = pC->pKeyInfo;
  78255. r.nField = (u16)pOp->p3;
  78256. r.default_rc = 0;
  78257. r.aMem = &aMem[pOp->p2];
  78258. rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  78259. if( rc ) goto abort_due_to_error;
  78260. if( res==0 ){
  78261. rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
  78262. if( rc ) goto abort_due_to_error;
  78263. }
  78264. assert( pC->deferredMoveto==0 );
  78265. pC->cacheStatus = CACHE_STALE;
  78266. pC->seekResult = 0;
  78267. break;
  78268. }
  78269. /* Opcode: Seek P1 * P3 P4 *
  78270. ** Synopsis: Move P3 to P1.rowid
  78271. **
  78272. ** P1 is an open index cursor and P3 is a cursor on the corresponding
  78273. ** table. This opcode does a deferred seek of the P3 table cursor
  78274. ** to the row that corresponds to the current row of P1.
  78275. **
  78276. ** This is a deferred seek. Nothing actually happens until
  78277. ** the cursor is used to read a record. That way, if no reads
  78278. ** occur, no unnecessary I/O happens.
  78279. **
  78280. ** P4 may be an array of integers (type P4_INTARRAY) containing
  78281. ** one entry for each column in the P3 table. If array entry a(i)
  78282. ** is non-zero, then reading column a(i)-1 from cursor P3 is
  78283. ** equivalent to performing the deferred seek and then reading column i
  78284. ** from P1. This information is stored in P3 and used to redirect
  78285. ** reads against P3 over to P1, thus possibly avoiding the need to
  78286. ** seek and read cursor P3.
  78287. */
  78288. /* Opcode: IdxRowid P1 P2 * * *
  78289. ** Synopsis: r[P2]=rowid
  78290. **
  78291. ** Write into register P2 an integer which is the last entry in the record at
  78292. ** the end of the index key pointed to by cursor P1. This integer should be
  78293. ** the rowid of the table entry to which this index entry points.
  78294. **
  78295. ** See also: Rowid, MakeRecord.
  78296. */
  78297. case OP_Seek:
  78298. case OP_IdxRowid: { /* out2 */
  78299. VdbeCursor *pC; /* The P1 index cursor */
  78300. VdbeCursor *pTabCur; /* The P2 table cursor (OP_Seek only) */
  78301. i64 rowid; /* Rowid that P1 current points to */
  78302. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78303. pC = p->apCsr[pOp->p1];
  78304. assert( pC!=0 );
  78305. assert( pC->eCurType==CURTYPE_BTREE );
  78306. assert( pC->uc.pCursor!=0 );
  78307. assert( pC->isTable==0 );
  78308. assert( pC->deferredMoveto==0 );
  78309. assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
  78310. /* The IdxRowid and Seek opcodes are combined because of the commonality
  78311. ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
  78312. rc = sqlite3VdbeCursorRestore(pC);
  78313. /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
  78314. ** out from under the cursor. That will never happens for an IdxRowid
  78315. ** or Seek opcode */
  78316. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  78317. if( !pC->nullRow ){
  78318. rowid = 0; /* Not needed. Only used to silence a warning. */
  78319. rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
  78320. if( rc!=SQLITE_OK ){
  78321. goto abort_due_to_error;
  78322. }
  78323. if( pOp->opcode==OP_Seek ){
  78324. assert( pOp->p3>=0 && pOp->p3<p->nCursor );
  78325. pTabCur = p->apCsr[pOp->p3];
  78326. assert( pTabCur!=0 );
  78327. assert( pTabCur->eCurType==CURTYPE_BTREE );
  78328. assert( pTabCur->uc.pCursor!=0 );
  78329. assert( pTabCur->isTable );
  78330. pTabCur->nullRow = 0;
  78331. pTabCur->movetoTarget = rowid;
  78332. pTabCur->deferredMoveto = 1;
  78333. assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
  78334. pTabCur->aAltMap = pOp->p4.ai;
  78335. pTabCur->pAltCursor = pC;
  78336. }else{
  78337. pOut = out2Prerelease(p, pOp);
  78338. pOut->u.i = rowid;
  78339. }
  78340. }else{
  78341. assert( pOp->opcode==OP_IdxRowid );
  78342. sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
  78343. }
  78344. break;
  78345. }
  78346. /* Opcode: IdxGE P1 P2 P3 P4 P5
  78347. ** Synopsis: key=r[P3@P4]
  78348. **
  78349. ** The P4 register values beginning with P3 form an unpacked index
  78350. ** key that omits the PRIMARY KEY. Compare this key value against the index
  78351. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  78352. ** fields at the end.
  78353. **
  78354. ** If the P1 index entry is greater than or equal to the key value
  78355. ** then jump to P2. Otherwise fall through to the next instruction.
  78356. */
  78357. /* Opcode: IdxGT P1 P2 P3 P4 P5
  78358. ** Synopsis: key=r[P3@P4]
  78359. **
  78360. ** The P4 register values beginning with P3 form an unpacked index
  78361. ** key that omits the PRIMARY KEY. Compare this key value against the index
  78362. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  78363. ** fields at the end.
  78364. **
  78365. ** If the P1 index entry is greater than the key value
  78366. ** then jump to P2. Otherwise fall through to the next instruction.
  78367. */
  78368. /* Opcode: IdxLT P1 P2 P3 P4 P5
  78369. ** Synopsis: key=r[P3@P4]
  78370. **
  78371. ** The P4 register values beginning with P3 form an unpacked index
  78372. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  78373. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  78374. ** ROWID on the P1 index.
  78375. **
  78376. ** If the P1 index entry is less than the key value then jump to P2.
  78377. ** Otherwise fall through to the next instruction.
  78378. */
  78379. /* Opcode: IdxLE P1 P2 P3 P4 P5
  78380. ** Synopsis: key=r[P3@P4]
  78381. **
  78382. ** The P4 register values beginning with P3 form an unpacked index
  78383. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  78384. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  78385. ** ROWID on the P1 index.
  78386. **
  78387. ** If the P1 index entry is less than or equal to the key value then jump
  78388. ** to P2. Otherwise fall through to the next instruction.
  78389. */
  78390. case OP_IdxLE: /* jump */
  78391. case OP_IdxGT: /* jump */
  78392. case OP_IdxLT: /* jump */
  78393. case OP_IdxGE: { /* jump */
  78394. VdbeCursor *pC;
  78395. int res;
  78396. UnpackedRecord r;
  78397. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78398. pC = p->apCsr[pOp->p1];
  78399. assert( pC!=0 );
  78400. assert( pC->isOrdered );
  78401. assert( pC->eCurType==CURTYPE_BTREE );
  78402. assert( pC->uc.pCursor!=0);
  78403. assert( pC->deferredMoveto==0 );
  78404. assert( pOp->p5==0 || pOp->p5==1 );
  78405. assert( pOp->p4type==P4_INT32 );
  78406. r.pKeyInfo = pC->pKeyInfo;
  78407. r.nField = (u16)pOp->p4.i;
  78408. if( pOp->opcode<OP_IdxLT ){
  78409. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
  78410. r.default_rc = -1;
  78411. }else{
  78412. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
  78413. r.default_rc = 0;
  78414. }
  78415. r.aMem = &aMem[pOp->p3];
  78416. #ifdef SQLITE_DEBUG
  78417. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  78418. #endif
  78419. res = 0; /* Not needed. Only used to silence a warning. */
  78420. rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
  78421. assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
  78422. if( (pOp->opcode&1)==(OP_IdxLT&1) ){
  78423. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
  78424. res = -res;
  78425. }else{
  78426. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
  78427. res++;
  78428. }
  78429. VdbeBranchTaken(res>0,2);
  78430. if( rc ) goto abort_due_to_error;
  78431. if( res>0 ) goto jump_to_p2;
  78432. break;
  78433. }
  78434. /* Opcode: Destroy P1 P2 P3 * *
  78435. **
  78436. ** Delete an entire database table or index whose root page in the database
  78437. ** file is given by P1.
  78438. **
  78439. ** The table being destroyed is in the main database file if P3==0. If
  78440. ** P3==1 then the table to be clear is in the auxiliary database file
  78441. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  78442. **
  78443. ** If AUTOVACUUM is enabled then it is possible that another root page
  78444. ** might be moved into the newly deleted root page in order to keep all
  78445. ** root pages contiguous at the beginning of the database. The former
  78446. ** value of the root page that moved - its value before the move occurred -
  78447. ** is stored in register P2. If no page movement was required (because the
  78448. ** table being dropped was already the last one in the database) then a
  78449. ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
  78450. ** is stored in register P2.
  78451. **
  78452. ** This opcode throws an error if there are any active reader VMs when
  78453. ** it is invoked. This is done to avoid the difficulty associated with
  78454. ** updating existing cursors when a root page is moved in an AUTOVACUUM
  78455. ** database. This error is thrown even if the database is not an AUTOVACUUM
  78456. ** db in order to avoid introducing an incompatibility between autovacuum
  78457. ** and non-autovacuum modes.
  78458. **
  78459. ** See also: Clear
  78460. */
  78461. case OP_Destroy: { /* out2 */
  78462. int iMoved;
  78463. int iDb;
  78464. assert( p->readOnly==0 );
  78465. assert( pOp->p1>1 );
  78466. pOut = out2Prerelease(p, pOp);
  78467. pOut->flags = MEM_Null;
  78468. if( db->nVdbeRead > db->nVDestroy+1 ){
  78469. rc = SQLITE_LOCKED;
  78470. p->errorAction = OE_Abort;
  78471. goto abort_due_to_error;
  78472. }else{
  78473. iDb = pOp->p3;
  78474. assert( DbMaskTest(p->btreeMask, iDb) );
  78475. iMoved = 0; /* Not needed. Only to silence a warning. */
  78476. rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
  78477. pOut->flags = MEM_Int;
  78478. pOut->u.i = iMoved;
  78479. if( rc ) goto abort_due_to_error;
  78480. #ifndef SQLITE_OMIT_AUTOVACUUM
  78481. if( iMoved!=0 ){
  78482. sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
  78483. /* All OP_Destroy operations occur on the same btree */
  78484. assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
  78485. resetSchemaOnFault = iDb+1;
  78486. }
  78487. #endif
  78488. }
  78489. break;
  78490. }
  78491. /* Opcode: Clear P1 P2 P3
  78492. **
  78493. ** Delete all contents of the database table or index whose root page
  78494. ** in the database file is given by P1. But, unlike Destroy, do not
  78495. ** remove the table or index from the database file.
  78496. **
  78497. ** The table being clear is in the main database file if P2==0. If
  78498. ** P2==1 then the table to be clear is in the auxiliary database file
  78499. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  78500. **
  78501. ** If the P3 value is non-zero, then the table referred to must be an
  78502. ** intkey table (an SQL table, not an index). In this case the row change
  78503. ** count is incremented by the number of rows in the table being cleared.
  78504. ** If P3 is greater than zero, then the value stored in register P3 is
  78505. ** also incremented by the number of rows in the table being cleared.
  78506. **
  78507. ** See also: Destroy
  78508. */
  78509. case OP_Clear: {
  78510. int nChange;
  78511. nChange = 0;
  78512. assert( p->readOnly==0 );
  78513. assert( DbMaskTest(p->btreeMask, pOp->p2) );
  78514. rc = sqlite3BtreeClearTable(
  78515. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  78516. );
  78517. if( pOp->p3 ){
  78518. p->nChange += nChange;
  78519. if( pOp->p3>0 ){
  78520. assert( memIsValid(&aMem[pOp->p3]) );
  78521. memAboutToChange(p, &aMem[pOp->p3]);
  78522. aMem[pOp->p3].u.i += nChange;
  78523. }
  78524. }
  78525. if( rc ) goto abort_due_to_error;
  78526. break;
  78527. }
  78528. /* Opcode: ResetSorter P1 * * * *
  78529. **
  78530. ** Delete all contents from the ephemeral table or sorter
  78531. ** that is open on cursor P1.
  78532. **
  78533. ** This opcode only works for cursors used for sorting and
  78534. ** opened with OP_OpenEphemeral or OP_SorterOpen.
  78535. */
  78536. case OP_ResetSorter: {
  78537. VdbeCursor *pC;
  78538. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78539. pC = p->apCsr[pOp->p1];
  78540. assert( pC!=0 );
  78541. if( isSorter(pC) ){
  78542. sqlite3VdbeSorterReset(db, pC->uc.pSorter);
  78543. }else{
  78544. assert( pC->eCurType==CURTYPE_BTREE );
  78545. assert( pC->isEphemeral );
  78546. rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
  78547. if( rc ) goto abort_due_to_error;
  78548. }
  78549. break;
  78550. }
  78551. /* Opcode: CreateTable P1 P2 * * *
  78552. ** Synopsis: r[P2]=root iDb=P1
  78553. **
  78554. ** Allocate a new table in the main database file if P1==0 or in the
  78555. ** auxiliary database file if P1==1 or in an attached database if
  78556. ** P1>1. Write the root page number of the new table into
  78557. ** register P2
  78558. **
  78559. ** The difference between a table and an index is this: A table must
  78560. ** have a 4-byte integer key and can have arbitrary data. An index
  78561. ** has an arbitrary key but no data.
  78562. **
  78563. ** See also: CreateIndex
  78564. */
  78565. /* Opcode: CreateIndex P1 P2 * * *
  78566. ** Synopsis: r[P2]=root iDb=P1
  78567. **
  78568. ** Allocate a new index in the main database file if P1==0 or in the
  78569. ** auxiliary database file if P1==1 or in an attached database if
  78570. ** P1>1. Write the root page number of the new table into
  78571. ** register P2.
  78572. **
  78573. ** See documentation on OP_CreateTable for additional information.
  78574. */
  78575. case OP_CreateIndex: /* out2 */
  78576. case OP_CreateTable: { /* out2 */
  78577. int pgno;
  78578. int flags;
  78579. Db *pDb;
  78580. pOut = out2Prerelease(p, pOp);
  78581. pgno = 0;
  78582. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  78583. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  78584. assert( p->readOnly==0 );
  78585. pDb = &db->aDb[pOp->p1];
  78586. assert( pDb->pBt!=0 );
  78587. if( pOp->opcode==OP_CreateTable ){
  78588. /* flags = BTREE_INTKEY; */
  78589. flags = BTREE_INTKEY;
  78590. }else{
  78591. flags = BTREE_BLOBKEY;
  78592. }
  78593. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
  78594. if( rc ) goto abort_due_to_error;
  78595. pOut->u.i = pgno;
  78596. break;
  78597. }
  78598. /* Opcode: SqlExec * * * P4 *
  78599. **
  78600. ** Run the SQL statement or statements specified in the P4 string.
  78601. */
  78602. case OP_SqlExec: {
  78603. db->nSqlExec++;
  78604. rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
  78605. db->nSqlExec--;
  78606. if( rc ) goto abort_due_to_error;
  78607. break;
  78608. }
  78609. /* Opcode: ParseSchema P1 * * P4 *
  78610. **
  78611. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  78612. ** that match the WHERE clause P4.
  78613. **
  78614. ** This opcode invokes the parser to create a new virtual machine,
  78615. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  78616. */
  78617. case OP_ParseSchema: {
  78618. int iDb;
  78619. const char *zMaster;
  78620. char *zSql;
  78621. InitData initData;
  78622. /* Any prepared statement that invokes this opcode will hold mutexes
  78623. ** on every btree. This is a prerequisite for invoking
  78624. ** sqlite3InitCallback().
  78625. */
  78626. #ifdef SQLITE_DEBUG
  78627. for(iDb=0; iDb<db->nDb; iDb++){
  78628. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  78629. }
  78630. #endif
  78631. iDb = pOp->p1;
  78632. assert( iDb>=0 && iDb<db->nDb );
  78633. assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
  78634. /* Used to be a conditional */ {
  78635. zMaster = MASTER_NAME;
  78636. initData.db = db;
  78637. initData.iDb = pOp->p1;
  78638. initData.pzErrMsg = &p->zErrMsg;
  78639. zSql = sqlite3MPrintf(db,
  78640. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  78641. db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
  78642. if( zSql==0 ){
  78643. rc = SQLITE_NOMEM_BKPT;
  78644. }else{
  78645. assert( db->init.busy==0 );
  78646. db->init.busy = 1;
  78647. initData.rc = SQLITE_OK;
  78648. assert( !db->mallocFailed );
  78649. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  78650. if( rc==SQLITE_OK ) rc = initData.rc;
  78651. sqlite3DbFreeNN(db, zSql);
  78652. db->init.busy = 0;
  78653. }
  78654. }
  78655. if( rc ){
  78656. sqlite3ResetAllSchemasOfConnection(db);
  78657. if( rc==SQLITE_NOMEM ){
  78658. goto no_mem;
  78659. }
  78660. goto abort_due_to_error;
  78661. }
  78662. break;
  78663. }
  78664. #if !defined(SQLITE_OMIT_ANALYZE)
  78665. /* Opcode: LoadAnalysis P1 * * * *
  78666. **
  78667. ** Read the sqlite_stat1 table for database P1 and load the content
  78668. ** of that table into the internal index hash table. This will cause
  78669. ** the analysis to be used when preparing all subsequent queries.
  78670. */
  78671. case OP_LoadAnalysis: {
  78672. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  78673. rc = sqlite3AnalysisLoad(db, pOp->p1);
  78674. if( rc ) goto abort_due_to_error;
  78675. break;
  78676. }
  78677. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  78678. /* Opcode: DropTable P1 * * P4 *
  78679. **
  78680. ** Remove the internal (in-memory) data structures that describe
  78681. ** the table named P4 in database P1. This is called after a table
  78682. ** is dropped from disk (using the Destroy opcode) in order to keep
  78683. ** the internal representation of the
  78684. ** schema consistent with what is on disk.
  78685. */
  78686. case OP_DropTable: {
  78687. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  78688. break;
  78689. }
  78690. /* Opcode: DropIndex P1 * * P4 *
  78691. **
  78692. ** Remove the internal (in-memory) data structures that describe
  78693. ** the index named P4 in database P1. This is called after an index
  78694. ** is dropped from disk (using the Destroy opcode)
  78695. ** in order to keep the internal representation of the
  78696. ** schema consistent with what is on disk.
  78697. */
  78698. case OP_DropIndex: {
  78699. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  78700. break;
  78701. }
  78702. /* Opcode: DropTrigger P1 * * P4 *
  78703. **
  78704. ** Remove the internal (in-memory) data structures that describe
  78705. ** the trigger named P4 in database P1. This is called after a trigger
  78706. ** is dropped from disk (using the Destroy opcode) in order to keep
  78707. ** the internal representation of the
  78708. ** schema consistent with what is on disk.
  78709. */
  78710. case OP_DropTrigger: {
  78711. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  78712. break;
  78713. }
  78714. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  78715. /* Opcode: IntegrityCk P1 P2 P3 P4 P5
  78716. **
  78717. ** Do an analysis of the currently open database. Store in
  78718. ** register P1 the text of an error message describing any problems.
  78719. ** If no problems are found, store a NULL in register P1.
  78720. **
  78721. ** The register P3 contains one less than the maximum number of allowed errors.
  78722. ** At most reg(P3) errors will be reported.
  78723. ** In other words, the analysis stops as soon as reg(P1) errors are
  78724. ** seen. Reg(P1) is updated with the number of errors remaining.
  78725. **
  78726. ** The root page numbers of all tables in the database are integers
  78727. ** stored in P4_INTARRAY argument.
  78728. **
  78729. ** If P5 is not zero, the check is done on the auxiliary database
  78730. ** file, not the main database file.
  78731. **
  78732. ** This opcode is used to implement the integrity_check pragma.
  78733. */
  78734. case OP_IntegrityCk: {
  78735. int nRoot; /* Number of tables to check. (Number of root pages.) */
  78736. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  78737. int nErr; /* Number of errors reported */
  78738. char *z; /* Text of the error report */
  78739. Mem *pnErr; /* Register keeping track of errors remaining */
  78740. assert( p->bIsReader );
  78741. nRoot = pOp->p2;
  78742. aRoot = pOp->p4.ai;
  78743. assert( nRoot>0 );
  78744. assert( aRoot[nRoot]==0 );
  78745. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  78746. pnErr = &aMem[pOp->p3];
  78747. assert( (pnErr->flags & MEM_Int)!=0 );
  78748. assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  78749. pIn1 = &aMem[pOp->p1];
  78750. assert( pOp->p5<db->nDb );
  78751. assert( DbMaskTest(p->btreeMask, pOp->p5) );
  78752. z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
  78753. (int)pnErr->u.i+1, &nErr);
  78754. sqlite3VdbeMemSetNull(pIn1);
  78755. if( nErr==0 ){
  78756. assert( z==0 );
  78757. }else if( z==0 ){
  78758. goto no_mem;
  78759. }else{
  78760. pnErr->u.i -= nErr-1;
  78761. sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  78762. }
  78763. UPDATE_MAX_BLOBSIZE(pIn1);
  78764. sqlite3VdbeChangeEncoding(pIn1, encoding);
  78765. break;
  78766. }
  78767. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  78768. /* Opcode: RowSetAdd P1 P2 * * *
  78769. ** Synopsis: rowset(P1)=r[P2]
  78770. **
  78771. ** Insert the integer value held by register P2 into a RowSet object
  78772. ** held in register P1.
  78773. **
  78774. ** An assertion fails if P2 is not an integer.
  78775. */
  78776. case OP_RowSetAdd: { /* in1, in2 */
  78777. pIn1 = &aMem[pOp->p1];
  78778. pIn2 = &aMem[pOp->p2];
  78779. assert( (pIn2->flags & MEM_Int)!=0 );
  78780. if( (pIn1->flags & MEM_RowSet)==0 ){
  78781. sqlite3VdbeMemSetRowSet(pIn1);
  78782. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  78783. }
  78784. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  78785. break;
  78786. }
  78787. /* Opcode: RowSetRead P1 P2 P3 * *
  78788. ** Synopsis: r[P3]=rowset(P1)
  78789. **
  78790. ** Extract the smallest value from the RowSet object in P1
  78791. ** and put that value into register P3.
  78792. ** Or, if RowSet object P1 is initially empty, leave P3
  78793. ** unchanged and jump to instruction P2.
  78794. */
  78795. case OP_RowSetRead: { /* jump, in1, out3 */
  78796. i64 val;
  78797. pIn1 = &aMem[pOp->p1];
  78798. if( (pIn1->flags & MEM_RowSet)==0
  78799. || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
  78800. ){
  78801. /* The boolean index is empty */
  78802. sqlite3VdbeMemSetNull(pIn1);
  78803. VdbeBranchTaken(1,2);
  78804. goto jump_to_p2_and_check_for_interrupt;
  78805. }else{
  78806. /* A value was pulled from the index */
  78807. VdbeBranchTaken(0,2);
  78808. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
  78809. }
  78810. goto check_for_interrupt;
  78811. }
  78812. /* Opcode: RowSetTest P1 P2 P3 P4
  78813. ** Synopsis: if r[P3] in rowset(P1) goto P2
  78814. **
  78815. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  78816. ** contains a RowSet object and that RowSet object contains
  78817. ** the value held in P3, jump to register P2. Otherwise, insert the
  78818. ** integer in P3 into the RowSet and continue on to the
  78819. ** next opcode.
  78820. **
  78821. ** The RowSet object is optimized for the case where sets of integers
  78822. ** are inserted in distinct phases, which each set contains no duplicates.
  78823. ** Each set is identified by a unique P4 value. The first set
  78824. ** must have P4==0, the final set must have P4==-1, and for all other sets
  78825. ** must have P4>0.
  78826. **
  78827. ** This allows optimizations: (a) when P4==0 there is no need to test
  78828. ** the RowSet object for P3, as it is guaranteed not to contain it,
  78829. ** (b) when P4==-1 there is no need to insert the value, as it will
  78830. ** never be tested for, and (c) when a value that is part of set X is
  78831. ** inserted, there is no need to search to see if the same value was
  78832. ** previously inserted as part of set X (only if it was previously
  78833. ** inserted as part of some other set).
  78834. */
  78835. case OP_RowSetTest: { /* jump, in1, in3 */
  78836. int iSet;
  78837. int exists;
  78838. pIn1 = &aMem[pOp->p1];
  78839. pIn3 = &aMem[pOp->p3];
  78840. iSet = pOp->p4.i;
  78841. assert( pIn3->flags&MEM_Int );
  78842. /* If there is anything other than a rowset object in memory cell P1,
  78843. ** delete it now and initialize P1 with an empty rowset
  78844. */
  78845. if( (pIn1->flags & MEM_RowSet)==0 ){
  78846. sqlite3VdbeMemSetRowSet(pIn1);
  78847. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  78848. }
  78849. assert( pOp->p4type==P4_INT32 );
  78850. assert( iSet==-1 || iSet>=0 );
  78851. if( iSet ){
  78852. exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
  78853. VdbeBranchTaken(exists!=0,2);
  78854. if( exists ) goto jump_to_p2;
  78855. }
  78856. if( iSet>=0 ){
  78857. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  78858. }
  78859. break;
  78860. }
  78861. #ifndef SQLITE_OMIT_TRIGGER
  78862. /* Opcode: Program P1 P2 P3 P4 P5
  78863. **
  78864. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  78865. **
  78866. ** P1 contains the address of the memory cell that contains the first memory
  78867. ** cell in an array of values used as arguments to the sub-program. P2
  78868. ** contains the address to jump to if the sub-program throws an IGNORE
  78869. ** exception using the RAISE() function. Register P3 contains the address
  78870. ** of a memory cell in this (the parent) VM that is used to allocate the
  78871. ** memory required by the sub-vdbe at runtime.
  78872. **
  78873. ** P4 is a pointer to the VM containing the trigger program.
  78874. **
  78875. ** If P5 is non-zero, then recursive program invocation is enabled.
  78876. */
  78877. case OP_Program: { /* jump */
  78878. int nMem; /* Number of memory registers for sub-program */
  78879. int nByte; /* Bytes of runtime space required for sub-program */
  78880. Mem *pRt; /* Register to allocate runtime space */
  78881. Mem *pMem; /* Used to iterate through memory cells */
  78882. Mem *pEnd; /* Last memory cell in new array */
  78883. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  78884. SubProgram *pProgram; /* Sub-program to execute */
  78885. void *t; /* Token identifying trigger */
  78886. pProgram = pOp->p4.pProgram;
  78887. pRt = &aMem[pOp->p3];
  78888. assert( pProgram->nOp>0 );
  78889. /* If the p5 flag is clear, then recursive invocation of triggers is
  78890. ** disabled for backwards compatibility (p5 is set if this sub-program
  78891. ** is really a trigger, not a foreign key action, and the flag set
  78892. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  78893. **
  78894. ** It is recursive invocation of triggers, at the SQL level, that is
  78895. ** disabled. In some cases a single trigger may generate more than one
  78896. ** SubProgram (if the trigger may be executed with more than one different
  78897. ** ON CONFLICT algorithm). SubProgram structures associated with a
  78898. ** single trigger all have the same value for the SubProgram.token
  78899. ** variable. */
  78900. if( pOp->p5 ){
  78901. t = pProgram->token;
  78902. for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
  78903. if( pFrame ) break;
  78904. }
  78905. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  78906. rc = SQLITE_ERROR;
  78907. sqlite3VdbeError(p, "too many levels of trigger recursion");
  78908. goto abort_due_to_error;
  78909. }
  78910. /* Register pRt is used to store the memory required to save the state
  78911. ** of the current program, and the memory required at runtime to execute
  78912. ** the trigger program. If this trigger has been fired before, then pRt
  78913. ** is already allocated. Otherwise, it must be initialized. */
  78914. if( (pRt->flags&MEM_Frame)==0 ){
  78915. /* SubProgram.nMem is set to the number of memory cells used by the
  78916. ** program stored in SubProgram.aOp. As well as these, one memory
  78917. ** cell is required for each cursor used by the program. Set local
  78918. ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
  78919. */
  78920. nMem = pProgram->nMem + pProgram->nCsr;
  78921. assert( nMem>0 );
  78922. if( pProgram->nCsr==0 ) nMem++;
  78923. nByte = ROUND8(sizeof(VdbeFrame))
  78924. + nMem * sizeof(Mem)
  78925. + pProgram->nCsr * sizeof(VdbeCursor*)
  78926. + (pProgram->nOp + 7)/8;
  78927. pFrame = sqlite3DbMallocZero(db, nByte);
  78928. if( !pFrame ){
  78929. goto no_mem;
  78930. }
  78931. sqlite3VdbeMemRelease(pRt);
  78932. pRt->flags = MEM_Frame;
  78933. pRt->u.pFrame = pFrame;
  78934. pFrame->v = p;
  78935. pFrame->nChildMem = nMem;
  78936. pFrame->nChildCsr = pProgram->nCsr;
  78937. pFrame->pc = (int)(pOp - aOp);
  78938. pFrame->aMem = p->aMem;
  78939. pFrame->nMem = p->nMem;
  78940. pFrame->apCsr = p->apCsr;
  78941. pFrame->nCursor = p->nCursor;
  78942. pFrame->aOp = p->aOp;
  78943. pFrame->nOp = p->nOp;
  78944. pFrame->token = pProgram->token;
  78945. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  78946. pFrame->anExec = p->anExec;
  78947. #endif
  78948. pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
  78949. for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
  78950. pMem->flags = MEM_Undefined;
  78951. pMem->db = db;
  78952. }
  78953. }else{
  78954. pFrame = pRt->u.pFrame;
  78955. assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
  78956. || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
  78957. assert( pProgram->nCsr==pFrame->nChildCsr );
  78958. assert( (int)(pOp - aOp)==pFrame->pc );
  78959. }
  78960. p->nFrame++;
  78961. pFrame->pParent = p->pFrame;
  78962. pFrame->lastRowid = db->lastRowid;
  78963. pFrame->nChange = p->nChange;
  78964. pFrame->nDbChange = p->db->nChange;
  78965. assert( pFrame->pAuxData==0 );
  78966. pFrame->pAuxData = p->pAuxData;
  78967. p->pAuxData = 0;
  78968. p->nChange = 0;
  78969. p->pFrame = pFrame;
  78970. p->aMem = aMem = VdbeFrameMem(pFrame);
  78971. p->nMem = pFrame->nChildMem;
  78972. p->nCursor = (u16)pFrame->nChildCsr;
  78973. p->apCsr = (VdbeCursor **)&aMem[p->nMem];
  78974. pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
  78975. memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
  78976. p->aOp = aOp = pProgram->aOp;
  78977. p->nOp = pProgram->nOp;
  78978. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  78979. p->anExec = 0;
  78980. #endif
  78981. pOp = &aOp[-1];
  78982. break;
  78983. }
  78984. /* Opcode: Param P1 P2 * * *
  78985. **
  78986. ** This opcode is only ever present in sub-programs called via the
  78987. ** OP_Program instruction. Copy a value currently stored in a memory
  78988. ** cell of the calling (parent) frame to cell P2 in the current frames
  78989. ** address space. This is used by trigger programs to access the new.*
  78990. ** and old.* values.
  78991. **
  78992. ** The address of the cell in the parent frame is determined by adding
  78993. ** the value of the P1 argument to the value of the P1 argument to the
  78994. ** calling OP_Program instruction.
  78995. */
  78996. case OP_Param: { /* out2 */
  78997. VdbeFrame *pFrame;
  78998. Mem *pIn;
  78999. pOut = out2Prerelease(p, pOp);
  79000. pFrame = p->pFrame;
  79001. pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
  79002. sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
  79003. break;
  79004. }
  79005. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  79006. #ifndef SQLITE_OMIT_FOREIGN_KEY
  79007. /* Opcode: FkCounter P1 P2 * * *
  79008. ** Synopsis: fkctr[P1]+=P2
  79009. **
  79010. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  79011. ** If P1 is non-zero, the database constraint counter is incremented
  79012. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  79013. ** statement counter is incremented (immediate foreign key constraints).
  79014. */
  79015. case OP_FkCounter: {
  79016. if( db->flags & SQLITE_DeferFKs ){
  79017. db->nDeferredImmCons += pOp->p2;
  79018. }else if( pOp->p1 ){
  79019. db->nDeferredCons += pOp->p2;
  79020. }else{
  79021. p->nFkConstraint += pOp->p2;
  79022. }
  79023. break;
  79024. }
  79025. /* Opcode: FkIfZero P1 P2 * * *
  79026. ** Synopsis: if fkctr[P1]==0 goto P2
  79027. **
  79028. ** This opcode tests if a foreign key constraint-counter is currently zero.
  79029. ** If so, jump to instruction P2. Otherwise, fall through to the next
  79030. ** instruction.
  79031. **
  79032. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  79033. ** is zero (the one that counts deferred constraint violations). If P1 is
  79034. ** zero, the jump is taken if the statement constraint-counter is zero
  79035. ** (immediate foreign key constraint violations).
  79036. */
  79037. case OP_FkIfZero: { /* jump */
  79038. if( pOp->p1 ){
  79039. VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
  79040. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  79041. }else{
  79042. VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
  79043. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  79044. }
  79045. break;
  79046. }
  79047. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  79048. #ifndef SQLITE_OMIT_AUTOINCREMENT
  79049. /* Opcode: MemMax P1 P2 * * *
  79050. ** Synopsis: r[P1]=max(r[P1],r[P2])
  79051. **
  79052. ** P1 is a register in the root frame of this VM (the root frame is
  79053. ** different from the current frame if this instruction is being executed
  79054. ** within a sub-program). Set the value of register P1 to the maximum of
  79055. ** its current value and the value in register P2.
  79056. **
  79057. ** This instruction throws an error if the memory cell is not initially
  79058. ** an integer.
  79059. */
  79060. case OP_MemMax: { /* in2 */
  79061. VdbeFrame *pFrame;
  79062. if( p->pFrame ){
  79063. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  79064. pIn1 = &pFrame->aMem[pOp->p1];
  79065. }else{
  79066. pIn1 = &aMem[pOp->p1];
  79067. }
  79068. assert( memIsValid(pIn1) );
  79069. sqlite3VdbeMemIntegerify(pIn1);
  79070. pIn2 = &aMem[pOp->p2];
  79071. sqlite3VdbeMemIntegerify(pIn2);
  79072. if( pIn1->u.i<pIn2->u.i){
  79073. pIn1->u.i = pIn2->u.i;
  79074. }
  79075. break;
  79076. }
  79077. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  79078. /* Opcode: IfPos P1 P2 P3 * *
  79079. ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
  79080. **
  79081. ** Register P1 must contain an integer.
  79082. ** If the value of register P1 is 1 or greater, subtract P3 from the
  79083. ** value in P1 and jump to P2.
  79084. **
  79085. ** If the initial value of register P1 is less than 1, then the
  79086. ** value is unchanged and control passes through to the next instruction.
  79087. */
  79088. case OP_IfPos: { /* jump, in1 */
  79089. pIn1 = &aMem[pOp->p1];
  79090. assert( pIn1->flags&MEM_Int );
  79091. VdbeBranchTaken( pIn1->u.i>0, 2);
  79092. if( pIn1->u.i>0 ){
  79093. pIn1->u.i -= pOp->p3;
  79094. goto jump_to_p2;
  79095. }
  79096. break;
  79097. }
  79098. /* Opcode: OffsetLimit P1 P2 P3 * *
  79099. ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
  79100. **
  79101. ** This opcode performs a commonly used computation associated with
  79102. ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
  79103. ** holds the offset counter. The opcode computes the combined value
  79104. ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
  79105. ** value computed is the total number of rows that will need to be
  79106. ** visited in order to complete the query.
  79107. **
  79108. ** If r[P3] is zero or negative, that means there is no OFFSET
  79109. ** and r[P2] is set to be the value of the LIMIT, r[P1].
  79110. **
  79111. ** if r[P1] is zero or negative, that means there is no LIMIT
  79112. ** and r[P2] is set to -1.
  79113. **
  79114. ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
  79115. */
  79116. case OP_OffsetLimit: { /* in1, out2, in3 */
  79117. i64 x;
  79118. pIn1 = &aMem[pOp->p1];
  79119. pIn3 = &aMem[pOp->p3];
  79120. pOut = out2Prerelease(p, pOp);
  79121. assert( pIn1->flags & MEM_Int );
  79122. assert( pIn3->flags & MEM_Int );
  79123. x = pIn1->u.i;
  79124. if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
  79125. /* If the LIMIT is less than or equal to zero, loop forever. This
  79126. ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
  79127. ** also loop forever. This is undocumented. In fact, one could argue
  79128. ** that the loop should terminate. But assuming 1 billion iterations
  79129. ** per second (far exceeding the capabilities of any current hardware)
  79130. ** it would take nearly 300 years to actually reach the limit. So
  79131. ** looping forever is a reasonable approximation. */
  79132. pOut->u.i = -1;
  79133. }else{
  79134. pOut->u.i = x;
  79135. }
  79136. break;
  79137. }
  79138. /* Opcode: IfNotZero P1 P2 * * *
  79139. ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
  79140. **
  79141. ** Register P1 must contain an integer. If the content of register P1 is
  79142. ** initially greater than zero, then decrement the value in register P1.
  79143. ** If it is non-zero (negative or positive) and then also jump to P2.
  79144. ** If register P1 is initially zero, leave it unchanged and fall through.
  79145. */
  79146. case OP_IfNotZero: { /* jump, in1 */
  79147. pIn1 = &aMem[pOp->p1];
  79148. assert( pIn1->flags&MEM_Int );
  79149. VdbeBranchTaken(pIn1->u.i<0, 2);
  79150. if( pIn1->u.i ){
  79151. if( pIn1->u.i>0 ) pIn1->u.i--;
  79152. goto jump_to_p2;
  79153. }
  79154. break;
  79155. }
  79156. /* Opcode: DecrJumpZero P1 P2 * * *
  79157. ** Synopsis: if (--r[P1])==0 goto P2
  79158. **
  79159. ** Register P1 must hold an integer. Decrement the value in P1
  79160. ** and jump to P2 if the new value is exactly zero.
  79161. */
  79162. case OP_DecrJumpZero: { /* jump, in1 */
  79163. pIn1 = &aMem[pOp->p1];
  79164. assert( pIn1->flags&MEM_Int );
  79165. if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
  79166. VdbeBranchTaken(pIn1->u.i==0, 2);
  79167. if( pIn1->u.i==0 ) goto jump_to_p2;
  79168. break;
  79169. }
  79170. /* Opcode: AggStep0 * P2 P3 P4 P5
  79171. ** Synopsis: accum=r[P3] step(r[P2@P5])
  79172. **
  79173. ** Execute the step function for an aggregate. The
  79174. ** function has P5 arguments. P4 is a pointer to the FuncDef
  79175. ** structure that specifies the function. Register P3 is the
  79176. ** accumulator.
  79177. **
  79178. ** The P5 arguments are taken from register P2 and its
  79179. ** successors.
  79180. */
  79181. /* Opcode: AggStep * P2 P3 P4 P5
  79182. ** Synopsis: accum=r[P3] step(r[P2@P5])
  79183. **
  79184. ** Execute the step function for an aggregate. The
  79185. ** function has P5 arguments. P4 is a pointer to an sqlite3_context
  79186. ** object that is used to run the function. Register P3 is
  79187. ** as the accumulator.
  79188. **
  79189. ** The P5 arguments are taken from register P2 and its
  79190. ** successors.
  79191. **
  79192. ** This opcode is initially coded as OP_AggStep0. On first evaluation,
  79193. ** the FuncDef stored in P4 is converted into an sqlite3_context and
  79194. ** the opcode is changed. In this way, the initialization of the
  79195. ** sqlite3_context only happens once, instead of on each call to the
  79196. ** step function.
  79197. */
  79198. case OP_AggStep0: {
  79199. int n;
  79200. sqlite3_context *pCtx;
  79201. assert( pOp->p4type==P4_FUNCDEF );
  79202. n = pOp->p5;
  79203. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  79204. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  79205. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  79206. pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  79207. if( pCtx==0 ) goto no_mem;
  79208. pCtx->pMem = 0;
  79209. pCtx->pFunc = pOp->p4.pFunc;
  79210. pCtx->iOp = (int)(pOp - aOp);
  79211. pCtx->pVdbe = p;
  79212. pCtx->argc = n;
  79213. pOp->p4type = P4_FUNCCTX;
  79214. pOp->p4.pCtx = pCtx;
  79215. pOp->opcode = OP_AggStep;
  79216. /* Fall through into OP_AggStep */
  79217. }
  79218. case OP_AggStep: {
  79219. int i;
  79220. sqlite3_context *pCtx;
  79221. Mem *pMem;
  79222. Mem t;
  79223. assert( pOp->p4type==P4_FUNCCTX );
  79224. pCtx = pOp->p4.pCtx;
  79225. pMem = &aMem[pOp->p3];
  79226. /* If this function is inside of a trigger, the register array in aMem[]
  79227. ** might change from one evaluation to the next. The next block of code
  79228. ** checks to see if the register array has changed, and if so it
  79229. ** reinitializes the relavant parts of the sqlite3_context object */
  79230. if( pCtx->pMem != pMem ){
  79231. pCtx->pMem = pMem;
  79232. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  79233. }
  79234. #ifdef SQLITE_DEBUG
  79235. for(i=0; i<pCtx->argc; i++){
  79236. assert( memIsValid(pCtx->argv[i]) );
  79237. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  79238. }
  79239. #endif
  79240. pMem->n++;
  79241. sqlite3VdbeMemInit(&t, db, MEM_Null);
  79242. pCtx->pOut = &t;
  79243. pCtx->fErrorOrAux = 0;
  79244. pCtx->skipFlag = 0;
  79245. (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
  79246. if( pCtx->fErrorOrAux ){
  79247. if( pCtx->isError ){
  79248. sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
  79249. rc = pCtx->isError;
  79250. }
  79251. sqlite3VdbeMemRelease(&t);
  79252. if( rc ) goto abort_due_to_error;
  79253. }else{
  79254. assert( t.flags==MEM_Null );
  79255. }
  79256. if( pCtx->skipFlag ){
  79257. assert( pOp[-1].opcode==OP_CollSeq );
  79258. i = pOp[-1].p1;
  79259. if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
  79260. }
  79261. break;
  79262. }
  79263. /* Opcode: AggFinal P1 P2 * P4 *
  79264. ** Synopsis: accum=r[P1] N=P2
  79265. **
  79266. ** Execute the finalizer function for an aggregate. P1 is
  79267. ** the memory location that is the accumulator for the aggregate.
  79268. **
  79269. ** P2 is the number of arguments that the step function takes and
  79270. ** P4 is a pointer to the FuncDef for this function. The P2
  79271. ** argument is not used by this opcode. It is only there to disambiguate
  79272. ** functions that can take varying numbers of arguments. The
  79273. ** P4 argument is only needed for the degenerate case where
  79274. ** the step function was not previously called.
  79275. */
  79276. case OP_AggFinal: {
  79277. Mem *pMem;
  79278. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  79279. pMem = &aMem[pOp->p1];
  79280. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  79281. rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  79282. if( rc ){
  79283. sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
  79284. goto abort_due_to_error;
  79285. }
  79286. sqlite3VdbeChangeEncoding(pMem, encoding);
  79287. UPDATE_MAX_BLOBSIZE(pMem);
  79288. if( sqlite3VdbeMemTooBig(pMem) ){
  79289. goto too_big;
  79290. }
  79291. break;
  79292. }
  79293. #ifndef SQLITE_OMIT_WAL
  79294. /* Opcode: Checkpoint P1 P2 P3 * *
  79295. **
  79296. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  79297. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
  79298. ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
  79299. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  79300. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  79301. ** in the WAL that have been checkpointed after the checkpoint
  79302. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  79303. ** mem[P3+2] are initialized to -1.
  79304. */
  79305. case OP_Checkpoint: {
  79306. int i; /* Loop counter */
  79307. int aRes[3]; /* Results */
  79308. Mem *pMem; /* Write results here */
  79309. assert( p->readOnly==0 );
  79310. aRes[0] = 0;
  79311. aRes[1] = aRes[2] = -1;
  79312. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  79313. || pOp->p2==SQLITE_CHECKPOINT_FULL
  79314. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  79315. || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
  79316. );
  79317. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
  79318. if( rc ){
  79319. if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
  79320. rc = SQLITE_OK;
  79321. aRes[0] = 1;
  79322. }
  79323. for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
  79324. sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
  79325. }
  79326. break;
  79327. };
  79328. #endif
  79329. #ifndef SQLITE_OMIT_PRAGMA
  79330. /* Opcode: JournalMode P1 P2 P3 * *
  79331. **
  79332. ** Change the journal mode of database P1 to P3. P3 must be one of the
  79333. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  79334. ** modes (delete, truncate, persist, off and memory), this is a simple
  79335. ** operation. No IO is required.
  79336. **
  79337. ** If changing into or out of WAL mode the procedure is more complicated.
  79338. **
  79339. ** Write a string containing the final journal-mode to register P2.
  79340. */
  79341. case OP_JournalMode: { /* out2 */
  79342. Btree *pBt; /* Btree to change journal mode of */
  79343. Pager *pPager; /* Pager associated with pBt */
  79344. int eNew; /* New journal mode */
  79345. int eOld; /* The old journal mode */
  79346. #ifndef SQLITE_OMIT_WAL
  79347. const char *zFilename; /* Name of database file for pPager */
  79348. #endif
  79349. pOut = out2Prerelease(p, pOp);
  79350. eNew = pOp->p3;
  79351. assert( eNew==PAGER_JOURNALMODE_DELETE
  79352. || eNew==PAGER_JOURNALMODE_TRUNCATE
  79353. || eNew==PAGER_JOURNALMODE_PERSIST
  79354. || eNew==PAGER_JOURNALMODE_OFF
  79355. || eNew==PAGER_JOURNALMODE_MEMORY
  79356. || eNew==PAGER_JOURNALMODE_WAL
  79357. || eNew==PAGER_JOURNALMODE_QUERY
  79358. );
  79359. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  79360. assert( p->readOnly==0 );
  79361. pBt = db->aDb[pOp->p1].pBt;
  79362. pPager = sqlite3BtreePager(pBt);
  79363. eOld = sqlite3PagerGetJournalMode(pPager);
  79364. if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
  79365. if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
  79366. #ifndef SQLITE_OMIT_WAL
  79367. zFilename = sqlite3PagerFilename(pPager, 1);
  79368. /* Do not allow a transition to journal_mode=WAL for a database
  79369. ** in temporary storage or if the VFS does not support shared memory
  79370. */
  79371. if( eNew==PAGER_JOURNALMODE_WAL
  79372. && (sqlite3Strlen30(zFilename)==0 /* Temp file */
  79373. || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
  79374. ){
  79375. eNew = eOld;
  79376. }
  79377. if( (eNew!=eOld)
  79378. && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
  79379. ){
  79380. if( !db->autoCommit || db->nVdbeRead>1 ){
  79381. rc = SQLITE_ERROR;
  79382. sqlite3VdbeError(p,
  79383. "cannot change %s wal mode from within a transaction",
  79384. (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  79385. );
  79386. goto abort_due_to_error;
  79387. }else{
  79388. if( eOld==PAGER_JOURNALMODE_WAL ){
  79389. /* If leaving WAL mode, close the log file. If successful, the call
  79390. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  79391. ** file. An EXCLUSIVE lock may still be held on the database file
  79392. ** after a successful return.
  79393. */
  79394. rc = sqlite3PagerCloseWal(pPager, db);
  79395. if( rc==SQLITE_OK ){
  79396. sqlite3PagerSetJournalMode(pPager, eNew);
  79397. }
  79398. }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
  79399. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  79400. ** as an intermediate */
  79401. sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
  79402. }
  79403. /* Open a transaction on the database file. Regardless of the journal
  79404. ** mode, this transaction always uses a rollback journal.
  79405. */
  79406. assert( sqlite3BtreeIsInTrans(pBt)==0 );
  79407. if( rc==SQLITE_OK ){
  79408. rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  79409. }
  79410. }
  79411. }
  79412. #endif /* ifndef SQLITE_OMIT_WAL */
  79413. if( rc ) eNew = eOld;
  79414. eNew = sqlite3PagerSetJournalMode(pPager, eNew);
  79415. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  79416. pOut->z = (char *)sqlite3JournalModename(eNew);
  79417. pOut->n = sqlite3Strlen30(pOut->z);
  79418. pOut->enc = SQLITE_UTF8;
  79419. sqlite3VdbeChangeEncoding(pOut, encoding);
  79420. if( rc ) goto abort_due_to_error;
  79421. break;
  79422. };
  79423. #endif /* SQLITE_OMIT_PRAGMA */
  79424. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  79425. /* Opcode: Vacuum P1 * * * *
  79426. **
  79427. ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
  79428. ** for an attached database. The "temp" database may not be vacuumed.
  79429. */
  79430. case OP_Vacuum: {
  79431. assert( p->readOnly==0 );
  79432. rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
  79433. if( rc ) goto abort_due_to_error;
  79434. break;
  79435. }
  79436. #endif
  79437. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  79438. /* Opcode: IncrVacuum P1 P2 * * *
  79439. **
  79440. ** Perform a single step of the incremental vacuum procedure on
  79441. ** the P1 database. If the vacuum has finished, jump to instruction
  79442. ** P2. Otherwise, fall through to the next instruction.
  79443. */
  79444. case OP_IncrVacuum: { /* jump */
  79445. Btree *pBt;
  79446. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  79447. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  79448. assert( p->readOnly==0 );
  79449. pBt = db->aDb[pOp->p1].pBt;
  79450. rc = sqlite3BtreeIncrVacuum(pBt);
  79451. VdbeBranchTaken(rc==SQLITE_DONE,2);
  79452. if( rc ){
  79453. if( rc!=SQLITE_DONE ) goto abort_due_to_error;
  79454. rc = SQLITE_OK;
  79455. goto jump_to_p2;
  79456. }
  79457. break;
  79458. }
  79459. #endif
  79460. /* Opcode: Expire P1 * * * *
  79461. **
  79462. ** Cause precompiled statements to expire. When an expired statement
  79463. ** is executed using sqlite3_step() it will either automatically
  79464. ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
  79465. ** or it will fail with SQLITE_SCHEMA.
  79466. **
  79467. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  79468. ** then only the currently executing statement is expired.
  79469. */
  79470. case OP_Expire: {
  79471. if( !pOp->p1 ){
  79472. sqlite3ExpirePreparedStatements(db);
  79473. }else{
  79474. p->expired = 1;
  79475. }
  79476. break;
  79477. }
  79478. #ifndef SQLITE_OMIT_SHARED_CACHE
  79479. /* Opcode: TableLock P1 P2 P3 P4 *
  79480. ** Synopsis: iDb=P1 root=P2 write=P3
  79481. **
  79482. ** Obtain a lock on a particular table. This instruction is only used when
  79483. ** the shared-cache feature is enabled.
  79484. **
  79485. ** P1 is the index of the database in sqlite3.aDb[] of the database
  79486. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  79487. ** a write lock if P3==1.
  79488. **
  79489. ** P2 contains the root-page of the table to lock.
  79490. **
  79491. ** P4 contains a pointer to the name of the table being locked. This is only
  79492. ** used to generate an error message if the lock cannot be obtained.
  79493. */
  79494. case OP_TableLock: {
  79495. u8 isWriteLock = (u8)pOp->p3;
  79496. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
  79497. int p1 = pOp->p1;
  79498. assert( p1>=0 && p1<db->nDb );
  79499. assert( DbMaskTest(p->btreeMask, p1) );
  79500. assert( isWriteLock==0 || isWriteLock==1 );
  79501. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  79502. if( rc ){
  79503. if( (rc&0xFF)==SQLITE_LOCKED ){
  79504. const char *z = pOp->p4.z;
  79505. sqlite3VdbeError(p, "database table is locked: %s", z);
  79506. }
  79507. goto abort_due_to_error;
  79508. }
  79509. }
  79510. break;
  79511. }
  79512. #endif /* SQLITE_OMIT_SHARED_CACHE */
  79513. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79514. /* Opcode: VBegin * * * P4 *
  79515. **
  79516. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  79517. ** xBegin method for that table.
  79518. **
  79519. ** Also, whether or not P4 is set, check that this is not being called from
  79520. ** within a callback to a virtual table xSync() method. If it is, the error
  79521. ** code will be set to SQLITE_LOCKED.
  79522. */
  79523. case OP_VBegin: {
  79524. VTable *pVTab;
  79525. pVTab = pOp->p4.pVtab;
  79526. rc = sqlite3VtabBegin(db, pVTab);
  79527. if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
  79528. if( rc ) goto abort_due_to_error;
  79529. break;
  79530. }
  79531. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  79532. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79533. /* Opcode: VCreate P1 P2 * * *
  79534. **
  79535. ** P2 is a register that holds the name of a virtual table in database
  79536. ** P1. Call the xCreate method for that table.
  79537. */
  79538. case OP_VCreate: {
  79539. Mem sMem; /* For storing the record being decoded */
  79540. const char *zTab; /* Name of the virtual table */
  79541. memset(&sMem, 0, sizeof(sMem));
  79542. sMem.db = db;
  79543. /* Because P2 is always a static string, it is impossible for the
  79544. ** sqlite3VdbeMemCopy() to fail */
  79545. assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
  79546. assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
  79547. rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
  79548. assert( rc==SQLITE_OK );
  79549. zTab = (const char*)sqlite3_value_text(&sMem);
  79550. assert( zTab || db->mallocFailed );
  79551. if( zTab ){
  79552. rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
  79553. }
  79554. sqlite3VdbeMemRelease(&sMem);
  79555. if( rc ) goto abort_due_to_error;
  79556. break;
  79557. }
  79558. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  79559. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79560. /* Opcode: VDestroy P1 * * P4 *
  79561. **
  79562. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  79563. ** of that table.
  79564. */
  79565. case OP_VDestroy: {
  79566. db->nVDestroy++;
  79567. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  79568. db->nVDestroy--;
  79569. if( rc ) goto abort_due_to_error;
  79570. break;
  79571. }
  79572. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  79573. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79574. /* Opcode: VOpen P1 * * P4 *
  79575. **
  79576. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  79577. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  79578. ** table and stores that cursor in P1.
  79579. */
  79580. case OP_VOpen: {
  79581. VdbeCursor *pCur;
  79582. sqlite3_vtab_cursor *pVCur;
  79583. sqlite3_vtab *pVtab;
  79584. const sqlite3_module *pModule;
  79585. assert( p->bIsReader );
  79586. pCur = 0;
  79587. pVCur = 0;
  79588. pVtab = pOp->p4.pVtab->pVtab;
  79589. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  79590. rc = SQLITE_LOCKED;
  79591. goto abort_due_to_error;
  79592. }
  79593. pModule = pVtab->pModule;
  79594. rc = pModule->xOpen(pVtab, &pVCur);
  79595. sqlite3VtabImportErrmsg(p, pVtab);
  79596. if( rc ) goto abort_due_to_error;
  79597. /* Initialize sqlite3_vtab_cursor base class */
  79598. pVCur->pVtab = pVtab;
  79599. /* Initialize vdbe cursor object */
  79600. pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
  79601. if( pCur ){
  79602. pCur->uc.pVCur = pVCur;
  79603. pVtab->nRef++;
  79604. }else{
  79605. assert( db->mallocFailed );
  79606. pModule->xClose(pVCur);
  79607. goto no_mem;
  79608. }
  79609. break;
  79610. }
  79611. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  79612. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79613. /* Opcode: VFilter P1 P2 P3 P4 *
  79614. ** Synopsis: iplan=r[P3] zplan='P4'
  79615. **
  79616. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  79617. ** the filtered result set is empty.
  79618. **
  79619. ** P4 is either NULL or a string that was generated by the xBestIndex
  79620. ** method of the module. The interpretation of the P4 string is left
  79621. ** to the module implementation.
  79622. **
  79623. ** This opcode invokes the xFilter method on the virtual table specified
  79624. ** by P1. The integer query plan parameter to xFilter is stored in register
  79625. ** P3. Register P3+1 stores the argc parameter to be passed to the
  79626. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  79627. ** additional parameters which are passed to
  79628. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  79629. **
  79630. ** A jump is made to P2 if the result set after filtering would be empty.
  79631. */
  79632. case OP_VFilter: { /* jump */
  79633. int nArg;
  79634. int iQuery;
  79635. const sqlite3_module *pModule;
  79636. Mem *pQuery;
  79637. Mem *pArgc;
  79638. sqlite3_vtab_cursor *pVCur;
  79639. sqlite3_vtab *pVtab;
  79640. VdbeCursor *pCur;
  79641. int res;
  79642. int i;
  79643. Mem **apArg;
  79644. pQuery = &aMem[pOp->p3];
  79645. pArgc = &pQuery[1];
  79646. pCur = p->apCsr[pOp->p1];
  79647. assert( memIsValid(pQuery) );
  79648. REGISTER_TRACE(pOp->p3, pQuery);
  79649. assert( pCur->eCurType==CURTYPE_VTAB );
  79650. pVCur = pCur->uc.pVCur;
  79651. pVtab = pVCur->pVtab;
  79652. pModule = pVtab->pModule;
  79653. /* Grab the index number and argc parameters */
  79654. assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  79655. nArg = (int)pArgc->u.i;
  79656. iQuery = (int)pQuery->u.i;
  79657. /* Invoke the xFilter method */
  79658. res = 0;
  79659. apArg = p->apArg;
  79660. for(i = 0; i<nArg; i++){
  79661. apArg[i] = &pArgc[i+1];
  79662. }
  79663. rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
  79664. sqlite3VtabImportErrmsg(p, pVtab);
  79665. if( rc ) goto abort_due_to_error;
  79666. res = pModule->xEof(pVCur);
  79667. pCur->nullRow = 0;
  79668. VdbeBranchTaken(res!=0,2);
  79669. if( res ) goto jump_to_p2;
  79670. break;
  79671. }
  79672. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  79673. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79674. /* Opcode: VColumn P1 P2 P3 * *
  79675. ** Synopsis: r[P3]=vcolumn(P2)
  79676. **
  79677. ** Store the value of the P2-th column of
  79678. ** the row of the virtual-table that the
  79679. ** P1 cursor is pointing to into register P3.
  79680. */
  79681. case OP_VColumn: {
  79682. sqlite3_vtab *pVtab;
  79683. const sqlite3_module *pModule;
  79684. Mem *pDest;
  79685. sqlite3_context sContext;
  79686. VdbeCursor *pCur = p->apCsr[pOp->p1];
  79687. assert( pCur->eCurType==CURTYPE_VTAB );
  79688. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  79689. pDest = &aMem[pOp->p3];
  79690. memAboutToChange(p, pDest);
  79691. if( pCur->nullRow ){
  79692. sqlite3VdbeMemSetNull(pDest);
  79693. break;
  79694. }
  79695. pVtab = pCur->uc.pVCur->pVtab;
  79696. pModule = pVtab->pModule;
  79697. assert( pModule->xColumn );
  79698. memset(&sContext, 0, sizeof(sContext));
  79699. sContext.pOut = pDest;
  79700. MemSetTypeFlag(pDest, MEM_Null);
  79701. rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
  79702. sqlite3VtabImportErrmsg(p, pVtab);
  79703. if( sContext.isError ){
  79704. rc = sContext.isError;
  79705. }
  79706. sqlite3VdbeChangeEncoding(pDest, encoding);
  79707. REGISTER_TRACE(pOp->p3, pDest);
  79708. UPDATE_MAX_BLOBSIZE(pDest);
  79709. if( sqlite3VdbeMemTooBig(pDest) ){
  79710. goto too_big;
  79711. }
  79712. if( rc ) goto abort_due_to_error;
  79713. break;
  79714. }
  79715. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  79716. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79717. /* Opcode: VNext P1 P2 * * *
  79718. **
  79719. ** Advance virtual table P1 to the next row in its result set and
  79720. ** jump to instruction P2. Or, if the virtual table has reached
  79721. ** the end of its result set, then fall through to the next instruction.
  79722. */
  79723. case OP_VNext: { /* jump */
  79724. sqlite3_vtab *pVtab;
  79725. const sqlite3_module *pModule;
  79726. int res;
  79727. VdbeCursor *pCur;
  79728. res = 0;
  79729. pCur = p->apCsr[pOp->p1];
  79730. assert( pCur->eCurType==CURTYPE_VTAB );
  79731. if( pCur->nullRow ){
  79732. break;
  79733. }
  79734. pVtab = pCur->uc.pVCur->pVtab;
  79735. pModule = pVtab->pModule;
  79736. assert( pModule->xNext );
  79737. /* Invoke the xNext() method of the module. There is no way for the
  79738. ** underlying implementation to return an error if one occurs during
  79739. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  79740. ** data is available) and the error code returned when xColumn or
  79741. ** some other method is next invoked on the save virtual table cursor.
  79742. */
  79743. rc = pModule->xNext(pCur->uc.pVCur);
  79744. sqlite3VtabImportErrmsg(p, pVtab);
  79745. if( rc ) goto abort_due_to_error;
  79746. res = pModule->xEof(pCur->uc.pVCur);
  79747. VdbeBranchTaken(!res,2);
  79748. if( !res ){
  79749. /* If there is data, jump to P2 */
  79750. goto jump_to_p2_and_check_for_interrupt;
  79751. }
  79752. goto check_for_interrupt;
  79753. }
  79754. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  79755. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79756. /* Opcode: VRename P1 * * P4 *
  79757. **
  79758. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  79759. ** This opcode invokes the corresponding xRename method. The value
  79760. ** in register P1 is passed as the zName argument to the xRename method.
  79761. */
  79762. case OP_VRename: {
  79763. sqlite3_vtab *pVtab;
  79764. Mem *pName;
  79765. pVtab = pOp->p4.pVtab->pVtab;
  79766. pName = &aMem[pOp->p1];
  79767. assert( pVtab->pModule->xRename );
  79768. assert( memIsValid(pName) );
  79769. assert( p->readOnly==0 );
  79770. REGISTER_TRACE(pOp->p1, pName);
  79771. assert( pName->flags & MEM_Str );
  79772. testcase( pName->enc==SQLITE_UTF8 );
  79773. testcase( pName->enc==SQLITE_UTF16BE );
  79774. testcase( pName->enc==SQLITE_UTF16LE );
  79775. rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
  79776. if( rc ) goto abort_due_to_error;
  79777. rc = pVtab->pModule->xRename(pVtab, pName->z);
  79778. sqlite3VtabImportErrmsg(p, pVtab);
  79779. p->expired = 0;
  79780. if( rc ) goto abort_due_to_error;
  79781. break;
  79782. }
  79783. #endif
  79784. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79785. /* Opcode: VUpdate P1 P2 P3 P4 P5
  79786. ** Synopsis: data=r[P3@P2]
  79787. **
  79788. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  79789. ** This opcode invokes the corresponding xUpdate method. P2 values
  79790. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  79791. ** invocation. The value in register (P3+P2-1) corresponds to the
  79792. ** p2th element of the argv array passed to xUpdate.
  79793. **
  79794. ** The xUpdate method will do a DELETE or an INSERT or both.
  79795. ** The argv[0] element (which corresponds to memory cell P3)
  79796. ** is the rowid of a row to delete. If argv[0] is NULL then no
  79797. ** deletion occurs. The argv[1] element is the rowid of the new
  79798. ** row. This can be NULL to have the virtual table select the new
  79799. ** rowid for itself. The subsequent elements in the array are
  79800. ** the values of columns in the new row.
  79801. **
  79802. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  79803. ** a row to delete.
  79804. **
  79805. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  79806. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  79807. ** is set to the value of the rowid for the row just inserted.
  79808. **
  79809. ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
  79810. ** apply in the case of a constraint failure on an insert or update.
  79811. */
  79812. case OP_VUpdate: {
  79813. sqlite3_vtab *pVtab;
  79814. const sqlite3_module *pModule;
  79815. int nArg;
  79816. int i;
  79817. sqlite_int64 rowid;
  79818. Mem **apArg;
  79819. Mem *pX;
  79820. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  79821. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  79822. );
  79823. assert( p->readOnly==0 );
  79824. pVtab = pOp->p4.pVtab->pVtab;
  79825. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  79826. rc = SQLITE_LOCKED;
  79827. goto abort_due_to_error;
  79828. }
  79829. pModule = pVtab->pModule;
  79830. nArg = pOp->p2;
  79831. assert( pOp->p4type==P4_VTAB );
  79832. if( ALWAYS(pModule->xUpdate) ){
  79833. u8 vtabOnConflict = db->vtabOnConflict;
  79834. apArg = p->apArg;
  79835. pX = &aMem[pOp->p3];
  79836. for(i=0; i<nArg; i++){
  79837. assert( memIsValid(pX) );
  79838. memAboutToChange(p, pX);
  79839. apArg[i] = pX;
  79840. pX++;
  79841. }
  79842. db->vtabOnConflict = pOp->p5;
  79843. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  79844. db->vtabOnConflict = vtabOnConflict;
  79845. sqlite3VtabImportErrmsg(p, pVtab);
  79846. if( rc==SQLITE_OK && pOp->p1 ){
  79847. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  79848. db->lastRowid = rowid;
  79849. }
  79850. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  79851. if( pOp->p5==OE_Ignore ){
  79852. rc = SQLITE_OK;
  79853. }else{
  79854. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  79855. }
  79856. }else{
  79857. p->nChange++;
  79858. }
  79859. if( rc ) goto abort_due_to_error;
  79860. }
  79861. break;
  79862. }
  79863. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  79864. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  79865. /* Opcode: Pagecount P1 P2 * * *
  79866. **
  79867. ** Write the current number of pages in database P1 to memory cell P2.
  79868. */
  79869. case OP_Pagecount: { /* out2 */
  79870. pOut = out2Prerelease(p, pOp);
  79871. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  79872. break;
  79873. }
  79874. #endif
  79875. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  79876. /* Opcode: MaxPgcnt P1 P2 P3 * *
  79877. **
  79878. ** Try to set the maximum page count for database P1 to the value in P3.
  79879. ** Do not let the maximum page count fall below the current page count and
  79880. ** do not change the maximum page count value if P3==0.
  79881. **
  79882. ** Store the maximum page count after the change in register P2.
  79883. */
  79884. case OP_MaxPgcnt: { /* out2 */
  79885. unsigned int newMax;
  79886. Btree *pBt;
  79887. pOut = out2Prerelease(p, pOp);
  79888. pBt = db->aDb[pOp->p1].pBt;
  79889. newMax = 0;
  79890. if( pOp->p3 ){
  79891. newMax = sqlite3BtreeLastPage(pBt);
  79892. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  79893. }
  79894. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  79895. break;
  79896. }
  79897. #endif
  79898. /* Opcode: Init P1 P2 * P4 *
  79899. ** Synopsis: Start at P2
  79900. **
  79901. ** Programs contain a single instance of this opcode as the very first
  79902. ** opcode.
  79903. **
  79904. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  79905. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  79906. ** Or if P4 is blank, use the string returned by sqlite3_sql().
  79907. **
  79908. ** If P2 is not zero, jump to instruction P2.
  79909. **
  79910. ** Increment the value of P1 so that OP_Once opcodes will jump the
  79911. ** first time they are evaluated for this run.
  79912. */
  79913. case OP_Init: { /* jump */
  79914. char *zTrace;
  79915. int i;
  79916. /* If the P4 argument is not NULL, then it must be an SQL comment string.
  79917. ** The "--" string is broken up to prevent false-positives with srcck1.c.
  79918. **
  79919. ** This assert() provides evidence for:
  79920. ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
  79921. ** would have been returned by the legacy sqlite3_trace() interface by
  79922. ** using the X argument when X begins with "--" and invoking
  79923. ** sqlite3_expanded_sql(P) otherwise.
  79924. */
  79925. assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
  79926. assert( pOp==p->aOp ); /* Always instruction 0 */
  79927. #ifndef SQLITE_OMIT_TRACE
  79928. if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
  79929. && !p->doingRerun
  79930. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  79931. ){
  79932. #ifndef SQLITE_OMIT_DEPRECATED
  79933. if( db->mTrace & SQLITE_TRACE_LEGACY ){
  79934. void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
  79935. char *z = sqlite3VdbeExpandSql(p, zTrace);
  79936. x(db->pTraceArg, z);
  79937. sqlite3_free(z);
  79938. }else
  79939. #endif
  79940. if( db->nVdbeExec>1 ){
  79941. char *z = sqlite3MPrintf(db, "-- %s", zTrace);
  79942. (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
  79943. sqlite3DbFree(db, z);
  79944. }else{
  79945. (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
  79946. }
  79947. }
  79948. #ifdef SQLITE_USE_FCNTL_TRACE
  79949. zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  79950. if( zTrace ){
  79951. int j;
  79952. for(j=0; j<db->nDb; j++){
  79953. if( DbMaskTest(p->btreeMask, j)==0 ) continue;
  79954. sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
  79955. }
  79956. }
  79957. #endif /* SQLITE_USE_FCNTL_TRACE */
  79958. #ifdef SQLITE_DEBUG
  79959. if( (db->flags & SQLITE_SqlTrace)!=0
  79960. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  79961. ){
  79962. sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
  79963. }
  79964. #endif /* SQLITE_DEBUG */
  79965. #endif /* SQLITE_OMIT_TRACE */
  79966. assert( pOp->p2>0 );
  79967. if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
  79968. for(i=1; i<p->nOp; i++){
  79969. if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
  79970. }
  79971. pOp->p1 = 0;
  79972. }
  79973. pOp->p1++;
  79974. goto jump_to_p2;
  79975. }
  79976. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  79977. /* Opcode: CursorHint P1 * * P4 *
  79978. **
  79979. ** Provide a hint to cursor P1 that it only needs to return rows that
  79980. ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
  79981. ** to values currently held in registers. TK_COLUMN terms in the P4
  79982. ** expression refer to columns in the b-tree to which cursor P1 is pointing.
  79983. */
  79984. case OP_CursorHint: {
  79985. VdbeCursor *pC;
  79986. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  79987. assert( pOp->p4type==P4_EXPR );
  79988. pC = p->apCsr[pOp->p1];
  79989. if( pC ){
  79990. assert( pC->eCurType==CURTYPE_BTREE );
  79991. sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
  79992. pOp->p4.pExpr, aMem);
  79993. }
  79994. break;
  79995. }
  79996. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  79997. /* Opcode: Noop * * * * *
  79998. **
  79999. ** Do nothing. This instruction is often useful as a jump
  80000. ** destination.
  80001. */
  80002. /*
  80003. ** The magic Explain opcode are only inserted when explain==2 (which
  80004. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  80005. ** This opcode records information from the optimizer. It is the
  80006. ** the same as a no-op. This opcodesnever appears in a real VM program.
  80007. */
  80008. default: { /* This is really OP_Noop and OP_Explain */
  80009. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  80010. break;
  80011. }
  80012. /*****************************************************************************
  80013. ** The cases of the switch statement above this line should all be indented
  80014. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  80015. ** readability. From this point on down, the normal indentation rules are
  80016. ** restored.
  80017. *****************************************************************************/
  80018. }
  80019. #ifdef VDBE_PROFILE
  80020. {
  80021. u64 endTime = sqlite3Hwtime();
  80022. if( endTime>start ) pOrigOp->cycles += endTime - start;
  80023. pOrigOp->cnt++;
  80024. }
  80025. #endif
  80026. /* The following code adds nothing to the actual functionality
  80027. ** of the program. It is only here for testing and debugging.
  80028. ** On the other hand, it does burn CPU cycles every time through
  80029. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  80030. */
  80031. #ifndef NDEBUG
  80032. assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
  80033. #ifdef SQLITE_DEBUG
  80034. if( db->flags & SQLITE_VdbeTrace ){
  80035. u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
  80036. if( rc!=0 ) printf("rc=%d\n",rc);
  80037. if( opProperty & (OPFLG_OUT2) ){
  80038. registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
  80039. }
  80040. if( opProperty & OPFLG_OUT3 ){
  80041. registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
  80042. }
  80043. }
  80044. #endif /* SQLITE_DEBUG */
  80045. #endif /* NDEBUG */
  80046. } /* The end of the for(;;) loop the loops through opcodes */
  80047. /* If we reach this point, it means that execution is finished with
  80048. ** an error of some kind.
  80049. */
  80050. abort_due_to_error:
  80051. if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
  80052. assert( rc );
  80053. if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
  80054. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  80055. }
  80056. p->rc = rc;
  80057. sqlite3SystemError(db, rc);
  80058. testcase( sqlite3GlobalConfig.xLog!=0 );
  80059. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  80060. (int)(pOp - aOp), p->zSql, p->zErrMsg);
  80061. sqlite3VdbeHalt(p);
  80062. if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
  80063. rc = SQLITE_ERROR;
  80064. if( resetSchemaOnFault>0 ){
  80065. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  80066. }
  80067. /* This is the only way out of this procedure. We have to
  80068. ** release the mutexes on btrees that were acquired at the
  80069. ** top. */
  80070. vdbe_return:
  80071. testcase( nVmStep>0 );
  80072. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  80073. sqlite3VdbeLeave(p);
  80074. assert( rc!=SQLITE_OK || nExtraDelete==0
  80075. || sqlite3_strlike("DELETE%",p->zSql,0)!=0
  80076. );
  80077. return rc;
  80078. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  80079. ** is encountered.
  80080. */
  80081. too_big:
  80082. sqlite3VdbeError(p, "string or blob too big");
  80083. rc = SQLITE_TOOBIG;
  80084. goto abort_due_to_error;
  80085. /* Jump to here if a malloc() fails.
  80086. */
  80087. no_mem:
  80088. sqlite3OomFault(db);
  80089. sqlite3VdbeError(p, "out of memory");
  80090. rc = SQLITE_NOMEM_BKPT;
  80091. goto abort_due_to_error;
  80092. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  80093. ** flag.
  80094. */
  80095. abort_due_to_interrupt:
  80096. assert( db->u1.isInterrupted );
  80097. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  80098. p->rc = rc;
  80099. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  80100. goto abort_due_to_error;
  80101. }
  80102. /************** End of vdbe.c ************************************************/
  80103. /************** Begin file vdbeblob.c ****************************************/
  80104. /*
  80105. ** 2007 May 1
  80106. **
  80107. ** The author disclaims copyright to this source code. In place of
  80108. ** a legal notice, here is a blessing:
  80109. **
  80110. ** May you do good and not evil.
  80111. ** May you find forgiveness for yourself and forgive others.
  80112. ** May you share freely, never taking more than you give.
  80113. **
  80114. *************************************************************************
  80115. **
  80116. ** This file contains code used to implement incremental BLOB I/O.
  80117. */
  80118. /* #include "sqliteInt.h" */
  80119. /* #include "vdbeInt.h" */
  80120. #ifndef SQLITE_OMIT_INCRBLOB
  80121. /*
  80122. ** Valid sqlite3_blob* handles point to Incrblob structures.
  80123. */
  80124. typedef struct Incrblob Incrblob;
  80125. struct Incrblob {
  80126. int nByte; /* Size of open blob, in bytes */
  80127. int iOffset; /* Byte offset of blob in cursor data */
  80128. u16 iCol; /* Table column this handle is open on */
  80129. BtCursor *pCsr; /* Cursor pointing at blob row */
  80130. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  80131. sqlite3 *db; /* The associated database */
  80132. char *zDb; /* Database name */
  80133. Table *pTab; /* Table object */
  80134. };
  80135. /*
  80136. ** This function is used by both blob_open() and blob_reopen(). It seeks
  80137. ** the b-tree cursor associated with blob handle p to point to row iRow.
  80138. ** If successful, SQLITE_OK is returned and subsequent calls to
  80139. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  80140. **
  80141. ** If an error occurs, or if the specified row does not exist or does not
  80142. ** contain a value of type TEXT or BLOB in the column nominated when the
  80143. ** blob handle was opened, then an error code is returned and *pzErr may
  80144. ** be set to point to a buffer containing an error message. It is the
  80145. ** responsibility of the caller to free the error message buffer using
  80146. ** sqlite3DbFree().
  80147. **
  80148. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  80149. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  80150. ** immediately return SQLITE_ABORT.
  80151. */
  80152. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  80153. int rc; /* Error code */
  80154. char *zErr = 0; /* Error message */
  80155. Vdbe *v = (Vdbe *)p->pStmt;
  80156. /* Set the value of register r[1] in the SQL statement to integer iRow.
  80157. ** This is done directly as a performance optimization
  80158. */
  80159. v->aMem[1].flags = MEM_Int;
  80160. v->aMem[1].u.i = iRow;
  80161. /* If the statement has been run before (and is paused at the OP_ResultRow)
  80162. ** then back it up to the point where it does the OP_SeekRowid. This could
  80163. ** have been down with an extra OP_Goto, but simply setting the program
  80164. ** counter is faster. */
  80165. if( v->pc>3 ){
  80166. v->pc = 3;
  80167. rc = sqlite3VdbeExec(v);
  80168. }else{
  80169. rc = sqlite3_step(p->pStmt);
  80170. }
  80171. if( rc==SQLITE_ROW ){
  80172. VdbeCursor *pC = v->apCsr[0];
  80173. u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
  80174. testcase( pC->nHdrParsed==p->iCol );
  80175. testcase( pC->nHdrParsed==p->iCol+1 );
  80176. if( type<12 ){
  80177. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  80178. type==0?"null": type==7?"real": "integer"
  80179. );
  80180. rc = SQLITE_ERROR;
  80181. sqlite3_finalize(p->pStmt);
  80182. p->pStmt = 0;
  80183. }else{
  80184. p->iOffset = pC->aType[p->iCol + pC->nField];
  80185. p->nByte = sqlite3VdbeSerialTypeLen(type);
  80186. p->pCsr = pC->uc.pCursor;
  80187. sqlite3BtreeIncrblobCursor(p->pCsr);
  80188. }
  80189. }
  80190. if( rc==SQLITE_ROW ){
  80191. rc = SQLITE_OK;
  80192. }else if( p->pStmt ){
  80193. rc = sqlite3_finalize(p->pStmt);
  80194. p->pStmt = 0;
  80195. if( rc==SQLITE_OK ){
  80196. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  80197. rc = SQLITE_ERROR;
  80198. }else{
  80199. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  80200. }
  80201. }
  80202. assert( rc!=SQLITE_OK || zErr==0 );
  80203. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  80204. *pzErr = zErr;
  80205. return rc;
  80206. }
  80207. /*
  80208. ** Open a blob handle.
  80209. */
  80210. SQLITE_API int sqlite3_blob_open(
  80211. sqlite3* db, /* The database connection */
  80212. const char *zDb, /* The attached database containing the blob */
  80213. const char *zTable, /* The table containing the blob */
  80214. const char *zColumn, /* The column containing the blob */
  80215. sqlite_int64 iRow, /* The row containing the glob */
  80216. int wrFlag, /* True -> read/write access, false -> read-only */
  80217. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  80218. ){
  80219. int nAttempt = 0;
  80220. int iCol; /* Index of zColumn in row-record */
  80221. int rc = SQLITE_OK;
  80222. char *zErr = 0;
  80223. Table *pTab;
  80224. Parse *pParse = 0;
  80225. Incrblob *pBlob = 0;
  80226. #ifdef SQLITE_ENABLE_API_ARMOR
  80227. if( ppBlob==0 ){
  80228. return SQLITE_MISUSE_BKPT;
  80229. }
  80230. #endif
  80231. *ppBlob = 0;
  80232. #ifdef SQLITE_ENABLE_API_ARMOR
  80233. if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
  80234. return SQLITE_MISUSE_BKPT;
  80235. }
  80236. #endif
  80237. wrFlag = !!wrFlag; /* wrFlag = (wrFlag ? 1 : 0); */
  80238. sqlite3_mutex_enter(db->mutex);
  80239. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  80240. if( !pBlob ) goto blob_open_out;
  80241. pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
  80242. if( !pParse ) goto blob_open_out;
  80243. do {
  80244. memset(pParse, 0, sizeof(Parse));
  80245. pParse->db = db;
  80246. sqlite3DbFree(db, zErr);
  80247. zErr = 0;
  80248. sqlite3BtreeEnterAll(db);
  80249. pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
  80250. if( pTab && IsVirtual(pTab) ){
  80251. pTab = 0;
  80252. sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
  80253. }
  80254. if( pTab && !HasRowid(pTab) ){
  80255. pTab = 0;
  80256. sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
  80257. }
  80258. #ifndef SQLITE_OMIT_VIEW
  80259. if( pTab && pTab->pSelect ){
  80260. pTab = 0;
  80261. sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
  80262. }
  80263. #endif
  80264. if( !pTab ){
  80265. if( pParse->zErrMsg ){
  80266. sqlite3DbFree(db, zErr);
  80267. zErr = pParse->zErrMsg;
  80268. pParse->zErrMsg = 0;
  80269. }
  80270. rc = SQLITE_ERROR;
  80271. sqlite3BtreeLeaveAll(db);
  80272. goto blob_open_out;
  80273. }
  80274. pBlob->pTab = pTab;
  80275. pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
  80276. /* Now search pTab for the exact column. */
  80277. for(iCol=0; iCol<pTab->nCol; iCol++) {
  80278. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  80279. break;
  80280. }
  80281. }
  80282. if( iCol==pTab->nCol ){
  80283. sqlite3DbFree(db, zErr);
  80284. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  80285. rc = SQLITE_ERROR;
  80286. sqlite3BtreeLeaveAll(db);
  80287. goto blob_open_out;
  80288. }
  80289. /* If the value is being opened for writing, check that the
  80290. ** column is not indexed, and that it is not part of a foreign key.
  80291. */
  80292. if( wrFlag ){
  80293. const char *zFault = 0;
  80294. Index *pIdx;
  80295. #ifndef SQLITE_OMIT_FOREIGN_KEY
  80296. if( db->flags&SQLITE_ForeignKeys ){
  80297. /* Check that the column is not part of an FK child key definition. It
  80298. ** is not necessary to check if it is part of a parent key, as parent
  80299. ** key columns must be indexed. The check below will pick up this
  80300. ** case. */
  80301. FKey *pFKey;
  80302. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  80303. int j;
  80304. for(j=0; j<pFKey->nCol; j++){
  80305. if( pFKey->aCol[j].iFrom==iCol ){
  80306. zFault = "foreign key";
  80307. }
  80308. }
  80309. }
  80310. }
  80311. #endif
  80312. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  80313. int j;
  80314. for(j=0; j<pIdx->nKeyCol; j++){
  80315. /* FIXME: Be smarter about indexes that use expressions */
  80316. if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
  80317. zFault = "indexed";
  80318. }
  80319. }
  80320. }
  80321. if( zFault ){
  80322. sqlite3DbFree(db, zErr);
  80323. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  80324. rc = SQLITE_ERROR;
  80325. sqlite3BtreeLeaveAll(db);
  80326. goto blob_open_out;
  80327. }
  80328. }
  80329. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
  80330. assert( pBlob->pStmt || db->mallocFailed );
  80331. if( pBlob->pStmt ){
  80332. /* This VDBE program seeks a btree cursor to the identified
  80333. ** db/table/row entry. The reason for using a vdbe program instead
  80334. ** of writing code to use the b-tree layer directly is that the
  80335. ** vdbe program will take advantage of the various transaction,
  80336. ** locking and error handling infrastructure built into the vdbe.
  80337. **
  80338. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  80339. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  80340. ** uses it to implement the blob_read(), blob_write() and
  80341. ** blob_bytes() functions.
  80342. **
  80343. ** The sqlite3_blob_close() function finalizes the vdbe program,
  80344. ** which closes the b-tree cursor and (possibly) commits the
  80345. ** transaction.
  80346. */
  80347. static const int iLn = VDBE_OFFSET_LINENO(2);
  80348. static const VdbeOpList openBlob[] = {
  80349. {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */
  80350. {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */
  80351. /* blobSeekToRow() will initialize r[1] to the desired rowid */
  80352. {OP_NotExists, 0, 5, 1}, /* 2: Seek the cursor to rowid=r[1] */
  80353. {OP_Column, 0, 0, 1}, /* 3 */
  80354. {OP_ResultRow, 1, 0, 0}, /* 4 */
  80355. {OP_Halt, 0, 0, 0}, /* 5 */
  80356. };
  80357. Vdbe *v = (Vdbe *)pBlob->pStmt;
  80358. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  80359. VdbeOp *aOp;
  80360. sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,
  80361. pTab->pSchema->schema_cookie,
  80362. pTab->pSchema->iGeneration);
  80363. sqlite3VdbeChangeP5(v, 1);
  80364. aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
  80365. /* Make sure a mutex is held on the table to be accessed */
  80366. sqlite3VdbeUsesBtree(v, iDb);
  80367. if( db->mallocFailed==0 ){
  80368. assert( aOp!=0 );
  80369. /* Configure the OP_TableLock instruction */
  80370. #ifdef SQLITE_OMIT_SHARED_CACHE
  80371. aOp[0].opcode = OP_Noop;
  80372. #else
  80373. aOp[0].p1 = iDb;
  80374. aOp[0].p2 = pTab->tnum;
  80375. aOp[0].p3 = wrFlag;
  80376. sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
  80377. }
  80378. if( db->mallocFailed==0 ){
  80379. #endif
  80380. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  80381. ** parameter of the other to pTab->tnum. */
  80382. if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
  80383. aOp[1].p2 = pTab->tnum;
  80384. aOp[1].p3 = iDb;
  80385. /* Configure the number of columns. Configure the cursor to
  80386. ** think that the table has one more column than it really
  80387. ** does. An OP_Column to retrieve this imaginary column will
  80388. ** always return an SQL NULL. This is useful because it means
  80389. ** we can invoke OP_Column to fill in the vdbe cursors type
  80390. ** and offset cache without causing any IO.
  80391. */
  80392. aOp[1].p4type = P4_INT32;
  80393. aOp[1].p4.i = pTab->nCol+1;
  80394. aOp[3].p2 = pTab->nCol;
  80395. pParse->nVar = 0;
  80396. pParse->nMem = 1;
  80397. pParse->nTab = 1;
  80398. sqlite3VdbeMakeReady(v, pParse);
  80399. }
  80400. }
  80401. pBlob->iCol = iCol;
  80402. pBlob->db = db;
  80403. sqlite3BtreeLeaveAll(db);
  80404. if( db->mallocFailed ){
  80405. goto blob_open_out;
  80406. }
  80407. rc = blobSeekToRow(pBlob, iRow, &zErr);
  80408. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  80409. blob_open_out:
  80410. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  80411. *ppBlob = (sqlite3_blob *)pBlob;
  80412. }else{
  80413. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  80414. sqlite3DbFree(db, pBlob);
  80415. }
  80416. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  80417. sqlite3DbFree(db, zErr);
  80418. sqlite3ParserReset(pParse);
  80419. sqlite3StackFree(db, pParse);
  80420. rc = sqlite3ApiExit(db, rc);
  80421. sqlite3_mutex_leave(db->mutex);
  80422. return rc;
  80423. }
  80424. /*
  80425. ** Close a blob handle that was previously created using
  80426. ** sqlite3_blob_open().
  80427. */
  80428. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  80429. Incrblob *p = (Incrblob *)pBlob;
  80430. int rc;
  80431. sqlite3 *db;
  80432. if( p ){
  80433. db = p->db;
  80434. sqlite3_mutex_enter(db->mutex);
  80435. rc = sqlite3_finalize(p->pStmt);
  80436. sqlite3DbFree(db, p);
  80437. sqlite3_mutex_leave(db->mutex);
  80438. }else{
  80439. rc = SQLITE_OK;
  80440. }
  80441. return rc;
  80442. }
  80443. /*
  80444. ** Perform a read or write operation on a blob
  80445. */
  80446. static int blobReadWrite(
  80447. sqlite3_blob *pBlob,
  80448. void *z,
  80449. int n,
  80450. int iOffset,
  80451. int (*xCall)(BtCursor*, u32, u32, void*)
  80452. ){
  80453. int rc;
  80454. Incrblob *p = (Incrblob *)pBlob;
  80455. Vdbe *v;
  80456. sqlite3 *db;
  80457. if( p==0 ) return SQLITE_MISUSE_BKPT;
  80458. db = p->db;
  80459. sqlite3_mutex_enter(db->mutex);
  80460. v = (Vdbe*)p->pStmt;
  80461. if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
  80462. /* Request is out of range. Return a transient error. */
  80463. rc = SQLITE_ERROR;
  80464. }else if( v==0 ){
  80465. /* If there is no statement handle, then the blob-handle has
  80466. ** already been invalidated. Return SQLITE_ABORT in this case.
  80467. */
  80468. rc = SQLITE_ABORT;
  80469. }else{
  80470. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  80471. ** returned, clean-up the statement handle.
  80472. */
  80473. assert( db == v->db );
  80474. sqlite3BtreeEnterCursor(p->pCsr);
  80475. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  80476. if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
  80477. /* If a pre-update hook is registered and this is a write cursor,
  80478. ** invoke it here.
  80479. **
  80480. ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
  80481. ** operation should really be an SQLITE_UPDATE. This is probably
  80482. ** incorrect, but is convenient because at this point the new.* values
  80483. ** are not easily obtainable. And for the sessions module, an
  80484. ** SQLITE_UPDATE where the PK columns do not change is handled in the
  80485. ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
  80486. ** slightly more efficient). Since you cannot write to a PK column
  80487. ** using the incremental-blob API, this works. For the sessions module
  80488. ** anyhow.
  80489. */
  80490. sqlite3_int64 iKey;
  80491. iKey = sqlite3BtreeIntegerKey(p->pCsr);
  80492. sqlite3VdbePreUpdateHook(
  80493. v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
  80494. );
  80495. }
  80496. #endif
  80497. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  80498. sqlite3BtreeLeaveCursor(p->pCsr);
  80499. if( rc==SQLITE_ABORT ){
  80500. sqlite3VdbeFinalize(v);
  80501. p->pStmt = 0;
  80502. }else{
  80503. v->rc = rc;
  80504. }
  80505. }
  80506. sqlite3Error(db, rc);
  80507. rc = sqlite3ApiExit(db, rc);
  80508. sqlite3_mutex_leave(db->mutex);
  80509. return rc;
  80510. }
  80511. /*
  80512. ** Read data from a blob handle.
  80513. */
  80514. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  80515. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
  80516. }
  80517. /*
  80518. ** Write data to a blob handle.
  80519. */
  80520. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  80521. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  80522. }
  80523. /*
  80524. ** Query a blob handle for the size of the data.
  80525. **
  80526. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  80527. ** so no mutex is required for access.
  80528. */
  80529. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  80530. Incrblob *p = (Incrblob *)pBlob;
  80531. return (p && p->pStmt) ? p->nByte : 0;
  80532. }
  80533. /*
  80534. ** Move an existing blob handle to point to a different row of the same
  80535. ** database table.
  80536. **
  80537. ** If an error occurs, or if the specified row does not exist or does not
  80538. ** contain a blob or text value, then an error code is returned and the
  80539. ** database handle error code and message set. If this happens, then all
  80540. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  80541. ** immediately return SQLITE_ABORT.
  80542. */
  80543. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  80544. int rc;
  80545. Incrblob *p = (Incrblob *)pBlob;
  80546. sqlite3 *db;
  80547. if( p==0 ) return SQLITE_MISUSE_BKPT;
  80548. db = p->db;
  80549. sqlite3_mutex_enter(db->mutex);
  80550. if( p->pStmt==0 ){
  80551. /* If there is no statement handle, then the blob-handle has
  80552. ** already been invalidated. Return SQLITE_ABORT in this case.
  80553. */
  80554. rc = SQLITE_ABORT;
  80555. }else{
  80556. char *zErr;
  80557. rc = blobSeekToRow(p, iRow, &zErr);
  80558. if( rc!=SQLITE_OK ){
  80559. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  80560. sqlite3DbFree(db, zErr);
  80561. }
  80562. assert( rc!=SQLITE_SCHEMA );
  80563. }
  80564. rc = sqlite3ApiExit(db, rc);
  80565. assert( rc==SQLITE_OK || p->pStmt==0 );
  80566. sqlite3_mutex_leave(db->mutex);
  80567. return rc;
  80568. }
  80569. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  80570. /************** End of vdbeblob.c ********************************************/
  80571. /************** Begin file vdbesort.c ****************************************/
  80572. /*
  80573. ** 2011-07-09
  80574. **
  80575. ** The author disclaims copyright to this source code. In place of
  80576. ** a legal notice, here is a blessing:
  80577. **
  80578. ** May you do good and not evil.
  80579. ** May you find forgiveness for yourself and forgive others.
  80580. ** May you share freely, never taking more than you give.
  80581. **
  80582. *************************************************************************
  80583. ** This file contains code for the VdbeSorter object, used in concert with
  80584. ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
  80585. ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
  80586. ** using indexes and without LIMIT clauses.
  80587. **
  80588. ** The VdbeSorter object implements a multi-threaded external merge sort
  80589. ** algorithm that is efficient even if the number of elements being sorted
  80590. ** exceeds the available memory.
  80591. **
  80592. ** Here is the (internal, non-API) interface between this module and the
  80593. ** rest of the SQLite system:
  80594. **
  80595. ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
  80596. **
  80597. ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
  80598. ** object. The row is a binary blob in the
  80599. ** OP_MakeRecord format that contains both
  80600. ** the ORDER BY key columns and result columns
  80601. ** in the case of a SELECT w/ ORDER BY, or
  80602. ** the complete record for an index entry
  80603. ** in the case of a CREATE INDEX.
  80604. **
  80605. ** sqlite3VdbeSorterRewind() Sort all content previously added.
  80606. ** Position the read cursor on the
  80607. ** first sorted element.
  80608. **
  80609. ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
  80610. ** element.
  80611. **
  80612. ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
  80613. ** row currently under the read cursor.
  80614. **
  80615. ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
  80616. ** currently under the read cursor against
  80617. ** another binary blob X and report if
  80618. ** X is strictly less than the read cursor.
  80619. ** Used to enforce uniqueness in a
  80620. ** CREATE UNIQUE INDEX statement.
  80621. **
  80622. ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
  80623. ** all resources.
  80624. **
  80625. ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
  80626. ** is like Close() followed by Init() only
  80627. ** much faster.
  80628. **
  80629. ** The interfaces above must be called in a particular order. Write() can
  80630. ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
  80631. ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
  80632. **
  80633. ** Init()
  80634. ** for each record: Write()
  80635. ** Rewind()
  80636. ** Rowkey()/Compare()
  80637. ** Next()
  80638. ** Close()
  80639. **
  80640. ** Algorithm:
  80641. **
  80642. ** Records passed to the sorter via calls to Write() are initially held
  80643. ** unsorted in main memory. Assuming the amount of memory used never exceeds
  80644. ** a threshold, when Rewind() is called the set of records is sorted using
  80645. ** an in-memory merge sort. In this case, no temporary files are required
  80646. ** and subsequent calls to Rowkey(), Next() and Compare() read records
  80647. ** directly from main memory.
  80648. **
  80649. ** If the amount of space used to store records in main memory exceeds the
  80650. ** threshold, then the set of records currently in memory are sorted and
  80651. ** written to a temporary file in "Packed Memory Array" (PMA) format.
  80652. ** A PMA created at this point is known as a "level-0 PMA". Higher levels
  80653. ** of PMAs may be created by merging existing PMAs together - for example
  80654. ** merging two or more level-0 PMAs together creates a level-1 PMA.
  80655. **
  80656. ** The threshold for the amount of main memory to use before flushing
  80657. ** records to a PMA is roughly the same as the limit configured for the
  80658. ** page-cache of the main database. Specifically, the threshold is set to
  80659. ** the value returned by "PRAGMA main.page_size" multipled by
  80660. ** that returned by "PRAGMA main.cache_size", in bytes.
  80661. **
  80662. ** If the sorter is running in single-threaded mode, then all PMAs generated
  80663. ** are appended to a single temporary file. Or, if the sorter is running in
  80664. ** multi-threaded mode then up to (N+1) temporary files may be opened, where
  80665. ** N is the configured number of worker threads. In this case, instead of
  80666. ** sorting the records and writing the PMA to a temporary file itself, the
  80667. ** calling thread usually launches a worker thread to do so. Except, if
  80668. ** there are already N worker threads running, the main thread does the work
  80669. ** itself.
  80670. **
  80671. ** The sorter is running in multi-threaded mode if (a) the library was built
  80672. ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
  80673. ** than zero, and (b) worker threads have been enabled at runtime by calling
  80674. ** "PRAGMA threads=N" with some value of N greater than 0.
  80675. **
  80676. ** When Rewind() is called, any data remaining in memory is flushed to a
  80677. ** final PMA. So at this point the data is stored in some number of sorted
  80678. ** PMAs within temporary files on disk.
  80679. **
  80680. ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
  80681. ** sorter is running in single-threaded mode, then these PMAs are merged
  80682. ** incrementally as keys are retreived from the sorter by the VDBE. The
  80683. ** MergeEngine object, described in further detail below, performs this
  80684. ** merge.
  80685. **
  80686. ** Or, if running in multi-threaded mode, then a background thread is
  80687. ** launched to merge the existing PMAs. Once the background thread has
  80688. ** merged T bytes of data into a single sorted PMA, the main thread
  80689. ** begins reading keys from that PMA while the background thread proceeds
  80690. ** with merging the next T bytes of data. And so on.
  80691. **
  80692. ** Parameter T is set to half the value of the memory threshold used
  80693. ** by Write() above to determine when to create a new PMA.
  80694. **
  80695. ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
  80696. ** Rewind() is called, then a hierarchy of incremental-merges is used.
  80697. ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
  80698. ** disk are merged together. Then T bytes of data from the second set, and
  80699. ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
  80700. ** PMAs at a time. This done is to improve locality.
  80701. **
  80702. ** If running in multi-threaded mode and there are more than
  80703. ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
  80704. ** than one background thread may be created. Specifically, there may be
  80705. ** one background thread for each temporary file on disk, and one background
  80706. ** thread to merge the output of each of the others to a single PMA for
  80707. ** the main thread to read from.
  80708. */
  80709. /* #include "sqliteInt.h" */
  80710. /* #include "vdbeInt.h" */
  80711. /*
  80712. ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
  80713. ** messages to stderr that may be helpful in understanding the performance
  80714. ** characteristics of the sorter in multi-threaded mode.
  80715. */
  80716. #if 0
  80717. # define SQLITE_DEBUG_SORTER_THREADS 1
  80718. #endif
  80719. /*
  80720. ** Hard-coded maximum amount of data to accumulate in memory before flushing
  80721. ** to a level 0 PMA. The purpose of this limit is to prevent various integer
  80722. ** overflows. 512MiB.
  80723. */
  80724. #define SQLITE_MAX_PMASZ (1<<29)
  80725. /*
  80726. ** Private objects used by the sorter
  80727. */
  80728. typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
  80729. typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
  80730. typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
  80731. typedef struct SorterRecord SorterRecord; /* A record being sorted */
  80732. typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
  80733. typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
  80734. typedef struct SorterList SorterList; /* In-memory list of records */
  80735. typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
  80736. /*
  80737. ** A container for a temp file handle and the current amount of data
  80738. ** stored in the file.
  80739. */
  80740. struct SorterFile {
  80741. sqlite3_file *pFd; /* File handle */
  80742. i64 iEof; /* Bytes of data stored in pFd */
  80743. };
  80744. /*
  80745. ** An in-memory list of objects to be sorted.
  80746. **
  80747. ** If aMemory==0 then each object is allocated separately and the objects
  80748. ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
  80749. ** are stored in the aMemory[] bulk memory, one right after the other, and
  80750. ** are connected using SorterRecord.u.iNext.
  80751. */
  80752. struct SorterList {
  80753. SorterRecord *pList; /* Linked list of records */
  80754. u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
  80755. int szPMA; /* Size of pList as PMA in bytes */
  80756. };
  80757. /*
  80758. ** The MergeEngine object is used to combine two or more smaller PMAs into
  80759. ** one big PMA using a merge operation. Separate PMAs all need to be
  80760. ** combined into one big PMA in order to be able to step through the sorted
  80761. ** records in order.
  80762. **
  80763. ** The aReadr[] array contains a PmaReader object for each of the PMAs being
  80764. ** merged. An aReadr[] object either points to a valid key or else is at EOF.
  80765. ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
  80766. ** For the purposes of the paragraphs below, we assume that the array is
  80767. ** actually N elements in size, where N is the smallest power of 2 greater
  80768. ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
  80769. ** are treated as if they are empty (always at EOF).
  80770. **
  80771. ** The aTree[] array is also N elements in size. The value of N is stored in
  80772. ** the MergeEngine.nTree variable.
  80773. **
  80774. ** The final (N/2) elements of aTree[] contain the results of comparing
  80775. ** pairs of PMA keys together. Element i contains the result of
  80776. ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
  80777. ** aTree element is set to the index of it.
  80778. **
  80779. ** For the purposes of this comparison, EOF is considered greater than any
  80780. ** other key value. If the keys are equal (only possible with two EOF
  80781. ** values), it doesn't matter which index is stored.
  80782. **
  80783. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  80784. ** above contains the index of the smallest of each block of 4 PmaReaders
  80785. ** And so on. So that aTree[1] contains the index of the PmaReader that
  80786. ** currently points to the smallest key value. aTree[0] is unused.
  80787. **
  80788. ** Example:
  80789. **
  80790. ** aReadr[0] -> Banana
  80791. ** aReadr[1] -> Feijoa
  80792. ** aReadr[2] -> Elderberry
  80793. ** aReadr[3] -> Currant
  80794. ** aReadr[4] -> Grapefruit
  80795. ** aReadr[5] -> Apple
  80796. ** aReadr[6] -> Durian
  80797. ** aReadr[7] -> EOF
  80798. **
  80799. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  80800. **
  80801. ** The current element is "Apple" (the value of the key indicated by
  80802. ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
  80803. ** be advanced to the next key in its segment. Say the next key is
  80804. ** "Eggplant":
  80805. **
  80806. ** aReadr[5] -> Eggplant
  80807. **
  80808. ** The contents of aTree[] are updated first by comparing the new PmaReader
  80809. ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
  80810. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  80811. ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
  80812. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  80813. ** so the value written into element 1 of the array is 0. As follows:
  80814. **
  80815. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  80816. **
  80817. ** In other words, each time we advance to the next sorter element, log2(N)
  80818. ** key comparison operations are required, where N is the number of segments
  80819. ** being merged (rounded up to the next power of 2).
  80820. */
  80821. struct MergeEngine {
  80822. int nTree; /* Used size of aTree/aReadr (power of 2) */
  80823. SortSubtask *pTask; /* Used by this thread only */
  80824. int *aTree; /* Current state of incremental merge */
  80825. PmaReader *aReadr; /* Array of PmaReaders to merge data from */
  80826. };
  80827. /*
  80828. ** This object represents a single thread of control in a sort operation.
  80829. ** Exactly VdbeSorter.nTask instances of this object are allocated
  80830. ** as part of each VdbeSorter object. Instances are never allocated any
  80831. ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
  80832. ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
  80833. ** single-threaded operation, there is exactly one instance of this object
  80834. ** and for multi-threaded operation there are two or more instances.
  80835. **
  80836. ** Essentially, this structure contains all those fields of the VdbeSorter
  80837. ** structure for which each thread requires a separate instance. For example,
  80838. ** each thread requries its own UnpackedRecord object to unpack records in
  80839. ** as part of comparison operations.
  80840. **
  80841. ** Before a background thread is launched, variable bDone is set to 0. Then,
  80842. ** right before it exits, the thread itself sets bDone to 1. This is used for
  80843. ** two purposes:
  80844. **
  80845. ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
  80846. ** attempt to select a SortSubtask for which there is not already an
  80847. ** active background thread (since doing so causes the main thread
  80848. ** to block until it finishes).
  80849. **
  80850. ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
  80851. ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
  80852. ** block provoke debugging output.
  80853. **
  80854. ** In both cases, the effects of the main thread seeing (bDone==0) even
  80855. ** after the thread has finished are not dire. So we don't worry about
  80856. ** memory barriers and such here.
  80857. */
  80858. typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
  80859. struct SortSubtask {
  80860. SQLiteThread *pThread; /* Background thread, if any */
  80861. int bDone; /* Set if thread is finished but not joined */
  80862. VdbeSorter *pSorter; /* Sorter that owns this sub-task */
  80863. UnpackedRecord *pUnpacked; /* Space to unpack a record */
  80864. SorterList list; /* List for thread to write to a PMA */
  80865. int nPMA; /* Number of PMAs currently in file */
  80866. SorterCompare xCompare; /* Compare function to use */
  80867. SorterFile file; /* Temp file for level-0 PMAs */
  80868. SorterFile file2; /* Space for other PMAs */
  80869. };
  80870. /*
  80871. ** Main sorter structure. A single instance of this is allocated for each
  80872. ** sorter cursor created by the VDBE.
  80873. **
  80874. ** mxKeysize:
  80875. ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
  80876. ** this variable is updated so as to be set to the size on disk of the
  80877. ** largest record in the sorter.
  80878. */
  80879. struct VdbeSorter {
  80880. int mnPmaSize; /* Minimum PMA size, in bytes */
  80881. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  80882. int mxKeysize; /* Largest serialized key seen so far */
  80883. int pgsz; /* Main database page size */
  80884. PmaReader *pReader; /* Readr data from here after Rewind() */
  80885. MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
  80886. sqlite3 *db; /* Database connection */
  80887. KeyInfo *pKeyInfo; /* How to compare records */
  80888. UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
  80889. SorterList list; /* List of in-memory records */
  80890. int iMemory; /* Offset of free space in list.aMemory */
  80891. int nMemory; /* Size of list.aMemory allocation in bytes */
  80892. u8 bUsePMA; /* True if one or more PMAs created */
  80893. u8 bUseThreads; /* True to use background threads */
  80894. u8 iPrev; /* Previous thread used to flush PMA */
  80895. u8 nTask; /* Size of aTask[] array */
  80896. u8 typeMask;
  80897. SortSubtask aTask[1]; /* One or more subtasks */
  80898. };
  80899. #define SORTER_TYPE_INTEGER 0x01
  80900. #define SORTER_TYPE_TEXT 0x02
  80901. /*
  80902. ** An instance of the following object is used to read records out of a
  80903. ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
  80904. ** aKey might point into aMap or into aBuffer. If neither of those locations
  80905. ** contain a contiguous representation of the key, then aAlloc is allocated
  80906. ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
  80907. **
  80908. ** pFd==0 at EOF.
  80909. */
  80910. struct PmaReader {
  80911. i64 iReadOff; /* Current read offset */
  80912. i64 iEof; /* 1 byte past EOF for this PmaReader */
  80913. int nAlloc; /* Bytes of space at aAlloc */
  80914. int nKey; /* Number of bytes in key */
  80915. sqlite3_file *pFd; /* File handle we are reading from */
  80916. u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
  80917. u8 *aKey; /* Pointer to current key */
  80918. u8 *aBuffer; /* Current read buffer */
  80919. int nBuffer; /* Size of read buffer in bytes */
  80920. u8 *aMap; /* Pointer to mapping of entire file */
  80921. IncrMerger *pIncr; /* Incremental merger */
  80922. };
  80923. /*
  80924. ** Normally, a PmaReader object iterates through an existing PMA stored
  80925. ** within a temp file. However, if the PmaReader.pIncr variable points to
  80926. ** an object of the following type, it may be used to iterate/merge through
  80927. ** multiple PMAs simultaneously.
  80928. **
  80929. ** There are two types of IncrMerger object - single (bUseThread==0) and
  80930. ** multi-threaded (bUseThread==1).
  80931. **
  80932. ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
  80933. ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
  80934. ** size. When the IncrMerger is initialized, it reads enough data from
  80935. ** pMerger to populate aFile[0]. It then sets variables within the
  80936. ** corresponding PmaReader object to read from that file and kicks off
  80937. ** a background thread to populate aFile[1] with the next mxSz bytes of
  80938. ** sorted record data from pMerger.
  80939. **
  80940. ** When the PmaReader reaches the end of aFile[0], it blocks until the
  80941. ** background thread has finished populating aFile[1]. It then exchanges
  80942. ** the contents of the aFile[0] and aFile[1] variables within this structure,
  80943. ** sets the PmaReader fields to read from the new aFile[0] and kicks off
  80944. ** another background thread to populate the new aFile[1]. And so on, until
  80945. ** the contents of pMerger are exhausted.
  80946. **
  80947. ** A single-threaded IncrMerger does not open any temporary files of its
  80948. ** own. Instead, it has exclusive access to mxSz bytes of space beginning
  80949. ** at offset iStartOff of file pTask->file2. And instead of using a
  80950. ** background thread to prepare data for the PmaReader, with a single
  80951. ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
  80952. ** keys from pMerger by the calling thread whenever the PmaReader runs out
  80953. ** of data.
  80954. */
  80955. struct IncrMerger {
  80956. SortSubtask *pTask; /* Task that owns this merger */
  80957. MergeEngine *pMerger; /* Merge engine thread reads data from */
  80958. i64 iStartOff; /* Offset to start writing file at */
  80959. int mxSz; /* Maximum bytes of data to store */
  80960. int bEof; /* Set to true when merge is finished */
  80961. int bUseThread; /* True to use a bg thread for this object */
  80962. SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
  80963. };
  80964. /*
  80965. ** An instance of this object is used for writing a PMA.
  80966. **
  80967. ** The PMA is written one record at a time. Each record is of an arbitrary
  80968. ** size. But I/O is more efficient if it occurs in page-sized blocks where
  80969. ** each block is aligned on a page boundary. This object caches writes to
  80970. ** the PMA so that aligned, page-size blocks are written.
  80971. */
  80972. struct PmaWriter {
  80973. int eFWErr; /* Non-zero if in an error state */
  80974. u8 *aBuffer; /* Pointer to write buffer */
  80975. int nBuffer; /* Size of write buffer in bytes */
  80976. int iBufStart; /* First byte of buffer to write */
  80977. int iBufEnd; /* Last byte of buffer to write */
  80978. i64 iWriteOff; /* Offset of start of buffer in file */
  80979. sqlite3_file *pFd; /* File handle to write to */
  80980. };
  80981. /*
  80982. ** This object is the header on a single record while that record is being
  80983. ** held in memory and prior to being written out as part of a PMA.
  80984. **
  80985. ** How the linked list is connected depends on how memory is being managed
  80986. ** by this module. If using a separate allocation for each in-memory record
  80987. ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
  80988. ** SorterRecord.u.pNext pointers.
  80989. **
  80990. ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
  80991. ** then while records are being accumulated the list is linked using the
  80992. ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
  80993. ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
  80994. ** has finished passing records to the sorter, or when the in-memory buffer
  80995. ** is full, the list is sorted. As part of the sorting process, it is
  80996. ** converted to use the SorterRecord.u.pNext pointers. See function
  80997. ** vdbeSorterSort() for details.
  80998. */
  80999. struct SorterRecord {
  81000. int nVal; /* Size of the record in bytes */
  81001. union {
  81002. SorterRecord *pNext; /* Pointer to next record in list */
  81003. int iNext; /* Offset within aMemory of next record */
  81004. } u;
  81005. /* The data for the record immediately follows this header */
  81006. };
  81007. /* Return a pointer to the buffer containing the record data for SorterRecord
  81008. ** object p. Should be used as if:
  81009. **
  81010. ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
  81011. */
  81012. #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
  81013. /* Maximum number of PMAs that a single MergeEngine can merge */
  81014. #define SORTER_MAX_MERGE_COUNT 16
  81015. static int vdbeIncrSwap(IncrMerger*);
  81016. static void vdbeIncrFree(IncrMerger *);
  81017. /*
  81018. ** Free all memory belonging to the PmaReader object passed as the
  81019. ** argument. All structure fields are set to zero before returning.
  81020. */
  81021. static void vdbePmaReaderClear(PmaReader *pReadr){
  81022. sqlite3_free(pReadr->aAlloc);
  81023. sqlite3_free(pReadr->aBuffer);
  81024. if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  81025. vdbeIncrFree(pReadr->pIncr);
  81026. memset(pReadr, 0, sizeof(PmaReader));
  81027. }
  81028. /*
  81029. ** Read the next nByte bytes of data from the PMA p.
  81030. ** If successful, set *ppOut to point to a buffer containing the data
  81031. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  81032. ** error code.
  81033. **
  81034. ** The buffer returned in *ppOut is only valid until the
  81035. ** next call to this function.
  81036. */
  81037. static int vdbePmaReadBlob(
  81038. PmaReader *p, /* PmaReader from which to take the blob */
  81039. int nByte, /* Bytes of data to read */
  81040. u8 **ppOut /* OUT: Pointer to buffer containing data */
  81041. ){
  81042. int iBuf; /* Offset within buffer to read from */
  81043. int nAvail; /* Bytes of data available in buffer */
  81044. if( p->aMap ){
  81045. *ppOut = &p->aMap[p->iReadOff];
  81046. p->iReadOff += nByte;
  81047. return SQLITE_OK;
  81048. }
  81049. assert( p->aBuffer );
  81050. /* If there is no more data to be read from the buffer, read the next
  81051. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  81052. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  81053. iBuf = p->iReadOff % p->nBuffer;
  81054. if( iBuf==0 ){
  81055. int nRead; /* Bytes to read from disk */
  81056. int rc; /* sqlite3OsRead() return code */
  81057. /* Determine how many bytes of data to read. */
  81058. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  81059. nRead = p->nBuffer;
  81060. }else{
  81061. nRead = (int)(p->iEof - p->iReadOff);
  81062. }
  81063. assert( nRead>0 );
  81064. /* Readr data from the file. Return early if an error occurs. */
  81065. rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
  81066. assert( rc!=SQLITE_IOERR_SHORT_READ );
  81067. if( rc!=SQLITE_OK ) return rc;
  81068. }
  81069. nAvail = p->nBuffer - iBuf;
  81070. if( nByte<=nAvail ){
  81071. /* The requested data is available in the in-memory buffer. In this
  81072. ** case there is no need to make a copy of the data, just return a
  81073. ** pointer into the buffer to the caller. */
  81074. *ppOut = &p->aBuffer[iBuf];
  81075. p->iReadOff += nByte;
  81076. }else{
  81077. /* The requested data is not all available in the in-memory buffer.
  81078. ** In this case, allocate space at p->aAlloc[] to copy the requested
  81079. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  81080. int nRem; /* Bytes remaining to copy */
  81081. /* Extend the p->aAlloc[] allocation if required. */
  81082. if( p->nAlloc<nByte ){
  81083. u8 *aNew;
  81084. int nNew = MAX(128, p->nAlloc*2);
  81085. while( nByte>nNew ) nNew = nNew*2;
  81086. aNew = sqlite3Realloc(p->aAlloc, nNew);
  81087. if( !aNew ) return SQLITE_NOMEM_BKPT;
  81088. p->nAlloc = nNew;
  81089. p->aAlloc = aNew;
  81090. }
  81091. /* Copy as much data as is available in the buffer into the start of
  81092. ** p->aAlloc[]. */
  81093. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  81094. p->iReadOff += nAvail;
  81095. nRem = nByte - nAvail;
  81096. /* The following loop copies up to p->nBuffer bytes per iteration into
  81097. ** the p->aAlloc[] buffer. */
  81098. while( nRem>0 ){
  81099. int rc; /* vdbePmaReadBlob() return code */
  81100. int nCopy; /* Number of bytes to copy */
  81101. u8 *aNext; /* Pointer to buffer to copy data from */
  81102. nCopy = nRem;
  81103. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  81104. rc = vdbePmaReadBlob(p, nCopy, &aNext);
  81105. if( rc!=SQLITE_OK ) return rc;
  81106. assert( aNext!=p->aAlloc );
  81107. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  81108. nRem -= nCopy;
  81109. }
  81110. *ppOut = p->aAlloc;
  81111. }
  81112. return SQLITE_OK;
  81113. }
  81114. /*
  81115. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  81116. ** the value read.
  81117. */
  81118. static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
  81119. int iBuf;
  81120. if( p->aMap ){
  81121. p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
  81122. }else{
  81123. iBuf = p->iReadOff % p->nBuffer;
  81124. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  81125. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  81126. }else{
  81127. u8 aVarint[16], *a;
  81128. int i = 0, rc;
  81129. do{
  81130. rc = vdbePmaReadBlob(p, 1, &a);
  81131. if( rc ) return rc;
  81132. aVarint[(i++)&0xf] = a[0];
  81133. }while( (a[0]&0x80)!=0 );
  81134. sqlite3GetVarint(aVarint, pnOut);
  81135. }
  81136. }
  81137. return SQLITE_OK;
  81138. }
  81139. /*
  81140. ** Attempt to memory map file pFile. If successful, set *pp to point to the
  81141. ** new mapping and return SQLITE_OK. If the mapping is not attempted
  81142. ** (because the file is too large or the VFS layer is configured not to use
  81143. ** mmap), return SQLITE_OK and set *pp to NULL.
  81144. **
  81145. ** Or, if an error occurs, return an SQLite error code. The final value of
  81146. ** *pp is undefined in this case.
  81147. */
  81148. static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
  81149. int rc = SQLITE_OK;
  81150. if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
  81151. sqlite3_file *pFd = pFile->pFd;
  81152. if( pFd->pMethods->iVersion>=3 ){
  81153. rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
  81154. testcase( rc!=SQLITE_OK );
  81155. }
  81156. }
  81157. return rc;
  81158. }
  81159. /*
  81160. ** Attach PmaReader pReadr to file pFile (if it is not already attached to
  81161. ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
  81162. ** if successful, or an SQLite error code if an error occurs.
  81163. */
  81164. static int vdbePmaReaderSeek(
  81165. SortSubtask *pTask, /* Task context */
  81166. PmaReader *pReadr, /* Reader whose cursor is to be moved */
  81167. SorterFile *pFile, /* Sorter file to read from */
  81168. i64 iOff /* Offset in pFile */
  81169. ){
  81170. int rc = SQLITE_OK;
  81171. assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
  81172. if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
  81173. if( pReadr->aMap ){
  81174. sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  81175. pReadr->aMap = 0;
  81176. }
  81177. pReadr->iReadOff = iOff;
  81178. pReadr->iEof = pFile->iEof;
  81179. pReadr->pFd = pFile->pFd;
  81180. rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
  81181. if( rc==SQLITE_OK && pReadr->aMap==0 ){
  81182. int pgsz = pTask->pSorter->pgsz;
  81183. int iBuf = pReadr->iReadOff % pgsz;
  81184. if( pReadr->aBuffer==0 ){
  81185. pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
  81186. if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
  81187. pReadr->nBuffer = pgsz;
  81188. }
  81189. if( rc==SQLITE_OK && iBuf ){
  81190. int nRead = pgsz - iBuf;
  81191. if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
  81192. nRead = (int)(pReadr->iEof - pReadr->iReadOff);
  81193. }
  81194. rc = sqlite3OsRead(
  81195. pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
  81196. );
  81197. testcase( rc!=SQLITE_OK );
  81198. }
  81199. }
  81200. return rc;
  81201. }
  81202. /*
  81203. ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
  81204. ** no error occurs, or an SQLite error code if one does.
  81205. */
  81206. static int vdbePmaReaderNext(PmaReader *pReadr){
  81207. int rc = SQLITE_OK; /* Return Code */
  81208. u64 nRec = 0; /* Size of record in bytes */
  81209. if( pReadr->iReadOff>=pReadr->iEof ){
  81210. IncrMerger *pIncr = pReadr->pIncr;
  81211. int bEof = 1;
  81212. if( pIncr ){
  81213. rc = vdbeIncrSwap(pIncr);
  81214. if( rc==SQLITE_OK && pIncr->bEof==0 ){
  81215. rc = vdbePmaReaderSeek(
  81216. pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
  81217. );
  81218. bEof = 0;
  81219. }
  81220. }
  81221. if( bEof ){
  81222. /* This is an EOF condition */
  81223. vdbePmaReaderClear(pReadr);
  81224. testcase( rc!=SQLITE_OK );
  81225. return rc;
  81226. }
  81227. }
  81228. if( rc==SQLITE_OK ){
  81229. rc = vdbePmaReadVarint(pReadr, &nRec);
  81230. }
  81231. if( rc==SQLITE_OK ){
  81232. pReadr->nKey = (int)nRec;
  81233. rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
  81234. testcase( rc!=SQLITE_OK );
  81235. }
  81236. return rc;
  81237. }
  81238. /*
  81239. ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
  81240. ** starting at offset iStart and ending at offset iEof-1. This function
  81241. ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
  81242. ** PMA is empty).
  81243. **
  81244. ** If the pnByte parameter is NULL, then it is assumed that the file
  81245. ** contains a single PMA, and that that PMA omits the initial length varint.
  81246. */
  81247. static int vdbePmaReaderInit(
  81248. SortSubtask *pTask, /* Task context */
  81249. SorterFile *pFile, /* Sorter file to read from */
  81250. i64 iStart, /* Start offset in pFile */
  81251. PmaReader *pReadr, /* PmaReader to populate */
  81252. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  81253. ){
  81254. int rc;
  81255. assert( pFile->iEof>iStart );
  81256. assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
  81257. assert( pReadr->aBuffer==0 );
  81258. assert( pReadr->aMap==0 );
  81259. rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
  81260. if( rc==SQLITE_OK ){
  81261. u64 nByte = 0; /* Size of PMA in bytes */
  81262. rc = vdbePmaReadVarint(pReadr, &nByte);
  81263. pReadr->iEof = pReadr->iReadOff + nByte;
  81264. *pnByte += nByte;
  81265. }
  81266. if( rc==SQLITE_OK ){
  81267. rc = vdbePmaReaderNext(pReadr);
  81268. }
  81269. return rc;
  81270. }
  81271. /*
  81272. ** A version of vdbeSorterCompare() that assumes that it has already been
  81273. ** determined that the first field of key1 is equal to the first field of
  81274. ** key2.
  81275. */
  81276. static int vdbeSorterCompareTail(
  81277. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  81278. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  81279. const void *pKey1, int nKey1, /* Left side of comparison */
  81280. const void *pKey2, int nKey2 /* Right side of comparison */
  81281. ){
  81282. UnpackedRecord *r2 = pTask->pUnpacked;
  81283. if( *pbKey2Cached==0 ){
  81284. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  81285. *pbKey2Cached = 1;
  81286. }
  81287. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
  81288. }
  81289. /*
  81290. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  81291. ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
  81292. ** used by the comparison. Return the result of the comparison.
  81293. **
  81294. ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
  81295. ** it is assumed that (pTask->pUnpacked) contains the unpacked version
  81296. ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
  81297. ** version of key2 and *pbKey2Cached set to true before returning.
  81298. **
  81299. ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
  81300. ** to SQLITE_NOMEM.
  81301. */
  81302. static int vdbeSorterCompare(
  81303. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  81304. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  81305. const void *pKey1, int nKey1, /* Left side of comparison */
  81306. const void *pKey2, int nKey2 /* Right side of comparison */
  81307. ){
  81308. UnpackedRecord *r2 = pTask->pUnpacked;
  81309. if( !*pbKey2Cached ){
  81310. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  81311. *pbKey2Cached = 1;
  81312. }
  81313. return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  81314. }
  81315. /*
  81316. ** A specially optimized version of vdbeSorterCompare() that assumes that
  81317. ** the first field of each key is a TEXT value and that the collation
  81318. ** sequence to compare them with is BINARY.
  81319. */
  81320. static int vdbeSorterCompareText(
  81321. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  81322. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  81323. const void *pKey1, int nKey1, /* Left side of comparison */
  81324. const void *pKey2, int nKey2 /* Right side of comparison */
  81325. ){
  81326. const u8 * const p1 = (const u8 * const)pKey1;
  81327. const u8 * const p2 = (const u8 * const)pKey2;
  81328. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  81329. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  81330. int n1;
  81331. int n2;
  81332. int res;
  81333. getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2;
  81334. getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2;
  81335. res = memcmp(v1, v2, MIN(n1, n2));
  81336. if( res==0 ){
  81337. res = n1 - n2;
  81338. }
  81339. if( res==0 ){
  81340. if( pTask->pSorter->pKeyInfo->nField>1 ){
  81341. res = vdbeSorterCompareTail(
  81342. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  81343. );
  81344. }
  81345. }else{
  81346. if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  81347. res = res * -1;
  81348. }
  81349. }
  81350. return res;
  81351. }
  81352. /*
  81353. ** A specially optimized version of vdbeSorterCompare() that assumes that
  81354. ** the first field of each key is an INTEGER value.
  81355. */
  81356. static int vdbeSorterCompareInt(
  81357. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  81358. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  81359. const void *pKey1, int nKey1, /* Left side of comparison */
  81360. const void *pKey2, int nKey2 /* Right side of comparison */
  81361. ){
  81362. const u8 * const p1 = (const u8 * const)pKey1;
  81363. const u8 * const p2 = (const u8 * const)pKey2;
  81364. const int s1 = p1[1]; /* Left hand serial type */
  81365. const int s2 = p2[1]; /* Right hand serial type */
  81366. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  81367. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  81368. int res; /* Return value */
  81369. assert( (s1>0 && s1<7) || s1==8 || s1==9 );
  81370. assert( (s2>0 && s2<7) || s2==8 || s2==9 );
  81371. if( s1==s2 ){
  81372. /* The two values have the same sign. Compare using memcmp(). */
  81373. static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 };
  81374. const u8 n = aLen[s1];
  81375. int i;
  81376. res = 0;
  81377. for(i=0; i<n; i++){
  81378. if( (res = v1[i] - v2[i])!=0 ){
  81379. if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){
  81380. res = v1[0] & 0x80 ? -1 : +1;
  81381. }
  81382. break;
  81383. }
  81384. }
  81385. }else if( s1>7 && s2>7 ){
  81386. res = s1 - s2;
  81387. }else{
  81388. if( s2>7 ){
  81389. res = +1;
  81390. }else if( s1>7 ){
  81391. res = -1;
  81392. }else{
  81393. res = s1 - s2;
  81394. }
  81395. assert( res!=0 );
  81396. if( res>0 ){
  81397. if( *v1 & 0x80 ) res = -1;
  81398. }else{
  81399. if( *v2 & 0x80 ) res = +1;
  81400. }
  81401. }
  81402. if( res==0 ){
  81403. if( pTask->pSorter->pKeyInfo->nField>1 ){
  81404. res = vdbeSorterCompareTail(
  81405. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  81406. );
  81407. }
  81408. }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  81409. res = res * -1;
  81410. }
  81411. return res;
  81412. }
  81413. /*
  81414. ** Initialize the temporary index cursor just opened as a sorter cursor.
  81415. **
  81416. ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
  81417. ** to determine the number of fields that should be compared from the
  81418. ** records being sorted. However, if the value passed as argument nField
  81419. ** is non-zero and the sorter is able to guarantee a stable sort, nField
  81420. ** is used instead. This is used when sorting records for a CREATE INDEX
  81421. ** statement. In this case, keys are always delivered to the sorter in
  81422. ** order of the primary key, which happens to be make up the final part
  81423. ** of the records being sorted. So if the sort is stable, there is never
  81424. ** any reason to compare PK fields and they can be ignored for a small
  81425. ** performance boost.
  81426. **
  81427. ** The sorter can guarantee a stable sort when running in single-threaded
  81428. ** mode, but not in multi-threaded mode.
  81429. **
  81430. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  81431. */
  81432. SQLITE_PRIVATE int sqlite3VdbeSorterInit(
  81433. sqlite3 *db, /* Database connection (for malloc()) */
  81434. int nField, /* Number of key fields in each record */
  81435. VdbeCursor *pCsr /* Cursor that holds the new sorter */
  81436. ){
  81437. int pgsz; /* Page size of main database */
  81438. int i; /* Used to iterate through aTask[] */
  81439. VdbeSorter *pSorter; /* The new sorter */
  81440. KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
  81441. int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
  81442. int sz; /* Size of pSorter in bytes */
  81443. int rc = SQLITE_OK;
  81444. #if SQLITE_MAX_WORKER_THREADS==0
  81445. # define nWorker 0
  81446. #else
  81447. int nWorker;
  81448. #endif
  81449. /* Initialize the upper limit on the number of worker threads */
  81450. #if SQLITE_MAX_WORKER_THREADS>0
  81451. if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
  81452. nWorker = 0;
  81453. }else{
  81454. nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
  81455. }
  81456. #endif
  81457. /* Do not allow the total number of threads (main thread + all workers)
  81458. ** to exceed the maximum merge count */
  81459. #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
  81460. if( nWorker>=SORTER_MAX_MERGE_COUNT ){
  81461. nWorker = SORTER_MAX_MERGE_COUNT-1;
  81462. }
  81463. #endif
  81464. assert( pCsr->pKeyInfo && pCsr->pBtx==0 );
  81465. assert( pCsr->eCurType==CURTYPE_SORTER );
  81466. szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
  81467. sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
  81468. pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
  81469. pCsr->uc.pSorter = pSorter;
  81470. if( pSorter==0 ){
  81471. rc = SQLITE_NOMEM_BKPT;
  81472. }else{
  81473. pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
  81474. memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
  81475. pKeyInfo->db = 0;
  81476. if( nField && nWorker==0 ){
  81477. pKeyInfo->nXField += (pKeyInfo->nField - nField);
  81478. pKeyInfo->nField = nField;
  81479. }
  81480. pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  81481. pSorter->nTask = nWorker + 1;
  81482. pSorter->iPrev = (u8)(nWorker - 1);
  81483. pSorter->bUseThreads = (pSorter->nTask>1);
  81484. pSorter->db = db;
  81485. for(i=0; i<pSorter->nTask; i++){
  81486. SortSubtask *pTask = &pSorter->aTask[i];
  81487. pTask->pSorter = pSorter;
  81488. }
  81489. if( !sqlite3TempInMemory(db) ){
  81490. i64 mxCache; /* Cache size in bytes*/
  81491. u32 szPma = sqlite3GlobalConfig.szPma;
  81492. pSorter->mnPmaSize = szPma * pgsz;
  81493. mxCache = db->aDb[0].pSchema->cache_size;
  81494. if( mxCache<0 ){
  81495. /* A negative cache-size value C indicates that the cache is abs(C)
  81496. ** KiB in size. */
  81497. mxCache = mxCache * -1024;
  81498. }else{
  81499. mxCache = mxCache * pgsz;
  81500. }
  81501. mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
  81502. pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
  81503. /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
  81504. ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
  81505. ** large heap allocations.
  81506. */
  81507. if( sqlite3GlobalConfig.pScratch==0 ){
  81508. assert( pSorter->iMemory==0 );
  81509. pSorter->nMemory = pgsz;
  81510. pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
  81511. if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
  81512. }
  81513. }
  81514. if( (pKeyInfo->nField+pKeyInfo->nXField)<13
  81515. && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
  81516. ){
  81517. pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
  81518. }
  81519. }
  81520. return rc;
  81521. }
  81522. #undef nWorker /* Defined at the top of this function */
  81523. /*
  81524. ** Free the list of sorted records starting at pRecord.
  81525. */
  81526. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  81527. SorterRecord *p;
  81528. SorterRecord *pNext;
  81529. for(p=pRecord; p; p=pNext){
  81530. pNext = p->u.pNext;
  81531. sqlite3DbFree(db, p);
  81532. }
  81533. }
  81534. /*
  81535. ** Free all resources owned by the object indicated by argument pTask. All
  81536. ** fields of *pTask are zeroed before returning.
  81537. */
  81538. static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
  81539. sqlite3DbFree(db, pTask->pUnpacked);
  81540. #if SQLITE_MAX_WORKER_THREADS>0
  81541. /* pTask->list.aMemory can only be non-zero if it was handed memory
  81542. ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
  81543. if( pTask->list.aMemory ){
  81544. sqlite3_free(pTask->list.aMemory);
  81545. }else
  81546. #endif
  81547. {
  81548. assert( pTask->list.aMemory==0 );
  81549. vdbeSorterRecordFree(0, pTask->list.pList);
  81550. }
  81551. if( pTask->file.pFd ){
  81552. sqlite3OsCloseFree(pTask->file.pFd);
  81553. }
  81554. if( pTask->file2.pFd ){
  81555. sqlite3OsCloseFree(pTask->file2.pFd);
  81556. }
  81557. memset(pTask, 0, sizeof(SortSubtask));
  81558. }
  81559. #ifdef SQLITE_DEBUG_SORTER_THREADS
  81560. static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
  81561. i64 t;
  81562. int iTask = (pTask - pTask->pSorter->aTask);
  81563. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  81564. fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
  81565. }
  81566. static void vdbeSorterRewindDebug(const char *zEvent){
  81567. i64 t;
  81568. sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
  81569. fprintf(stderr, "%lld:X %s\n", t, zEvent);
  81570. }
  81571. static void vdbeSorterPopulateDebug(
  81572. SortSubtask *pTask,
  81573. const char *zEvent
  81574. ){
  81575. i64 t;
  81576. int iTask = (pTask - pTask->pSorter->aTask);
  81577. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  81578. fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
  81579. }
  81580. static void vdbeSorterBlockDebug(
  81581. SortSubtask *pTask,
  81582. int bBlocked,
  81583. const char *zEvent
  81584. ){
  81585. if( bBlocked ){
  81586. i64 t;
  81587. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  81588. fprintf(stderr, "%lld:main %s\n", t, zEvent);
  81589. }
  81590. }
  81591. #else
  81592. # define vdbeSorterWorkDebug(x,y)
  81593. # define vdbeSorterRewindDebug(y)
  81594. # define vdbeSorterPopulateDebug(x,y)
  81595. # define vdbeSorterBlockDebug(x,y,z)
  81596. #endif
  81597. #if SQLITE_MAX_WORKER_THREADS>0
  81598. /*
  81599. ** Join thread pTask->thread.
  81600. */
  81601. static int vdbeSorterJoinThread(SortSubtask *pTask){
  81602. int rc = SQLITE_OK;
  81603. if( pTask->pThread ){
  81604. #ifdef SQLITE_DEBUG_SORTER_THREADS
  81605. int bDone = pTask->bDone;
  81606. #endif
  81607. void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
  81608. vdbeSorterBlockDebug(pTask, !bDone, "enter");
  81609. (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
  81610. vdbeSorterBlockDebug(pTask, !bDone, "exit");
  81611. rc = SQLITE_PTR_TO_INT(pRet);
  81612. assert( pTask->bDone==1 );
  81613. pTask->bDone = 0;
  81614. pTask->pThread = 0;
  81615. }
  81616. return rc;
  81617. }
  81618. /*
  81619. ** Launch a background thread to run xTask(pIn).
  81620. */
  81621. static int vdbeSorterCreateThread(
  81622. SortSubtask *pTask, /* Thread will use this task object */
  81623. void *(*xTask)(void*), /* Routine to run in a separate thread */
  81624. void *pIn /* Argument passed into xTask() */
  81625. ){
  81626. assert( pTask->pThread==0 && pTask->bDone==0 );
  81627. return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
  81628. }
  81629. /*
  81630. ** Join all outstanding threads launched by SorterWrite() to create
  81631. ** level-0 PMAs.
  81632. */
  81633. static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
  81634. int rc = rcin;
  81635. int i;
  81636. /* This function is always called by the main user thread.
  81637. **
  81638. ** If this function is being called after SorterRewind() has been called,
  81639. ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
  81640. ** is currently attempt to join one of the other threads. To avoid a race
  81641. ** condition where this thread also attempts to join the same object, join
  81642. ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
  81643. for(i=pSorter->nTask-1; i>=0; i--){
  81644. SortSubtask *pTask = &pSorter->aTask[i];
  81645. int rc2 = vdbeSorterJoinThread(pTask);
  81646. if( rc==SQLITE_OK ) rc = rc2;
  81647. }
  81648. return rc;
  81649. }
  81650. #else
  81651. # define vdbeSorterJoinAll(x,rcin) (rcin)
  81652. # define vdbeSorterJoinThread(pTask) SQLITE_OK
  81653. #endif
  81654. /*
  81655. ** Allocate a new MergeEngine object capable of handling up to
  81656. ** nReader PmaReader inputs.
  81657. **
  81658. ** nReader is automatically rounded up to the next power of two.
  81659. ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
  81660. */
  81661. static MergeEngine *vdbeMergeEngineNew(int nReader){
  81662. int N = 2; /* Smallest power of two >= nReader */
  81663. int nByte; /* Total bytes of space to allocate */
  81664. MergeEngine *pNew; /* Pointer to allocated object to return */
  81665. assert( nReader<=SORTER_MAX_MERGE_COUNT );
  81666. while( N<nReader ) N += N;
  81667. nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
  81668. pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
  81669. if( pNew ){
  81670. pNew->nTree = N;
  81671. pNew->pTask = 0;
  81672. pNew->aReadr = (PmaReader*)&pNew[1];
  81673. pNew->aTree = (int*)&pNew->aReadr[N];
  81674. }
  81675. return pNew;
  81676. }
  81677. /*
  81678. ** Free the MergeEngine object passed as the only argument.
  81679. */
  81680. static void vdbeMergeEngineFree(MergeEngine *pMerger){
  81681. int i;
  81682. if( pMerger ){
  81683. for(i=0; i<pMerger->nTree; i++){
  81684. vdbePmaReaderClear(&pMerger->aReadr[i]);
  81685. }
  81686. }
  81687. sqlite3_free(pMerger);
  81688. }
  81689. /*
  81690. ** Free all resources associated with the IncrMerger object indicated by
  81691. ** the first argument.
  81692. */
  81693. static void vdbeIncrFree(IncrMerger *pIncr){
  81694. if( pIncr ){
  81695. #if SQLITE_MAX_WORKER_THREADS>0
  81696. if( pIncr->bUseThread ){
  81697. vdbeSorterJoinThread(pIncr->pTask);
  81698. if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
  81699. if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
  81700. }
  81701. #endif
  81702. vdbeMergeEngineFree(pIncr->pMerger);
  81703. sqlite3_free(pIncr);
  81704. }
  81705. }
  81706. /*
  81707. ** Reset a sorting cursor back to its original empty state.
  81708. */
  81709. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
  81710. int i;
  81711. (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
  81712. assert( pSorter->bUseThreads || pSorter->pReader==0 );
  81713. #if SQLITE_MAX_WORKER_THREADS>0
  81714. if( pSorter->pReader ){
  81715. vdbePmaReaderClear(pSorter->pReader);
  81716. sqlite3DbFree(db, pSorter->pReader);
  81717. pSorter->pReader = 0;
  81718. }
  81719. #endif
  81720. vdbeMergeEngineFree(pSorter->pMerger);
  81721. pSorter->pMerger = 0;
  81722. for(i=0; i<pSorter->nTask; i++){
  81723. SortSubtask *pTask = &pSorter->aTask[i];
  81724. vdbeSortSubtaskCleanup(db, pTask);
  81725. pTask->pSorter = pSorter;
  81726. }
  81727. if( pSorter->list.aMemory==0 ){
  81728. vdbeSorterRecordFree(0, pSorter->list.pList);
  81729. }
  81730. pSorter->list.pList = 0;
  81731. pSorter->list.szPMA = 0;
  81732. pSorter->bUsePMA = 0;
  81733. pSorter->iMemory = 0;
  81734. pSorter->mxKeysize = 0;
  81735. sqlite3DbFree(db, pSorter->pUnpacked);
  81736. pSorter->pUnpacked = 0;
  81737. }
  81738. /*
  81739. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  81740. */
  81741. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  81742. VdbeSorter *pSorter;
  81743. assert( pCsr->eCurType==CURTYPE_SORTER );
  81744. pSorter = pCsr->uc.pSorter;
  81745. if( pSorter ){
  81746. sqlite3VdbeSorterReset(db, pSorter);
  81747. sqlite3_free(pSorter->list.aMemory);
  81748. sqlite3DbFree(db, pSorter);
  81749. pCsr->uc.pSorter = 0;
  81750. }
  81751. }
  81752. #if SQLITE_MAX_MMAP_SIZE>0
  81753. /*
  81754. ** The first argument is a file-handle open on a temporary file. The file
  81755. ** is guaranteed to be nByte bytes or smaller in size. This function
  81756. ** attempts to extend the file to nByte bytes in size and to ensure that
  81757. ** the VFS has memory mapped it.
  81758. **
  81759. ** Whether or not the file does end up memory mapped of course depends on
  81760. ** the specific VFS implementation.
  81761. */
  81762. static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
  81763. if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
  81764. void *p = 0;
  81765. int chunksize = 4*1024;
  81766. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
  81767. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
  81768. sqlite3OsFetch(pFd, 0, (int)nByte, &p);
  81769. sqlite3OsUnfetch(pFd, 0, p);
  81770. }
  81771. }
  81772. #else
  81773. # define vdbeSorterExtendFile(x,y,z)
  81774. #endif
  81775. /*
  81776. ** Allocate space for a file-handle and open a temporary file. If successful,
  81777. ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
  81778. ** Otherwise, set *ppFd to 0 and return an SQLite error code.
  81779. */
  81780. static int vdbeSorterOpenTempFile(
  81781. sqlite3 *db, /* Database handle doing sort */
  81782. i64 nExtend, /* Attempt to extend file to this size */
  81783. sqlite3_file **ppFd
  81784. ){
  81785. int rc;
  81786. if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
  81787. rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
  81788. SQLITE_OPEN_TEMP_JOURNAL |
  81789. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  81790. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
  81791. );
  81792. if( rc==SQLITE_OK ){
  81793. i64 max = SQLITE_MAX_MMAP_SIZE;
  81794. sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
  81795. if( nExtend>0 ){
  81796. vdbeSorterExtendFile(db, *ppFd, nExtend);
  81797. }
  81798. }
  81799. return rc;
  81800. }
  81801. /*
  81802. ** If it has not already been allocated, allocate the UnpackedRecord
  81803. ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
  81804. ** if no allocation was required), or SQLITE_NOMEM otherwise.
  81805. */
  81806. static int vdbeSortAllocUnpacked(SortSubtask *pTask){
  81807. if( pTask->pUnpacked==0 ){
  81808. pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
  81809. if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
  81810. pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
  81811. pTask->pUnpacked->errCode = 0;
  81812. }
  81813. return SQLITE_OK;
  81814. }
  81815. /*
  81816. ** Merge the two sorted lists p1 and p2 into a single list.
  81817. */
  81818. static SorterRecord *vdbeSorterMerge(
  81819. SortSubtask *pTask, /* Calling thread context */
  81820. SorterRecord *p1, /* First list to merge */
  81821. SorterRecord *p2 /* Second list to merge */
  81822. ){
  81823. SorterRecord *pFinal = 0;
  81824. SorterRecord **pp = &pFinal;
  81825. int bCached = 0;
  81826. assert( p1!=0 && p2!=0 );
  81827. for(;;){
  81828. int res;
  81829. res = pTask->xCompare(
  81830. pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
  81831. );
  81832. if( res<=0 ){
  81833. *pp = p1;
  81834. pp = &p1->u.pNext;
  81835. p1 = p1->u.pNext;
  81836. if( p1==0 ){
  81837. *pp = p2;
  81838. break;
  81839. }
  81840. }else{
  81841. *pp = p2;
  81842. pp = &p2->u.pNext;
  81843. p2 = p2->u.pNext;
  81844. bCached = 0;
  81845. if( p2==0 ){
  81846. *pp = p1;
  81847. break;
  81848. }
  81849. }
  81850. }
  81851. return pFinal;
  81852. }
  81853. /*
  81854. ** Return the SorterCompare function to compare values collected by the
  81855. ** sorter object passed as the only argument.
  81856. */
  81857. static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
  81858. if( p->typeMask==SORTER_TYPE_INTEGER ){
  81859. return vdbeSorterCompareInt;
  81860. }else if( p->typeMask==SORTER_TYPE_TEXT ){
  81861. return vdbeSorterCompareText;
  81862. }
  81863. return vdbeSorterCompare;
  81864. }
  81865. /*
  81866. ** Sort the linked list of records headed at pTask->pList. Return
  81867. ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
  81868. ** an error occurs.
  81869. */
  81870. static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
  81871. int i;
  81872. SorterRecord **aSlot;
  81873. SorterRecord *p;
  81874. int rc;
  81875. rc = vdbeSortAllocUnpacked(pTask);
  81876. if( rc!=SQLITE_OK ) return rc;
  81877. p = pList->pList;
  81878. pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
  81879. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  81880. if( !aSlot ){
  81881. return SQLITE_NOMEM_BKPT;
  81882. }
  81883. while( p ){
  81884. SorterRecord *pNext;
  81885. if( pList->aMemory ){
  81886. if( (u8*)p==pList->aMemory ){
  81887. pNext = 0;
  81888. }else{
  81889. assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
  81890. pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
  81891. }
  81892. }else{
  81893. pNext = p->u.pNext;
  81894. }
  81895. p->u.pNext = 0;
  81896. for(i=0; aSlot[i]; i++){
  81897. p = vdbeSorterMerge(pTask, p, aSlot[i]);
  81898. aSlot[i] = 0;
  81899. }
  81900. aSlot[i] = p;
  81901. p = pNext;
  81902. }
  81903. p = 0;
  81904. for(i=0; i<64; i++){
  81905. if( aSlot[i]==0 ) continue;
  81906. p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
  81907. }
  81908. pList->pList = p;
  81909. sqlite3_free(aSlot);
  81910. assert( pTask->pUnpacked->errCode==SQLITE_OK
  81911. || pTask->pUnpacked->errCode==SQLITE_NOMEM
  81912. );
  81913. return pTask->pUnpacked->errCode;
  81914. }
  81915. /*
  81916. ** Initialize a PMA-writer object.
  81917. */
  81918. static void vdbePmaWriterInit(
  81919. sqlite3_file *pFd, /* File handle to write to */
  81920. PmaWriter *p, /* Object to populate */
  81921. int nBuf, /* Buffer size */
  81922. i64 iStart /* Offset of pFd to begin writing at */
  81923. ){
  81924. memset(p, 0, sizeof(PmaWriter));
  81925. p->aBuffer = (u8*)sqlite3Malloc(nBuf);
  81926. if( !p->aBuffer ){
  81927. p->eFWErr = SQLITE_NOMEM_BKPT;
  81928. }else{
  81929. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  81930. p->iWriteOff = iStart - p->iBufStart;
  81931. p->nBuffer = nBuf;
  81932. p->pFd = pFd;
  81933. }
  81934. }
  81935. /*
  81936. ** Write nData bytes of data to the PMA. Return SQLITE_OK
  81937. ** if successful, or an SQLite error code if an error occurs.
  81938. */
  81939. static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
  81940. int nRem = nData;
  81941. while( nRem>0 && p->eFWErr==0 ){
  81942. int nCopy = nRem;
  81943. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  81944. nCopy = p->nBuffer - p->iBufEnd;
  81945. }
  81946. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  81947. p->iBufEnd += nCopy;
  81948. if( p->iBufEnd==p->nBuffer ){
  81949. p->eFWErr = sqlite3OsWrite(p->pFd,
  81950. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  81951. p->iWriteOff + p->iBufStart
  81952. );
  81953. p->iBufStart = p->iBufEnd = 0;
  81954. p->iWriteOff += p->nBuffer;
  81955. }
  81956. assert( p->iBufEnd<p->nBuffer );
  81957. nRem -= nCopy;
  81958. }
  81959. }
  81960. /*
  81961. ** Flush any buffered data to disk and clean up the PMA-writer object.
  81962. ** The results of using the PMA-writer after this call are undefined.
  81963. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  81964. ** required. Otherwise, return an SQLite error code.
  81965. **
  81966. ** Before returning, set *piEof to the offset immediately following the
  81967. ** last byte written to the file.
  81968. */
  81969. static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
  81970. int rc;
  81971. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  81972. p->eFWErr = sqlite3OsWrite(p->pFd,
  81973. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  81974. p->iWriteOff + p->iBufStart
  81975. );
  81976. }
  81977. *piEof = (p->iWriteOff + p->iBufEnd);
  81978. sqlite3_free(p->aBuffer);
  81979. rc = p->eFWErr;
  81980. memset(p, 0, sizeof(PmaWriter));
  81981. return rc;
  81982. }
  81983. /*
  81984. ** Write value iVal encoded as a varint to the PMA. Return
  81985. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  81986. */
  81987. static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
  81988. int nByte;
  81989. u8 aByte[10];
  81990. nByte = sqlite3PutVarint(aByte, iVal);
  81991. vdbePmaWriteBlob(p, aByte, nByte);
  81992. }
  81993. /*
  81994. ** Write the current contents of in-memory linked-list pList to a level-0
  81995. ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
  81996. ** successful, or an SQLite error code otherwise.
  81997. **
  81998. ** The format of a PMA is:
  81999. **
  82000. ** * A varint. This varint contains the total number of bytes of content
  82001. ** in the PMA (not including the varint itself).
  82002. **
  82003. ** * One or more records packed end-to-end in order of ascending keys.
  82004. ** Each record consists of a varint followed by a blob of data (the
  82005. ** key). The varint is the number of bytes in the blob of data.
  82006. */
  82007. static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
  82008. sqlite3 *db = pTask->pSorter->db;
  82009. int rc = SQLITE_OK; /* Return code */
  82010. PmaWriter writer; /* Object used to write to the file */
  82011. #ifdef SQLITE_DEBUG
  82012. /* Set iSz to the expected size of file pTask->file after writing the PMA.
  82013. ** This is used by an assert() statement at the end of this function. */
  82014. i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
  82015. #endif
  82016. vdbeSorterWorkDebug(pTask, "enter");
  82017. memset(&writer, 0, sizeof(PmaWriter));
  82018. assert( pList->szPMA>0 );
  82019. /* If the first temporary PMA file has not been opened, open it now. */
  82020. if( pTask->file.pFd==0 ){
  82021. rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
  82022. assert( rc!=SQLITE_OK || pTask->file.pFd );
  82023. assert( pTask->file.iEof==0 );
  82024. assert( pTask->nPMA==0 );
  82025. }
  82026. /* Try to get the file to memory map */
  82027. if( rc==SQLITE_OK ){
  82028. vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
  82029. }
  82030. /* Sort the list */
  82031. if( rc==SQLITE_OK ){
  82032. rc = vdbeSorterSort(pTask, pList);
  82033. }
  82034. if( rc==SQLITE_OK ){
  82035. SorterRecord *p;
  82036. SorterRecord *pNext = 0;
  82037. vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
  82038. pTask->file.iEof);
  82039. pTask->nPMA++;
  82040. vdbePmaWriteVarint(&writer, pList->szPMA);
  82041. for(p=pList->pList; p; p=pNext){
  82042. pNext = p->u.pNext;
  82043. vdbePmaWriteVarint(&writer, p->nVal);
  82044. vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
  82045. if( pList->aMemory==0 ) sqlite3_free(p);
  82046. }
  82047. pList->pList = p;
  82048. rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
  82049. }
  82050. vdbeSorterWorkDebug(pTask, "exit");
  82051. assert( rc!=SQLITE_OK || pList->pList==0 );
  82052. assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
  82053. return rc;
  82054. }
  82055. /*
  82056. ** Advance the MergeEngine to its next entry.
  82057. ** Set *pbEof to true there is no next entry because
  82058. ** the MergeEngine has reached the end of all its inputs.
  82059. **
  82060. ** Return SQLITE_OK if successful or an error code if an error occurs.
  82061. */
  82062. static int vdbeMergeEngineStep(
  82063. MergeEngine *pMerger, /* The merge engine to advance to the next row */
  82064. int *pbEof /* Set TRUE at EOF. Set false for more content */
  82065. ){
  82066. int rc;
  82067. int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
  82068. SortSubtask *pTask = pMerger->pTask;
  82069. /* Advance the current PmaReader */
  82070. rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
  82071. /* Update contents of aTree[] */
  82072. if( rc==SQLITE_OK ){
  82073. int i; /* Index of aTree[] to recalculate */
  82074. PmaReader *pReadr1; /* First PmaReader to compare */
  82075. PmaReader *pReadr2; /* Second PmaReader to compare */
  82076. int bCached = 0;
  82077. /* Find the first two PmaReaders to compare. The one that was just
  82078. ** advanced (iPrev) and the one next to it in the array. */
  82079. pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
  82080. pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
  82081. for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
  82082. /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
  82083. int iRes;
  82084. if( pReadr1->pFd==0 ){
  82085. iRes = +1;
  82086. }else if( pReadr2->pFd==0 ){
  82087. iRes = -1;
  82088. }else{
  82089. iRes = pTask->xCompare(pTask, &bCached,
  82090. pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
  82091. );
  82092. }
  82093. /* If pReadr1 contained the smaller value, set aTree[i] to its index.
  82094. ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
  82095. ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
  82096. ** pKey2 to point to the record belonging to pReadr2.
  82097. **
  82098. ** Alternatively, if pReadr2 contains the smaller of the two values,
  82099. ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
  82100. ** was actually called above, then pTask->pUnpacked now contains
  82101. ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
  82102. ** vdbeSorterCompare() from decoding pReadr2 again.
  82103. **
  82104. ** If the two values were equal, then the value from the oldest
  82105. ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
  82106. ** is sorted from oldest to newest, so pReadr1 contains older values
  82107. ** than pReadr2 iff (pReadr1<pReadr2). */
  82108. if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
  82109. pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
  82110. pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  82111. bCached = 0;
  82112. }else{
  82113. if( pReadr1->pFd ) bCached = 0;
  82114. pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
  82115. pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  82116. }
  82117. }
  82118. *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
  82119. }
  82120. return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
  82121. }
  82122. #if SQLITE_MAX_WORKER_THREADS>0
  82123. /*
  82124. ** The main routine for background threads that write level-0 PMAs.
  82125. */
  82126. static void *vdbeSorterFlushThread(void *pCtx){
  82127. SortSubtask *pTask = (SortSubtask*)pCtx;
  82128. int rc; /* Return code */
  82129. assert( pTask->bDone==0 );
  82130. rc = vdbeSorterListToPMA(pTask, &pTask->list);
  82131. pTask->bDone = 1;
  82132. return SQLITE_INT_TO_PTR(rc);
  82133. }
  82134. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  82135. /*
  82136. ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
  82137. ** using a background thread.
  82138. */
  82139. static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
  82140. #if SQLITE_MAX_WORKER_THREADS==0
  82141. pSorter->bUsePMA = 1;
  82142. return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
  82143. #else
  82144. int rc = SQLITE_OK;
  82145. int i;
  82146. SortSubtask *pTask = 0; /* Thread context used to create new PMA */
  82147. int nWorker = (pSorter->nTask-1);
  82148. /* Set the flag to indicate that at least one PMA has been written.
  82149. ** Or will be, anyhow. */
  82150. pSorter->bUsePMA = 1;
  82151. /* Select a sub-task to sort and flush the current list of in-memory
  82152. ** records to disk. If the sorter is running in multi-threaded mode,
  82153. ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
  82154. ** the background thread from a sub-tasks previous turn is still running,
  82155. ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
  82156. ** fall back to using the final sub-task. The first (pSorter->nTask-1)
  82157. ** sub-tasks are prefered as they use background threads - the final
  82158. ** sub-task uses the main thread. */
  82159. for(i=0; i<nWorker; i++){
  82160. int iTest = (pSorter->iPrev + i + 1) % nWorker;
  82161. pTask = &pSorter->aTask[iTest];
  82162. if( pTask->bDone ){
  82163. rc = vdbeSorterJoinThread(pTask);
  82164. }
  82165. if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
  82166. }
  82167. if( rc==SQLITE_OK ){
  82168. if( i==nWorker ){
  82169. /* Use the foreground thread for this operation */
  82170. rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
  82171. }else{
  82172. /* Launch a background thread for this operation */
  82173. u8 *aMem = pTask->list.aMemory;
  82174. void *pCtx = (void*)pTask;
  82175. assert( pTask->pThread==0 && pTask->bDone==0 );
  82176. assert( pTask->list.pList==0 );
  82177. assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
  82178. pSorter->iPrev = (u8)(pTask - pSorter->aTask);
  82179. pTask->list = pSorter->list;
  82180. pSorter->list.pList = 0;
  82181. pSorter->list.szPMA = 0;
  82182. if( aMem ){
  82183. pSorter->list.aMemory = aMem;
  82184. pSorter->nMemory = sqlite3MallocSize(aMem);
  82185. }else if( pSorter->list.aMemory ){
  82186. pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
  82187. if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
  82188. }
  82189. rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
  82190. }
  82191. }
  82192. return rc;
  82193. #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
  82194. }
  82195. /*
  82196. ** Add a record to the sorter.
  82197. */
  82198. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  82199. const VdbeCursor *pCsr, /* Sorter cursor */
  82200. Mem *pVal /* Memory cell containing record */
  82201. ){
  82202. VdbeSorter *pSorter;
  82203. int rc = SQLITE_OK; /* Return Code */
  82204. SorterRecord *pNew; /* New list element */
  82205. int bFlush; /* True to flush contents of memory to PMA */
  82206. int nReq; /* Bytes of memory required */
  82207. int nPMA; /* Bytes of PMA space required */
  82208. int t; /* serial type of first record field */
  82209. assert( pCsr->eCurType==CURTYPE_SORTER );
  82210. pSorter = pCsr->uc.pSorter;
  82211. getVarint32((const u8*)&pVal->z[1], t);
  82212. if( t>0 && t<10 && t!=7 ){
  82213. pSorter->typeMask &= SORTER_TYPE_INTEGER;
  82214. }else if( t>10 && (t & 0x01) ){
  82215. pSorter->typeMask &= SORTER_TYPE_TEXT;
  82216. }else{
  82217. pSorter->typeMask = 0;
  82218. }
  82219. assert( pSorter );
  82220. /* Figure out whether or not the current contents of memory should be
  82221. ** flushed to a PMA before continuing. If so, do so.
  82222. **
  82223. ** If using the single large allocation mode (pSorter->aMemory!=0), then
  82224. ** flush the contents of memory to a new PMA if (a) at least one value is
  82225. ** already in memory and (b) the new value will not fit in memory.
  82226. **
  82227. ** Or, if using separate allocations for each record, flush the contents
  82228. ** of memory to a PMA if either of the following are true:
  82229. **
  82230. ** * The total memory allocated for the in-memory list is greater
  82231. ** than (page-size * cache-size), or
  82232. **
  82233. ** * The total memory allocated for the in-memory list is greater
  82234. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  82235. */
  82236. nReq = pVal->n + sizeof(SorterRecord);
  82237. nPMA = pVal->n + sqlite3VarintLen(pVal->n);
  82238. if( pSorter->mxPmaSize ){
  82239. if( pSorter->list.aMemory ){
  82240. bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
  82241. }else{
  82242. bFlush = (
  82243. (pSorter->list.szPMA > pSorter->mxPmaSize)
  82244. || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  82245. );
  82246. }
  82247. if( bFlush ){
  82248. rc = vdbeSorterFlushPMA(pSorter);
  82249. pSorter->list.szPMA = 0;
  82250. pSorter->iMemory = 0;
  82251. assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
  82252. }
  82253. }
  82254. pSorter->list.szPMA += nPMA;
  82255. if( nPMA>pSorter->mxKeysize ){
  82256. pSorter->mxKeysize = nPMA;
  82257. }
  82258. if( pSorter->list.aMemory ){
  82259. int nMin = pSorter->iMemory + nReq;
  82260. if( nMin>pSorter->nMemory ){
  82261. u8 *aNew;
  82262. int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
  82263. int nNew = pSorter->nMemory * 2;
  82264. while( nNew < nMin ) nNew = nNew*2;
  82265. if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
  82266. if( nNew < nMin ) nNew = nMin;
  82267. aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
  82268. if( !aNew ) return SQLITE_NOMEM_BKPT;
  82269. pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
  82270. pSorter->list.aMemory = aNew;
  82271. pSorter->nMemory = nNew;
  82272. }
  82273. pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
  82274. pSorter->iMemory += ROUND8(nReq);
  82275. if( pSorter->list.pList ){
  82276. pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
  82277. }
  82278. }else{
  82279. pNew = (SorterRecord *)sqlite3Malloc(nReq);
  82280. if( pNew==0 ){
  82281. return SQLITE_NOMEM_BKPT;
  82282. }
  82283. pNew->u.pNext = pSorter->list.pList;
  82284. }
  82285. memcpy(SRVAL(pNew), pVal->z, pVal->n);
  82286. pNew->nVal = pVal->n;
  82287. pSorter->list.pList = pNew;
  82288. return rc;
  82289. }
  82290. /*
  82291. ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
  82292. ** of the data stored in aFile[1] is the same as that used by regular PMAs,
  82293. ** except that the number-of-bytes varint is omitted from the start.
  82294. */
  82295. static int vdbeIncrPopulate(IncrMerger *pIncr){
  82296. int rc = SQLITE_OK;
  82297. int rc2;
  82298. i64 iStart = pIncr->iStartOff;
  82299. SorterFile *pOut = &pIncr->aFile[1];
  82300. SortSubtask *pTask = pIncr->pTask;
  82301. MergeEngine *pMerger = pIncr->pMerger;
  82302. PmaWriter writer;
  82303. assert( pIncr->bEof==0 );
  82304. vdbeSorterPopulateDebug(pTask, "enter");
  82305. vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
  82306. while( rc==SQLITE_OK ){
  82307. int dummy;
  82308. PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
  82309. int nKey = pReader->nKey;
  82310. i64 iEof = writer.iWriteOff + writer.iBufEnd;
  82311. /* Check if the output file is full or if the input has been exhausted.
  82312. ** In either case exit the loop. */
  82313. if( pReader->pFd==0 ) break;
  82314. if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
  82315. /* Write the next key to the output. */
  82316. vdbePmaWriteVarint(&writer, nKey);
  82317. vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
  82318. assert( pIncr->pMerger->pTask==pTask );
  82319. rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
  82320. }
  82321. rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
  82322. if( rc==SQLITE_OK ) rc = rc2;
  82323. vdbeSorterPopulateDebug(pTask, "exit");
  82324. return rc;
  82325. }
  82326. #if SQLITE_MAX_WORKER_THREADS>0
  82327. /*
  82328. ** The main routine for background threads that populate aFile[1] of
  82329. ** multi-threaded IncrMerger objects.
  82330. */
  82331. static void *vdbeIncrPopulateThread(void *pCtx){
  82332. IncrMerger *pIncr = (IncrMerger*)pCtx;
  82333. void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
  82334. pIncr->pTask->bDone = 1;
  82335. return pRet;
  82336. }
  82337. /*
  82338. ** Launch a background thread to populate aFile[1] of pIncr.
  82339. */
  82340. static int vdbeIncrBgPopulate(IncrMerger *pIncr){
  82341. void *p = (void*)pIncr;
  82342. assert( pIncr->bUseThread );
  82343. return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
  82344. }
  82345. #endif
  82346. /*
  82347. ** This function is called when the PmaReader corresponding to pIncr has
  82348. ** finished reading the contents of aFile[0]. Its purpose is to "refill"
  82349. ** aFile[0] such that the PmaReader should start rereading it from the
  82350. ** beginning.
  82351. **
  82352. ** For single-threaded objects, this is accomplished by literally reading
  82353. ** keys from pIncr->pMerger and repopulating aFile[0].
  82354. **
  82355. ** For multi-threaded objects, all that is required is to wait until the
  82356. ** background thread is finished (if it is not already) and then swap
  82357. ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
  82358. ** been exhausted, this function also launches a new background thread
  82359. ** to populate the new aFile[1].
  82360. **
  82361. ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
  82362. */
  82363. static int vdbeIncrSwap(IncrMerger *pIncr){
  82364. int rc = SQLITE_OK;
  82365. #if SQLITE_MAX_WORKER_THREADS>0
  82366. if( pIncr->bUseThread ){
  82367. rc = vdbeSorterJoinThread(pIncr->pTask);
  82368. if( rc==SQLITE_OK ){
  82369. SorterFile f0 = pIncr->aFile[0];
  82370. pIncr->aFile[0] = pIncr->aFile[1];
  82371. pIncr->aFile[1] = f0;
  82372. }
  82373. if( rc==SQLITE_OK ){
  82374. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  82375. pIncr->bEof = 1;
  82376. }else{
  82377. rc = vdbeIncrBgPopulate(pIncr);
  82378. }
  82379. }
  82380. }else
  82381. #endif
  82382. {
  82383. rc = vdbeIncrPopulate(pIncr);
  82384. pIncr->aFile[0] = pIncr->aFile[1];
  82385. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  82386. pIncr->bEof = 1;
  82387. }
  82388. }
  82389. return rc;
  82390. }
  82391. /*
  82392. ** Allocate and return a new IncrMerger object to read data from pMerger.
  82393. **
  82394. ** If an OOM condition is encountered, return NULL. In this case free the
  82395. ** pMerger argument before returning.
  82396. */
  82397. static int vdbeIncrMergerNew(
  82398. SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
  82399. MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
  82400. IncrMerger **ppOut /* Write the new IncrMerger here */
  82401. ){
  82402. int rc = SQLITE_OK;
  82403. IncrMerger *pIncr = *ppOut = (IncrMerger*)
  82404. (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
  82405. if( pIncr ){
  82406. pIncr->pMerger = pMerger;
  82407. pIncr->pTask = pTask;
  82408. pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
  82409. pTask->file2.iEof += pIncr->mxSz;
  82410. }else{
  82411. vdbeMergeEngineFree(pMerger);
  82412. rc = SQLITE_NOMEM_BKPT;
  82413. }
  82414. return rc;
  82415. }
  82416. #if SQLITE_MAX_WORKER_THREADS>0
  82417. /*
  82418. ** Set the "use-threads" flag on object pIncr.
  82419. */
  82420. static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
  82421. pIncr->bUseThread = 1;
  82422. pIncr->pTask->file2.iEof -= pIncr->mxSz;
  82423. }
  82424. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  82425. /*
  82426. ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
  82427. ** two PmaReaders that feed that entry. Neither of the PmaReaders
  82428. ** are advanced. This routine merely does the comparison.
  82429. */
  82430. static void vdbeMergeEngineCompare(
  82431. MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
  82432. int iOut /* Store the result in pMerger->aTree[iOut] */
  82433. ){
  82434. int i1;
  82435. int i2;
  82436. int iRes;
  82437. PmaReader *p1;
  82438. PmaReader *p2;
  82439. assert( iOut<pMerger->nTree && iOut>0 );
  82440. if( iOut>=(pMerger->nTree/2) ){
  82441. i1 = (iOut - pMerger->nTree/2) * 2;
  82442. i2 = i1 + 1;
  82443. }else{
  82444. i1 = pMerger->aTree[iOut*2];
  82445. i2 = pMerger->aTree[iOut*2+1];
  82446. }
  82447. p1 = &pMerger->aReadr[i1];
  82448. p2 = &pMerger->aReadr[i2];
  82449. if( p1->pFd==0 ){
  82450. iRes = i2;
  82451. }else if( p2->pFd==0 ){
  82452. iRes = i1;
  82453. }else{
  82454. SortSubtask *pTask = pMerger->pTask;
  82455. int bCached = 0;
  82456. int res;
  82457. assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
  82458. res = pTask->xCompare(
  82459. pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
  82460. );
  82461. if( res<=0 ){
  82462. iRes = i1;
  82463. }else{
  82464. iRes = i2;
  82465. }
  82466. }
  82467. pMerger->aTree[iOut] = iRes;
  82468. }
  82469. /*
  82470. ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
  82471. ** and vdbePmaReaderIncrMergeInit().
  82472. **
  82473. ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
  82474. ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
  82475. ** when there exists one or more separate worker threads.
  82476. */
  82477. #define INCRINIT_NORMAL 0
  82478. #define INCRINIT_TASK 1
  82479. #define INCRINIT_ROOT 2
  82480. /*
  82481. ** Forward reference required as the vdbeIncrMergeInit() and
  82482. ** vdbePmaReaderIncrInit() routines are called mutually recursively when
  82483. ** building a merge tree.
  82484. */
  82485. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
  82486. /*
  82487. ** Initialize the MergeEngine object passed as the second argument. Once this
  82488. ** function returns, the first key of merged data may be read from the
  82489. ** MergeEngine object in the usual fashion.
  82490. **
  82491. ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
  82492. ** objects attached to the PmaReader objects that the merger reads from have
  82493. ** already been populated, but that they have not yet populated aFile[0] and
  82494. ** set the PmaReader objects up to read from it. In this case all that is
  82495. ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
  82496. ** its first key.
  82497. **
  82498. ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
  82499. ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
  82500. ** to pMerger.
  82501. **
  82502. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  82503. */
  82504. static int vdbeMergeEngineInit(
  82505. SortSubtask *pTask, /* Thread that will run pMerger */
  82506. MergeEngine *pMerger, /* MergeEngine to initialize */
  82507. int eMode /* One of the INCRINIT_XXX constants */
  82508. ){
  82509. int rc = SQLITE_OK; /* Return code */
  82510. int i; /* For looping over PmaReader objects */
  82511. int nTree = pMerger->nTree;
  82512. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  82513. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  82514. /* Verify that the MergeEngine is assigned to a single thread */
  82515. assert( pMerger->pTask==0 );
  82516. pMerger->pTask = pTask;
  82517. for(i=0; i<nTree; i++){
  82518. if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
  82519. /* PmaReaders should be normally initialized in order, as if they are
  82520. ** reading from the same temp file this makes for more linear file IO.
  82521. ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
  82522. ** in use it will block the vdbePmaReaderNext() call while it uses
  82523. ** the main thread to fill its buffer. So calling PmaReaderNext()
  82524. ** on this PmaReader before any of the multi-threaded PmaReaders takes
  82525. ** better advantage of multi-processor hardware. */
  82526. rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
  82527. }else{
  82528. rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
  82529. }
  82530. if( rc!=SQLITE_OK ) return rc;
  82531. }
  82532. for(i=pMerger->nTree-1; i>0; i--){
  82533. vdbeMergeEngineCompare(pMerger, i);
  82534. }
  82535. return pTask->pUnpacked->errCode;
  82536. }
  82537. /*
  82538. ** The PmaReader passed as the first argument is guaranteed to be an
  82539. ** incremental-reader (pReadr->pIncr!=0). This function serves to open
  82540. ** and/or initialize the temp file related fields of the IncrMerge
  82541. ** object at (pReadr->pIncr).
  82542. **
  82543. ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
  82544. ** in the sub-tree headed by pReadr are also initialized. Data is then
  82545. ** loaded into the buffers belonging to pReadr and it is set to point to
  82546. ** the first key in its range.
  82547. **
  82548. ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
  82549. ** to be a multi-threaded PmaReader and this function is being called in a
  82550. ** background thread. In this case all PmaReaders in the sub-tree are
  82551. ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
  82552. ** pReadr is populated. However, pReadr itself is not set up to point
  82553. ** to its first key. A call to vdbePmaReaderNext() is still required to do
  82554. ** that.
  82555. **
  82556. ** The reason this function does not call vdbePmaReaderNext() immediately
  82557. ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
  82558. ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
  82559. ** this entire function is being run by thread (pTask->thread), that will
  82560. ** lead to the current background thread attempting to join itself.
  82561. **
  82562. ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
  82563. ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
  82564. ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
  82565. ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
  82566. ** the current PmaReader set to point to the first key in its range.
  82567. **
  82568. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  82569. */
  82570. static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
  82571. int rc = SQLITE_OK;
  82572. IncrMerger *pIncr = pReadr->pIncr;
  82573. SortSubtask *pTask = pIncr->pTask;
  82574. sqlite3 *db = pTask->pSorter->db;
  82575. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  82576. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  82577. rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
  82578. /* Set up the required files for pIncr. A multi-theaded IncrMerge object
  82579. ** requires two temp files to itself, whereas a single-threaded object
  82580. ** only requires a region of pTask->file2. */
  82581. if( rc==SQLITE_OK ){
  82582. int mxSz = pIncr->mxSz;
  82583. #if SQLITE_MAX_WORKER_THREADS>0
  82584. if( pIncr->bUseThread ){
  82585. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
  82586. if( rc==SQLITE_OK ){
  82587. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
  82588. }
  82589. }else
  82590. #endif
  82591. /*if( !pIncr->bUseThread )*/{
  82592. if( pTask->file2.pFd==0 ){
  82593. assert( pTask->file2.iEof>0 );
  82594. rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
  82595. pTask->file2.iEof = 0;
  82596. }
  82597. if( rc==SQLITE_OK ){
  82598. pIncr->aFile[1].pFd = pTask->file2.pFd;
  82599. pIncr->iStartOff = pTask->file2.iEof;
  82600. pTask->file2.iEof += mxSz;
  82601. }
  82602. }
  82603. }
  82604. #if SQLITE_MAX_WORKER_THREADS>0
  82605. if( rc==SQLITE_OK && pIncr->bUseThread ){
  82606. /* Use the current thread to populate aFile[1], even though this
  82607. ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
  82608. ** then this function is already running in background thread
  82609. ** pIncr->pTask->thread.
  82610. **
  82611. ** If this is the INCRINIT_ROOT object, then it is running in the
  82612. ** main VDBE thread. But that is Ok, as that thread cannot return
  82613. ** control to the VDBE or proceed with anything useful until the
  82614. ** first results are ready from this merger object anyway.
  82615. */
  82616. assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
  82617. rc = vdbeIncrPopulate(pIncr);
  82618. }
  82619. #endif
  82620. if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
  82621. rc = vdbePmaReaderNext(pReadr);
  82622. }
  82623. return rc;
  82624. }
  82625. #if SQLITE_MAX_WORKER_THREADS>0
  82626. /*
  82627. ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
  82628. ** background threads.
  82629. */
  82630. static void *vdbePmaReaderBgIncrInit(void *pCtx){
  82631. PmaReader *pReader = (PmaReader*)pCtx;
  82632. void *pRet = SQLITE_INT_TO_PTR(
  82633. vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
  82634. );
  82635. pReader->pIncr->pTask->bDone = 1;
  82636. return pRet;
  82637. }
  82638. #endif
  82639. /*
  82640. ** If the PmaReader passed as the first argument is not an incremental-reader
  82641. ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
  82642. ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
  82643. ** this routine to initialize the incremental merge.
  82644. **
  82645. ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
  82646. ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
  82647. ** Or, if the IncrMerger is single threaded, the same function is called
  82648. ** using the current thread.
  82649. */
  82650. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
  82651. IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
  82652. int rc = SQLITE_OK; /* Return code */
  82653. if( pIncr ){
  82654. #if SQLITE_MAX_WORKER_THREADS>0
  82655. assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
  82656. if( pIncr->bUseThread ){
  82657. void *pCtx = (void*)pReadr;
  82658. rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
  82659. }else
  82660. #endif
  82661. {
  82662. rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
  82663. }
  82664. }
  82665. return rc;
  82666. }
  82667. /*
  82668. ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
  82669. ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
  82670. ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
  82671. ** to NULL and return an SQLite error code.
  82672. **
  82673. ** When this function is called, *piOffset is set to the offset of the
  82674. ** first PMA to read from pTask->file. Assuming no error occurs, it is
  82675. ** set to the offset immediately following the last byte of the last
  82676. ** PMA before returning. If an error does occur, then the final value of
  82677. ** *piOffset is undefined.
  82678. */
  82679. static int vdbeMergeEngineLevel0(
  82680. SortSubtask *pTask, /* Sorter task to read from */
  82681. int nPMA, /* Number of PMAs to read */
  82682. i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
  82683. MergeEngine **ppOut /* OUT: New merge-engine */
  82684. ){
  82685. MergeEngine *pNew; /* Merge engine to return */
  82686. i64 iOff = *piOffset;
  82687. int i;
  82688. int rc = SQLITE_OK;
  82689. *ppOut = pNew = vdbeMergeEngineNew(nPMA);
  82690. if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
  82691. for(i=0; i<nPMA && rc==SQLITE_OK; i++){
  82692. i64 nDummy = 0;
  82693. PmaReader *pReadr = &pNew->aReadr[i];
  82694. rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
  82695. iOff = pReadr->iEof;
  82696. }
  82697. if( rc!=SQLITE_OK ){
  82698. vdbeMergeEngineFree(pNew);
  82699. *ppOut = 0;
  82700. }
  82701. *piOffset = iOff;
  82702. return rc;
  82703. }
  82704. /*
  82705. ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
  82706. ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
  82707. **
  82708. ** i.e.
  82709. **
  82710. ** nPMA<=16 -> TreeDepth() == 0
  82711. ** nPMA<=256 -> TreeDepth() == 1
  82712. ** nPMA<=65536 -> TreeDepth() == 2
  82713. */
  82714. static int vdbeSorterTreeDepth(int nPMA){
  82715. int nDepth = 0;
  82716. i64 nDiv = SORTER_MAX_MERGE_COUNT;
  82717. while( nDiv < (i64)nPMA ){
  82718. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  82719. nDepth++;
  82720. }
  82721. return nDepth;
  82722. }
  82723. /*
  82724. ** pRoot is the root of an incremental merge-tree with depth nDepth (according
  82725. ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
  82726. ** tree, counting from zero. This function adds pLeaf to the tree.
  82727. **
  82728. ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
  82729. ** code is returned and pLeaf is freed.
  82730. */
  82731. static int vdbeSorterAddToTree(
  82732. SortSubtask *pTask, /* Task context */
  82733. int nDepth, /* Depth of tree according to TreeDepth() */
  82734. int iSeq, /* Sequence number of leaf within tree */
  82735. MergeEngine *pRoot, /* Root of tree */
  82736. MergeEngine *pLeaf /* Leaf to add to tree */
  82737. ){
  82738. int rc = SQLITE_OK;
  82739. int nDiv = 1;
  82740. int i;
  82741. MergeEngine *p = pRoot;
  82742. IncrMerger *pIncr;
  82743. rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
  82744. for(i=1; i<nDepth; i++){
  82745. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  82746. }
  82747. for(i=1; i<nDepth && rc==SQLITE_OK; i++){
  82748. int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
  82749. PmaReader *pReadr = &p->aReadr[iIter];
  82750. if( pReadr->pIncr==0 ){
  82751. MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  82752. if( pNew==0 ){
  82753. rc = SQLITE_NOMEM_BKPT;
  82754. }else{
  82755. rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
  82756. }
  82757. }
  82758. if( rc==SQLITE_OK ){
  82759. p = pReadr->pIncr->pMerger;
  82760. nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
  82761. }
  82762. }
  82763. if( rc==SQLITE_OK ){
  82764. p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
  82765. }else{
  82766. vdbeIncrFree(pIncr);
  82767. }
  82768. return rc;
  82769. }
  82770. /*
  82771. ** This function is called as part of a SorterRewind() operation on a sorter
  82772. ** that has already written two or more level-0 PMAs to one or more temp
  82773. ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
  82774. ** can be used to incrementally merge all PMAs on disk.
  82775. **
  82776. ** If successful, SQLITE_OK is returned and *ppOut set to point to the
  82777. ** MergeEngine object at the root of the tree before returning. Or, if an
  82778. ** error occurs, an SQLite error code is returned and the final value
  82779. ** of *ppOut is undefined.
  82780. */
  82781. static int vdbeSorterMergeTreeBuild(
  82782. VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
  82783. MergeEngine **ppOut /* Write the MergeEngine here */
  82784. ){
  82785. MergeEngine *pMain = 0;
  82786. int rc = SQLITE_OK;
  82787. int iTask;
  82788. #if SQLITE_MAX_WORKER_THREADS>0
  82789. /* If the sorter uses more than one task, then create the top-level
  82790. ** MergeEngine here. This MergeEngine will read data from exactly
  82791. ** one PmaReader per sub-task. */
  82792. assert( pSorter->bUseThreads || pSorter->nTask==1 );
  82793. if( pSorter->nTask>1 ){
  82794. pMain = vdbeMergeEngineNew(pSorter->nTask);
  82795. if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
  82796. }
  82797. #endif
  82798. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  82799. SortSubtask *pTask = &pSorter->aTask[iTask];
  82800. assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
  82801. if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
  82802. MergeEngine *pRoot = 0; /* Root node of tree for this task */
  82803. int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
  82804. i64 iReadOff = 0;
  82805. if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
  82806. rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
  82807. }else{
  82808. int i;
  82809. int iSeq = 0;
  82810. pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  82811. if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
  82812. for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
  82813. MergeEngine *pMerger = 0; /* New level-0 PMA merger */
  82814. int nReader; /* Number of level-0 PMAs to merge */
  82815. nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
  82816. rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
  82817. if( rc==SQLITE_OK ){
  82818. rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
  82819. }
  82820. }
  82821. }
  82822. if( rc==SQLITE_OK ){
  82823. #if SQLITE_MAX_WORKER_THREADS>0
  82824. if( pMain!=0 ){
  82825. rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
  82826. }else
  82827. #endif
  82828. {
  82829. assert( pMain==0 );
  82830. pMain = pRoot;
  82831. }
  82832. }else{
  82833. vdbeMergeEngineFree(pRoot);
  82834. }
  82835. }
  82836. }
  82837. if( rc!=SQLITE_OK ){
  82838. vdbeMergeEngineFree(pMain);
  82839. pMain = 0;
  82840. }
  82841. *ppOut = pMain;
  82842. return rc;
  82843. }
  82844. /*
  82845. ** This function is called as part of an sqlite3VdbeSorterRewind() operation
  82846. ** on a sorter that has written two or more PMAs to temporary files. It sets
  82847. ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
  82848. ** (for multi-threaded sorters) so that it can be used to iterate through
  82849. ** all records stored in the sorter.
  82850. **
  82851. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  82852. */
  82853. static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
  82854. int rc; /* Return code */
  82855. SortSubtask *pTask0 = &pSorter->aTask[0];
  82856. MergeEngine *pMain = 0;
  82857. #if SQLITE_MAX_WORKER_THREADS
  82858. sqlite3 *db = pTask0->pSorter->db;
  82859. int i;
  82860. SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
  82861. for(i=0; i<pSorter->nTask; i++){
  82862. pSorter->aTask[i].xCompare = xCompare;
  82863. }
  82864. #endif
  82865. rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
  82866. if( rc==SQLITE_OK ){
  82867. #if SQLITE_MAX_WORKER_THREADS
  82868. assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
  82869. if( pSorter->bUseThreads ){
  82870. int iTask;
  82871. PmaReader *pReadr = 0;
  82872. SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
  82873. rc = vdbeSortAllocUnpacked(pLast);
  82874. if( rc==SQLITE_OK ){
  82875. pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
  82876. pSorter->pReader = pReadr;
  82877. if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
  82878. }
  82879. if( rc==SQLITE_OK ){
  82880. rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
  82881. if( rc==SQLITE_OK ){
  82882. vdbeIncrMergerSetThreads(pReadr->pIncr);
  82883. for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
  82884. IncrMerger *pIncr;
  82885. if( (pIncr = pMain->aReadr[iTask].pIncr) ){
  82886. vdbeIncrMergerSetThreads(pIncr);
  82887. assert( pIncr->pTask!=pLast );
  82888. }
  82889. }
  82890. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  82891. /* Check that:
  82892. **
  82893. ** a) The incremental merge object is configured to use the
  82894. ** right task, and
  82895. ** b) If it is using task (nTask-1), it is configured to run
  82896. ** in single-threaded mode. This is important, as the
  82897. ** root merge (INCRINIT_ROOT) will be using the same task
  82898. ** object.
  82899. */
  82900. PmaReader *p = &pMain->aReadr[iTask];
  82901. assert( p->pIncr==0 || (
  82902. (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
  82903. && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
  82904. ));
  82905. rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
  82906. }
  82907. }
  82908. pMain = 0;
  82909. }
  82910. if( rc==SQLITE_OK ){
  82911. rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
  82912. }
  82913. }else
  82914. #endif
  82915. {
  82916. rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
  82917. pSorter->pMerger = pMain;
  82918. pMain = 0;
  82919. }
  82920. }
  82921. if( rc!=SQLITE_OK ){
  82922. vdbeMergeEngineFree(pMain);
  82923. }
  82924. return rc;
  82925. }
  82926. /*
  82927. ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
  82928. ** this function is called to prepare for iterating through the records
  82929. ** in sorted order.
  82930. */
  82931. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
  82932. VdbeSorter *pSorter;
  82933. int rc = SQLITE_OK; /* Return code */
  82934. assert( pCsr->eCurType==CURTYPE_SORTER );
  82935. pSorter = pCsr->uc.pSorter;
  82936. assert( pSorter );
  82937. /* If no data has been written to disk, then do not do so now. Instead,
  82938. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  82939. ** from the in-memory list. */
  82940. if( pSorter->bUsePMA==0 ){
  82941. if( pSorter->list.pList ){
  82942. *pbEof = 0;
  82943. rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
  82944. }else{
  82945. *pbEof = 1;
  82946. }
  82947. return rc;
  82948. }
  82949. /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
  82950. ** function flushes the contents of memory to disk, it immediately always
  82951. ** creates a new list consisting of a single key immediately afterwards.
  82952. ** So the list is never empty at this point. */
  82953. assert( pSorter->list.pList );
  82954. rc = vdbeSorterFlushPMA(pSorter);
  82955. /* Join all threads */
  82956. rc = vdbeSorterJoinAll(pSorter, rc);
  82957. vdbeSorterRewindDebug("rewind");
  82958. /* Assuming no errors have occurred, set up a merger structure to
  82959. ** incrementally read and merge all remaining PMAs. */
  82960. assert( pSorter->pReader==0 );
  82961. if( rc==SQLITE_OK ){
  82962. rc = vdbeSorterSetupMerge(pSorter);
  82963. *pbEof = 0;
  82964. }
  82965. vdbeSorterRewindDebug("rewinddone");
  82966. return rc;
  82967. }
  82968. /*
  82969. ** Advance to the next element in the sorter.
  82970. */
  82971. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  82972. VdbeSorter *pSorter;
  82973. int rc; /* Return code */
  82974. assert( pCsr->eCurType==CURTYPE_SORTER );
  82975. pSorter = pCsr->uc.pSorter;
  82976. assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
  82977. if( pSorter->bUsePMA ){
  82978. assert( pSorter->pReader==0 || pSorter->pMerger==0 );
  82979. assert( pSorter->bUseThreads==0 || pSorter->pReader );
  82980. assert( pSorter->bUseThreads==1 || pSorter->pMerger );
  82981. #if SQLITE_MAX_WORKER_THREADS>0
  82982. if( pSorter->bUseThreads ){
  82983. rc = vdbePmaReaderNext(pSorter->pReader);
  82984. *pbEof = (pSorter->pReader->pFd==0);
  82985. }else
  82986. #endif
  82987. /*if( !pSorter->bUseThreads )*/ {
  82988. assert( pSorter->pMerger!=0 );
  82989. assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
  82990. rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
  82991. }
  82992. }else{
  82993. SorterRecord *pFree = pSorter->list.pList;
  82994. pSorter->list.pList = pFree->u.pNext;
  82995. pFree->u.pNext = 0;
  82996. if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
  82997. *pbEof = !pSorter->list.pList;
  82998. rc = SQLITE_OK;
  82999. }
  83000. return rc;
  83001. }
  83002. /*
  83003. ** Return a pointer to a buffer owned by the sorter that contains the
  83004. ** current key.
  83005. */
  83006. static void *vdbeSorterRowkey(
  83007. const VdbeSorter *pSorter, /* Sorter object */
  83008. int *pnKey /* OUT: Size of current key in bytes */
  83009. ){
  83010. void *pKey;
  83011. if( pSorter->bUsePMA ){
  83012. PmaReader *pReader;
  83013. #if SQLITE_MAX_WORKER_THREADS>0
  83014. if( pSorter->bUseThreads ){
  83015. pReader = pSorter->pReader;
  83016. }else
  83017. #endif
  83018. /*if( !pSorter->bUseThreads )*/{
  83019. pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
  83020. }
  83021. *pnKey = pReader->nKey;
  83022. pKey = pReader->aKey;
  83023. }else{
  83024. *pnKey = pSorter->list.pList->nVal;
  83025. pKey = SRVAL(pSorter->list.pList);
  83026. }
  83027. return pKey;
  83028. }
  83029. /*
  83030. ** Copy the current sorter key into the memory cell pOut.
  83031. */
  83032. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  83033. VdbeSorter *pSorter;
  83034. void *pKey; int nKey; /* Sorter key to copy into pOut */
  83035. assert( pCsr->eCurType==CURTYPE_SORTER );
  83036. pSorter = pCsr->uc.pSorter;
  83037. pKey = vdbeSorterRowkey(pSorter, &nKey);
  83038. if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
  83039. return SQLITE_NOMEM_BKPT;
  83040. }
  83041. pOut->n = nKey;
  83042. MemSetTypeFlag(pOut, MEM_Blob);
  83043. memcpy(pOut->z, pKey, nKey);
  83044. return SQLITE_OK;
  83045. }
  83046. /*
  83047. ** Compare the key in memory cell pVal with the key that the sorter cursor
  83048. ** passed as the first argument currently points to. For the purposes of
  83049. ** the comparison, ignore the rowid field at the end of each record.
  83050. **
  83051. ** If the sorter cursor key contains any NULL values, consider it to be
  83052. ** less than pVal. Even if pVal also contains NULL values.
  83053. **
  83054. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  83055. ** Otherwise, set *pRes to a negative, zero or positive value if the
  83056. ** key in pVal is smaller than, equal to or larger than the current sorter
  83057. ** key.
  83058. **
  83059. ** This routine forms the core of the OP_SorterCompare opcode, which in
  83060. ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
  83061. */
  83062. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  83063. const VdbeCursor *pCsr, /* Sorter cursor */
  83064. Mem *pVal, /* Value to compare to current sorter key */
  83065. int nKeyCol, /* Compare this many columns */
  83066. int *pRes /* OUT: Result of comparison */
  83067. ){
  83068. VdbeSorter *pSorter;
  83069. UnpackedRecord *r2;
  83070. KeyInfo *pKeyInfo;
  83071. int i;
  83072. void *pKey; int nKey; /* Sorter key to compare pVal with */
  83073. assert( pCsr->eCurType==CURTYPE_SORTER );
  83074. pSorter = pCsr->uc.pSorter;
  83075. r2 = pSorter->pUnpacked;
  83076. pKeyInfo = pCsr->pKeyInfo;
  83077. if( r2==0 ){
  83078. r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  83079. if( r2==0 ) return SQLITE_NOMEM_BKPT;
  83080. r2->nField = nKeyCol;
  83081. }
  83082. assert( r2->nField==nKeyCol );
  83083. pKey = vdbeSorterRowkey(pSorter, &nKey);
  83084. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
  83085. for(i=0; i<nKeyCol; i++){
  83086. if( r2->aMem[i].flags & MEM_Null ){
  83087. *pRes = -1;
  83088. return SQLITE_OK;
  83089. }
  83090. }
  83091. *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
  83092. return SQLITE_OK;
  83093. }
  83094. /************** End of vdbesort.c ********************************************/
  83095. /************** Begin file memjournal.c **************************************/
  83096. /*
  83097. ** 2008 October 7
  83098. **
  83099. ** The author disclaims copyright to this source code. In place of
  83100. ** a legal notice, here is a blessing:
  83101. **
  83102. ** May you do good and not evil.
  83103. ** May you find forgiveness for yourself and forgive others.
  83104. ** May you share freely, never taking more than you give.
  83105. **
  83106. *************************************************************************
  83107. **
  83108. ** This file contains code use to implement an in-memory rollback journal.
  83109. ** The in-memory rollback journal is used to journal transactions for
  83110. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  83111. **
  83112. ** Update: The in-memory journal is also used to temporarily cache
  83113. ** smaller journals that are not critical for power-loss recovery.
  83114. ** For example, statement journals that are not too big will be held
  83115. ** entirely in memory, thus reducing the number of file I/O calls, and
  83116. ** more importantly, reducing temporary file creation events. If these
  83117. ** journals become too large for memory, they are spilled to disk. But
  83118. ** in the common case, they are usually small and no file I/O needs to
  83119. ** occur.
  83120. */
  83121. /* #include "sqliteInt.h" */
  83122. /* Forward references to internal structures */
  83123. typedef struct MemJournal MemJournal;
  83124. typedef struct FilePoint FilePoint;
  83125. typedef struct FileChunk FileChunk;
  83126. /*
  83127. ** The rollback journal is composed of a linked list of these structures.
  83128. **
  83129. ** The zChunk array is always at least 8 bytes in size - usually much more.
  83130. ** Its actual size is stored in the MemJournal.nChunkSize variable.
  83131. */
  83132. struct FileChunk {
  83133. FileChunk *pNext; /* Next chunk in the journal */
  83134. u8 zChunk[8]; /* Content of this chunk */
  83135. };
  83136. /*
  83137. ** By default, allocate this many bytes of memory for each FileChunk object.
  83138. */
  83139. #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
  83140. /*
  83141. ** For chunk size nChunkSize, return the number of bytes that should
  83142. ** be allocated for each FileChunk structure.
  83143. */
  83144. #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
  83145. /*
  83146. ** An instance of this object serves as a cursor into the rollback journal.
  83147. ** The cursor can be either for reading or writing.
  83148. */
  83149. struct FilePoint {
  83150. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  83151. FileChunk *pChunk; /* Specific chunk into which cursor points */
  83152. };
  83153. /*
  83154. ** This structure is a subclass of sqlite3_file. Each open memory-journal
  83155. ** is an instance of this class.
  83156. */
  83157. struct MemJournal {
  83158. const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  83159. int nChunkSize; /* In-memory chunk-size */
  83160. int nSpill; /* Bytes of data before flushing */
  83161. int nSize; /* Bytes of data currently in memory */
  83162. FileChunk *pFirst; /* Head of in-memory chunk-list */
  83163. FilePoint endpoint; /* Pointer to the end of the file */
  83164. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  83165. int flags; /* xOpen flags */
  83166. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  83167. const char *zJournal; /* Name of the journal file */
  83168. };
  83169. /*
  83170. ** Read data from the in-memory journal file. This is the implementation
  83171. ** of the sqlite3_vfs.xRead method.
  83172. */
  83173. static int memjrnlRead(
  83174. sqlite3_file *pJfd, /* The journal file from which to read */
  83175. void *zBuf, /* Put the results here */
  83176. int iAmt, /* Number of bytes to read */
  83177. sqlite_int64 iOfst /* Begin reading at this offset */
  83178. ){
  83179. MemJournal *p = (MemJournal *)pJfd;
  83180. u8 *zOut = zBuf;
  83181. int nRead = iAmt;
  83182. int iChunkOffset;
  83183. FileChunk *pChunk;
  83184. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  83185. if( (iAmt+iOfst)>p->endpoint.iOffset ){
  83186. return SQLITE_IOERR_SHORT_READ;
  83187. }
  83188. #endif
  83189. assert( (iAmt+iOfst)<=p->endpoint.iOffset );
  83190. assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
  83191. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  83192. sqlite3_int64 iOff = 0;
  83193. for(pChunk=p->pFirst;
  83194. ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
  83195. pChunk=pChunk->pNext
  83196. ){
  83197. iOff += p->nChunkSize;
  83198. }
  83199. }else{
  83200. pChunk = p->readpoint.pChunk;
  83201. assert( pChunk!=0 );
  83202. }
  83203. iChunkOffset = (int)(iOfst%p->nChunkSize);
  83204. do {
  83205. int iSpace = p->nChunkSize - iChunkOffset;
  83206. int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
  83207. memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
  83208. zOut += nCopy;
  83209. nRead -= iSpace;
  83210. iChunkOffset = 0;
  83211. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  83212. p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
  83213. p->readpoint.pChunk = pChunk;
  83214. return SQLITE_OK;
  83215. }
  83216. /*
  83217. ** Free the list of FileChunk structures headed at MemJournal.pFirst.
  83218. */
  83219. static void memjrnlFreeChunks(MemJournal *p){
  83220. FileChunk *pIter;
  83221. FileChunk *pNext;
  83222. for(pIter=p->pFirst; pIter; pIter=pNext){
  83223. pNext = pIter->pNext;
  83224. sqlite3_free(pIter);
  83225. }
  83226. p->pFirst = 0;
  83227. }
  83228. /*
  83229. ** Flush the contents of memory to a real file on disk.
  83230. */
  83231. static int memjrnlCreateFile(MemJournal *p){
  83232. int rc;
  83233. sqlite3_file *pReal = (sqlite3_file*)p;
  83234. MemJournal copy = *p;
  83235. memset(p, 0, sizeof(MemJournal));
  83236. rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
  83237. if( rc==SQLITE_OK ){
  83238. int nChunk = copy.nChunkSize;
  83239. i64 iOff = 0;
  83240. FileChunk *pIter;
  83241. for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
  83242. if( iOff + nChunk > copy.endpoint.iOffset ){
  83243. nChunk = copy.endpoint.iOffset - iOff;
  83244. }
  83245. rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
  83246. if( rc ) break;
  83247. iOff += nChunk;
  83248. }
  83249. if( rc==SQLITE_OK ){
  83250. /* No error has occurred. Free the in-memory buffers. */
  83251. memjrnlFreeChunks(&copy);
  83252. }
  83253. }
  83254. if( rc!=SQLITE_OK ){
  83255. /* If an error occurred while creating or writing to the file, restore
  83256. ** the original before returning. This way, SQLite uses the in-memory
  83257. ** journal data to roll back changes made to the internal page-cache
  83258. ** before this function was called. */
  83259. sqlite3OsClose(pReal);
  83260. *p = copy;
  83261. }
  83262. return rc;
  83263. }
  83264. /*
  83265. ** Write data to the file.
  83266. */
  83267. static int memjrnlWrite(
  83268. sqlite3_file *pJfd, /* The journal file into which to write */
  83269. const void *zBuf, /* Take data to be written from here */
  83270. int iAmt, /* Number of bytes to write */
  83271. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  83272. ){
  83273. MemJournal *p = (MemJournal *)pJfd;
  83274. int nWrite = iAmt;
  83275. u8 *zWrite = (u8 *)zBuf;
  83276. /* If the file should be created now, create it and write the new data
  83277. ** into the file on disk. */
  83278. if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
  83279. int rc = memjrnlCreateFile(p);
  83280. if( rc==SQLITE_OK ){
  83281. rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
  83282. }
  83283. return rc;
  83284. }
  83285. /* If the contents of this write should be stored in memory */
  83286. else{
  83287. /* An in-memory journal file should only ever be appended to. Random
  83288. ** access writes are not required. The only exception to this is when
  83289. ** the in-memory journal is being used by a connection using the
  83290. ** atomic-write optimization. In this case the first 28 bytes of the
  83291. ** journal file may be written as part of committing the transaction. */
  83292. assert( iOfst==p->endpoint.iOffset || iOfst==0 );
  83293. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  83294. if( iOfst==0 && p->pFirst ){
  83295. assert( p->nChunkSize>iAmt );
  83296. memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
  83297. }else
  83298. #else
  83299. assert( iOfst>0 || p->pFirst==0 );
  83300. #endif
  83301. {
  83302. while( nWrite>0 ){
  83303. FileChunk *pChunk = p->endpoint.pChunk;
  83304. int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
  83305. int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
  83306. if( iChunkOffset==0 ){
  83307. /* New chunk is required to extend the file. */
  83308. FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
  83309. if( !pNew ){
  83310. return SQLITE_IOERR_NOMEM_BKPT;
  83311. }
  83312. pNew->pNext = 0;
  83313. if( pChunk ){
  83314. assert( p->pFirst );
  83315. pChunk->pNext = pNew;
  83316. }else{
  83317. assert( !p->pFirst );
  83318. p->pFirst = pNew;
  83319. }
  83320. p->endpoint.pChunk = pNew;
  83321. }
  83322. memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
  83323. zWrite += iSpace;
  83324. nWrite -= iSpace;
  83325. p->endpoint.iOffset += iSpace;
  83326. }
  83327. p->nSize = iAmt + iOfst;
  83328. }
  83329. }
  83330. return SQLITE_OK;
  83331. }
  83332. /*
  83333. ** Truncate the file.
  83334. **
  83335. ** If the journal file is already on disk, truncate it there. Or, if it
  83336. ** is still in main memory but is being truncated to zero bytes in size,
  83337. ** ignore
  83338. */
  83339. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  83340. MemJournal *p = (MemJournal *)pJfd;
  83341. if( ALWAYS(size==0) ){
  83342. memjrnlFreeChunks(p);
  83343. p->nSize = 0;
  83344. p->endpoint.pChunk = 0;
  83345. p->endpoint.iOffset = 0;
  83346. p->readpoint.pChunk = 0;
  83347. p->readpoint.iOffset = 0;
  83348. }
  83349. return SQLITE_OK;
  83350. }
  83351. /*
  83352. ** Close the file.
  83353. */
  83354. static int memjrnlClose(sqlite3_file *pJfd){
  83355. MemJournal *p = (MemJournal *)pJfd;
  83356. memjrnlFreeChunks(p);
  83357. return SQLITE_OK;
  83358. }
  83359. /*
  83360. ** Sync the file.
  83361. **
  83362. ** If the real file has been created, call its xSync method. Otherwise,
  83363. ** syncing an in-memory journal is a no-op.
  83364. */
  83365. static int memjrnlSync(sqlite3_file *pJfd, int flags){
  83366. UNUSED_PARAMETER2(pJfd, flags);
  83367. return SQLITE_OK;
  83368. }
  83369. /*
  83370. ** Query the size of the file in bytes.
  83371. */
  83372. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  83373. MemJournal *p = (MemJournal *)pJfd;
  83374. *pSize = (sqlite_int64) p->endpoint.iOffset;
  83375. return SQLITE_OK;
  83376. }
  83377. /*
  83378. ** Table of methods for MemJournal sqlite3_file object.
  83379. */
  83380. static const struct sqlite3_io_methods MemJournalMethods = {
  83381. 1, /* iVersion */
  83382. memjrnlClose, /* xClose */
  83383. memjrnlRead, /* xRead */
  83384. memjrnlWrite, /* xWrite */
  83385. memjrnlTruncate, /* xTruncate */
  83386. memjrnlSync, /* xSync */
  83387. memjrnlFileSize, /* xFileSize */
  83388. 0, /* xLock */
  83389. 0, /* xUnlock */
  83390. 0, /* xCheckReservedLock */
  83391. 0, /* xFileControl */
  83392. 0, /* xSectorSize */
  83393. 0, /* xDeviceCharacteristics */
  83394. 0, /* xShmMap */
  83395. 0, /* xShmLock */
  83396. 0, /* xShmBarrier */
  83397. 0, /* xShmUnmap */
  83398. 0, /* xFetch */
  83399. 0 /* xUnfetch */
  83400. };
  83401. /*
  83402. ** Open a journal file.
  83403. **
  83404. ** The behaviour of the journal file depends on the value of parameter
  83405. ** nSpill. If nSpill is 0, then the journal file is always create and
  83406. ** accessed using the underlying VFS. If nSpill is less than zero, then
  83407. ** all content is always stored in main-memory. Finally, if nSpill is a
  83408. ** positive value, then the journal file is initially created in-memory
  83409. ** but may be flushed to disk later on. In this case the journal file is
  83410. ** flushed to disk either when it grows larger than nSpill bytes in size,
  83411. ** or when sqlite3JournalCreate() is called.
  83412. */
  83413. SQLITE_PRIVATE int sqlite3JournalOpen(
  83414. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  83415. const char *zName, /* Name of the journal file */
  83416. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  83417. int flags, /* Opening flags */
  83418. int nSpill /* Bytes buffered before opening the file */
  83419. ){
  83420. MemJournal *p = (MemJournal*)pJfd;
  83421. /* Zero the file-handle object. If nSpill was passed zero, initialize
  83422. ** it using the sqlite3OsOpen() function of the underlying VFS. In this
  83423. ** case none of the code in this module is executed as a result of calls
  83424. ** made on the journal file-handle. */
  83425. memset(p, 0, sizeof(MemJournal));
  83426. if( nSpill==0 ){
  83427. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  83428. }
  83429. if( nSpill>0 ){
  83430. p->nChunkSize = nSpill;
  83431. }else{
  83432. p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
  83433. assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
  83434. }
  83435. p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
  83436. p->nSpill = nSpill;
  83437. p->flags = flags;
  83438. p->zJournal = zName;
  83439. p->pVfs = pVfs;
  83440. return SQLITE_OK;
  83441. }
  83442. /*
  83443. ** Open an in-memory journal file.
  83444. */
  83445. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  83446. sqlite3JournalOpen(0, 0, pJfd, 0, -1);
  83447. }
  83448. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  83449. /*
  83450. ** If the argument p points to a MemJournal structure that is not an
  83451. ** in-memory-only journal file (i.e. is one that was opened with a +ve
  83452. ** nSpill parameter), and the underlying file has not yet been created,
  83453. ** create it now.
  83454. */
  83455. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  83456. int rc = SQLITE_OK;
  83457. if( p->pMethods==&MemJournalMethods && ((MemJournal*)p)->nSpill>0 ){
  83458. rc = memjrnlCreateFile((MemJournal*)p);
  83459. }
  83460. return rc;
  83461. }
  83462. #endif
  83463. /*
  83464. ** The file-handle passed as the only argument is open on a journal file.
  83465. ** Return true if this "journal file" is currently stored in heap memory,
  83466. ** or false otherwise.
  83467. */
  83468. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
  83469. return p->pMethods==&MemJournalMethods;
  83470. }
  83471. /*
  83472. ** Return the number of bytes required to store a JournalFile that uses vfs
  83473. ** pVfs to create the underlying on-disk files.
  83474. */
  83475. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  83476. return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
  83477. }
  83478. /************** End of memjournal.c ******************************************/
  83479. /************** Begin file walker.c ******************************************/
  83480. /*
  83481. ** 2008 August 16
  83482. **
  83483. ** The author disclaims copyright to this source code. In place of
  83484. ** a legal notice, here is a blessing:
  83485. **
  83486. ** May you do good and not evil.
  83487. ** May you find forgiveness for yourself and forgive others.
  83488. ** May you share freely, never taking more than you give.
  83489. **
  83490. *************************************************************************
  83491. ** This file contains routines used for walking the parser tree for
  83492. ** an SQL statement.
  83493. */
  83494. /* #include "sqliteInt.h" */
  83495. /* #include <stdlib.h> */
  83496. /* #include <string.h> */
  83497. /*
  83498. ** Walk an expression tree. Invoke the callback once for each node
  83499. ** of the expression, while descending. (In other words, the callback
  83500. ** is invoked before visiting children.)
  83501. **
  83502. ** The return value from the callback should be one of the WRC_*
  83503. ** constants to specify how to proceed with the walk.
  83504. **
  83505. ** WRC_Continue Continue descending down the tree.
  83506. **
  83507. ** WRC_Prune Do not descend into child nodes, but allow
  83508. ** the walk to continue with sibling nodes.
  83509. **
  83510. ** WRC_Abort Do no more callbacks. Unwind the stack and
  83511. ** return from the top-level walk call.
  83512. **
  83513. ** The return value from this routine is WRC_Abort to abandon the tree walk
  83514. ** and WRC_Continue to continue.
  83515. */
  83516. static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
  83517. int rc;
  83518. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  83519. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  83520. rc = pWalker->xExprCallback(pWalker, pExpr);
  83521. if( rc || ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
  83522. return rc & WRC_Abort;
  83523. }
  83524. if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  83525. if( pExpr->pRight && walkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  83526. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  83527. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  83528. }else if( pExpr->x.pList ){
  83529. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  83530. }
  83531. return WRC_Continue;
  83532. }
  83533. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  83534. return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
  83535. }
  83536. /*
  83537. ** Call sqlite3WalkExpr() for every expression in list p or until
  83538. ** an abort request is seen.
  83539. */
  83540. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  83541. int i;
  83542. struct ExprList_item *pItem;
  83543. if( p ){
  83544. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  83545. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  83546. }
  83547. }
  83548. return WRC_Continue;
  83549. }
  83550. /*
  83551. ** Walk all expressions associated with SELECT statement p. Do
  83552. ** not invoke the SELECT callback on p, but do (of course) invoke
  83553. ** any expr callbacks and SELECT callbacks that come from subqueries.
  83554. ** Return WRC_Abort or WRC_Continue.
  83555. */
  83556. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  83557. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  83558. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  83559. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  83560. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  83561. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  83562. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  83563. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  83564. return WRC_Continue;
  83565. }
  83566. /*
  83567. ** Walk the parse trees associated with all subqueries in the
  83568. ** FROM clause of SELECT statement p. Do not invoke the select
  83569. ** callback on p, but do invoke it on each FROM clause subquery
  83570. ** and on any subqueries further down in the tree. Return
  83571. ** WRC_Abort or WRC_Continue;
  83572. */
  83573. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  83574. SrcList *pSrc;
  83575. int i;
  83576. struct SrcList_item *pItem;
  83577. pSrc = p->pSrc;
  83578. if( ALWAYS(pSrc) ){
  83579. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  83580. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  83581. return WRC_Abort;
  83582. }
  83583. if( pItem->fg.isTabFunc
  83584. && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
  83585. ){
  83586. return WRC_Abort;
  83587. }
  83588. }
  83589. }
  83590. return WRC_Continue;
  83591. }
  83592. /*
  83593. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  83594. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  83595. ** on the compound select chain, p->pPrior.
  83596. **
  83597. ** If it is not NULL, the xSelectCallback() callback is invoked before
  83598. ** the walk of the expressions and FROM clause. The xSelectCallback2()
  83599. ** method, if it is not NULL, is invoked following the walk of the
  83600. ** expressions and FROM clause.
  83601. **
  83602. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  83603. ** there is an abort request.
  83604. **
  83605. ** If the Walker does not have an xSelectCallback() then this routine
  83606. ** is a no-op returning WRC_Continue.
  83607. */
  83608. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  83609. int rc;
  83610. if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
  83611. return WRC_Continue;
  83612. }
  83613. rc = WRC_Continue;
  83614. pWalker->walkerDepth++;
  83615. while( p ){
  83616. if( pWalker->xSelectCallback ){
  83617. rc = pWalker->xSelectCallback(pWalker, p);
  83618. if( rc ) break;
  83619. }
  83620. if( sqlite3WalkSelectExpr(pWalker, p)
  83621. || sqlite3WalkSelectFrom(pWalker, p)
  83622. ){
  83623. pWalker->walkerDepth--;
  83624. return WRC_Abort;
  83625. }
  83626. if( pWalker->xSelectCallback2 ){
  83627. pWalker->xSelectCallback2(pWalker, p);
  83628. }
  83629. p = p->pPrior;
  83630. }
  83631. pWalker->walkerDepth--;
  83632. return rc & WRC_Abort;
  83633. }
  83634. /************** End of walker.c **********************************************/
  83635. /************** Begin file resolve.c *****************************************/
  83636. /*
  83637. ** 2008 August 18
  83638. **
  83639. ** The author disclaims copyright to this source code. In place of
  83640. ** a legal notice, here is a blessing:
  83641. **
  83642. ** May you do good and not evil.
  83643. ** May you find forgiveness for yourself and forgive others.
  83644. ** May you share freely, never taking more than you give.
  83645. **
  83646. *************************************************************************
  83647. **
  83648. ** This file contains routines used for walking the parser tree and
  83649. ** resolve all identifiers by associating them with a particular
  83650. ** table and column.
  83651. */
  83652. /* #include "sqliteInt.h" */
  83653. /*
  83654. ** Walk the expression tree pExpr and increase the aggregate function
  83655. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  83656. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  83657. ** outer query into an inner subquery.
  83658. **
  83659. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  83660. ** is a helper function - a callback for the tree walker.
  83661. */
  83662. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  83663. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
  83664. return WRC_Continue;
  83665. }
  83666. static void incrAggFunctionDepth(Expr *pExpr, int N){
  83667. if( N>0 ){
  83668. Walker w;
  83669. memset(&w, 0, sizeof(w));
  83670. w.xExprCallback = incrAggDepth;
  83671. w.u.n = N;
  83672. sqlite3WalkExpr(&w, pExpr);
  83673. }
  83674. }
  83675. /*
  83676. ** Turn the pExpr expression into an alias for the iCol-th column of the
  83677. ** result set in pEList.
  83678. **
  83679. ** If the reference is followed by a COLLATE operator, then make sure
  83680. ** the COLLATE operator is preserved. For example:
  83681. **
  83682. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  83683. **
  83684. ** Should be transformed into:
  83685. **
  83686. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  83687. **
  83688. ** The nSubquery parameter specifies how many levels of subquery the
  83689. ** alias is removed from the original expression. The usual value is
  83690. ** zero but it might be more if the alias is contained within a subquery
  83691. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  83692. ** structures must be increased by the nSubquery amount.
  83693. */
  83694. static void resolveAlias(
  83695. Parse *pParse, /* Parsing context */
  83696. ExprList *pEList, /* A result set */
  83697. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  83698. Expr *pExpr, /* Transform this into an alias to the result set */
  83699. const char *zType, /* "GROUP" or "ORDER" or "" */
  83700. int nSubquery /* Number of subqueries that the label is moving */
  83701. ){
  83702. Expr *pOrig; /* The iCol-th column of the result set */
  83703. Expr *pDup; /* Copy of pOrig */
  83704. sqlite3 *db; /* The database connection */
  83705. assert( iCol>=0 && iCol<pEList->nExpr );
  83706. pOrig = pEList->a[iCol].pExpr;
  83707. assert( pOrig!=0 );
  83708. db = pParse->db;
  83709. pDup = sqlite3ExprDup(db, pOrig, 0);
  83710. if( pDup==0 ) return;
  83711. if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
  83712. if( pExpr->op==TK_COLLATE ){
  83713. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  83714. }
  83715. ExprSetProperty(pDup, EP_Alias);
  83716. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  83717. ** prevents ExprDelete() from deleting the Expr structure itself,
  83718. ** allowing it to be repopulated by the memcpy() on the following line.
  83719. ** The pExpr->u.zToken might point into memory that will be freed by the
  83720. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  83721. ** make a copy of the token before doing the sqlite3DbFree().
  83722. */
  83723. ExprSetProperty(pExpr, EP_Static);
  83724. sqlite3ExprDelete(db, pExpr);
  83725. memcpy(pExpr, pDup, sizeof(*pExpr));
  83726. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  83727. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  83728. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  83729. pExpr->flags |= EP_MemToken;
  83730. }
  83731. sqlite3DbFree(db, pDup);
  83732. }
  83733. /*
  83734. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  83735. **
  83736. ** Return FALSE if the USING clause is NULL or if it does not contain
  83737. ** zCol.
  83738. */
  83739. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  83740. if( pUsing ){
  83741. int k;
  83742. for(k=0; k<pUsing->nId; k++){
  83743. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  83744. }
  83745. }
  83746. return 0;
  83747. }
  83748. /*
  83749. ** Subqueries stores the original database, table and column names for their
  83750. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  83751. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  83752. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  83753. ** match anything.
  83754. */
  83755. SQLITE_PRIVATE int sqlite3MatchSpanName(
  83756. const char *zSpan,
  83757. const char *zCol,
  83758. const char *zTab,
  83759. const char *zDb
  83760. ){
  83761. int n;
  83762. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  83763. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  83764. return 0;
  83765. }
  83766. zSpan += n+1;
  83767. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  83768. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  83769. return 0;
  83770. }
  83771. zSpan += n+1;
  83772. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  83773. return 0;
  83774. }
  83775. return 1;
  83776. }
  83777. /*
  83778. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  83779. ** that name in the set of source tables in pSrcList and make the pExpr
  83780. ** expression node refer back to that source column. The following changes
  83781. ** are made to pExpr:
  83782. **
  83783. ** pExpr->iDb Set the index in db->aDb[] of the database X
  83784. ** (even if X is implied).
  83785. ** pExpr->iTable Set to the cursor number for the table obtained
  83786. ** from pSrcList.
  83787. ** pExpr->pTab Points to the Table structure of X.Y (even if
  83788. ** X and/or Y are implied.)
  83789. ** pExpr->iColumn Set to the column number within the table.
  83790. ** pExpr->op Set to TK_COLUMN.
  83791. ** pExpr->pLeft Any expression this points to is deleted
  83792. ** pExpr->pRight Any expression this points to is deleted.
  83793. **
  83794. ** The zDb variable is the name of the database (the "X"). This value may be
  83795. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  83796. ** can be used. The zTable variable is the name of the table (the "Y"). This
  83797. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  83798. ** means that the form of the name is Z and that columns from any table
  83799. ** can be used.
  83800. **
  83801. ** If the name cannot be resolved unambiguously, leave an error message
  83802. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  83803. */
  83804. static int lookupName(
  83805. Parse *pParse, /* The parsing context */
  83806. const char *zDb, /* Name of the database containing table, or NULL */
  83807. const char *zTab, /* Name of table containing column, or NULL */
  83808. const char *zCol, /* Name of the column. */
  83809. NameContext *pNC, /* The name context used to resolve the name */
  83810. Expr *pExpr /* Make this EXPR node point to the selected column */
  83811. ){
  83812. int i, j; /* Loop counters */
  83813. int cnt = 0; /* Number of matching column names */
  83814. int cntTab = 0; /* Number of matching table names */
  83815. int nSubquery = 0; /* How many levels of subquery */
  83816. sqlite3 *db = pParse->db; /* The database connection */
  83817. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  83818. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  83819. NameContext *pTopNC = pNC; /* First namecontext in the list */
  83820. Schema *pSchema = 0; /* Schema of the expression */
  83821. int isTrigger = 0; /* True if resolved to a trigger column */
  83822. Table *pTab = 0; /* Table hold the row */
  83823. Column *pCol; /* A column of pTab */
  83824. assert( pNC ); /* the name context cannot be NULL. */
  83825. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  83826. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  83827. /* Initialize the node to no-match */
  83828. pExpr->iTable = -1;
  83829. pExpr->pTab = 0;
  83830. ExprSetVVAProperty(pExpr, EP_NoReduce);
  83831. /* Translate the schema name in zDb into a pointer to the corresponding
  83832. ** schema. If not found, pSchema will remain NULL and nothing will match
  83833. ** resulting in an appropriate error message toward the end of this routine
  83834. */
  83835. if( zDb ){
  83836. testcase( pNC->ncFlags & NC_PartIdx );
  83837. testcase( pNC->ncFlags & NC_IsCheck );
  83838. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  83839. /* Silently ignore database qualifiers inside CHECK constraints and
  83840. ** partial indices. Do not raise errors because that might break
  83841. ** legacy and because it does not hurt anything to just ignore the
  83842. ** database name. */
  83843. zDb = 0;
  83844. }else{
  83845. for(i=0; i<db->nDb; i++){
  83846. assert( db->aDb[i].zDbSName );
  83847. if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
  83848. pSchema = db->aDb[i].pSchema;
  83849. break;
  83850. }
  83851. }
  83852. }
  83853. }
  83854. /* Start at the inner-most context and move outward until a match is found */
  83855. assert( pNC && cnt==0 );
  83856. do{
  83857. ExprList *pEList;
  83858. SrcList *pSrcList = pNC->pSrcList;
  83859. if( pSrcList ){
  83860. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  83861. pTab = pItem->pTab;
  83862. assert( pTab!=0 && pTab->zName!=0 );
  83863. assert( pTab->nCol>0 );
  83864. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  83865. int hit = 0;
  83866. pEList = pItem->pSelect->pEList;
  83867. for(j=0; j<pEList->nExpr; j++){
  83868. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  83869. cnt++;
  83870. cntTab = 2;
  83871. pMatch = pItem;
  83872. pExpr->iColumn = j;
  83873. hit = 1;
  83874. }
  83875. }
  83876. if( hit || zTab==0 ) continue;
  83877. }
  83878. if( zDb && pTab->pSchema!=pSchema ){
  83879. continue;
  83880. }
  83881. if( zTab ){
  83882. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  83883. assert( zTabName!=0 );
  83884. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  83885. continue;
  83886. }
  83887. }
  83888. if( 0==(cntTab++) ){
  83889. pMatch = pItem;
  83890. }
  83891. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  83892. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  83893. /* If there has been exactly one prior match and this match
  83894. ** is for the right-hand table of a NATURAL JOIN or is in a
  83895. ** USING clause, then skip this match.
  83896. */
  83897. if( cnt==1 ){
  83898. if( pItem->fg.jointype & JT_NATURAL ) continue;
  83899. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  83900. }
  83901. cnt++;
  83902. pMatch = pItem;
  83903. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  83904. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  83905. break;
  83906. }
  83907. }
  83908. }
  83909. if( pMatch ){
  83910. pExpr->iTable = pMatch->iCursor;
  83911. pExpr->pTab = pMatch->pTab;
  83912. /* RIGHT JOIN not (yet) supported */
  83913. assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
  83914. if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
  83915. ExprSetProperty(pExpr, EP_CanBeNull);
  83916. }
  83917. pSchema = pExpr->pTab->pSchema;
  83918. }
  83919. } /* if( pSrcList ) */
  83920. #ifndef SQLITE_OMIT_TRIGGER
  83921. /* If we have not already resolved the name, then maybe
  83922. ** it is a new.* or old.* trigger argument reference
  83923. */
  83924. if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
  83925. int op = pParse->eTriggerOp;
  83926. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  83927. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  83928. pExpr->iTable = 1;
  83929. pTab = pParse->pTriggerTab;
  83930. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  83931. pExpr->iTable = 0;
  83932. pTab = pParse->pTriggerTab;
  83933. }else{
  83934. pTab = 0;
  83935. }
  83936. if( pTab ){
  83937. int iCol;
  83938. pSchema = pTab->pSchema;
  83939. cntTab++;
  83940. for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
  83941. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  83942. if( iCol==pTab->iPKey ){
  83943. iCol = -1;
  83944. }
  83945. break;
  83946. }
  83947. }
  83948. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
  83949. /* IMP: R-51414-32910 */
  83950. iCol = -1;
  83951. }
  83952. if( iCol<pTab->nCol ){
  83953. cnt++;
  83954. if( iCol<0 ){
  83955. pExpr->affinity = SQLITE_AFF_INTEGER;
  83956. }else if( pExpr->iTable==0 ){
  83957. testcase( iCol==31 );
  83958. testcase( iCol==32 );
  83959. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  83960. }else{
  83961. testcase( iCol==31 );
  83962. testcase( iCol==32 );
  83963. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  83964. }
  83965. pExpr->iColumn = (i16)iCol;
  83966. pExpr->pTab = pTab;
  83967. isTrigger = 1;
  83968. }
  83969. }
  83970. }
  83971. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  83972. /*
  83973. ** Perhaps the name is a reference to the ROWID
  83974. */
  83975. if( cnt==0
  83976. && cntTab==1
  83977. && pMatch
  83978. && (pNC->ncFlags & NC_IdxExpr)==0
  83979. && sqlite3IsRowid(zCol)
  83980. && VisibleRowid(pMatch->pTab)
  83981. ){
  83982. cnt = 1;
  83983. pExpr->iColumn = -1;
  83984. pExpr->affinity = SQLITE_AFF_INTEGER;
  83985. }
  83986. /*
  83987. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  83988. ** might refer to an result-set alias. This happens, for example, when
  83989. ** we are resolving names in the WHERE clause of the following command:
  83990. **
  83991. ** SELECT a+b AS x FROM table WHERE x<10;
  83992. **
  83993. ** In cases like this, replace pExpr with a copy of the expression that
  83994. ** forms the result set entry ("a+b" in the example) and return immediately.
  83995. ** Note that the expression in the result set should have already been
  83996. ** resolved by the time the WHERE clause is resolved.
  83997. **
  83998. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  83999. ** or HAVING clauses, or as part of a larger expression in the ORDER BY
  84000. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  84001. ** is supported for backwards compatibility only. Hence, we issue a warning
  84002. ** on sqlite3_log() whenever the capability is used.
  84003. */
  84004. if( (pEList = pNC->pEList)!=0
  84005. && zTab==0
  84006. && cnt==0
  84007. ){
  84008. for(j=0; j<pEList->nExpr; j++){
  84009. char *zAs = pEList->a[j].zName;
  84010. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  84011. Expr *pOrig;
  84012. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  84013. assert( pExpr->x.pList==0 );
  84014. assert( pExpr->x.pSelect==0 );
  84015. pOrig = pEList->a[j].pExpr;
  84016. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  84017. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  84018. return WRC_Abort;
  84019. }
  84020. if( sqlite3ExprVectorSize(pOrig)!=1 ){
  84021. sqlite3ErrorMsg(pParse, "row value misused");
  84022. return WRC_Abort;
  84023. }
  84024. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  84025. cnt = 1;
  84026. pMatch = 0;
  84027. assert( zTab==0 && zDb==0 );
  84028. goto lookupname_end;
  84029. }
  84030. }
  84031. }
  84032. /* Advance to the next name context. The loop will exit when either
  84033. ** we have a match (cnt>0) or when we run out of name contexts.
  84034. */
  84035. if( cnt ) break;
  84036. pNC = pNC->pNext;
  84037. nSubquery++;
  84038. }while( pNC );
  84039. /*
  84040. ** If X and Y are NULL (in other words if only the column name Z is
  84041. ** supplied) and the value of Z is enclosed in double-quotes, then
  84042. ** Z is a string literal if it doesn't match any column names. In that
  84043. ** case, we need to return right away and not make any changes to
  84044. ** pExpr.
  84045. **
  84046. ** Because no reference was made to outer contexts, the pNC->nRef
  84047. ** fields are not changed in any context.
  84048. */
  84049. if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
  84050. pExpr->op = TK_STRING;
  84051. pExpr->pTab = 0;
  84052. return WRC_Prune;
  84053. }
  84054. /*
  84055. ** cnt==0 means there was not match. cnt>1 means there were two or
  84056. ** more matches. Either way, we have an error.
  84057. */
  84058. if( cnt!=1 ){
  84059. const char *zErr;
  84060. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  84061. if( zDb ){
  84062. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  84063. }else if( zTab ){
  84064. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  84065. }else{
  84066. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  84067. }
  84068. pParse->checkSchema = 1;
  84069. pTopNC->nErr++;
  84070. }
  84071. /* If a column from a table in pSrcList is referenced, then record
  84072. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  84073. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  84074. ** column number is greater than the number of bits in the bitmask
  84075. ** then set the high-order bit of the bitmask.
  84076. */
  84077. if( pExpr->iColumn>=0 && pMatch!=0 ){
  84078. int n = pExpr->iColumn;
  84079. testcase( n==BMS-1 );
  84080. if( n>=BMS ){
  84081. n = BMS-1;
  84082. }
  84083. assert( pMatch->iCursor==pExpr->iTable );
  84084. pMatch->colUsed |= ((Bitmask)1)<<n;
  84085. }
  84086. /* Clean up and return
  84087. */
  84088. sqlite3ExprDelete(db, pExpr->pLeft);
  84089. pExpr->pLeft = 0;
  84090. sqlite3ExprDelete(db, pExpr->pRight);
  84091. pExpr->pRight = 0;
  84092. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  84093. lookupname_end:
  84094. if( cnt==1 ){
  84095. assert( pNC!=0 );
  84096. if( !ExprHasProperty(pExpr, EP_Alias) ){
  84097. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  84098. }
  84099. /* Increment the nRef value on all name contexts from TopNC up to
  84100. ** the point where the name matched. */
  84101. for(;;){
  84102. assert( pTopNC!=0 );
  84103. pTopNC->nRef++;
  84104. if( pTopNC==pNC ) break;
  84105. pTopNC = pTopNC->pNext;
  84106. }
  84107. return WRC_Prune;
  84108. } else {
  84109. return WRC_Abort;
  84110. }
  84111. }
  84112. /*
  84113. ** Allocate and return a pointer to an expression to load the column iCol
  84114. ** from datasource iSrc in SrcList pSrc.
  84115. */
  84116. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  84117. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  84118. if( p ){
  84119. struct SrcList_item *pItem = &pSrc->a[iSrc];
  84120. p->pTab = pItem->pTab;
  84121. p->iTable = pItem->iCursor;
  84122. if( p->pTab->iPKey==iCol ){
  84123. p->iColumn = -1;
  84124. }else{
  84125. p->iColumn = (ynVar)iCol;
  84126. testcase( iCol==BMS );
  84127. testcase( iCol==BMS-1 );
  84128. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  84129. }
  84130. ExprSetProperty(p, EP_Resolved);
  84131. }
  84132. return p;
  84133. }
  84134. /*
  84135. ** Report an error that an expression is not valid for some set of
  84136. ** pNC->ncFlags values determined by validMask.
  84137. */
  84138. static void notValid(
  84139. Parse *pParse, /* Leave error message here */
  84140. NameContext *pNC, /* The name context */
  84141. const char *zMsg, /* Type of error */
  84142. int validMask /* Set of contexts for which prohibited */
  84143. ){
  84144. assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
  84145. if( (pNC->ncFlags & validMask)!=0 ){
  84146. const char *zIn = "partial index WHERE clauses";
  84147. if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
  84148. #ifndef SQLITE_OMIT_CHECK
  84149. else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
  84150. #endif
  84151. sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
  84152. }
  84153. }
  84154. /*
  84155. ** Expression p should encode a floating point value between 1.0 and 0.0.
  84156. ** Return 1024 times this value. Or return -1 if p is not a floating point
  84157. ** value between 1.0 and 0.0.
  84158. */
  84159. static int exprProbability(Expr *p){
  84160. double r = -1.0;
  84161. if( p->op!=TK_FLOAT ) return -1;
  84162. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  84163. assert( r>=0.0 );
  84164. if( r>1.0 ) return -1;
  84165. return (int)(r*134217728.0);
  84166. }
  84167. /*
  84168. ** This routine is callback for sqlite3WalkExpr().
  84169. **
  84170. ** Resolve symbolic names into TK_COLUMN operators for the current
  84171. ** node in the expression tree. Return 0 to continue the search down
  84172. ** the tree or 2 to abort the tree walk.
  84173. **
  84174. ** This routine also does error checking and name resolution for
  84175. ** function names. The operator for aggregate functions is changed
  84176. ** to TK_AGG_FUNCTION.
  84177. */
  84178. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  84179. NameContext *pNC;
  84180. Parse *pParse;
  84181. pNC = pWalker->u.pNC;
  84182. assert( pNC!=0 );
  84183. pParse = pNC->pParse;
  84184. assert( pParse==pWalker->pParse );
  84185. if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  84186. ExprSetProperty(pExpr, EP_Resolved);
  84187. #ifndef NDEBUG
  84188. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  84189. SrcList *pSrcList = pNC->pSrcList;
  84190. int i;
  84191. for(i=0; i<pNC->pSrcList->nSrc; i++){
  84192. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  84193. }
  84194. }
  84195. #endif
  84196. switch( pExpr->op ){
  84197. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  84198. /* The special operator TK_ROW means use the rowid for the first
  84199. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  84200. ** clause processing on UPDATE and DELETE statements.
  84201. */
  84202. case TK_ROW: {
  84203. SrcList *pSrcList = pNC->pSrcList;
  84204. struct SrcList_item *pItem;
  84205. assert( pSrcList && pSrcList->nSrc==1 );
  84206. pItem = pSrcList->a;
  84207. pExpr->op = TK_COLUMN;
  84208. pExpr->pTab = pItem->pTab;
  84209. pExpr->iTable = pItem->iCursor;
  84210. pExpr->iColumn = -1;
  84211. pExpr->affinity = SQLITE_AFF_INTEGER;
  84212. break;
  84213. }
  84214. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  84215. && !defined(SQLITE_OMIT_SUBQUERY) */
  84216. /* A column name: ID
  84217. ** Or table name and column name: ID.ID
  84218. ** Or a database, table and column: ID.ID.ID
  84219. **
  84220. ** The TK_ID and TK_OUT cases are combined so that there will only
  84221. ** be one call to lookupName(). Then the compiler will in-line
  84222. ** lookupName() for a size reduction and performance increase.
  84223. */
  84224. case TK_ID:
  84225. case TK_DOT: {
  84226. const char *zColumn;
  84227. const char *zTable;
  84228. const char *zDb;
  84229. Expr *pRight;
  84230. if( pExpr->op==TK_ID ){
  84231. zDb = 0;
  84232. zTable = 0;
  84233. zColumn = pExpr->u.zToken;
  84234. }else{
  84235. notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
  84236. pRight = pExpr->pRight;
  84237. if( pRight->op==TK_ID ){
  84238. zDb = 0;
  84239. zTable = pExpr->pLeft->u.zToken;
  84240. zColumn = pRight->u.zToken;
  84241. }else{
  84242. assert( pRight->op==TK_DOT );
  84243. zDb = pExpr->pLeft->u.zToken;
  84244. zTable = pRight->pLeft->u.zToken;
  84245. zColumn = pRight->pRight->u.zToken;
  84246. }
  84247. }
  84248. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  84249. }
  84250. /* Resolve function names
  84251. */
  84252. case TK_FUNCTION: {
  84253. ExprList *pList = pExpr->x.pList; /* The argument list */
  84254. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  84255. int no_such_func = 0; /* True if no such function exists */
  84256. int wrong_num_args = 0; /* True if wrong number of arguments */
  84257. int is_agg = 0; /* True if is an aggregate function */
  84258. int nId; /* Number of characters in function name */
  84259. const char *zId; /* The function name. */
  84260. FuncDef *pDef; /* Information about the function */
  84261. u8 enc = ENC(pParse->db); /* The database encoding */
  84262. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  84263. zId = pExpr->u.zToken;
  84264. nId = sqlite3Strlen30(zId);
  84265. pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
  84266. if( pDef==0 ){
  84267. pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
  84268. if( pDef==0 ){
  84269. no_such_func = 1;
  84270. }else{
  84271. wrong_num_args = 1;
  84272. }
  84273. }else{
  84274. is_agg = pDef->xFinalize!=0;
  84275. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  84276. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  84277. if( n==2 ){
  84278. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  84279. if( pExpr->iTable<0 ){
  84280. sqlite3ErrorMsg(pParse,
  84281. "second argument to likelihood() must be a "
  84282. "constant between 0.0 and 1.0");
  84283. pNC->nErr++;
  84284. }
  84285. }else{
  84286. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
  84287. ** equivalent to likelihood(X, 0.0625).
  84288. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
  84289. ** short-hand for likelihood(X,0.0625).
  84290. ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
  84291. ** for likelihood(X,0.9375).
  84292. ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
  84293. ** to likelihood(X,0.9375). */
  84294. /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
  84295. pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
  84296. }
  84297. }
  84298. #ifndef SQLITE_OMIT_AUTHORIZATION
  84299. {
  84300. int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
  84301. if( auth!=SQLITE_OK ){
  84302. if( auth==SQLITE_DENY ){
  84303. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  84304. pDef->zName);
  84305. pNC->nErr++;
  84306. }
  84307. pExpr->op = TK_NULL;
  84308. return WRC_Prune;
  84309. }
  84310. }
  84311. #endif
  84312. if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
  84313. /* For the purposes of the EP_ConstFunc flag, date and time
  84314. ** functions and other functions that change slowly are considered
  84315. ** constant because they are constant for the duration of one query */
  84316. ExprSetProperty(pExpr,EP_ConstFunc);
  84317. }
  84318. if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
  84319. /* Date/time functions that use 'now', and other functions like
  84320. ** sqlite_version() that might change over time cannot be used
  84321. ** in an index. */
  84322. notValid(pParse, pNC, "non-deterministic functions",
  84323. NC_IdxExpr|NC_PartIdx);
  84324. }
  84325. }
  84326. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  84327. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  84328. pNC->nErr++;
  84329. is_agg = 0;
  84330. }else if( no_such_func && pParse->db->init.busy==0
  84331. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  84332. && pParse->explain==0
  84333. #endif
  84334. ){
  84335. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  84336. pNC->nErr++;
  84337. }else if( wrong_num_args ){
  84338. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  84339. nId, zId);
  84340. pNC->nErr++;
  84341. }
  84342. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  84343. sqlite3WalkExprList(pWalker, pList);
  84344. if( is_agg ){
  84345. NameContext *pNC2 = pNC;
  84346. pExpr->op = TK_AGG_FUNCTION;
  84347. pExpr->op2 = 0;
  84348. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  84349. pExpr->op2++;
  84350. pNC2 = pNC2->pNext;
  84351. }
  84352. assert( pDef!=0 );
  84353. if( pNC2 ){
  84354. assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
  84355. testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
  84356. pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
  84357. }
  84358. pNC->ncFlags |= NC_AllowAgg;
  84359. }
  84360. /* FIX ME: Compute pExpr->affinity based on the expected return
  84361. ** type of the function
  84362. */
  84363. return WRC_Prune;
  84364. }
  84365. #ifndef SQLITE_OMIT_SUBQUERY
  84366. case TK_SELECT:
  84367. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  84368. #endif
  84369. case TK_IN: {
  84370. testcase( pExpr->op==TK_IN );
  84371. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  84372. int nRef = pNC->nRef;
  84373. notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  84374. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  84375. assert( pNC->nRef>=nRef );
  84376. if( nRef!=pNC->nRef ){
  84377. ExprSetProperty(pExpr, EP_VarSelect);
  84378. pNC->ncFlags |= NC_VarSelect;
  84379. }
  84380. }
  84381. break;
  84382. }
  84383. case TK_VARIABLE: {
  84384. notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  84385. break;
  84386. }
  84387. case TK_BETWEEN:
  84388. case TK_EQ:
  84389. case TK_NE:
  84390. case TK_LT:
  84391. case TK_LE:
  84392. case TK_GT:
  84393. case TK_GE:
  84394. case TK_IS:
  84395. case TK_ISNOT: {
  84396. int nLeft, nRight;
  84397. if( pParse->db->mallocFailed ) break;
  84398. assert( pExpr->pLeft!=0 );
  84399. nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
  84400. if( pExpr->op==TK_BETWEEN ){
  84401. nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
  84402. if( nRight==nLeft ){
  84403. nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
  84404. }
  84405. }else{
  84406. assert( pExpr->pRight!=0 );
  84407. nRight = sqlite3ExprVectorSize(pExpr->pRight);
  84408. }
  84409. if( nLeft!=nRight ){
  84410. testcase( pExpr->op==TK_EQ );
  84411. testcase( pExpr->op==TK_NE );
  84412. testcase( pExpr->op==TK_LT );
  84413. testcase( pExpr->op==TK_LE );
  84414. testcase( pExpr->op==TK_GT );
  84415. testcase( pExpr->op==TK_GE );
  84416. testcase( pExpr->op==TK_IS );
  84417. testcase( pExpr->op==TK_ISNOT );
  84418. testcase( pExpr->op==TK_BETWEEN );
  84419. sqlite3ErrorMsg(pParse, "row value misused");
  84420. }
  84421. break;
  84422. }
  84423. }
  84424. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  84425. }
  84426. /*
  84427. ** pEList is a list of expressions which are really the result set of the
  84428. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  84429. ** This routine checks to see if pE is a simple identifier which corresponds
  84430. ** to the AS-name of one of the terms of the expression list. If it is,
  84431. ** this routine return an integer between 1 and N where N is the number of
  84432. ** elements in pEList, corresponding to the matching entry. If there is
  84433. ** no match, or if pE is not a simple identifier, then this routine
  84434. ** return 0.
  84435. **
  84436. ** pEList has been resolved. pE has not.
  84437. */
  84438. static int resolveAsName(
  84439. Parse *pParse, /* Parsing context for error messages */
  84440. ExprList *pEList, /* List of expressions to scan */
  84441. Expr *pE /* Expression we are trying to match */
  84442. ){
  84443. int i; /* Loop counter */
  84444. UNUSED_PARAMETER(pParse);
  84445. if( pE->op==TK_ID ){
  84446. char *zCol = pE->u.zToken;
  84447. for(i=0; i<pEList->nExpr; i++){
  84448. char *zAs = pEList->a[i].zName;
  84449. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  84450. return i+1;
  84451. }
  84452. }
  84453. }
  84454. return 0;
  84455. }
  84456. /*
  84457. ** pE is a pointer to an expression which is a single term in the
  84458. ** ORDER BY of a compound SELECT. The expression has not been
  84459. ** name resolved.
  84460. **
  84461. ** At the point this routine is called, we already know that the
  84462. ** ORDER BY term is not an integer index into the result set. That
  84463. ** case is handled by the calling routine.
  84464. **
  84465. ** Attempt to match pE against result set columns in the left-most
  84466. ** SELECT statement. Return the index i of the matching column,
  84467. ** as an indication to the caller that it should sort by the i-th column.
  84468. ** The left-most column is 1. In other words, the value returned is the
  84469. ** same integer value that would be used in the SQL statement to indicate
  84470. ** the column.
  84471. **
  84472. ** If there is no match, return 0. Return -1 if an error occurs.
  84473. */
  84474. static int resolveOrderByTermToExprList(
  84475. Parse *pParse, /* Parsing context for error messages */
  84476. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  84477. Expr *pE /* The specific ORDER BY term */
  84478. ){
  84479. int i; /* Loop counter */
  84480. ExprList *pEList; /* The columns of the result set */
  84481. NameContext nc; /* Name context for resolving pE */
  84482. sqlite3 *db; /* Database connection */
  84483. int rc; /* Return code from subprocedures */
  84484. u8 savedSuppErr; /* Saved value of db->suppressErr */
  84485. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  84486. pEList = pSelect->pEList;
  84487. /* Resolve all names in the ORDER BY term expression
  84488. */
  84489. memset(&nc, 0, sizeof(nc));
  84490. nc.pParse = pParse;
  84491. nc.pSrcList = pSelect->pSrc;
  84492. nc.pEList = pEList;
  84493. nc.ncFlags = NC_AllowAgg;
  84494. nc.nErr = 0;
  84495. db = pParse->db;
  84496. savedSuppErr = db->suppressErr;
  84497. db->suppressErr = 1;
  84498. rc = sqlite3ResolveExprNames(&nc, pE);
  84499. db->suppressErr = savedSuppErr;
  84500. if( rc ) return 0;
  84501. /* Try to match the ORDER BY expression against an expression
  84502. ** in the result set. Return an 1-based index of the matching
  84503. ** result-set entry.
  84504. */
  84505. for(i=0; i<pEList->nExpr; i++){
  84506. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
  84507. return i+1;
  84508. }
  84509. }
  84510. /* If no match, return 0. */
  84511. return 0;
  84512. }
  84513. /*
  84514. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  84515. */
  84516. static void resolveOutOfRangeError(
  84517. Parse *pParse, /* The error context into which to write the error */
  84518. const char *zType, /* "ORDER" or "GROUP" */
  84519. int i, /* The index (1-based) of the term out of range */
  84520. int mx /* Largest permissible value of i */
  84521. ){
  84522. sqlite3ErrorMsg(pParse,
  84523. "%r %s BY term out of range - should be "
  84524. "between 1 and %d", i, zType, mx);
  84525. }
  84526. /*
  84527. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  84528. ** each term of the ORDER BY clause is a constant integer between 1
  84529. ** and N where N is the number of columns in the compound SELECT.
  84530. **
  84531. ** ORDER BY terms that are already an integer between 1 and N are
  84532. ** unmodified. ORDER BY terms that are integers outside the range of
  84533. ** 1 through N generate an error. ORDER BY terms that are expressions
  84534. ** are matched against result set expressions of compound SELECT
  84535. ** beginning with the left-most SELECT and working toward the right.
  84536. ** At the first match, the ORDER BY expression is transformed into
  84537. ** the integer column number.
  84538. **
  84539. ** Return the number of errors seen.
  84540. */
  84541. static int resolveCompoundOrderBy(
  84542. Parse *pParse, /* Parsing context. Leave error messages here */
  84543. Select *pSelect /* The SELECT statement containing the ORDER BY */
  84544. ){
  84545. int i;
  84546. ExprList *pOrderBy;
  84547. ExprList *pEList;
  84548. sqlite3 *db;
  84549. int moreToDo = 1;
  84550. pOrderBy = pSelect->pOrderBy;
  84551. if( pOrderBy==0 ) return 0;
  84552. db = pParse->db;
  84553. #if SQLITE_MAX_COLUMN
  84554. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  84555. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  84556. return 1;
  84557. }
  84558. #endif
  84559. for(i=0; i<pOrderBy->nExpr; i++){
  84560. pOrderBy->a[i].done = 0;
  84561. }
  84562. pSelect->pNext = 0;
  84563. while( pSelect->pPrior ){
  84564. pSelect->pPrior->pNext = pSelect;
  84565. pSelect = pSelect->pPrior;
  84566. }
  84567. while( pSelect && moreToDo ){
  84568. struct ExprList_item *pItem;
  84569. moreToDo = 0;
  84570. pEList = pSelect->pEList;
  84571. assert( pEList!=0 );
  84572. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  84573. int iCol = -1;
  84574. Expr *pE, *pDup;
  84575. if( pItem->done ) continue;
  84576. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  84577. if( sqlite3ExprIsInteger(pE, &iCol) ){
  84578. if( iCol<=0 || iCol>pEList->nExpr ){
  84579. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  84580. return 1;
  84581. }
  84582. }else{
  84583. iCol = resolveAsName(pParse, pEList, pE);
  84584. if( iCol==0 ){
  84585. pDup = sqlite3ExprDup(db, pE, 0);
  84586. if( !db->mallocFailed ){
  84587. assert(pDup);
  84588. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  84589. }
  84590. sqlite3ExprDelete(db, pDup);
  84591. }
  84592. }
  84593. if( iCol>0 ){
  84594. /* Convert the ORDER BY term into an integer column number iCol,
  84595. ** taking care to preserve the COLLATE clause if it exists */
  84596. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  84597. if( pNew==0 ) return 1;
  84598. pNew->flags |= EP_IntValue;
  84599. pNew->u.iValue = iCol;
  84600. if( pItem->pExpr==pE ){
  84601. pItem->pExpr = pNew;
  84602. }else{
  84603. Expr *pParent = pItem->pExpr;
  84604. assert( pParent->op==TK_COLLATE );
  84605. while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
  84606. assert( pParent->pLeft==pE );
  84607. pParent->pLeft = pNew;
  84608. }
  84609. sqlite3ExprDelete(db, pE);
  84610. pItem->u.x.iOrderByCol = (u16)iCol;
  84611. pItem->done = 1;
  84612. }else{
  84613. moreToDo = 1;
  84614. }
  84615. }
  84616. pSelect = pSelect->pNext;
  84617. }
  84618. for(i=0; i<pOrderBy->nExpr; i++){
  84619. if( pOrderBy->a[i].done==0 ){
  84620. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  84621. "column in the result set", i+1);
  84622. return 1;
  84623. }
  84624. }
  84625. return 0;
  84626. }
  84627. /*
  84628. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  84629. ** the SELECT statement pSelect. If any term is reference to a
  84630. ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
  84631. ** field) then convert that term into a copy of the corresponding result set
  84632. ** column.
  84633. **
  84634. ** If any errors are detected, add an error message to pParse and
  84635. ** return non-zero. Return zero if no errors are seen.
  84636. */
  84637. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  84638. Parse *pParse, /* Parsing context. Leave error messages here */
  84639. Select *pSelect, /* The SELECT statement containing the clause */
  84640. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  84641. const char *zType /* "ORDER" or "GROUP" */
  84642. ){
  84643. int i;
  84644. sqlite3 *db = pParse->db;
  84645. ExprList *pEList;
  84646. struct ExprList_item *pItem;
  84647. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  84648. #if SQLITE_MAX_COLUMN
  84649. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  84650. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  84651. return 1;
  84652. }
  84653. #endif
  84654. pEList = pSelect->pEList;
  84655. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  84656. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  84657. if( pItem->u.x.iOrderByCol ){
  84658. if( pItem->u.x.iOrderByCol>pEList->nExpr ){
  84659. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  84660. return 1;
  84661. }
  84662. resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
  84663. zType,0);
  84664. }
  84665. }
  84666. return 0;
  84667. }
  84668. /*
  84669. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  84670. ** The Name context of the SELECT statement is pNC. zType is either
  84671. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  84672. **
  84673. ** This routine resolves each term of the clause into an expression.
  84674. ** If the order-by term is an integer I between 1 and N (where N is the
  84675. ** number of columns in the result set of the SELECT) then the expression
  84676. ** in the resolution is a copy of the I-th result-set expression. If
  84677. ** the order-by term is an identifier that corresponds to the AS-name of
  84678. ** a result-set expression, then the term resolves to a copy of the
  84679. ** result-set expression. Otherwise, the expression is resolved in
  84680. ** the usual way - using sqlite3ResolveExprNames().
  84681. **
  84682. ** This routine returns the number of errors. If errors occur, then
  84683. ** an appropriate error message might be left in pParse. (OOM errors
  84684. ** excepted.)
  84685. */
  84686. static int resolveOrderGroupBy(
  84687. NameContext *pNC, /* The name context of the SELECT statement */
  84688. Select *pSelect, /* The SELECT statement holding pOrderBy */
  84689. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  84690. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  84691. ){
  84692. int i, j; /* Loop counters */
  84693. int iCol; /* Column number */
  84694. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  84695. Parse *pParse; /* Parsing context */
  84696. int nResult; /* Number of terms in the result set */
  84697. if( pOrderBy==0 ) return 0;
  84698. nResult = pSelect->pEList->nExpr;
  84699. pParse = pNC->pParse;
  84700. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  84701. Expr *pE = pItem->pExpr;
  84702. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  84703. if( zType[0]!='G' ){
  84704. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  84705. if( iCol>0 ){
  84706. /* If an AS-name match is found, mark this ORDER BY column as being
  84707. ** a copy of the iCol-th result-set column. The subsequent call to
  84708. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  84709. ** copy of the iCol-th result-set expression. */
  84710. pItem->u.x.iOrderByCol = (u16)iCol;
  84711. continue;
  84712. }
  84713. }
  84714. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  84715. /* The ORDER BY term is an integer constant. Again, set the column
  84716. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  84717. ** order-by term to a copy of the result-set expression */
  84718. if( iCol<1 || iCol>0xffff ){
  84719. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  84720. return 1;
  84721. }
  84722. pItem->u.x.iOrderByCol = (u16)iCol;
  84723. continue;
  84724. }
  84725. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  84726. pItem->u.x.iOrderByCol = 0;
  84727. if( sqlite3ResolveExprNames(pNC, pE) ){
  84728. return 1;
  84729. }
  84730. for(j=0; j<pSelect->pEList->nExpr; j++){
  84731. if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  84732. pItem->u.x.iOrderByCol = j+1;
  84733. }
  84734. }
  84735. }
  84736. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  84737. }
  84738. /*
  84739. ** Resolve names in the SELECT statement p and all of its descendants.
  84740. */
  84741. static int resolveSelectStep(Walker *pWalker, Select *p){
  84742. NameContext *pOuterNC; /* Context that contains this SELECT */
  84743. NameContext sNC; /* Name context of this SELECT */
  84744. int isCompound; /* True if p is a compound select */
  84745. int nCompound; /* Number of compound terms processed so far */
  84746. Parse *pParse; /* Parsing context */
  84747. int i; /* Loop counter */
  84748. ExprList *pGroupBy; /* The GROUP BY clause */
  84749. Select *pLeftmost; /* Left-most of SELECT of a compound */
  84750. sqlite3 *db; /* Database connection */
  84751. assert( p!=0 );
  84752. if( p->selFlags & SF_Resolved ){
  84753. return WRC_Prune;
  84754. }
  84755. pOuterNC = pWalker->u.pNC;
  84756. pParse = pWalker->pParse;
  84757. db = pParse->db;
  84758. /* Normally sqlite3SelectExpand() will be called first and will have
  84759. ** already expanded this SELECT. However, if this is a subquery within
  84760. ** an expression, sqlite3ResolveExprNames() will be called without a
  84761. ** prior call to sqlite3SelectExpand(). When that happens, let
  84762. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  84763. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  84764. ** this routine in the correct order.
  84765. */
  84766. if( (p->selFlags & SF_Expanded)==0 ){
  84767. sqlite3SelectPrep(pParse, p, pOuterNC);
  84768. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  84769. }
  84770. isCompound = p->pPrior!=0;
  84771. nCompound = 0;
  84772. pLeftmost = p;
  84773. while( p ){
  84774. assert( (p->selFlags & SF_Expanded)!=0 );
  84775. assert( (p->selFlags & SF_Resolved)==0 );
  84776. p->selFlags |= SF_Resolved;
  84777. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  84778. ** are not allowed to refer to any names, so pass an empty NameContext.
  84779. */
  84780. memset(&sNC, 0, sizeof(sNC));
  84781. sNC.pParse = pParse;
  84782. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  84783. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  84784. return WRC_Abort;
  84785. }
  84786. /* If the SF_Converted flags is set, then this Select object was
  84787. ** was created by the convertCompoundSelectToSubquery() function.
  84788. ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
  84789. ** as if it were part of the sub-query, not the parent. This block
  84790. ** moves the pOrderBy down to the sub-query. It will be moved back
  84791. ** after the names have been resolved. */
  84792. if( p->selFlags & SF_Converted ){
  84793. Select *pSub = p->pSrc->a[0].pSelect;
  84794. assert( p->pSrc->nSrc==1 && p->pOrderBy );
  84795. assert( pSub->pPrior && pSub->pOrderBy==0 );
  84796. pSub->pOrderBy = p->pOrderBy;
  84797. p->pOrderBy = 0;
  84798. }
  84799. /* Recursively resolve names in all subqueries
  84800. */
  84801. for(i=0; i<p->pSrc->nSrc; i++){
  84802. struct SrcList_item *pItem = &p->pSrc->a[i];
  84803. if( pItem->pSelect ){
  84804. NameContext *pNC; /* Used to iterate name contexts */
  84805. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  84806. const char *zSavedContext = pParse->zAuthContext;
  84807. /* Count the total number of references to pOuterNC and all of its
  84808. ** parent contexts. After resolving references to expressions in
  84809. ** pItem->pSelect, check if this value has changed. If so, then
  84810. ** SELECT statement pItem->pSelect must be correlated. Set the
  84811. ** pItem->fg.isCorrelated flag if this is the case. */
  84812. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  84813. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  84814. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  84815. pParse->zAuthContext = zSavedContext;
  84816. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  84817. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  84818. assert( pItem->fg.isCorrelated==0 && nRef<=0 );
  84819. pItem->fg.isCorrelated = (nRef!=0);
  84820. }
  84821. }
  84822. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  84823. ** resolve the result-set expression list.
  84824. */
  84825. sNC.ncFlags = NC_AllowAgg;
  84826. sNC.pSrcList = p->pSrc;
  84827. sNC.pNext = pOuterNC;
  84828. /* Resolve names in the result set. */
  84829. if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
  84830. /* If there are no aggregate functions in the result-set, and no GROUP BY
  84831. ** expression, do not allow aggregates in any of the other expressions.
  84832. */
  84833. assert( (p->selFlags & SF_Aggregate)==0 );
  84834. pGroupBy = p->pGroupBy;
  84835. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  84836. assert( NC_MinMaxAgg==SF_MinMaxAgg );
  84837. p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
  84838. }else{
  84839. sNC.ncFlags &= ~NC_AllowAgg;
  84840. }
  84841. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  84842. */
  84843. if( p->pHaving && !pGroupBy ){
  84844. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  84845. return WRC_Abort;
  84846. }
  84847. /* Add the output column list to the name-context before parsing the
  84848. ** other expressions in the SELECT statement. This is so that
  84849. ** expressions in the WHERE clause (etc.) can refer to expressions by
  84850. ** aliases in the result set.
  84851. **
  84852. ** Minor point: If this is the case, then the expression will be
  84853. ** re-evaluated for each reference to it.
  84854. */
  84855. sNC.pEList = p->pEList;
  84856. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  84857. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  84858. /* Resolve names in table-valued-function arguments */
  84859. for(i=0; i<p->pSrc->nSrc; i++){
  84860. struct SrcList_item *pItem = &p->pSrc->a[i];
  84861. if( pItem->fg.isTabFunc
  84862. && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
  84863. ){
  84864. return WRC_Abort;
  84865. }
  84866. }
  84867. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  84868. ** outer queries
  84869. */
  84870. sNC.pNext = 0;
  84871. sNC.ncFlags |= NC_AllowAgg;
  84872. /* If this is a converted compound query, move the ORDER BY clause from
  84873. ** the sub-query back to the parent query. At this point each term
  84874. ** within the ORDER BY clause has been transformed to an integer value.
  84875. ** These integers will be replaced by copies of the corresponding result
  84876. ** set expressions by the call to resolveOrderGroupBy() below. */
  84877. if( p->selFlags & SF_Converted ){
  84878. Select *pSub = p->pSrc->a[0].pSelect;
  84879. p->pOrderBy = pSub->pOrderBy;
  84880. pSub->pOrderBy = 0;
  84881. }
  84882. /* Process the ORDER BY clause for singleton SELECT statements.
  84883. ** The ORDER BY clause for compounds SELECT statements is handled
  84884. ** below, after all of the result-sets for all of the elements of
  84885. ** the compound have been resolved.
  84886. **
  84887. ** If there is an ORDER BY clause on a term of a compound-select other
  84888. ** than the right-most term, then that is a syntax error. But the error
  84889. ** is not detected until much later, and so we need to go ahead and
  84890. ** resolve those symbols on the incorrect ORDER BY for consistency.
  84891. */
  84892. if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
  84893. && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
  84894. ){
  84895. return WRC_Abort;
  84896. }
  84897. if( db->mallocFailed ){
  84898. return WRC_Abort;
  84899. }
  84900. /* Resolve the GROUP BY clause. At the same time, make sure
  84901. ** the GROUP BY clause does not contain aggregate functions.
  84902. */
  84903. if( pGroupBy ){
  84904. struct ExprList_item *pItem;
  84905. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  84906. return WRC_Abort;
  84907. }
  84908. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  84909. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  84910. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  84911. "the GROUP BY clause");
  84912. return WRC_Abort;
  84913. }
  84914. }
  84915. }
  84916. /* If this is part of a compound SELECT, check that it has the right
  84917. ** number of expressions in the select list. */
  84918. if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
  84919. sqlite3SelectWrongNumTermsError(pParse, p->pNext);
  84920. return WRC_Abort;
  84921. }
  84922. /* Advance to the next term of the compound
  84923. */
  84924. p = p->pPrior;
  84925. nCompound++;
  84926. }
  84927. /* Resolve the ORDER BY on a compound SELECT after all terms of
  84928. ** the compound have been resolved.
  84929. */
  84930. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  84931. return WRC_Abort;
  84932. }
  84933. return WRC_Prune;
  84934. }
  84935. /*
  84936. ** This routine walks an expression tree and resolves references to
  84937. ** table columns and result-set columns. At the same time, do error
  84938. ** checking on function usage and set a flag if any aggregate functions
  84939. ** are seen.
  84940. **
  84941. ** To resolve table columns references we look for nodes (or subtrees) of the
  84942. ** form X.Y.Z or Y.Z or just Z where
  84943. **
  84944. ** X: The name of a database. Ex: "main" or "temp" or
  84945. ** the symbolic name assigned to an ATTACH-ed database.
  84946. **
  84947. ** Y: The name of a table in a FROM clause. Or in a trigger
  84948. ** one of the special names "old" or "new".
  84949. **
  84950. ** Z: The name of a column in table Y.
  84951. **
  84952. ** The node at the root of the subtree is modified as follows:
  84953. **
  84954. ** Expr.op Changed to TK_COLUMN
  84955. ** Expr.pTab Points to the Table object for X.Y
  84956. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  84957. ** Expr.iTable The VDBE cursor number for X.Y
  84958. **
  84959. **
  84960. ** To resolve result-set references, look for expression nodes of the
  84961. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  84962. ** size of an AS clause in the result-set of a SELECT. The Z expression
  84963. ** is replaced by a copy of the left-hand side of the result-set expression.
  84964. ** Table-name and function resolution occurs on the substituted expression
  84965. ** tree. For example, in:
  84966. **
  84967. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  84968. **
  84969. ** The "x" term of the order by is replaced by "a+b" to render:
  84970. **
  84971. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  84972. **
  84973. ** Function calls are checked to make sure that the function is
  84974. ** defined and that the correct number of arguments are specified.
  84975. ** If the function is an aggregate function, then the NC_HasAgg flag is
  84976. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  84977. ** If an expression contains aggregate functions then the EP_Agg
  84978. ** property on the expression is set.
  84979. **
  84980. ** An error message is left in pParse if anything is amiss. The number
  84981. ** if errors is returned.
  84982. */
  84983. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  84984. NameContext *pNC, /* Namespace to resolve expressions in. */
  84985. Expr *pExpr /* The expression to be analyzed. */
  84986. ){
  84987. u16 savedHasAgg;
  84988. Walker w;
  84989. if( pExpr==0 ) return 0;
  84990. #if SQLITE_MAX_EXPR_DEPTH>0
  84991. {
  84992. Parse *pParse = pNC->pParse;
  84993. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  84994. return 1;
  84995. }
  84996. pParse->nHeight += pExpr->nHeight;
  84997. }
  84998. #endif
  84999. savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
  85000. pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
  85001. w.pParse = pNC->pParse;
  85002. w.xExprCallback = resolveExprStep;
  85003. w.xSelectCallback = resolveSelectStep;
  85004. w.xSelectCallback2 = 0;
  85005. w.walkerDepth = 0;
  85006. w.eCode = 0;
  85007. w.u.pNC = pNC;
  85008. sqlite3WalkExpr(&w, pExpr);
  85009. #if SQLITE_MAX_EXPR_DEPTH>0
  85010. pNC->pParse->nHeight -= pExpr->nHeight;
  85011. #endif
  85012. if( pNC->nErr>0 || w.pParse->nErr>0 ){
  85013. ExprSetProperty(pExpr, EP_Error);
  85014. }
  85015. if( pNC->ncFlags & NC_HasAgg ){
  85016. ExprSetProperty(pExpr, EP_Agg);
  85017. }
  85018. pNC->ncFlags |= savedHasAgg;
  85019. return ExprHasProperty(pExpr, EP_Error);
  85020. }
  85021. /*
  85022. ** Resolve all names for all expression in an expression list. This is
  85023. ** just like sqlite3ResolveExprNames() except that it works for an expression
  85024. ** list rather than a single expression.
  85025. */
  85026. SQLITE_PRIVATE int sqlite3ResolveExprListNames(
  85027. NameContext *pNC, /* Namespace to resolve expressions in. */
  85028. ExprList *pList /* The expression list to be analyzed. */
  85029. ){
  85030. int i;
  85031. if( pList ){
  85032. for(i=0; i<pList->nExpr; i++){
  85033. if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
  85034. }
  85035. }
  85036. return WRC_Continue;
  85037. }
  85038. /*
  85039. ** Resolve all names in all expressions of a SELECT and in all
  85040. ** decendents of the SELECT, including compounds off of p->pPrior,
  85041. ** subqueries in expressions, and subqueries used as FROM clause
  85042. ** terms.
  85043. **
  85044. ** See sqlite3ResolveExprNames() for a description of the kinds of
  85045. ** transformations that occur.
  85046. **
  85047. ** All SELECT statements should have been expanded using
  85048. ** sqlite3SelectExpand() prior to invoking this routine.
  85049. */
  85050. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  85051. Parse *pParse, /* The parser context */
  85052. Select *p, /* The SELECT statement being coded. */
  85053. NameContext *pOuterNC /* Name context for parent SELECT statement */
  85054. ){
  85055. Walker w;
  85056. assert( p!=0 );
  85057. memset(&w, 0, sizeof(w));
  85058. w.xExprCallback = resolveExprStep;
  85059. w.xSelectCallback = resolveSelectStep;
  85060. w.pParse = pParse;
  85061. w.u.pNC = pOuterNC;
  85062. sqlite3WalkSelect(&w, p);
  85063. }
  85064. /*
  85065. ** Resolve names in expressions that can only reference a single table:
  85066. **
  85067. ** * CHECK constraints
  85068. ** * WHERE clauses on partial indices
  85069. **
  85070. ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
  85071. ** is set to -1 and the Expr.iColumn value is set to the column number.
  85072. **
  85073. ** Any errors cause an error message to be set in pParse.
  85074. */
  85075. SQLITE_PRIVATE void sqlite3ResolveSelfReference(
  85076. Parse *pParse, /* Parsing context */
  85077. Table *pTab, /* The table being referenced */
  85078. int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
  85079. Expr *pExpr, /* Expression to resolve. May be NULL. */
  85080. ExprList *pList /* Expression list to resolve. May be NUL. */
  85081. ){
  85082. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  85083. NameContext sNC; /* Name context for pParse->pNewTable */
  85084. assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
  85085. memset(&sNC, 0, sizeof(sNC));
  85086. memset(&sSrc, 0, sizeof(sSrc));
  85087. sSrc.nSrc = 1;
  85088. sSrc.a[0].zName = pTab->zName;
  85089. sSrc.a[0].pTab = pTab;
  85090. sSrc.a[0].iCursor = -1;
  85091. sNC.pParse = pParse;
  85092. sNC.pSrcList = &sSrc;
  85093. sNC.ncFlags = type;
  85094. if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
  85095. if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
  85096. }
  85097. /************** End of resolve.c *********************************************/
  85098. /************** Begin file expr.c ********************************************/
  85099. /*
  85100. ** 2001 September 15
  85101. **
  85102. ** The author disclaims copyright to this source code. In place of
  85103. ** a legal notice, here is a blessing:
  85104. **
  85105. ** May you do good and not evil.
  85106. ** May you find forgiveness for yourself and forgive others.
  85107. ** May you share freely, never taking more than you give.
  85108. **
  85109. *************************************************************************
  85110. ** This file contains routines used for analyzing expressions and
  85111. ** for generating VDBE code that evaluates expressions in SQLite.
  85112. */
  85113. /* #include "sqliteInt.h" */
  85114. /* Forward declarations */
  85115. static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
  85116. static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
  85117. /*
  85118. ** Return the affinity character for a single column of a table.
  85119. */
  85120. SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
  85121. assert( iCol<pTab->nCol );
  85122. return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
  85123. }
  85124. /*
  85125. ** Return the 'affinity' of the expression pExpr if any.
  85126. **
  85127. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  85128. ** or a sub-select with a column as the return value, then the
  85129. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  85130. ** indicating no affinity for the expression.
  85131. **
  85132. ** i.e. the WHERE clause expressions in the following statements all
  85133. ** have an affinity:
  85134. **
  85135. ** CREATE TABLE t1(a);
  85136. ** SELECT * FROM t1 WHERE a;
  85137. ** SELECT a AS b FROM t1 WHERE b;
  85138. ** SELECT * FROM t1 WHERE (select a from t1);
  85139. */
  85140. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  85141. int op;
  85142. pExpr = sqlite3ExprSkipCollate(pExpr);
  85143. if( pExpr->flags & EP_Generic ) return 0;
  85144. op = pExpr->op;
  85145. if( op==TK_SELECT ){
  85146. assert( pExpr->flags&EP_xIsSelect );
  85147. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  85148. }
  85149. if( op==TK_REGISTER ) op = pExpr->op2;
  85150. #ifndef SQLITE_OMIT_CAST
  85151. if( op==TK_CAST ){
  85152. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  85153. return sqlite3AffinityType(pExpr->u.zToken, 0);
  85154. }
  85155. #endif
  85156. if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->pTab ){
  85157. return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn);
  85158. }
  85159. if( op==TK_SELECT_COLUMN ){
  85160. assert( pExpr->pLeft->flags&EP_xIsSelect );
  85161. return sqlite3ExprAffinity(
  85162. pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
  85163. );
  85164. }
  85165. return pExpr->affinity;
  85166. }
  85167. /*
  85168. ** Set the collating sequence for expression pExpr to be the collating
  85169. ** sequence named by pToken. Return a pointer to a new Expr node that
  85170. ** implements the COLLATE operator.
  85171. **
  85172. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  85173. ** and the pExpr parameter is returned unchanged.
  85174. */
  85175. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
  85176. Parse *pParse, /* Parsing context */
  85177. Expr *pExpr, /* Add the "COLLATE" clause to this expression */
  85178. const Token *pCollName, /* Name of collating sequence */
  85179. int dequote /* True to dequote pCollName */
  85180. ){
  85181. if( pCollName->n>0 ){
  85182. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
  85183. if( pNew ){
  85184. pNew->pLeft = pExpr;
  85185. pNew->flags |= EP_Collate|EP_Skip;
  85186. pExpr = pNew;
  85187. }
  85188. }
  85189. return pExpr;
  85190. }
  85191. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  85192. Token s;
  85193. assert( zC!=0 );
  85194. sqlite3TokenInit(&s, (char*)zC);
  85195. return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
  85196. }
  85197. /*
  85198. ** Skip over any TK_COLLATE operators and any unlikely()
  85199. ** or likelihood() function at the root of an expression.
  85200. */
  85201. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  85202. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  85203. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  85204. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  85205. assert( pExpr->x.pList->nExpr>0 );
  85206. assert( pExpr->op==TK_FUNCTION );
  85207. pExpr = pExpr->x.pList->a[0].pExpr;
  85208. }else{
  85209. assert( pExpr->op==TK_COLLATE );
  85210. pExpr = pExpr->pLeft;
  85211. }
  85212. }
  85213. return pExpr;
  85214. }
  85215. /*
  85216. ** Return the collation sequence for the expression pExpr. If
  85217. ** there is no defined collating sequence, return NULL.
  85218. **
  85219. ** The collating sequence might be determined by a COLLATE operator
  85220. ** or by the presence of a column with a defined collating sequence.
  85221. ** COLLATE operators take first precedence. Left operands take
  85222. ** precedence over right operands.
  85223. */
  85224. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  85225. sqlite3 *db = pParse->db;
  85226. CollSeq *pColl = 0;
  85227. Expr *p = pExpr;
  85228. while( p ){
  85229. int op = p->op;
  85230. if( p->flags & EP_Generic ) break;
  85231. if( op==TK_CAST || op==TK_UPLUS ){
  85232. p = p->pLeft;
  85233. continue;
  85234. }
  85235. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  85236. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  85237. break;
  85238. }
  85239. if( (op==TK_AGG_COLUMN || op==TK_COLUMN
  85240. || op==TK_REGISTER || op==TK_TRIGGER)
  85241. && p->pTab!=0
  85242. ){
  85243. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  85244. ** a TK_COLUMN but was previously evaluated and cached in a register */
  85245. int j = p->iColumn;
  85246. if( j>=0 ){
  85247. const char *zColl = p->pTab->aCol[j].zColl;
  85248. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  85249. }
  85250. break;
  85251. }
  85252. if( p->flags & EP_Collate ){
  85253. if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
  85254. p = p->pLeft;
  85255. }else{
  85256. Expr *pNext = p->pRight;
  85257. /* The Expr.x union is never used at the same time as Expr.pRight */
  85258. assert( p->x.pList==0 || p->pRight==0 );
  85259. /* p->flags holds EP_Collate and p->pLeft->flags does not. And
  85260. ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
  85261. ** least one EP_Collate. Thus the following two ALWAYS. */
  85262. if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
  85263. int i;
  85264. for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
  85265. if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
  85266. pNext = p->x.pList->a[i].pExpr;
  85267. break;
  85268. }
  85269. }
  85270. }
  85271. p = pNext;
  85272. }
  85273. }else{
  85274. break;
  85275. }
  85276. }
  85277. if( sqlite3CheckCollSeq(pParse, pColl) ){
  85278. pColl = 0;
  85279. }
  85280. return pColl;
  85281. }
  85282. /*
  85283. ** pExpr is an operand of a comparison operator. aff2 is the
  85284. ** type affinity of the other operand. This routine returns the
  85285. ** type affinity that should be used for the comparison operator.
  85286. */
  85287. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  85288. char aff1 = sqlite3ExprAffinity(pExpr);
  85289. if( aff1 && aff2 ){
  85290. /* Both sides of the comparison are columns. If one has numeric
  85291. ** affinity, use that. Otherwise use no affinity.
  85292. */
  85293. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  85294. return SQLITE_AFF_NUMERIC;
  85295. }else{
  85296. return SQLITE_AFF_BLOB;
  85297. }
  85298. }else if( !aff1 && !aff2 ){
  85299. /* Neither side of the comparison is a column. Compare the
  85300. ** results directly.
  85301. */
  85302. return SQLITE_AFF_BLOB;
  85303. }else{
  85304. /* One side is a column, the other is not. Use the columns affinity. */
  85305. assert( aff1==0 || aff2==0 );
  85306. return (aff1 + aff2);
  85307. }
  85308. }
  85309. /*
  85310. ** pExpr is a comparison operator. Return the type affinity that should
  85311. ** be applied to both operands prior to doing the comparison.
  85312. */
  85313. static char comparisonAffinity(Expr *pExpr){
  85314. char aff;
  85315. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  85316. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  85317. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  85318. assert( pExpr->pLeft );
  85319. aff = sqlite3ExprAffinity(pExpr->pLeft);
  85320. if( pExpr->pRight ){
  85321. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  85322. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  85323. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  85324. }else if( aff==0 ){
  85325. aff = SQLITE_AFF_BLOB;
  85326. }
  85327. return aff;
  85328. }
  85329. /*
  85330. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  85331. ** idx_affinity is the affinity of an indexed column. Return true
  85332. ** if the index with affinity idx_affinity may be used to implement
  85333. ** the comparison in pExpr.
  85334. */
  85335. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  85336. char aff = comparisonAffinity(pExpr);
  85337. switch( aff ){
  85338. case SQLITE_AFF_BLOB:
  85339. return 1;
  85340. case SQLITE_AFF_TEXT:
  85341. return idx_affinity==SQLITE_AFF_TEXT;
  85342. default:
  85343. return sqlite3IsNumericAffinity(idx_affinity);
  85344. }
  85345. }
  85346. /*
  85347. ** Return the P5 value that should be used for a binary comparison
  85348. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  85349. */
  85350. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  85351. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  85352. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  85353. return aff;
  85354. }
  85355. /*
  85356. ** Return a pointer to the collation sequence that should be used by
  85357. ** a binary comparison operator comparing pLeft and pRight.
  85358. **
  85359. ** If the left hand expression has a collating sequence type, then it is
  85360. ** used. Otherwise the collation sequence for the right hand expression
  85361. ** is used, or the default (BINARY) if neither expression has a collating
  85362. ** type.
  85363. **
  85364. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  85365. ** it is not considered.
  85366. */
  85367. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  85368. Parse *pParse,
  85369. Expr *pLeft,
  85370. Expr *pRight
  85371. ){
  85372. CollSeq *pColl;
  85373. assert( pLeft );
  85374. if( pLeft->flags & EP_Collate ){
  85375. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  85376. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  85377. pColl = sqlite3ExprCollSeq(pParse, pRight);
  85378. }else{
  85379. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  85380. if( !pColl ){
  85381. pColl = sqlite3ExprCollSeq(pParse, pRight);
  85382. }
  85383. }
  85384. return pColl;
  85385. }
  85386. /*
  85387. ** Generate code for a comparison operator.
  85388. */
  85389. static int codeCompare(
  85390. Parse *pParse, /* The parsing (and code generating) context */
  85391. Expr *pLeft, /* The left operand */
  85392. Expr *pRight, /* The right operand */
  85393. int opcode, /* The comparison opcode */
  85394. int in1, int in2, /* Register holding operands */
  85395. int dest, /* Jump here if true. */
  85396. int jumpIfNull /* If true, jump if either operand is NULL */
  85397. ){
  85398. int p5;
  85399. int addr;
  85400. CollSeq *p4;
  85401. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  85402. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  85403. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  85404. (void*)p4, P4_COLLSEQ);
  85405. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  85406. return addr;
  85407. }
  85408. /*
  85409. ** Return true if expression pExpr is a vector, or false otherwise.
  85410. **
  85411. ** A vector is defined as any expression that results in two or more
  85412. ** columns of result. Every TK_VECTOR node is an vector because the
  85413. ** parser will not generate a TK_VECTOR with fewer than two entries.
  85414. ** But a TK_SELECT might be either a vector or a scalar. It is only
  85415. ** considered a vector if it has two or more result columns.
  85416. */
  85417. SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
  85418. return sqlite3ExprVectorSize(pExpr)>1;
  85419. }
  85420. /*
  85421. ** If the expression passed as the only argument is of type TK_VECTOR
  85422. ** return the number of expressions in the vector. Or, if the expression
  85423. ** is a sub-select, return the number of columns in the sub-select. For
  85424. ** any other type of expression, return 1.
  85425. */
  85426. SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
  85427. u8 op = pExpr->op;
  85428. if( op==TK_REGISTER ) op = pExpr->op2;
  85429. if( op==TK_VECTOR ){
  85430. return pExpr->x.pList->nExpr;
  85431. }else if( op==TK_SELECT ){
  85432. return pExpr->x.pSelect->pEList->nExpr;
  85433. }else{
  85434. return 1;
  85435. }
  85436. }
  85437. /*
  85438. ** Return a pointer to a subexpression of pVector that is the i-th
  85439. ** column of the vector (numbered starting with 0). The caller must
  85440. ** ensure that i is within range.
  85441. **
  85442. ** If pVector is really a scalar (and "scalar" here includes subqueries
  85443. ** that return a single column!) then return pVector unmodified.
  85444. **
  85445. ** pVector retains ownership of the returned subexpression.
  85446. **
  85447. ** If the vector is a (SELECT ...) then the expression returned is
  85448. ** just the expression for the i-th term of the result set, and may
  85449. ** not be ready for evaluation because the table cursor has not yet
  85450. ** been positioned.
  85451. */
  85452. SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
  85453. assert( i<sqlite3ExprVectorSize(pVector) );
  85454. if( sqlite3ExprIsVector(pVector) ){
  85455. assert( pVector->op2==0 || pVector->op==TK_REGISTER );
  85456. if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
  85457. return pVector->x.pSelect->pEList->a[i].pExpr;
  85458. }else{
  85459. return pVector->x.pList->a[i].pExpr;
  85460. }
  85461. }
  85462. return pVector;
  85463. }
  85464. /*
  85465. ** Compute and return a new Expr object which when passed to
  85466. ** sqlite3ExprCode() will generate all necessary code to compute
  85467. ** the iField-th column of the vector expression pVector.
  85468. **
  85469. ** It is ok for pVector to be a scalar (as long as iField==0).
  85470. ** In that case, this routine works like sqlite3ExprDup().
  85471. **
  85472. ** The caller owns the returned Expr object and is responsible for
  85473. ** ensuring that the returned value eventually gets freed.
  85474. **
  85475. ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
  85476. ** then the returned object will reference pVector and so pVector must remain
  85477. ** valid for the life of the returned object. If pVector is a TK_VECTOR
  85478. ** or a scalar expression, then it can be deleted as soon as this routine
  85479. ** returns.
  85480. **
  85481. ** A trick to cause a TK_SELECT pVector to be deleted together with
  85482. ** the returned Expr object is to attach the pVector to the pRight field
  85483. ** of the returned TK_SELECT_COLUMN Expr object.
  85484. */
  85485. SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
  85486. Parse *pParse, /* Parsing context */
  85487. Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
  85488. int iField /* Which column of the vector to return */
  85489. ){
  85490. Expr *pRet;
  85491. if( pVector->op==TK_SELECT ){
  85492. assert( pVector->flags & EP_xIsSelect );
  85493. /* The TK_SELECT_COLUMN Expr node:
  85494. **
  85495. ** pLeft: pVector containing TK_SELECT. Not deleted.
  85496. ** pRight: not used. But recursively deleted.
  85497. ** iColumn: Index of a column in pVector
  85498. ** iTable: 0 or the number of columns on the LHS of an assignment
  85499. ** pLeft->iTable: First in an array of register holding result, or 0
  85500. ** if the result is not yet computed.
  85501. **
  85502. ** sqlite3ExprDelete() specifically skips the recursive delete of
  85503. ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
  85504. ** can be attached to pRight to cause this node to take ownership of
  85505. ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
  85506. ** with the same pLeft pointer to the pVector, but only one of them
  85507. ** will own the pVector.
  85508. */
  85509. pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
  85510. if( pRet ){
  85511. pRet->iColumn = iField;
  85512. pRet->pLeft = pVector;
  85513. }
  85514. assert( pRet==0 || pRet->iTable==0 );
  85515. }else{
  85516. if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
  85517. pRet = sqlite3ExprDup(pParse->db, pVector, 0);
  85518. }
  85519. return pRet;
  85520. }
  85521. /*
  85522. ** If expression pExpr is of type TK_SELECT, generate code to evaluate
  85523. ** it. Return the register in which the result is stored (or, if the
  85524. ** sub-select returns more than one column, the first in an array
  85525. ** of registers in which the result is stored).
  85526. **
  85527. ** If pExpr is not a TK_SELECT expression, return 0.
  85528. */
  85529. static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
  85530. int reg = 0;
  85531. #ifndef SQLITE_OMIT_SUBQUERY
  85532. if( pExpr->op==TK_SELECT ){
  85533. reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  85534. }
  85535. #endif
  85536. return reg;
  85537. }
  85538. /*
  85539. ** Argument pVector points to a vector expression - either a TK_VECTOR
  85540. ** or TK_SELECT that returns more than one column. This function returns
  85541. ** the register number of a register that contains the value of
  85542. ** element iField of the vector.
  85543. **
  85544. ** If pVector is a TK_SELECT expression, then code for it must have
  85545. ** already been generated using the exprCodeSubselect() routine. In this
  85546. ** case parameter regSelect should be the first in an array of registers
  85547. ** containing the results of the sub-select.
  85548. **
  85549. ** If pVector is of type TK_VECTOR, then code for the requested field
  85550. ** is generated. In this case (*pRegFree) may be set to the number of
  85551. ** a temporary register to be freed by the caller before returning.
  85552. **
  85553. ** Before returning, output parameter (*ppExpr) is set to point to the
  85554. ** Expr object corresponding to element iElem of the vector.
  85555. */
  85556. static int exprVectorRegister(
  85557. Parse *pParse, /* Parse context */
  85558. Expr *pVector, /* Vector to extract element from */
  85559. int iField, /* Field to extract from pVector */
  85560. int regSelect, /* First in array of registers */
  85561. Expr **ppExpr, /* OUT: Expression element */
  85562. int *pRegFree /* OUT: Temp register to free */
  85563. ){
  85564. u8 op = pVector->op;
  85565. assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
  85566. if( op==TK_REGISTER ){
  85567. *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
  85568. return pVector->iTable+iField;
  85569. }
  85570. if( op==TK_SELECT ){
  85571. *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
  85572. return regSelect+iField;
  85573. }
  85574. *ppExpr = pVector->x.pList->a[iField].pExpr;
  85575. return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
  85576. }
  85577. /*
  85578. ** Expression pExpr is a comparison between two vector values. Compute
  85579. ** the result of the comparison (1, 0, or NULL) and write that
  85580. ** result into register dest.
  85581. **
  85582. ** The caller must satisfy the following preconditions:
  85583. **
  85584. ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
  85585. ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
  85586. ** otherwise: op==pExpr->op and p5==0
  85587. */
  85588. static void codeVectorCompare(
  85589. Parse *pParse, /* Code generator context */
  85590. Expr *pExpr, /* The comparison operation */
  85591. int dest, /* Write results into this register */
  85592. u8 op, /* Comparison operator */
  85593. u8 p5 /* SQLITE_NULLEQ or zero */
  85594. ){
  85595. Vdbe *v = pParse->pVdbe;
  85596. Expr *pLeft = pExpr->pLeft;
  85597. Expr *pRight = pExpr->pRight;
  85598. int nLeft = sqlite3ExprVectorSize(pLeft);
  85599. int i;
  85600. int regLeft = 0;
  85601. int regRight = 0;
  85602. u8 opx = op;
  85603. int addrDone = sqlite3VdbeMakeLabel(v);
  85604. if( nLeft!=sqlite3ExprVectorSize(pRight) ){
  85605. sqlite3ErrorMsg(pParse, "row value misused");
  85606. return;
  85607. }
  85608. assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
  85609. || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
  85610. || pExpr->op==TK_LT || pExpr->op==TK_GT
  85611. || pExpr->op==TK_LE || pExpr->op==TK_GE
  85612. );
  85613. assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
  85614. || (pExpr->op==TK_ISNOT && op==TK_NE) );
  85615. assert( p5==0 || pExpr->op!=op );
  85616. assert( p5==SQLITE_NULLEQ || pExpr->op==op );
  85617. p5 |= SQLITE_STOREP2;
  85618. if( opx==TK_LE ) opx = TK_LT;
  85619. if( opx==TK_GE ) opx = TK_GT;
  85620. regLeft = exprCodeSubselect(pParse, pLeft);
  85621. regRight = exprCodeSubselect(pParse, pRight);
  85622. for(i=0; 1 /*Loop exits by "break"*/; i++){
  85623. int regFree1 = 0, regFree2 = 0;
  85624. Expr *pL, *pR;
  85625. int r1, r2;
  85626. assert( i>=0 && i<nLeft );
  85627. if( i>0 ) sqlite3ExprCachePush(pParse);
  85628. r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
  85629. r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
  85630. codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
  85631. testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  85632. testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  85633. testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  85634. testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  85635. testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  85636. testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  85637. sqlite3ReleaseTempReg(pParse, regFree1);
  85638. sqlite3ReleaseTempReg(pParse, regFree2);
  85639. if( i>0 ) sqlite3ExprCachePop(pParse);
  85640. if( i==nLeft-1 ){
  85641. break;
  85642. }
  85643. if( opx==TK_EQ ){
  85644. sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
  85645. p5 |= SQLITE_KEEPNULL;
  85646. }else if( opx==TK_NE ){
  85647. sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
  85648. p5 |= SQLITE_KEEPNULL;
  85649. }else{
  85650. assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
  85651. sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
  85652. VdbeCoverageIf(v, op==TK_LT);
  85653. VdbeCoverageIf(v, op==TK_GT);
  85654. VdbeCoverageIf(v, op==TK_LE);
  85655. VdbeCoverageIf(v, op==TK_GE);
  85656. if( i==nLeft-2 ) opx = op;
  85657. }
  85658. }
  85659. sqlite3VdbeResolveLabel(v, addrDone);
  85660. }
  85661. #if SQLITE_MAX_EXPR_DEPTH>0
  85662. /*
  85663. ** Check that argument nHeight is less than or equal to the maximum
  85664. ** expression depth allowed. If it is not, leave an error message in
  85665. ** pParse.
  85666. */
  85667. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  85668. int rc = SQLITE_OK;
  85669. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  85670. if( nHeight>mxHeight ){
  85671. sqlite3ErrorMsg(pParse,
  85672. "Expression tree is too large (maximum depth %d)", mxHeight
  85673. );
  85674. rc = SQLITE_ERROR;
  85675. }
  85676. return rc;
  85677. }
  85678. /* The following three functions, heightOfExpr(), heightOfExprList()
  85679. ** and heightOfSelect(), are used to determine the maximum height
  85680. ** of any expression tree referenced by the structure passed as the
  85681. ** first argument.
  85682. **
  85683. ** If this maximum height is greater than the current value pointed
  85684. ** to by pnHeight, the second parameter, then set *pnHeight to that
  85685. ** value.
  85686. */
  85687. static void heightOfExpr(Expr *p, int *pnHeight){
  85688. if( p ){
  85689. if( p->nHeight>*pnHeight ){
  85690. *pnHeight = p->nHeight;
  85691. }
  85692. }
  85693. }
  85694. static void heightOfExprList(ExprList *p, int *pnHeight){
  85695. if( p ){
  85696. int i;
  85697. for(i=0; i<p->nExpr; i++){
  85698. heightOfExpr(p->a[i].pExpr, pnHeight);
  85699. }
  85700. }
  85701. }
  85702. static void heightOfSelect(Select *p, int *pnHeight){
  85703. if( p ){
  85704. heightOfExpr(p->pWhere, pnHeight);
  85705. heightOfExpr(p->pHaving, pnHeight);
  85706. heightOfExpr(p->pLimit, pnHeight);
  85707. heightOfExpr(p->pOffset, pnHeight);
  85708. heightOfExprList(p->pEList, pnHeight);
  85709. heightOfExprList(p->pGroupBy, pnHeight);
  85710. heightOfExprList(p->pOrderBy, pnHeight);
  85711. heightOfSelect(p->pPrior, pnHeight);
  85712. }
  85713. }
  85714. /*
  85715. ** Set the Expr.nHeight variable in the structure passed as an
  85716. ** argument. An expression with no children, Expr.pList or
  85717. ** Expr.pSelect member has a height of 1. Any other expression
  85718. ** has a height equal to the maximum height of any other
  85719. ** referenced Expr plus one.
  85720. **
  85721. ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
  85722. ** if appropriate.
  85723. */
  85724. static void exprSetHeight(Expr *p){
  85725. int nHeight = 0;
  85726. heightOfExpr(p->pLeft, &nHeight);
  85727. heightOfExpr(p->pRight, &nHeight);
  85728. if( ExprHasProperty(p, EP_xIsSelect) ){
  85729. heightOfSelect(p->x.pSelect, &nHeight);
  85730. }else if( p->x.pList ){
  85731. heightOfExprList(p->x.pList, &nHeight);
  85732. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  85733. }
  85734. p->nHeight = nHeight + 1;
  85735. }
  85736. /*
  85737. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  85738. ** the height is greater than the maximum allowed expression depth,
  85739. ** leave an error in pParse.
  85740. **
  85741. ** Also propagate all EP_Propagate flags from the Expr.x.pList into
  85742. ** Expr.flags.
  85743. */
  85744. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  85745. if( pParse->nErr ) return;
  85746. exprSetHeight(p);
  85747. sqlite3ExprCheckHeight(pParse, p->nHeight);
  85748. }
  85749. /*
  85750. ** Return the maximum height of any expression tree referenced
  85751. ** by the select statement passed as an argument.
  85752. */
  85753. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  85754. int nHeight = 0;
  85755. heightOfSelect(p, &nHeight);
  85756. return nHeight;
  85757. }
  85758. #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
  85759. /*
  85760. ** Propagate all EP_Propagate flags from the Expr.x.pList into
  85761. ** Expr.flags.
  85762. */
  85763. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  85764. if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
  85765. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  85766. }
  85767. }
  85768. #define exprSetHeight(y)
  85769. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  85770. /*
  85771. ** This routine is the core allocator for Expr nodes.
  85772. **
  85773. ** Construct a new expression node and return a pointer to it. Memory
  85774. ** for this node and for the pToken argument is a single allocation
  85775. ** obtained from sqlite3DbMalloc(). The calling function
  85776. ** is responsible for making sure the node eventually gets freed.
  85777. **
  85778. ** If dequote is true, then the token (if it exists) is dequoted.
  85779. ** If dequote is false, no dequoting is performed. The deQuote
  85780. ** parameter is ignored if pToken is NULL or if the token does not
  85781. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  85782. ** then the EP_DblQuoted flag is set on the expression node.
  85783. **
  85784. ** Special case: If op==TK_INTEGER and pToken points to a string that
  85785. ** can be translated into a 32-bit integer, then the token is not
  85786. ** stored in u.zToken. Instead, the integer values is written
  85787. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  85788. ** is allocated to hold the integer text and the dequote flag is ignored.
  85789. */
  85790. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  85791. sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
  85792. int op, /* Expression opcode */
  85793. const Token *pToken, /* Token argument. Might be NULL */
  85794. int dequote /* True to dequote */
  85795. ){
  85796. Expr *pNew;
  85797. int nExtra = 0;
  85798. int iValue = 0;
  85799. assert( db!=0 );
  85800. if( pToken ){
  85801. if( op!=TK_INTEGER || pToken->z==0
  85802. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  85803. nExtra = pToken->n+1;
  85804. assert( iValue>=0 );
  85805. }
  85806. }
  85807. pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
  85808. if( pNew ){
  85809. memset(pNew, 0, sizeof(Expr));
  85810. pNew->op = (u8)op;
  85811. pNew->iAgg = -1;
  85812. if( pToken ){
  85813. if( nExtra==0 ){
  85814. pNew->flags |= EP_IntValue;
  85815. pNew->u.iValue = iValue;
  85816. }else{
  85817. pNew->u.zToken = (char*)&pNew[1];
  85818. assert( pToken->z!=0 || pToken->n==0 );
  85819. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  85820. pNew->u.zToken[pToken->n] = 0;
  85821. if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
  85822. if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
  85823. sqlite3Dequote(pNew->u.zToken);
  85824. }
  85825. }
  85826. }
  85827. #if SQLITE_MAX_EXPR_DEPTH>0
  85828. pNew->nHeight = 1;
  85829. #endif
  85830. }
  85831. return pNew;
  85832. }
  85833. /*
  85834. ** Allocate a new expression node from a zero-terminated token that has
  85835. ** already been dequoted.
  85836. */
  85837. SQLITE_PRIVATE Expr *sqlite3Expr(
  85838. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  85839. int op, /* Expression opcode */
  85840. const char *zToken /* Token argument. Might be NULL */
  85841. ){
  85842. Token x;
  85843. x.z = zToken;
  85844. x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  85845. return sqlite3ExprAlloc(db, op, &x, 0);
  85846. }
  85847. /*
  85848. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  85849. **
  85850. ** If pRoot==NULL that means that a memory allocation error has occurred.
  85851. ** In that case, delete the subtrees pLeft and pRight.
  85852. */
  85853. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  85854. sqlite3 *db,
  85855. Expr *pRoot,
  85856. Expr *pLeft,
  85857. Expr *pRight
  85858. ){
  85859. if( pRoot==0 ){
  85860. assert( db->mallocFailed );
  85861. sqlite3ExprDelete(db, pLeft);
  85862. sqlite3ExprDelete(db, pRight);
  85863. }else{
  85864. if( pRight ){
  85865. pRoot->pRight = pRight;
  85866. pRoot->flags |= EP_Propagate & pRight->flags;
  85867. }
  85868. if( pLeft ){
  85869. pRoot->pLeft = pLeft;
  85870. pRoot->flags |= EP_Propagate & pLeft->flags;
  85871. }
  85872. exprSetHeight(pRoot);
  85873. }
  85874. }
  85875. /*
  85876. ** Allocate an Expr node which joins as many as two subtrees.
  85877. **
  85878. ** One or both of the subtrees can be NULL. Return a pointer to the new
  85879. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  85880. ** free the subtrees and return NULL.
  85881. */
  85882. SQLITE_PRIVATE Expr *sqlite3PExpr(
  85883. Parse *pParse, /* Parsing context */
  85884. int op, /* Expression opcode */
  85885. Expr *pLeft, /* Left operand */
  85886. Expr *pRight /* Right operand */
  85887. ){
  85888. Expr *p;
  85889. if( op==TK_AND && pParse->nErr==0 ){
  85890. /* Take advantage of short-circuit false optimization for AND */
  85891. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  85892. }else{
  85893. p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
  85894. if( p ){
  85895. memset(p, 0, sizeof(Expr));
  85896. p->op = op & TKFLG_MASK;
  85897. p->iAgg = -1;
  85898. }
  85899. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  85900. }
  85901. if( p ) {
  85902. sqlite3ExprCheckHeight(pParse, p->nHeight);
  85903. }
  85904. return p;
  85905. }
  85906. /*
  85907. ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
  85908. ** do a memory allocation failure) then delete the pSelect object.
  85909. */
  85910. SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
  85911. if( pExpr ){
  85912. pExpr->x.pSelect = pSelect;
  85913. ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
  85914. sqlite3ExprSetHeightAndFlags(pParse, pExpr);
  85915. }else{
  85916. assert( pParse->db->mallocFailed );
  85917. sqlite3SelectDelete(pParse->db, pSelect);
  85918. }
  85919. }
  85920. /*
  85921. ** If the expression is always either TRUE or FALSE (respectively),
  85922. ** then return 1. If one cannot determine the truth value of the
  85923. ** expression at compile-time return 0.
  85924. **
  85925. ** This is an optimization. If is OK to return 0 here even if
  85926. ** the expression really is always false or false (a false negative).
  85927. ** But it is a bug to return 1 if the expression might have different
  85928. ** boolean values in different circumstances (a false positive.)
  85929. **
  85930. ** Note that if the expression is part of conditional for a
  85931. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  85932. ** is it true or false, so always return 0.
  85933. */
  85934. static int exprAlwaysTrue(Expr *p){
  85935. int v = 0;
  85936. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  85937. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  85938. return v!=0;
  85939. }
  85940. static int exprAlwaysFalse(Expr *p){
  85941. int v = 0;
  85942. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  85943. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  85944. return v==0;
  85945. }
  85946. /*
  85947. ** Join two expressions using an AND operator. If either expression is
  85948. ** NULL, then just return the other expression.
  85949. **
  85950. ** If one side or the other of the AND is known to be false, then instead
  85951. ** of returning an AND expression, just return a constant expression with
  85952. ** a value of false.
  85953. */
  85954. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  85955. if( pLeft==0 ){
  85956. return pRight;
  85957. }else if( pRight==0 ){
  85958. return pLeft;
  85959. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  85960. sqlite3ExprDelete(db, pLeft);
  85961. sqlite3ExprDelete(db, pRight);
  85962. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  85963. }else{
  85964. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  85965. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  85966. return pNew;
  85967. }
  85968. }
  85969. /*
  85970. ** Construct a new expression node for a function with multiple
  85971. ** arguments.
  85972. */
  85973. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  85974. Expr *pNew;
  85975. sqlite3 *db = pParse->db;
  85976. assert( pToken );
  85977. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  85978. if( pNew==0 ){
  85979. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  85980. return 0;
  85981. }
  85982. pNew->x.pList = pList;
  85983. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  85984. sqlite3ExprSetHeightAndFlags(pParse, pNew);
  85985. return pNew;
  85986. }
  85987. /*
  85988. ** Assign a variable number to an expression that encodes a wildcard
  85989. ** in the original SQL statement.
  85990. **
  85991. ** Wildcards consisting of a single "?" are assigned the next sequential
  85992. ** variable number.
  85993. **
  85994. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  85995. ** sure "nnn" is not too big to avoid a denial of service attack when
  85996. ** the SQL statement comes from an external source.
  85997. **
  85998. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  85999. ** as the previous instance of the same wildcard. Or if this is the first
  86000. ** instance of the wildcard, the next sequential variable number is
  86001. ** assigned.
  86002. */
  86003. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
  86004. sqlite3 *db = pParse->db;
  86005. const char *z;
  86006. ynVar x;
  86007. if( pExpr==0 ) return;
  86008. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  86009. z = pExpr->u.zToken;
  86010. assert( z!=0 );
  86011. assert( z[0]!=0 );
  86012. assert( n==(u32)sqlite3Strlen30(z) );
  86013. if( z[1]==0 ){
  86014. /* Wildcard of the form "?". Assign the next variable number */
  86015. assert( z[0]=='?' );
  86016. x = (ynVar)(++pParse->nVar);
  86017. }else{
  86018. int doAdd = 0;
  86019. if( z[0]=='?' ){
  86020. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  86021. ** use it as the variable number */
  86022. i64 i;
  86023. int bOk;
  86024. if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
  86025. i = z[1]-'0'; /* The common case of ?N for a single digit N */
  86026. bOk = 1;
  86027. }else{
  86028. bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  86029. }
  86030. testcase( i==0 );
  86031. testcase( i==1 );
  86032. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  86033. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  86034. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  86035. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  86036. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  86037. return;
  86038. }
  86039. x = (ynVar)i;
  86040. if( x>pParse->nVar ){
  86041. pParse->nVar = (int)x;
  86042. doAdd = 1;
  86043. }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
  86044. doAdd = 1;
  86045. }
  86046. }else{
  86047. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  86048. ** number as the prior appearance of the same name, or if the name
  86049. ** has never appeared before, reuse the same variable number
  86050. */
  86051. x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
  86052. if( x==0 ){
  86053. x = (ynVar)(++pParse->nVar);
  86054. doAdd = 1;
  86055. }
  86056. }
  86057. if( doAdd ){
  86058. pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
  86059. }
  86060. }
  86061. pExpr->iColumn = x;
  86062. if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  86063. sqlite3ErrorMsg(pParse, "too many SQL variables");
  86064. }
  86065. }
  86066. /*
  86067. ** Recursively delete an expression tree.
  86068. */
  86069. static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
  86070. assert( p!=0 );
  86071. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  86072. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  86073. #ifdef SQLITE_DEBUG
  86074. if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
  86075. assert( p->pLeft==0 );
  86076. assert( p->pRight==0 );
  86077. assert( p->x.pSelect==0 );
  86078. }
  86079. #endif
  86080. if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
  86081. /* The Expr.x union is never used at the same time as Expr.pRight */
  86082. assert( p->x.pList==0 || p->pRight==0 );
  86083. if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
  86084. sqlite3ExprDelete(db, p->pRight);
  86085. if( ExprHasProperty(p, EP_xIsSelect) ){
  86086. sqlite3SelectDelete(db, p->x.pSelect);
  86087. }else{
  86088. sqlite3ExprListDelete(db, p->x.pList);
  86089. }
  86090. }
  86091. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  86092. if( !ExprHasProperty(p, EP_Static) ){
  86093. sqlite3DbFreeNN(db, p);
  86094. }
  86095. }
  86096. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  86097. if( p ) sqlite3ExprDeleteNN(db, p);
  86098. }
  86099. /*
  86100. ** Return the number of bytes allocated for the expression structure
  86101. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  86102. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  86103. */
  86104. static int exprStructSize(Expr *p){
  86105. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  86106. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  86107. return EXPR_FULLSIZE;
  86108. }
  86109. /*
  86110. ** The dupedExpr*Size() routines each return the number of bytes required
  86111. ** to store a copy of an expression or expression tree. They differ in
  86112. ** how much of the tree is measured.
  86113. **
  86114. ** dupedExprStructSize() Size of only the Expr structure
  86115. ** dupedExprNodeSize() Size of Expr + space for token
  86116. ** dupedExprSize() Expr + token + subtree components
  86117. **
  86118. ***************************************************************************
  86119. **
  86120. ** The dupedExprStructSize() function returns two values OR-ed together:
  86121. ** (1) the space required for a copy of the Expr structure only and
  86122. ** (2) the EP_xxx flags that indicate what the structure size should be.
  86123. ** The return values is always one of:
  86124. **
  86125. ** EXPR_FULLSIZE
  86126. ** EXPR_REDUCEDSIZE | EP_Reduced
  86127. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  86128. **
  86129. ** The size of the structure can be found by masking the return value
  86130. ** of this routine with 0xfff. The flags can be found by masking the
  86131. ** return value with EP_Reduced|EP_TokenOnly.
  86132. **
  86133. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  86134. ** (unreduced) Expr objects as they or originally constructed by the parser.
  86135. ** During expression analysis, extra information is computed and moved into
  86136. ** later parts of teh Expr object and that extra information might get chopped
  86137. ** off if the expression is reduced. Note also that it does not work to
  86138. ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  86139. ** to reduce a pristine expression tree from the parser. The implementation
  86140. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  86141. ** to enforce this constraint.
  86142. */
  86143. static int dupedExprStructSize(Expr *p, int flags){
  86144. int nSize;
  86145. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  86146. assert( EXPR_FULLSIZE<=0xfff );
  86147. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  86148. if( 0==flags || p->op==TK_SELECT_COLUMN ){
  86149. nSize = EXPR_FULLSIZE;
  86150. }else{
  86151. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  86152. assert( !ExprHasProperty(p, EP_FromJoin) );
  86153. assert( !ExprHasProperty(p, EP_MemToken) );
  86154. assert( !ExprHasProperty(p, EP_NoReduce) );
  86155. if( p->pLeft || p->x.pList ){
  86156. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  86157. }else{
  86158. assert( p->pRight==0 );
  86159. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  86160. }
  86161. }
  86162. return nSize;
  86163. }
  86164. /*
  86165. ** This function returns the space in bytes required to store the copy
  86166. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  86167. ** string is defined.)
  86168. */
  86169. static int dupedExprNodeSize(Expr *p, int flags){
  86170. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  86171. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  86172. nByte += sqlite3Strlen30(p->u.zToken)+1;
  86173. }
  86174. return ROUND8(nByte);
  86175. }
  86176. /*
  86177. ** Return the number of bytes required to create a duplicate of the
  86178. ** expression passed as the first argument. The second argument is a
  86179. ** mask containing EXPRDUP_XXX flags.
  86180. **
  86181. ** The value returned includes space to create a copy of the Expr struct
  86182. ** itself and the buffer referred to by Expr.u.zToken, if any.
  86183. **
  86184. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  86185. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  86186. ** and Expr.pRight variables (but not for any structures pointed to or
  86187. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  86188. */
  86189. static int dupedExprSize(Expr *p, int flags){
  86190. int nByte = 0;
  86191. if( p ){
  86192. nByte = dupedExprNodeSize(p, flags);
  86193. if( flags&EXPRDUP_REDUCE ){
  86194. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  86195. }
  86196. }
  86197. return nByte;
  86198. }
  86199. /*
  86200. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  86201. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  86202. ** to store the copy of expression p, the copies of p->u.zToken
  86203. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  86204. ** if any. Before returning, *pzBuffer is set to the first byte past the
  86205. ** portion of the buffer copied into by this function.
  86206. */
  86207. static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
  86208. Expr *pNew; /* Value to return */
  86209. u8 *zAlloc; /* Memory space from which to build Expr object */
  86210. u32 staticFlag; /* EP_Static if space not obtained from malloc */
  86211. assert( db!=0 );
  86212. assert( p );
  86213. assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
  86214. assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
  86215. /* Figure out where to write the new Expr structure. */
  86216. if( pzBuffer ){
  86217. zAlloc = *pzBuffer;
  86218. staticFlag = EP_Static;
  86219. }else{
  86220. zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
  86221. staticFlag = 0;
  86222. }
  86223. pNew = (Expr *)zAlloc;
  86224. if( pNew ){
  86225. /* Set nNewSize to the size allocated for the structure pointed to
  86226. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  86227. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  86228. ** by the copy of the p->u.zToken string (if any).
  86229. */
  86230. const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
  86231. const int nNewSize = nStructSize & 0xfff;
  86232. int nToken;
  86233. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  86234. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  86235. }else{
  86236. nToken = 0;
  86237. }
  86238. if( dupFlags ){
  86239. assert( ExprHasProperty(p, EP_Reduced)==0 );
  86240. memcpy(zAlloc, p, nNewSize);
  86241. }else{
  86242. u32 nSize = (u32)exprStructSize(p);
  86243. memcpy(zAlloc, p, nSize);
  86244. if( nSize<EXPR_FULLSIZE ){
  86245. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  86246. }
  86247. }
  86248. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  86249. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  86250. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  86251. pNew->flags |= staticFlag;
  86252. /* Copy the p->u.zToken string, if any. */
  86253. if( nToken ){
  86254. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  86255. memcpy(zToken, p->u.zToken, nToken);
  86256. }
  86257. if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
  86258. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  86259. if( ExprHasProperty(p, EP_xIsSelect) ){
  86260. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
  86261. }else{
  86262. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
  86263. }
  86264. }
  86265. /* Fill in pNew->pLeft and pNew->pRight. */
  86266. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  86267. zAlloc += dupedExprNodeSize(p, dupFlags);
  86268. if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
  86269. pNew->pLeft = p->pLeft ?
  86270. exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
  86271. pNew->pRight = p->pRight ?
  86272. exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
  86273. }
  86274. if( pzBuffer ){
  86275. *pzBuffer = zAlloc;
  86276. }
  86277. }else{
  86278. if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
  86279. if( pNew->op==TK_SELECT_COLUMN ){
  86280. pNew->pLeft = p->pLeft;
  86281. assert( p->iColumn==0 || p->pRight==0 );
  86282. assert( p->pRight==0 || p->pRight==p->pLeft );
  86283. }else{
  86284. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  86285. }
  86286. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  86287. }
  86288. }
  86289. }
  86290. return pNew;
  86291. }
  86292. /*
  86293. ** Create and return a deep copy of the object passed as the second
  86294. ** argument. If an OOM condition is encountered, NULL is returned
  86295. ** and the db->mallocFailed flag set.
  86296. */
  86297. #ifndef SQLITE_OMIT_CTE
  86298. static With *withDup(sqlite3 *db, With *p){
  86299. With *pRet = 0;
  86300. if( p ){
  86301. int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
  86302. pRet = sqlite3DbMallocZero(db, nByte);
  86303. if( pRet ){
  86304. int i;
  86305. pRet->nCte = p->nCte;
  86306. for(i=0; i<p->nCte; i++){
  86307. pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
  86308. pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
  86309. pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
  86310. }
  86311. }
  86312. }
  86313. return pRet;
  86314. }
  86315. #else
  86316. # define withDup(x,y) 0
  86317. #endif
  86318. /*
  86319. ** The following group of routines make deep copies of expressions,
  86320. ** expression lists, ID lists, and select statements. The copies can
  86321. ** be deleted (by being passed to their respective ...Delete() routines)
  86322. ** without effecting the originals.
  86323. **
  86324. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  86325. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  86326. ** by subsequent calls to sqlite*ListAppend() routines.
  86327. **
  86328. ** Any tables that the SrcList might point to are not duplicated.
  86329. **
  86330. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  86331. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  86332. ** truncated version of the usual Expr structure that will be stored as
  86333. ** part of the in-memory representation of the database schema.
  86334. */
  86335. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  86336. assert( flags==0 || flags==EXPRDUP_REDUCE );
  86337. return p ? exprDup(db, p, flags, 0) : 0;
  86338. }
  86339. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  86340. ExprList *pNew;
  86341. struct ExprList_item *pItem, *pOldItem;
  86342. int i;
  86343. Expr *pPriorSelectCol = 0;
  86344. assert( db!=0 );
  86345. if( p==0 ) return 0;
  86346. pNew = sqlite3DbMallocRawNN(db,
  86347. sizeof(*pNew)+sizeof(pNew->a[0])*(p->nExpr-1) );
  86348. if( pNew==0 ) return 0;
  86349. pNew->nAlloc = pNew->nExpr = p->nExpr;
  86350. pItem = pNew->a;
  86351. pOldItem = p->a;
  86352. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  86353. Expr *pOldExpr = pOldItem->pExpr;
  86354. Expr *pNewExpr;
  86355. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  86356. if( pOldExpr
  86357. && pOldExpr->op==TK_SELECT_COLUMN
  86358. && (pNewExpr = pItem->pExpr)!=0
  86359. ){
  86360. assert( pNewExpr->iColumn==0 || i>0 );
  86361. if( pNewExpr->iColumn==0 ){
  86362. assert( pOldExpr->pLeft==pOldExpr->pRight );
  86363. pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
  86364. }else{
  86365. assert( i>0 );
  86366. assert( pItem[-1].pExpr!=0 );
  86367. assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
  86368. assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
  86369. pNewExpr->pLeft = pPriorSelectCol;
  86370. }
  86371. }
  86372. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  86373. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  86374. pItem->sortOrder = pOldItem->sortOrder;
  86375. pItem->done = 0;
  86376. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  86377. pItem->u = pOldItem->u;
  86378. }
  86379. return pNew;
  86380. }
  86381. /*
  86382. ** If cursors, triggers, views and subqueries are all omitted from
  86383. ** the build, then none of the following routines, except for
  86384. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  86385. ** called with a NULL argument.
  86386. */
  86387. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  86388. || !defined(SQLITE_OMIT_SUBQUERY)
  86389. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  86390. SrcList *pNew;
  86391. int i;
  86392. int nByte;
  86393. assert( db!=0 );
  86394. if( p==0 ) return 0;
  86395. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  86396. pNew = sqlite3DbMallocRawNN(db, nByte );
  86397. if( pNew==0 ) return 0;
  86398. pNew->nSrc = pNew->nAlloc = p->nSrc;
  86399. for(i=0; i<p->nSrc; i++){
  86400. struct SrcList_item *pNewItem = &pNew->a[i];
  86401. struct SrcList_item *pOldItem = &p->a[i];
  86402. Table *pTab;
  86403. pNewItem->pSchema = pOldItem->pSchema;
  86404. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  86405. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  86406. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  86407. pNewItem->fg = pOldItem->fg;
  86408. pNewItem->iCursor = pOldItem->iCursor;
  86409. pNewItem->addrFillSub = pOldItem->addrFillSub;
  86410. pNewItem->regReturn = pOldItem->regReturn;
  86411. if( pNewItem->fg.isIndexedBy ){
  86412. pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
  86413. }
  86414. pNewItem->pIBIndex = pOldItem->pIBIndex;
  86415. if( pNewItem->fg.isTabFunc ){
  86416. pNewItem->u1.pFuncArg =
  86417. sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
  86418. }
  86419. pTab = pNewItem->pTab = pOldItem->pTab;
  86420. if( pTab ){
  86421. pTab->nTabRef++;
  86422. }
  86423. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  86424. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  86425. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  86426. pNewItem->colUsed = pOldItem->colUsed;
  86427. }
  86428. return pNew;
  86429. }
  86430. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  86431. IdList *pNew;
  86432. int i;
  86433. assert( db!=0 );
  86434. if( p==0 ) return 0;
  86435. pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
  86436. if( pNew==0 ) return 0;
  86437. pNew->nId = p->nId;
  86438. pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
  86439. if( pNew->a==0 ){
  86440. sqlite3DbFreeNN(db, pNew);
  86441. return 0;
  86442. }
  86443. /* Note that because the size of the allocation for p->a[] is not
  86444. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  86445. ** on the duplicate created by this function. */
  86446. for(i=0; i<p->nId; i++){
  86447. struct IdList_item *pNewItem = &pNew->a[i];
  86448. struct IdList_item *pOldItem = &p->a[i];
  86449. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  86450. pNewItem->idx = pOldItem->idx;
  86451. }
  86452. return pNew;
  86453. }
  86454. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
  86455. Select *pRet = 0;
  86456. Select *pNext = 0;
  86457. Select **pp = &pRet;
  86458. Select *p;
  86459. assert( db!=0 );
  86460. for(p=pDup; p; p=p->pPrior){
  86461. Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
  86462. if( pNew==0 ) break;
  86463. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  86464. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  86465. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  86466. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  86467. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  86468. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  86469. pNew->op = p->op;
  86470. pNew->pNext = pNext;
  86471. pNew->pPrior = 0;
  86472. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  86473. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  86474. pNew->iLimit = 0;
  86475. pNew->iOffset = 0;
  86476. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  86477. pNew->addrOpenEphm[0] = -1;
  86478. pNew->addrOpenEphm[1] = -1;
  86479. pNew->nSelectRow = p->nSelectRow;
  86480. pNew->pWith = withDup(db, p->pWith);
  86481. sqlite3SelectSetName(pNew, p->zSelName);
  86482. *pp = pNew;
  86483. pp = &pNew->pPrior;
  86484. pNext = pNew;
  86485. }
  86486. return pRet;
  86487. }
  86488. #else
  86489. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  86490. assert( p==0 );
  86491. return 0;
  86492. }
  86493. #endif
  86494. /*
  86495. ** Add a new element to the end of an expression list. If pList is
  86496. ** initially NULL, then create a new expression list.
  86497. **
  86498. ** If a memory allocation error occurs, the entire list is freed and
  86499. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  86500. ** that the new entry was successfully appended.
  86501. */
  86502. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  86503. Parse *pParse, /* Parsing context */
  86504. ExprList *pList, /* List to which to append. Might be NULL */
  86505. Expr *pExpr /* Expression to be appended. Might be NULL */
  86506. ){
  86507. struct ExprList_item *pItem;
  86508. sqlite3 *db = pParse->db;
  86509. assert( db!=0 );
  86510. if( pList==0 ){
  86511. pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
  86512. if( pList==0 ){
  86513. goto no_mem;
  86514. }
  86515. pList->nExpr = 0;
  86516. pList->nAlloc = 1;
  86517. }else if( pList->nExpr==pList->nAlloc ){
  86518. ExprList *pNew;
  86519. pNew = sqlite3DbRealloc(db, pList,
  86520. sizeof(*pList)+(2*pList->nAlloc - 1)*sizeof(pList->a[0]));
  86521. if( pNew==0 ){
  86522. goto no_mem;
  86523. }
  86524. pList = pNew;
  86525. pList->nAlloc *= 2;
  86526. }
  86527. pItem = &pList->a[pList->nExpr++];
  86528. memset(pItem, 0, sizeof(*pItem));
  86529. pItem->pExpr = pExpr;
  86530. return pList;
  86531. no_mem:
  86532. /* Avoid leaking memory if malloc has failed. */
  86533. sqlite3ExprDelete(db, pExpr);
  86534. sqlite3ExprListDelete(db, pList);
  86535. return 0;
  86536. }
  86537. /*
  86538. ** pColumns and pExpr form a vector assignment which is part of the SET
  86539. ** clause of an UPDATE statement. Like this:
  86540. **
  86541. ** (a,b,c) = (expr1,expr2,expr3)
  86542. ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
  86543. **
  86544. ** For each term of the vector assignment, append new entries to the
  86545. ** expression list pList. In the case of a subquery on the RHS, append
  86546. ** TK_SELECT_COLUMN expressions.
  86547. */
  86548. SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
  86549. Parse *pParse, /* Parsing context */
  86550. ExprList *pList, /* List to which to append. Might be NULL */
  86551. IdList *pColumns, /* List of names of LHS of the assignment */
  86552. Expr *pExpr /* Vector expression to be appended. Might be NULL */
  86553. ){
  86554. sqlite3 *db = pParse->db;
  86555. int n;
  86556. int i;
  86557. int iFirst = pList ? pList->nExpr : 0;
  86558. /* pColumns can only be NULL due to an OOM but an OOM will cause an
  86559. ** exit prior to this routine being invoked */
  86560. if( NEVER(pColumns==0) ) goto vector_append_error;
  86561. if( pExpr==0 ) goto vector_append_error;
  86562. /* If the RHS is a vector, then we can immediately check to see that
  86563. ** the size of the RHS and LHS match. But if the RHS is a SELECT,
  86564. ** wildcards ("*") in the result set of the SELECT must be expanded before
  86565. ** we can do the size check, so defer the size check until code generation.
  86566. */
  86567. if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
  86568. sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
  86569. pColumns->nId, n);
  86570. goto vector_append_error;
  86571. }
  86572. for(i=0; i<pColumns->nId; i++){
  86573. Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
  86574. pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
  86575. if( pList ){
  86576. assert( pList->nExpr==iFirst+i+1 );
  86577. pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
  86578. pColumns->a[i].zName = 0;
  86579. }
  86580. }
  86581. if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
  86582. Expr *pFirst = pList->a[iFirst].pExpr;
  86583. assert( pFirst!=0 );
  86584. assert( pFirst->op==TK_SELECT_COLUMN );
  86585. /* Store the SELECT statement in pRight so it will be deleted when
  86586. ** sqlite3ExprListDelete() is called */
  86587. pFirst->pRight = pExpr;
  86588. pExpr = 0;
  86589. /* Remember the size of the LHS in iTable so that we can check that
  86590. ** the RHS and LHS sizes match during code generation. */
  86591. pFirst->iTable = pColumns->nId;
  86592. }
  86593. vector_append_error:
  86594. sqlite3ExprDelete(db, pExpr);
  86595. sqlite3IdListDelete(db, pColumns);
  86596. return pList;
  86597. }
  86598. /*
  86599. ** Set the sort order for the last element on the given ExprList.
  86600. */
  86601. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
  86602. if( p==0 ) return;
  86603. assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
  86604. assert( p->nExpr>0 );
  86605. if( iSortOrder<0 ){
  86606. assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
  86607. return;
  86608. }
  86609. p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
  86610. }
  86611. /*
  86612. ** Set the ExprList.a[].zName element of the most recently added item
  86613. ** on the expression list.
  86614. **
  86615. ** pList might be NULL following an OOM error. But pName should never be
  86616. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  86617. ** is set.
  86618. */
  86619. SQLITE_PRIVATE void sqlite3ExprListSetName(
  86620. Parse *pParse, /* Parsing context */
  86621. ExprList *pList, /* List to which to add the span. */
  86622. Token *pName, /* Name to be added */
  86623. int dequote /* True to cause the name to be dequoted */
  86624. ){
  86625. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  86626. if( pList ){
  86627. struct ExprList_item *pItem;
  86628. assert( pList->nExpr>0 );
  86629. pItem = &pList->a[pList->nExpr-1];
  86630. assert( pItem->zName==0 );
  86631. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  86632. if( dequote ) sqlite3Dequote(pItem->zName);
  86633. }
  86634. }
  86635. /*
  86636. ** Set the ExprList.a[].zSpan element of the most recently added item
  86637. ** on the expression list.
  86638. **
  86639. ** pList might be NULL following an OOM error. But pSpan should never be
  86640. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  86641. ** is set.
  86642. */
  86643. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  86644. Parse *pParse, /* Parsing context */
  86645. ExprList *pList, /* List to which to add the span. */
  86646. ExprSpan *pSpan /* The span to be added */
  86647. ){
  86648. sqlite3 *db = pParse->db;
  86649. assert( pList!=0 || db->mallocFailed!=0 );
  86650. if( pList ){
  86651. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  86652. assert( pList->nExpr>0 );
  86653. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  86654. sqlite3DbFree(db, pItem->zSpan);
  86655. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  86656. (int)(pSpan->zEnd - pSpan->zStart));
  86657. }
  86658. }
  86659. /*
  86660. ** If the expression list pEList contains more than iLimit elements,
  86661. ** leave an error message in pParse.
  86662. */
  86663. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  86664. Parse *pParse,
  86665. ExprList *pEList,
  86666. const char *zObject
  86667. ){
  86668. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  86669. testcase( pEList && pEList->nExpr==mx );
  86670. testcase( pEList && pEList->nExpr==mx+1 );
  86671. if( pEList && pEList->nExpr>mx ){
  86672. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  86673. }
  86674. }
  86675. /*
  86676. ** Delete an entire expression list.
  86677. */
  86678. static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
  86679. int i = pList->nExpr;
  86680. struct ExprList_item *pItem = pList->a;
  86681. assert( pList->nExpr>0 );
  86682. do{
  86683. sqlite3ExprDelete(db, pItem->pExpr);
  86684. sqlite3DbFree(db, pItem->zName);
  86685. sqlite3DbFree(db, pItem->zSpan);
  86686. pItem++;
  86687. }while( --i>0 );
  86688. sqlite3DbFreeNN(db, pList);
  86689. }
  86690. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  86691. if( pList ) exprListDeleteNN(db, pList);
  86692. }
  86693. /*
  86694. ** Return the bitwise-OR of all Expr.flags fields in the given
  86695. ** ExprList.
  86696. */
  86697. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
  86698. int i;
  86699. u32 m = 0;
  86700. if( pList ){
  86701. for(i=0; i<pList->nExpr; i++){
  86702. Expr *pExpr = pList->a[i].pExpr;
  86703. assert( pExpr!=0 );
  86704. m |= pExpr->flags;
  86705. }
  86706. }
  86707. return m;
  86708. }
  86709. /*
  86710. ** These routines are Walker callbacks used to check expressions to
  86711. ** see if they are "constant" for some definition of constant. The
  86712. ** Walker.eCode value determines the type of "constant" we are looking
  86713. ** for.
  86714. **
  86715. ** These callback routines are used to implement the following:
  86716. **
  86717. ** sqlite3ExprIsConstant() pWalker->eCode==1
  86718. ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
  86719. ** sqlite3ExprIsTableConstant() pWalker->eCode==3
  86720. ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
  86721. **
  86722. ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
  86723. ** is found to not be a constant.
  86724. **
  86725. ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
  86726. ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
  86727. ** an existing schema and 4 when processing a new statement. A bound
  86728. ** parameter raises an error for new statements, but is silently converted
  86729. ** to NULL for existing schemas. This allows sqlite_master tables that
  86730. ** contain a bound parameter because they were generated by older versions
  86731. ** of SQLite to be parsed by newer versions of SQLite without raising a
  86732. ** malformed schema error.
  86733. */
  86734. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  86735. /* If pWalker->eCode is 2 then any term of the expression that comes from
  86736. ** the ON or USING clauses of a left join disqualifies the expression
  86737. ** from being considered constant. */
  86738. if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
  86739. pWalker->eCode = 0;
  86740. return WRC_Abort;
  86741. }
  86742. switch( pExpr->op ){
  86743. /* Consider functions to be constant if all their arguments are constant
  86744. ** and either pWalker->eCode==4 or 5 or the function has the
  86745. ** SQLITE_FUNC_CONST flag. */
  86746. case TK_FUNCTION:
  86747. if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
  86748. return WRC_Continue;
  86749. }else{
  86750. pWalker->eCode = 0;
  86751. return WRC_Abort;
  86752. }
  86753. case TK_ID:
  86754. case TK_COLUMN:
  86755. case TK_AGG_FUNCTION:
  86756. case TK_AGG_COLUMN:
  86757. testcase( pExpr->op==TK_ID );
  86758. testcase( pExpr->op==TK_COLUMN );
  86759. testcase( pExpr->op==TK_AGG_FUNCTION );
  86760. testcase( pExpr->op==TK_AGG_COLUMN );
  86761. if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
  86762. return WRC_Continue;
  86763. }
  86764. /* Fall through */
  86765. case TK_IF_NULL_ROW:
  86766. testcase( pExpr->op==TK_IF_NULL_ROW );
  86767. pWalker->eCode = 0;
  86768. return WRC_Abort;
  86769. case TK_VARIABLE:
  86770. if( pWalker->eCode==5 ){
  86771. /* Silently convert bound parameters that appear inside of CREATE
  86772. ** statements into a NULL when parsing the CREATE statement text out
  86773. ** of the sqlite_master table */
  86774. pExpr->op = TK_NULL;
  86775. }else if( pWalker->eCode==4 ){
  86776. /* A bound parameter in a CREATE statement that originates from
  86777. ** sqlite3_prepare() causes an error */
  86778. pWalker->eCode = 0;
  86779. return WRC_Abort;
  86780. }
  86781. /* Fall through */
  86782. default:
  86783. testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  86784. testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  86785. return WRC_Continue;
  86786. }
  86787. }
  86788. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  86789. UNUSED_PARAMETER(NotUsed);
  86790. pWalker->eCode = 0;
  86791. return WRC_Abort;
  86792. }
  86793. static int exprIsConst(Expr *p, int initFlag, int iCur){
  86794. Walker w;
  86795. memset(&w, 0, sizeof(w));
  86796. w.eCode = initFlag;
  86797. w.xExprCallback = exprNodeIsConstant;
  86798. w.xSelectCallback = selectNodeIsConstant;
  86799. w.u.iCur = iCur;
  86800. sqlite3WalkExpr(&w, p);
  86801. return w.eCode;
  86802. }
  86803. /*
  86804. ** Walk an expression tree. Return non-zero if the expression is constant
  86805. ** and 0 if it involves variables or function calls.
  86806. **
  86807. ** For the purposes of this function, a double-quoted string (ex: "abc")
  86808. ** is considered a variable but a single-quoted string (ex: 'abc') is
  86809. ** a constant.
  86810. */
  86811. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  86812. return exprIsConst(p, 1, 0);
  86813. }
  86814. /*
  86815. ** Walk an expression tree. Return non-zero if the expression is constant
  86816. ** that does no originate from the ON or USING clauses of a join.
  86817. ** Return 0 if it involves variables or function calls or terms from
  86818. ** an ON or USING clause.
  86819. */
  86820. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  86821. return exprIsConst(p, 2, 0);
  86822. }
  86823. /*
  86824. ** Walk an expression tree. Return non-zero if the expression is constant
  86825. ** for any single row of the table with cursor iCur. In other words, the
  86826. ** expression must not refer to any non-deterministic function nor any
  86827. ** table other than iCur.
  86828. */
  86829. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
  86830. return exprIsConst(p, 3, iCur);
  86831. }
  86832. /*
  86833. ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
  86834. */
  86835. static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
  86836. ExprList *pGroupBy = pWalker->u.pGroupBy;
  86837. int i;
  86838. /* Check if pExpr is identical to any GROUP BY term. If so, consider
  86839. ** it constant. */
  86840. for(i=0; i<pGroupBy->nExpr; i++){
  86841. Expr *p = pGroupBy->a[i].pExpr;
  86842. if( sqlite3ExprCompare(pExpr, p, -1)<2 ){
  86843. CollSeq *pColl = sqlite3ExprCollSeq(pWalker->pParse, p);
  86844. if( pColl==0 || sqlite3_stricmp("BINARY", pColl->zName)==0 ){
  86845. return WRC_Prune;
  86846. }
  86847. }
  86848. }
  86849. /* Check if pExpr is a sub-select. If so, consider it variable. */
  86850. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  86851. pWalker->eCode = 0;
  86852. return WRC_Abort;
  86853. }
  86854. return exprNodeIsConstant(pWalker, pExpr);
  86855. }
  86856. /*
  86857. ** Walk the expression tree passed as the first argument. Return non-zero
  86858. ** if the expression consists entirely of constants or copies of terms
  86859. ** in pGroupBy that sort with the BINARY collation sequence.
  86860. **
  86861. ** This routine is used to determine if a term of the HAVING clause can
  86862. ** be promoted into the WHERE clause. In order for such a promotion to work,
  86863. ** the value of the HAVING clause term must be the same for all members of
  86864. ** a "group". The requirement that the GROUP BY term must be BINARY
  86865. ** assumes that no other collating sequence will have a finer-grained
  86866. ** grouping than binary. In other words (A=B COLLATE binary) implies
  86867. ** A=B in every other collating sequence. The requirement that the
  86868. ** GROUP BY be BINARY is stricter than necessary. It would also work
  86869. ** to promote HAVING clauses that use the same alternative collating
  86870. ** sequence as the GROUP BY term, but that is much harder to check,
  86871. ** alternative collating sequences are uncommon, and this is only an
  86872. ** optimization, so we take the easy way out and simply require the
  86873. ** GROUP BY to use the BINARY collating sequence.
  86874. */
  86875. SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
  86876. Walker w;
  86877. memset(&w, 0, sizeof(w));
  86878. w.eCode = 1;
  86879. w.xExprCallback = exprNodeIsConstantOrGroupBy;
  86880. w.u.pGroupBy = pGroupBy;
  86881. w.pParse = pParse;
  86882. sqlite3WalkExpr(&w, p);
  86883. return w.eCode;
  86884. }
  86885. /*
  86886. ** Walk an expression tree. Return non-zero if the expression is constant
  86887. ** or a function call with constant arguments. Return and 0 if there
  86888. ** are any variables.
  86889. **
  86890. ** For the purposes of this function, a double-quoted string (ex: "abc")
  86891. ** is considered a variable but a single-quoted string (ex: 'abc') is
  86892. ** a constant.
  86893. */
  86894. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
  86895. assert( isInit==0 || isInit==1 );
  86896. return exprIsConst(p, 4+isInit, 0);
  86897. }
  86898. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  86899. /*
  86900. ** Walk an expression tree. Return 1 if the expression contains a
  86901. ** subquery of some kind. Return 0 if there are no subqueries.
  86902. */
  86903. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
  86904. Walker w;
  86905. memset(&w, 0, sizeof(w));
  86906. w.eCode = 1;
  86907. w.xExprCallback = sqlite3ExprWalkNoop;
  86908. w.xSelectCallback = selectNodeIsConstant;
  86909. sqlite3WalkExpr(&w, p);
  86910. return w.eCode==0;
  86911. }
  86912. #endif
  86913. /*
  86914. ** If the expression p codes a constant integer that is small enough
  86915. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  86916. ** in *pValue. If the expression is not an integer or if it is too big
  86917. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  86918. */
  86919. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  86920. int rc = 0;
  86921. if( p==0 ) return 0; /* Can only happen following on OOM */
  86922. /* If an expression is an integer literal that fits in a signed 32-bit
  86923. ** integer, then the EP_IntValue flag will have already been set */
  86924. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  86925. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  86926. if( p->flags & EP_IntValue ){
  86927. *pValue = p->u.iValue;
  86928. return 1;
  86929. }
  86930. switch( p->op ){
  86931. case TK_UPLUS: {
  86932. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  86933. break;
  86934. }
  86935. case TK_UMINUS: {
  86936. int v;
  86937. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  86938. assert( v!=(-2147483647-1) );
  86939. *pValue = -v;
  86940. rc = 1;
  86941. }
  86942. break;
  86943. }
  86944. default: break;
  86945. }
  86946. return rc;
  86947. }
  86948. /*
  86949. ** Return FALSE if there is no chance that the expression can be NULL.
  86950. **
  86951. ** If the expression might be NULL or if the expression is too complex
  86952. ** to tell return TRUE.
  86953. **
  86954. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  86955. ** when we know that a value cannot be NULL. Hence, a false positive
  86956. ** (returning TRUE when in fact the expression can never be NULL) might
  86957. ** be a small performance hit but is otherwise harmless. On the other
  86958. ** hand, a false negative (returning FALSE when the result could be NULL)
  86959. ** will likely result in an incorrect answer. So when in doubt, return
  86960. ** TRUE.
  86961. */
  86962. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  86963. u8 op;
  86964. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  86965. op = p->op;
  86966. if( op==TK_REGISTER ) op = p->op2;
  86967. switch( op ){
  86968. case TK_INTEGER:
  86969. case TK_STRING:
  86970. case TK_FLOAT:
  86971. case TK_BLOB:
  86972. return 0;
  86973. case TK_COLUMN:
  86974. assert( p->pTab!=0 );
  86975. return ExprHasProperty(p, EP_CanBeNull) ||
  86976. (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
  86977. default:
  86978. return 1;
  86979. }
  86980. }
  86981. /*
  86982. ** Return TRUE if the given expression is a constant which would be
  86983. ** unchanged by OP_Affinity with the affinity given in the second
  86984. ** argument.
  86985. **
  86986. ** This routine is used to determine if the OP_Affinity operation
  86987. ** can be omitted. When in doubt return FALSE. A false negative
  86988. ** is harmless. A false positive, however, can result in the wrong
  86989. ** answer.
  86990. */
  86991. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  86992. u8 op;
  86993. if( aff==SQLITE_AFF_BLOB ) return 1;
  86994. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  86995. op = p->op;
  86996. if( op==TK_REGISTER ) op = p->op2;
  86997. switch( op ){
  86998. case TK_INTEGER: {
  86999. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  87000. }
  87001. case TK_FLOAT: {
  87002. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  87003. }
  87004. case TK_STRING: {
  87005. return aff==SQLITE_AFF_TEXT;
  87006. }
  87007. case TK_BLOB: {
  87008. return 1;
  87009. }
  87010. case TK_COLUMN: {
  87011. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  87012. return p->iColumn<0
  87013. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  87014. }
  87015. default: {
  87016. return 0;
  87017. }
  87018. }
  87019. }
  87020. /*
  87021. ** Return TRUE if the given string is a row-id column name.
  87022. */
  87023. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  87024. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  87025. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  87026. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  87027. return 0;
  87028. }
  87029. /*
  87030. ** pX is the RHS of an IN operator. If pX is a SELECT statement
  87031. ** that can be simplified to a direct table access, then return
  87032. ** a pointer to the SELECT statement. If pX is not a SELECT statement,
  87033. ** or if the SELECT statement needs to be manifested into a transient
  87034. ** table, then return NULL.
  87035. */
  87036. #ifndef SQLITE_OMIT_SUBQUERY
  87037. static Select *isCandidateForInOpt(Expr *pX){
  87038. Select *p;
  87039. SrcList *pSrc;
  87040. ExprList *pEList;
  87041. Table *pTab;
  87042. int i;
  87043. if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
  87044. if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
  87045. p = pX->x.pSelect;
  87046. if( p->pPrior ) return 0; /* Not a compound SELECT */
  87047. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  87048. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  87049. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  87050. return 0; /* No DISTINCT keyword and no aggregate functions */
  87051. }
  87052. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  87053. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  87054. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  87055. if( p->pWhere ) return 0; /* Has no WHERE clause */
  87056. pSrc = p->pSrc;
  87057. assert( pSrc!=0 );
  87058. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  87059. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  87060. pTab = pSrc->a[0].pTab;
  87061. assert( pTab!=0 );
  87062. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  87063. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  87064. pEList = p->pEList;
  87065. assert( pEList!=0 );
  87066. /* All SELECT results must be columns. */
  87067. for(i=0; i<pEList->nExpr; i++){
  87068. Expr *pRes = pEList->a[i].pExpr;
  87069. if( pRes->op!=TK_COLUMN ) return 0;
  87070. assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
  87071. }
  87072. return p;
  87073. }
  87074. #endif /* SQLITE_OMIT_SUBQUERY */
  87075. #ifndef SQLITE_OMIT_SUBQUERY
  87076. /*
  87077. ** Generate code that checks the left-most column of index table iCur to see if
  87078. ** it contains any NULL entries. Cause the register at regHasNull to be set
  87079. ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
  87080. ** to be set to NULL if iCur contains one or more NULL values.
  87081. */
  87082. static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
  87083. int addr1;
  87084. sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
  87085. addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
  87086. sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
  87087. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  87088. VdbeComment((v, "first_entry_in(%d)", iCur));
  87089. sqlite3VdbeJumpHere(v, addr1);
  87090. }
  87091. #endif
  87092. #ifndef SQLITE_OMIT_SUBQUERY
  87093. /*
  87094. ** The argument is an IN operator with a list (not a subquery) on the
  87095. ** right-hand side. Return TRUE if that list is constant.
  87096. */
  87097. static int sqlite3InRhsIsConstant(Expr *pIn){
  87098. Expr *pLHS;
  87099. int res;
  87100. assert( !ExprHasProperty(pIn, EP_xIsSelect) );
  87101. pLHS = pIn->pLeft;
  87102. pIn->pLeft = 0;
  87103. res = sqlite3ExprIsConstant(pIn);
  87104. pIn->pLeft = pLHS;
  87105. return res;
  87106. }
  87107. #endif
  87108. /*
  87109. ** This function is used by the implementation of the IN (...) operator.
  87110. ** The pX parameter is the expression on the RHS of the IN operator, which
  87111. ** might be either a list of expressions or a subquery.
  87112. **
  87113. ** The job of this routine is to find or create a b-tree object that can
  87114. ** be used either to test for membership in the RHS set or to iterate through
  87115. ** all members of the RHS set, skipping duplicates.
  87116. **
  87117. ** A cursor is opened on the b-tree object that is the RHS of the IN operator
  87118. ** and pX->iTable is set to the index of that cursor.
  87119. **
  87120. ** The returned value of this function indicates the b-tree type, as follows:
  87121. **
  87122. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  87123. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  87124. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  87125. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  87126. ** populated epheremal table.
  87127. ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
  87128. ** implemented as a sequence of comparisons.
  87129. **
  87130. ** An existing b-tree might be used if the RHS expression pX is a simple
  87131. ** subquery such as:
  87132. **
  87133. ** SELECT <column1>, <column2>... FROM <table>
  87134. **
  87135. ** If the RHS of the IN operator is a list or a more complex subquery, then
  87136. ** an ephemeral table might need to be generated from the RHS and then
  87137. ** pX->iTable made to point to the ephemeral table instead of an
  87138. ** existing table.
  87139. **
  87140. ** The inFlags parameter must contain exactly one of the bits
  87141. ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
  87142. ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
  87143. ** fast membership test. When the IN_INDEX_LOOP bit is set, the
  87144. ** IN index will be used to loop over all values of the RHS of the
  87145. ** IN operator.
  87146. **
  87147. ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
  87148. ** through the set members) then the b-tree must not contain duplicates.
  87149. ** An epheremal table must be used unless the selected columns are guaranteed
  87150. ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
  87151. ** a UNIQUE constraint or index.
  87152. **
  87153. ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
  87154. ** for fast set membership tests) then an epheremal table must
  87155. ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
  87156. ** index can be found with the specified <columns> as its left-most.
  87157. **
  87158. ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
  87159. ** if the RHS of the IN operator is a list (not a subquery) then this
  87160. ** routine might decide that creating an ephemeral b-tree for membership
  87161. ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
  87162. ** calling routine should implement the IN operator using a sequence
  87163. ** of Eq or Ne comparison operations.
  87164. **
  87165. ** When the b-tree is being used for membership tests, the calling function
  87166. ** might need to know whether or not the RHS side of the IN operator
  87167. ** contains a NULL. If prRhsHasNull is not a NULL pointer and
  87168. ** if there is any chance that the (...) might contain a NULL value at
  87169. ** runtime, then a register is allocated and the register number written
  87170. ** to *prRhsHasNull. If there is no chance that the (...) contains a
  87171. ** NULL value, then *prRhsHasNull is left unchanged.
  87172. **
  87173. ** If a register is allocated and its location stored in *prRhsHasNull, then
  87174. ** the value in that register will be NULL if the b-tree contains one or more
  87175. ** NULL values, and it will be some non-NULL value if the b-tree contains no
  87176. ** NULL values.
  87177. **
  87178. ** If the aiMap parameter is not NULL, it must point to an array containing
  87179. ** one element for each column returned by the SELECT statement on the RHS
  87180. ** of the IN(...) operator. The i'th entry of the array is populated with the
  87181. ** offset of the index column that matches the i'th column returned by the
  87182. ** SELECT. For example, if the expression and selected index are:
  87183. **
  87184. ** (?,?,?) IN (SELECT a, b, c FROM t1)
  87185. ** CREATE INDEX i1 ON t1(b, c, a);
  87186. **
  87187. ** then aiMap[] is populated with {2, 0, 1}.
  87188. */
  87189. #ifndef SQLITE_OMIT_SUBQUERY
  87190. SQLITE_PRIVATE int sqlite3FindInIndex(
  87191. Parse *pParse, /* Parsing context */
  87192. Expr *pX, /* The right-hand side (RHS) of the IN operator */
  87193. u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
  87194. int *prRhsHasNull, /* Register holding NULL status. See notes */
  87195. int *aiMap /* Mapping from Index fields to RHS fields */
  87196. ){
  87197. Select *p; /* SELECT to the right of IN operator */
  87198. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  87199. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  87200. int mustBeUnique; /* True if RHS must be unique */
  87201. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  87202. assert( pX->op==TK_IN );
  87203. mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
  87204. /* If the RHS of this IN(...) operator is a SELECT, and if it matters
  87205. ** whether or not the SELECT result contains NULL values, check whether
  87206. ** or not NULL is actually possible (it may not be, for example, due
  87207. ** to NOT NULL constraints in the schema). If no NULL values are possible,
  87208. ** set prRhsHasNull to 0 before continuing. */
  87209. if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
  87210. int i;
  87211. ExprList *pEList = pX->x.pSelect->pEList;
  87212. for(i=0; i<pEList->nExpr; i++){
  87213. if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
  87214. }
  87215. if( i==pEList->nExpr ){
  87216. prRhsHasNull = 0;
  87217. }
  87218. }
  87219. /* Check to see if an existing table or index can be used to
  87220. ** satisfy the query. This is preferable to generating a new
  87221. ** ephemeral table. */
  87222. if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
  87223. sqlite3 *db = pParse->db; /* Database connection */
  87224. Table *pTab; /* Table <table>. */
  87225. i16 iDb; /* Database idx for pTab */
  87226. ExprList *pEList = p->pEList;
  87227. int nExpr = pEList->nExpr;
  87228. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  87229. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  87230. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  87231. pTab = p->pSrc->a[0].pTab;
  87232. /* Code an OP_Transaction and OP_TableLock for <table>. */
  87233. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  87234. sqlite3CodeVerifySchema(pParse, iDb);
  87235. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  87236. assert(v); /* sqlite3GetVdbe() has always been previously called */
  87237. if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
  87238. /* The "x IN (SELECT rowid FROM table)" case */
  87239. int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
  87240. VdbeCoverage(v);
  87241. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  87242. eType = IN_INDEX_ROWID;
  87243. sqlite3VdbeJumpHere(v, iAddr);
  87244. }else{
  87245. Index *pIdx; /* Iterator variable */
  87246. int affinity_ok = 1;
  87247. int i;
  87248. /* Check that the affinity that will be used to perform each
  87249. ** comparison is the same as the affinity of each column in table
  87250. ** on the RHS of the IN operator. If it not, it is not possible to
  87251. ** use any index of the RHS table. */
  87252. for(i=0; i<nExpr && affinity_ok; i++){
  87253. Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
  87254. int iCol = pEList->a[i].pExpr->iColumn;
  87255. char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
  87256. char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
  87257. testcase( cmpaff==SQLITE_AFF_BLOB );
  87258. testcase( cmpaff==SQLITE_AFF_TEXT );
  87259. switch( cmpaff ){
  87260. case SQLITE_AFF_BLOB:
  87261. break;
  87262. case SQLITE_AFF_TEXT:
  87263. /* sqlite3CompareAffinity() only returns TEXT if one side or the
  87264. ** other has no affinity and the other side is TEXT. Hence,
  87265. ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
  87266. ** and for the term on the LHS of the IN to have no affinity. */
  87267. assert( idxaff==SQLITE_AFF_TEXT );
  87268. break;
  87269. default:
  87270. affinity_ok = sqlite3IsNumericAffinity(idxaff);
  87271. }
  87272. }
  87273. if( affinity_ok ){
  87274. /* Search for an existing index that will work for this IN operator */
  87275. for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
  87276. Bitmask colUsed; /* Columns of the index used */
  87277. Bitmask mCol; /* Mask for the current column */
  87278. if( pIdx->nColumn<nExpr ) continue;
  87279. /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
  87280. ** BITMASK(nExpr) without overflowing */
  87281. testcase( pIdx->nColumn==BMS-2 );
  87282. testcase( pIdx->nColumn==BMS-1 );
  87283. if( pIdx->nColumn>=BMS-1 ) continue;
  87284. if( mustBeUnique ){
  87285. if( pIdx->nKeyCol>nExpr
  87286. ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
  87287. ){
  87288. continue; /* This index is not unique over the IN RHS columns */
  87289. }
  87290. }
  87291. colUsed = 0; /* Columns of index used so far */
  87292. for(i=0; i<nExpr; i++){
  87293. Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
  87294. Expr *pRhs = pEList->a[i].pExpr;
  87295. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
  87296. int j;
  87297. assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
  87298. for(j=0; j<nExpr; j++){
  87299. if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
  87300. assert( pIdx->azColl[j] );
  87301. if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
  87302. continue;
  87303. }
  87304. break;
  87305. }
  87306. if( j==nExpr ) break;
  87307. mCol = MASKBIT(j);
  87308. if( mCol & colUsed ) break; /* Each column used only once */
  87309. colUsed |= mCol;
  87310. if( aiMap ) aiMap[i] = j;
  87311. }
  87312. assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
  87313. if( colUsed==(MASKBIT(nExpr)-1) ){
  87314. /* If we reach this point, that means the index pIdx is usable */
  87315. int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  87316. #ifndef SQLITE_OMIT_EXPLAIN
  87317. sqlite3VdbeAddOp4(v, OP_Explain, 0, 0, 0,
  87318. sqlite3MPrintf(db, "USING INDEX %s FOR IN-OPERATOR",pIdx->zName),
  87319. P4_DYNAMIC);
  87320. #endif
  87321. sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
  87322. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  87323. VdbeComment((v, "%s", pIdx->zName));
  87324. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  87325. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  87326. if( prRhsHasNull ){
  87327. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  87328. i64 mask = (1<<nExpr)-1;
  87329. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
  87330. iTab, 0, 0, (u8*)&mask, P4_INT64);
  87331. #endif
  87332. *prRhsHasNull = ++pParse->nMem;
  87333. if( nExpr==1 ){
  87334. sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
  87335. }
  87336. }
  87337. sqlite3VdbeJumpHere(v, iAddr);
  87338. }
  87339. } /* End loop over indexes */
  87340. } /* End if( affinity_ok ) */
  87341. } /* End if not an rowid index */
  87342. } /* End attempt to optimize using an index */
  87343. /* If no preexisting index is available for the IN clause
  87344. ** and IN_INDEX_NOOP is an allowed reply
  87345. ** and the RHS of the IN operator is a list, not a subquery
  87346. ** and the RHS is not constant or has two or fewer terms,
  87347. ** then it is not worth creating an ephemeral table to evaluate
  87348. ** the IN operator so return IN_INDEX_NOOP.
  87349. */
  87350. if( eType==0
  87351. && (inFlags & IN_INDEX_NOOP_OK)
  87352. && !ExprHasProperty(pX, EP_xIsSelect)
  87353. && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
  87354. ){
  87355. eType = IN_INDEX_NOOP;
  87356. }
  87357. if( eType==0 ){
  87358. /* Could not find an existing table or index to use as the RHS b-tree.
  87359. ** We will have to generate an ephemeral table to do the job.
  87360. */
  87361. u32 savedNQueryLoop = pParse->nQueryLoop;
  87362. int rMayHaveNull = 0;
  87363. eType = IN_INDEX_EPH;
  87364. if( inFlags & IN_INDEX_LOOP ){
  87365. pParse->nQueryLoop = 0;
  87366. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  87367. eType = IN_INDEX_ROWID;
  87368. }
  87369. }else if( prRhsHasNull ){
  87370. *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
  87371. }
  87372. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  87373. pParse->nQueryLoop = savedNQueryLoop;
  87374. }else{
  87375. pX->iTable = iTab;
  87376. }
  87377. if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
  87378. int i, n;
  87379. n = sqlite3ExprVectorSize(pX->pLeft);
  87380. for(i=0; i<n; i++) aiMap[i] = i;
  87381. }
  87382. return eType;
  87383. }
  87384. #endif
  87385. #ifndef SQLITE_OMIT_SUBQUERY
  87386. /*
  87387. ** Argument pExpr is an (?, ?...) IN(...) expression. This
  87388. ** function allocates and returns a nul-terminated string containing
  87389. ** the affinities to be used for each column of the comparison.
  87390. **
  87391. ** It is the responsibility of the caller to ensure that the returned
  87392. ** string is eventually freed using sqlite3DbFree().
  87393. */
  87394. static char *exprINAffinity(Parse *pParse, Expr *pExpr){
  87395. Expr *pLeft = pExpr->pLeft;
  87396. int nVal = sqlite3ExprVectorSize(pLeft);
  87397. Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
  87398. char *zRet;
  87399. assert( pExpr->op==TK_IN );
  87400. zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
  87401. if( zRet ){
  87402. int i;
  87403. for(i=0; i<nVal; i++){
  87404. Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
  87405. char a = sqlite3ExprAffinity(pA);
  87406. if( pSelect ){
  87407. zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
  87408. }else{
  87409. zRet[i] = a;
  87410. }
  87411. }
  87412. zRet[nVal] = '\0';
  87413. }
  87414. return zRet;
  87415. }
  87416. #endif
  87417. #ifndef SQLITE_OMIT_SUBQUERY
  87418. /*
  87419. ** Load the Parse object passed as the first argument with an error
  87420. ** message of the form:
  87421. **
  87422. ** "sub-select returns N columns - expected M"
  87423. */
  87424. SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
  87425. const char *zFmt = "sub-select returns %d columns - expected %d";
  87426. sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
  87427. }
  87428. #endif
  87429. /*
  87430. ** Expression pExpr is a vector that has been used in a context where
  87431. ** it is not permitted. If pExpr is a sub-select vector, this routine
  87432. ** loads the Parse object with a message of the form:
  87433. **
  87434. ** "sub-select returns N columns - expected 1"
  87435. **
  87436. ** Or, if it is a regular scalar vector:
  87437. **
  87438. ** "row value misused"
  87439. */
  87440. SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
  87441. #ifndef SQLITE_OMIT_SUBQUERY
  87442. if( pExpr->flags & EP_xIsSelect ){
  87443. sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
  87444. }else
  87445. #endif
  87446. {
  87447. sqlite3ErrorMsg(pParse, "row value misused");
  87448. }
  87449. }
  87450. /*
  87451. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  87452. ** or IN operators. Examples:
  87453. **
  87454. ** (SELECT a FROM b) -- subquery
  87455. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  87456. ** x IN (4,5,11) -- IN operator with list on right-hand side
  87457. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  87458. **
  87459. ** The pExpr parameter describes the expression that contains the IN
  87460. ** operator or subquery.
  87461. **
  87462. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  87463. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  87464. ** to some integer key column of a table B-Tree. In this case, use an
  87465. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  87466. ** (slower) variable length keys B-Tree.
  87467. **
  87468. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  87469. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  87470. ** All this routine does is initialize the register given by rMayHaveNull
  87471. ** to NULL. Calling routines will take care of changing this register
  87472. ** value to non-NULL if the RHS is NULL-free.
  87473. **
  87474. ** For a SELECT or EXISTS operator, return the register that holds the
  87475. ** result. For a multi-column SELECT, the result is stored in a contiguous
  87476. ** array of registers and the return value is the register of the left-most
  87477. ** result column. Return 0 for IN operators or if an error occurs.
  87478. */
  87479. #ifndef SQLITE_OMIT_SUBQUERY
  87480. SQLITE_PRIVATE int sqlite3CodeSubselect(
  87481. Parse *pParse, /* Parsing context */
  87482. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  87483. int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
  87484. int isRowid /* If true, LHS of IN operator is a rowid */
  87485. ){
  87486. int jmpIfDynamic = -1; /* One-time test address */
  87487. int rReg = 0; /* Register storing resulting */
  87488. Vdbe *v = sqlite3GetVdbe(pParse);
  87489. if( NEVER(v==0) ) return 0;
  87490. sqlite3ExprCachePush(pParse);
  87491. /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
  87492. ** is encountered if any of the following is true:
  87493. **
  87494. ** * The right-hand side is a correlated subquery
  87495. ** * The right-hand side is an expression list containing variables
  87496. ** * We are inside a trigger
  87497. **
  87498. ** If all of the above are false, then we can run this code just once
  87499. ** save the results, and reuse the same result on subsequent invocations.
  87500. */
  87501. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  87502. jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  87503. }
  87504. #ifndef SQLITE_OMIT_EXPLAIN
  87505. if( pParse->explain==2 ){
  87506. char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
  87507. jmpIfDynamic>=0?"":"CORRELATED ",
  87508. pExpr->op==TK_IN?"LIST":"SCALAR",
  87509. pParse->iNextSelectId
  87510. );
  87511. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  87512. }
  87513. #endif
  87514. switch( pExpr->op ){
  87515. case TK_IN: {
  87516. int addr; /* Address of OP_OpenEphemeral instruction */
  87517. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  87518. KeyInfo *pKeyInfo = 0; /* Key information */
  87519. int nVal; /* Size of vector pLeft */
  87520. nVal = sqlite3ExprVectorSize(pLeft);
  87521. assert( !isRowid || nVal==1 );
  87522. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  87523. ** expression it is handled the same way. An ephemeral table is
  87524. ** filled with index keys representing the results from the
  87525. ** SELECT or the <exprlist>.
  87526. **
  87527. ** If the 'x' expression is a column value, or the SELECT...
  87528. ** statement returns a column value, then the affinity of that
  87529. ** column is used to build the index keys. If both 'x' and the
  87530. ** SELECT... statement are columns, then numeric affinity is used
  87531. ** if either column has NUMERIC or INTEGER affinity. If neither
  87532. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  87533. ** is used.
  87534. */
  87535. pExpr->iTable = pParse->nTab++;
  87536. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
  87537. pExpr->iTable, (isRowid?0:nVal));
  87538. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
  87539. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  87540. /* Case 1: expr IN (SELECT ...)
  87541. **
  87542. ** Generate code to write the results of the select into the temporary
  87543. ** table allocated and opened above.
  87544. */
  87545. Select *pSelect = pExpr->x.pSelect;
  87546. ExprList *pEList = pSelect->pEList;
  87547. assert( !isRowid );
  87548. /* If the LHS and RHS of the IN operator do not match, that
  87549. ** error will have been caught long before we reach this point. */
  87550. if( ALWAYS(pEList->nExpr==nVal) ){
  87551. SelectDest dest;
  87552. int i;
  87553. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  87554. dest.zAffSdst = exprINAffinity(pParse, pExpr);
  87555. pSelect->iLimit = 0;
  87556. testcase( pSelect->selFlags & SF_Distinct );
  87557. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  87558. if( sqlite3Select(pParse, pSelect, &dest) ){
  87559. sqlite3DbFree(pParse->db, dest.zAffSdst);
  87560. sqlite3KeyInfoUnref(pKeyInfo);
  87561. return 0;
  87562. }
  87563. sqlite3DbFree(pParse->db, dest.zAffSdst);
  87564. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  87565. assert( pEList!=0 );
  87566. assert( pEList->nExpr>0 );
  87567. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  87568. for(i=0; i<nVal; i++){
  87569. Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
  87570. pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
  87571. pParse, p, pEList->a[i].pExpr
  87572. );
  87573. }
  87574. }
  87575. }else if( ALWAYS(pExpr->x.pList!=0) ){
  87576. /* Case 2: expr IN (exprlist)
  87577. **
  87578. ** For each expression, build an index key from the evaluation and
  87579. ** store it in the temporary table. If <expr> is a column, then use
  87580. ** that columns affinity when building index keys. If <expr> is not
  87581. ** a column, use numeric affinity.
  87582. */
  87583. char affinity; /* Affinity of the LHS of the IN */
  87584. int i;
  87585. ExprList *pList = pExpr->x.pList;
  87586. struct ExprList_item *pItem;
  87587. int r1, r2, r3;
  87588. affinity = sqlite3ExprAffinity(pLeft);
  87589. if( !affinity ){
  87590. affinity = SQLITE_AFF_BLOB;
  87591. }
  87592. if( pKeyInfo ){
  87593. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  87594. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  87595. }
  87596. /* Loop through each expression in <exprlist>. */
  87597. r1 = sqlite3GetTempReg(pParse);
  87598. r2 = sqlite3GetTempReg(pParse);
  87599. if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  87600. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  87601. Expr *pE2 = pItem->pExpr;
  87602. int iValToIns;
  87603. /* If the expression is not constant then we will need to
  87604. ** disable the test that was generated above that makes sure
  87605. ** this code only executes once. Because for a non-constant
  87606. ** expression we need to rerun this code each time.
  87607. */
  87608. if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
  87609. sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
  87610. jmpIfDynamic = -1;
  87611. }
  87612. /* Evaluate the expression and insert it into the temp table */
  87613. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  87614. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  87615. }else{
  87616. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  87617. if( isRowid ){
  87618. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  87619. sqlite3VdbeCurrentAddr(v)+2);
  87620. VdbeCoverage(v);
  87621. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  87622. }else{
  87623. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  87624. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  87625. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pExpr->iTable, r2, r3, 1);
  87626. }
  87627. }
  87628. }
  87629. sqlite3ReleaseTempReg(pParse, r1);
  87630. sqlite3ReleaseTempReg(pParse, r2);
  87631. }
  87632. if( pKeyInfo ){
  87633. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
  87634. }
  87635. break;
  87636. }
  87637. case TK_EXISTS:
  87638. case TK_SELECT:
  87639. default: {
  87640. /* Case 3: (SELECT ... FROM ...)
  87641. ** or: EXISTS(SELECT ... FROM ...)
  87642. **
  87643. ** For a SELECT, generate code to put the values for all columns of
  87644. ** the first row into an array of registers and return the index of
  87645. ** the first register.
  87646. **
  87647. ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
  87648. ** into a register and return that register number.
  87649. **
  87650. ** In both cases, the query is augmented with "LIMIT 1". Any
  87651. ** preexisting limit is discarded in place of the new LIMIT 1.
  87652. */
  87653. Select *pSel; /* SELECT statement to encode */
  87654. SelectDest dest; /* How to deal with SELECT result */
  87655. int nReg; /* Registers to allocate */
  87656. testcase( pExpr->op==TK_EXISTS );
  87657. testcase( pExpr->op==TK_SELECT );
  87658. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  87659. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  87660. pSel = pExpr->x.pSelect;
  87661. nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
  87662. sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
  87663. pParse->nMem += nReg;
  87664. if( pExpr->op==TK_SELECT ){
  87665. dest.eDest = SRT_Mem;
  87666. dest.iSdst = dest.iSDParm;
  87667. dest.nSdst = nReg;
  87668. sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
  87669. VdbeComment((v, "Init subquery result"));
  87670. }else{
  87671. dest.eDest = SRT_Exists;
  87672. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  87673. VdbeComment((v, "Init EXISTS result"));
  87674. }
  87675. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  87676. pSel->pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,
  87677. &sqlite3IntTokens[1], 0);
  87678. pSel->iLimit = 0;
  87679. pSel->selFlags &= ~SF_MultiValue;
  87680. if( sqlite3Select(pParse, pSel, &dest) ){
  87681. return 0;
  87682. }
  87683. rReg = dest.iSDParm;
  87684. ExprSetVVAProperty(pExpr, EP_NoReduce);
  87685. break;
  87686. }
  87687. }
  87688. if( rHasNullFlag ){
  87689. sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
  87690. }
  87691. if( jmpIfDynamic>=0 ){
  87692. sqlite3VdbeJumpHere(v, jmpIfDynamic);
  87693. }
  87694. sqlite3ExprCachePop(pParse);
  87695. return rReg;
  87696. }
  87697. #endif /* SQLITE_OMIT_SUBQUERY */
  87698. #ifndef SQLITE_OMIT_SUBQUERY
  87699. /*
  87700. ** Expr pIn is an IN(...) expression. This function checks that the
  87701. ** sub-select on the RHS of the IN() operator has the same number of
  87702. ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
  87703. ** a sub-query, that the LHS is a vector of size 1.
  87704. */
  87705. SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
  87706. int nVector = sqlite3ExprVectorSize(pIn->pLeft);
  87707. if( (pIn->flags & EP_xIsSelect) ){
  87708. if( nVector!=pIn->x.pSelect->pEList->nExpr ){
  87709. sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
  87710. return 1;
  87711. }
  87712. }else if( nVector!=1 ){
  87713. sqlite3VectorErrorMsg(pParse, pIn->pLeft);
  87714. return 1;
  87715. }
  87716. return 0;
  87717. }
  87718. #endif
  87719. #ifndef SQLITE_OMIT_SUBQUERY
  87720. /*
  87721. ** Generate code for an IN expression.
  87722. **
  87723. ** x IN (SELECT ...)
  87724. ** x IN (value, value, ...)
  87725. **
  87726. ** The left-hand side (LHS) is a scalar or vector expression. The
  87727. ** right-hand side (RHS) is an array of zero or more scalar values, or a
  87728. ** subquery. If the RHS is a subquery, the number of result columns must
  87729. ** match the number of columns in the vector on the LHS. If the RHS is
  87730. ** a list of values, the LHS must be a scalar.
  87731. **
  87732. ** The IN operator is true if the LHS value is contained within the RHS.
  87733. ** The result is false if the LHS is definitely not in the RHS. The
  87734. ** result is NULL if the presence of the LHS in the RHS cannot be
  87735. ** determined due to NULLs.
  87736. **
  87737. ** This routine generates code that jumps to destIfFalse if the LHS is not
  87738. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  87739. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  87740. ** within the RHS then fall through.
  87741. **
  87742. ** See the separate in-operator.md documentation file in the canonical
  87743. ** SQLite source tree for additional information.
  87744. */
  87745. static void sqlite3ExprCodeIN(
  87746. Parse *pParse, /* Parsing and code generating context */
  87747. Expr *pExpr, /* The IN expression */
  87748. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  87749. int destIfNull /* Jump here if the results are unknown due to NULLs */
  87750. ){
  87751. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  87752. int eType; /* Type of the RHS */
  87753. int rLhs; /* Register(s) holding the LHS values */
  87754. int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
  87755. Vdbe *v; /* Statement under construction */
  87756. int *aiMap = 0; /* Map from vector field to index column */
  87757. char *zAff = 0; /* Affinity string for comparisons */
  87758. int nVector; /* Size of vectors for this IN operator */
  87759. int iDummy; /* Dummy parameter to exprCodeVector() */
  87760. Expr *pLeft; /* The LHS of the IN operator */
  87761. int i; /* loop counter */
  87762. int destStep2; /* Where to jump when NULLs seen in step 2 */
  87763. int destStep6 = 0; /* Start of code for Step 6 */
  87764. int addrTruthOp; /* Address of opcode that determines the IN is true */
  87765. int destNotNull; /* Jump here if a comparison is not true in step 6 */
  87766. int addrTop; /* Top of the step-6 loop */
  87767. pLeft = pExpr->pLeft;
  87768. if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
  87769. zAff = exprINAffinity(pParse, pExpr);
  87770. nVector = sqlite3ExprVectorSize(pExpr->pLeft);
  87771. aiMap = (int*)sqlite3DbMallocZero(
  87772. pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
  87773. );
  87774. if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
  87775. /* Attempt to compute the RHS. After this step, if anything other than
  87776. ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
  87777. ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
  87778. ** the RHS has not yet been coded. */
  87779. v = pParse->pVdbe;
  87780. assert( v!=0 ); /* OOM detected prior to this routine */
  87781. VdbeNoopComment((v, "begin IN expr"));
  87782. eType = sqlite3FindInIndex(pParse, pExpr,
  87783. IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
  87784. destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
  87785. assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
  87786. || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
  87787. );
  87788. #ifdef SQLITE_DEBUG
  87789. /* Confirm that aiMap[] contains nVector integer values between 0 and
  87790. ** nVector-1. */
  87791. for(i=0; i<nVector; i++){
  87792. int j, cnt;
  87793. for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
  87794. assert( cnt==1 );
  87795. }
  87796. #endif
  87797. /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
  87798. ** vector, then it is stored in an array of nVector registers starting
  87799. ** at r1.
  87800. **
  87801. ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
  87802. ** so that the fields are in the same order as an existing index. The
  87803. ** aiMap[] array contains a mapping from the original LHS field order to
  87804. ** the field order that matches the RHS index.
  87805. */
  87806. sqlite3ExprCachePush(pParse);
  87807. rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
  87808. for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
  87809. if( i==nVector ){
  87810. /* LHS fields are not reordered */
  87811. rLhs = rLhsOrig;
  87812. }else{
  87813. /* Need to reorder the LHS fields according to aiMap */
  87814. rLhs = sqlite3GetTempRange(pParse, nVector);
  87815. for(i=0; i<nVector; i++){
  87816. sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
  87817. }
  87818. }
  87819. /* If sqlite3FindInIndex() did not find or create an index that is
  87820. ** suitable for evaluating the IN operator, then evaluate using a
  87821. ** sequence of comparisons.
  87822. **
  87823. ** This is step (1) in the in-operator.md optimized algorithm.
  87824. */
  87825. if( eType==IN_INDEX_NOOP ){
  87826. ExprList *pList = pExpr->x.pList;
  87827. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  87828. int labelOk = sqlite3VdbeMakeLabel(v);
  87829. int r2, regToFree;
  87830. int regCkNull = 0;
  87831. int ii;
  87832. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  87833. if( destIfNull!=destIfFalse ){
  87834. regCkNull = sqlite3GetTempReg(pParse);
  87835. sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
  87836. }
  87837. for(ii=0; ii<pList->nExpr; ii++){
  87838. r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
  87839. if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
  87840. sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
  87841. }
  87842. if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
  87843. sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
  87844. (void*)pColl, P4_COLLSEQ);
  87845. VdbeCoverageIf(v, ii<pList->nExpr-1);
  87846. VdbeCoverageIf(v, ii==pList->nExpr-1);
  87847. sqlite3VdbeChangeP5(v, zAff[0]);
  87848. }else{
  87849. assert( destIfNull==destIfFalse );
  87850. sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
  87851. (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
  87852. sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
  87853. }
  87854. sqlite3ReleaseTempReg(pParse, regToFree);
  87855. }
  87856. if( regCkNull ){
  87857. sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
  87858. sqlite3VdbeGoto(v, destIfFalse);
  87859. }
  87860. sqlite3VdbeResolveLabel(v, labelOk);
  87861. sqlite3ReleaseTempReg(pParse, regCkNull);
  87862. goto sqlite3ExprCodeIN_finished;
  87863. }
  87864. /* Step 2: Check to see if the LHS contains any NULL columns. If the
  87865. ** LHS does contain NULLs then the result must be either FALSE or NULL.
  87866. ** We will then skip the binary search of the RHS.
  87867. */
  87868. if( destIfNull==destIfFalse ){
  87869. destStep2 = destIfFalse;
  87870. }else{
  87871. destStep2 = destStep6 = sqlite3VdbeMakeLabel(v);
  87872. }
  87873. for(i=0; i<nVector; i++){
  87874. Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
  87875. if( sqlite3ExprCanBeNull(p) ){
  87876. sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
  87877. VdbeCoverage(v);
  87878. }
  87879. }
  87880. /* Step 3. The LHS is now known to be non-NULL. Do the binary search
  87881. ** of the RHS using the LHS as a probe. If found, the result is
  87882. ** true.
  87883. */
  87884. if( eType==IN_INDEX_ROWID ){
  87885. /* In this case, the RHS is the ROWID of table b-tree and so we also
  87886. ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
  87887. ** into a single opcode. */
  87888. sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs);
  87889. VdbeCoverage(v);
  87890. addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
  87891. }else{
  87892. sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
  87893. if( destIfFalse==destIfNull ){
  87894. /* Combine Step 3 and Step 5 into a single opcode */
  87895. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse,
  87896. rLhs, nVector); VdbeCoverage(v);
  87897. goto sqlite3ExprCodeIN_finished;
  87898. }
  87899. /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
  87900. addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0,
  87901. rLhs, nVector); VdbeCoverage(v);
  87902. }
  87903. /* Step 4. If the RHS is known to be non-NULL and we did not find
  87904. ** an match on the search above, then the result must be FALSE.
  87905. */
  87906. if( rRhsHasNull && nVector==1 ){
  87907. sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
  87908. VdbeCoverage(v);
  87909. }
  87910. /* Step 5. If we do not care about the difference between NULL and
  87911. ** FALSE, then just return false.
  87912. */
  87913. if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
  87914. /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
  87915. ** If any comparison is NULL, then the result is NULL. If all
  87916. ** comparisons are FALSE then the final result is FALSE.
  87917. **
  87918. ** For a scalar LHS, it is sufficient to check just the first row
  87919. ** of the RHS.
  87920. */
  87921. if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
  87922. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  87923. VdbeCoverage(v);
  87924. if( nVector>1 ){
  87925. destNotNull = sqlite3VdbeMakeLabel(v);
  87926. }else{
  87927. /* For nVector==1, combine steps 6 and 7 by immediately returning
  87928. ** FALSE if the first comparison is not NULL */
  87929. destNotNull = destIfFalse;
  87930. }
  87931. for(i=0; i<nVector; i++){
  87932. Expr *p;
  87933. CollSeq *pColl;
  87934. int r3 = sqlite3GetTempReg(pParse);
  87935. p = sqlite3VectorFieldSubexpr(pLeft, i);
  87936. pColl = sqlite3ExprCollSeq(pParse, p);
  87937. sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3);
  87938. sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
  87939. (void*)pColl, P4_COLLSEQ);
  87940. VdbeCoverage(v);
  87941. sqlite3ReleaseTempReg(pParse, r3);
  87942. }
  87943. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  87944. if( nVector>1 ){
  87945. sqlite3VdbeResolveLabel(v, destNotNull);
  87946. sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1);
  87947. VdbeCoverage(v);
  87948. /* Step 7: If we reach this point, we know that the result must
  87949. ** be false. */
  87950. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  87951. }
  87952. /* Jumps here in order to return true. */
  87953. sqlite3VdbeJumpHere(v, addrTruthOp);
  87954. sqlite3ExprCodeIN_finished:
  87955. if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
  87956. sqlite3ExprCachePop(pParse);
  87957. VdbeComment((v, "end IN expr"));
  87958. sqlite3ExprCodeIN_oom_error:
  87959. sqlite3DbFree(pParse->db, aiMap);
  87960. sqlite3DbFree(pParse->db, zAff);
  87961. }
  87962. #endif /* SQLITE_OMIT_SUBQUERY */
  87963. #ifndef SQLITE_OMIT_FLOATING_POINT
  87964. /*
  87965. ** Generate an instruction that will put the floating point
  87966. ** value described by z[0..n-1] into register iMem.
  87967. **
  87968. ** The z[] string will probably not be zero-terminated. But the
  87969. ** z[n] character is guaranteed to be something that does not look
  87970. ** like the continuation of the number.
  87971. */
  87972. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  87973. if( ALWAYS(z!=0) ){
  87974. double value;
  87975. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  87976. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  87977. if( negateFlag ) value = -value;
  87978. sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
  87979. }
  87980. }
  87981. #endif
  87982. /*
  87983. ** Generate an instruction that will put the integer describe by
  87984. ** text z[0..n-1] into register iMem.
  87985. **
  87986. ** Expr.u.zToken is always UTF8 and zero-terminated.
  87987. */
  87988. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  87989. Vdbe *v = pParse->pVdbe;
  87990. if( pExpr->flags & EP_IntValue ){
  87991. int i = pExpr->u.iValue;
  87992. assert( i>=0 );
  87993. if( negFlag ) i = -i;
  87994. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  87995. }else{
  87996. int c;
  87997. i64 value;
  87998. const char *z = pExpr->u.zToken;
  87999. assert( z!=0 );
  88000. c = sqlite3DecOrHexToI64(z, &value);
  88001. if( c==1 || (c==2 && !negFlag) || (negFlag && value==SMALLEST_INT64)){
  88002. #ifdef SQLITE_OMIT_FLOATING_POINT
  88003. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  88004. #else
  88005. #ifndef SQLITE_OMIT_HEX_INTEGER
  88006. if( sqlite3_strnicmp(z,"0x",2)==0 ){
  88007. sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
  88008. }else
  88009. #endif
  88010. {
  88011. codeReal(v, z, negFlag, iMem);
  88012. }
  88013. #endif
  88014. }else{
  88015. if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
  88016. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
  88017. }
  88018. }
  88019. }
  88020. /*
  88021. ** Erase column-cache entry number i
  88022. */
  88023. static void cacheEntryClear(Parse *pParse, int i){
  88024. if( pParse->aColCache[i].tempReg ){
  88025. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  88026. pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
  88027. }
  88028. }
  88029. pParse->nColCache--;
  88030. if( i<pParse->nColCache ){
  88031. pParse->aColCache[i] = pParse->aColCache[pParse->nColCache];
  88032. }
  88033. }
  88034. /*
  88035. ** Record in the column cache that a particular column from a
  88036. ** particular table is stored in a particular register.
  88037. */
  88038. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  88039. int i;
  88040. int minLru;
  88041. int idxLru;
  88042. struct yColCache *p;
  88043. /* Unless an error has occurred, register numbers are always positive. */
  88044. assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
  88045. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  88046. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  88047. ** for testing only - to verify that SQLite always gets the same answer
  88048. ** with and without the column cache.
  88049. */
  88050. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  88051. /* First replace any existing entry.
  88052. **
  88053. ** Actually, the way the column cache is currently used, we are guaranteed
  88054. ** that the object will never already be in cache. Verify this guarantee.
  88055. */
  88056. #ifndef NDEBUG
  88057. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  88058. assert( p->iTable!=iTab || p->iColumn!=iCol );
  88059. }
  88060. #endif
  88061. /* If the cache is already full, delete the least recently used entry */
  88062. if( pParse->nColCache>=SQLITE_N_COLCACHE ){
  88063. minLru = 0x7fffffff;
  88064. idxLru = -1;
  88065. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  88066. if( p->lru<minLru ){
  88067. idxLru = i;
  88068. minLru = p->lru;
  88069. }
  88070. }
  88071. p = &pParse->aColCache[idxLru];
  88072. }else{
  88073. p = &pParse->aColCache[pParse->nColCache++];
  88074. }
  88075. /* Add the new entry to the end of the cache */
  88076. p->iLevel = pParse->iCacheLevel;
  88077. p->iTable = iTab;
  88078. p->iColumn = iCol;
  88079. p->iReg = iReg;
  88080. p->tempReg = 0;
  88081. p->lru = pParse->iCacheCnt++;
  88082. }
  88083. /*
  88084. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  88085. ** Purge the range of registers from the column cache.
  88086. */
  88087. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  88088. int i = 0;
  88089. while( i<pParse->nColCache ){
  88090. struct yColCache *p = &pParse->aColCache[i];
  88091. if( p->iReg >= iReg && p->iReg < iReg+nReg ){
  88092. cacheEntryClear(pParse, i);
  88093. }else{
  88094. i++;
  88095. }
  88096. }
  88097. }
  88098. /*
  88099. ** Remember the current column cache context. Any new entries added
  88100. ** added to the column cache after this call are removed when the
  88101. ** corresponding pop occurs.
  88102. */
  88103. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  88104. pParse->iCacheLevel++;
  88105. #ifdef SQLITE_DEBUG
  88106. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  88107. printf("PUSH to %d\n", pParse->iCacheLevel);
  88108. }
  88109. #endif
  88110. }
  88111. /*
  88112. ** Remove from the column cache any entries that were added since the
  88113. ** the previous sqlite3ExprCachePush operation. In other words, restore
  88114. ** the cache to the state it was in prior the most recent Push.
  88115. */
  88116. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
  88117. int i = 0;
  88118. assert( pParse->iCacheLevel>=1 );
  88119. pParse->iCacheLevel--;
  88120. #ifdef SQLITE_DEBUG
  88121. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  88122. printf("POP to %d\n", pParse->iCacheLevel);
  88123. }
  88124. #endif
  88125. while( i<pParse->nColCache ){
  88126. if( pParse->aColCache[i].iLevel>pParse->iCacheLevel ){
  88127. cacheEntryClear(pParse, i);
  88128. }else{
  88129. i++;
  88130. }
  88131. }
  88132. }
  88133. /*
  88134. ** When a cached column is reused, make sure that its register is
  88135. ** no longer available as a temp register. ticket #3879: that same
  88136. ** register might be in the cache in multiple places, so be sure to
  88137. ** get them all.
  88138. */
  88139. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  88140. int i;
  88141. struct yColCache *p;
  88142. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  88143. if( p->iReg==iReg ){
  88144. p->tempReg = 0;
  88145. }
  88146. }
  88147. }
  88148. /* Generate code that will load into register regOut a value that is
  88149. ** appropriate for the iIdxCol-th column of index pIdx.
  88150. */
  88151. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
  88152. Parse *pParse, /* The parsing context */
  88153. Index *pIdx, /* The index whose column is to be loaded */
  88154. int iTabCur, /* Cursor pointing to a table row */
  88155. int iIdxCol, /* The column of the index to be loaded */
  88156. int regOut /* Store the index column value in this register */
  88157. ){
  88158. i16 iTabCol = pIdx->aiColumn[iIdxCol];
  88159. if( iTabCol==XN_EXPR ){
  88160. assert( pIdx->aColExpr );
  88161. assert( pIdx->aColExpr->nExpr>iIdxCol );
  88162. pParse->iSelfTab = iTabCur;
  88163. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
  88164. }else{
  88165. sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
  88166. iTabCol, regOut);
  88167. }
  88168. }
  88169. /*
  88170. ** Generate code to extract the value of the iCol-th column of a table.
  88171. */
  88172. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  88173. Vdbe *v, /* The VDBE under construction */
  88174. Table *pTab, /* The table containing the value */
  88175. int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
  88176. int iCol, /* Index of the column to extract */
  88177. int regOut /* Extract the value into this register */
  88178. ){
  88179. if( pTab==0 ){
  88180. sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
  88181. return;
  88182. }
  88183. if( iCol<0 || iCol==pTab->iPKey ){
  88184. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  88185. }else{
  88186. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  88187. int x = iCol;
  88188. if( !HasRowid(pTab) && !IsVirtual(pTab) ){
  88189. x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
  88190. }
  88191. sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
  88192. }
  88193. if( iCol>=0 ){
  88194. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  88195. }
  88196. }
  88197. /*
  88198. ** Generate code that will extract the iColumn-th column from
  88199. ** table pTab and store the column value in a register.
  88200. **
  88201. ** An effort is made to store the column value in register iReg. This
  88202. ** is not garanteeed for GetColumn() - the result can be stored in
  88203. ** any register. But the result is guaranteed to land in register iReg
  88204. ** for GetColumnToReg().
  88205. **
  88206. ** There must be an open cursor to pTab in iTable when this routine
  88207. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  88208. */
  88209. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  88210. Parse *pParse, /* Parsing and code generating context */
  88211. Table *pTab, /* Description of the table we are reading from */
  88212. int iColumn, /* Index of the table column */
  88213. int iTable, /* The cursor pointing to the table */
  88214. int iReg, /* Store results here */
  88215. u8 p5 /* P5 value for OP_Column + FLAGS */
  88216. ){
  88217. Vdbe *v = pParse->pVdbe;
  88218. int i;
  88219. struct yColCache *p;
  88220. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  88221. if( p->iTable==iTable && p->iColumn==iColumn ){
  88222. p->lru = pParse->iCacheCnt++;
  88223. sqlite3ExprCachePinRegister(pParse, p->iReg);
  88224. return p->iReg;
  88225. }
  88226. }
  88227. assert( v!=0 );
  88228. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  88229. if( p5 ){
  88230. sqlite3VdbeChangeP5(v, p5);
  88231. }else{
  88232. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  88233. }
  88234. return iReg;
  88235. }
  88236. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(
  88237. Parse *pParse, /* Parsing and code generating context */
  88238. Table *pTab, /* Description of the table we are reading from */
  88239. int iColumn, /* Index of the table column */
  88240. int iTable, /* The cursor pointing to the table */
  88241. int iReg /* Store results here */
  88242. ){
  88243. int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
  88244. if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
  88245. }
  88246. /*
  88247. ** Clear all column cache entries.
  88248. */
  88249. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  88250. int i;
  88251. #ifdef SQLITE_DEBUG
  88252. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  88253. printf("CLEAR\n");
  88254. }
  88255. #endif
  88256. for(i=0; i<pParse->nColCache; i++){
  88257. if( pParse->aColCache[i].tempReg
  88258. && pParse->nTempReg<ArraySize(pParse->aTempReg)
  88259. ){
  88260. pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
  88261. }
  88262. }
  88263. pParse->nColCache = 0;
  88264. }
  88265. /*
  88266. ** Record the fact that an affinity change has occurred on iCount
  88267. ** registers starting with iStart.
  88268. */
  88269. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  88270. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  88271. }
  88272. /*
  88273. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  88274. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  88275. */
  88276. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  88277. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  88278. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  88279. sqlite3ExprCacheRemove(pParse, iFrom, nReg);
  88280. }
  88281. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  88282. /*
  88283. ** Return true if any register in the range iFrom..iTo (inclusive)
  88284. ** is used as part of the column cache.
  88285. **
  88286. ** This routine is used within assert() and testcase() macros only
  88287. ** and does not appear in a normal build.
  88288. */
  88289. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  88290. int i;
  88291. struct yColCache *p;
  88292. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  88293. int r = p->iReg;
  88294. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  88295. }
  88296. return 0;
  88297. }
  88298. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  88299. /*
  88300. ** Convert a scalar expression node to a TK_REGISTER referencing
  88301. ** register iReg. The caller must ensure that iReg already contains
  88302. ** the correct value for the expression.
  88303. */
  88304. static void exprToRegister(Expr *p, int iReg){
  88305. p->op2 = p->op;
  88306. p->op = TK_REGISTER;
  88307. p->iTable = iReg;
  88308. ExprClearProperty(p, EP_Skip);
  88309. }
  88310. /*
  88311. ** Evaluate an expression (either a vector or a scalar expression) and store
  88312. ** the result in continguous temporary registers. Return the index of
  88313. ** the first register used to store the result.
  88314. **
  88315. ** If the returned result register is a temporary scalar, then also write
  88316. ** that register number into *piFreeable. If the returned result register
  88317. ** is not a temporary or if the expression is a vector set *piFreeable
  88318. ** to 0.
  88319. */
  88320. static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
  88321. int iResult;
  88322. int nResult = sqlite3ExprVectorSize(p);
  88323. if( nResult==1 ){
  88324. iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
  88325. }else{
  88326. *piFreeable = 0;
  88327. if( p->op==TK_SELECT ){
  88328. #if SQLITE_OMIT_SUBQUERY
  88329. iResult = 0;
  88330. #else
  88331. iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
  88332. #endif
  88333. }else{
  88334. int i;
  88335. iResult = pParse->nMem+1;
  88336. pParse->nMem += nResult;
  88337. for(i=0; i<nResult; i++){
  88338. sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
  88339. }
  88340. }
  88341. }
  88342. return iResult;
  88343. }
  88344. /*
  88345. ** Generate code into the current Vdbe to evaluate the given
  88346. ** expression. Attempt to store the results in register "target".
  88347. ** Return the register where results are stored.
  88348. **
  88349. ** With this routine, there is no guarantee that results will
  88350. ** be stored in target. The result might be stored in some other
  88351. ** register if it is convenient to do so. The calling function
  88352. ** must check the return code and move the results to the desired
  88353. ** register.
  88354. */
  88355. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  88356. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  88357. int op; /* The opcode being coded */
  88358. int inReg = target; /* Results stored in register inReg */
  88359. int regFree1 = 0; /* If non-zero free this temporary register */
  88360. int regFree2 = 0; /* If non-zero free this temporary register */
  88361. int r1, r2; /* Various register numbers */
  88362. Expr tempX; /* Temporary expression node */
  88363. int p5 = 0;
  88364. assert( target>0 && target<=pParse->nMem );
  88365. if( v==0 ){
  88366. assert( pParse->db->mallocFailed );
  88367. return 0;
  88368. }
  88369. if( pExpr==0 ){
  88370. op = TK_NULL;
  88371. }else{
  88372. op = pExpr->op;
  88373. }
  88374. switch( op ){
  88375. case TK_AGG_COLUMN: {
  88376. AggInfo *pAggInfo = pExpr->pAggInfo;
  88377. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  88378. if( !pAggInfo->directMode ){
  88379. assert( pCol->iMem>0 );
  88380. return pCol->iMem;
  88381. }else if( pAggInfo->useSortingIdx ){
  88382. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  88383. pCol->iSorterColumn, target);
  88384. return target;
  88385. }
  88386. /* Otherwise, fall thru into the TK_COLUMN case */
  88387. }
  88388. case TK_COLUMN: {
  88389. int iTab = pExpr->iTable;
  88390. if( iTab<0 ){
  88391. if( pParse->ckBase>0 ){
  88392. /* Generating CHECK constraints or inserting into partial index */
  88393. return pExpr->iColumn + pParse->ckBase;
  88394. }else{
  88395. /* Coding an expression that is part of an index where column names
  88396. ** in the index refer to the table to which the index belongs */
  88397. iTab = pParse->iSelfTab;
  88398. }
  88399. }
  88400. return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  88401. pExpr->iColumn, iTab, target,
  88402. pExpr->op2);
  88403. }
  88404. case TK_INTEGER: {
  88405. codeInteger(pParse, pExpr, 0, target);
  88406. return target;
  88407. }
  88408. #ifndef SQLITE_OMIT_FLOATING_POINT
  88409. case TK_FLOAT: {
  88410. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  88411. codeReal(v, pExpr->u.zToken, 0, target);
  88412. return target;
  88413. }
  88414. #endif
  88415. case TK_STRING: {
  88416. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  88417. sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
  88418. return target;
  88419. }
  88420. case TK_NULL: {
  88421. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  88422. return target;
  88423. }
  88424. #ifndef SQLITE_OMIT_BLOB_LITERAL
  88425. case TK_BLOB: {
  88426. int n;
  88427. const char *z;
  88428. char *zBlob;
  88429. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  88430. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  88431. assert( pExpr->u.zToken[1]=='\'' );
  88432. z = &pExpr->u.zToken[2];
  88433. n = sqlite3Strlen30(z) - 1;
  88434. assert( z[n]=='\'' );
  88435. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  88436. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  88437. return target;
  88438. }
  88439. #endif
  88440. case TK_VARIABLE: {
  88441. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  88442. assert( pExpr->u.zToken!=0 );
  88443. assert( pExpr->u.zToken[0]!=0 );
  88444. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  88445. if( pExpr->u.zToken[1]!=0 ){
  88446. const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
  88447. assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
  88448. pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
  88449. sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
  88450. }
  88451. return target;
  88452. }
  88453. case TK_REGISTER: {
  88454. return pExpr->iTable;
  88455. }
  88456. #ifndef SQLITE_OMIT_CAST
  88457. case TK_CAST: {
  88458. /* Expressions of the form: CAST(pLeft AS token) */
  88459. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  88460. if( inReg!=target ){
  88461. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  88462. inReg = target;
  88463. }
  88464. sqlite3VdbeAddOp2(v, OP_Cast, target,
  88465. sqlite3AffinityType(pExpr->u.zToken, 0));
  88466. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  88467. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  88468. return inReg;
  88469. }
  88470. #endif /* SQLITE_OMIT_CAST */
  88471. case TK_IS:
  88472. case TK_ISNOT:
  88473. op = (op==TK_IS) ? TK_EQ : TK_NE;
  88474. p5 = SQLITE_NULLEQ;
  88475. /* fall-through */
  88476. case TK_LT:
  88477. case TK_LE:
  88478. case TK_GT:
  88479. case TK_GE:
  88480. case TK_NE:
  88481. case TK_EQ: {
  88482. Expr *pLeft = pExpr->pLeft;
  88483. if( sqlite3ExprIsVector(pLeft) ){
  88484. codeVectorCompare(pParse, pExpr, target, op, p5);
  88485. }else{
  88486. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  88487. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  88488. codeCompare(pParse, pLeft, pExpr->pRight, op,
  88489. r1, r2, inReg, SQLITE_STOREP2 | p5);
  88490. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  88491. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  88492. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  88493. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  88494. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  88495. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  88496. testcase( regFree1==0 );
  88497. testcase( regFree2==0 );
  88498. }
  88499. break;
  88500. }
  88501. case TK_AND:
  88502. case TK_OR:
  88503. case TK_PLUS:
  88504. case TK_STAR:
  88505. case TK_MINUS:
  88506. case TK_REM:
  88507. case TK_BITAND:
  88508. case TK_BITOR:
  88509. case TK_SLASH:
  88510. case TK_LSHIFT:
  88511. case TK_RSHIFT:
  88512. case TK_CONCAT: {
  88513. assert( TK_AND==OP_And ); testcase( op==TK_AND );
  88514. assert( TK_OR==OP_Or ); testcase( op==TK_OR );
  88515. assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
  88516. assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
  88517. assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
  88518. assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
  88519. assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
  88520. assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
  88521. assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
  88522. assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
  88523. assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
  88524. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  88525. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  88526. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  88527. testcase( regFree1==0 );
  88528. testcase( regFree2==0 );
  88529. break;
  88530. }
  88531. case TK_UMINUS: {
  88532. Expr *pLeft = pExpr->pLeft;
  88533. assert( pLeft );
  88534. if( pLeft->op==TK_INTEGER ){
  88535. codeInteger(pParse, pLeft, 1, target);
  88536. return target;
  88537. #ifndef SQLITE_OMIT_FLOATING_POINT
  88538. }else if( pLeft->op==TK_FLOAT ){
  88539. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  88540. codeReal(v, pLeft->u.zToken, 1, target);
  88541. return target;
  88542. #endif
  88543. }else{
  88544. tempX.op = TK_INTEGER;
  88545. tempX.flags = EP_IntValue|EP_TokenOnly;
  88546. tempX.u.iValue = 0;
  88547. r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
  88548. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  88549. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  88550. testcase( regFree2==0 );
  88551. }
  88552. break;
  88553. }
  88554. case TK_BITNOT:
  88555. case TK_NOT: {
  88556. assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
  88557. assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
  88558. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  88559. testcase( regFree1==0 );
  88560. sqlite3VdbeAddOp2(v, op, r1, inReg);
  88561. break;
  88562. }
  88563. case TK_ISNULL:
  88564. case TK_NOTNULL: {
  88565. int addr;
  88566. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  88567. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  88568. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  88569. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  88570. testcase( regFree1==0 );
  88571. addr = sqlite3VdbeAddOp1(v, op, r1);
  88572. VdbeCoverageIf(v, op==TK_ISNULL);
  88573. VdbeCoverageIf(v, op==TK_NOTNULL);
  88574. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  88575. sqlite3VdbeJumpHere(v, addr);
  88576. break;
  88577. }
  88578. case TK_AGG_FUNCTION: {
  88579. AggInfo *pInfo = pExpr->pAggInfo;
  88580. if( pInfo==0 ){
  88581. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  88582. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  88583. }else{
  88584. return pInfo->aFunc[pExpr->iAgg].iMem;
  88585. }
  88586. break;
  88587. }
  88588. case TK_FUNCTION: {
  88589. ExprList *pFarg; /* List of function arguments */
  88590. int nFarg; /* Number of function arguments */
  88591. FuncDef *pDef; /* The function definition object */
  88592. const char *zId; /* The function name */
  88593. u32 constMask = 0; /* Mask of function arguments that are constant */
  88594. int i; /* Loop counter */
  88595. sqlite3 *db = pParse->db; /* The database connection */
  88596. u8 enc = ENC(db); /* The text encoding used by this database */
  88597. CollSeq *pColl = 0; /* A collating sequence */
  88598. if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
  88599. /* SQL functions can be expensive. So try to move constant functions
  88600. ** out of the inner loop, even if that means an extra OP_Copy. */
  88601. return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
  88602. }
  88603. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  88604. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  88605. pFarg = 0;
  88606. }else{
  88607. pFarg = pExpr->x.pList;
  88608. }
  88609. nFarg = pFarg ? pFarg->nExpr : 0;
  88610. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  88611. zId = pExpr->u.zToken;
  88612. pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
  88613. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  88614. if( pDef==0 && pParse->explain ){
  88615. pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
  88616. }
  88617. #endif
  88618. if( pDef==0 || pDef->xFinalize!=0 ){
  88619. sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
  88620. break;
  88621. }
  88622. /* Attempt a direct implementation of the built-in COALESCE() and
  88623. ** IFNULL() functions. This avoids unnecessary evaluation of
  88624. ** arguments past the first non-NULL argument.
  88625. */
  88626. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  88627. int endCoalesce = sqlite3VdbeMakeLabel(v);
  88628. assert( nFarg>=2 );
  88629. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  88630. for(i=1; i<nFarg; i++){
  88631. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  88632. VdbeCoverage(v);
  88633. sqlite3ExprCacheRemove(pParse, target, 1);
  88634. sqlite3ExprCachePush(pParse);
  88635. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  88636. sqlite3ExprCachePop(pParse);
  88637. }
  88638. sqlite3VdbeResolveLabel(v, endCoalesce);
  88639. break;
  88640. }
  88641. /* The UNLIKELY() function is a no-op. The result is the value
  88642. ** of the first argument.
  88643. */
  88644. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  88645. assert( nFarg>=1 );
  88646. return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
  88647. }
  88648. #ifdef SQLITE_DEBUG
  88649. /* The AFFINITY() function evaluates to a string that describes
  88650. ** the type affinity of the argument. This is used for testing of
  88651. ** the SQLite type logic.
  88652. */
  88653. if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
  88654. const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
  88655. char aff;
  88656. assert( nFarg==1 );
  88657. aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
  88658. sqlite3VdbeLoadString(v, target,
  88659. aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
  88660. return target;
  88661. }
  88662. #endif
  88663. for(i=0; i<nFarg; i++){
  88664. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  88665. testcase( i==31 );
  88666. constMask |= MASKBIT32(i);
  88667. }
  88668. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  88669. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  88670. }
  88671. }
  88672. if( pFarg ){
  88673. if( constMask ){
  88674. r1 = pParse->nMem+1;
  88675. pParse->nMem += nFarg;
  88676. }else{
  88677. r1 = sqlite3GetTempRange(pParse, nFarg);
  88678. }
  88679. /* For length() and typeof() functions with a column argument,
  88680. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  88681. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  88682. ** loading.
  88683. */
  88684. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  88685. u8 exprOp;
  88686. assert( nFarg==1 );
  88687. assert( pFarg->a[0].pExpr!=0 );
  88688. exprOp = pFarg->a[0].pExpr->op;
  88689. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  88690. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  88691. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  88692. testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
  88693. pFarg->a[0].pExpr->op2 =
  88694. pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
  88695. }
  88696. }
  88697. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  88698. sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
  88699. SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
  88700. sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
  88701. }else{
  88702. r1 = 0;
  88703. }
  88704. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88705. /* Possibly overload the function if the first argument is
  88706. ** a virtual table column.
  88707. **
  88708. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  88709. ** second argument, not the first, as the argument to test to
  88710. ** see if it is a column in a virtual table. This is done because
  88711. ** the left operand of infix functions (the operand we want to
  88712. ** control overloading) ends up as the second argument to the
  88713. ** function. The expression "A glob B" is equivalent to
  88714. ** "glob(B,A). We want to use the A in "A glob B" to test
  88715. ** for function overloading. But we use the B term in "glob(B,A)".
  88716. */
  88717. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  88718. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  88719. }else if( nFarg>0 ){
  88720. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  88721. }
  88722. #endif
  88723. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  88724. if( !pColl ) pColl = db->pDfltColl;
  88725. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  88726. }
  88727. sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
  88728. (char*)pDef, P4_FUNCDEF);
  88729. sqlite3VdbeChangeP5(v, (u8)nFarg);
  88730. if( nFarg && constMask==0 ){
  88731. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  88732. }
  88733. return target;
  88734. }
  88735. #ifndef SQLITE_OMIT_SUBQUERY
  88736. case TK_EXISTS:
  88737. case TK_SELECT: {
  88738. int nCol;
  88739. testcase( op==TK_EXISTS );
  88740. testcase( op==TK_SELECT );
  88741. if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
  88742. sqlite3SubselectError(pParse, nCol, 1);
  88743. }else{
  88744. return sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  88745. }
  88746. break;
  88747. }
  88748. case TK_SELECT_COLUMN: {
  88749. int n;
  88750. if( pExpr->pLeft->iTable==0 ){
  88751. pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
  88752. }
  88753. assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
  88754. if( pExpr->iTable
  88755. && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
  88756. ){
  88757. sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
  88758. pExpr->iTable, n);
  88759. }
  88760. return pExpr->pLeft->iTable + pExpr->iColumn;
  88761. }
  88762. case TK_IN: {
  88763. int destIfFalse = sqlite3VdbeMakeLabel(v);
  88764. int destIfNull = sqlite3VdbeMakeLabel(v);
  88765. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  88766. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  88767. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  88768. sqlite3VdbeResolveLabel(v, destIfFalse);
  88769. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  88770. sqlite3VdbeResolveLabel(v, destIfNull);
  88771. return target;
  88772. }
  88773. #endif /* SQLITE_OMIT_SUBQUERY */
  88774. /*
  88775. ** x BETWEEN y AND z
  88776. **
  88777. ** This is equivalent to
  88778. **
  88779. ** x>=y AND x<=z
  88780. **
  88781. ** X is stored in pExpr->pLeft.
  88782. ** Y is stored in pExpr->pList->a[0].pExpr.
  88783. ** Z is stored in pExpr->pList->a[1].pExpr.
  88784. */
  88785. case TK_BETWEEN: {
  88786. exprCodeBetween(pParse, pExpr, target, 0, 0);
  88787. return target;
  88788. }
  88789. case TK_SPAN:
  88790. case TK_COLLATE:
  88791. case TK_UPLUS: {
  88792. return sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  88793. }
  88794. case TK_TRIGGER: {
  88795. /* If the opcode is TK_TRIGGER, then the expression is a reference
  88796. ** to a column in the new.* or old.* pseudo-tables available to
  88797. ** trigger programs. In this case Expr.iTable is set to 1 for the
  88798. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  88799. ** is set to the column of the pseudo-table to read, or to -1 to
  88800. ** read the rowid field.
  88801. **
  88802. ** The expression is implemented using an OP_Param opcode. The p1
  88803. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  88804. ** to reference another column of the old.* pseudo-table, where
  88805. ** i is the index of the column. For a new.rowid reference, p1 is
  88806. ** set to (n+1), where n is the number of columns in each pseudo-table.
  88807. ** For a reference to any other column in the new.* pseudo-table, p1
  88808. ** is set to (n+2+i), where n and i are as defined previously. For
  88809. ** example, if the table on which triggers are being fired is
  88810. ** declared as:
  88811. **
  88812. ** CREATE TABLE t1(a, b);
  88813. **
  88814. ** Then p1 is interpreted as follows:
  88815. **
  88816. ** p1==0 -> old.rowid p1==3 -> new.rowid
  88817. ** p1==1 -> old.a p1==4 -> new.a
  88818. ** p1==2 -> old.b p1==5 -> new.b
  88819. */
  88820. Table *pTab = pExpr->pTab;
  88821. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  88822. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  88823. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  88824. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  88825. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  88826. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  88827. VdbeComment((v, "%s.%s -> $%d",
  88828. (pExpr->iTable ? "new" : "old"),
  88829. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  88830. target
  88831. ));
  88832. #ifndef SQLITE_OMIT_FLOATING_POINT
  88833. /* If the column has REAL affinity, it may currently be stored as an
  88834. ** integer. Use OP_RealAffinity to make sure it is really real.
  88835. **
  88836. ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
  88837. ** floating point when extracting it from the record. */
  88838. if( pExpr->iColumn>=0
  88839. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  88840. ){
  88841. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  88842. }
  88843. #endif
  88844. break;
  88845. }
  88846. case TK_VECTOR: {
  88847. sqlite3ErrorMsg(pParse, "row value misused");
  88848. break;
  88849. }
  88850. case TK_IF_NULL_ROW: {
  88851. int addrINR;
  88852. addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
  88853. sqlite3ExprCachePush(pParse);
  88854. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  88855. sqlite3ExprCachePop(pParse);
  88856. sqlite3VdbeJumpHere(v, addrINR);
  88857. sqlite3VdbeChangeP3(v, addrINR, inReg);
  88858. break;
  88859. }
  88860. /*
  88861. ** Form A:
  88862. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  88863. **
  88864. ** Form B:
  88865. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  88866. **
  88867. ** Form A is can be transformed into the equivalent form B as follows:
  88868. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  88869. ** WHEN x=eN THEN rN ELSE y END
  88870. **
  88871. ** X (if it exists) is in pExpr->pLeft.
  88872. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  88873. ** odd. The Y is also optional. If the number of elements in x.pList
  88874. ** is even, then Y is omitted and the "otherwise" result is NULL.
  88875. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  88876. **
  88877. ** The result of the expression is the Ri for the first matching Ei,
  88878. ** or if there is no matching Ei, the ELSE term Y, or if there is
  88879. ** no ELSE term, NULL.
  88880. */
  88881. default: assert( op==TK_CASE ); {
  88882. int endLabel; /* GOTO label for end of CASE stmt */
  88883. int nextCase; /* GOTO label for next WHEN clause */
  88884. int nExpr; /* 2x number of WHEN terms */
  88885. int i; /* Loop counter */
  88886. ExprList *pEList; /* List of WHEN terms */
  88887. struct ExprList_item *aListelem; /* Array of WHEN terms */
  88888. Expr opCompare; /* The X==Ei expression */
  88889. Expr *pX; /* The X expression */
  88890. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  88891. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  88892. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  88893. assert(pExpr->x.pList->nExpr > 0);
  88894. pEList = pExpr->x.pList;
  88895. aListelem = pEList->a;
  88896. nExpr = pEList->nExpr;
  88897. endLabel = sqlite3VdbeMakeLabel(v);
  88898. if( (pX = pExpr->pLeft)!=0 ){
  88899. tempX = *pX;
  88900. testcase( pX->op==TK_COLUMN );
  88901. exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
  88902. testcase( regFree1==0 );
  88903. memset(&opCompare, 0, sizeof(opCompare));
  88904. opCompare.op = TK_EQ;
  88905. opCompare.pLeft = &tempX;
  88906. pTest = &opCompare;
  88907. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  88908. ** The value in regFree1 might get SCopy-ed into the file result.
  88909. ** So make sure that the regFree1 register is not reused for other
  88910. ** purposes and possibly overwritten. */
  88911. regFree1 = 0;
  88912. }
  88913. for(i=0; i<nExpr-1; i=i+2){
  88914. sqlite3ExprCachePush(pParse);
  88915. if( pX ){
  88916. assert( pTest!=0 );
  88917. opCompare.pRight = aListelem[i].pExpr;
  88918. }else{
  88919. pTest = aListelem[i].pExpr;
  88920. }
  88921. nextCase = sqlite3VdbeMakeLabel(v);
  88922. testcase( pTest->op==TK_COLUMN );
  88923. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  88924. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  88925. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  88926. sqlite3VdbeGoto(v, endLabel);
  88927. sqlite3ExprCachePop(pParse);
  88928. sqlite3VdbeResolveLabel(v, nextCase);
  88929. }
  88930. if( (nExpr&1)!=0 ){
  88931. sqlite3ExprCachePush(pParse);
  88932. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  88933. sqlite3ExprCachePop(pParse);
  88934. }else{
  88935. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  88936. }
  88937. assert( pParse->db->mallocFailed || pParse->nErr>0
  88938. || pParse->iCacheLevel==iCacheLevel );
  88939. sqlite3VdbeResolveLabel(v, endLabel);
  88940. break;
  88941. }
  88942. #ifndef SQLITE_OMIT_TRIGGER
  88943. case TK_RAISE: {
  88944. assert( pExpr->affinity==OE_Rollback
  88945. || pExpr->affinity==OE_Abort
  88946. || pExpr->affinity==OE_Fail
  88947. || pExpr->affinity==OE_Ignore
  88948. );
  88949. if( !pParse->pTriggerTab ){
  88950. sqlite3ErrorMsg(pParse,
  88951. "RAISE() may only be used within a trigger-program");
  88952. return 0;
  88953. }
  88954. if( pExpr->affinity==OE_Abort ){
  88955. sqlite3MayAbort(pParse);
  88956. }
  88957. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  88958. if( pExpr->affinity==OE_Ignore ){
  88959. sqlite3VdbeAddOp4(
  88960. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  88961. VdbeCoverage(v);
  88962. }else{
  88963. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  88964. pExpr->affinity, pExpr->u.zToken, 0, 0);
  88965. }
  88966. break;
  88967. }
  88968. #endif
  88969. }
  88970. sqlite3ReleaseTempReg(pParse, regFree1);
  88971. sqlite3ReleaseTempReg(pParse, regFree2);
  88972. return inReg;
  88973. }
  88974. /*
  88975. ** Factor out the code of the given expression to initialization time.
  88976. **
  88977. ** If regDest>=0 then the result is always stored in that register and the
  88978. ** result is not reusable. If regDest<0 then this routine is free to
  88979. ** store the value whereever it wants. The register where the expression
  88980. ** is stored is returned. When regDest<0, two identical expressions will
  88981. ** code to the same register.
  88982. */
  88983. SQLITE_PRIVATE int sqlite3ExprCodeAtInit(
  88984. Parse *pParse, /* Parsing context */
  88985. Expr *pExpr, /* The expression to code when the VDBE initializes */
  88986. int regDest /* Store the value in this register */
  88987. ){
  88988. ExprList *p;
  88989. assert( ConstFactorOk(pParse) );
  88990. p = pParse->pConstExpr;
  88991. if( regDest<0 && p ){
  88992. struct ExprList_item *pItem;
  88993. int i;
  88994. for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
  88995. if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
  88996. return pItem->u.iConstExprReg;
  88997. }
  88998. }
  88999. }
  89000. pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  89001. p = sqlite3ExprListAppend(pParse, p, pExpr);
  89002. if( p ){
  89003. struct ExprList_item *pItem = &p->a[p->nExpr-1];
  89004. pItem->reusable = regDest<0;
  89005. if( regDest<0 ) regDest = ++pParse->nMem;
  89006. pItem->u.iConstExprReg = regDest;
  89007. }
  89008. pParse->pConstExpr = p;
  89009. return regDest;
  89010. }
  89011. /*
  89012. ** Generate code to evaluate an expression and store the results
  89013. ** into a register. Return the register number where the results
  89014. ** are stored.
  89015. **
  89016. ** If the register is a temporary register that can be deallocated,
  89017. ** then write its number into *pReg. If the result register is not
  89018. ** a temporary, then set *pReg to zero.
  89019. **
  89020. ** If pExpr is a constant, then this routine might generate this
  89021. ** code to fill the register in the initialization section of the
  89022. ** VDBE program, in order to factor it out of the evaluation loop.
  89023. */
  89024. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  89025. int r2;
  89026. pExpr = sqlite3ExprSkipCollate(pExpr);
  89027. if( ConstFactorOk(pParse)
  89028. && pExpr->op!=TK_REGISTER
  89029. && sqlite3ExprIsConstantNotJoin(pExpr)
  89030. ){
  89031. *pReg = 0;
  89032. r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
  89033. }else{
  89034. int r1 = sqlite3GetTempReg(pParse);
  89035. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  89036. if( r2==r1 ){
  89037. *pReg = r1;
  89038. }else{
  89039. sqlite3ReleaseTempReg(pParse, r1);
  89040. *pReg = 0;
  89041. }
  89042. }
  89043. return r2;
  89044. }
  89045. /*
  89046. ** Generate code that will evaluate expression pExpr and store the
  89047. ** results in register target. The results are guaranteed to appear
  89048. ** in register target.
  89049. */
  89050. SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  89051. int inReg;
  89052. assert( target>0 && target<=pParse->nMem );
  89053. if( pExpr && pExpr->op==TK_REGISTER ){
  89054. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  89055. }else{
  89056. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  89057. assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
  89058. if( inReg!=target && pParse->pVdbe ){
  89059. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  89060. }
  89061. }
  89062. }
  89063. /*
  89064. ** Make a transient copy of expression pExpr and then code it using
  89065. ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
  89066. ** except that the input expression is guaranteed to be unchanged.
  89067. */
  89068. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
  89069. sqlite3 *db = pParse->db;
  89070. pExpr = sqlite3ExprDup(db, pExpr, 0);
  89071. if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
  89072. sqlite3ExprDelete(db, pExpr);
  89073. }
  89074. /*
  89075. ** Generate code that will evaluate expression pExpr and store the
  89076. ** results in register target. The results are guaranteed to appear
  89077. ** in register target. If the expression is constant, then this routine
  89078. ** might choose to code the expression at initialization time.
  89079. */
  89080. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
  89081. if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
  89082. sqlite3ExprCodeAtInit(pParse, pExpr, target);
  89083. }else{
  89084. sqlite3ExprCode(pParse, pExpr, target);
  89085. }
  89086. }
  89087. /*
  89088. ** Generate code that evaluates the given expression and puts the result
  89089. ** in register target.
  89090. **
  89091. ** Also make a copy of the expression results into another "cache" register
  89092. ** and modify the expression so that the next time it is evaluated,
  89093. ** the result is a copy of the cache register.
  89094. **
  89095. ** This routine is used for expressions that are used multiple
  89096. ** times. They are evaluated once and the results of the expression
  89097. ** are reused.
  89098. */
  89099. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  89100. Vdbe *v = pParse->pVdbe;
  89101. int iMem;
  89102. assert( target>0 );
  89103. assert( pExpr->op!=TK_REGISTER );
  89104. sqlite3ExprCode(pParse, pExpr, target);
  89105. iMem = ++pParse->nMem;
  89106. sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
  89107. exprToRegister(pExpr, iMem);
  89108. }
  89109. /*
  89110. ** Generate code that pushes the value of every element of the given
  89111. ** expression list into a sequence of registers beginning at target.
  89112. **
  89113. ** Return the number of elements evaluated.
  89114. **
  89115. ** The SQLITE_ECEL_DUP flag prevents the arguments from being
  89116. ** filled using OP_SCopy. OP_Copy must be used instead.
  89117. **
  89118. ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
  89119. ** factored out into initialization code.
  89120. **
  89121. ** The SQLITE_ECEL_REF flag means that expressions in the list with
  89122. ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
  89123. ** in registers at srcReg, and so the value can be copied from there.
  89124. */
  89125. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  89126. Parse *pParse, /* Parsing context */
  89127. ExprList *pList, /* The expression list to be coded */
  89128. int target, /* Where to write results */
  89129. int srcReg, /* Source registers if SQLITE_ECEL_REF */
  89130. u8 flags /* SQLITE_ECEL_* flags */
  89131. ){
  89132. struct ExprList_item *pItem;
  89133. int i, j, n;
  89134. u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
  89135. Vdbe *v = pParse->pVdbe;
  89136. assert( pList!=0 );
  89137. assert( target>0 );
  89138. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  89139. n = pList->nExpr;
  89140. if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
  89141. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  89142. Expr *pExpr = pItem->pExpr;
  89143. if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
  89144. if( flags & SQLITE_ECEL_OMITREF ){
  89145. i--;
  89146. n--;
  89147. }else{
  89148. sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
  89149. }
  89150. }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
  89151. sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
  89152. }else{
  89153. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  89154. if( inReg!=target+i ){
  89155. VdbeOp *pOp;
  89156. if( copyOp==OP_Copy
  89157. && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
  89158. && pOp->p1+pOp->p3+1==inReg
  89159. && pOp->p2+pOp->p3+1==target+i
  89160. ){
  89161. pOp->p3++;
  89162. }else{
  89163. sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
  89164. }
  89165. }
  89166. }
  89167. }
  89168. return n;
  89169. }
  89170. /*
  89171. ** Generate code for a BETWEEN operator.
  89172. **
  89173. ** x BETWEEN y AND z
  89174. **
  89175. ** The above is equivalent to
  89176. **
  89177. ** x>=y AND x<=z
  89178. **
  89179. ** Code it as such, taking care to do the common subexpression
  89180. ** elimination of x.
  89181. **
  89182. ** The xJumpIf parameter determines details:
  89183. **
  89184. ** NULL: Store the boolean result in reg[dest]
  89185. ** sqlite3ExprIfTrue: Jump to dest if true
  89186. ** sqlite3ExprIfFalse: Jump to dest if false
  89187. **
  89188. ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
  89189. */
  89190. static void exprCodeBetween(
  89191. Parse *pParse, /* Parsing and code generating context */
  89192. Expr *pExpr, /* The BETWEEN expression */
  89193. int dest, /* Jump destination or storage location */
  89194. void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
  89195. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  89196. ){
  89197. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  89198. Expr compLeft; /* The x>=y term */
  89199. Expr compRight; /* The x<=z term */
  89200. Expr exprX; /* The x subexpression */
  89201. int regFree1 = 0; /* Temporary use register */
  89202. memset(&compLeft, 0, sizeof(Expr));
  89203. memset(&compRight, 0, sizeof(Expr));
  89204. memset(&exprAnd, 0, sizeof(Expr));
  89205. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  89206. exprX = *pExpr->pLeft;
  89207. exprAnd.op = TK_AND;
  89208. exprAnd.pLeft = &compLeft;
  89209. exprAnd.pRight = &compRight;
  89210. compLeft.op = TK_GE;
  89211. compLeft.pLeft = &exprX;
  89212. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  89213. compRight.op = TK_LE;
  89214. compRight.pLeft = &exprX;
  89215. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  89216. exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
  89217. if( xJump ){
  89218. xJump(pParse, &exprAnd, dest, jumpIfNull);
  89219. }else{
  89220. /* Mark the expression is being from the ON or USING clause of a join
  89221. ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
  89222. ** it into the Parse.pConstExpr list. We should use a new bit for this,
  89223. ** for clarity, but we are out of bits in the Expr.flags field so we
  89224. ** have to reuse the EP_FromJoin bit. Bummer. */
  89225. exprX.flags |= EP_FromJoin;
  89226. sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
  89227. }
  89228. sqlite3ReleaseTempReg(pParse, regFree1);
  89229. /* Ensure adequate test coverage */
  89230. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
  89231. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
  89232. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
  89233. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
  89234. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
  89235. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
  89236. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
  89237. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
  89238. testcase( xJump==0 );
  89239. }
  89240. /*
  89241. ** Generate code for a boolean expression such that a jump is made
  89242. ** to the label "dest" if the expression is true but execution
  89243. ** continues straight thru if the expression is false.
  89244. **
  89245. ** If the expression evaluates to NULL (neither true nor false), then
  89246. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  89247. **
  89248. ** This code depends on the fact that certain token values (ex: TK_EQ)
  89249. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  89250. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  89251. ** the make process cause these values to align. Assert()s in the code
  89252. ** below verify that the numbers are aligned correctly.
  89253. */
  89254. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  89255. Vdbe *v = pParse->pVdbe;
  89256. int op = 0;
  89257. int regFree1 = 0;
  89258. int regFree2 = 0;
  89259. int r1, r2;
  89260. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  89261. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  89262. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  89263. op = pExpr->op;
  89264. switch( op ){
  89265. case TK_AND: {
  89266. int d2 = sqlite3VdbeMakeLabel(v);
  89267. testcase( jumpIfNull==0 );
  89268. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  89269. sqlite3ExprCachePush(pParse);
  89270. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  89271. sqlite3VdbeResolveLabel(v, d2);
  89272. sqlite3ExprCachePop(pParse);
  89273. break;
  89274. }
  89275. case TK_OR: {
  89276. testcase( jumpIfNull==0 );
  89277. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  89278. sqlite3ExprCachePush(pParse);
  89279. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  89280. sqlite3ExprCachePop(pParse);
  89281. break;
  89282. }
  89283. case TK_NOT: {
  89284. testcase( jumpIfNull==0 );
  89285. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  89286. break;
  89287. }
  89288. case TK_IS:
  89289. case TK_ISNOT:
  89290. testcase( op==TK_IS );
  89291. testcase( op==TK_ISNOT );
  89292. op = (op==TK_IS) ? TK_EQ : TK_NE;
  89293. jumpIfNull = SQLITE_NULLEQ;
  89294. /* Fall thru */
  89295. case TK_LT:
  89296. case TK_LE:
  89297. case TK_GT:
  89298. case TK_GE:
  89299. case TK_NE:
  89300. case TK_EQ: {
  89301. if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
  89302. testcase( jumpIfNull==0 );
  89303. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  89304. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  89305. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  89306. r1, r2, dest, jumpIfNull);
  89307. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  89308. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  89309. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  89310. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  89311. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  89312. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  89313. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  89314. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  89315. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  89316. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  89317. testcase( regFree1==0 );
  89318. testcase( regFree2==0 );
  89319. break;
  89320. }
  89321. case TK_ISNULL:
  89322. case TK_NOTNULL: {
  89323. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  89324. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  89325. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  89326. sqlite3VdbeAddOp2(v, op, r1, dest);
  89327. VdbeCoverageIf(v, op==TK_ISNULL);
  89328. VdbeCoverageIf(v, op==TK_NOTNULL);
  89329. testcase( regFree1==0 );
  89330. break;
  89331. }
  89332. case TK_BETWEEN: {
  89333. testcase( jumpIfNull==0 );
  89334. exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
  89335. break;
  89336. }
  89337. #ifndef SQLITE_OMIT_SUBQUERY
  89338. case TK_IN: {
  89339. int destIfFalse = sqlite3VdbeMakeLabel(v);
  89340. int destIfNull = jumpIfNull ? dest : destIfFalse;
  89341. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  89342. sqlite3VdbeGoto(v, dest);
  89343. sqlite3VdbeResolveLabel(v, destIfFalse);
  89344. break;
  89345. }
  89346. #endif
  89347. default: {
  89348. default_expr:
  89349. if( exprAlwaysTrue(pExpr) ){
  89350. sqlite3VdbeGoto(v, dest);
  89351. }else if( exprAlwaysFalse(pExpr) ){
  89352. /* No-op */
  89353. }else{
  89354. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  89355. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  89356. VdbeCoverage(v);
  89357. testcase( regFree1==0 );
  89358. testcase( jumpIfNull==0 );
  89359. }
  89360. break;
  89361. }
  89362. }
  89363. sqlite3ReleaseTempReg(pParse, regFree1);
  89364. sqlite3ReleaseTempReg(pParse, regFree2);
  89365. }
  89366. /*
  89367. ** Generate code for a boolean expression such that a jump is made
  89368. ** to the label "dest" if the expression is false but execution
  89369. ** continues straight thru if the expression is true.
  89370. **
  89371. ** If the expression evaluates to NULL (neither true nor false) then
  89372. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  89373. ** is 0.
  89374. */
  89375. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  89376. Vdbe *v = pParse->pVdbe;
  89377. int op = 0;
  89378. int regFree1 = 0;
  89379. int regFree2 = 0;
  89380. int r1, r2;
  89381. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  89382. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  89383. if( pExpr==0 ) return;
  89384. /* The value of pExpr->op and op are related as follows:
  89385. **
  89386. ** pExpr->op op
  89387. ** --------- ----------
  89388. ** TK_ISNULL OP_NotNull
  89389. ** TK_NOTNULL OP_IsNull
  89390. ** TK_NE OP_Eq
  89391. ** TK_EQ OP_Ne
  89392. ** TK_GT OP_Le
  89393. ** TK_LE OP_Gt
  89394. ** TK_GE OP_Lt
  89395. ** TK_LT OP_Ge
  89396. **
  89397. ** For other values of pExpr->op, op is undefined and unused.
  89398. ** The value of TK_ and OP_ constants are arranged such that we
  89399. ** can compute the mapping above using the following expression.
  89400. ** Assert()s verify that the computation is correct.
  89401. */
  89402. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  89403. /* Verify correct alignment of TK_ and OP_ constants
  89404. */
  89405. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  89406. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  89407. assert( pExpr->op!=TK_NE || op==OP_Eq );
  89408. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  89409. assert( pExpr->op!=TK_LT || op==OP_Ge );
  89410. assert( pExpr->op!=TK_LE || op==OP_Gt );
  89411. assert( pExpr->op!=TK_GT || op==OP_Le );
  89412. assert( pExpr->op!=TK_GE || op==OP_Lt );
  89413. switch( pExpr->op ){
  89414. case TK_AND: {
  89415. testcase( jumpIfNull==0 );
  89416. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  89417. sqlite3ExprCachePush(pParse);
  89418. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  89419. sqlite3ExprCachePop(pParse);
  89420. break;
  89421. }
  89422. case TK_OR: {
  89423. int d2 = sqlite3VdbeMakeLabel(v);
  89424. testcase( jumpIfNull==0 );
  89425. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  89426. sqlite3ExprCachePush(pParse);
  89427. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  89428. sqlite3VdbeResolveLabel(v, d2);
  89429. sqlite3ExprCachePop(pParse);
  89430. break;
  89431. }
  89432. case TK_NOT: {
  89433. testcase( jumpIfNull==0 );
  89434. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  89435. break;
  89436. }
  89437. case TK_IS:
  89438. case TK_ISNOT:
  89439. testcase( pExpr->op==TK_IS );
  89440. testcase( pExpr->op==TK_ISNOT );
  89441. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  89442. jumpIfNull = SQLITE_NULLEQ;
  89443. /* Fall thru */
  89444. case TK_LT:
  89445. case TK_LE:
  89446. case TK_GT:
  89447. case TK_GE:
  89448. case TK_NE:
  89449. case TK_EQ: {
  89450. if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
  89451. testcase( jumpIfNull==0 );
  89452. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  89453. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  89454. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  89455. r1, r2, dest, jumpIfNull);
  89456. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  89457. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  89458. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  89459. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  89460. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  89461. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  89462. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  89463. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  89464. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  89465. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  89466. testcase( regFree1==0 );
  89467. testcase( regFree2==0 );
  89468. break;
  89469. }
  89470. case TK_ISNULL:
  89471. case TK_NOTNULL: {
  89472. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  89473. sqlite3VdbeAddOp2(v, op, r1, dest);
  89474. testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
  89475. testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
  89476. testcase( regFree1==0 );
  89477. break;
  89478. }
  89479. case TK_BETWEEN: {
  89480. testcase( jumpIfNull==0 );
  89481. exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
  89482. break;
  89483. }
  89484. #ifndef SQLITE_OMIT_SUBQUERY
  89485. case TK_IN: {
  89486. if( jumpIfNull ){
  89487. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  89488. }else{
  89489. int destIfNull = sqlite3VdbeMakeLabel(v);
  89490. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  89491. sqlite3VdbeResolveLabel(v, destIfNull);
  89492. }
  89493. break;
  89494. }
  89495. #endif
  89496. default: {
  89497. default_expr:
  89498. if( exprAlwaysFalse(pExpr) ){
  89499. sqlite3VdbeGoto(v, dest);
  89500. }else if( exprAlwaysTrue(pExpr) ){
  89501. /* no-op */
  89502. }else{
  89503. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  89504. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  89505. VdbeCoverage(v);
  89506. testcase( regFree1==0 );
  89507. testcase( jumpIfNull==0 );
  89508. }
  89509. break;
  89510. }
  89511. }
  89512. sqlite3ReleaseTempReg(pParse, regFree1);
  89513. sqlite3ReleaseTempReg(pParse, regFree2);
  89514. }
  89515. /*
  89516. ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
  89517. ** code generation, and that copy is deleted after code generation. This
  89518. ** ensures that the original pExpr is unchanged.
  89519. */
  89520. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
  89521. sqlite3 *db = pParse->db;
  89522. Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
  89523. if( db->mallocFailed==0 ){
  89524. sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
  89525. }
  89526. sqlite3ExprDelete(db, pCopy);
  89527. }
  89528. /*
  89529. ** Do a deep comparison of two expression trees. Return 0 if the two
  89530. ** expressions are completely identical. Return 1 if they differ only
  89531. ** by a COLLATE operator at the top level. Return 2 if there are differences
  89532. ** other than the top-level COLLATE operator.
  89533. **
  89534. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  89535. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  89536. **
  89537. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  89538. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  89539. **
  89540. ** Sometimes this routine will return 2 even if the two expressions
  89541. ** really are equivalent. If we cannot prove that the expressions are
  89542. ** identical, we return 2 just to be safe. So if this routine
  89543. ** returns 2, then you do not really know for certain if the two
  89544. ** expressions are the same. But if you get a 0 or 1 return, then you
  89545. ** can be sure the expressions are the same. In the places where
  89546. ** this routine is used, it does not hurt to get an extra 2 - that
  89547. ** just might result in some slightly slower code. But returning
  89548. ** an incorrect 0 or 1 could lead to a malfunction.
  89549. */
  89550. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
  89551. u32 combinedFlags;
  89552. if( pA==0 || pB==0 ){
  89553. return pB==pA ? 0 : 2;
  89554. }
  89555. combinedFlags = pA->flags | pB->flags;
  89556. if( combinedFlags & EP_IntValue ){
  89557. if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
  89558. return 0;
  89559. }
  89560. return 2;
  89561. }
  89562. if( pA->op!=pB->op ){
  89563. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
  89564. return 1;
  89565. }
  89566. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
  89567. return 1;
  89568. }
  89569. return 2;
  89570. }
  89571. if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
  89572. if( pA->op==TK_FUNCTION ){
  89573. if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
  89574. }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  89575. return pA->op==TK_COLLATE ? 1 : 2;
  89576. }
  89577. }
  89578. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  89579. if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
  89580. if( combinedFlags & EP_xIsSelect ) return 2;
  89581. if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
  89582. if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
  89583. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  89584. if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
  89585. if( pA->iColumn!=pB->iColumn ) return 2;
  89586. if( pA->iTable!=pB->iTable
  89587. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  89588. }
  89589. }
  89590. return 0;
  89591. }
  89592. /*
  89593. ** Compare two ExprList objects. Return 0 if they are identical and
  89594. ** non-zero if they differ in any way.
  89595. **
  89596. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  89597. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  89598. **
  89599. ** This routine might return non-zero for equivalent ExprLists. The
  89600. ** only consequence will be disabled optimizations. But this routine
  89601. ** must never return 0 if the two ExprList objects are different, or
  89602. ** a malfunction will result.
  89603. **
  89604. ** Two NULL pointers are considered to be the same. But a NULL pointer
  89605. ** always differs from a non-NULL pointer.
  89606. */
  89607. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  89608. int i;
  89609. if( pA==0 && pB==0 ) return 0;
  89610. if( pA==0 || pB==0 ) return 1;
  89611. if( pA->nExpr!=pB->nExpr ) return 1;
  89612. for(i=0; i<pA->nExpr; i++){
  89613. Expr *pExprA = pA->a[i].pExpr;
  89614. Expr *pExprB = pB->a[i].pExpr;
  89615. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  89616. if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
  89617. }
  89618. return 0;
  89619. }
  89620. /*
  89621. ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
  89622. ** are ignored.
  89623. */
  89624. SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
  89625. return sqlite3ExprCompare(
  89626. sqlite3ExprSkipCollate(pA),
  89627. sqlite3ExprSkipCollate(pB),
  89628. iTab);
  89629. }
  89630. /*
  89631. ** Return true if we can prove the pE2 will always be true if pE1 is
  89632. ** true. Return false if we cannot complete the proof or if pE2 might
  89633. ** be false. Examples:
  89634. **
  89635. ** pE1: x==5 pE2: x==5 Result: true
  89636. ** pE1: x>0 pE2: x==5 Result: false
  89637. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  89638. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  89639. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  89640. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  89641. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  89642. **
  89643. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  89644. ** Expr.iTable<0 then assume a table number given by iTab.
  89645. **
  89646. ** When in doubt, return false. Returning true might give a performance
  89647. ** improvement. Returning false might cause a performance reduction, but
  89648. ** it will always give the correct answer and is hence always safe.
  89649. */
  89650. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
  89651. if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
  89652. return 1;
  89653. }
  89654. if( pE2->op==TK_OR
  89655. && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
  89656. || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
  89657. ){
  89658. return 1;
  89659. }
  89660. if( pE2->op==TK_NOTNULL && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){
  89661. Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft);
  89662. testcase( pX!=pE1->pLeft );
  89663. if( sqlite3ExprCompare(pX, pE2->pLeft, iTab)==0 ) return 1;
  89664. }
  89665. return 0;
  89666. }
  89667. /*
  89668. ** An instance of the following structure is used by the tree walker
  89669. ** to determine if an expression can be evaluated by reference to the
  89670. ** index only, without having to do a search for the corresponding
  89671. ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
  89672. ** is the cursor for the table.
  89673. */
  89674. struct IdxCover {
  89675. Index *pIdx; /* The index to be tested for coverage */
  89676. int iCur; /* Cursor number for the table corresponding to the index */
  89677. };
  89678. /*
  89679. ** Check to see if there are references to columns in table
  89680. ** pWalker->u.pIdxCover->iCur can be satisfied using the index
  89681. ** pWalker->u.pIdxCover->pIdx.
  89682. */
  89683. static int exprIdxCover(Walker *pWalker, Expr *pExpr){
  89684. if( pExpr->op==TK_COLUMN
  89685. && pExpr->iTable==pWalker->u.pIdxCover->iCur
  89686. && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
  89687. ){
  89688. pWalker->eCode = 1;
  89689. return WRC_Abort;
  89690. }
  89691. return WRC_Continue;
  89692. }
  89693. /*
  89694. ** Determine if an index pIdx on table with cursor iCur contains will
  89695. ** the expression pExpr. Return true if the index does cover the
  89696. ** expression and false if the pExpr expression references table columns
  89697. ** that are not found in the index pIdx.
  89698. **
  89699. ** An index covering an expression means that the expression can be
  89700. ** evaluated using only the index and without having to lookup the
  89701. ** corresponding table entry.
  89702. */
  89703. SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
  89704. Expr *pExpr, /* The index to be tested */
  89705. int iCur, /* The cursor number for the corresponding table */
  89706. Index *pIdx /* The index that might be used for coverage */
  89707. ){
  89708. Walker w;
  89709. struct IdxCover xcov;
  89710. memset(&w, 0, sizeof(w));
  89711. xcov.iCur = iCur;
  89712. xcov.pIdx = pIdx;
  89713. w.xExprCallback = exprIdxCover;
  89714. w.u.pIdxCover = &xcov;
  89715. sqlite3WalkExpr(&w, pExpr);
  89716. return !w.eCode;
  89717. }
  89718. /*
  89719. ** An instance of the following structure is used by the tree walker
  89720. ** to count references to table columns in the arguments of an
  89721. ** aggregate function, in order to implement the
  89722. ** sqlite3FunctionThisSrc() routine.
  89723. */
  89724. struct SrcCount {
  89725. SrcList *pSrc; /* One particular FROM clause in a nested query */
  89726. int nThis; /* Number of references to columns in pSrcList */
  89727. int nOther; /* Number of references to columns in other FROM clauses */
  89728. };
  89729. /*
  89730. ** Count the number of references to columns.
  89731. */
  89732. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  89733. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  89734. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  89735. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  89736. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  89737. ** NEVER() will need to be removed. */
  89738. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  89739. int i;
  89740. struct SrcCount *p = pWalker->u.pSrcCount;
  89741. SrcList *pSrc = p->pSrc;
  89742. int nSrc = pSrc ? pSrc->nSrc : 0;
  89743. for(i=0; i<nSrc; i++){
  89744. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  89745. }
  89746. if( i<nSrc ){
  89747. p->nThis++;
  89748. }else{
  89749. p->nOther++;
  89750. }
  89751. }
  89752. return WRC_Continue;
  89753. }
  89754. /*
  89755. ** Determine if any of the arguments to the pExpr Function reference
  89756. ** pSrcList. Return true if they do. Also return true if the function
  89757. ** has no arguments or has only constant arguments. Return false if pExpr
  89758. ** references columns but not columns of tables found in pSrcList.
  89759. */
  89760. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  89761. Walker w;
  89762. struct SrcCount cnt;
  89763. assert( pExpr->op==TK_AGG_FUNCTION );
  89764. memset(&w, 0, sizeof(w));
  89765. w.xExprCallback = exprSrcCount;
  89766. w.u.pSrcCount = &cnt;
  89767. cnt.pSrc = pSrcList;
  89768. cnt.nThis = 0;
  89769. cnt.nOther = 0;
  89770. sqlite3WalkExprList(&w, pExpr->x.pList);
  89771. return cnt.nThis>0 || cnt.nOther==0;
  89772. }
  89773. /*
  89774. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  89775. ** the new element. Return a negative number if malloc fails.
  89776. */
  89777. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  89778. int i;
  89779. pInfo->aCol = sqlite3ArrayAllocate(
  89780. db,
  89781. pInfo->aCol,
  89782. sizeof(pInfo->aCol[0]),
  89783. &pInfo->nColumn,
  89784. &i
  89785. );
  89786. return i;
  89787. }
  89788. /*
  89789. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  89790. ** the new element. Return a negative number if malloc fails.
  89791. */
  89792. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  89793. int i;
  89794. pInfo->aFunc = sqlite3ArrayAllocate(
  89795. db,
  89796. pInfo->aFunc,
  89797. sizeof(pInfo->aFunc[0]),
  89798. &pInfo->nFunc,
  89799. &i
  89800. );
  89801. return i;
  89802. }
  89803. /*
  89804. ** This is the xExprCallback for a tree walker. It is used to
  89805. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  89806. ** for additional information.
  89807. */
  89808. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  89809. int i;
  89810. NameContext *pNC = pWalker->u.pNC;
  89811. Parse *pParse = pNC->pParse;
  89812. SrcList *pSrcList = pNC->pSrcList;
  89813. AggInfo *pAggInfo = pNC->pAggInfo;
  89814. switch( pExpr->op ){
  89815. case TK_AGG_COLUMN:
  89816. case TK_COLUMN: {
  89817. testcase( pExpr->op==TK_AGG_COLUMN );
  89818. testcase( pExpr->op==TK_COLUMN );
  89819. /* Check to see if the column is in one of the tables in the FROM
  89820. ** clause of the aggregate query */
  89821. if( ALWAYS(pSrcList!=0) ){
  89822. struct SrcList_item *pItem = pSrcList->a;
  89823. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  89824. struct AggInfo_col *pCol;
  89825. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  89826. if( pExpr->iTable==pItem->iCursor ){
  89827. /* If we reach this point, it means that pExpr refers to a table
  89828. ** that is in the FROM clause of the aggregate query.
  89829. **
  89830. ** Make an entry for the column in pAggInfo->aCol[] if there
  89831. ** is not an entry there already.
  89832. */
  89833. int k;
  89834. pCol = pAggInfo->aCol;
  89835. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  89836. if( pCol->iTable==pExpr->iTable &&
  89837. pCol->iColumn==pExpr->iColumn ){
  89838. break;
  89839. }
  89840. }
  89841. if( (k>=pAggInfo->nColumn)
  89842. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  89843. ){
  89844. pCol = &pAggInfo->aCol[k];
  89845. pCol->pTab = pExpr->pTab;
  89846. pCol->iTable = pExpr->iTable;
  89847. pCol->iColumn = pExpr->iColumn;
  89848. pCol->iMem = ++pParse->nMem;
  89849. pCol->iSorterColumn = -1;
  89850. pCol->pExpr = pExpr;
  89851. if( pAggInfo->pGroupBy ){
  89852. int j, n;
  89853. ExprList *pGB = pAggInfo->pGroupBy;
  89854. struct ExprList_item *pTerm = pGB->a;
  89855. n = pGB->nExpr;
  89856. for(j=0; j<n; j++, pTerm++){
  89857. Expr *pE = pTerm->pExpr;
  89858. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  89859. pE->iColumn==pExpr->iColumn ){
  89860. pCol->iSorterColumn = j;
  89861. break;
  89862. }
  89863. }
  89864. }
  89865. if( pCol->iSorterColumn<0 ){
  89866. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  89867. }
  89868. }
  89869. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  89870. ** because it was there before or because we just created it).
  89871. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  89872. ** pAggInfo->aCol[] entry.
  89873. */
  89874. ExprSetVVAProperty(pExpr, EP_NoReduce);
  89875. pExpr->pAggInfo = pAggInfo;
  89876. pExpr->op = TK_AGG_COLUMN;
  89877. pExpr->iAgg = (i16)k;
  89878. break;
  89879. } /* endif pExpr->iTable==pItem->iCursor */
  89880. } /* end loop over pSrcList */
  89881. }
  89882. return WRC_Prune;
  89883. }
  89884. case TK_AGG_FUNCTION: {
  89885. if( (pNC->ncFlags & NC_InAggFunc)==0
  89886. && pWalker->walkerDepth==pExpr->op2
  89887. ){
  89888. /* Check to see if pExpr is a duplicate of another aggregate
  89889. ** function that is already in the pAggInfo structure
  89890. */
  89891. struct AggInfo_func *pItem = pAggInfo->aFunc;
  89892. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  89893. if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
  89894. break;
  89895. }
  89896. }
  89897. if( i>=pAggInfo->nFunc ){
  89898. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  89899. */
  89900. u8 enc = ENC(pParse->db);
  89901. i = addAggInfoFunc(pParse->db, pAggInfo);
  89902. if( i>=0 ){
  89903. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  89904. pItem = &pAggInfo->aFunc[i];
  89905. pItem->pExpr = pExpr;
  89906. pItem->iMem = ++pParse->nMem;
  89907. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  89908. pItem->pFunc = sqlite3FindFunction(pParse->db,
  89909. pExpr->u.zToken,
  89910. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  89911. if( pExpr->flags & EP_Distinct ){
  89912. pItem->iDistinct = pParse->nTab++;
  89913. }else{
  89914. pItem->iDistinct = -1;
  89915. }
  89916. }
  89917. }
  89918. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  89919. */
  89920. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  89921. ExprSetVVAProperty(pExpr, EP_NoReduce);
  89922. pExpr->iAgg = (i16)i;
  89923. pExpr->pAggInfo = pAggInfo;
  89924. return WRC_Prune;
  89925. }else{
  89926. return WRC_Continue;
  89927. }
  89928. }
  89929. }
  89930. return WRC_Continue;
  89931. }
  89932. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  89933. UNUSED_PARAMETER(pWalker);
  89934. UNUSED_PARAMETER(pSelect);
  89935. return WRC_Continue;
  89936. }
  89937. /*
  89938. ** Analyze the pExpr expression looking for aggregate functions and
  89939. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  89940. ** points to. Additional entries are made on the AggInfo object as
  89941. ** necessary.
  89942. **
  89943. ** This routine should only be called after the expression has been
  89944. ** analyzed by sqlite3ResolveExprNames().
  89945. */
  89946. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  89947. Walker w;
  89948. memset(&w, 0, sizeof(w));
  89949. w.xExprCallback = analyzeAggregate;
  89950. w.xSelectCallback = analyzeAggregatesInSelect;
  89951. w.u.pNC = pNC;
  89952. assert( pNC->pSrcList!=0 );
  89953. sqlite3WalkExpr(&w, pExpr);
  89954. }
  89955. /*
  89956. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  89957. ** expression list. Return the number of errors.
  89958. **
  89959. ** If an error is found, the analysis is cut short.
  89960. */
  89961. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  89962. struct ExprList_item *pItem;
  89963. int i;
  89964. if( pList ){
  89965. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  89966. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  89967. }
  89968. }
  89969. }
  89970. /*
  89971. ** Allocate a single new register for use to hold some intermediate result.
  89972. */
  89973. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  89974. if( pParse->nTempReg==0 ){
  89975. return ++pParse->nMem;
  89976. }
  89977. return pParse->aTempReg[--pParse->nTempReg];
  89978. }
  89979. /*
  89980. ** Deallocate a register, making available for reuse for some other
  89981. ** purpose.
  89982. **
  89983. ** If a register is currently being used by the column cache, then
  89984. ** the deallocation is deferred until the column cache line that uses
  89985. ** the register becomes stale.
  89986. */
  89987. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  89988. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  89989. int i;
  89990. struct yColCache *p;
  89991. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  89992. if( p->iReg==iReg ){
  89993. p->tempReg = 1;
  89994. return;
  89995. }
  89996. }
  89997. pParse->aTempReg[pParse->nTempReg++] = iReg;
  89998. }
  89999. }
  90000. /*
  90001. ** Allocate or deallocate a block of nReg consecutive registers.
  90002. */
  90003. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  90004. int i, n;
  90005. if( nReg==1 ) return sqlite3GetTempReg(pParse);
  90006. i = pParse->iRangeReg;
  90007. n = pParse->nRangeReg;
  90008. if( nReg<=n ){
  90009. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  90010. pParse->iRangeReg += nReg;
  90011. pParse->nRangeReg -= nReg;
  90012. }else{
  90013. i = pParse->nMem+1;
  90014. pParse->nMem += nReg;
  90015. }
  90016. return i;
  90017. }
  90018. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  90019. if( nReg==1 ){
  90020. sqlite3ReleaseTempReg(pParse, iReg);
  90021. return;
  90022. }
  90023. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  90024. if( nReg>pParse->nRangeReg ){
  90025. pParse->nRangeReg = nReg;
  90026. pParse->iRangeReg = iReg;
  90027. }
  90028. }
  90029. /*
  90030. ** Mark all temporary registers as being unavailable for reuse.
  90031. */
  90032. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  90033. pParse->nTempReg = 0;
  90034. pParse->nRangeReg = 0;
  90035. }
  90036. /*
  90037. ** Validate that no temporary register falls within the range of
  90038. ** iFirst..iLast, inclusive. This routine is only call from within assert()
  90039. ** statements.
  90040. */
  90041. #ifdef SQLITE_DEBUG
  90042. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
  90043. int i;
  90044. if( pParse->nRangeReg>0
  90045. && pParse->iRangeReg+pParse->nRangeReg<iLast
  90046. && pParse->iRangeReg>=iFirst
  90047. ){
  90048. return 0;
  90049. }
  90050. for(i=0; i<pParse->nTempReg; i++){
  90051. if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
  90052. return 0;
  90053. }
  90054. }
  90055. return 1;
  90056. }
  90057. #endif /* SQLITE_DEBUG */
  90058. /************** End of expr.c ************************************************/
  90059. /************** Begin file alter.c *******************************************/
  90060. /*
  90061. ** 2005 February 15
  90062. **
  90063. ** The author disclaims copyright to this source code. In place of
  90064. ** a legal notice, here is a blessing:
  90065. **
  90066. ** May you do good and not evil.
  90067. ** May you find forgiveness for yourself and forgive others.
  90068. ** May you share freely, never taking more than you give.
  90069. **
  90070. *************************************************************************
  90071. ** This file contains C code routines that used to generate VDBE code
  90072. ** that implements the ALTER TABLE command.
  90073. */
  90074. /* #include "sqliteInt.h" */
  90075. /*
  90076. ** The code in this file only exists if we are not omitting the
  90077. ** ALTER TABLE logic from the build.
  90078. */
  90079. #ifndef SQLITE_OMIT_ALTERTABLE
  90080. /*
  90081. ** This function is used by SQL generated to implement the
  90082. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  90083. ** CREATE INDEX command. The second is a table name. The table name in
  90084. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  90085. ** argument and the result returned. Examples:
  90086. **
  90087. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  90088. ** -> 'CREATE TABLE def(a, b, c)'
  90089. **
  90090. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  90091. ** -> 'CREATE INDEX i ON def(a, b, c)'
  90092. */
  90093. static void renameTableFunc(
  90094. sqlite3_context *context,
  90095. int NotUsed,
  90096. sqlite3_value **argv
  90097. ){
  90098. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  90099. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  90100. int token;
  90101. Token tname;
  90102. unsigned char const *zCsr = zSql;
  90103. int len = 0;
  90104. char *zRet;
  90105. sqlite3 *db = sqlite3_context_db_handle(context);
  90106. UNUSED_PARAMETER(NotUsed);
  90107. /* The principle used to locate the table name in the CREATE TABLE
  90108. ** statement is that the table name is the first non-space token that
  90109. ** is immediately followed by a TK_LP or TK_USING token.
  90110. */
  90111. if( zSql ){
  90112. do {
  90113. if( !*zCsr ){
  90114. /* Ran out of input before finding an opening bracket. Return NULL. */
  90115. return;
  90116. }
  90117. /* Store the token that zCsr points to in tname. */
  90118. tname.z = (char*)zCsr;
  90119. tname.n = len;
  90120. /* Advance zCsr to the next token. Store that token type in 'token',
  90121. ** and its length in 'len' (to be used next iteration of this loop).
  90122. */
  90123. do {
  90124. zCsr += len;
  90125. len = sqlite3GetToken(zCsr, &token);
  90126. } while( token==TK_SPACE );
  90127. assert( len>0 );
  90128. } while( token!=TK_LP && token!=TK_USING );
  90129. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  90130. zSql, zTableName, tname.z+tname.n);
  90131. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  90132. }
  90133. }
  90134. /*
  90135. ** This C function implements an SQL user function that is used by SQL code
  90136. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  90137. ** of any foreign key constraints that use the table being renamed as the
  90138. ** parent table. It is passed three arguments:
  90139. **
  90140. ** 1) The complete text of the CREATE TABLE statement being modified,
  90141. ** 2) The old name of the table being renamed, and
  90142. ** 3) The new name of the table being renamed.
  90143. **
  90144. ** It returns the new CREATE TABLE statement. For example:
  90145. **
  90146. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  90147. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  90148. */
  90149. #ifndef SQLITE_OMIT_FOREIGN_KEY
  90150. static void renameParentFunc(
  90151. sqlite3_context *context,
  90152. int NotUsed,
  90153. sqlite3_value **argv
  90154. ){
  90155. sqlite3 *db = sqlite3_context_db_handle(context);
  90156. char *zOutput = 0;
  90157. char *zResult;
  90158. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  90159. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  90160. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  90161. unsigned const char *z; /* Pointer to token */
  90162. int n; /* Length of token z */
  90163. int token; /* Type of token */
  90164. UNUSED_PARAMETER(NotUsed);
  90165. if( zInput==0 || zOld==0 ) return;
  90166. for(z=zInput; *z; z=z+n){
  90167. n = sqlite3GetToken(z, &token);
  90168. if( token==TK_REFERENCES ){
  90169. char *zParent;
  90170. do {
  90171. z += n;
  90172. n = sqlite3GetToken(z, &token);
  90173. }while( token==TK_SPACE );
  90174. if( token==TK_ILLEGAL ) break;
  90175. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  90176. if( zParent==0 ) break;
  90177. sqlite3Dequote(zParent);
  90178. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  90179. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  90180. (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
  90181. );
  90182. sqlite3DbFree(db, zOutput);
  90183. zOutput = zOut;
  90184. zInput = &z[n];
  90185. }
  90186. sqlite3DbFree(db, zParent);
  90187. }
  90188. }
  90189. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  90190. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  90191. sqlite3DbFree(db, zOutput);
  90192. }
  90193. #endif
  90194. #ifndef SQLITE_OMIT_TRIGGER
  90195. /* This function is used by SQL generated to implement the
  90196. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  90197. ** statement. The second is a table name. The table name in the CREATE
  90198. ** TRIGGER statement is replaced with the third argument and the result
  90199. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  90200. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  90201. */
  90202. static void renameTriggerFunc(
  90203. sqlite3_context *context,
  90204. int NotUsed,
  90205. sqlite3_value **argv
  90206. ){
  90207. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  90208. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  90209. int token;
  90210. Token tname;
  90211. int dist = 3;
  90212. unsigned char const *zCsr = zSql;
  90213. int len = 0;
  90214. char *zRet;
  90215. sqlite3 *db = sqlite3_context_db_handle(context);
  90216. UNUSED_PARAMETER(NotUsed);
  90217. /* The principle used to locate the table name in the CREATE TRIGGER
  90218. ** statement is that the table name is the first token that is immediately
  90219. ** preceded by either TK_ON or TK_DOT and immediately followed by one
  90220. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  90221. */
  90222. if( zSql ){
  90223. do {
  90224. if( !*zCsr ){
  90225. /* Ran out of input before finding the table name. Return NULL. */
  90226. return;
  90227. }
  90228. /* Store the token that zCsr points to in tname. */
  90229. tname.z = (char*)zCsr;
  90230. tname.n = len;
  90231. /* Advance zCsr to the next token. Store that token type in 'token',
  90232. ** and its length in 'len' (to be used next iteration of this loop).
  90233. */
  90234. do {
  90235. zCsr += len;
  90236. len = sqlite3GetToken(zCsr, &token);
  90237. }while( token==TK_SPACE );
  90238. assert( len>0 );
  90239. /* Variable 'dist' stores the number of tokens read since the most
  90240. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  90241. ** token is read and 'dist' equals 2, the condition stated above
  90242. ** to be met.
  90243. **
  90244. ** Note that ON cannot be a database, table or column name, so
  90245. ** there is no need to worry about syntax like
  90246. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  90247. */
  90248. dist++;
  90249. if( token==TK_DOT || token==TK_ON ){
  90250. dist = 0;
  90251. }
  90252. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  90253. /* Variable tname now contains the token that is the old table-name
  90254. ** in the CREATE TRIGGER statement.
  90255. */
  90256. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  90257. zSql, zTableName, tname.z+tname.n);
  90258. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  90259. }
  90260. }
  90261. #endif /* !SQLITE_OMIT_TRIGGER */
  90262. /*
  90263. ** Register built-in functions used to help implement ALTER TABLE
  90264. */
  90265. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  90266. static FuncDef aAlterTableFuncs[] = {
  90267. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  90268. #ifndef SQLITE_OMIT_TRIGGER
  90269. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  90270. #endif
  90271. #ifndef SQLITE_OMIT_FOREIGN_KEY
  90272. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  90273. #endif
  90274. };
  90275. sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
  90276. }
  90277. /*
  90278. ** This function is used to create the text of expressions of the form:
  90279. **
  90280. ** name=<constant1> OR name=<constant2> OR ...
  90281. **
  90282. ** If argument zWhere is NULL, then a pointer string containing the text
  90283. ** "name=<constant>" is returned, where <constant> is the quoted version
  90284. ** of the string passed as argument zConstant. The returned buffer is
  90285. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  90286. ** caller to ensure that it is eventually freed.
  90287. **
  90288. ** If argument zWhere is not NULL, then the string returned is
  90289. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  90290. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  90291. **
  90292. */
  90293. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  90294. char *zNew;
  90295. if( !zWhere ){
  90296. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  90297. }else{
  90298. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  90299. sqlite3DbFree(db, zWhere);
  90300. }
  90301. return zNew;
  90302. }
  90303. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  90304. /*
  90305. ** Generate the text of a WHERE expression which can be used to select all
  90306. ** tables that have foreign key constraints that refer to table pTab (i.e.
  90307. ** constraints for which pTab is the parent table) from the sqlite_master
  90308. ** table.
  90309. */
  90310. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  90311. FKey *p;
  90312. char *zWhere = 0;
  90313. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  90314. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  90315. }
  90316. return zWhere;
  90317. }
  90318. #endif
  90319. /*
  90320. ** Generate the text of a WHERE expression which can be used to select all
  90321. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  90322. ** table pTab has no temporary triggers, or is itself stored in the
  90323. ** temporary database, NULL is returned.
  90324. */
  90325. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  90326. Trigger *pTrig;
  90327. char *zWhere = 0;
  90328. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  90329. /* If the table is not located in the temp-db (in which case NULL is
  90330. ** returned, loop through the tables list of triggers. For each trigger
  90331. ** that is not part of the temp-db schema, add a clause to the WHERE
  90332. ** expression being built up in zWhere.
  90333. */
  90334. if( pTab->pSchema!=pTempSchema ){
  90335. sqlite3 *db = pParse->db;
  90336. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  90337. if( pTrig->pSchema==pTempSchema ){
  90338. zWhere = whereOrName(db, zWhere, pTrig->zName);
  90339. }
  90340. }
  90341. }
  90342. if( zWhere ){
  90343. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  90344. sqlite3DbFree(pParse->db, zWhere);
  90345. zWhere = zNew;
  90346. }
  90347. return zWhere;
  90348. }
  90349. /*
  90350. ** Generate code to drop and reload the internal representation of table
  90351. ** pTab from the database, including triggers and temporary triggers.
  90352. ** Argument zName is the name of the table in the database schema at
  90353. ** the time the generated code is executed. This can be different from
  90354. ** pTab->zName if this function is being called to code part of an
  90355. ** "ALTER TABLE RENAME TO" statement.
  90356. */
  90357. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  90358. Vdbe *v;
  90359. char *zWhere;
  90360. int iDb; /* Index of database containing pTab */
  90361. #ifndef SQLITE_OMIT_TRIGGER
  90362. Trigger *pTrig;
  90363. #endif
  90364. v = sqlite3GetVdbe(pParse);
  90365. if( NEVER(v==0) ) return;
  90366. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  90367. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  90368. assert( iDb>=0 );
  90369. #ifndef SQLITE_OMIT_TRIGGER
  90370. /* Drop any table triggers from the internal schema. */
  90371. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  90372. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  90373. assert( iTrigDb==iDb || iTrigDb==1 );
  90374. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  90375. }
  90376. #endif
  90377. /* Drop the table and index from the internal schema. */
  90378. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  90379. /* Reload the table, index and permanent trigger schemas. */
  90380. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  90381. if( !zWhere ) return;
  90382. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  90383. #ifndef SQLITE_OMIT_TRIGGER
  90384. /* Now, if the table is not stored in the temp database, reload any temp
  90385. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  90386. */
  90387. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  90388. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  90389. }
  90390. #endif
  90391. }
  90392. /*
  90393. ** Parameter zName is the name of a table that is about to be altered
  90394. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  90395. ** If the table is a system table, this function leaves an error message
  90396. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  90397. **
  90398. ** Or, if zName is not a system table, zero is returned.
  90399. */
  90400. static int isSystemTable(Parse *pParse, const char *zName){
  90401. if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  90402. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  90403. return 1;
  90404. }
  90405. return 0;
  90406. }
  90407. /*
  90408. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  90409. ** command.
  90410. */
  90411. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  90412. Parse *pParse, /* Parser context. */
  90413. SrcList *pSrc, /* The table to rename. */
  90414. Token *pName /* The new table name. */
  90415. ){
  90416. int iDb; /* Database that contains the table */
  90417. char *zDb; /* Name of database iDb */
  90418. Table *pTab; /* Table being renamed */
  90419. char *zName = 0; /* NULL-terminated version of pName */
  90420. sqlite3 *db = pParse->db; /* Database connection */
  90421. int nTabName; /* Number of UTF-8 characters in zTabName */
  90422. const char *zTabName; /* Original name of the table */
  90423. Vdbe *v;
  90424. #ifndef SQLITE_OMIT_TRIGGER
  90425. char *zWhere = 0; /* Where clause to locate temp triggers */
  90426. #endif
  90427. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  90428. int savedDbFlags; /* Saved value of db->flags */
  90429. savedDbFlags = db->flags;
  90430. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  90431. assert( pSrc->nSrc==1 );
  90432. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  90433. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  90434. if( !pTab ) goto exit_rename_table;
  90435. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  90436. zDb = db->aDb[iDb].zDbSName;
  90437. db->flags |= SQLITE_PreferBuiltin;
  90438. /* Get a NULL terminated version of the new table name. */
  90439. zName = sqlite3NameFromToken(db, pName);
  90440. if( !zName ) goto exit_rename_table;
  90441. /* Check that a table or index named 'zName' does not already exist
  90442. ** in database iDb. If so, this is an error.
  90443. */
  90444. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  90445. sqlite3ErrorMsg(pParse,
  90446. "there is already another table or index with this name: %s", zName);
  90447. goto exit_rename_table;
  90448. }
  90449. /* Make sure it is not a system table being altered, or a reserved name
  90450. ** that the table is being renamed to.
  90451. */
  90452. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  90453. goto exit_rename_table;
  90454. }
  90455. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  90456. exit_rename_table;
  90457. }
  90458. #ifndef SQLITE_OMIT_VIEW
  90459. if( pTab->pSelect ){
  90460. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  90461. goto exit_rename_table;
  90462. }
  90463. #endif
  90464. #ifndef SQLITE_OMIT_AUTHORIZATION
  90465. /* Invoke the authorization callback. */
  90466. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  90467. goto exit_rename_table;
  90468. }
  90469. #endif
  90470. #ifndef SQLITE_OMIT_VIRTUALTABLE
  90471. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  90472. goto exit_rename_table;
  90473. }
  90474. if( IsVirtual(pTab) ){
  90475. pVTab = sqlite3GetVTable(db, pTab);
  90476. if( pVTab->pVtab->pModule->xRename==0 ){
  90477. pVTab = 0;
  90478. }
  90479. }
  90480. #endif
  90481. /* Begin a transaction for database iDb.
  90482. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  90483. ** schema). Open a statement transaction if the table is a virtual
  90484. ** table.
  90485. */
  90486. v = sqlite3GetVdbe(pParse);
  90487. if( v==0 ){
  90488. goto exit_rename_table;
  90489. }
  90490. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  90491. sqlite3ChangeCookie(pParse, iDb);
  90492. /* If this is a virtual table, invoke the xRename() function if
  90493. ** one is defined. The xRename() callback will modify the names
  90494. ** of any resources used by the v-table implementation (including other
  90495. ** SQLite tables) that are identified by the name of the virtual table.
  90496. */
  90497. #ifndef SQLITE_OMIT_VIRTUALTABLE
  90498. if( pVTab ){
  90499. int i = ++pParse->nMem;
  90500. sqlite3VdbeLoadString(v, i, zName);
  90501. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  90502. sqlite3MayAbort(pParse);
  90503. }
  90504. #endif
  90505. /* figure out how many UTF-8 characters are in zName */
  90506. zTabName = pTab->zName;
  90507. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  90508. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  90509. if( db->flags&SQLITE_ForeignKeys ){
  90510. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  90511. ** statements corresponding to all child tables of foreign key constraints
  90512. ** for which the renamed table is the parent table. */
  90513. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  90514. sqlite3NestedParse(pParse,
  90515. "UPDATE \"%w\".%s SET "
  90516. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  90517. "WHERE %s;", zDb, MASTER_NAME, zTabName, zName, zWhere);
  90518. sqlite3DbFree(db, zWhere);
  90519. }
  90520. }
  90521. #endif
  90522. /* Modify the sqlite_master table to use the new table name. */
  90523. sqlite3NestedParse(pParse,
  90524. "UPDATE %Q.%s SET "
  90525. #ifdef SQLITE_OMIT_TRIGGER
  90526. "sql = sqlite_rename_table(sql, %Q), "
  90527. #else
  90528. "sql = CASE "
  90529. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  90530. "ELSE sqlite_rename_table(sql, %Q) END, "
  90531. #endif
  90532. "tbl_name = %Q, "
  90533. "name = CASE "
  90534. "WHEN type='table' THEN %Q "
  90535. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  90536. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  90537. "ELSE name END "
  90538. "WHERE tbl_name=%Q COLLATE nocase AND "
  90539. "(type='table' OR type='index' OR type='trigger');",
  90540. zDb, MASTER_NAME, zName, zName, zName,
  90541. #ifndef SQLITE_OMIT_TRIGGER
  90542. zName,
  90543. #endif
  90544. zName, nTabName, zTabName
  90545. );
  90546. #ifndef SQLITE_OMIT_AUTOINCREMENT
  90547. /* If the sqlite_sequence table exists in this database, then update
  90548. ** it with the new table name.
  90549. */
  90550. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  90551. sqlite3NestedParse(pParse,
  90552. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  90553. zDb, zName, pTab->zName);
  90554. }
  90555. #endif
  90556. #ifndef SQLITE_OMIT_TRIGGER
  90557. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  90558. ** table. Don't do this if the table being ALTERed is itself located in
  90559. ** the temp database.
  90560. */
  90561. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  90562. sqlite3NestedParse(pParse,
  90563. "UPDATE sqlite_temp_master SET "
  90564. "sql = sqlite_rename_trigger(sql, %Q), "
  90565. "tbl_name = %Q "
  90566. "WHERE %s;", zName, zName, zWhere);
  90567. sqlite3DbFree(db, zWhere);
  90568. }
  90569. #endif
  90570. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  90571. if( db->flags&SQLITE_ForeignKeys ){
  90572. FKey *p;
  90573. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  90574. Table *pFrom = p->pFrom;
  90575. if( pFrom!=pTab ){
  90576. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  90577. }
  90578. }
  90579. }
  90580. #endif
  90581. /* Drop and reload the internal table schema. */
  90582. reloadTableSchema(pParse, pTab, zName);
  90583. exit_rename_table:
  90584. sqlite3SrcListDelete(db, pSrc);
  90585. sqlite3DbFree(db, zName);
  90586. db->flags = savedDbFlags;
  90587. }
  90588. /*
  90589. ** This function is called after an "ALTER TABLE ... ADD" statement
  90590. ** has been parsed. Argument pColDef contains the text of the new
  90591. ** column definition.
  90592. **
  90593. ** The Table structure pParse->pNewTable was extended to include
  90594. ** the new column during parsing.
  90595. */
  90596. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  90597. Table *pNew; /* Copy of pParse->pNewTable */
  90598. Table *pTab; /* Table being altered */
  90599. int iDb; /* Database number */
  90600. const char *zDb; /* Database name */
  90601. const char *zTab; /* Table name */
  90602. char *zCol; /* Null-terminated column definition */
  90603. Column *pCol; /* The new column */
  90604. Expr *pDflt; /* Default value for the new column */
  90605. sqlite3 *db; /* The database connection; */
  90606. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  90607. int r1; /* Temporary registers */
  90608. db = pParse->db;
  90609. if( pParse->nErr || db->mallocFailed ) return;
  90610. assert( v!=0 );
  90611. pNew = pParse->pNewTable;
  90612. assert( pNew );
  90613. assert( sqlite3BtreeHoldsAllMutexes(db) );
  90614. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  90615. zDb = db->aDb[iDb].zDbSName;
  90616. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  90617. pCol = &pNew->aCol[pNew->nCol-1];
  90618. pDflt = pCol->pDflt;
  90619. pTab = sqlite3FindTable(db, zTab, zDb);
  90620. assert( pTab );
  90621. #ifndef SQLITE_OMIT_AUTHORIZATION
  90622. /* Invoke the authorization callback. */
  90623. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  90624. return;
  90625. }
  90626. #endif
  90627. /* If the default value for the new column was specified with a
  90628. ** literal NULL, then set pDflt to 0. This simplifies checking
  90629. ** for an SQL NULL default below.
  90630. */
  90631. assert( pDflt==0 || pDflt->op==TK_SPAN );
  90632. if( pDflt && pDflt->pLeft->op==TK_NULL ){
  90633. pDflt = 0;
  90634. }
  90635. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  90636. ** If there is a NOT NULL constraint, then the default value for the
  90637. ** column must not be NULL.
  90638. */
  90639. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  90640. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  90641. return;
  90642. }
  90643. if( pNew->pIndex ){
  90644. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  90645. return;
  90646. }
  90647. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  90648. sqlite3ErrorMsg(pParse,
  90649. "Cannot add a REFERENCES column with non-NULL default value");
  90650. return;
  90651. }
  90652. if( pCol->notNull && !pDflt ){
  90653. sqlite3ErrorMsg(pParse,
  90654. "Cannot add a NOT NULL column with default value NULL");
  90655. return;
  90656. }
  90657. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  90658. ** can handle (i.e. not CURRENT_TIME etc.)
  90659. */
  90660. if( pDflt ){
  90661. sqlite3_value *pVal = 0;
  90662. int rc;
  90663. rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
  90664. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  90665. if( rc!=SQLITE_OK ){
  90666. assert( db->mallocFailed == 1 );
  90667. return;
  90668. }
  90669. if( !pVal ){
  90670. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  90671. return;
  90672. }
  90673. sqlite3ValueFree(pVal);
  90674. }
  90675. /* Modify the CREATE TABLE statement. */
  90676. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  90677. if( zCol ){
  90678. char *zEnd = &zCol[pColDef->n-1];
  90679. int savedDbFlags = db->flags;
  90680. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  90681. *zEnd-- = '\0';
  90682. }
  90683. db->flags |= SQLITE_PreferBuiltin;
  90684. sqlite3NestedParse(pParse,
  90685. "UPDATE \"%w\".%s SET "
  90686. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  90687. "WHERE type = 'table' AND name = %Q",
  90688. zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
  90689. zTab
  90690. );
  90691. sqlite3DbFree(db, zCol);
  90692. db->flags = savedDbFlags;
  90693. }
  90694. /* Make sure the schema version is at least 3. But do not upgrade
  90695. ** from less than 3 to 4, as that will corrupt any preexisting DESC
  90696. ** index.
  90697. */
  90698. r1 = sqlite3GetTempReg(pParse);
  90699. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  90700. sqlite3VdbeUsesBtree(v, iDb);
  90701. sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
  90702. sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
  90703. VdbeCoverage(v);
  90704. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
  90705. sqlite3ReleaseTempReg(pParse, r1);
  90706. /* Reload the schema of the modified table. */
  90707. reloadTableSchema(pParse, pTab, pTab->zName);
  90708. }
  90709. /*
  90710. ** This function is called by the parser after the table-name in
  90711. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  90712. ** pSrc is the full-name of the table being altered.
  90713. **
  90714. ** This routine makes a (partial) copy of the Table structure
  90715. ** for the table being altered and sets Parse.pNewTable to point
  90716. ** to it. Routines called by the parser as the column definition
  90717. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  90718. ** the copy. The copy of the Table structure is deleted by tokenize.c
  90719. ** after parsing is finished.
  90720. **
  90721. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  90722. ** coding the "ALTER TABLE ... ADD" statement.
  90723. */
  90724. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  90725. Table *pNew;
  90726. Table *pTab;
  90727. Vdbe *v;
  90728. int iDb;
  90729. int i;
  90730. int nAlloc;
  90731. sqlite3 *db = pParse->db;
  90732. /* Look up the table being altered. */
  90733. assert( pParse->pNewTable==0 );
  90734. assert( sqlite3BtreeHoldsAllMutexes(db) );
  90735. if( db->mallocFailed ) goto exit_begin_add_column;
  90736. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  90737. if( !pTab ) goto exit_begin_add_column;
  90738. #ifndef SQLITE_OMIT_VIRTUALTABLE
  90739. if( IsVirtual(pTab) ){
  90740. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  90741. goto exit_begin_add_column;
  90742. }
  90743. #endif
  90744. /* Make sure this is not an attempt to ALTER a view. */
  90745. if( pTab->pSelect ){
  90746. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  90747. goto exit_begin_add_column;
  90748. }
  90749. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  90750. goto exit_begin_add_column;
  90751. }
  90752. assert( pTab->addColOffset>0 );
  90753. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  90754. /* Put a copy of the Table struct in Parse.pNewTable for the
  90755. ** sqlite3AddColumn() function and friends to modify. But modify
  90756. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  90757. ** prefix, we insure that the name will not collide with an existing
  90758. ** table because user table are not allowed to have the "sqlite_"
  90759. ** prefix on their name.
  90760. */
  90761. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  90762. if( !pNew ) goto exit_begin_add_column;
  90763. pParse->pNewTable = pNew;
  90764. pNew->nTabRef = 1;
  90765. pNew->nCol = pTab->nCol;
  90766. assert( pNew->nCol>0 );
  90767. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  90768. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  90769. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  90770. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  90771. if( !pNew->aCol || !pNew->zName ){
  90772. assert( db->mallocFailed );
  90773. goto exit_begin_add_column;
  90774. }
  90775. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  90776. for(i=0; i<pNew->nCol; i++){
  90777. Column *pCol = &pNew->aCol[i];
  90778. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  90779. pCol->zColl = 0;
  90780. pCol->pDflt = 0;
  90781. }
  90782. pNew->pSchema = db->aDb[iDb].pSchema;
  90783. pNew->addColOffset = pTab->addColOffset;
  90784. pNew->nTabRef = 1;
  90785. /* Begin a transaction and increment the schema cookie. */
  90786. sqlite3BeginWriteOperation(pParse, 0, iDb);
  90787. v = sqlite3GetVdbe(pParse);
  90788. if( !v ) goto exit_begin_add_column;
  90789. sqlite3ChangeCookie(pParse, iDb);
  90790. exit_begin_add_column:
  90791. sqlite3SrcListDelete(db, pSrc);
  90792. return;
  90793. }
  90794. #endif /* SQLITE_ALTER_TABLE */
  90795. /************** End of alter.c ***********************************************/
  90796. /************** Begin file analyze.c *****************************************/
  90797. /*
  90798. ** 2005-07-08
  90799. **
  90800. ** The author disclaims copyright to this source code. In place of
  90801. ** a legal notice, here is a blessing:
  90802. **
  90803. ** May you do good and not evil.
  90804. ** May you find forgiveness for yourself and forgive others.
  90805. ** May you share freely, never taking more than you give.
  90806. **
  90807. *************************************************************************
  90808. ** This file contains code associated with the ANALYZE command.
  90809. **
  90810. ** The ANALYZE command gather statistics about the content of tables
  90811. ** and indices. These statistics are made available to the query planner
  90812. ** to help it make better decisions about how to perform queries.
  90813. **
  90814. ** The following system tables are or have been supported:
  90815. **
  90816. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  90817. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  90818. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  90819. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  90820. **
  90821. ** Additional tables might be added in future releases of SQLite.
  90822. ** The sqlite_stat2 table is not created or used unless the SQLite version
  90823. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  90824. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  90825. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  90826. ** created and used by SQLite versions 3.7.9 and later and with
  90827. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  90828. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  90829. ** version of sqlite_stat3 and is only available when compiled with
  90830. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  90831. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  90832. ** are both enabled, then STAT4 takes precedence.
  90833. **
  90834. ** For most applications, sqlite_stat1 provides all the statistics required
  90835. ** for the query planner to make good choices.
  90836. **
  90837. ** Format of sqlite_stat1:
  90838. **
  90839. ** There is normally one row per index, with the index identified by the
  90840. ** name in the idx column. The tbl column is the name of the table to
  90841. ** which the index belongs. In each such row, the stat column will be
  90842. ** a string consisting of a list of integers. The first integer in this
  90843. ** list is the number of rows in the index. (This is the same as the
  90844. ** number of rows in the table, except for partial indices.) The second
  90845. ** integer is the average number of rows in the index that have the same
  90846. ** value in the first column of the index. The third integer is the average
  90847. ** number of rows in the index that have the same value for the first two
  90848. ** columns. The N-th integer (for N>1) is the average number of rows in
  90849. ** the index which have the same value for the first N-1 columns. For
  90850. ** a K-column index, there will be K+1 integers in the stat column. If
  90851. ** the index is unique, then the last integer will be 1.
  90852. **
  90853. ** The list of integers in the stat column can optionally be followed
  90854. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  90855. ** must be separated from the last integer by a single space. If the
  90856. ** "unordered" keyword is present, then the query planner assumes that
  90857. ** the index is unordered and will not use the index for a range query.
  90858. **
  90859. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  90860. ** column contains a single integer which is the (estimated) number of
  90861. ** rows in the table identified by sqlite_stat1.tbl.
  90862. **
  90863. ** Format of sqlite_stat2:
  90864. **
  90865. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  90866. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  90867. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  90868. ** about the distribution of keys within an index. The index is identified by
  90869. ** the "idx" column and the "tbl" column is the name of the table to which
  90870. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  90871. ** table for each index.
  90872. **
  90873. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  90874. ** inclusive are samples of the left-most key value in the index taken at
  90875. ** evenly spaced points along the index. Let the number of samples be S
  90876. ** (10 in the standard build) and let C be the number of rows in the index.
  90877. ** Then the sampled rows are given by:
  90878. **
  90879. ** rownumber = (i*C*2 + C)/(S*2)
  90880. **
  90881. ** For i between 0 and S-1. Conceptually, the index space is divided into
  90882. ** S uniform buckets and the samples are the middle row from each bucket.
  90883. **
  90884. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  90885. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  90886. ** writes the sqlite_stat2 table. This version of SQLite only supports
  90887. ** sqlite_stat3.
  90888. **
  90889. ** Format for sqlite_stat3:
  90890. **
  90891. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  90892. ** sqlite_stat4 format will be described first. Further information
  90893. ** about sqlite_stat3 follows the sqlite_stat4 description.
  90894. **
  90895. ** Format for sqlite_stat4:
  90896. **
  90897. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  90898. ** to aid the query planner in choosing good indices based on the values
  90899. ** that indexed columns are compared against in the WHERE clauses of
  90900. ** queries.
  90901. **
  90902. ** The sqlite_stat4 table contains multiple entries for each index.
  90903. ** The idx column names the index and the tbl column is the table of the
  90904. ** index. If the idx and tbl columns are the same, then the sample is
  90905. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  90906. ** binary encoding of a key from the index. The nEq column is a
  90907. ** list of integers. The first integer is the approximate number
  90908. ** of entries in the index whose left-most column exactly matches
  90909. ** the left-most column of the sample. The second integer in nEq
  90910. ** is the approximate number of entries in the index where the
  90911. ** first two columns match the first two columns of the sample.
  90912. ** And so forth. nLt is another list of integers that show the approximate
  90913. ** number of entries that are strictly less than the sample. The first
  90914. ** integer in nLt contains the number of entries in the index where the
  90915. ** left-most column is less than the left-most column of the sample.
  90916. ** The K-th integer in the nLt entry is the number of index entries
  90917. ** where the first K columns are less than the first K columns of the
  90918. ** sample. The nDLt column is like nLt except that it contains the
  90919. ** number of distinct entries in the index that are less than the
  90920. ** sample.
  90921. **
  90922. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  90923. ** The ANALYZE command will typically generate sqlite_stat4 tables
  90924. ** that contain between 10 and 40 samples which are distributed across
  90925. ** the key space, though not uniformly, and which include samples with
  90926. ** large nEq values.
  90927. **
  90928. ** Format for sqlite_stat3 redux:
  90929. **
  90930. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  90931. ** looks at the left-most column of the index. The sqlite_stat3.sample
  90932. ** column contains the actual value of the left-most column instead
  90933. ** of a blob encoding of the complete index key as is found in
  90934. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  90935. ** all contain just a single integer which is the same as the first
  90936. ** integer in the equivalent columns in sqlite_stat4.
  90937. */
  90938. #ifndef SQLITE_OMIT_ANALYZE
  90939. /* #include "sqliteInt.h" */
  90940. #if defined(SQLITE_ENABLE_STAT4)
  90941. # define IsStat4 1
  90942. # define IsStat3 0
  90943. #elif defined(SQLITE_ENABLE_STAT3)
  90944. # define IsStat4 0
  90945. # define IsStat3 1
  90946. #else
  90947. # define IsStat4 0
  90948. # define IsStat3 0
  90949. # undef SQLITE_STAT4_SAMPLES
  90950. # define SQLITE_STAT4_SAMPLES 1
  90951. #endif
  90952. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  90953. /*
  90954. ** This routine generates code that opens the sqlite_statN tables.
  90955. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  90956. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  90957. ** appropriate compile-time options are provided.
  90958. **
  90959. ** If the sqlite_statN tables do not previously exist, it is created.
  90960. **
  90961. ** Argument zWhere may be a pointer to a buffer containing a table name,
  90962. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  90963. ** the sqlite_statN tables associated with the named table are deleted.
  90964. ** If zWhere==0, then code is generated to delete all stat table entries.
  90965. */
  90966. static void openStatTable(
  90967. Parse *pParse, /* Parsing context */
  90968. int iDb, /* The database we are looking in */
  90969. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  90970. const char *zWhere, /* Delete entries for this table or index */
  90971. const char *zWhereType /* Either "tbl" or "idx" */
  90972. ){
  90973. static const struct {
  90974. const char *zName;
  90975. const char *zCols;
  90976. } aTable[] = {
  90977. { "sqlite_stat1", "tbl,idx,stat" },
  90978. #if defined(SQLITE_ENABLE_STAT4)
  90979. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  90980. { "sqlite_stat3", 0 },
  90981. #elif defined(SQLITE_ENABLE_STAT3)
  90982. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  90983. { "sqlite_stat4", 0 },
  90984. #else
  90985. { "sqlite_stat3", 0 },
  90986. { "sqlite_stat4", 0 },
  90987. #endif
  90988. };
  90989. int i;
  90990. sqlite3 *db = pParse->db;
  90991. Db *pDb;
  90992. Vdbe *v = sqlite3GetVdbe(pParse);
  90993. int aRoot[ArraySize(aTable)];
  90994. u8 aCreateTbl[ArraySize(aTable)];
  90995. if( v==0 ) return;
  90996. assert( sqlite3BtreeHoldsAllMutexes(db) );
  90997. assert( sqlite3VdbeDb(v)==db );
  90998. pDb = &db->aDb[iDb];
  90999. /* Create new statistic tables if they do not exist, or clear them
  91000. ** if they do already exist.
  91001. */
  91002. for(i=0; i<ArraySize(aTable); i++){
  91003. const char *zTab = aTable[i].zName;
  91004. Table *pStat;
  91005. if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
  91006. if( aTable[i].zCols ){
  91007. /* The sqlite_statN table does not exist. Create it. Note that a
  91008. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  91009. ** of the new table in register pParse->regRoot. This is important
  91010. ** because the OpenWrite opcode below will be needing it. */
  91011. sqlite3NestedParse(pParse,
  91012. "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
  91013. );
  91014. aRoot[i] = pParse->regRoot;
  91015. aCreateTbl[i] = OPFLAG_P2ISREG;
  91016. }
  91017. }else{
  91018. /* The table already exists. If zWhere is not NULL, delete all entries
  91019. ** associated with the table zWhere. If zWhere is NULL, delete the
  91020. ** entire contents of the table. */
  91021. aRoot[i] = pStat->tnum;
  91022. aCreateTbl[i] = 0;
  91023. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  91024. if( zWhere ){
  91025. sqlite3NestedParse(pParse,
  91026. "DELETE FROM %Q.%s WHERE %s=%Q",
  91027. pDb->zDbSName, zTab, zWhereType, zWhere
  91028. );
  91029. }else{
  91030. /* The sqlite_stat[134] table already exists. Delete all rows. */
  91031. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  91032. }
  91033. }
  91034. }
  91035. /* Open the sqlite_stat[134] tables for writing. */
  91036. for(i=0; aTable[i].zCols; i++){
  91037. assert( i<ArraySize(aTable) );
  91038. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
  91039. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  91040. VdbeComment((v, aTable[i].zName));
  91041. }
  91042. }
  91043. /*
  91044. ** Recommended number of samples for sqlite_stat4
  91045. */
  91046. #ifndef SQLITE_STAT4_SAMPLES
  91047. # define SQLITE_STAT4_SAMPLES 24
  91048. #endif
  91049. /*
  91050. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  91051. ** share an instance of the following structure to hold their state
  91052. ** information.
  91053. */
  91054. typedef struct Stat4Accum Stat4Accum;
  91055. typedef struct Stat4Sample Stat4Sample;
  91056. struct Stat4Sample {
  91057. tRowcnt *anEq; /* sqlite_stat4.nEq */
  91058. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  91059. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91060. tRowcnt *anLt; /* sqlite_stat4.nLt */
  91061. union {
  91062. i64 iRowid; /* Rowid in main table of the key */
  91063. u8 *aRowid; /* Key for WITHOUT ROWID tables */
  91064. } u;
  91065. u32 nRowid; /* Sizeof aRowid[] */
  91066. u8 isPSample; /* True if a periodic sample */
  91067. int iCol; /* If !isPSample, the reason for inclusion */
  91068. u32 iHash; /* Tiebreaker hash */
  91069. #endif
  91070. };
  91071. struct Stat4Accum {
  91072. tRowcnt nRow; /* Number of rows in the entire table */
  91073. tRowcnt nPSample; /* How often to do a periodic sample */
  91074. int nCol; /* Number of columns in index + pk/rowid */
  91075. int nKeyCol; /* Number of index columns w/o the pk/rowid */
  91076. int mxSample; /* Maximum number of samples to accumulate */
  91077. Stat4Sample current; /* Current row as a Stat4Sample */
  91078. u32 iPrn; /* Pseudo-random number used for sampling */
  91079. Stat4Sample *aBest; /* Array of nCol best samples */
  91080. int iMin; /* Index in a[] of entry with minimum score */
  91081. int nSample; /* Current number of samples */
  91082. int nMaxEqZero; /* Max leading 0 in anEq[] for any a[] entry */
  91083. int iGet; /* Index of current sample accessed by stat_get() */
  91084. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  91085. sqlite3 *db; /* Database connection, for malloc() */
  91086. };
  91087. /* Reclaim memory used by a Stat4Sample
  91088. */
  91089. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91090. static void sampleClear(sqlite3 *db, Stat4Sample *p){
  91091. assert( db!=0 );
  91092. if( p->nRowid ){
  91093. sqlite3DbFree(db, p->u.aRowid);
  91094. p->nRowid = 0;
  91095. }
  91096. }
  91097. #endif
  91098. /* Initialize the BLOB value of a ROWID
  91099. */
  91100. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91101. static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
  91102. assert( db!=0 );
  91103. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  91104. p->u.aRowid = sqlite3DbMallocRawNN(db, n);
  91105. if( p->u.aRowid ){
  91106. p->nRowid = n;
  91107. memcpy(p->u.aRowid, pData, n);
  91108. }else{
  91109. p->nRowid = 0;
  91110. }
  91111. }
  91112. #endif
  91113. /* Initialize the INTEGER value of a ROWID.
  91114. */
  91115. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91116. static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
  91117. assert( db!=0 );
  91118. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  91119. p->nRowid = 0;
  91120. p->u.iRowid = iRowid;
  91121. }
  91122. #endif
  91123. /*
  91124. ** Copy the contents of object (*pFrom) into (*pTo).
  91125. */
  91126. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91127. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  91128. pTo->isPSample = pFrom->isPSample;
  91129. pTo->iCol = pFrom->iCol;
  91130. pTo->iHash = pFrom->iHash;
  91131. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  91132. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  91133. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  91134. if( pFrom->nRowid ){
  91135. sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
  91136. }else{
  91137. sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
  91138. }
  91139. }
  91140. #endif
  91141. /*
  91142. ** Reclaim all memory of a Stat4Accum structure.
  91143. */
  91144. static void stat4Destructor(void *pOld){
  91145. Stat4Accum *p = (Stat4Accum*)pOld;
  91146. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91147. int i;
  91148. for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
  91149. for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
  91150. sampleClear(p->db, &p->current);
  91151. #endif
  91152. sqlite3DbFree(p->db, p);
  91153. }
  91154. /*
  91155. ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
  91156. ** are:
  91157. ** N: The number of columns in the index including the rowid/pk (note 1)
  91158. ** K: The number of columns in the index excluding the rowid/pk.
  91159. ** C: The number of rows in the index (note 2)
  91160. **
  91161. ** Note 1: In the special case of the covering index that implements a
  91162. ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
  91163. ** total number of columns in the table.
  91164. **
  91165. ** Note 2: C is only used for STAT3 and STAT4.
  91166. **
  91167. ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
  91168. ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
  91169. ** PRIMARY KEY of the table. The covering index that implements the
  91170. ** original WITHOUT ROWID table as N==K as a special case.
  91171. **
  91172. ** This routine allocates the Stat4Accum object in heap memory. The return
  91173. ** value is a pointer to the Stat4Accum object. The datatype of the
  91174. ** return value is BLOB, but it is really just a pointer to the Stat4Accum
  91175. ** object.
  91176. */
  91177. static void statInit(
  91178. sqlite3_context *context,
  91179. int argc,
  91180. sqlite3_value **argv
  91181. ){
  91182. Stat4Accum *p;
  91183. int nCol; /* Number of columns in index being sampled */
  91184. int nKeyCol; /* Number of key columns */
  91185. int nColUp; /* nCol rounded up for alignment */
  91186. int n; /* Bytes of space to allocate */
  91187. sqlite3 *db; /* Database connection */
  91188. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91189. int mxSample = SQLITE_STAT4_SAMPLES;
  91190. #endif
  91191. /* Decode the three function arguments */
  91192. UNUSED_PARAMETER(argc);
  91193. nCol = sqlite3_value_int(argv[0]);
  91194. assert( nCol>0 );
  91195. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  91196. nKeyCol = sqlite3_value_int(argv[1]);
  91197. assert( nKeyCol<=nCol );
  91198. assert( nKeyCol>0 );
  91199. /* Allocate the space required for the Stat4Accum object */
  91200. n = sizeof(*p)
  91201. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  91202. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  91203. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91204. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  91205. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  91206. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  91207. #endif
  91208. ;
  91209. db = sqlite3_context_db_handle(context);
  91210. p = sqlite3DbMallocZero(db, n);
  91211. if( p==0 ){
  91212. sqlite3_result_error_nomem(context);
  91213. return;
  91214. }
  91215. p->db = db;
  91216. p->nRow = 0;
  91217. p->nCol = nCol;
  91218. p->nKeyCol = nKeyCol;
  91219. p->current.anDLt = (tRowcnt*)&p[1];
  91220. p->current.anEq = &p->current.anDLt[nColUp];
  91221. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91222. {
  91223. u8 *pSpace; /* Allocated space not yet assigned */
  91224. int i; /* Used to iterate through p->aSample[] */
  91225. p->iGet = -1;
  91226. p->mxSample = mxSample;
  91227. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
  91228. p->current.anLt = &p->current.anEq[nColUp];
  91229. p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
  91230. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  91231. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  91232. p->aBest = &p->a[mxSample];
  91233. pSpace = (u8*)(&p->a[mxSample+nCol]);
  91234. for(i=0; i<(mxSample+nCol); i++){
  91235. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  91236. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  91237. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  91238. }
  91239. assert( (pSpace - (u8*)p)==n );
  91240. for(i=0; i<nCol; i++){
  91241. p->aBest[i].iCol = i;
  91242. }
  91243. }
  91244. #endif
  91245. /* Return a pointer to the allocated object to the caller. Note that
  91246. ** only the pointer (the 2nd parameter) matters. The size of the object
  91247. ** (given by the 3rd parameter) is never used and can be any positive
  91248. ** value. */
  91249. sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
  91250. }
  91251. static const FuncDef statInitFuncdef = {
  91252. 2+IsStat34, /* nArg */
  91253. SQLITE_UTF8, /* funcFlags */
  91254. 0, /* pUserData */
  91255. 0, /* pNext */
  91256. statInit, /* xSFunc */
  91257. 0, /* xFinalize */
  91258. "stat_init", /* zName */
  91259. {0}
  91260. };
  91261. #ifdef SQLITE_ENABLE_STAT4
  91262. /*
  91263. ** pNew and pOld are both candidate non-periodic samples selected for
  91264. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  91265. ** considering only any trailing columns and the sample hash value, this
  91266. ** function returns true if sample pNew is to be preferred over pOld.
  91267. ** In other words, if we assume that the cardinalities of the selected
  91268. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  91269. **
  91270. ** This function assumes that for each argument sample, the contents of
  91271. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  91272. */
  91273. static int sampleIsBetterPost(
  91274. Stat4Accum *pAccum,
  91275. Stat4Sample *pNew,
  91276. Stat4Sample *pOld
  91277. ){
  91278. int nCol = pAccum->nCol;
  91279. int i;
  91280. assert( pNew->iCol==pOld->iCol );
  91281. for(i=pNew->iCol+1; i<nCol; i++){
  91282. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  91283. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  91284. }
  91285. if( pNew->iHash>pOld->iHash ) return 1;
  91286. return 0;
  91287. }
  91288. #endif
  91289. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91290. /*
  91291. ** Return true if pNew is to be preferred over pOld.
  91292. **
  91293. ** This function assumes that for each argument sample, the contents of
  91294. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  91295. */
  91296. static int sampleIsBetter(
  91297. Stat4Accum *pAccum,
  91298. Stat4Sample *pNew,
  91299. Stat4Sample *pOld
  91300. ){
  91301. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  91302. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  91303. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  91304. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  91305. if( (nEqNew>nEqOld) ) return 1;
  91306. #ifdef SQLITE_ENABLE_STAT4
  91307. if( nEqNew==nEqOld ){
  91308. if( pNew->iCol<pOld->iCol ) return 1;
  91309. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  91310. }
  91311. return 0;
  91312. #else
  91313. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  91314. #endif
  91315. }
  91316. /*
  91317. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  91318. ** remove the least desirable sample from p->a[] to make room.
  91319. */
  91320. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  91321. Stat4Sample *pSample = 0;
  91322. int i;
  91323. assert( IsStat4 || nEqZero==0 );
  91324. #ifdef SQLITE_ENABLE_STAT4
  91325. /* Stat4Accum.nMaxEqZero is set to the maximum number of leading 0
  91326. ** values in the anEq[] array of any sample in Stat4Accum.a[]. In
  91327. ** other words, if nMaxEqZero is n, then it is guaranteed that there
  91328. ** are no samples with Stat4Sample.anEq[m]==0 for (m>=n). */
  91329. if( nEqZero>p->nMaxEqZero ){
  91330. p->nMaxEqZero = nEqZero;
  91331. }
  91332. if( pNew->isPSample==0 ){
  91333. Stat4Sample *pUpgrade = 0;
  91334. assert( pNew->anEq[pNew->iCol]>0 );
  91335. /* This sample is being added because the prefix that ends in column
  91336. ** iCol occurs many times in the table. However, if we have already
  91337. ** added a sample that shares this prefix, there is no need to add
  91338. ** this one. Instead, upgrade the priority of the highest priority
  91339. ** existing sample that shares this prefix. */
  91340. for(i=p->nSample-1; i>=0; i--){
  91341. Stat4Sample *pOld = &p->a[i];
  91342. if( pOld->anEq[pNew->iCol]==0 ){
  91343. if( pOld->isPSample ) return;
  91344. assert( pOld->iCol>pNew->iCol );
  91345. assert( sampleIsBetter(p, pNew, pOld) );
  91346. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  91347. pUpgrade = pOld;
  91348. }
  91349. }
  91350. }
  91351. if( pUpgrade ){
  91352. pUpgrade->iCol = pNew->iCol;
  91353. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  91354. goto find_new_min;
  91355. }
  91356. }
  91357. #endif
  91358. /* If necessary, remove sample iMin to make room for the new sample. */
  91359. if( p->nSample>=p->mxSample ){
  91360. Stat4Sample *pMin = &p->a[p->iMin];
  91361. tRowcnt *anEq = pMin->anEq;
  91362. tRowcnt *anLt = pMin->anLt;
  91363. tRowcnt *anDLt = pMin->anDLt;
  91364. sampleClear(p->db, pMin);
  91365. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  91366. pSample = &p->a[p->nSample-1];
  91367. pSample->nRowid = 0;
  91368. pSample->anEq = anEq;
  91369. pSample->anDLt = anDLt;
  91370. pSample->anLt = anLt;
  91371. p->nSample = p->mxSample-1;
  91372. }
  91373. /* The "rows less-than" for the rowid column must be greater than that
  91374. ** for the last sample in the p->a[] array. Otherwise, the samples would
  91375. ** be out of order. */
  91376. #ifdef SQLITE_ENABLE_STAT4
  91377. assert( p->nSample==0
  91378. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  91379. #endif
  91380. /* Insert the new sample */
  91381. pSample = &p->a[p->nSample];
  91382. sampleCopy(p, pSample, pNew);
  91383. p->nSample++;
  91384. /* Zero the first nEqZero entries in the anEq[] array. */
  91385. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  91386. #ifdef SQLITE_ENABLE_STAT4
  91387. find_new_min:
  91388. #endif
  91389. if( p->nSample>=p->mxSample ){
  91390. int iMin = -1;
  91391. for(i=0; i<p->mxSample; i++){
  91392. if( p->a[i].isPSample ) continue;
  91393. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  91394. iMin = i;
  91395. }
  91396. }
  91397. assert( iMin>=0 );
  91398. p->iMin = iMin;
  91399. }
  91400. }
  91401. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  91402. /*
  91403. ** Field iChng of the index being scanned has changed. So at this point
  91404. ** p->current contains a sample that reflects the previous row of the
  91405. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  91406. ** correct at this point.
  91407. */
  91408. static void samplePushPrevious(Stat4Accum *p, int iChng){
  91409. #ifdef SQLITE_ENABLE_STAT4
  91410. int i;
  91411. /* Check if any samples from the aBest[] array should be pushed
  91412. ** into IndexSample.a[] at this point. */
  91413. for(i=(p->nCol-2); i>=iChng; i--){
  91414. Stat4Sample *pBest = &p->aBest[i];
  91415. pBest->anEq[i] = p->current.anEq[i];
  91416. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  91417. sampleInsert(p, pBest, i);
  91418. }
  91419. }
  91420. /* Check that no sample contains an anEq[] entry with an index of
  91421. ** p->nMaxEqZero or greater set to zero. */
  91422. for(i=p->nSample-1; i>=0; i--){
  91423. int j;
  91424. for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
  91425. }
  91426. /* Update the anEq[] fields of any samples already collected. */
  91427. if( iChng<p->nMaxEqZero ){
  91428. for(i=p->nSample-1; i>=0; i--){
  91429. int j;
  91430. for(j=iChng; j<p->nCol; j++){
  91431. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  91432. }
  91433. }
  91434. p->nMaxEqZero = iChng;
  91435. }
  91436. #endif
  91437. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  91438. if( iChng==0 ){
  91439. tRowcnt nLt = p->current.anLt[0];
  91440. tRowcnt nEq = p->current.anEq[0];
  91441. /* Check if this is to be a periodic sample. If so, add it. */
  91442. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  91443. p->current.isPSample = 1;
  91444. sampleInsert(p, &p->current, 0);
  91445. p->current.isPSample = 0;
  91446. }else
  91447. /* Or if it is a non-periodic sample. Add it in this case too. */
  91448. if( p->nSample<p->mxSample
  91449. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  91450. ){
  91451. sampleInsert(p, &p->current, 0);
  91452. }
  91453. }
  91454. #endif
  91455. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  91456. UNUSED_PARAMETER( p );
  91457. UNUSED_PARAMETER( iChng );
  91458. #endif
  91459. }
  91460. /*
  91461. ** Implementation of the stat_push SQL function: stat_push(P,C,R)
  91462. ** Arguments:
  91463. **
  91464. ** P Pointer to the Stat4Accum object created by stat_init()
  91465. ** C Index of left-most column to differ from previous row
  91466. ** R Rowid for the current row. Might be a key record for
  91467. ** WITHOUT ROWID tables.
  91468. **
  91469. ** This SQL function always returns NULL. It's purpose it to accumulate
  91470. ** statistical data and/or samples in the Stat4Accum object about the
  91471. ** index being analyzed. The stat_get() SQL function will later be used to
  91472. ** extract relevant information for constructing the sqlite_statN tables.
  91473. **
  91474. ** The R parameter is only used for STAT3 and STAT4
  91475. */
  91476. static void statPush(
  91477. sqlite3_context *context,
  91478. int argc,
  91479. sqlite3_value **argv
  91480. ){
  91481. int i;
  91482. /* The three function arguments */
  91483. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  91484. int iChng = sqlite3_value_int(argv[1]);
  91485. UNUSED_PARAMETER( argc );
  91486. UNUSED_PARAMETER( context );
  91487. assert( p->nCol>0 );
  91488. assert( iChng<p->nCol );
  91489. if( p->nRow==0 ){
  91490. /* This is the first call to this function. Do initialization. */
  91491. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  91492. }else{
  91493. /* Second and subsequent calls get processed here */
  91494. samplePushPrevious(p, iChng);
  91495. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  91496. ** to the current row of the index. */
  91497. for(i=0; i<iChng; i++){
  91498. p->current.anEq[i]++;
  91499. }
  91500. for(i=iChng; i<p->nCol; i++){
  91501. p->current.anDLt[i]++;
  91502. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91503. p->current.anLt[i] += p->current.anEq[i];
  91504. #endif
  91505. p->current.anEq[i] = 1;
  91506. }
  91507. }
  91508. p->nRow++;
  91509. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91510. if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
  91511. sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
  91512. }else{
  91513. sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
  91514. sqlite3_value_blob(argv[2]));
  91515. }
  91516. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  91517. #endif
  91518. #ifdef SQLITE_ENABLE_STAT4
  91519. {
  91520. tRowcnt nLt = p->current.anLt[p->nCol-1];
  91521. /* Check if this is to be a periodic sample. If so, add it. */
  91522. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  91523. p->current.isPSample = 1;
  91524. p->current.iCol = 0;
  91525. sampleInsert(p, &p->current, p->nCol-1);
  91526. p->current.isPSample = 0;
  91527. }
  91528. /* Update the aBest[] array. */
  91529. for(i=0; i<(p->nCol-1); i++){
  91530. p->current.iCol = i;
  91531. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  91532. sampleCopy(p, &p->aBest[i], &p->current);
  91533. }
  91534. }
  91535. }
  91536. #endif
  91537. }
  91538. static const FuncDef statPushFuncdef = {
  91539. 2+IsStat34, /* nArg */
  91540. SQLITE_UTF8, /* funcFlags */
  91541. 0, /* pUserData */
  91542. 0, /* pNext */
  91543. statPush, /* xSFunc */
  91544. 0, /* xFinalize */
  91545. "stat_push", /* zName */
  91546. {0}
  91547. };
  91548. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  91549. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  91550. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  91551. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  91552. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  91553. /*
  91554. ** Implementation of the stat_get(P,J) SQL function. This routine is
  91555. ** used to query statistical information that has been gathered into
  91556. ** the Stat4Accum object by prior calls to stat_push(). The P parameter
  91557. ** has type BLOB but it is really just a pointer to the Stat4Accum object.
  91558. ** The content to returned is determined by the parameter J
  91559. ** which is one of the STAT_GET_xxxx values defined above.
  91560. **
  91561. ** The stat_get(P,J) function is not available to generic SQL. It is
  91562. ** inserted as part of a manually constructed bytecode program. (See
  91563. ** the callStatGet() routine below.) It is guaranteed that the P
  91564. ** parameter will always be a poiner to a Stat4Accum object, never a
  91565. ** NULL.
  91566. **
  91567. ** If neither STAT3 nor STAT4 are enabled, then J is always
  91568. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  91569. ** a one-parameter function, stat_get(P), that always returns the
  91570. ** stat1 table entry information.
  91571. */
  91572. static void statGet(
  91573. sqlite3_context *context,
  91574. int argc,
  91575. sqlite3_value **argv
  91576. ){
  91577. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  91578. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91579. /* STAT3 and STAT4 have a parameter on this routine. */
  91580. int eCall = sqlite3_value_int(argv[1]);
  91581. assert( argc==2 );
  91582. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  91583. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  91584. || eCall==STAT_GET_NDLT
  91585. );
  91586. if( eCall==STAT_GET_STAT1 )
  91587. #else
  91588. assert( argc==1 );
  91589. #endif
  91590. {
  91591. /* Return the value to store in the "stat" column of the sqlite_stat1
  91592. ** table for this index.
  91593. **
  91594. ** The value is a string composed of a list of integers describing
  91595. ** the index. The first integer in the list is the total number of
  91596. ** entries in the index. There is one additional integer in the list
  91597. ** for each indexed column. This additional integer is an estimate of
  91598. ** the number of rows matched by a stabbing query on the index using
  91599. ** a key with the corresponding number of fields. In other words,
  91600. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  91601. ** "100 10 2", then SQLite estimates that:
  91602. **
  91603. ** * the index contains 100 rows,
  91604. ** * "WHERE a=?" matches 10 rows, and
  91605. ** * "WHERE a=? AND b=?" matches 2 rows.
  91606. **
  91607. ** If D is the count of distinct values and K is the total number of
  91608. ** rows, then each estimate is computed as:
  91609. **
  91610. ** I = (K+D-1)/D
  91611. */
  91612. char *z;
  91613. int i;
  91614. char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
  91615. if( zRet==0 ){
  91616. sqlite3_result_error_nomem(context);
  91617. return;
  91618. }
  91619. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  91620. z = zRet + sqlite3Strlen30(zRet);
  91621. for(i=0; i<p->nKeyCol; i++){
  91622. u64 nDistinct = p->current.anDLt[i] + 1;
  91623. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  91624. sqlite3_snprintf(24, z, " %llu", iVal);
  91625. z += sqlite3Strlen30(z);
  91626. assert( p->current.anEq[i] );
  91627. }
  91628. assert( z[0]=='\0' && z>zRet );
  91629. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  91630. }
  91631. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91632. else if( eCall==STAT_GET_ROWID ){
  91633. if( p->iGet<0 ){
  91634. samplePushPrevious(p, 0);
  91635. p->iGet = 0;
  91636. }
  91637. if( p->iGet<p->nSample ){
  91638. Stat4Sample *pS = p->a + p->iGet;
  91639. if( pS->nRowid==0 ){
  91640. sqlite3_result_int64(context, pS->u.iRowid);
  91641. }else{
  91642. sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
  91643. SQLITE_TRANSIENT);
  91644. }
  91645. }
  91646. }else{
  91647. tRowcnt *aCnt = 0;
  91648. assert( p->iGet<p->nSample );
  91649. switch( eCall ){
  91650. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  91651. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  91652. default: {
  91653. aCnt = p->a[p->iGet].anDLt;
  91654. p->iGet++;
  91655. break;
  91656. }
  91657. }
  91658. if( IsStat3 ){
  91659. sqlite3_result_int64(context, (i64)aCnt[0]);
  91660. }else{
  91661. char *zRet = sqlite3MallocZero(p->nCol * 25);
  91662. if( zRet==0 ){
  91663. sqlite3_result_error_nomem(context);
  91664. }else{
  91665. int i;
  91666. char *z = zRet;
  91667. for(i=0; i<p->nCol; i++){
  91668. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  91669. z += sqlite3Strlen30(z);
  91670. }
  91671. assert( z[0]=='\0' && z>zRet );
  91672. z[-1] = '\0';
  91673. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  91674. }
  91675. }
  91676. }
  91677. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  91678. #ifndef SQLITE_DEBUG
  91679. UNUSED_PARAMETER( argc );
  91680. #endif
  91681. }
  91682. static const FuncDef statGetFuncdef = {
  91683. 1+IsStat34, /* nArg */
  91684. SQLITE_UTF8, /* funcFlags */
  91685. 0, /* pUserData */
  91686. 0, /* pNext */
  91687. statGet, /* xSFunc */
  91688. 0, /* xFinalize */
  91689. "stat_get", /* zName */
  91690. {0}
  91691. };
  91692. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  91693. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  91694. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91695. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  91696. #elif SQLITE_DEBUG
  91697. assert( iParam==STAT_GET_STAT1 );
  91698. #else
  91699. UNUSED_PARAMETER( iParam );
  91700. #endif
  91701. sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
  91702. (char*)&statGetFuncdef, P4_FUNCDEF);
  91703. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  91704. }
  91705. /*
  91706. ** Generate code to do an analysis of all indices associated with
  91707. ** a single table.
  91708. */
  91709. static void analyzeOneTable(
  91710. Parse *pParse, /* Parser context */
  91711. Table *pTab, /* Table whose indices are to be analyzed */
  91712. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  91713. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  91714. int iMem, /* Available memory locations begin here */
  91715. int iTab /* Next available cursor */
  91716. ){
  91717. sqlite3 *db = pParse->db; /* Database handle */
  91718. Index *pIdx; /* An index to being analyzed */
  91719. int iIdxCur; /* Cursor open on index being analyzed */
  91720. int iTabCur; /* Table cursor */
  91721. Vdbe *v; /* The virtual machine being built up */
  91722. int i; /* Loop counter */
  91723. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  91724. int iDb; /* Index of database containing pTab */
  91725. u8 needTableCnt = 1; /* True to count the table */
  91726. int regNewRowid = iMem++; /* Rowid for the inserted record */
  91727. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  91728. int regChng = iMem++; /* Index of changed index field */
  91729. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91730. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  91731. #endif
  91732. int regTemp = iMem++; /* Temporary use register */
  91733. int regTabname = iMem++; /* Register containing table name */
  91734. int regIdxname = iMem++; /* Register containing index name */
  91735. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  91736. int regPrev = iMem; /* MUST BE LAST (see below) */
  91737. pParse->nMem = MAX(pParse->nMem, iMem);
  91738. v = sqlite3GetVdbe(pParse);
  91739. if( v==0 || NEVER(pTab==0) ){
  91740. return;
  91741. }
  91742. if( pTab->tnum==0 ){
  91743. /* Do not gather statistics on views or virtual tables */
  91744. return;
  91745. }
  91746. if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){
  91747. /* Do not gather statistics on system tables */
  91748. return;
  91749. }
  91750. assert( sqlite3BtreeHoldsAllMutexes(db) );
  91751. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  91752. assert( iDb>=0 );
  91753. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  91754. #ifndef SQLITE_OMIT_AUTHORIZATION
  91755. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  91756. db->aDb[iDb].zDbSName ) ){
  91757. return;
  91758. }
  91759. #endif
  91760. /* Establish a read-lock on the table at the shared-cache level.
  91761. ** Open a read-only cursor on the table. Also allocate a cursor number
  91762. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  91763. ** this time though. */
  91764. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  91765. iTabCur = iTab++;
  91766. iIdxCur = iTab++;
  91767. pParse->nTab = MAX(pParse->nTab, iTab);
  91768. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  91769. sqlite3VdbeLoadString(v, regTabname, pTab->zName);
  91770. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  91771. int nCol; /* Number of columns in pIdx. "N" */
  91772. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  91773. int addrNextRow; /* Address of "next_row:" */
  91774. const char *zIdxName; /* Name of the index */
  91775. int nColTest; /* Number of columns to test for changes */
  91776. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  91777. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  91778. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
  91779. nCol = pIdx->nKeyCol;
  91780. zIdxName = pTab->zName;
  91781. nColTest = nCol - 1;
  91782. }else{
  91783. nCol = pIdx->nColumn;
  91784. zIdxName = pIdx->zName;
  91785. nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
  91786. }
  91787. /* Populate the register containing the index name. */
  91788. sqlite3VdbeLoadString(v, regIdxname, zIdxName);
  91789. VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
  91790. /*
  91791. ** Pseudo-code for loop that calls stat_push():
  91792. **
  91793. ** Rewind csr
  91794. ** if eof(csr) goto end_of_scan;
  91795. ** regChng = 0
  91796. ** goto chng_addr_0;
  91797. **
  91798. ** next_row:
  91799. ** regChng = 0
  91800. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  91801. ** regChng = 1
  91802. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  91803. ** ...
  91804. ** regChng = N
  91805. ** goto chng_addr_N
  91806. **
  91807. ** chng_addr_0:
  91808. ** regPrev(0) = idx(0)
  91809. ** chng_addr_1:
  91810. ** regPrev(1) = idx(1)
  91811. ** ...
  91812. **
  91813. ** endDistinctTest:
  91814. ** regRowid = idx(rowid)
  91815. ** stat_push(P, regChng, regRowid)
  91816. ** Next csr
  91817. ** if !eof(csr) goto next_row;
  91818. **
  91819. ** end_of_scan:
  91820. */
  91821. /* Make sure there are enough memory cells allocated to accommodate
  91822. ** the regPrev array and a trailing rowid (the rowid slot is required
  91823. ** when building a record to insert into the sample column of
  91824. ** the sqlite_stat4 table. */
  91825. pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
  91826. /* Open a read-only cursor on the index being analyzed. */
  91827. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  91828. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  91829. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  91830. VdbeComment((v, "%s", pIdx->zName));
  91831. /* Invoke the stat_init() function. The arguments are:
  91832. **
  91833. ** (1) the number of columns in the index including the rowid
  91834. ** (or for a WITHOUT ROWID table, the number of PK columns),
  91835. ** (2) the number of columns in the key without the rowid/pk
  91836. ** (3) the number of rows in the index,
  91837. **
  91838. **
  91839. ** The third argument is only used for STAT3 and STAT4
  91840. */
  91841. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91842. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
  91843. #endif
  91844. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
  91845. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
  91846. sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
  91847. (char*)&statInitFuncdef, P4_FUNCDEF);
  91848. sqlite3VdbeChangeP5(v, 2+IsStat34);
  91849. /* Implementation of the following:
  91850. **
  91851. ** Rewind csr
  91852. ** if eof(csr) goto end_of_scan;
  91853. ** regChng = 0
  91854. ** goto next_push_0;
  91855. **
  91856. */
  91857. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  91858. VdbeCoverage(v);
  91859. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  91860. addrNextRow = sqlite3VdbeCurrentAddr(v);
  91861. if( nColTest>0 ){
  91862. int endDistinctTest = sqlite3VdbeMakeLabel(v);
  91863. int *aGotoChng; /* Array of jump instruction addresses */
  91864. aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
  91865. if( aGotoChng==0 ) continue;
  91866. /*
  91867. ** next_row:
  91868. ** regChng = 0
  91869. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  91870. ** regChng = 1
  91871. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  91872. ** ...
  91873. ** regChng = N
  91874. ** goto endDistinctTest
  91875. */
  91876. sqlite3VdbeAddOp0(v, OP_Goto);
  91877. addrNextRow = sqlite3VdbeCurrentAddr(v);
  91878. if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
  91879. /* For a single-column UNIQUE index, once we have found a non-NULL
  91880. ** row, we know that all the rest will be distinct, so skip
  91881. ** subsequent distinctness tests. */
  91882. sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
  91883. VdbeCoverage(v);
  91884. }
  91885. for(i=0; i<nColTest; i++){
  91886. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  91887. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  91888. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  91889. aGotoChng[i] =
  91890. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  91891. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  91892. VdbeCoverage(v);
  91893. }
  91894. sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
  91895. sqlite3VdbeGoto(v, endDistinctTest);
  91896. /*
  91897. ** chng_addr_0:
  91898. ** regPrev(0) = idx(0)
  91899. ** chng_addr_1:
  91900. ** regPrev(1) = idx(1)
  91901. ** ...
  91902. */
  91903. sqlite3VdbeJumpHere(v, addrNextRow-1);
  91904. for(i=0; i<nColTest; i++){
  91905. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  91906. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  91907. }
  91908. sqlite3VdbeResolveLabel(v, endDistinctTest);
  91909. sqlite3DbFree(db, aGotoChng);
  91910. }
  91911. /*
  91912. ** chng_addr_N:
  91913. ** regRowid = idx(rowid) // STAT34 only
  91914. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  91915. ** Next csr
  91916. ** if !eof(csr) goto next_row;
  91917. */
  91918. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91919. assert( regRowid==(regStat4+2) );
  91920. if( HasRowid(pTab) ){
  91921. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  91922. }else{
  91923. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  91924. int j, k, regKey;
  91925. regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  91926. for(j=0; j<pPk->nKeyCol; j++){
  91927. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  91928. assert( k>=0 && k<pIdx->nColumn );
  91929. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
  91930. VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
  91931. }
  91932. sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
  91933. sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
  91934. }
  91935. #endif
  91936. assert( regChng==(regStat4+1) );
  91937. sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
  91938. (char*)&statPushFuncdef, P4_FUNCDEF);
  91939. sqlite3VdbeChangeP5(v, 2+IsStat34);
  91940. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
  91941. /* Add the entry to the stat1 table. */
  91942. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  91943. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  91944. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  91945. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  91946. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  91947. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  91948. /* Add the entries to the stat3 or stat4 table. */
  91949. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  91950. {
  91951. int regEq = regStat1;
  91952. int regLt = regStat1+1;
  91953. int regDLt = regStat1+2;
  91954. int regSample = regStat1+3;
  91955. int regCol = regStat1+4;
  91956. int regSampleRowid = regCol + nCol;
  91957. int addrNext;
  91958. int addrIsNull;
  91959. u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  91960. pParse->nMem = MAX(pParse->nMem, regCol+nCol);
  91961. addrNext = sqlite3VdbeCurrentAddr(v);
  91962. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  91963. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  91964. VdbeCoverage(v);
  91965. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  91966. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  91967. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  91968. sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
  91969. /* We know that the regSampleRowid row exists because it was read by
  91970. ** the previous loop. Thus the not-found jump of seekOp will never
  91971. ** be taken */
  91972. VdbeCoverageNeverTaken(v);
  91973. #ifdef SQLITE_ENABLE_STAT3
  91974. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
  91975. #else
  91976. for(i=0; i<nCol; i++){
  91977. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
  91978. }
  91979. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
  91980. #endif
  91981. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
  91982. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  91983. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  91984. sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
  91985. sqlite3VdbeJumpHere(v, addrIsNull);
  91986. }
  91987. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  91988. /* End of analysis */
  91989. sqlite3VdbeJumpHere(v, addrRewind);
  91990. }
  91991. /* Create a single sqlite_stat1 entry containing NULL as the index
  91992. ** name and the row count as the content.
  91993. */
  91994. if( pOnlyIdx==0 && needTableCnt ){
  91995. VdbeComment((v, "%s", pTab->zName));
  91996. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  91997. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
  91998. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  91999. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  92000. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  92001. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  92002. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  92003. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  92004. sqlite3VdbeJumpHere(v, jZeroRows);
  92005. }
  92006. }
  92007. /*
  92008. ** Generate code that will cause the most recent index analysis to
  92009. ** be loaded into internal hash tables where is can be used.
  92010. */
  92011. static void loadAnalysis(Parse *pParse, int iDb){
  92012. Vdbe *v = sqlite3GetVdbe(pParse);
  92013. if( v ){
  92014. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  92015. }
  92016. }
  92017. /*
  92018. ** Generate code that will do an analysis of an entire database
  92019. */
  92020. static void analyzeDatabase(Parse *pParse, int iDb){
  92021. sqlite3 *db = pParse->db;
  92022. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  92023. HashElem *k;
  92024. int iStatCur;
  92025. int iMem;
  92026. int iTab;
  92027. sqlite3BeginWriteOperation(pParse, 0, iDb);
  92028. iStatCur = pParse->nTab;
  92029. pParse->nTab += 3;
  92030. openStatTable(pParse, iDb, iStatCur, 0, 0);
  92031. iMem = pParse->nMem+1;
  92032. iTab = pParse->nTab;
  92033. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  92034. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  92035. Table *pTab = (Table*)sqliteHashData(k);
  92036. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  92037. }
  92038. loadAnalysis(pParse, iDb);
  92039. }
  92040. /*
  92041. ** Generate code that will do an analysis of a single table in
  92042. ** a database. If pOnlyIdx is not NULL then it is a single index
  92043. ** in pTab that should be analyzed.
  92044. */
  92045. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  92046. int iDb;
  92047. int iStatCur;
  92048. assert( pTab!=0 );
  92049. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  92050. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  92051. sqlite3BeginWriteOperation(pParse, 0, iDb);
  92052. iStatCur = pParse->nTab;
  92053. pParse->nTab += 3;
  92054. if( pOnlyIdx ){
  92055. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  92056. }else{
  92057. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  92058. }
  92059. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  92060. loadAnalysis(pParse, iDb);
  92061. }
  92062. /*
  92063. ** Generate code for the ANALYZE command. The parser calls this routine
  92064. ** when it recognizes an ANALYZE command.
  92065. **
  92066. ** ANALYZE -- 1
  92067. ** ANALYZE <database> -- 2
  92068. ** ANALYZE ?<database>.?<tablename> -- 3
  92069. **
  92070. ** Form 1 causes all indices in all attached databases to be analyzed.
  92071. ** Form 2 analyzes all indices the single database named.
  92072. ** Form 3 analyzes all indices associated with the named table.
  92073. */
  92074. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  92075. sqlite3 *db = pParse->db;
  92076. int iDb;
  92077. int i;
  92078. char *z, *zDb;
  92079. Table *pTab;
  92080. Index *pIdx;
  92081. Token *pTableName;
  92082. Vdbe *v;
  92083. /* Read the database schema. If an error occurs, leave an error message
  92084. ** and code in pParse and return NULL. */
  92085. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  92086. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  92087. return;
  92088. }
  92089. assert( pName2!=0 || pName1==0 );
  92090. if( pName1==0 ){
  92091. /* Form 1: Analyze everything */
  92092. for(i=0; i<db->nDb; i++){
  92093. if( i==1 ) continue; /* Do not analyze the TEMP database */
  92094. analyzeDatabase(pParse, i);
  92095. }
  92096. }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
  92097. /* Analyze the schema named as the argument */
  92098. analyzeDatabase(pParse, iDb);
  92099. }else{
  92100. /* Form 3: Analyze the table or index named as an argument */
  92101. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  92102. if( iDb>=0 ){
  92103. zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
  92104. z = sqlite3NameFromToken(db, pTableName);
  92105. if( z ){
  92106. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  92107. analyzeTable(pParse, pIdx->pTable, pIdx);
  92108. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  92109. analyzeTable(pParse, pTab, 0);
  92110. }
  92111. sqlite3DbFree(db, z);
  92112. }
  92113. }
  92114. }
  92115. if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
  92116. sqlite3VdbeAddOp0(v, OP_Expire);
  92117. }
  92118. }
  92119. /*
  92120. ** Used to pass information from the analyzer reader through to the
  92121. ** callback routine.
  92122. */
  92123. typedef struct analysisInfo analysisInfo;
  92124. struct analysisInfo {
  92125. sqlite3 *db;
  92126. const char *zDatabase;
  92127. };
  92128. /*
  92129. ** The first argument points to a nul-terminated string containing a
  92130. ** list of space separated integers. Read the first nOut of these into
  92131. ** the array aOut[].
  92132. */
  92133. static void decodeIntArray(
  92134. char *zIntArray, /* String containing int array to decode */
  92135. int nOut, /* Number of slots in aOut[] */
  92136. tRowcnt *aOut, /* Store integers here */
  92137. LogEst *aLog, /* Or, if aOut==0, here */
  92138. Index *pIndex /* Handle extra flags for this index, if not NULL */
  92139. ){
  92140. char *z = zIntArray;
  92141. int c;
  92142. int i;
  92143. tRowcnt v;
  92144. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92145. if( z==0 ) z = "";
  92146. #else
  92147. assert( z!=0 );
  92148. #endif
  92149. for(i=0; *z && i<nOut; i++){
  92150. v = 0;
  92151. while( (c=z[0])>='0' && c<='9' ){
  92152. v = v*10 + c - '0';
  92153. z++;
  92154. }
  92155. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92156. if( aOut ) aOut[i] = v;
  92157. if( aLog ) aLog[i] = sqlite3LogEst(v);
  92158. #else
  92159. assert( aOut==0 );
  92160. UNUSED_PARAMETER(aOut);
  92161. assert( aLog!=0 );
  92162. aLog[i] = sqlite3LogEst(v);
  92163. #endif
  92164. if( *z==' ' ) z++;
  92165. }
  92166. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  92167. assert( pIndex!=0 ); {
  92168. #else
  92169. if( pIndex ){
  92170. #endif
  92171. pIndex->bUnordered = 0;
  92172. pIndex->noSkipScan = 0;
  92173. while( z[0] ){
  92174. if( sqlite3_strglob("unordered*", z)==0 ){
  92175. pIndex->bUnordered = 1;
  92176. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  92177. pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
  92178. }else if( sqlite3_strglob("noskipscan*", z)==0 ){
  92179. pIndex->noSkipScan = 1;
  92180. }
  92181. #ifdef SQLITE_ENABLE_COSTMULT
  92182. else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
  92183. pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
  92184. }
  92185. #endif
  92186. while( z[0]!=0 && z[0]!=' ' ) z++;
  92187. while( z[0]==' ' ) z++;
  92188. }
  92189. }
  92190. }
  92191. /*
  92192. ** This callback is invoked once for each index when reading the
  92193. ** sqlite_stat1 table.
  92194. **
  92195. ** argv[0] = name of the table
  92196. ** argv[1] = name of the index (might be NULL)
  92197. ** argv[2] = results of analysis - on integer for each column
  92198. **
  92199. ** Entries for which argv[1]==NULL simply record the number of rows in
  92200. ** the table.
  92201. */
  92202. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  92203. analysisInfo *pInfo = (analysisInfo*)pData;
  92204. Index *pIndex;
  92205. Table *pTable;
  92206. const char *z;
  92207. assert( argc==3 );
  92208. UNUSED_PARAMETER2(NotUsed, argc);
  92209. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  92210. return 0;
  92211. }
  92212. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  92213. if( pTable==0 ){
  92214. return 0;
  92215. }
  92216. if( argv[1]==0 ){
  92217. pIndex = 0;
  92218. }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
  92219. pIndex = sqlite3PrimaryKeyIndex(pTable);
  92220. }else{
  92221. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  92222. }
  92223. z = argv[2];
  92224. if( pIndex ){
  92225. tRowcnt *aiRowEst = 0;
  92226. int nCol = pIndex->nKeyCol+1;
  92227. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92228. /* Index.aiRowEst may already be set here if there are duplicate
  92229. ** sqlite_stat1 entries for this index. In that case just clobber
  92230. ** the old data with the new instead of allocating a new array. */
  92231. if( pIndex->aiRowEst==0 ){
  92232. pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
  92233. if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
  92234. }
  92235. aiRowEst = pIndex->aiRowEst;
  92236. #endif
  92237. pIndex->bUnordered = 0;
  92238. decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
  92239. pIndex->hasStat1 = 1;
  92240. if( pIndex->pPartIdxWhere==0 ){
  92241. pTable->nRowLogEst = pIndex->aiRowLogEst[0];
  92242. pTable->tabFlags |= TF_HasStat1;
  92243. }
  92244. }else{
  92245. Index fakeIdx;
  92246. fakeIdx.szIdxRow = pTable->szTabRow;
  92247. #ifdef SQLITE_ENABLE_COSTMULT
  92248. fakeIdx.pTable = pTable;
  92249. #endif
  92250. decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
  92251. pTable->szTabRow = fakeIdx.szIdxRow;
  92252. pTable->tabFlags |= TF_HasStat1;
  92253. }
  92254. return 0;
  92255. }
  92256. /*
  92257. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  92258. ** and its contents.
  92259. */
  92260. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  92261. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92262. if( pIdx->aSample ){
  92263. int j;
  92264. for(j=0; j<pIdx->nSample; j++){
  92265. IndexSample *p = &pIdx->aSample[j];
  92266. sqlite3DbFree(db, p->p);
  92267. }
  92268. sqlite3DbFree(db, pIdx->aSample);
  92269. }
  92270. if( db && db->pnBytesFreed==0 ){
  92271. pIdx->nSample = 0;
  92272. pIdx->aSample = 0;
  92273. }
  92274. #else
  92275. UNUSED_PARAMETER(db);
  92276. UNUSED_PARAMETER(pIdx);
  92277. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  92278. }
  92279. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92280. /*
  92281. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  92282. ** stored in pIdx->aSample[].
  92283. */
  92284. static void initAvgEq(Index *pIdx){
  92285. if( pIdx ){
  92286. IndexSample *aSample = pIdx->aSample;
  92287. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  92288. int iCol;
  92289. int nCol = 1;
  92290. if( pIdx->nSampleCol>1 ){
  92291. /* If this is stat4 data, then calculate aAvgEq[] values for all
  92292. ** sample columns except the last. The last is always set to 1, as
  92293. ** once the trailing PK fields are considered all index keys are
  92294. ** unique. */
  92295. nCol = pIdx->nSampleCol-1;
  92296. pIdx->aAvgEq[nCol] = 1;
  92297. }
  92298. for(iCol=0; iCol<nCol; iCol++){
  92299. int nSample = pIdx->nSample;
  92300. int i; /* Used to iterate through samples */
  92301. tRowcnt sumEq = 0; /* Sum of the nEq values */
  92302. tRowcnt avgEq = 0;
  92303. tRowcnt nRow; /* Number of rows in index */
  92304. i64 nSum100 = 0; /* Number of terms contributing to sumEq */
  92305. i64 nDist100; /* Number of distinct values in index */
  92306. if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
  92307. nRow = pFinal->anLt[iCol];
  92308. nDist100 = (i64)100 * pFinal->anDLt[iCol];
  92309. nSample--;
  92310. }else{
  92311. nRow = pIdx->aiRowEst[0];
  92312. nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
  92313. }
  92314. pIdx->nRowEst0 = nRow;
  92315. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  92316. ** occur in the stat4 table for this index. Set sumEq to the sum of
  92317. ** the nEq values for column iCol for the same set (adding the value
  92318. ** only once where there exist duplicate prefixes). */
  92319. for(i=0; i<nSample; i++){
  92320. if( i==(pIdx->nSample-1)
  92321. || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
  92322. ){
  92323. sumEq += aSample[i].anEq[iCol];
  92324. nSum100 += 100;
  92325. }
  92326. }
  92327. if( nDist100>nSum100 && sumEq<nRow ){
  92328. avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
  92329. }
  92330. if( avgEq==0 ) avgEq = 1;
  92331. pIdx->aAvgEq[iCol] = avgEq;
  92332. }
  92333. }
  92334. }
  92335. /*
  92336. ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
  92337. ** is supplied instead, find the PRIMARY KEY index for that table.
  92338. */
  92339. static Index *findIndexOrPrimaryKey(
  92340. sqlite3 *db,
  92341. const char *zName,
  92342. const char *zDb
  92343. ){
  92344. Index *pIdx = sqlite3FindIndex(db, zName, zDb);
  92345. if( pIdx==0 ){
  92346. Table *pTab = sqlite3FindTable(db, zName, zDb);
  92347. if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
  92348. }
  92349. return pIdx;
  92350. }
  92351. /*
  92352. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  92353. ** into the relevant Index.aSample[] arrays.
  92354. **
  92355. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  92356. ** data equivalent to the following (statements are different for stat3,
  92357. ** see the caller of this function for details):
  92358. **
  92359. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  92360. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  92361. **
  92362. ** where %Q is replaced with the database name before the SQL is executed.
  92363. */
  92364. static int loadStatTbl(
  92365. sqlite3 *db, /* Database handle */
  92366. int bStat3, /* Assume single column records only */
  92367. const char *zSql1, /* SQL statement 1 (see above) */
  92368. const char *zSql2, /* SQL statement 2 (see above) */
  92369. const char *zDb /* Database name (e.g. "main") */
  92370. ){
  92371. int rc; /* Result codes from subroutines */
  92372. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  92373. char *zSql; /* Text of the SQL statement */
  92374. Index *pPrevIdx = 0; /* Previous index in the loop */
  92375. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  92376. assert( db->lookaside.bDisable );
  92377. zSql = sqlite3MPrintf(db, zSql1, zDb);
  92378. if( !zSql ){
  92379. return SQLITE_NOMEM_BKPT;
  92380. }
  92381. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  92382. sqlite3DbFree(db, zSql);
  92383. if( rc ) return rc;
  92384. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  92385. int nIdxCol = 1; /* Number of columns in stat4 records */
  92386. char *zIndex; /* Index name */
  92387. Index *pIdx; /* Pointer to the index object */
  92388. int nSample; /* Number of samples */
  92389. int nByte; /* Bytes of space required */
  92390. int i; /* Bytes of space required */
  92391. tRowcnt *pSpace;
  92392. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  92393. if( zIndex==0 ) continue;
  92394. nSample = sqlite3_column_int(pStmt, 1);
  92395. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  92396. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  92397. /* Index.nSample is non-zero at this point if data has already been
  92398. ** loaded from the stat4 table. In this case ignore stat3 data. */
  92399. if( pIdx==0 || pIdx->nSample ) continue;
  92400. if( bStat3==0 ){
  92401. assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
  92402. if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
  92403. nIdxCol = pIdx->nKeyCol;
  92404. }else{
  92405. nIdxCol = pIdx->nColumn;
  92406. }
  92407. }
  92408. pIdx->nSampleCol = nIdxCol;
  92409. nByte = sizeof(IndexSample) * nSample;
  92410. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  92411. nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  92412. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  92413. if( pIdx->aSample==0 ){
  92414. sqlite3_finalize(pStmt);
  92415. return SQLITE_NOMEM_BKPT;
  92416. }
  92417. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  92418. pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
  92419. for(i=0; i<nSample; i++){
  92420. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  92421. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  92422. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  92423. }
  92424. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  92425. }
  92426. rc = sqlite3_finalize(pStmt);
  92427. if( rc ) return rc;
  92428. zSql = sqlite3MPrintf(db, zSql2, zDb);
  92429. if( !zSql ){
  92430. return SQLITE_NOMEM_BKPT;
  92431. }
  92432. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  92433. sqlite3DbFree(db, zSql);
  92434. if( rc ) return rc;
  92435. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  92436. char *zIndex; /* Index name */
  92437. Index *pIdx; /* Pointer to the index object */
  92438. int nCol = 1; /* Number of columns in index */
  92439. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  92440. if( zIndex==0 ) continue;
  92441. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  92442. if( pIdx==0 ) continue;
  92443. /* This next condition is true if data has already been loaded from
  92444. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  92445. nCol = pIdx->nSampleCol;
  92446. if( bStat3 && nCol>1 ) continue;
  92447. if( pIdx!=pPrevIdx ){
  92448. initAvgEq(pPrevIdx);
  92449. pPrevIdx = pIdx;
  92450. }
  92451. pSample = &pIdx->aSample[pIdx->nSample];
  92452. decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
  92453. decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
  92454. decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
  92455. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  92456. ** This is in case the sample record is corrupted. In that case, the
  92457. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  92458. ** end of the allocated buffer before it realizes it is dealing with
  92459. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  92460. ** a buffer overread. */
  92461. pSample->n = sqlite3_column_bytes(pStmt, 4);
  92462. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  92463. if( pSample->p==0 ){
  92464. sqlite3_finalize(pStmt);
  92465. return SQLITE_NOMEM_BKPT;
  92466. }
  92467. if( pSample->n ){
  92468. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  92469. }
  92470. pIdx->nSample++;
  92471. }
  92472. rc = sqlite3_finalize(pStmt);
  92473. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  92474. return rc;
  92475. }
  92476. /*
  92477. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  92478. ** the Index.aSample[] arrays of all indices.
  92479. */
  92480. static int loadStat4(sqlite3 *db, const char *zDb){
  92481. int rc = SQLITE_OK; /* Result codes from subroutines */
  92482. assert( db->lookaside.bDisable );
  92483. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  92484. rc = loadStatTbl(db, 0,
  92485. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  92486. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  92487. zDb
  92488. );
  92489. }
  92490. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  92491. rc = loadStatTbl(db, 1,
  92492. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  92493. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  92494. zDb
  92495. );
  92496. }
  92497. return rc;
  92498. }
  92499. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  92500. /*
  92501. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  92502. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  92503. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  92504. ** Index.aSample[] arrays.
  92505. **
  92506. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  92507. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  92508. ** during compilation and the sqlite_stat3/4 table is present, no data is
  92509. ** read from it.
  92510. **
  92511. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  92512. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  92513. ** returned. However, in this case, data is read from the sqlite_stat1
  92514. ** table (if it is present) before returning.
  92515. **
  92516. ** If an OOM error occurs, this function always sets db->mallocFailed.
  92517. ** This means if the caller does not care about other errors, the return
  92518. ** code may be ignored.
  92519. */
  92520. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  92521. analysisInfo sInfo;
  92522. HashElem *i;
  92523. char *zSql;
  92524. int rc = SQLITE_OK;
  92525. Schema *pSchema = db->aDb[iDb].pSchema;
  92526. assert( iDb>=0 && iDb<db->nDb );
  92527. assert( db->aDb[iDb].pBt!=0 );
  92528. /* Clear any prior statistics */
  92529. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  92530. for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
  92531. Table *pTab = sqliteHashData(i);
  92532. pTab->tabFlags &= ~TF_HasStat1;
  92533. }
  92534. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  92535. Index *pIdx = sqliteHashData(i);
  92536. pIdx->hasStat1 = 0;
  92537. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92538. sqlite3DeleteIndexSamples(db, pIdx);
  92539. pIdx->aSample = 0;
  92540. #endif
  92541. }
  92542. /* Load new statistics out of the sqlite_stat1 table */
  92543. sInfo.db = db;
  92544. sInfo.zDatabase = db->aDb[iDb].zDbSName;
  92545. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
  92546. zSql = sqlite3MPrintf(db,
  92547. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  92548. if( zSql==0 ){
  92549. rc = SQLITE_NOMEM_BKPT;
  92550. }else{
  92551. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  92552. sqlite3DbFree(db, zSql);
  92553. }
  92554. }
  92555. /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
  92556. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  92557. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  92558. Index *pIdx = sqliteHashData(i);
  92559. if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
  92560. }
  92561. /* Load the statistics from the sqlite_stat4 table. */
  92562. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  92563. if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
  92564. db->lookaside.bDisable++;
  92565. rc = loadStat4(db, sInfo.zDatabase);
  92566. db->lookaside.bDisable--;
  92567. }
  92568. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  92569. Index *pIdx = sqliteHashData(i);
  92570. sqlite3_free(pIdx->aiRowEst);
  92571. pIdx->aiRowEst = 0;
  92572. }
  92573. #endif
  92574. if( rc==SQLITE_NOMEM ){
  92575. sqlite3OomFault(db);
  92576. }
  92577. return rc;
  92578. }
  92579. #endif /* SQLITE_OMIT_ANALYZE */
  92580. /************** End of analyze.c *********************************************/
  92581. /************** Begin file attach.c ******************************************/
  92582. /*
  92583. ** 2003 April 6
  92584. **
  92585. ** The author disclaims copyright to this source code. In place of
  92586. ** a legal notice, here is a blessing:
  92587. **
  92588. ** May you do good and not evil.
  92589. ** May you find forgiveness for yourself and forgive others.
  92590. ** May you share freely, never taking more than you give.
  92591. **
  92592. *************************************************************************
  92593. ** This file contains code used to implement the ATTACH and DETACH commands.
  92594. */
  92595. /* #include "sqliteInt.h" */
  92596. #ifndef SQLITE_OMIT_ATTACH
  92597. /*
  92598. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  92599. ** is slightly different from resolving a normal SQL expression, because simple
  92600. ** identifiers are treated as strings, not possible column names or aliases.
  92601. **
  92602. ** i.e. if the parser sees:
  92603. **
  92604. ** ATTACH DATABASE abc AS def
  92605. **
  92606. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  92607. ** looking for columns of the same name.
  92608. **
  92609. ** This only applies to the root node of pExpr, so the statement:
  92610. **
  92611. ** ATTACH DATABASE abc||def AS 'db2'
  92612. **
  92613. ** will fail because neither abc or def can be resolved.
  92614. */
  92615. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  92616. {
  92617. int rc = SQLITE_OK;
  92618. if( pExpr ){
  92619. if( pExpr->op!=TK_ID ){
  92620. rc = sqlite3ResolveExprNames(pName, pExpr);
  92621. }else{
  92622. pExpr->op = TK_STRING;
  92623. }
  92624. }
  92625. return rc;
  92626. }
  92627. /*
  92628. ** An SQL user-function registered to do the work of an ATTACH statement. The
  92629. ** three arguments to the function come directly from an attach statement:
  92630. **
  92631. ** ATTACH DATABASE x AS y KEY z
  92632. **
  92633. ** SELECT sqlite_attach(x, y, z)
  92634. **
  92635. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  92636. ** third argument.
  92637. */
  92638. static void attachFunc(
  92639. sqlite3_context *context,
  92640. int NotUsed,
  92641. sqlite3_value **argv
  92642. ){
  92643. int i;
  92644. int rc = 0;
  92645. sqlite3 *db = sqlite3_context_db_handle(context);
  92646. const char *zName;
  92647. const char *zFile;
  92648. char *zPath = 0;
  92649. char *zErr = 0;
  92650. unsigned int flags;
  92651. Db *aNew;
  92652. char *zErrDyn = 0;
  92653. sqlite3_vfs *pVfs;
  92654. UNUSED_PARAMETER(NotUsed);
  92655. zFile = (const char *)sqlite3_value_text(argv[0]);
  92656. zName = (const char *)sqlite3_value_text(argv[1]);
  92657. if( zFile==0 ) zFile = "";
  92658. if( zName==0 ) zName = "";
  92659. /* Check for the following errors:
  92660. **
  92661. ** * Too many attached databases,
  92662. ** * Transaction currently open
  92663. ** * Specified database name already being used.
  92664. */
  92665. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  92666. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  92667. db->aLimit[SQLITE_LIMIT_ATTACHED]
  92668. );
  92669. goto attach_error;
  92670. }
  92671. if( !db->autoCommit ){
  92672. zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
  92673. goto attach_error;
  92674. }
  92675. for(i=0; i<db->nDb; i++){
  92676. char *z = db->aDb[i].zDbSName;
  92677. assert( z && zName );
  92678. if( sqlite3StrICmp(z, zName)==0 ){
  92679. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  92680. goto attach_error;
  92681. }
  92682. }
  92683. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  92684. ** hash tables.
  92685. */
  92686. if( db->aDb==db->aDbStatic ){
  92687. aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
  92688. if( aNew==0 ) return;
  92689. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  92690. }else{
  92691. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  92692. if( aNew==0 ) return;
  92693. }
  92694. db->aDb = aNew;
  92695. aNew = &db->aDb[db->nDb];
  92696. memset(aNew, 0, sizeof(*aNew));
  92697. /* Open the database file. If the btree is successfully opened, use
  92698. ** it to obtain the database schema. At this point the schema may
  92699. ** or may not be initialized.
  92700. */
  92701. flags = db->openFlags;
  92702. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  92703. if( rc!=SQLITE_OK ){
  92704. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  92705. sqlite3_result_error(context, zErr, -1);
  92706. sqlite3_free(zErr);
  92707. return;
  92708. }
  92709. assert( pVfs );
  92710. flags |= SQLITE_OPEN_MAIN_DB;
  92711. rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
  92712. sqlite3_free( zPath );
  92713. db->nDb++;
  92714. db->skipBtreeMutex = 0;
  92715. if( rc==SQLITE_CONSTRAINT ){
  92716. rc = SQLITE_ERROR;
  92717. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  92718. }else if( rc==SQLITE_OK ){
  92719. Pager *pPager;
  92720. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  92721. if( !aNew->pSchema ){
  92722. rc = SQLITE_NOMEM_BKPT;
  92723. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  92724. zErrDyn = sqlite3MPrintf(db,
  92725. "attached databases must use the same text encoding as main database");
  92726. rc = SQLITE_ERROR;
  92727. }
  92728. sqlite3BtreeEnter(aNew->pBt);
  92729. pPager = sqlite3BtreePager(aNew->pBt);
  92730. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  92731. sqlite3BtreeSecureDelete(aNew->pBt,
  92732. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  92733. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  92734. sqlite3BtreeSetPagerFlags(aNew->pBt,
  92735. PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
  92736. #endif
  92737. sqlite3BtreeLeave(aNew->pBt);
  92738. }
  92739. aNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  92740. aNew->zDbSName = sqlite3DbStrDup(db, zName);
  92741. if( rc==SQLITE_OK && aNew->zDbSName==0 ){
  92742. rc = SQLITE_NOMEM_BKPT;
  92743. }
  92744. #ifdef SQLITE_HAS_CODEC
  92745. if( rc==SQLITE_OK ){
  92746. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  92747. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  92748. int nKey;
  92749. char *zKey;
  92750. int t = sqlite3_value_type(argv[2]);
  92751. switch( t ){
  92752. case SQLITE_INTEGER:
  92753. case SQLITE_FLOAT:
  92754. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  92755. rc = SQLITE_ERROR;
  92756. break;
  92757. case SQLITE_TEXT:
  92758. case SQLITE_BLOB:
  92759. nKey = sqlite3_value_bytes(argv[2]);
  92760. zKey = (char *)sqlite3_value_blob(argv[2]);
  92761. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  92762. break;
  92763. case SQLITE_NULL:
  92764. /* No key specified. Use the key from the main database */
  92765. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  92766. if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
  92767. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  92768. }
  92769. break;
  92770. }
  92771. }
  92772. #endif
  92773. /* If the file was opened successfully, read the schema for the new database.
  92774. ** If this fails, or if opening the file failed, then close the file and
  92775. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  92776. ** we found it.
  92777. */
  92778. if( rc==SQLITE_OK ){
  92779. sqlite3BtreeEnterAll(db);
  92780. rc = sqlite3Init(db, &zErrDyn);
  92781. sqlite3BtreeLeaveAll(db);
  92782. }
  92783. #ifdef SQLITE_USER_AUTHENTICATION
  92784. if( rc==SQLITE_OK ){
  92785. u8 newAuth = 0;
  92786. rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
  92787. if( newAuth<db->auth.authLevel ){
  92788. rc = SQLITE_AUTH_USER;
  92789. }
  92790. }
  92791. #endif
  92792. if( rc ){
  92793. int iDb = db->nDb - 1;
  92794. assert( iDb>=2 );
  92795. if( db->aDb[iDb].pBt ){
  92796. sqlite3BtreeClose(db->aDb[iDb].pBt);
  92797. db->aDb[iDb].pBt = 0;
  92798. db->aDb[iDb].pSchema = 0;
  92799. }
  92800. sqlite3ResetAllSchemasOfConnection(db);
  92801. db->nDb = iDb;
  92802. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  92803. sqlite3OomFault(db);
  92804. sqlite3DbFree(db, zErrDyn);
  92805. zErrDyn = sqlite3MPrintf(db, "out of memory");
  92806. }else if( zErrDyn==0 ){
  92807. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  92808. }
  92809. goto attach_error;
  92810. }
  92811. return;
  92812. attach_error:
  92813. /* Return an error if we get here */
  92814. if( zErrDyn ){
  92815. sqlite3_result_error(context, zErrDyn, -1);
  92816. sqlite3DbFree(db, zErrDyn);
  92817. }
  92818. if( rc ) sqlite3_result_error_code(context, rc);
  92819. }
  92820. /*
  92821. ** An SQL user-function registered to do the work of an DETACH statement. The
  92822. ** three arguments to the function come directly from a detach statement:
  92823. **
  92824. ** DETACH DATABASE x
  92825. **
  92826. ** SELECT sqlite_detach(x)
  92827. */
  92828. static void detachFunc(
  92829. sqlite3_context *context,
  92830. int NotUsed,
  92831. sqlite3_value **argv
  92832. ){
  92833. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  92834. sqlite3 *db = sqlite3_context_db_handle(context);
  92835. int i;
  92836. Db *pDb = 0;
  92837. char zErr[128];
  92838. UNUSED_PARAMETER(NotUsed);
  92839. if( zName==0 ) zName = "";
  92840. for(i=0; i<db->nDb; i++){
  92841. pDb = &db->aDb[i];
  92842. if( pDb->pBt==0 ) continue;
  92843. if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
  92844. }
  92845. if( i>=db->nDb ){
  92846. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  92847. goto detach_error;
  92848. }
  92849. if( i<2 ){
  92850. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  92851. goto detach_error;
  92852. }
  92853. if( !db->autoCommit ){
  92854. sqlite3_snprintf(sizeof(zErr), zErr,
  92855. "cannot DETACH database within transaction");
  92856. goto detach_error;
  92857. }
  92858. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  92859. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  92860. goto detach_error;
  92861. }
  92862. sqlite3BtreeClose(pDb->pBt);
  92863. pDb->pBt = 0;
  92864. pDb->pSchema = 0;
  92865. sqlite3CollapseDatabaseArray(db);
  92866. return;
  92867. detach_error:
  92868. sqlite3_result_error(context, zErr, -1);
  92869. }
  92870. /*
  92871. ** This procedure generates VDBE code for a single invocation of either the
  92872. ** sqlite_detach() or sqlite_attach() SQL user functions.
  92873. */
  92874. static void codeAttach(
  92875. Parse *pParse, /* The parser context */
  92876. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  92877. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  92878. Expr *pAuthArg, /* Expression to pass to authorization callback */
  92879. Expr *pFilename, /* Name of database file */
  92880. Expr *pDbname, /* Name of the database to use internally */
  92881. Expr *pKey /* Database key for encryption extension */
  92882. ){
  92883. int rc;
  92884. NameContext sName;
  92885. Vdbe *v;
  92886. sqlite3* db = pParse->db;
  92887. int regArgs;
  92888. if( pParse->nErr ) goto attach_end;
  92889. memset(&sName, 0, sizeof(NameContext));
  92890. sName.pParse = pParse;
  92891. if(
  92892. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  92893. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  92894. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  92895. ){
  92896. goto attach_end;
  92897. }
  92898. #ifndef SQLITE_OMIT_AUTHORIZATION
  92899. if( pAuthArg ){
  92900. char *zAuthArg;
  92901. if( pAuthArg->op==TK_STRING ){
  92902. zAuthArg = pAuthArg->u.zToken;
  92903. }else{
  92904. zAuthArg = 0;
  92905. }
  92906. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  92907. if(rc!=SQLITE_OK ){
  92908. goto attach_end;
  92909. }
  92910. }
  92911. #endif /* SQLITE_OMIT_AUTHORIZATION */
  92912. v = sqlite3GetVdbe(pParse);
  92913. regArgs = sqlite3GetTempRange(pParse, 4);
  92914. sqlite3ExprCode(pParse, pFilename, regArgs);
  92915. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  92916. sqlite3ExprCode(pParse, pKey, regArgs+2);
  92917. assert( v || db->mallocFailed );
  92918. if( v ){
  92919. sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
  92920. (char *)pFunc, P4_FUNCDEF);
  92921. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  92922. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  92923. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  92924. ** statement only). For DETACH, set it to false (expire all existing
  92925. ** statements).
  92926. */
  92927. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  92928. }
  92929. attach_end:
  92930. sqlite3ExprDelete(db, pFilename);
  92931. sqlite3ExprDelete(db, pDbname);
  92932. sqlite3ExprDelete(db, pKey);
  92933. }
  92934. /*
  92935. ** Called by the parser to compile a DETACH statement.
  92936. **
  92937. ** DETACH pDbname
  92938. */
  92939. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  92940. static const FuncDef detach_func = {
  92941. 1, /* nArg */
  92942. SQLITE_UTF8, /* funcFlags */
  92943. 0, /* pUserData */
  92944. 0, /* pNext */
  92945. detachFunc, /* xSFunc */
  92946. 0, /* xFinalize */
  92947. "sqlite_detach", /* zName */
  92948. {0}
  92949. };
  92950. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  92951. }
  92952. /*
  92953. ** Called by the parser to compile an ATTACH statement.
  92954. **
  92955. ** ATTACH p AS pDbname KEY pKey
  92956. */
  92957. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  92958. static const FuncDef attach_func = {
  92959. 3, /* nArg */
  92960. SQLITE_UTF8, /* funcFlags */
  92961. 0, /* pUserData */
  92962. 0, /* pNext */
  92963. attachFunc, /* xSFunc */
  92964. 0, /* xFinalize */
  92965. "sqlite_attach", /* zName */
  92966. {0}
  92967. };
  92968. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  92969. }
  92970. #endif /* SQLITE_OMIT_ATTACH */
  92971. /*
  92972. ** Initialize a DbFixer structure. This routine must be called prior
  92973. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  92974. */
  92975. SQLITE_PRIVATE void sqlite3FixInit(
  92976. DbFixer *pFix, /* The fixer to be initialized */
  92977. Parse *pParse, /* Error messages will be written here */
  92978. int iDb, /* This is the database that must be used */
  92979. const char *zType, /* "view", "trigger", or "index" */
  92980. const Token *pName /* Name of the view, trigger, or index */
  92981. ){
  92982. sqlite3 *db;
  92983. db = pParse->db;
  92984. assert( db->nDb>iDb );
  92985. pFix->pParse = pParse;
  92986. pFix->zDb = db->aDb[iDb].zDbSName;
  92987. pFix->pSchema = db->aDb[iDb].pSchema;
  92988. pFix->zType = zType;
  92989. pFix->pName = pName;
  92990. pFix->bVarOnly = (iDb==1);
  92991. }
  92992. /*
  92993. ** The following set of routines walk through the parse tree and assign
  92994. ** a specific database to all table references where the database name
  92995. ** was left unspecified in the original SQL statement. The pFix structure
  92996. ** must have been initialized by a prior call to sqlite3FixInit().
  92997. **
  92998. ** These routines are used to make sure that an index, trigger, or
  92999. ** view in one database does not refer to objects in a different database.
  93000. ** (Exception: indices, triggers, and views in the TEMP database are
  93001. ** allowed to refer to anything.) If a reference is explicitly made
  93002. ** to an object in a different database, an error message is added to
  93003. ** pParse->zErrMsg and these routines return non-zero. If everything
  93004. ** checks out, these routines return 0.
  93005. */
  93006. SQLITE_PRIVATE int sqlite3FixSrcList(
  93007. DbFixer *pFix, /* Context of the fixation */
  93008. SrcList *pList /* The Source list to check and modify */
  93009. ){
  93010. int i;
  93011. const char *zDb;
  93012. struct SrcList_item *pItem;
  93013. if( NEVER(pList==0) ) return 0;
  93014. zDb = pFix->zDb;
  93015. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  93016. if( pFix->bVarOnly==0 ){
  93017. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  93018. sqlite3ErrorMsg(pFix->pParse,
  93019. "%s %T cannot reference objects in database %s",
  93020. pFix->zType, pFix->pName, pItem->zDatabase);
  93021. return 1;
  93022. }
  93023. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  93024. pItem->zDatabase = 0;
  93025. pItem->pSchema = pFix->pSchema;
  93026. }
  93027. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  93028. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  93029. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  93030. #endif
  93031. }
  93032. return 0;
  93033. }
  93034. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  93035. SQLITE_PRIVATE int sqlite3FixSelect(
  93036. DbFixer *pFix, /* Context of the fixation */
  93037. Select *pSelect /* The SELECT statement to be fixed to one database */
  93038. ){
  93039. while( pSelect ){
  93040. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  93041. return 1;
  93042. }
  93043. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  93044. return 1;
  93045. }
  93046. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  93047. return 1;
  93048. }
  93049. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  93050. return 1;
  93051. }
  93052. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  93053. return 1;
  93054. }
  93055. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  93056. return 1;
  93057. }
  93058. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  93059. return 1;
  93060. }
  93061. if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
  93062. return 1;
  93063. }
  93064. pSelect = pSelect->pPrior;
  93065. }
  93066. return 0;
  93067. }
  93068. SQLITE_PRIVATE int sqlite3FixExpr(
  93069. DbFixer *pFix, /* Context of the fixation */
  93070. Expr *pExpr /* The expression to be fixed to one database */
  93071. ){
  93072. while( pExpr ){
  93073. if( pExpr->op==TK_VARIABLE ){
  93074. if( pFix->pParse->db->init.busy ){
  93075. pExpr->op = TK_NULL;
  93076. }else{
  93077. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  93078. return 1;
  93079. }
  93080. }
  93081. if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
  93082. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  93083. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  93084. }else{
  93085. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  93086. }
  93087. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  93088. return 1;
  93089. }
  93090. pExpr = pExpr->pLeft;
  93091. }
  93092. return 0;
  93093. }
  93094. SQLITE_PRIVATE int sqlite3FixExprList(
  93095. DbFixer *pFix, /* Context of the fixation */
  93096. ExprList *pList /* The expression to be fixed to one database */
  93097. ){
  93098. int i;
  93099. struct ExprList_item *pItem;
  93100. if( pList==0 ) return 0;
  93101. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  93102. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  93103. return 1;
  93104. }
  93105. }
  93106. return 0;
  93107. }
  93108. #endif
  93109. #ifndef SQLITE_OMIT_TRIGGER
  93110. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  93111. DbFixer *pFix, /* Context of the fixation */
  93112. TriggerStep *pStep /* The trigger step be fixed to one database */
  93113. ){
  93114. while( pStep ){
  93115. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  93116. return 1;
  93117. }
  93118. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  93119. return 1;
  93120. }
  93121. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  93122. return 1;
  93123. }
  93124. pStep = pStep->pNext;
  93125. }
  93126. return 0;
  93127. }
  93128. #endif
  93129. /************** End of attach.c **********************************************/
  93130. /************** Begin file auth.c ********************************************/
  93131. /*
  93132. ** 2003 January 11
  93133. **
  93134. ** The author disclaims copyright to this source code. In place of
  93135. ** a legal notice, here is a blessing:
  93136. **
  93137. ** May you do good and not evil.
  93138. ** May you find forgiveness for yourself and forgive others.
  93139. ** May you share freely, never taking more than you give.
  93140. **
  93141. *************************************************************************
  93142. ** This file contains code used to implement the sqlite3_set_authorizer()
  93143. ** API. This facility is an optional feature of the library. Embedded
  93144. ** systems that do not need this facility may omit it by recompiling
  93145. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  93146. */
  93147. /* #include "sqliteInt.h" */
  93148. /*
  93149. ** All of the code in this file may be omitted by defining a single
  93150. ** macro.
  93151. */
  93152. #ifndef SQLITE_OMIT_AUTHORIZATION
  93153. /*
  93154. ** Set or clear the access authorization function.
  93155. **
  93156. ** The access authorization function is be called during the compilation
  93157. ** phase to verify that the user has read and/or write access permission on
  93158. ** various fields of the database. The first argument to the auth function
  93159. ** is a copy of the 3rd argument to this routine. The second argument
  93160. ** to the auth function is one of these constants:
  93161. **
  93162. ** SQLITE_CREATE_INDEX
  93163. ** SQLITE_CREATE_TABLE
  93164. ** SQLITE_CREATE_TEMP_INDEX
  93165. ** SQLITE_CREATE_TEMP_TABLE
  93166. ** SQLITE_CREATE_TEMP_TRIGGER
  93167. ** SQLITE_CREATE_TEMP_VIEW
  93168. ** SQLITE_CREATE_TRIGGER
  93169. ** SQLITE_CREATE_VIEW
  93170. ** SQLITE_DELETE
  93171. ** SQLITE_DROP_INDEX
  93172. ** SQLITE_DROP_TABLE
  93173. ** SQLITE_DROP_TEMP_INDEX
  93174. ** SQLITE_DROP_TEMP_TABLE
  93175. ** SQLITE_DROP_TEMP_TRIGGER
  93176. ** SQLITE_DROP_TEMP_VIEW
  93177. ** SQLITE_DROP_TRIGGER
  93178. ** SQLITE_DROP_VIEW
  93179. ** SQLITE_INSERT
  93180. ** SQLITE_PRAGMA
  93181. ** SQLITE_READ
  93182. ** SQLITE_SELECT
  93183. ** SQLITE_TRANSACTION
  93184. ** SQLITE_UPDATE
  93185. **
  93186. ** The third and fourth arguments to the auth function are the name of
  93187. ** the table and the column that are being accessed. The auth function
  93188. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  93189. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  93190. ** means that the SQL statement will never-run - the sqlite3_exec() call
  93191. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  93192. ** should run but attempts to read the specified column will return NULL
  93193. ** and attempts to write the column will be ignored.
  93194. **
  93195. ** Setting the auth function to NULL disables this hook. The default
  93196. ** setting of the auth function is NULL.
  93197. */
  93198. SQLITE_API int sqlite3_set_authorizer(
  93199. sqlite3 *db,
  93200. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  93201. void *pArg
  93202. ){
  93203. #ifdef SQLITE_ENABLE_API_ARMOR
  93204. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  93205. #endif
  93206. sqlite3_mutex_enter(db->mutex);
  93207. db->xAuth = (sqlite3_xauth)xAuth;
  93208. db->pAuthArg = pArg;
  93209. sqlite3ExpirePreparedStatements(db);
  93210. sqlite3_mutex_leave(db->mutex);
  93211. return SQLITE_OK;
  93212. }
  93213. /*
  93214. ** Write an error message into pParse->zErrMsg that explains that the
  93215. ** user-supplied authorization function returned an illegal value.
  93216. */
  93217. static void sqliteAuthBadReturnCode(Parse *pParse){
  93218. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  93219. pParse->rc = SQLITE_ERROR;
  93220. }
  93221. /*
  93222. ** Invoke the authorization callback for permission to read column zCol from
  93223. ** table zTab in database zDb. This function assumes that an authorization
  93224. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  93225. **
  93226. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  93227. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  93228. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  93229. */
  93230. SQLITE_PRIVATE int sqlite3AuthReadCol(
  93231. Parse *pParse, /* The parser context */
  93232. const char *zTab, /* Table name */
  93233. const char *zCol, /* Column name */
  93234. int iDb /* Index of containing database. */
  93235. ){
  93236. sqlite3 *db = pParse->db; /* Database handle */
  93237. char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
  93238. int rc; /* Auth callback return code */
  93239. if( db->init.busy ) return SQLITE_OK;
  93240. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
  93241. #ifdef SQLITE_USER_AUTHENTICATION
  93242. ,db->auth.zAuthUser
  93243. #endif
  93244. );
  93245. if( rc==SQLITE_DENY ){
  93246. if( db->nDb>2 || iDb!=0 ){
  93247. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
  93248. }else{
  93249. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
  93250. }
  93251. pParse->rc = SQLITE_AUTH;
  93252. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  93253. sqliteAuthBadReturnCode(pParse);
  93254. }
  93255. return rc;
  93256. }
  93257. /*
  93258. ** The pExpr should be a TK_COLUMN expression. The table referred to
  93259. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  93260. ** Check to see if it is OK to read this particular column.
  93261. **
  93262. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  93263. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  93264. ** then generate an error.
  93265. */
  93266. SQLITE_PRIVATE void sqlite3AuthRead(
  93267. Parse *pParse, /* The parser context */
  93268. Expr *pExpr, /* The expression to check authorization on */
  93269. Schema *pSchema, /* The schema of the expression */
  93270. SrcList *pTabList /* All table that pExpr might refer to */
  93271. ){
  93272. sqlite3 *db = pParse->db;
  93273. Table *pTab = 0; /* The table being read */
  93274. const char *zCol; /* Name of the column of the table */
  93275. int iSrc; /* Index in pTabList->a[] of table being read */
  93276. int iDb; /* The index of the database the expression refers to */
  93277. int iCol; /* Index of column in table */
  93278. if( db->xAuth==0 ) return;
  93279. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  93280. if( iDb<0 ){
  93281. /* An attempt to read a column out of a subquery or other
  93282. ** temporary table. */
  93283. return;
  93284. }
  93285. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  93286. if( pExpr->op==TK_TRIGGER ){
  93287. pTab = pParse->pTriggerTab;
  93288. }else{
  93289. assert( pTabList );
  93290. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  93291. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  93292. pTab = pTabList->a[iSrc].pTab;
  93293. break;
  93294. }
  93295. }
  93296. }
  93297. iCol = pExpr->iColumn;
  93298. if( NEVER(pTab==0) ) return;
  93299. if( iCol>=0 ){
  93300. assert( iCol<pTab->nCol );
  93301. zCol = pTab->aCol[iCol].zName;
  93302. }else if( pTab->iPKey>=0 ){
  93303. assert( pTab->iPKey<pTab->nCol );
  93304. zCol = pTab->aCol[pTab->iPKey].zName;
  93305. }else{
  93306. zCol = "ROWID";
  93307. }
  93308. assert( iDb>=0 && iDb<db->nDb );
  93309. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  93310. pExpr->op = TK_NULL;
  93311. }
  93312. }
  93313. /*
  93314. ** Do an authorization check using the code and arguments given. Return
  93315. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  93316. ** is returned, then the error count and error message in pParse are
  93317. ** modified appropriately.
  93318. */
  93319. SQLITE_PRIVATE int sqlite3AuthCheck(
  93320. Parse *pParse,
  93321. int code,
  93322. const char *zArg1,
  93323. const char *zArg2,
  93324. const char *zArg3
  93325. ){
  93326. sqlite3 *db = pParse->db;
  93327. int rc;
  93328. /* Don't do any authorization checks if the database is initialising
  93329. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  93330. */
  93331. if( db->init.busy || IN_DECLARE_VTAB ){
  93332. return SQLITE_OK;
  93333. }
  93334. if( db->xAuth==0 ){
  93335. return SQLITE_OK;
  93336. }
  93337. /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the
  93338. ** callback are either NULL pointers or zero-terminated strings that
  93339. ** contain additional details about the action to be authorized.
  93340. **
  93341. ** The following testcase() macros show that any of the 3rd through 6th
  93342. ** parameters can be either NULL or a string. */
  93343. testcase( zArg1==0 );
  93344. testcase( zArg2==0 );
  93345. testcase( zArg3==0 );
  93346. testcase( pParse->zAuthContext==0 );
  93347. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
  93348. #ifdef SQLITE_USER_AUTHENTICATION
  93349. ,db->auth.zAuthUser
  93350. #endif
  93351. );
  93352. if( rc==SQLITE_DENY ){
  93353. sqlite3ErrorMsg(pParse, "not authorized");
  93354. pParse->rc = SQLITE_AUTH;
  93355. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  93356. rc = SQLITE_DENY;
  93357. sqliteAuthBadReturnCode(pParse);
  93358. }
  93359. return rc;
  93360. }
  93361. /*
  93362. ** Push an authorization context. After this routine is called, the
  93363. ** zArg3 argument to authorization callbacks will be zContext until
  93364. ** popped. Or if pParse==0, this routine is a no-op.
  93365. */
  93366. SQLITE_PRIVATE void sqlite3AuthContextPush(
  93367. Parse *pParse,
  93368. AuthContext *pContext,
  93369. const char *zContext
  93370. ){
  93371. assert( pParse );
  93372. pContext->pParse = pParse;
  93373. pContext->zAuthContext = pParse->zAuthContext;
  93374. pParse->zAuthContext = zContext;
  93375. }
  93376. /*
  93377. ** Pop an authorization context that was previously pushed
  93378. ** by sqlite3AuthContextPush
  93379. */
  93380. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  93381. if( pContext->pParse ){
  93382. pContext->pParse->zAuthContext = pContext->zAuthContext;
  93383. pContext->pParse = 0;
  93384. }
  93385. }
  93386. #endif /* SQLITE_OMIT_AUTHORIZATION */
  93387. /************** End of auth.c ************************************************/
  93388. /************** Begin file build.c *******************************************/
  93389. /*
  93390. ** 2001 September 15
  93391. **
  93392. ** The author disclaims copyright to this source code. In place of
  93393. ** a legal notice, here is a blessing:
  93394. **
  93395. ** May you do good and not evil.
  93396. ** May you find forgiveness for yourself and forgive others.
  93397. ** May you share freely, never taking more than you give.
  93398. **
  93399. *************************************************************************
  93400. ** This file contains C code routines that are called by the SQLite parser
  93401. ** when syntax rules are reduced. The routines in this file handle the
  93402. ** following kinds of SQL syntax:
  93403. **
  93404. ** CREATE TABLE
  93405. ** DROP TABLE
  93406. ** CREATE INDEX
  93407. ** DROP INDEX
  93408. ** creating ID lists
  93409. ** BEGIN TRANSACTION
  93410. ** COMMIT
  93411. ** ROLLBACK
  93412. */
  93413. /* #include "sqliteInt.h" */
  93414. #ifndef SQLITE_OMIT_SHARED_CACHE
  93415. /*
  93416. ** The TableLock structure is only used by the sqlite3TableLock() and
  93417. ** codeTableLocks() functions.
  93418. */
  93419. struct TableLock {
  93420. int iDb; /* The database containing the table to be locked */
  93421. int iTab; /* The root page of the table to be locked */
  93422. u8 isWriteLock; /* True for write lock. False for a read lock */
  93423. const char *zLockName; /* Name of the table */
  93424. };
  93425. /*
  93426. ** Record the fact that we want to lock a table at run-time.
  93427. **
  93428. ** The table to be locked has root page iTab and is found in database iDb.
  93429. ** A read or a write lock can be taken depending on isWritelock.
  93430. **
  93431. ** This routine just records the fact that the lock is desired. The
  93432. ** code to make the lock occur is generated by a later call to
  93433. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  93434. */
  93435. SQLITE_PRIVATE void sqlite3TableLock(
  93436. Parse *pParse, /* Parsing context */
  93437. int iDb, /* Index of the database containing the table to lock */
  93438. int iTab, /* Root page number of the table to be locked */
  93439. u8 isWriteLock, /* True for a write lock */
  93440. const char *zName /* Name of the table to be locked */
  93441. ){
  93442. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  93443. int i;
  93444. int nBytes;
  93445. TableLock *p;
  93446. assert( iDb>=0 );
  93447. if( iDb==1 ) return;
  93448. if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
  93449. for(i=0; i<pToplevel->nTableLock; i++){
  93450. p = &pToplevel->aTableLock[i];
  93451. if( p->iDb==iDb && p->iTab==iTab ){
  93452. p->isWriteLock = (p->isWriteLock || isWriteLock);
  93453. return;
  93454. }
  93455. }
  93456. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  93457. pToplevel->aTableLock =
  93458. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  93459. if( pToplevel->aTableLock ){
  93460. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  93461. p->iDb = iDb;
  93462. p->iTab = iTab;
  93463. p->isWriteLock = isWriteLock;
  93464. p->zLockName = zName;
  93465. }else{
  93466. pToplevel->nTableLock = 0;
  93467. sqlite3OomFault(pToplevel->db);
  93468. }
  93469. }
  93470. /*
  93471. ** Code an OP_TableLock instruction for each table locked by the
  93472. ** statement (configured by calls to sqlite3TableLock()).
  93473. */
  93474. static void codeTableLocks(Parse *pParse){
  93475. int i;
  93476. Vdbe *pVdbe;
  93477. pVdbe = sqlite3GetVdbe(pParse);
  93478. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  93479. for(i=0; i<pParse->nTableLock; i++){
  93480. TableLock *p = &pParse->aTableLock[i];
  93481. int p1 = p->iDb;
  93482. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  93483. p->zLockName, P4_STATIC);
  93484. }
  93485. }
  93486. #else
  93487. #define codeTableLocks(x)
  93488. #endif
  93489. /*
  93490. ** Return TRUE if the given yDbMask object is empty - if it contains no
  93491. ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
  93492. ** macros when SQLITE_MAX_ATTACHED is greater than 30.
  93493. */
  93494. #if SQLITE_MAX_ATTACHED>30
  93495. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
  93496. int i;
  93497. for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
  93498. return 1;
  93499. }
  93500. #endif
  93501. /*
  93502. ** This routine is called after a single SQL statement has been
  93503. ** parsed and a VDBE program to execute that statement has been
  93504. ** prepared. This routine puts the finishing touches on the
  93505. ** VDBE program and resets the pParse structure for the next
  93506. ** parse.
  93507. **
  93508. ** Note that if an error occurred, it might be the case that
  93509. ** no VDBE code was generated.
  93510. */
  93511. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  93512. sqlite3 *db;
  93513. Vdbe *v;
  93514. assert( pParse->pToplevel==0 );
  93515. db = pParse->db;
  93516. if( pParse->nested ) return;
  93517. if( db->mallocFailed || pParse->nErr ){
  93518. if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
  93519. return;
  93520. }
  93521. /* Begin by generating some termination code at the end of the
  93522. ** vdbe program
  93523. */
  93524. v = sqlite3GetVdbe(pParse);
  93525. assert( !pParse->isMultiWrite
  93526. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  93527. if( v ){
  93528. sqlite3VdbeAddOp0(v, OP_Halt);
  93529. #if SQLITE_USER_AUTHENTICATION
  93530. if( pParse->nTableLock>0 && db->init.busy==0 ){
  93531. sqlite3UserAuthInit(db);
  93532. if( db->auth.authLevel<UAUTH_User ){
  93533. sqlite3ErrorMsg(pParse, "user not authenticated");
  93534. pParse->rc = SQLITE_AUTH_USER;
  93535. return;
  93536. }
  93537. }
  93538. #endif
  93539. /* The cookie mask contains one bit for each database file open.
  93540. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  93541. ** set for each database that is used. Generate code to start a
  93542. ** transaction on each used database and to verify the schema cookie
  93543. ** on each used database.
  93544. */
  93545. if( db->mallocFailed==0
  93546. && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
  93547. ){
  93548. int iDb, i;
  93549. assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
  93550. sqlite3VdbeJumpHere(v, 0);
  93551. for(iDb=0; iDb<db->nDb; iDb++){
  93552. Schema *pSchema;
  93553. if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
  93554. sqlite3VdbeUsesBtree(v, iDb);
  93555. pSchema = db->aDb[iDb].pSchema;
  93556. sqlite3VdbeAddOp4Int(v,
  93557. OP_Transaction, /* Opcode */
  93558. iDb, /* P1 */
  93559. DbMaskTest(pParse->writeMask,iDb), /* P2 */
  93560. pSchema->schema_cookie, /* P3 */
  93561. pSchema->iGeneration /* P4 */
  93562. );
  93563. if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
  93564. VdbeComment((v,
  93565. "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
  93566. }
  93567. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93568. for(i=0; i<pParse->nVtabLock; i++){
  93569. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  93570. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  93571. }
  93572. pParse->nVtabLock = 0;
  93573. #endif
  93574. /* Once all the cookies have been verified and transactions opened,
  93575. ** obtain the required table-locks. This is a no-op unless the
  93576. ** shared-cache feature is enabled.
  93577. */
  93578. codeTableLocks(pParse);
  93579. /* Initialize any AUTOINCREMENT data structures required.
  93580. */
  93581. sqlite3AutoincrementBegin(pParse);
  93582. /* Code constant expressions that where factored out of inner loops */
  93583. if( pParse->pConstExpr ){
  93584. ExprList *pEL = pParse->pConstExpr;
  93585. pParse->okConstFactor = 0;
  93586. for(i=0; i<pEL->nExpr; i++){
  93587. sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
  93588. }
  93589. }
  93590. /* Finally, jump back to the beginning of the executable code. */
  93591. sqlite3VdbeGoto(v, 1);
  93592. }
  93593. }
  93594. /* Get the VDBE program ready for execution
  93595. */
  93596. if( v && pParse->nErr==0 && !db->mallocFailed ){
  93597. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  93598. /* A minimum of one cursor is required if autoincrement is used
  93599. * See ticket [a696379c1f08866] */
  93600. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  93601. sqlite3VdbeMakeReady(v, pParse);
  93602. pParse->rc = SQLITE_DONE;
  93603. }else{
  93604. pParse->rc = SQLITE_ERROR;
  93605. }
  93606. }
  93607. /*
  93608. ** Run the parser and code generator recursively in order to generate
  93609. ** code for the SQL statement given onto the end of the pParse context
  93610. ** currently under construction. When the parser is run recursively
  93611. ** this way, the final OP_Halt is not appended and other initialization
  93612. ** and finalization steps are omitted because those are handling by the
  93613. ** outermost parser.
  93614. **
  93615. ** Not everything is nestable. This facility is designed to permit
  93616. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  93617. ** care if you decide to try to use this routine for some other purposes.
  93618. */
  93619. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  93620. va_list ap;
  93621. char *zSql;
  93622. char *zErrMsg = 0;
  93623. sqlite3 *db = pParse->db;
  93624. char saveBuf[PARSE_TAIL_SZ];
  93625. if( pParse->nErr ) return;
  93626. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  93627. va_start(ap, zFormat);
  93628. zSql = sqlite3VMPrintf(db, zFormat, ap);
  93629. va_end(ap);
  93630. if( zSql==0 ){
  93631. return; /* A malloc must have failed */
  93632. }
  93633. pParse->nested++;
  93634. memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
  93635. memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
  93636. sqlite3RunParser(pParse, zSql, &zErrMsg);
  93637. sqlite3DbFree(db, zErrMsg);
  93638. sqlite3DbFree(db, zSql);
  93639. memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
  93640. pParse->nested--;
  93641. }
  93642. #if SQLITE_USER_AUTHENTICATION
  93643. /*
  93644. ** Return TRUE if zTable is the name of the system table that stores the
  93645. ** list of users and their access credentials.
  93646. */
  93647. SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
  93648. return sqlite3_stricmp(zTable, "sqlite_user")==0;
  93649. }
  93650. #endif
  93651. /*
  93652. ** Locate the in-memory structure that describes a particular database
  93653. ** table given the name of that table and (optionally) the name of the
  93654. ** database containing the table. Return NULL if not found.
  93655. **
  93656. ** If zDatabase is 0, all databases are searched for the table and the
  93657. ** first matching table is returned. (No checking for duplicate table
  93658. ** names is done.) The search order is TEMP first, then MAIN, then any
  93659. ** auxiliary databases added using the ATTACH command.
  93660. **
  93661. ** See also sqlite3LocateTable().
  93662. */
  93663. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  93664. Table *p = 0;
  93665. int i;
  93666. /* All mutexes are required for schema access. Make sure we hold them. */
  93667. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  93668. #if SQLITE_USER_AUTHENTICATION
  93669. /* Only the admin user is allowed to know that the sqlite_user table
  93670. ** exists */
  93671. if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
  93672. return 0;
  93673. }
  93674. #endif
  93675. while(1){
  93676. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  93677. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  93678. if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
  93679. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  93680. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
  93681. if( p ) return p;
  93682. }
  93683. }
  93684. /* Not found. If the name we were looking for was temp.sqlite_master
  93685. ** then change the name to sqlite_temp_master and try again. */
  93686. if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
  93687. if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
  93688. zName = TEMP_MASTER_NAME;
  93689. }
  93690. return 0;
  93691. }
  93692. /*
  93693. ** Locate the in-memory structure that describes a particular database
  93694. ** table given the name of that table and (optionally) the name of the
  93695. ** database containing the table. Return NULL if not found. Also leave an
  93696. ** error message in pParse->zErrMsg.
  93697. **
  93698. ** The difference between this routine and sqlite3FindTable() is that this
  93699. ** routine leaves an error message in pParse->zErrMsg where
  93700. ** sqlite3FindTable() does not.
  93701. */
  93702. SQLITE_PRIVATE Table *sqlite3LocateTable(
  93703. Parse *pParse, /* context in which to report errors */
  93704. u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
  93705. const char *zName, /* Name of the table we are looking for */
  93706. const char *zDbase /* Name of the database. Might be NULL */
  93707. ){
  93708. Table *p;
  93709. /* Read the database schema. If an error occurs, leave an error message
  93710. ** and code in pParse and return NULL. */
  93711. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  93712. return 0;
  93713. }
  93714. p = sqlite3FindTable(pParse->db, zName, zDbase);
  93715. if( p==0 ){
  93716. const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
  93717. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93718. if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
  93719. /* If zName is the not the name of a table in the schema created using
  93720. ** CREATE, then check to see if it is the name of an virtual table that
  93721. ** can be an eponymous virtual table. */
  93722. Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
  93723. if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
  93724. pMod = sqlite3PragmaVtabRegister(pParse->db, zName);
  93725. }
  93726. if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
  93727. return pMod->pEpoTab;
  93728. }
  93729. }
  93730. #endif
  93731. if( (flags & LOCATE_NOERR)==0 ){
  93732. if( zDbase ){
  93733. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  93734. }else{
  93735. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  93736. }
  93737. pParse->checkSchema = 1;
  93738. }
  93739. }
  93740. return p;
  93741. }
  93742. /*
  93743. ** Locate the table identified by *p.
  93744. **
  93745. ** This is a wrapper around sqlite3LocateTable(). The difference between
  93746. ** sqlite3LocateTable() and this function is that this function restricts
  93747. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  93748. ** non-NULL if it is part of a view or trigger program definition. See
  93749. ** sqlite3FixSrcList() for details.
  93750. */
  93751. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  93752. Parse *pParse,
  93753. u32 flags,
  93754. struct SrcList_item *p
  93755. ){
  93756. const char *zDb;
  93757. assert( p->pSchema==0 || p->zDatabase==0 );
  93758. if( p->pSchema ){
  93759. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  93760. zDb = pParse->db->aDb[iDb].zDbSName;
  93761. }else{
  93762. zDb = p->zDatabase;
  93763. }
  93764. return sqlite3LocateTable(pParse, flags, p->zName, zDb);
  93765. }
  93766. /*
  93767. ** Locate the in-memory structure that describes
  93768. ** a particular index given the name of that index
  93769. ** and the name of the database that contains the index.
  93770. ** Return NULL if not found.
  93771. **
  93772. ** If zDatabase is 0, all databases are searched for the
  93773. ** table and the first matching index is returned. (No checking
  93774. ** for duplicate index names is done.) The search order is
  93775. ** TEMP first, then MAIN, then any auxiliary databases added
  93776. ** using the ATTACH command.
  93777. */
  93778. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  93779. Index *p = 0;
  93780. int i;
  93781. /* All mutexes are required for schema access. Make sure we hold them. */
  93782. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  93783. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  93784. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  93785. Schema *pSchema = db->aDb[j].pSchema;
  93786. assert( pSchema );
  93787. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
  93788. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  93789. p = sqlite3HashFind(&pSchema->idxHash, zName);
  93790. if( p ) break;
  93791. }
  93792. return p;
  93793. }
  93794. /*
  93795. ** Reclaim the memory used by an index
  93796. */
  93797. static void freeIndex(sqlite3 *db, Index *p){
  93798. #ifndef SQLITE_OMIT_ANALYZE
  93799. sqlite3DeleteIndexSamples(db, p);
  93800. #endif
  93801. sqlite3ExprDelete(db, p->pPartIdxWhere);
  93802. sqlite3ExprListDelete(db, p->aColExpr);
  93803. sqlite3DbFree(db, p->zColAff);
  93804. if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
  93805. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  93806. sqlite3_free(p->aiRowEst);
  93807. #endif
  93808. sqlite3DbFree(db, p);
  93809. }
  93810. /*
  93811. ** For the index called zIdxName which is found in the database iDb,
  93812. ** unlike that index from its Table then remove the index from
  93813. ** the index hash table and free all memory structures associated
  93814. ** with the index.
  93815. */
  93816. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  93817. Index *pIndex;
  93818. Hash *pHash;
  93819. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  93820. pHash = &db->aDb[iDb].pSchema->idxHash;
  93821. pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
  93822. if( ALWAYS(pIndex) ){
  93823. if( pIndex->pTable->pIndex==pIndex ){
  93824. pIndex->pTable->pIndex = pIndex->pNext;
  93825. }else{
  93826. Index *p;
  93827. /* Justification of ALWAYS(); The index must be on the list of
  93828. ** indices. */
  93829. p = pIndex->pTable->pIndex;
  93830. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  93831. if( ALWAYS(p && p->pNext==pIndex) ){
  93832. p->pNext = pIndex->pNext;
  93833. }
  93834. }
  93835. freeIndex(db, pIndex);
  93836. }
  93837. db->flags |= SQLITE_InternChanges;
  93838. }
  93839. /*
  93840. ** Look through the list of open database files in db->aDb[] and if
  93841. ** any have been closed, remove them from the list. Reallocate the
  93842. ** db->aDb[] structure to a smaller size, if possible.
  93843. **
  93844. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  93845. ** are never candidates for being collapsed.
  93846. */
  93847. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  93848. int i, j;
  93849. for(i=j=2; i<db->nDb; i++){
  93850. struct Db *pDb = &db->aDb[i];
  93851. if( pDb->pBt==0 ){
  93852. sqlite3DbFree(db, pDb->zDbSName);
  93853. pDb->zDbSName = 0;
  93854. continue;
  93855. }
  93856. if( j<i ){
  93857. db->aDb[j] = db->aDb[i];
  93858. }
  93859. j++;
  93860. }
  93861. db->nDb = j;
  93862. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  93863. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  93864. sqlite3DbFree(db, db->aDb);
  93865. db->aDb = db->aDbStatic;
  93866. }
  93867. }
  93868. /*
  93869. ** Reset the schema for the database at index iDb. Also reset the
  93870. ** TEMP schema.
  93871. */
  93872. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  93873. Db *pDb;
  93874. assert( iDb<db->nDb );
  93875. /* Case 1: Reset the single schema identified by iDb */
  93876. pDb = &db->aDb[iDb];
  93877. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  93878. assert( pDb->pSchema!=0 );
  93879. sqlite3SchemaClear(pDb->pSchema);
  93880. /* If any database other than TEMP is reset, then also reset TEMP
  93881. ** since TEMP might be holding triggers that reference tables in the
  93882. ** other database.
  93883. */
  93884. if( iDb!=1 ){
  93885. pDb = &db->aDb[1];
  93886. assert( pDb->pSchema!=0 );
  93887. sqlite3SchemaClear(pDb->pSchema);
  93888. }
  93889. return;
  93890. }
  93891. /*
  93892. ** Erase all schema information from all attached databases (including
  93893. ** "main" and "temp") for a single database connection.
  93894. */
  93895. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  93896. int i;
  93897. sqlite3BtreeEnterAll(db);
  93898. for(i=0; i<db->nDb; i++){
  93899. Db *pDb = &db->aDb[i];
  93900. if( pDb->pSchema ){
  93901. sqlite3SchemaClear(pDb->pSchema);
  93902. }
  93903. }
  93904. db->flags &= ~SQLITE_InternChanges;
  93905. sqlite3VtabUnlockList(db);
  93906. sqlite3BtreeLeaveAll(db);
  93907. sqlite3CollapseDatabaseArray(db);
  93908. }
  93909. /*
  93910. ** This routine is called when a commit occurs.
  93911. */
  93912. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  93913. db->flags &= ~SQLITE_InternChanges;
  93914. }
  93915. /*
  93916. ** Delete memory allocated for the column names of a table or view (the
  93917. ** Table.aCol[] array).
  93918. */
  93919. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
  93920. int i;
  93921. Column *pCol;
  93922. assert( pTable!=0 );
  93923. if( (pCol = pTable->aCol)!=0 ){
  93924. for(i=0; i<pTable->nCol; i++, pCol++){
  93925. sqlite3DbFree(db, pCol->zName);
  93926. sqlite3ExprDelete(db, pCol->pDflt);
  93927. sqlite3DbFree(db, pCol->zColl);
  93928. }
  93929. sqlite3DbFree(db, pTable->aCol);
  93930. }
  93931. }
  93932. /*
  93933. ** Remove the memory data structures associated with the given
  93934. ** Table. No changes are made to disk by this routine.
  93935. **
  93936. ** This routine just deletes the data structure. It does not unlink
  93937. ** the table data structure from the hash table. But it does destroy
  93938. ** memory structures of the indices and foreign keys associated with
  93939. ** the table.
  93940. **
  93941. ** The db parameter is optional. It is needed if the Table object
  93942. ** contains lookaside memory. (Table objects in the schema do not use
  93943. ** lookaside memory, but some ephemeral Table objects do.) Or the
  93944. ** db parameter can be used with db->pnBytesFreed to measure the memory
  93945. ** used by the Table object.
  93946. */
  93947. static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
  93948. Index *pIndex, *pNext;
  93949. TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
  93950. /* Record the number of outstanding lookaside allocations in schema Tables
  93951. ** prior to doing any free() operations. Since schema Tables do not use
  93952. ** lookaside, this number should not change. */
  93953. TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
  93954. db->lookaside.nOut : 0 );
  93955. /* Delete all indices associated with this table. */
  93956. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  93957. pNext = pIndex->pNext;
  93958. assert( pIndex->pSchema==pTable->pSchema
  93959. || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
  93960. if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
  93961. char *zName = pIndex->zName;
  93962. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  93963. &pIndex->pSchema->idxHash, zName, 0
  93964. );
  93965. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  93966. assert( pOld==pIndex || pOld==0 );
  93967. }
  93968. freeIndex(db, pIndex);
  93969. }
  93970. /* Delete any foreign keys attached to this table. */
  93971. sqlite3FkDelete(db, pTable);
  93972. /* Delete the Table structure itself.
  93973. */
  93974. sqlite3DeleteColumnNames(db, pTable);
  93975. sqlite3DbFree(db, pTable->zName);
  93976. sqlite3DbFree(db, pTable->zColAff);
  93977. sqlite3SelectDelete(db, pTable->pSelect);
  93978. sqlite3ExprListDelete(db, pTable->pCheck);
  93979. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93980. sqlite3VtabClear(db, pTable);
  93981. #endif
  93982. sqlite3DbFree(db, pTable);
  93983. /* Verify that no lookaside memory was used by schema tables */
  93984. assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
  93985. }
  93986. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  93987. /* Do not delete the table until the reference count reaches zero. */
  93988. if( !pTable ) return;
  93989. if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
  93990. deleteTable(db, pTable);
  93991. }
  93992. /*
  93993. ** Unlink the given table from the hash tables and the delete the
  93994. ** table structure with all its indices and foreign keys.
  93995. */
  93996. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  93997. Table *p;
  93998. Db *pDb;
  93999. assert( db!=0 );
  94000. assert( iDb>=0 && iDb<db->nDb );
  94001. assert( zTabName );
  94002. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  94003. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  94004. pDb = &db->aDb[iDb];
  94005. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
  94006. sqlite3DeleteTable(db, p);
  94007. db->flags |= SQLITE_InternChanges;
  94008. }
  94009. /*
  94010. ** Given a token, return a string that consists of the text of that
  94011. ** token. Space to hold the returned string
  94012. ** is obtained from sqliteMalloc() and must be freed by the calling
  94013. ** function.
  94014. **
  94015. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  94016. ** surround the body of the token are removed.
  94017. **
  94018. ** Tokens are often just pointers into the original SQL text and so
  94019. ** are not \000 terminated and are not persistent. The returned string
  94020. ** is \000 terminated and is persistent.
  94021. */
  94022. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  94023. char *zName;
  94024. if( pName ){
  94025. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  94026. sqlite3Dequote(zName);
  94027. }else{
  94028. zName = 0;
  94029. }
  94030. return zName;
  94031. }
  94032. /*
  94033. ** Open the sqlite_master table stored in database number iDb for
  94034. ** writing. The table is opened using cursor 0.
  94035. */
  94036. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  94037. Vdbe *v = sqlite3GetVdbe(p);
  94038. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
  94039. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
  94040. if( p->nTab==0 ){
  94041. p->nTab = 1;
  94042. }
  94043. }
  94044. /*
  94045. ** Parameter zName points to a nul-terminated buffer containing the name
  94046. ** of a database ("main", "temp" or the name of an attached db). This
  94047. ** function returns the index of the named database in db->aDb[], or
  94048. ** -1 if the named db cannot be found.
  94049. */
  94050. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  94051. int i = -1; /* Database number */
  94052. if( zName ){
  94053. Db *pDb;
  94054. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  94055. if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
  94056. /* "main" is always an acceptable alias for the primary database
  94057. ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
  94058. if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
  94059. }
  94060. }
  94061. return i;
  94062. }
  94063. /*
  94064. ** The token *pName contains the name of a database (either "main" or
  94065. ** "temp" or the name of an attached db). This routine returns the
  94066. ** index of the named database in db->aDb[], or -1 if the named db
  94067. ** does not exist.
  94068. */
  94069. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  94070. int i; /* Database number */
  94071. char *zName; /* Name we are searching for */
  94072. zName = sqlite3NameFromToken(db, pName);
  94073. i = sqlite3FindDbName(db, zName);
  94074. sqlite3DbFree(db, zName);
  94075. return i;
  94076. }
  94077. /* The table or view or trigger name is passed to this routine via tokens
  94078. ** pName1 and pName2. If the table name was fully qualified, for example:
  94079. **
  94080. ** CREATE TABLE xxx.yyy (...);
  94081. **
  94082. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  94083. ** the table name is not fully qualified, i.e.:
  94084. **
  94085. ** CREATE TABLE yyy(...);
  94086. **
  94087. ** Then pName1 is set to "yyy" and pName2 is "".
  94088. **
  94089. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  94090. ** pName2) that stores the unqualified table name. The index of the
  94091. ** database "xxx" is returned.
  94092. */
  94093. SQLITE_PRIVATE int sqlite3TwoPartName(
  94094. Parse *pParse, /* Parsing and code generating context */
  94095. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  94096. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  94097. Token **pUnqual /* Write the unqualified object name here */
  94098. ){
  94099. int iDb; /* Database holding the object */
  94100. sqlite3 *db = pParse->db;
  94101. assert( pName2!=0 );
  94102. if( pName2->n>0 ){
  94103. if( db->init.busy ) {
  94104. sqlite3ErrorMsg(pParse, "corrupt database");
  94105. return -1;
  94106. }
  94107. *pUnqual = pName2;
  94108. iDb = sqlite3FindDb(db, pName1);
  94109. if( iDb<0 ){
  94110. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  94111. return -1;
  94112. }
  94113. }else{
  94114. assert( db->init.iDb==0 || db->init.busy || (db->flags & SQLITE_Vacuum)!=0);
  94115. iDb = db->init.iDb;
  94116. *pUnqual = pName1;
  94117. }
  94118. return iDb;
  94119. }
  94120. /*
  94121. ** This routine is used to check if the UTF-8 string zName is a legal
  94122. ** unqualified name for a new schema object (table, index, view or
  94123. ** trigger). All names are legal except those that begin with the string
  94124. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  94125. ** is reserved for internal use.
  94126. */
  94127. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  94128. if( !pParse->db->init.busy && pParse->nested==0
  94129. && (pParse->db->flags & SQLITE_WriteSchema)==0
  94130. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  94131. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  94132. return SQLITE_ERROR;
  94133. }
  94134. return SQLITE_OK;
  94135. }
  94136. /*
  94137. ** Return the PRIMARY KEY index of a table
  94138. */
  94139. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
  94140. Index *p;
  94141. for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
  94142. return p;
  94143. }
  94144. /*
  94145. ** Return the column of index pIdx that corresponds to table
  94146. ** column iCol. Return -1 if not found.
  94147. */
  94148. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
  94149. int i;
  94150. for(i=0; i<pIdx->nColumn; i++){
  94151. if( iCol==pIdx->aiColumn[i] ) return i;
  94152. }
  94153. return -1;
  94154. }
  94155. /*
  94156. ** Begin constructing a new table representation in memory. This is
  94157. ** the first of several action routines that get called in response
  94158. ** to a CREATE TABLE statement. In particular, this routine is called
  94159. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  94160. ** flag is true if the table should be stored in the auxiliary database
  94161. ** file instead of in the main database file. This is normally the case
  94162. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  94163. ** CREATE and TABLE.
  94164. **
  94165. ** The new table record is initialized and put in pParse->pNewTable.
  94166. ** As more of the CREATE TABLE statement is parsed, additional action
  94167. ** routines will be called to add more information to this record.
  94168. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  94169. ** is called to complete the construction of the new table record.
  94170. */
  94171. SQLITE_PRIVATE void sqlite3StartTable(
  94172. Parse *pParse, /* Parser context */
  94173. Token *pName1, /* First part of the name of the table or view */
  94174. Token *pName2, /* Second part of the name of the table or view */
  94175. int isTemp, /* True if this is a TEMP table */
  94176. int isView, /* True if this is a VIEW */
  94177. int isVirtual, /* True if this is a VIRTUAL table */
  94178. int noErr /* Do nothing if table already exists */
  94179. ){
  94180. Table *pTable;
  94181. char *zName = 0; /* The name of the new table */
  94182. sqlite3 *db = pParse->db;
  94183. Vdbe *v;
  94184. int iDb; /* Database number to create the table in */
  94185. Token *pName; /* Unqualified name of the table to create */
  94186. if( db->init.busy && db->init.newTnum==1 ){
  94187. /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
  94188. iDb = db->init.iDb;
  94189. zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
  94190. pName = pName1;
  94191. }else{
  94192. /* The common case */
  94193. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  94194. if( iDb<0 ) return;
  94195. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  94196. /* If creating a temp table, the name may not be qualified. Unless
  94197. ** the database name is "temp" anyway. */
  94198. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  94199. return;
  94200. }
  94201. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  94202. zName = sqlite3NameFromToken(db, pName);
  94203. }
  94204. pParse->sNameToken = *pName;
  94205. if( zName==0 ) return;
  94206. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  94207. goto begin_table_error;
  94208. }
  94209. if( db->init.iDb==1 ) isTemp = 1;
  94210. #ifndef SQLITE_OMIT_AUTHORIZATION
  94211. assert( isTemp==0 || isTemp==1 );
  94212. assert( isView==0 || isView==1 );
  94213. {
  94214. static const u8 aCode[] = {
  94215. SQLITE_CREATE_TABLE,
  94216. SQLITE_CREATE_TEMP_TABLE,
  94217. SQLITE_CREATE_VIEW,
  94218. SQLITE_CREATE_TEMP_VIEW
  94219. };
  94220. char *zDb = db->aDb[iDb].zDbSName;
  94221. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  94222. goto begin_table_error;
  94223. }
  94224. if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
  94225. zName, 0, zDb) ){
  94226. goto begin_table_error;
  94227. }
  94228. }
  94229. #endif
  94230. /* Make sure the new table name does not collide with an existing
  94231. ** index or table name in the same database. Issue an error message if
  94232. ** it does. The exception is if the statement being parsed was passed
  94233. ** to an sqlite3_declare_vtab() call. In that case only the column names
  94234. ** and types will be used, so there is no need to test for namespace
  94235. ** collisions.
  94236. */
  94237. if( !IN_DECLARE_VTAB ){
  94238. char *zDb = db->aDb[iDb].zDbSName;
  94239. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  94240. goto begin_table_error;
  94241. }
  94242. pTable = sqlite3FindTable(db, zName, zDb);
  94243. if( pTable ){
  94244. if( !noErr ){
  94245. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  94246. }else{
  94247. assert( !db->init.busy || CORRUPT_DB );
  94248. sqlite3CodeVerifySchema(pParse, iDb);
  94249. }
  94250. goto begin_table_error;
  94251. }
  94252. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  94253. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  94254. goto begin_table_error;
  94255. }
  94256. }
  94257. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  94258. if( pTable==0 ){
  94259. assert( db->mallocFailed );
  94260. pParse->rc = SQLITE_NOMEM_BKPT;
  94261. pParse->nErr++;
  94262. goto begin_table_error;
  94263. }
  94264. pTable->zName = zName;
  94265. pTable->iPKey = -1;
  94266. pTable->pSchema = db->aDb[iDb].pSchema;
  94267. pTable->nTabRef = 1;
  94268. pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  94269. assert( pParse->pNewTable==0 );
  94270. pParse->pNewTable = pTable;
  94271. /* If this is the magic sqlite_sequence table used by autoincrement,
  94272. ** then record a pointer to this table in the main database structure
  94273. ** so that INSERT can find the table easily.
  94274. */
  94275. #ifndef SQLITE_OMIT_AUTOINCREMENT
  94276. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  94277. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  94278. pTable->pSchema->pSeqTab = pTable;
  94279. }
  94280. #endif
  94281. /* Begin generating the code that will insert the table record into
  94282. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  94283. ** and allocate the record number for the table entry now. Before any
  94284. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  94285. ** indices to be created and the table record must come before the
  94286. ** indices. Hence, the record number for the table must be allocated
  94287. ** now.
  94288. */
  94289. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  94290. int addr1;
  94291. int fileFormat;
  94292. int reg1, reg2, reg3;
  94293. /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
  94294. static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
  94295. sqlite3BeginWriteOperation(pParse, 1, iDb);
  94296. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94297. if( isVirtual ){
  94298. sqlite3VdbeAddOp0(v, OP_VBegin);
  94299. }
  94300. #endif
  94301. /* If the file format and encoding in the database have not been set,
  94302. ** set them now.
  94303. */
  94304. reg1 = pParse->regRowid = ++pParse->nMem;
  94305. reg2 = pParse->regRoot = ++pParse->nMem;
  94306. reg3 = ++pParse->nMem;
  94307. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  94308. sqlite3VdbeUsesBtree(v, iDb);
  94309. addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
  94310. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  94311. 1 : SQLITE_MAX_FILE_FORMAT;
  94312. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
  94313. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
  94314. sqlite3VdbeJumpHere(v, addr1);
  94315. /* This just creates a place-holder record in the sqlite_master table.
  94316. ** The record created does not contain anything yet. It will be replaced
  94317. ** by the real entry in code generated at sqlite3EndTable().
  94318. **
  94319. ** The rowid for the new entry is left in register pParse->regRowid.
  94320. ** The root page number of the new table is left in reg pParse->regRoot.
  94321. ** The rowid and root page number values are needed by the code that
  94322. ** sqlite3EndTable will generate.
  94323. */
  94324. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  94325. if( isView || isVirtual ){
  94326. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  94327. }else
  94328. #endif
  94329. {
  94330. pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  94331. }
  94332. sqlite3OpenMasterTable(pParse, iDb);
  94333. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  94334. sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
  94335. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  94336. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  94337. sqlite3VdbeAddOp0(v, OP_Close);
  94338. }
  94339. /* Normal (non-error) return. */
  94340. return;
  94341. /* If an error occurs, we jump here */
  94342. begin_table_error:
  94343. sqlite3DbFree(db, zName);
  94344. return;
  94345. }
  94346. /* Set properties of a table column based on the (magical)
  94347. ** name of the column.
  94348. */
  94349. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  94350. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
  94351. if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
  94352. pCol->colFlags |= COLFLAG_HIDDEN;
  94353. }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
  94354. pTab->tabFlags |= TF_OOOHidden;
  94355. }
  94356. }
  94357. #endif
  94358. /*
  94359. ** Add a new column to the table currently being constructed.
  94360. **
  94361. ** The parser calls this routine once for each column declaration
  94362. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  94363. ** first to get things going. Then this routine is called for each
  94364. ** column.
  94365. */
  94366. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
  94367. Table *p;
  94368. int i;
  94369. char *z;
  94370. char *zType;
  94371. Column *pCol;
  94372. sqlite3 *db = pParse->db;
  94373. if( (p = pParse->pNewTable)==0 ) return;
  94374. #if SQLITE_MAX_COLUMN
  94375. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  94376. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  94377. return;
  94378. }
  94379. #endif
  94380. z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
  94381. if( z==0 ) return;
  94382. memcpy(z, pName->z, pName->n);
  94383. z[pName->n] = 0;
  94384. sqlite3Dequote(z);
  94385. for(i=0; i<p->nCol; i++){
  94386. if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
  94387. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  94388. sqlite3DbFree(db, z);
  94389. return;
  94390. }
  94391. }
  94392. if( (p->nCol & 0x7)==0 ){
  94393. Column *aNew;
  94394. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  94395. if( aNew==0 ){
  94396. sqlite3DbFree(db, z);
  94397. return;
  94398. }
  94399. p->aCol = aNew;
  94400. }
  94401. pCol = &p->aCol[p->nCol];
  94402. memset(pCol, 0, sizeof(p->aCol[0]));
  94403. pCol->zName = z;
  94404. sqlite3ColumnPropertiesFromName(p, pCol);
  94405. if( pType->n==0 ){
  94406. /* If there is no type specified, columns have the default affinity
  94407. ** 'BLOB'. */
  94408. pCol->affinity = SQLITE_AFF_BLOB;
  94409. pCol->szEst = 1;
  94410. }else{
  94411. zType = z + sqlite3Strlen30(z) + 1;
  94412. memcpy(zType, pType->z, pType->n);
  94413. zType[pType->n] = 0;
  94414. sqlite3Dequote(zType);
  94415. pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
  94416. pCol->colFlags |= COLFLAG_HASTYPE;
  94417. }
  94418. p->nCol++;
  94419. pParse->constraintName.n = 0;
  94420. }
  94421. /*
  94422. ** This routine is called by the parser while in the middle of
  94423. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  94424. ** been seen on a column. This routine sets the notNull flag on
  94425. ** the column currently under construction.
  94426. */
  94427. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  94428. Table *p;
  94429. p = pParse->pNewTable;
  94430. if( p==0 || NEVER(p->nCol<1) ) return;
  94431. p->aCol[p->nCol-1].notNull = (u8)onError;
  94432. p->tabFlags |= TF_HasNotNull;
  94433. }
  94434. /*
  94435. ** Scan the column type name zType (length nType) and return the
  94436. ** associated affinity type.
  94437. **
  94438. ** This routine does a case-independent search of zType for the
  94439. ** substrings in the following table. If one of the substrings is
  94440. ** found, the corresponding affinity is returned. If zType contains
  94441. ** more than one of the substrings, entries toward the top of
  94442. ** the table take priority. For example, if zType is 'BLOBINT',
  94443. ** SQLITE_AFF_INTEGER is returned.
  94444. **
  94445. ** Substring | Affinity
  94446. ** --------------------------------
  94447. ** 'INT' | SQLITE_AFF_INTEGER
  94448. ** 'CHAR' | SQLITE_AFF_TEXT
  94449. ** 'CLOB' | SQLITE_AFF_TEXT
  94450. ** 'TEXT' | SQLITE_AFF_TEXT
  94451. ** 'BLOB' | SQLITE_AFF_BLOB
  94452. ** 'REAL' | SQLITE_AFF_REAL
  94453. ** 'FLOA' | SQLITE_AFF_REAL
  94454. ** 'DOUB' | SQLITE_AFF_REAL
  94455. **
  94456. ** If none of the substrings in the above table are found,
  94457. ** SQLITE_AFF_NUMERIC is returned.
  94458. */
  94459. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
  94460. u32 h = 0;
  94461. char aff = SQLITE_AFF_NUMERIC;
  94462. const char *zChar = 0;
  94463. assert( zIn!=0 );
  94464. while( zIn[0] ){
  94465. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  94466. zIn++;
  94467. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  94468. aff = SQLITE_AFF_TEXT;
  94469. zChar = zIn;
  94470. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  94471. aff = SQLITE_AFF_TEXT;
  94472. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  94473. aff = SQLITE_AFF_TEXT;
  94474. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  94475. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  94476. aff = SQLITE_AFF_BLOB;
  94477. if( zIn[0]=='(' ) zChar = zIn;
  94478. #ifndef SQLITE_OMIT_FLOATING_POINT
  94479. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  94480. && aff==SQLITE_AFF_NUMERIC ){
  94481. aff = SQLITE_AFF_REAL;
  94482. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  94483. && aff==SQLITE_AFF_NUMERIC ){
  94484. aff = SQLITE_AFF_REAL;
  94485. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  94486. && aff==SQLITE_AFF_NUMERIC ){
  94487. aff = SQLITE_AFF_REAL;
  94488. #endif
  94489. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  94490. aff = SQLITE_AFF_INTEGER;
  94491. break;
  94492. }
  94493. }
  94494. /* If pszEst is not NULL, store an estimate of the field size. The
  94495. ** estimate is scaled so that the size of an integer is 1. */
  94496. if( pszEst ){
  94497. *pszEst = 1; /* default size is approx 4 bytes */
  94498. if( aff<SQLITE_AFF_NUMERIC ){
  94499. if( zChar ){
  94500. while( zChar[0] ){
  94501. if( sqlite3Isdigit(zChar[0]) ){
  94502. int v = 0;
  94503. sqlite3GetInt32(zChar, &v);
  94504. v = v/4 + 1;
  94505. if( v>255 ) v = 255;
  94506. *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  94507. break;
  94508. }
  94509. zChar++;
  94510. }
  94511. }else{
  94512. *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  94513. }
  94514. }
  94515. }
  94516. return aff;
  94517. }
  94518. /*
  94519. ** The expression is the default value for the most recently added column
  94520. ** of the table currently under construction.
  94521. **
  94522. ** Default value expressions must be constant. Raise an exception if this
  94523. ** is not the case.
  94524. **
  94525. ** This routine is called by the parser while in the middle of
  94526. ** parsing a CREATE TABLE statement.
  94527. */
  94528. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  94529. Table *p;
  94530. Column *pCol;
  94531. sqlite3 *db = pParse->db;
  94532. p = pParse->pNewTable;
  94533. if( p!=0 ){
  94534. pCol = &(p->aCol[p->nCol-1]);
  94535. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
  94536. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  94537. pCol->zName);
  94538. }else{
  94539. /* A copy of pExpr is used instead of the original, as pExpr contains
  94540. ** tokens that point to volatile memory. The 'span' of the expression
  94541. ** is required by pragma table_info.
  94542. */
  94543. Expr x;
  94544. sqlite3ExprDelete(db, pCol->pDflt);
  94545. memset(&x, 0, sizeof(x));
  94546. x.op = TK_SPAN;
  94547. x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  94548. (int)(pSpan->zEnd - pSpan->zStart));
  94549. x.pLeft = pSpan->pExpr;
  94550. x.flags = EP_Skip;
  94551. pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
  94552. sqlite3DbFree(db, x.u.zToken);
  94553. }
  94554. }
  94555. sqlite3ExprDelete(db, pSpan->pExpr);
  94556. }
  94557. /*
  94558. ** Backwards Compatibility Hack:
  94559. **
  94560. ** Historical versions of SQLite accepted strings as column names in
  94561. ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
  94562. **
  94563. ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
  94564. ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
  94565. **
  94566. ** This is goofy. But to preserve backwards compatibility we continue to
  94567. ** accept it. This routine does the necessary conversion. It converts
  94568. ** the expression given in its argument from a TK_STRING into a TK_ID
  94569. ** if the expression is just a TK_STRING with an optional COLLATE clause.
  94570. ** If the epxression is anything other than TK_STRING, the expression is
  94571. ** unchanged.
  94572. */
  94573. static void sqlite3StringToId(Expr *p){
  94574. if( p->op==TK_STRING ){
  94575. p->op = TK_ID;
  94576. }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
  94577. p->pLeft->op = TK_ID;
  94578. }
  94579. }
  94580. /*
  94581. ** Designate the PRIMARY KEY for the table. pList is a list of names
  94582. ** of columns that form the primary key. If pList is NULL, then the
  94583. ** most recently added column of the table is the primary key.
  94584. **
  94585. ** A table can have at most one primary key. If the table already has
  94586. ** a primary key (and this is the second primary key) then create an
  94587. ** error.
  94588. **
  94589. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  94590. ** then we will try to use that column as the rowid. Set the Table.iPKey
  94591. ** field of the table under construction to be the index of the
  94592. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  94593. ** no INTEGER PRIMARY KEY.
  94594. **
  94595. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  94596. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  94597. */
  94598. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  94599. Parse *pParse, /* Parsing context */
  94600. ExprList *pList, /* List of field names to be indexed */
  94601. int onError, /* What to do with a uniqueness conflict */
  94602. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  94603. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  94604. ){
  94605. Table *pTab = pParse->pNewTable;
  94606. Column *pCol = 0;
  94607. int iCol = -1, i;
  94608. int nTerm;
  94609. if( pTab==0 ) goto primary_key_exit;
  94610. if( pTab->tabFlags & TF_HasPrimaryKey ){
  94611. sqlite3ErrorMsg(pParse,
  94612. "table \"%s\" has more than one primary key", pTab->zName);
  94613. goto primary_key_exit;
  94614. }
  94615. pTab->tabFlags |= TF_HasPrimaryKey;
  94616. if( pList==0 ){
  94617. iCol = pTab->nCol - 1;
  94618. pCol = &pTab->aCol[iCol];
  94619. pCol->colFlags |= COLFLAG_PRIMKEY;
  94620. nTerm = 1;
  94621. }else{
  94622. nTerm = pList->nExpr;
  94623. for(i=0; i<nTerm; i++){
  94624. Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  94625. assert( pCExpr!=0 );
  94626. sqlite3StringToId(pCExpr);
  94627. if( pCExpr->op==TK_ID ){
  94628. const char *zCName = pCExpr->u.zToken;
  94629. for(iCol=0; iCol<pTab->nCol; iCol++){
  94630. if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
  94631. pCol = &pTab->aCol[iCol];
  94632. pCol->colFlags |= COLFLAG_PRIMKEY;
  94633. break;
  94634. }
  94635. }
  94636. }
  94637. }
  94638. }
  94639. if( nTerm==1
  94640. && pCol
  94641. && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
  94642. && sortOrder!=SQLITE_SO_DESC
  94643. ){
  94644. pTab->iPKey = iCol;
  94645. pTab->keyConf = (u8)onError;
  94646. assert( autoInc==0 || autoInc==1 );
  94647. pTab->tabFlags |= autoInc*TF_Autoincrement;
  94648. if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
  94649. }else if( autoInc ){
  94650. #ifndef SQLITE_OMIT_AUTOINCREMENT
  94651. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  94652. "INTEGER PRIMARY KEY");
  94653. #endif
  94654. }else{
  94655. sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  94656. 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
  94657. pList = 0;
  94658. }
  94659. primary_key_exit:
  94660. sqlite3ExprListDelete(pParse->db, pList);
  94661. return;
  94662. }
  94663. /*
  94664. ** Add a new CHECK constraint to the table currently under construction.
  94665. */
  94666. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  94667. Parse *pParse, /* Parsing context */
  94668. Expr *pCheckExpr /* The check expression */
  94669. ){
  94670. #ifndef SQLITE_OMIT_CHECK
  94671. Table *pTab = pParse->pNewTable;
  94672. sqlite3 *db = pParse->db;
  94673. if( pTab && !IN_DECLARE_VTAB
  94674. && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
  94675. ){
  94676. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  94677. if( pParse->constraintName.n ){
  94678. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  94679. }
  94680. }else
  94681. #endif
  94682. {
  94683. sqlite3ExprDelete(pParse->db, pCheckExpr);
  94684. }
  94685. }
  94686. /*
  94687. ** Set the collation function of the most recently parsed table column
  94688. ** to the CollSeq given.
  94689. */
  94690. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  94691. Table *p;
  94692. int i;
  94693. char *zColl; /* Dequoted name of collation sequence */
  94694. sqlite3 *db;
  94695. if( (p = pParse->pNewTable)==0 ) return;
  94696. i = p->nCol-1;
  94697. db = pParse->db;
  94698. zColl = sqlite3NameFromToken(db, pToken);
  94699. if( !zColl ) return;
  94700. if( sqlite3LocateCollSeq(pParse, zColl) ){
  94701. Index *pIdx;
  94702. sqlite3DbFree(db, p->aCol[i].zColl);
  94703. p->aCol[i].zColl = zColl;
  94704. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  94705. ** then an index may have been created on this column before the
  94706. ** collation type was added. Correct this if it is the case.
  94707. */
  94708. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  94709. assert( pIdx->nKeyCol==1 );
  94710. if( pIdx->aiColumn[0]==i ){
  94711. pIdx->azColl[0] = p->aCol[i].zColl;
  94712. }
  94713. }
  94714. }else{
  94715. sqlite3DbFree(db, zColl);
  94716. }
  94717. }
  94718. /*
  94719. ** This function returns the collation sequence for database native text
  94720. ** encoding identified by the string zName, length nName.
  94721. **
  94722. ** If the requested collation sequence is not available, or not available
  94723. ** in the database native encoding, the collation factory is invoked to
  94724. ** request it. If the collation factory does not supply such a sequence,
  94725. ** and the sequence is available in another text encoding, then that is
  94726. ** returned instead.
  94727. **
  94728. ** If no versions of the requested collations sequence are available, or
  94729. ** another error occurs, NULL is returned and an error message written into
  94730. ** pParse.
  94731. **
  94732. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  94733. ** invokes the collation factory if the named collation cannot be found
  94734. ** and generates an error message.
  94735. **
  94736. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  94737. */
  94738. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  94739. sqlite3 *db = pParse->db;
  94740. u8 enc = ENC(db);
  94741. u8 initbusy = db->init.busy;
  94742. CollSeq *pColl;
  94743. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  94744. if( !initbusy && (!pColl || !pColl->xCmp) ){
  94745. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  94746. }
  94747. return pColl;
  94748. }
  94749. /*
  94750. ** Generate code that will increment the schema cookie.
  94751. **
  94752. ** The schema cookie is used to determine when the schema for the
  94753. ** database changes. After each schema change, the cookie value
  94754. ** changes. When a process first reads the schema it records the
  94755. ** cookie. Thereafter, whenever it goes to access the database,
  94756. ** it checks the cookie to make sure the schema has not changed
  94757. ** since it was last read.
  94758. **
  94759. ** This plan is not completely bullet-proof. It is possible for
  94760. ** the schema to change multiple times and for the cookie to be
  94761. ** set back to prior value. But schema changes are infrequent
  94762. ** and the probability of hitting the same cookie value is only
  94763. ** 1 chance in 2^32. So we're safe enough.
  94764. **
  94765. ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
  94766. ** the schema-version whenever the schema changes.
  94767. */
  94768. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  94769. sqlite3 *db = pParse->db;
  94770. Vdbe *v = pParse->pVdbe;
  94771. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  94772. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
  94773. db->aDb[iDb].pSchema->schema_cookie+1);
  94774. }
  94775. /*
  94776. ** Measure the number of characters needed to output the given
  94777. ** identifier. The number returned includes any quotes used
  94778. ** but does not include the null terminator.
  94779. **
  94780. ** The estimate is conservative. It might be larger that what is
  94781. ** really needed.
  94782. */
  94783. static int identLength(const char *z){
  94784. int n;
  94785. for(n=0; *z; n++, z++){
  94786. if( *z=='"' ){ n++; }
  94787. }
  94788. return n + 2;
  94789. }
  94790. /*
  94791. ** The first parameter is a pointer to an output buffer. The second
  94792. ** parameter is a pointer to an integer that contains the offset at
  94793. ** which to write into the output buffer. This function copies the
  94794. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  94795. ** to the specified offset in the buffer and updates *pIdx to refer
  94796. ** to the first byte after the last byte written before returning.
  94797. **
  94798. ** If the string zSignedIdent consists entirely of alpha-numeric
  94799. ** characters, does not begin with a digit and is not an SQL keyword,
  94800. ** then it is copied to the output buffer exactly as it is. Otherwise,
  94801. ** it is quoted using double-quotes.
  94802. */
  94803. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  94804. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  94805. int i, j, needQuote;
  94806. i = *pIdx;
  94807. for(j=0; zIdent[j]; j++){
  94808. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  94809. }
  94810. needQuote = sqlite3Isdigit(zIdent[0])
  94811. || sqlite3KeywordCode(zIdent, j)!=TK_ID
  94812. || zIdent[j]!=0
  94813. || j==0;
  94814. if( needQuote ) z[i++] = '"';
  94815. for(j=0; zIdent[j]; j++){
  94816. z[i++] = zIdent[j];
  94817. if( zIdent[j]=='"' ) z[i++] = '"';
  94818. }
  94819. if( needQuote ) z[i++] = '"';
  94820. z[i] = 0;
  94821. *pIdx = i;
  94822. }
  94823. /*
  94824. ** Generate a CREATE TABLE statement appropriate for the given
  94825. ** table. Memory to hold the text of the statement is obtained
  94826. ** from sqliteMalloc() and must be freed by the calling function.
  94827. */
  94828. static char *createTableStmt(sqlite3 *db, Table *p){
  94829. int i, k, n;
  94830. char *zStmt;
  94831. char *zSep, *zSep2, *zEnd;
  94832. Column *pCol;
  94833. n = 0;
  94834. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  94835. n += identLength(pCol->zName) + 5;
  94836. }
  94837. n += identLength(p->zName);
  94838. if( n<50 ){
  94839. zSep = "";
  94840. zSep2 = ",";
  94841. zEnd = ")";
  94842. }else{
  94843. zSep = "\n ";
  94844. zSep2 = ",\n ";
  94845. zEnd = "\n)";
  94846. }
  94847. n += 35 + 6*p->nCol;
  94848. zStmt = sqlite3DbMallocRaw(0, n);
  94849. if( zStmt==0 ){
  94850. sqlite3OomFault(db);
  94851. return 0;
  94852. }
  94853. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  94854. k = sqlite3Strlen30(zStmt);
  94855. identPut(zStmt, &k, p->zName);
  94856. zStmt[k++] = '(';
  94857. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  94858. static const char * const azType[] = {
  94859. /* SQLITE_AFF_BLOB */ "",
  94860. /* SQLITE_AFF_TEXT */ " TEXT",
  94861. /* SQLITE_AFF_NUMERIC */ " NUM",
  94862. /* SQLITE_AFF_INTEGER */ " INT",
  94863. /* SQLITE_AFF_REAL */ " REAL"
  94864. };
  94865. int len;
  94866. const char *zType;
  94867. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  94868. k += sqlite3Strlen30(&zStmt[k]);
  94869. zSep = zSep2;
  94870. identPut(zStmt, &k, pCol->zName);
  94871. assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
  94872. assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
  94873. testcase( pCol->affinity==SQLITE_AFF_BLOB );
  94874. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  94875. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  94876. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  94877. testcase( pCol->affinity==SQLITE_AFF_REAL );
  94878. zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
  94879. len = sqlite3Strlen30(zType);
  94880. assert( pCol->affinity==SQLITE_AFF_BLOB
  94881. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  94882. memcpy(&zStmt[k], zType, len);
  94883. k += len;
  94884. assert( k<=n );
  94885. }
  94886. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  94887. return zStmt;
  94888. }
  94889. /*
  94890. ** Resize an Index object to hold N columns total. Return SQLITE_OK
  94891. ** on success and SQLITE_NOMEM on an OOM error.
  94892. */
  94893. static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
  94894. char *zExtra;
  94895. int nByte;
  94896. if( pIdx->nColumn>=N ) return SQLITE_OK;
  94897. assert( pIdx->isResized==0 );
  94898. nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
  94899. zExtra = sqlite3DbMallocZero(db, nByte);
  94900. if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
  94901. memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
  94902. pIdx->azColl = (const char**)zExtra;
  94903. zExtra += sizeof(char*)*N;
  94904. memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
  94905. pIdx->aiColumn = (i16*)zExtra;
  94906. zExtra += sizeof(i16)*N;
  94907. memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
  94908. pIdx->aSortOrder = (u8*)zExtra;
  94909. pIdx->nColumn = N;
  94910. pIdx->isResized = 1;
  94911. return SQLITE_OK;
  94912. }
  94913. /*
  94914. ** Estimate the total row width for a table.
  94915. */
  94916. static void estimateTableWidth(Table *pTab){
  94917. unsigned wTable = 0;
  94918. const Column *pTabCol;
  94919. int i;
  94920. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  94921. wTable += pTabCol->szEst;
  94922. }
  94923. if( pTab->iPKey<0 ) wTable++;
  94924. pTab->szTabRow = sqlite3LogEst(wTable*4);
  94925. }
  94926. /*
  94927. ** Estimate the average size of a row for an index.
  94928. */
  94929. static void estimateIndexWidth(Index *pIdx){
  94930. unsigned wIndex = 0;
  94931. int i;
  94932. const Column *aCol = pIdx->pTable->aCol;
  94933. for(i=0; i<pIdx->nColumn; i++){
  94934. i16 x = pIdx->aiColumn[i];
  94935. assert( x<pIdx->pTable->nCol );
  94936. wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
  94937. }
  94938. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  94939. }
  94940. /* Return true if value x is found any of the first nCol entries of aiCol[]
  94941. */
  94942. static int hasColumn(const i16 *aiCol, int nCol, int x){
  94943. while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
  94944. return 0;
  94945. }
  94946. /*
  94947. ** This routine runs at the end of parsing a CREATE TABLE statement that
  94948. ** has a WITHOUT ROWID clause. The job of this routine is to convert both
  94949. ** internal schema data structures and the generated VDBE code so that they
  94950. ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
  94951. ** Changes include:
  94952. **
  94953. ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
  94954. ** (2) Convert the OP_CreateTable into an OP_CreateIndex. There is
  94955. ** no rowid btree for a WITHOUT ROWID. Instead, the canonical
  94956. ** data storage is a covering index btree.
  94957. ** (3) Bypass the creation of the sqlite_master table entry
  94958. ** for the PRIMARY KEY as the primary key index is now
  94959. ** identified by the sqlite_master table entry of the table itself.
  94960. ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
  94961. ** schema to the rootpage from the main table.
  94962. ** (5) Add all table columns to the PRIMARY KEY Index object
  94963. ** so that the PRIMARY KEY is a covering index. The surplus
  94964. ** columns are part of KeyInfo.nXField and are not used for
  94965. ** sorting or lookup or uniqueness checks.
  94966. ** (6) Replace the rowid tail on all automatically generated UNIQUE
  94967. ** indices with the PRIMARY KEY columns.
  94968. **
  94969. ** For virtual tables, only (1) is performed.
  94970. */
  94971. static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
  94972. Index *pIdx;
  94973. Index *pPk;
  94974. int nPk;
  94975. int i, j;
  94976. sqlite3 *db = pParse->db;
  94977. Vdbe *v = pParse->pVdbe;
  94978. /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
  94979. */
  94980. if( !db->init.imposterTable ){
  94981. for(i=0; i<pTab->nCol; i++){
  94982. if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
  94983. pTab->aCol[i].notNull = OE_Abort;
  94984. }
  94985. }
  94986. }
  94987. /* The remaining transformations only apply to b-tree tables, not to
  94988. ** virtual tables */
  94989. if( IN_DECLARE_VTAB ) return;
  94990. /* Convert the OP_CreateTable opcode that would normally create the
  94991. ** root-page for the table into an OP_CreateIndex opcode. The index
  94992. ** created will become the PRIMARY KEY index.
  94993. */
  94994. if( pParse->addrCrTab ){
  94995. assert( v );
  94996. sqlite3VdbeChangeOpcode(v, pParse->addrCrTab, OP_CreateIndex);
  94997. }
  94998. /* Locate the PRIMARY KEY index. Or, if this table was originally
  94999. ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
  95000. */
  95001. if( pTab->iPKey>=0 ){
  95002. ExprList *pList;
  95003. Token ipkToken;
  95004. sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
  95005. pList = sqlite3ExprListAppend(pParse, 0,
  95006. sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
  95007. if( pList==0 ) return;
  95008. pList->a[0].sortOrder = pParse->iPkSortOrder;
  95009. assert( pParse->pNewTable==pTab );
  95010. sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
  95011. SQLITE_IDXTYPE_PRIMARYKEY);
  95012. if( db->mallocFailed ) return;
  95013. pPk = sqlite3PrimaryKeyIndex(pTab);
  95014. pTab->iPKey = -1;
  95015. }else{
  95016. pPk = sqlite3PrimaryKeyIndex(pTab);
  95017. /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
  95018. ** table entry. This is only required if currently generating VDBE
  95019. ** code for a CREATE TABLE (not when parsing one as part of reading
  95020. ** a database schema). */
  95021. if( v ){
  95022. assert( db->init.busy==0 );
  95023. sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
  95024. }
  95025. /*
  95026. ** Remove all redundant columns from the PRIMARY KEY. For example, change
  95027. ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
  95028. ** code assumes the PRIMARY KEY contains no repeated columns.
  95029. */
  95030. for(i=j=1; i<pPk->nKeyCol; i++){
  95031. if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
  95032. pPk->nColumn--;
  95033. }else{
  95034. pPk->aiColumn[j++] = pPk->aiColumn[i];
  95035. }
  95036. }
  95037. pPk->nKeyCol = j;
  95038. }
  95039. assert( pPk!=0 );
  95040. pPk->isCovering = 1;
  95041. if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
  95042. nPk = pPk->nKeyCol;
  95043. /* The root page of the PRIMARY KEY is the table root page */
  95044. pPk->tnum = pTab->tnum;
  95045. /* Update the in-memory representation of all UNIQUE indices by converting
  95046. ** the final rowid column into one or more columns of the PRIMARY KEY.
  95047. */
  95048. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  95049. int n;
  95050. if( IsPrimaryKeyIndex(pIdx) ) continue;
  95051. for(i=n=0; i<nPk; i++){
  95052. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
  95053. }
  95054. if( n==0 ){
  95055. /* This index is a superset of the primary key */
  95056. pIdx->nColumn = pIdx->nKeyCol;
  95057. continue;
  95058. }
  95059. if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
  95060. for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
  95061. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
  95062. pIdx->aiColumn[j] = pPk->aiColumn[i];
  95063. pIdx->azColl[j] = pPk->azColl[i];
  95064. j++;
  95065. }
  95066. }
  95067. assert( pIdx->nColumn>=pIdx->nKeyCol+n );
  95068. assert( pIdx->nColumn>=j );
  95069. }
  95070. /* Add all table columns to the PRIMARY KEY index
  95071. */
  95072. if( nPk<pTab->nCol ){
  95073. if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
  95074. for(i=0, j=nPk; i<pTab->nCol; i++){
  95075. if( !hasColumn(pPk->aiColumn, j, i) ){
  95076. assert( j<pPk->nColumn );
  95077. pPk->aiColumn[j] = i;
  95078. pPk->azColl[j] = sqlite3StrBINARY;
  95079. j++;
  95080. }
  95081. }
  95082. assert( pPk->nColumn==j );
  95083. assert( pTab->nCol==j );
  95084. }else{
  95085. pPk->nColumn = pTab->nCol;
  95086. }
  95087. }
  95088. /*
  95089. ** This routine is called to report the final ")" that terminates
  95090. ** a CREATE TABLE statement.
  95091. **
  95092. ** The table structure that other action routines have been building
  95093. ** is added to the internal hash tables, assuming no errors have
  95094. ** occurred.
  95095. **
  95096. ** An entry for the table is made in the master table on disk, unless
  95097. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  95098. ** it means we are reading the sqlite_master table because we just
  95099. ** connected to the database or because the sqlite_master table has
  95100. ** recently changed, so the entry for this table already exists in
  95101. ** the sqlite_master table. We do not want to create it again.
  95102. **
  95103. ** If the pSelect argument is not NULL, it means that this routine
  95104. ** was called to create a table generated from a
  95105. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  95106. ** the new table will match the result set of the SELECT.
  95107. */
  95108. SQLITE_PRIVATE void sqlite3EndTable(
  95109. Parse *pParse, /* Parse context */
  95110. Token *pCons, /* The ',' token after the last column defn. */
  95111. Token *pEnd, /* The ')' before options in the CREATE TABLE */
  95112. u8 tabOpts, /* Extra table options. Usually 0. */
  95113. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  95114. ){
  95115. Table *p; /* The new table */
  95116. sqlite3 *db = pParse->db; /* The database connection */
  95117. int iDb; /* Database in which the table lives */
  95118. Index *pIdx; /* An implied index of the table */
  95119. if( pEnd==0 && pSelect==0 ){
  95120. return;
  95121. }
  95122. assert( !db->mallocFailed );
  95123. p = pParse->pNewTable;
  95124. if( p==0 ) return;
  95125. assert( !db->init.busy || !pSelect );
  95126. /* If the db->init.busy is 1 it means we are reading the SQL off the
  95127. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  95128. ** So do not write to the disk again. Extract the root page number
  95129. ** for the table from the db->init.newTnum field. (The page number
  95130. ** should have been put there by the sqliteOpenCb routine.)
  95131. **
  95132. ** If the root page number is 1, that means this is the sqlite_master
  95133. ** table itself. So mark it read-only.
  95134. */
  95135. if( db->init.busy ){
  95136. p->tnum = db->init.newTnum;
  95137. if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
  95138. }
  95139. /* Special processing for WITHOUT ROWID Tables */
  95140. if( tabOpts & TF_WithoutRowid ){
  95141. if( (p->tabFlags & TF_Autoincrement) ){
  95142. sqlite3ErrorMsg(pParse,
  95143. "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
  95144. return;
  95145. }
  95146. if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
  95147. sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
  95148. }else{
  95149. p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
  95150. convertToWithoutRowidTable(pParse, p);
  95151. }
  95152. }
  95153. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  95154. #ifndef SQLITE_OMIT_CHECK
  95155. /* Resolve names in all CHECK constraint expressions.
  95156. */
  95157. if( p->pCheck ){
  95158. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  95159. }
  95160. #endif /* !defined(SQLITE_OMIT_CHECK) */
  95161. /* Estimate the average row size for the table and for all implied indices */
  95162. estimateTableWidth(p);
  95163. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  95164. estimateIndexWidth(pIdx);
  95165. }
  95166. /* If not initializing, then create a record for the new table
  95167. ** in the SQLITE_MASTER table of the database.
  95168. **
  95169. ** If this is a TEMPORARY table, write the entry into the auxiliary
  95170. ** file instead of into the main database file.
  95171. */
  95172. if( !db->init.busy ){
  95173. int n;
  95174. Vdbe *v;
  95175. char *zType; /* "view" or "table" */
  95176. char *zType2; /* "VIEW" or "TABLE" */
  95177. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  95178. v = sqlite3GetVdbe(pParse);
  95179. if( NEVER(v==0) ) return;
  95180. sqlite3VdbeAddOp1(v, OP_Close, 0);
  95181. /*
  95182. ** Initialize zType for the new view or table.
  95183. */
  95184. if( p->pSelect==0 ){
  95185. /* A regular table */
  95186. zType = "table";
  95187. zType2 = "TABLE";
  95188. #ifndef SQLITE_OMIT_VIEW
  95189. }else{
  95190. /* A view */
  95191. zType = "view";
  95192. zType2 = "VIEW";
  95193. #endif
  95194. }
  95195. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  95196. ** statement to populate the new table. The root-page number for the
  95197. ** new table is in register pParse->regRoot.
  95198. **
  95199. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  95200. ** suitable state to query for the column names and types to be used
  95201. ** by the new table.
  95202. **
  95203. ** A shared-cache write-lock is not required to write to the new table,
  95204. ** as a schema-lock must have already been obtained to create it. Since
  95205. ** a schema-lock excludes all other database users, the write-lock would
  95206. ** be redundant.
  95207. */
  95208. if( pSelect ){
  95209. SelectDest dest; /* Where the SELECT should store results */
  95210. int regYield; /* Register holding co-routine entry-point */
  95211. int addrTop; /* Top of the co-routine */
  95212. int regRec; /* A record to be insert into the new table */
  95213. int regRowid; /* Rowid of the next row to insert */
  95214. int addrInsLoop; /* Top of the loop for inserting rows */
  95215. Table *pSelTab; /* A table that describes the SELECT results */
  95216. regYield = ++pParse->nMem;
  95217. regRec = ++pParse->nMem;
  95218. regRowid = ++pParse->nMem;
  95219. assert(pParse->nTab==1);
  95220. sqlite3MayAbort(pParse);
  95221. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  95222. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  95223. pParse->nTab = 2;
  95224. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  95225. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  95226. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  95227. sqlite3Select(pParse, pSelect, &dest);
  95228. sqlite3VdbeEndCoroutine(v, regYield);
  95229. sqlite3VdbeJumpHere(v, addrTop - 1);
  95230. if( pParse->nErr ) return;
  95231. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  95232. if( pSelTab==0 ) return;
  95233. assert( p->aCol==0 );
  95234. p->nCol = pSelTab->nCol;
  95235. p->aCol = pSelTab->aCol;
  95236. pSelTab->nCol = 0;
  95237. pSelTab->aCol = 0;
  95238. sqlite3DeleteTable(db, pSelTab);
  95239. addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  95240. VdbeCoverage(v);
  95241. sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
  95242. sqlite3TableAffinity(v, p, 0);
  95243. sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
  95244. sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
  95245. sqlite3VdbeGoto(v, addrInsLoop);
  95246. sqlite3VdbeJumpHere(v, addrInsLoop);
  95247. sqlite3VdbeAddOp1(v, OP_Close, 1);
  95248. }
  95249. /* Compute the complete text of the CREATE statement */
  95250. if( pSelect ){
  95251. zStmt = createTableStmt(db, p);
  95252. }else{
  95253. Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
  95254. n = (int)(pEnd2->z - pParse->sNameToken.z);
  95255. if( pEnd2->z[0]!=';' ) n += pEnd2->n;
  95256. zStmt = sqlite3MPrintf(db,
  95257. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  95258. );
  95259. }
  95260. /* A slot for the record has already been allocated in the
  95261. ** SQLITE_MASTER table. We just need to update that slot with all
  95262. ** the information we've collected.
  95263. */
  95264. sqlite3NestedParse(pParse,
  95265. "UPDATE %Q.%s "
  95266. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  95267. "WHERE rowid=#%d",
  95268. db->aDb[iDb].zDbSName, MASTER_NAME,
  95269. zType,
  95270. p->zName,
  95271. p->zName,
  95272. pParse->regRoot,
  95273. zStmt,
  95274. pParse->regRowid
  95275. );
  95276. sqlite3DbFree(db, zStmt);
  95277. sqlite3ChangeCookie(pParse, iDb);
  95278. #ifndef SQLITE_OMIT_AUTOINCREMENT
  95279. /* Check to see if we need to create an sqlite_sequence table for
  95280. ** keeping track of autoincrement keys.
  95281. */
  95282. if( (p->tabFlags & TF_Autoincrement)!=0 ){
  95283. Db *pDb = &db->aDb[iDb];
  95284. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95285. if( pDb->pSchema->pSeqTab==0 ){
  95286. sqlite3NestedParse(pParse,
  95287. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  95288. pDb->zDbSName
  95289. );
  95290. }
  95291. }
  95292. #endif
  95293. /* Reparse everything to update our internal data structures */
  95294. sqlite3VdbeAddParseSchemaOp(v, iDb,
  95295. sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
  95296. }
  95297. /* Add the table to the in-memory representation of the database.
  95298. */
  95299. if( db->init.busy ){
  95300. Table *pOld;
  95301. Schema *pSchema = p->pSchema;
  95302. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95303. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
  95304. if( pOld ){
  95305. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  95306. sqlite3OomFault(db);
  95307. return;
  95308. }
  95309. pParse->pNewTable = 0;
  95310. db->flags |= SQLITE_InternChanges;
  95311. #ifndef SQLITE_OMIT_ALTERTABLE
  95312. if( !p->pSelect ){
  95313. const char *zName = (const char *)pParse->sNameToken.z;
  95314. int nName;
  95315. assert( !pSelect && pCons && pEnd );
  95316. if( pCons->z==0 ){
  95317. pCons = pEnd;
  95318. }
  95319. nName = (int)((const char *)pCons->z - zName);
  95320. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  95321. }
  95322. #endif
  95323. }
  95324. }
  95325. #ifndef SQLITE_OMIT_VIEW
  95326. /*
  95327. ** The parser calls this routine in order to create a new VIEW
  95328. */
  95329. SQLITE_PRIVATE void sqlite3CreateView(
  95330. Parse *pParse, /* The parsing context */
  95331. Token *pBegin, /* The CREATE token that begins the statement */
  95332. Token *pName1, /* The token that holds the name of the view */
  95333. Token *pName2, /* The token that holds the name of the view */
  95334. ExprList *pCNames, /* Optional list of view column names */
  95335. Select *pSelect, /* A SELECT statement that will become the new view */
  95336. int isTemp, /* TRUE for a TEMPORARY view */
  95337. int noErr /* Suppress error messages if VIEW already exists */
  95338. ){
  95339. Table *p;
  95340. int n;
  95341. const char *z;
  95342. Token sEnd;
  95343. DbFixer sFix;
  95344. Token *pName = 0;
  95345. int iDb;
  95346. sqlite3 *db = pParse->db;
  95347. if( pParse->nVar>0 ){
  95348. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  95349. goto create_view_fail;
  95350. }
  95351. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  95352. p = pParse->pNewTable;
  95353. if( p==0 || pParse->nErr ) goto create_view_fail;
  95354. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  95355. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  95356. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  95357. if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
  95358. /* Make a copy of the entire SELECT statement that defines the view.
  95359. ** This will force all the Expr.token.z values to be dynamically
  95360. ** allocated rather than point to the input string - which means that
  95361. ** they will persist after the current sqlite3_exec() call returns.
  95362. */
  95363. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  95364. p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
  95365. if( db->mallocFailed ) goto create_view_fail;
  95366. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  95367. ** the end.
  95368. */
  95369. sEnd = pParse->sLastToken;
  95370. assert( sEnd.z[0]!=0 );
  95371. if( sEnd.z[0]!=';' ){
  95372. sEnd.z += sEnd.n;
  95373. }
  95374. sEnd.n = 0;
  95375. n = (int)(sEnd.z - pBegin->z);
  95376. assert( n>0 );
  95377. z = pBegin->z;
  95378. while( sqlite3Isspace(z[n-1]) ){ n--; }
  95379. sEnd.z = &z[n-1];
  95380. sEnd.n = 1;
  95381. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  95382. sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
  95383. create_view_fail:
  95384. sqlite3SelectDelete(db, pSelect);
  95385. sqlite3ExprListDelete(db, pCNames);
  95386. return;
  95387. }
  95388. #endif /* SQLITE_OMIT_VIEW */
  95389. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  95390. /*
  95391. ** The Table structure pTable is really a VIEW. Fill in the names of
  95392. ** the columns of the view in the pTable structure. Return the number
  95393. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  95394. */
  95395. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  95396. Table *pSelTab; /* A fake table from which we get the result set */
  95397. Select *pSel; /* Copy of the SELECT that implements the view */
  95398. int nErr = 0; /* Number of errors encountered */
  95399. int n; /* Temporarily holds the number of cursors assigned */
  95400. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  95401. #ifndef SQLITE_OMIT_AUTHORIZATION
  95402. sqlite3_xauth xAuth; /* Saved xAuth pointer */
  95403. #endif
  95404. assert( pTable );
  95405. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95406. if( sqlite3VtabCallConnect(pParse, pTable) ){
  95407. return SQLITE_ERROR;
  95408. }
  95409. if( IsVirtual(pTable) ) return 0;
  95410. #endif
  95411. #ifndef SQLITE_OMIT_VIEW
  95412. /* A positive nCol means the columns names for this view are
  95413. ** already known.
  95414. */
  95415. if( pTable->nCol>0 ) return 0;
  95416. /* A negative nCol is a special marker meaning that we are currently
  95417. ** trying to compute the column names. If we enter this routine with
  95418. ** a negative nCol, it means two or more views form a loop, like this:
  95419. **
  95420. ** CREATE VIEW one AS SELECT * FROM two;
  95421. ** CREATE VIEW two AS SELECT * FROM one;
  95422. **
  95423. ** Actually, the error above is now caught prior to reaching this point.
  95424. ** But the following test is still important as it does come up
  95425. ** in the following:
  95426. **
  95427. ** CREATE TABLE main.ex1(a);
  95428. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  95429. ** SELECT * FROM temp.ex1;
  95430. */
  95431. if( pTable->nCol<0 ){
  95432. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  95433. return 1;
  95434. }
  95435. assert( pTable->nCol>=0 );
  95436. /* If we get this far, it means we need to compute the table names.
  95437. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  95438. ** "*" elements in the results set of the view and will assign cursors
  95439. ** to the elements of the FROM clause. But we do not want these changes
  95440. ** to be permanent. So the computation is done on a copy of the SELECT
  95441. ** statement that defines the view.
  95442. */
  95443. assert( pTable->pSelect );
  95444. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  95445. if( pSel ){
  95446. n = pParse->nTab;
  95447. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  95448. pTable->nCol = -1;
  95449. db->lookaside.bDisable++;
  95450. #ifndef SQLITE_OMIT_AUTHORIZATION
  95451. xAuth = db->xAuth;
  95452. db->xAuth = 0;
  95453. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  95454. db->xAuth = xAuth;
  95455. #else
  95456. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  95457. #endif
  95458. pParse->nTab = n;
  95459. if( pTable->pCheck ){
  95460. /* CREATE VIEW name(arglist) AS ...
  95461. ** The names of the columns in the table are taken from
  95462. ** arglist which is stored in pTable->pCheck. The pCheck field
  95463. ** normally holds CHECK constraints on an ordinary table, but for
  95464. ** a VIEW it holds the list of column names.
  95465. */
  95466. sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
  95467. &pTable->nCol, &pTable->aCol);
  95468. if( db->mallocFailed==0
  95469. && pParse->nErr==0
  95470. && pTable->nCol==pSel->pEList->nExpr
  95471. ){
  95472. sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
  95473. }
  95474. }else if( pSelTab ){
  95475. /* CREATE VIEW name AS... without an argument list. Construct
  95476. ** the column names from the SELECT statement that defines the view.
  95477. */
  95478. assert( pTable->aCol==0 );
  95479. pTable->nCol = pSelTab->nCol;
  95480. pTable->aCol = pSelTab->aCol;
  95481. pSelTab->nCol = 0;
  95482. pSelTab->aCol = 0;
  95483. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  95484. }else{
  95485. pTable->nCol = 0;
  95486. nErr++;
  95487. }
  95488. sqlite3DeleteTable(db, pSelTab);
  95489. sqlite3SelectDelete(db, pSel);
  95490. db->lookaside.bDisable--;
  95491. } else {
  95492. nErr++;
  95493. }
  95494. pTable->pSchema->schemaFlags |= DB_UnresetViews;
  95495. #endif /* SQLITE_OMIT_VIEW */
  95496. return nErr;
  95497. }
  95498. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  95499. #ifndef SQLITE_OMIT_VIEW
  95500. /*
  95501. ** Clear the column names from every VIEW in database idx.
  95502. */
  95503. static void sqliteViewResetAll(sqlite3 *db, int idx){
  95504. HashElem *i;
  95505. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  95506. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  95507. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  95508. Table *pTab = sqliteHashData(i);
  95509. if( pTab->pSelect ){
  95510. sqlite3DeleteColumnNames(db, pTab);
  95511. pTab->aCol = 0;
  95512. pTab->nCol = 0;
  95513. }
  95514. }
  95515. DbClearProperty(db, idx, DB_UnresetViews);
  95516. }
  95517. #else
  95518. # define sqliteViewResetAll(A,B)
  95519. #endif /* SQLITE_OMIT_VIEW */
  95520. /*
  95521. ** This function is called by the VDBE to adjust the internal schema
  95522. ** used by SQLite when the btree layer moves a table root page. The
  95523. ** root-page of a table or index in database iDb has changed from iFrom
  95524. ** to iTo.
  95525. **
  95526. ** Ticket #1728: The symbol table might still contain information
  95527. ** on tables and/or indices that are the process of being deleted.
  95528. ** If you are unlucky, one of those deleted indices or tables might
  95529. ** have the same rootpage number as the real table or index that is
  95530. ** being moved. So we cannot stop searching after the first match
  95531. ** because the first match might be for one of the deleted indices
  95532. ** or tables and not the table/index that is actually being moved.
  95533. ** We must continue looping until all tables and indices with
  95534. ** rootpage==iFrom have been converted to have a rootpage of iTo
  95535. ** in order to be certain that we got the right one.
  95536. */
  95537. #ifndef SQLITE_OMIT_AUTOVACUUM
  95538. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  95539. HashElem *pElem;
  95540. Hash *pHash;
  95541. Db *pDb;
  95542. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95543. pDb = &db->aDb[iDb];
  95544. pHash = &pDb->pSchema->tblHash;
  95545. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  95546. Table *pTab = sqliteHashData(pElem);
  95547. if( pTab->tnum==iFrom ){
  95548. pTab->tnum = iTo;
  95549. }
  95550. }
  95551. pHash = &pDb->pSchema->idxHash;
  95552. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  95553. Index *pIdx = sqliteHashData(pElem);
  95554. if( pIdx->tnum==iFrom ){
  95555. pIdx->tnum = iTo;
  95556. }
  95557. }
  95558. }
  95559. #endif
  95560. /*
  95561. ** Write code to erase the table with root-page iTable from database iDb.
  95562. ** Also write code to modify the sqlite_master table and internal schema
  95563. ** if a root-page of another table is moved by the btree-layer whilst
  95564. ** erasing iTable (this can happen with an auto-vacuum database).
  95565. */
  95566. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  95567. Vdbe *v = sqlite3GetVdbe(pParse);
  95568. int r1 = sqlite3GetTempReg(pParse);
  95569. assert( iTable>1 );
  95570. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  95571. sqlite3MayAbort(pParse);
  95572. #ifndef SQLITE_OMIT_AUTOVACUUM
  95573. /* OP_Destroy stores an in integer r1. If this integer
  95574. ** is non-zero, then it is the root page number of a table moved to
  95575. ** location iTable. The following code modifies the sqlite_master table to
  95576. ** reflect this.
  95577. **
  95578. ** The "#NNN" in the SQL is a special constant that means whatever value
  95579. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  95580. ** token for additional information.
  95581. */
  95582. sqlite3NestedParse(pParse,
  95583. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  95584. pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
  95585. #endif
  95586. sqlite3ReleaseTempReg(pParse, r1);
  95587. }
  95588. /*
  95589. ** Write VDBE code to erase table pTab and all associated indices on disk.
  95590. ** Code to update the sqlite_master tables and internal schema definitions
  95591. ** in case a root-page belonging to another table is moved by the btree layer
  95592. ** is also added (this can happen with an auto-vacuum database).
  95593. */
  95594. static void destroyTable(Parse *pParse, Table *pTab){
  95595. #ifdef SQLITE_OMIT_AUTOVACUUM
  95596. Index *pIdx;
  95597. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  95598. destroyRootPage(pParse, pTab->tnum, iDb);
  95599. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  95600. destroyRootPage(pParse, pIdx->tnum, iDb);
  95601. }
  95602. #else
  95603. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  95604. ** is not defined), then it is important to call OP_Destroy on the
  95605. ** table and index root-pages in order, starting with the numerically
  95606. ** largest root-page number. This guarantees that none of the root-pages
  95607. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  95608. ** following were coded:
  95609. **
  95610. ** OP_Destroy 4 0
  95611. ** ...
  95612. ** OP_Destroy 5 0
  95613. **
  95614. ** and root page 5 happened to be the largest root-page number in the
  95615. ** database, then root page 5 would be moved to page 4 by the
  95616. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  95617. ** a free-list page.
  95618. */
  95619. int iTab = pTab->tnum;
  95620. int iDestroyed = 0;
  95621. while( 1 ){
  95622. Index *pIdx;
  95623. int iLargest = 0;
  95624. if( iDestroyed==0 || iTab<iDestroyed ){
  95625. iLargest = iTab;
  95626. }
  95627. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  95628. int iIdx = pIdx->tnum;
  95629. assert( pIdx->pSchema==pTab->pSchema );
  95630. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  95631. iLargest = iIdx;
  95632. }
  95633. }
  95634. if( iLargest==0 ){
  95635. return;
  95636. }else{
  95637. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  95638. assert( iDb>=0 && iDb<pParse->db->nDb );
  95639. destroyRootPage(pParse, iLargest, iDb);
  95640. iDestroyed = iLargest;
  95641. }
  95642. }
  95643. #endif
  95644. }
  95645. /*
  95646. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  95647. ** after a DROP INDEX or DROP TABLE command.
  95648. */
  95649. static void sqlite3ClearStatTables(
  95650. Parse *pParse, /* The parsing context */
  95651. int iDb, /* The database number */
  95652. const char *zType, /* "idx" or "tbl" */
  95653. const char *zName /* Name of index or table */
  95654. ){
  95655. int i;
  95656. const char *zDbName = pParse->db->aDb[iDb].zDbSName;
  95657. for(i=1; i<=4; i++){
  95658. char zTab[24];
  95659. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  95660. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  95661. sqlite3NestedParse(pParse,
  95662. "DELETE FROM %Q.%s WHERE %s=%Q",
  95663. zDbName, zTab, zType, zName
  95664. );
  95665. }
  95666. }
  95667. }
  95668. /*
  95669. ** Generate code to drop a table.
  95670. */
  95671. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  95672. Vdbe *v;
  95673. sqlite3 *db = pParse->db;
  95674. Trigger *pTrigger;
  95675. Db *pDb = &db->aDb[iDb];
  95676. v = sqlite3GetVdbe(pParse);
  95677. assert( v!=0 );
  95678. sqlite3BeginWriteOperation(pParse, 1, iDb);
  95679. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95680. if( IsVirtual(pTab) ){
  95681. sqlite3VdbeAddOp0(v, OP_VBegin);
  95682. }
  95683. #endif
  95684. /* Drop all triggers associated with the table being dropped. Code
  95685. ** is generated to remove entries from sqlite_master and/or
  95686. ** sqlite_temp_master if required.
  95687. */
  95688. pTrigger = sqlite3TriggerList(pParse, pTab);
  95689. while( pTrigger ){
  95690. assert( pTrigger->pSchema==pTab->pSchema ||
  95691. pTrigger->pSchema==db->aDb[1].pSchema );
  95692. sqlite3DropTriggerPtr(pParse, pTrigger);
  95693. pTrigger = pTrigger->pNext;
  95694. }
  95695. #ifndef SQLITE_OMIT_AUTOINCREMENT
  95696. /* Remove any entries of the sqlite_sequence table associated with
  95697. ** the table being dropped. This is done before the table is dropped
  95698. ** at the btree level, in case the sqlite_sequence table needs to
  95699. ** move as a result of the drop (can happen in auto-vacuum mode).
  95700. */
  95701. if( pTab->tabFlags & TF_Autoincrement ){
  95702. sqlite3NestedParse(pParse,
  95703. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  95704. pDb->zDbSName, pTab->zName
  95705. );
  95706. }
  95707. #endif
  95708. /* Drop all SQLITE_MASTER table and index entries that refer to the
  95709. ** table. The program name loops through the master table and deletes
  95710. ** every row that refers to a table of the same name as the one being
  95711. ** dropped. Triggers are handled separately because a trigger can be
  95712. ** created in the temp database that refers to a table in another
  95713. ** database.
  95714. */
  95715. sqlite3NestedParse(pParse,
  95716. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  95717. pDb->zDbSName, MASTER_NAME, pTab->zName);
  95718. if( !isView && !IsVirtual(pTab) ){
  95719. destroyTable(pParse, pTab);
  95720. }
  95721. /* Remove the table entry from SQLite's internal schema and modify
  95722. ** the schema cookie.
  95723. */
  95724. if( IsVirtual(pTab) ){
  95725. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  95726. }
  95727. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  95728. sqlite3ChangeCookie(pParse, iDb);
  95729. sqliteViewResetAll(db, iDb);
  95730. }
  95731. /*
  95732. ** This routine is called to do the work of a DROP TABLE statement.
  95733. ** pName is the name of the table to be dropped.
  95734. */
  95735. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  95736. Table *pTab;
  95737. Vdbe *v;
  95738. sqlite3 *db = pParse->db;
  95739. int iDb;
  95740. if( db->mallocFailed ){
  95741. goto exit_drop_table;
  95742. }
  95743. assert( pParse->nErr==0 );
  95744. assert( pName->nSrc==1 );
  95745. if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
  95746. if( noErr ) db->suppressErr++;
  95747. assert( isView==0 || isView==LOCATE_VIEW );
  95748. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  95749. if( noErr ) db->suppressErr--;
  95750. if( pTab==0 ){
  95751. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  95752. goto exit_drop_table;
  95753. }
  95754. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  95755. assert( iDb>=0 && iDb<db->nDb );
  95756. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  95757. ** it is initialized.
  95758. */
  95759. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  95760. goto exit_drop_table;
  95761. }
  95762. #ifndef SQLITE_OMIT_AUTHORIZATION
  95763. {
  95764. int code;
  95765. const char *zTab = SCHEMA_TABLE(iDb);
  95766. const char *zDb = db->aDb[iDb].zDbSName;
  95767. const char *zArg2 = 0;
  95768. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  95769. goto exit_drop_table;
  95770. }
  95771. if( isView ){
  95772. if( !OMIT_TEMPDB && iDb==1 ){
  95773. code = SQLITE_DROP_TEMP_VIEW;
  95774. }else{
  95775. code = SQLITE_DROP_VIEW;
  95776. }
  95777. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95778. }else if( IsVirtual(pTab) ){
  95779. code = SQLITE_DROP_VTABLE;
  95780. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  95781. #endif
  95782. }else{
  95783. if( !OMIT_TEMPDB && iDb==1 ){
  95784. code = SQLITE_DROP_TEMP_TABLE;
  95785. }else{
  95786. code = SQLITE_DROP_TABLE;
  95787. }
  95788. }
  95789. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  95790. goto exit_drop_table;
  95791. }
  95792. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  95793. goto exit_drop_table;
  95794. }
  95795. }
  95796. #endif
  95797. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  95798. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  95799. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  95800. goto exit_drop_table;
  95801. }
  95802. #ifndef SQLITE_OMIT_VIEW
  95803. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  95804. ** on a table.
  95805. */
  95806. if( isView && pTab->pSelect==0 ){
  95807. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  95808. goto exit_drop_table;
  95809. }
  95810. if( !isView && pTab->pSelect ){
  95811. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  95812. goto exit_drop_table;
  95813. }
  95814. #endif
  95815. /* Generate code to remove the table from the master table
  95816. ** on disk.
  95817. */
  95818. v = sqlite3GetVdbe(pParse);
  95819. if( v ){
  95820. sqlite3BeginWriteOperation(pParse, 1, iDb);
  95821. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  95822. sqlite3FkDropTable(pParse, pName, pTab);
  95823. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  95824. }
  95825. exit_drop_table:
  95826. sqlite3SrcListDelete(db, pName);
  95827. }
  95828. /*
  95829. ** This routine is called to create a new foreign key on the table
  95830. ** currently under construction. pFromCol determines which columns
  95831. ** in the current table point to the foreign key. If pFromCol==0 then
  95832. ** connect the key to the last column inserted. pTo is the name of
  95833. ** the table referred to (a.k.a the "parent" table). pToCol is a list
  95834. ** of tables in the parent pTo table. flags contains all
  95835. ** information about the conflict resolution algorithms specified
  95836. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  95837. **
  95838. ** An FKey structure is created and added to the table currently
  95839. ** under construction in the pParse->pNewTable field.
  95840. **
  95841. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  95842. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  95843. */
  95844. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  95845. Parse *pParse, /* Parsing context */
  95846. ExprList *pFromCol, /* Columns in this table that point to other table */
  95847. Token *pTo, /* Name of the other table */
  95848. ExprList *pToCol, /* Columns in the other table */
  95849. int flags /* Conflict resolution algorithms. */
  95850. ){
  95851. sqlite3 *db = pParse->db;
  95852. #ifndef SQLITE_OMIT_FOREIGN_KEY
  95853. FKey *pFKey = 0;
  95854. FKey *pNextTo;
  95855. Table *p = pParse->pNewTable;
  95856. int nByte;
  95857. int i;
  95858. int nCol;
  95859. char *z;
  95860. assert( pTo!=0 );
  95861. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  95862. if( pFromCol==0 ){
  95863. int iCol = p->nCol-1;
  95864. if( NEVER(iCol<0) ) goto fk_end;
  95865. if( pToCol && pToCol->nExpr!=1 ){
  95866. sqlite3ErrorMsg(pParse, "foreign key on %s"
  95867. " should reference only one column of table %T",
  95868. p->aCol[iCol].zName, pTo);
  95869. goto fk_end;
  95870. }
  95871. nCol = 1;
  95872. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  95873. sqlite3ErrorMsg(pParse,
  95874. "number of columns in foreign key does not match the number of "
  95875. "columns in the referenced table");
  95876. goto fk_end;
  95877. }else{
  95878. nCol = pFromCol->nExpr;
  95879. }
  95880. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  95881. if( pToCol ){
  95882. for(i=0; i<pToCol->nExpr; i++){
  95883. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  95884. }
  95885. }
  95886. pFKey = sqlite3DbMallocZero(db, nByte );
  95887. if( pFKey==0 ){
  95888. goto fk_end;
  95889. }
  95890. pFKey->pFrom = p;
  95891. pFKey->pNextFrom = p->pFKey;
  95892. z = (char*)&pFKey->aCol[nCol];
  95893. pFKey->zTo = z;
  95894. memcpy(z, pTo->z, pTo->n);
  95895. z[pTo->n] = 0;
  95896. sqlite3Dequote(z);
  95897. z += pTo->n+1;
  95898. pFKey->nCol = nCol;
  95899. if( pFromCol==0 ){
  95900. pFKey->aCol[0].iFrom = p->nCol-1;
  95901. }else{
  95902. for(i=0; i<nCol; i++){
  95903. int j;
  95904. for(j=0; j<p->nCol; j++){
  95905. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  95906. pFKey->aCol[i].iFrom = j;
  95907. break;
  95908. }
  95909. }
  95910. if( j>=p->nCol ){
  95911. sqlite3ErrorMsg(pParse,
  95912. "unknown column \"%s\" in foreign key definition",
  95913. pFromCol->a[i].zName);
  95914. goto fk_end;
  95915. }
  95916. }
  95917. }
  95918. if( pToCol ){
  95919. for(i=0; i<nCol; i++){
  95920. int n = sqlite3Strlen30(pToCol->a[i].zName);
  95921. pFKey->aCol[i].zCol = z;
  95922. memcpy(z, pToCol->a[i].zName, n);
  95923. z[n] = 0;
  95924. z += n+1;
  95925. }
  95926. }
  95927. pFKey->isDeferred = 0;
  95928. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  95929. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  95930. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  95931. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  95932. pFKey->zTo, (void *)pFKey
  95933. );
  95934. if( pNextTo==pFKey ){
  95935. sqlite3OomFault(db);
  95936. goto fk_end;
  95937. }
  95938. if( pNextTo ){
  95939. assert( pNextTo->pPrevTo==0 );
  95940. pFKey->pNextTo = pNextTo;
  95941. pNextTo->pPrevTo = pFKey;
  95942. }
  95943. /* Link the foreign key to the table as the last step.
  95944. */
  95945. p->pFKey = pFKey;
  95946. pFKey = 0;
  95947. fk_end:
  95948. sqlite3DbFree(db, pFKey);
  95949. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  95950. sqlite3ExprListDelete(db, pFromCol);
  95951. sqlite3ExprListDelete(db, pToCol);
  95952. }
  95953. /*
  95954. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  95955. ** clause is seen as part of a foreign key definition. The isDeferred
  95956. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  95957. ** The behavior of the most recently created foreign key is adjusted
  95958. ** accordingly.
  95959. */
  95960. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  95961. #ifndef SQLITE_OMIT_FOREIGN_KEY
  95962. Table *pTab;
  95963. FKey *pFKey;
  95964. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  95965. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  95966. pFKey->isDeferred = (u8)isDeferred;
  95967. #endif
  95968. }
  95969. /*
  95970. ** Generate code that will erase and refill index *pIdx. This is
  95971. ** used to initialize a newly created index or to recompute the
  95972. ** content of an index in response to a REINDEX command.
  95973. **
  95974. ** if memRootPage is not negative, it means that the index is newly
  95975. ** created. The register specified by memRootPage contains the
  95976. ** root page number of the index. If memRootPage is negative, then
  95977. ** the index already exists and must be cleared before being refilled and
  95978. ** the root page number of the index is taken from pIndex->tnum.
  95979. */
  95980. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  95981. Table *pTab = pIndex->pTable; /* The table that is indexed */
  95982. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  95983. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  95984. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  95985. int addr1; /* Address of top of loop */
  95986. int addr2; /* Address to jump to for next iteration */
  95987. int tnum; /* Root page of index */
  95988. int iPartIdxLabel; /* Jump to this label to skip a row */
  95989. Vdbe *v; /* Generate code into this virtual machine */
  95990. KeyInfo *pKey; /* KeyInfo for index */
  95991. int regRecord; /* Register holding assembled index record */
  95992. sqlite3 *db = pParse->db; /* The database connection */
  95993. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  95994. #ifndef SQLITE_OMIT_AUTHORIZATION
  95995. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  95996. db->aDb[iDb].zDbSName ) ){
  95997. return;
  95998. }
  95999. #endif
  96000. /* Require a write-lock on the table to perform this operation */
  96001. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  96002. v = sqlite3GetVdbe(pParse);
  96003. if( v==0 ) return;
  96004. if( memRootPage>=0 ){
  96005. tnum = memRootPage;
  96006. }else{
  96007. tnum = pIndex->tnum;
  96008. }
  96009. pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
  96010. assert( pKey!=0 || db->mallocFailed || pParse->nErr );
  96011. /* Open the sorter cursor if we are to use one. */
  96012. iSorter = pParse->nTab++;
  96013. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
  96014. sqlite3KeyInfoRef(pKey), P4_KEYINFO);
  96015. /* Open the table. Loop through all rows of the table, inserting index
  96016. ** records into the sorter. */
  96017. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  96018. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
  96019. regRecord = sqlite3GetTempReg(pParse);
  96020. sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
  96021. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  96022. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  96023. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
  96024. sqlite3VdbeJumpHere(v, addr1);
  96025. if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  96026. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  96027. (char *)pKey, P4_KEYINFO);
  96028. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  96029. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
  96030. if( IsUniqueIndex(pIndex) ){
  96031. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  96032. sqlite3VdbeGoto(v, j2);
  96033. addr2 = sqlite3VdbeCurrentAddr(v);
  96034. sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
  96035. pIndex->nKeyCol); VdbeCoverage(v);
  96036. sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
  96037. }else{
  96038. addr2 = sqlite3VdbeCurrentAddr(v);
  96039. }
  96040. sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
  96041. sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
  96042. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
  96043. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  96044. sqlite3ReleaseTempReg(pParse, regRecord);
  96045. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
  96046. sqlite3VdbeJumpHere(v, addr1);
  96047. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  96048. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  96049. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  96050. }
  96051. /*
  96052. ** Allocate heap space to hold an Index object with nCol columns.
  96053. **
  96054. ** Increase the allocation size to provide an extra nExtra bytes
  96055. ** of 8-byte aligned space after the Index object and return a
  96056. ** pointer to this extra space in *ppExtra.
  96057. */
  96058. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
  96059. sqlite3 *db, /* Database connection */
  96060. i16 nCol, /* Total number of columns in the index */
  96061. int nExtra, /* Number of bytes of extra space to alloc */
  96062. char **ppExtra /* Pointer to the "extra" space */
  96063. ){
  96064. Index *p; /* Allocated index object */
  96065. int nByte; /* Bytes of space for Index object + arrays */
  96066. nByte = ROUND8(sizeof(Index)) + /* Index structure */
  96067. ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
  96068. ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
  96069. sizeof(i16)*nCol + /* Index.aiColumn */
  96070. sizeof(u8)*nCol); /* Index.aSortOrder */
  96071. p = sqlite3DbMallocZero(db, nByte + nExtra);
  96072. if( p ){
  96073. char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
  96074. p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
  96075. p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
  96076. p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
  96077. p->aSortOrder = (u8*)pExtra;
  96078. p->nColumn = nCol;
  96079. p->nKeyCol = nCol - 1;
  96080. *ppExtra = ((char*)p) + nByte;
  96081. }
  96082. return p;
  96083. }
  96084. /*
  96085. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  96086. ** and pTblList is the name of the table that is to be indexed. Both will
  96087. ** be NULL for a primary key or an index that is created to satisfy a
  96088. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  96089. ** as the table to be indexed. pParse->pNewTable is a table that is
  96090. ** currently being constructed by a CREATE TABLE statement.
  96091. **
  96092. ** pList is a list of columns to be indexed. pList will be NULL if this
  96093. ** is a primary key or unique-constraint on the most recent column added
  96094. ** to the table currently under construction.
  96095. */
  96096. SQLITE_PRIVATE void sqlite3CreateIndex(
  96097. Parse *pParse, /* All information about this parse */
  96098. Token *pName1, /* First part of index name. May be NULL */
  96099. Token *pName2, /* Second part of index name. May be NULL */
  96100. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  96101. ExprList *pList, /* A list of columns to be indexed */
  96102. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  96103. Token *pStart, /* The CREATE token that begins this statement */
  96104. Expr *pPIWhere, /* WHERE clause for partial indices */
  96105. int sortOrder, /* Sort order of primary key when pList==NULL */
  96106. int ifNotExist, /* Omit error if index already exists */
  96107. u8 idxType /* The index type */
  96108. ){
  96109. Table *pTab = 0; /* Table to be indexed */
  96110. Index *pIndex = 0; /* The index to be created */
  96111. char *zName = 0; /* Name of the index */
  96112. int nName; /* Number of characters in zName */
  96113. int i, j;
  96114. DbFixer sFix; /* For assigning database names to pTable */
  96115. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  96116. sqlite3 *db = pParse->db;
  96117. Db *pDb; /* The specific table containing the indexed database */
  96118. int iDb; /* Index of the database that is being written */
  96119. Token *pName = 0; /* Unqualified name of the index to create */
  96120. struct ExprList_item *pListItem; /* For looping over pList */
  96121. int nExtra = 0; /* Space allocated for zExtra[] */
  96122. int nExtraCol; /* Number of extra columns needed */
  96123. char *zExtra = 0; /* Extra space after the Index object */
  96124. Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
  96125. if( db->mallocFailed || pParse->nErr>0 ){
  96126. goto exit_create_index;
  96127. }
  96128. if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
  96129. goto exit_create_index;
  96130. }
  96131. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  96132. goto exit_create_index;
  96133. }
  96134. /*
  96135. ** Find the table that is to be indexed. Return early if not found.
  96136. */
  96137. if( pTblName!=0 ){
  96138. /* Use the two-part index name to determine the database
  96139. ** to search for the table. 'Fix' the table name to this db
  96140. ** before looking up the table.
  96141. */
  96142. assert( pName1 && pName2 );
  96143. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  96144. if( iDb<0 ) goto exit_create_index;
  96145. assert( pName && pName->z );
  96146. #ifndef SQLITE_OMIT_TEMPDB
  96147. /* If the index name was unqualified, check if the table
  96148. ** is a temp table. If so, set the database to 1. Do not do this
  96149. ** if initialising a database schema.
  96150. */
  96151. if( !db->init.busy ){
  96152. pTab = sqlite3SrcListLookup(pParse, pTblName);
  96153. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  96154. iDb = 1;
  96155. }
  96156. }
  96157. #endif
  96158. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  96159. if( sqlite3FixSrcList(&sFix, pTblName) ){
  96160. /* Because the parser constructs pTblName from a single identifier,
  96161. ** sqlite3FixSrcList can never fail. */
  96162. assert(0);
  96163. }
  96164. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  96165. assert( db->mallocFailed==0 || pTab==0 );
  96166. if( pTab==0 ) goto exit_create_index;
  96167. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  96168. sqlite3ErrorMsg(pParse,
  96169. "cannot create a TEMP index on non-TEMP table \"%s\"",
  96170. pTab->zName);
  96171. goto exit_create_index;
  96172. }
  96173. if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
  96174. }else{
  96175. assert( pName==0 );
  96176. assert( pStart==0 );
  96177. pTab = pParse->pNewTable;
  96178. if( !pTab ) goto exit_create_index;
  96179. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  96180. }
  96181. pDb = &db->aDb[iDb];
  96182. assert( pTab!=0 );
  96183. assert( pParse->nErr==0 );
  96184. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  96185. && db->init.busy==0
  96186. #if SQLITE_USER_AUTHENTICATION
  96187. && sqlite3UserAuthTable(pTab->zName)==0
  96188. #endif
  96189. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  96190. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  96191. goto exit_create_index;
  96192. }
  96193. #ifndef SQLITE_OMIT_VIEW
  96194. if( pTab->pSelect ){
  96195. sqlite3ErrorMsg(pParse, "views may not be indexed");
  96196. goto exit_create_index;
  96197. }
  96198. #endif
  96199. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96200. if( IsVirtual(pTab) ){
  96201. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  96202. goto exit_create_index;
  96203. }
  96204. #endif
  96205. /*
  96206. ** Find the name of the index. Make sure there is not already another
  96207. ** index or table with the same name.
  96208. **
  96209. ** Exception: If we are reading the names of permanent indices from the
  96210. ** sqlite_master table (because some other process changed the schema) and
  96211. ** one of the index names collides with the name of a temporary table or
  96212. ** index, then we will continue to process this index.
  96213. **
  96214. ** If pName==0 it means that we are
  96215. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  96216. ** own name.
  96217. */
  96218. if( pName ){
  96219. zName = sqlite3NameFromToken(db, pName);
  96220. if( zName==0 ) goto exit_create_index;
  96221. assert( pName->z!=0 );
  96222. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  96223. goto exit_create_index;
  96224. }
  96225. if( !db->init.busy ){
  96226. if( sqlite3FindTable(db, zName, 0)!=0 ){
  96227. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  96228. goto exit_create_index;
  96229. }
  96230. }
  96231. if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
  96232. if( !ifNotExist ){
  96233. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  96234. }else{
  96235. assert( !db->init.busy );
  96236. sqlite3CodeVerifySchema(pParse, iDb);
  96237. }
  96238. goto exit_create_index;
  96239. }
  96240. }else{
  96241. int n;
  96242. Index *pLoop;
  96243. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  96244. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  96245. if( zName==0 ){
  96246. goto exit_create_index;
  96247. }
  96248. /* Automatic index names generated from within sqlite3_declare_vtab()
  96249. ** must have names that are distinct from normal automatic index names.
  96250. ** The following statement converts "sqlite3_autoindex..." into
  96251. ** "sqlite3_butoindex..." in order to make the names distinct.
  96252. ** The "vtab_err.test" test demonstrates the need of this statement. */
  96253. if( IN_DECLARE_VTAB ) zName[7]++;
  96254. }
  96255. /* Check for authorization to create an index.
  96256. */
  96257. #ifndef SQLITE_OMIT_AUTHORIZATION
  96258. {
  96259. const char *zDb = pDb->zDbSName;
  96260. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  96261. goto exit_create_index;
  96262. }
  96263. i = SQLITE_CREATE_INDEX;
  96264. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  96265. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  96266. goto exit_create_index;
  96267. }
  96268. }
  96269. #endif
  96270. /* If pList==0, it means this routine was called to make a primary
  96271. ** key out of the last column added to the table under construction.
  96272. ** So create a fake list to simulate this.
  96273. */
  96274. if( pList==0 ){
  96275. Token prevCol;
  96276. sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName);
  96277. pList = sqlite3ExprListAppend(pParse, 0,
  96278. sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
  96279. if( pList==0 ) goto exit_create_index;
  96280. assert( pList->nExpr==1 );
  96281. sqlite3ExprListSetSortOrder(pList, sortOrder);
  96282. }else{
  96283. sqlite3ExprListCheckLength(pParse, pList, "index");
  96284. }
  96285. /* Figure out how many bytes of space are required to store explicitly
  96286. ** specified collation sequence names.
  96287. */
  96288. for(i=0; i<pList->nExpr; i++){
  96289. Expr *pExpr = pList->a[i].pExpr;
  96290. assert( pExpr!=0 );
  96291. if( pExpr->op==TK_COLLATE ){
  96292. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  96293. }
  96294. }
  96295. /*
  96296. ** Allocate the index structure.
  96297. */
  96298. nName = sqlite3Strlen30(zName);
  96299. nExtraCol = pPk ? pPk->nKeyCol : 1;
  96300. pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
  96301. nName + nExtra + 1, &zExtra);
  96302. if( db->mallocFailed ){
  96303. goto exit_create_index;
  96304. }
  96305. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
  96306. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  96307. pIndex->zName = zExtra;
  96308. zExtra += nName + 1;
  96309. memcpy(pIndex->zName, zName, nName+1);
  96310. pIndex->pTable = pTab;
  96311. pIndex->onError = (u8)onError;
  96312. pIndex->uniqNotNull = onError!=OE_None;
  96313. pIndex->idxType = idxType;
  96314. pIndex->pSchema = db->aDb[iDb].pSchema;
  96315. pIndex->nKeyCol = pList->nExpr;
  96316. if( pPIWhere ){
  96317. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  96318. pIndex->pPartIdxWhere = pPIWhere;
  96319. pPIWhere = 0;
  96320. }
  96321. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  96322. /* Check to see if we should honor DESC requests on index columns
  96323. */
  96324. if( pDb->pSchema->file_format>=4 ){
  96325. sortOrderMask = -1; /* Honor DESC */
  96326. }else{
  96327. sortOrderMask = 0; /* Ignore DESC */
  96328. }
  96329. /* Analyze the list of expressions that form the terms of the index and
  96330. ** report any errors. In the common case where the expression is exactly
  96331. ** a table column, store that column in aiColumn[]. For general expressions,
  96332. ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
  96333. **
  96334. ** TODO: Issue a warning if two or more columns of the index are identical.
  96335. ** TODO: Issue a warning if the table primary key is used as part of the
  96336. ** index key.
  96337. */
  96338. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  96339. Expr *pCExpr; /* The i-th index expression */
  96340. int requestedSortOrder; /* ASC or DESC on the i-th expression */
  96341. const char *zColl; /* Collation sequence name */
  96342. sqlite3StringToId(pListItem->pExpr);
  96343. sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
  96344. if( pParse->nErr ) goto exit_create_index;
  96345. pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
  96346. if( pCExpr->op!=TK_COLUMN ){
  96347. if( pTab==pParse->pNewTable ){
  96348. sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
  96349. "UNIQUE constraints");
  96350. goto exit_create_index;
  96351. }
  96352. if( pIndex->aColExpr==0 ){
  96353. ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
  96354. pIndex->aColExpr = pCopy;
  96355. if( !db->mallocFailed ){
  96356. assert( pCopy!=0 );
  96357. pListItem = &pCopy->a[i];
  96358. }
  96359. }
  96360. j = XN_EXPR;
  96361. pIndex->aiColumn[i] = XN_EXPR;
  96362. pIndex->uniqNotNull = 0;
  96363. }else{
  96364. j = pCExpr->iColumn;
  96365. assert( j<=0x7fff );
  96366. if( j<0 ){
  96367. j = pTab->iPKey;
  96368. }else if( pTab->aCol[j].notNull==0 ){
  96369. pIndex->uniqNotNull = 0;
  96370. }
  96371. pIndex->aiColumn[i] = (i16)j;
  96372. }
  96373. zColl = 0;
  96374. if( pListItem->pExpr->op==TK_COLLATE ){
  96375. int nColl;
  96376. zColl = pListItem->pExpr->u.zToken;
  96377. nColl = sqlite3Strlen30(zColl) + 1;
  96378. assert( nExtra>=nColl );
  96379. memcpy(zExtra, zColl, nColl);
  96380. zColl = zExtra;
  96381. zExtra += nColl;
  96382. nExtra -= nColl;
  96383. }else if( j>=0 ){
  96384. zColl = pTab->aCol[j].zColl;
  96385. }
  96386. if( !zColl ) zColl = sqlite3StrBINARY;
  96387. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  96388. goto exit_create_index;
  96389. }
  96390. pIndex->azColl[i] = zColl;
  96391. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  96392. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  96393. }
  96394. /* Append the table key to the end of the index. For WITHOUT ROWID
  96395. ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
  96396. ** normal tables (when pPk==0) this will be the rowid.
  96397. */
  96398. if( pPk ){
  96399. for(j=0; j<pPk->nKeyCol; j++){
  96400. int x = pPk->aiColumn[j];
  96401. assert( x>=0 );
  96402. if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
  96403. pIndex->nColumn--;
  96404. }else{
  96405. pIndex->aiColumn[i] = x;
  96406. pIndex->azColl[i] = pPk->azColl[j];
  96407. pIndex->aSortOrder[i] = pPk->aSortOrder[j];
  96408. i++;
  96409. }
  96410. }
  96411. assert( i==pIndex->nColumn );
  96412. }else{
  96413. pIndex->aiColumn[i] = XN_ROWID;
  96414. pIndex->azColl[i] = sqlite3StrBINARY;
  96415. }
  96416. sqlite3DefaultRowEst(pIndex);
  96417. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  96418. /* If this index contains every column of its table, then mark
  96419. ** it as a covering index */
  96420. assert( HasRowid(pTab)
  96421. || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
  96422. if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
  96423. pIndex->isCovering = 1;
  96424. for(j=0; j<pTab->nCol; j++){
  96425. if( j==pTab->iPKey ) continue;
  96426. if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
  96427. pIndex->isCovering = 0;
  96428. break;
  96429. }
  96430. }
  96431. if( pTab==pParse->pNewTable ){
  96432. /* This routine has been called to create an automatic index as a
  96433. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  96434. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  96435. ** i.e. one of:
  96436. **
  96437. ** CREATE TABLE t(x PRIMARY KEY, y);
  96438. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  96439. **
  96440. ** Either way, check to see if the table already has such an index. If
  96441. ** so, don't bother creating this one. This only applies to
  96442. ** automatically created indices. Users can do as they wish with
  96443. ** explicit indices.
  96444. **
  96445. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  96446. ** (and thus suppressing the second one) even if they have different
  96447. ** sort orders.
  96448. **
  96449. ** If there are different collating sequences or if the columns of
  96450. ** the constraint occur in different orders, then the constraints are
  96451. ** considered distinct and both result in separate indices.
  96452. */
  96453. Index *pIdx;
  96454. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  96455. int k;
  96456. assert( IsUniqueIndex(pIdx) );
  96457. assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
  96458. assert( IsUniqueIndex(pIndex) );
  96459. if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
  96460. for(k=0; k<pIdx->nKeyCol; k++){
  96461. const char *z1;
  96462. const char *z2;
  96463. assert( pIdx->aiColumn[k]>=0 );
  96464. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  96465. z1 = pIdx->azColl[k];
  96466. z2 = pIndex->azColl[k];
  96467. if( sqlite3StrICmp(z1, z2) ) break;
  96468. }
  96469. if( k==pIdx->nKeyCol ){
  96470. if( pIdx->onError!=pIndex->onError ){
  96471. /* This constraint creates the same index as a previous
  96472. ** constraint specified somewhere in the CREATE TABLE statement.
  96473. ** However the ON CONFLICT clauses are different. If both this
  96474. ** constraint and the previous equivalent constraint have explicit
  96475. ** ON CONFLICT clauses this is an error. Otherwise, use the
  96476. ** explicitly specified behavior for the index.
  96477. */
  96478. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  96479. sqlite3ErrorMsg(pParse,
  96480. "conflicting ON CONFLICT clauses specified", 0);
  96481. }
  96482. if( pIdx->onError==OE_Default ){
  96483. pIdx->onError = pIndex->onError;
  96484. }
  96485. }
  96486. if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
  96487. goto exit_create_index;
  96488. }
  96489. }
  96490. }
  96491. /* Link the new Index structure to its table and to the other
  96492. ** in-memory database structures.
  96493. */
  96494. assert( pParse->nErr==0 );
  96495. if( db->init.busy ){
  96496. Index *p;
  96497. assert( !IN_DECLARE_VTAB );
  96498. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  96499. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  96500. pIndex->zName, pIndex);
  96501. if( p ){
  96502. assert( p==pIndex ); /* Malloc must have failed */
  96503. sqlite3OomFault(db);
  96504. goto exit_create_index;
  96505. }
  96506. db->flags |= SQLITE_InternChanges;
  96507. if( pTblName!=0 ){
  96508. pIndex->tnum = db->init.newTnum;
  96509. }
  96510. }
  96511. /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
  96512. ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
  96513. ** emit code to allocate the index rootpage on disk and make an entry for
  96514. ** the index in the sqlite_master table and populate the index with
  96515. ** content. But, do not do this if we are simply reading the sqlite_master
  96516. ** table to parse the schema, or if this index is the PRIMARY KEY index
  96517. ** of a WITHOUT ROWID table.
  96518. **
  96519. ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
  96520. ** or UNIQUE index in a CREATE TABLE statement. Since the table
  96521. ** has just been created, it contains no data and the index initialization
  96522. ** step can be skipped.
  96523. */
  96524. else if( HasRowid(pTab) || pTblName!=0 ){
  96525. Vdbe *v;
  96526. char *zStmt;
  96527. int iMem = ++pParse->nMem;
  96528. v = sqlite3GetVdbe(pParse);
  96529. if( v==0 ) goto exit_create_index;
  96530. sqlite3BeginWriteOperation(pParse, 1, iDb);
  96531. /* Create the rootpage for the index using CreateIndex. But before
  96532. ** doing so, code a Noop instruction and store its address in
  96533. ** Index.tnum. This is required in case this index is actually a
  96534. ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
  96535. ** that case the convertToWithoutRowidTable() routine will replace
  96536. ** the Noop with a Goto to jump over the VDBE code generated below. */
  96537. pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
  96538. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  96539. /* Gather the complete text of the CREATE INDEX statement into
  96540. ** the zStmt variable
  96541. */
  96542. if( pStart ){
  96543. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  96544. if( pName->z[n-1]==';' ) n--;
  96545. /* A named index with an explicit CREATE INDEX statement */
  96546. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  96547. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  96548. }else{
  96549. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  96550. /* zStmt = sqlite3MPrintf(""); */
  96551. zStmt = 0;
  96552. }
  96553. /* Add an entry in sqlite_master for this index
  96554. */
  96555. sqlite3NestedParse(pParse,
  96556. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  96557. db->aDb[iDb].zDbSName, MASTER_NAME,
  96558. pIndex->zName,
  96559. pTab->zName,
  96560. iMem,
  96561. zStmt
  96562. );
  96563. sqlite3DbFree(db, zStmt);
  96564. /* Fill the index with data and reparse the schema. Code an OP_Expire
  96565. ** to invalidate all pre-compiled statements.
  96566. */
  96567. if( pTblName ){
  96568. sqlite3RefillIndex(pParse, pIndex, iMem);
  96569. sqlite3ChangeCookie(pParse, iDb);
  96570. sqlite3VdbeAddParseSchemaOp(v, iDb,
  96571. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  96572. sqlite3VdbeAddOp0(v, OP_Expire);
  96573. }
  96574. sqlite3VdbeJumpHere(v, pIndex->tnum);
  96575. }
  96576. /* When adding an index to the list of indices for a table, make
  96577. ** sure all indices labeled OE_Replace come after all those labeled
  96578. ** OE_Ignore. This is necessary for the correct constraint check
  96579. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  96580. ** UPDATE and INSERT statements.
  96581. */
  96582. if( db->init.busy || pTblName==0 ){
  96583. if( onError!=OE_Replace || pTab->pIndex==0
  96584. || pTab->pIndex->onError==OE_Replace){
  96585. pIndex->pNext = pTab->pIndex;
  96586. pTab->pIndex = pIndex;
  96587. }else{
  96588. Index *pOther = pTab->pIndex;
  96589. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  96590. pOther = pOther->pNext;
  96591. }
  96592. pIndex->pNext = pOther->pNext;
  96593. pOther->pNext = pIndex;
  96594. }
  96595. pIndex = 0;
  96596. }
  96597. /* Clean up before exiting */
  96598. exit_create_index:
  96599. if( pIndex ) freeIndex(db, pIndex);
  96600. sqlite3ExprDelete(db, pPIWhere);
  96601. sqlite3ExprListDelete(db, pList);
  96602. sqlite3SrcListDelete(db, pTblName);
  96603. sqlite3DbFree(db, zName);
  96604. }
  96605. /*
  96606. ** Fill the Index.aiRowEst[] array with default information - information
  96607. ** to be used when we have not run the ANALYZE command.
  96608. **
  96609. ** aiRowEst[0] is supposed to contain the number of elements in the index.
  96610. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  96611. ** number of rows in the table that match any particular value of the
  96612. ** first column of the index. aiRowEst[2] is an estimate of the number
  96613. ** of rows that match any particular combination of the first 2 columns
  96614. ** of the index. And so forth. It must always be the case that
  96615. *
  96616. ** aiRowEst[N]<=aiRowEst[N-1]
  96617. ** aiRowEst[N]>=1
  96618. **
  96619. ** Apart from that, we have little to go on besides intuition as to
  96620. ** how aiRowEst[] should be initialized. The numbers generated here
  96621. ** are based on typical values found in actual indices.
  96622. */
  96623. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  96624. /* 10, 9, 8, 7, 6 */
  96625. LogEst aVal[] = { 33, 32, 30, 28, 26 };
  96626. LogEst *a = pIdx->aiRowLogEst;
  96627. int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
  96628. int i;
  96629. /* Indexes with default row estimates should not have stat1 data */
  96630. assert( !pIdx->hasStat1 );
  96631. /* Set the first entry (number of rows in the index) to the estimated
  96632. ** number of rows in the table, or half the number of rows in the table
  96633. ** for a partial index. But do not let the estimate drop below 10. */
  96634. a[0] = pIdx->pTable->nRowLogEst;
  96635. if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) );
  96636. if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
  96637. /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
  96638. ** 6 and each subsequent value (if any) is 5. */
  96639. memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
  96640. for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
  96641. a[i] = 23; assert( 23==sqlite3LogEst(5) );
  96642. }
  96643. assert( 0==sqlite3LogEst(1) );
  96644. if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
  96645. }
  96646. /*
  96647. ** This routine will drop an existing named index. This routine
  96648. ** implements the DROP INDEX statement.
  96649. */
  96650. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  96651. Index *pIndex;
  96652. Vdbe *v;
  96653. sqlite3 *db = pParse->db;
  96654. int iDb;
  96655. assert( pParse->nErr==0 ); /* Never called with prior errors */
  96656. if( db->mallocFailed ){
  96657. goto exit_drop_index;
  96658. }
  96659. assert( pName->nSrc==1 );
  96660. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  96661. goto exit_drop_index;
  96662. }
  96663. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  96664. if( pIndex==0 ){
  96665. if( !ifExists ){
  96666. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  96667. }else{
  96668. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  96669. }
  96670. pParse->checkSchema = 1;
  96671. goto exit_drop_index;
  96672. }
  96673. if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
  96674. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  96675. "or PRIMARY KEY constraint cannot be dropped", 0);
  96676. goto exit_drop_index;
  96677. }
  96678. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  96679. #ifndef SQLITE_OMIT_AUTHORIZATION
  96680. {
  96681. int code = SQLITE_DROP_INDEX;
  96682. Table *pTab = pIndex->pTable;
  96683. const char *zDb = db->aDb[iDb].zDbSName;
  96684. const char *zTab = SCHEMA_TABLE(iDb);
  96685. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  96686. goto exit_drop_index;
  96687. }
  96688. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  96689. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  96690. goto exit_drop_index;
  96691. }
  96692. }
  96693. #endif
  96694. /* Generate code to remove the index and from the master table */
  96695. v = sqlite3GetVdbe(pParse);
  96696. if( v ){
  96697. sqlite3BeginWriteOperation(pParse, 1, iDb);
  96698. sqlite3NestedParse(pParse,
  96699. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  96700. db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
  96701. );
  96702. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  96703. sqlite3ChangeCookie(pParse, iDb);
  96704. destroyRootPage(pParse, pIndex->tnum, iDb);
  96705. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  96706. }
  96707. exit_drop_index:
  96708. sqlite3SrcListDelete(db, pName);
  96709. }
  96710. /*
  96711. ** pArray is a pointer to an array of objects. Each object in the
  96712. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  96713. ** to extend the array so that there is space for a new object at the end.
  96714. **
  96715. ** When this function is called, *pnEntry contains the current size of
  96716. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  96717. ** in total).
  96718. **
  96719. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  96720. ** space allocated for the new object is zeroed, *pnEntry updated to
  96721. ** reflect the new size of the array and a pointer to the new allocation
  96722. ** returned. *pIdx is set to the index of the new array entry in this case.
  96723. **
  96724. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  96725. ** unchanged and a copy of pArray returned.
  96726. */
  96727. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  96728. sqlite3 *db, /* Connection to notify of malloc failures */
  96729. void *pArray, /* Array of objects. Might be reallocated */
  96730. int szEntry, /* Size of each object in the array */
  96731. int *pnEntry, /* Number of objects currently in use */
  96732. int *pIdx /* Write the index of a new slot here */
  96733. ){
  96734. char *z;
  96735. int n = *pnEntry;
  96736. if( (n & (n-1))==0 ){
  96737. int sz = (n==0) ? 1 : 2*n;
  96738. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  96739. if( pNew==0 ){
  96740. *pIdx = -1;
  96741. return pArray;
  96742. }
  96743. pArray = pNew;
  96744. }
  96745. z = (char*)pArray;
  96746. memset(&z[n * szEntry], 0, szEntry);
  96747. *pIdx = n;
  96748. ++*pnEntry;
  96749. return pArray;
  96750. }
  96751. /*
  96752. ** Append a new element to the given IdList. Create a new IdList if
  96753. ** need be.
  96754. **
  96755. ** A new IdList is returned, or NULL if malloc() fails.
  96756. */
  96757. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  96758. int i;
  96759. if( pList==0 ){
  96760. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  96761. if( pList==0 ) return 0;
  96762. }
  96763. pList->a = sqlite3ArrayAllocate(
  96764. db,
  96765. pList->a,
  96766. sizeof(pList->a[0]),
  96767. &pList->nId,
  96768. &i
  96769. );
  96770. if( i<0 ){
  96771. sqlite3IdListDelete(db, pList);
  96772. return 0;
  96773. }
  96774. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  96775. return pList;
  96776. }
  96777. /*
  96778. ** Delete an IdList.
  96779. */
  96780. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  96781. int i;
  96782. if( pList==0 ) return;
  96783. for(i=0; i<pList->nId; i++){
  96784. sqlite3DbFree(db, pList->a[i].zName);
  96785. }
  96786. sqlite3DbFree(db, pList->a);
  96787. sqlite3DbFreeNN(db, pList);
  96788. }
  96789. /*
  96790. ** Return the index in pList of the identifier named zId. Return -1
  96791. ** if not found.
  96792. */
  96793. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  96794. int i;
  96795. if( pList==0 ) return -1;
  96796. for(i=0; i<pList->nId; i++){
  96797. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  96798. }
  96799. return -1;
  96800. }
  96801. /*
  96802. ** Expand the space allocated for the given SrcList object by
  96803. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  96804. ** New slots are zeroed.
  96805. **
  96806. ** For example, suppose a SrcList initially contains two entries: A,B.
  96807. ** To append 3 new entries onto the end, do this:
  96808. **
  96809. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  96810. **
  96811. ** After the call above it would contain: A, B, nil, nil, nil.
  96812. ** If the iStart argument had been 1 instead of 2, then the result
  96813. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  96814. ** the iStart value would be 0. The result then would
  96815. ** be: nil, nil, nil, A, B.
  96816. **
  96817. ** If a memory allocation fails the SrcList is unchanged. The
  96818. ** db->mallocFailed flag will be set to true.
  96819. */
  96820. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  96821. sqlite3 *db, /* Database connection to notify of OOM errors */
  96822. SrcList *pSrc, /* The SrcList to be enlarged */
  96823. int nExtra, /* Number of new slots to add to pSrc->a[] */
  96824. int iStart /* Index in pSrc->a[] of first new slot */
  96825. ){
  96826. int i;
  96827. /* Sanity checking on calling parameters */
  96828. assert( iStart>=0 );
  96829. assert( nExtra>=1 );
  96830. assert( pSrc!=0 );
  96831. assert( iStart<=pSrc->nSrc );
  96832. /* Allocate additional space if needed */
  96833. if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
  96834. SrcList *pNew;
  96835. int nAlloc = pSrc->nSrc*2+nExtra;
  96836. int nGot;
  96837. pNew = sqlite3DbRealloc(db, pSrc,
  96838. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  96839. if( pNew==0 ){
  96840. assert( db->mallocFailed );
  96841. return pSrc;
  96842. }
  96843. pSrc = pNew;
  96844. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  96845. pSrc->nAlloc = nGot;
  96846. }
  96847. /* Move existing slots that come after the newly inserted slots
  96848. ** out of the way */
  96849. for(i=pSrc->nSrc-1; i>=iStart; i--){
  96850. pSrc->a[i+nExtra] = pSrc->a[i];
  96851. }
  96852. pSrc->nSrc += nExtra;
  96853. /* Zero the newly allocated slots */
  96854. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  96855. for(i=iStart; i<iStart+nExtra; i++){
  96856. pSrc->a[i].iCursor = -1;
  96857. }
  96858. /* Return a pointer to the enlarged SrcList */
  96859. return pSrc;
  96860. }
  96861. /*
  96862. ** Append a new table name to the given SrcList. Create a new SrcList if
  96863. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  96864. **
  96865. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  96866. ** SrcList might be the same as the SrcList that was input or it might be
  96867. ** a new one. If an OOM error does occurs, then the prior value of pList
  96868. ** that is input to this routine is automatically freed.
  96869. **
  96870. ** If pDatabase is not null, it means that the table has an optional
  96871. ** database name prefix. Like this: "database.table". The pDatabase
  96872. ** points to the table name and the pTable points to the database name.
  96873. ** The SrcList.a[].zName field is filled with the table name which might
  96874. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  96875. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  96876. ** or with NULL if no database is specified.
  96877. **
  96878. ** In other words, if call like this:
  96879. **
  96880. ** sqlite3SrcListAppend(D,A,B,0);
  96881. **
  96882. ** Then B is a table name and the database name is unspecified. If called
  96883. ** like this:
  96884. **
  96885. ** sqlite3SrcListAppend(D,A,B,C);
  96886. **
  96887. ** Then C is the table name and B is the database name. If C is defined
  96888. ** then so is B. In other words, we never have a case where:
  96889. **
  96890. ** sqlite3SrcListAppend(D,A,0,C);
  96891. **
  96892. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  96893. ** before being added to the SrcList.
  96894. */
  96895. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  96896. sqlite3 *db, /* Connection to notify of malloc failures */
  96897. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  96898. Token *pTable, /* Table to append */
  96899. Token *pDatabase /* Database of the table */
  96900. ){
  96901. struct SrcList_item *pItem;
  96902. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  96903. assert( db!=0 );
  96904. if( pList==0 ){
  96905. pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
  96906. if( pList==0 ) return 0;
  96907. pList->nAlloc = 1;
  96908. pList->nSrc = 1;
  96909. memset(&pList->a[0], 0, sizeof(pList->a[0]));
  96910. pList->a[0].iCursor = -1;
  96911. }else{
  96912. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  96913. }
  96914. if( db->mallocFailed ){
  96915. sqlite3SrcListDelete(db, pList);
  96916. return 0;
  96917. }
  96918. pItem = &pList->a[pList->nSrc-1];
  96919. if( pDatabase && pDatabase->z==0 ){
  96920. pDatabase = 0;
  96921. }
  96922. if( pDatabase ){
  96923. Token *pTemp = pDatabase;
  96924. pDatabase = pTable;
  96925. pTable = pTemp;
  96926. }
  96927. pItem->zName = sqlite3NameFromToken(db, pTable);
  96928. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  96929. return pList;
  96930. }
  96931. /*
  96932. ** Assign VdbeCursor index numbers to all tables in a SrcList
  96933. */
  96934. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  96935. int i;
  96936. struct SrcList_item *pItem;
  96937. assert(pList || pParse->db->mallocFailed );
  96938. if( pList ){
  96939. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  96940. if( pItem->iCursor>=0 ) break;
  96941. pItem->iCursor = pParse->nTab++;
  96942. if( pItem->pSelect ){
  96943. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  96944. }
  96945. }
  96946. }
  96947. }
  96948. /*
  96949. ** Delete an entire SrcList including all its substructure.
  96950. */
  96951. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  96952. int i;
  96953. struct SrcList_item *pItem;
  96954. if( pList==0 ) return;
  96955. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  96956. sqlite3DbFree(db, pItem->zDatabase);
  96957. sqlite3DbFree(db, pItem->zName);
  96958. sqlite3DbFree(db, pItem->zAlias);
  96959. if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
  96960. if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
  96961. sqlite3DeleteTable(db, pItem->pTab);
  96962. sqlite3SelectDelete(db, pItem->pSelect);
  96963. sqlite3ExprDelete(db, pItem->pOn);
  96964. sqlite3IdListDelete(db, pItem->pUsing);
  96965. }
  96966. sqlite3DbFreeNN(db, pList);
  96967. }
  96968. /*
  96969. ** This routine is called by the parser to add a new term to the
  96970. ** end of a growing FROM clause. The "p" parameter is the part of
  96971. ** the FROM clause that has already been constructed. "p" is NULL
  96972. ** if this is the first term of the FROM clause. pTable and pDatabase
  96973. ** are the name of the table and database named in the FROM clause term.
  96974. ** pDatabase is NULL if the database name qualifier is missing - the
  96975. ** usual case. If the term has an alias, then pAlias points to the
  96976. ** alias token. If the term is a subquery, then pSubquery is the
  96977. ** SELECT statement that the subquery encodes. The pTable and
  96978. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  96979. ** parameters are the content of the ON and USING clauses.
  96980. **
  96981. ** Return a new SrcList which encodes is the FROM with the new
  96982. ** term added.
  96983. */
  96984. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  96985. Parse *pParse, /* Parsing context */
  96986. SrcList *p, /* The left part of the FROM clause already seen */
  96987. Token *pTable, /* Name of the table to add to the FROM clause */
  96988. Token *pDatabase, /* Name of the database containing pTable */
  96989. Token *pAlias, /* The right-hand side of the AS subexpression */
  96990. Select *pSubquery, /* A subquery used in place of a table name */
  96991. Expr *pOn, /* The ON clause of a join */
  96992. IdList *pUsing /* The USING clause of a join */
  96993. ){
  96994. struct SrcList_item *pItem;
  96995. sqlite3 *db = pParse->db;
  96996. if( !p && (pOn || pUsing) ){
  96997. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  96998. (pOn ? "ON" : "USING")
  96999. );
  97000. goto append_from_error;
  97001. }
  97002. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  97003. if( p==0 || NEVER(p->nSrc==0) ){
  97004. goto append_from_error;
  97005. }
  97006. pItem = &p->a[p->nSrc-1];
  97007. assert( pAlias!=0 );
  97008. if( pAlias->n ){
  97009. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  97010. }
  97011. pItem->pSelect = pSubquery;
  97012. pItem->pOn = pOn;
  97013. pItem->pUsing = pUsing;
  97014. return p;
  97015. append_from_error:
  97016. assert( p==0 );
  97017. sqlite3ExprDelete(db, pOn);
  97018. sqlite3IdListDelete(db, pUsing);
  97019. sqlite3SelectDelete(db, pSubquery);
  97020. return 0;
  97021. }
  97022. /*
  97023. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  97024. ** element of the source-list passed as the second argument.
  97025. */
  97026. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  97027. assert( pIndexedBy!=0 );
  97028. if( p && ALWAYS(p->nSrc>0) ){
  97029. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  97030. assert( pItem->fg.notIndexed==0 );
  97031. assert( pItem->fg.isIndexedBy==0 );
  97032. assert( pItem->fg.isTabFunc==0 );
  97033. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  97034. /* A "NOT INDEXED" clause was supplied. See parse.y
  97035. ** construct "indexed_opt" for details. */
  97036. pItem->fg.notIndexed = 1;
  97037. }else{
  97038. pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
  97039. pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
  97040. }
  97041. }
  97042. }
  97043. /*
  97044. ** Add the list of function arguments to the SrcList entry for a
  97045. ** table-valued-function.
  97046. */
  97047. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
  97048. if( p ){
  97049. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  97050. assert( pItem->fg.notIndexed==0 );
  97051. assert( pItem->fg.isIndexedBy==0 );
  97052. assert( pItem->fg.isTabFunc==0 );
  97053. pItem->u1.pFuncArg = pList;
  97054. pItem->fg.isTabFunc = 1;
  97055. }else{
  97056. sqlite3ExprListDelete(pParse->db, pList);
  97057. }
  97058. }
  97059. /*
  97060. ** When building up a FROM clause in the parser, the join operator
  97061. ** is initially attached to the left operand. But the code generator
  97062. ** expects the join operator to be on the right operand. This routine
  97063. ** Shifts all join operators from left to right for an entire FROM
  97064. ** clause.
  97065. **
  97066. ** Example: Suppose the join is like this:
  97067. **
  97068. ** A natural cross join B
  97069. **
  97070. ** The operator is "natural cross join". The A and B operands are stored
  97071. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  97072. ** operator with A. This routine shifts that operator over to B.
  97073. */
  97074. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  97075. if( p ){
  97076. int i;
  97077. for(i=p->nSrc-1; i>0; i--){
  97078. p->a[i].fg.jointype = p->a[i-1].fg.jointype;
  97079. }
  97080. p->a[0].fg.jointype = 0;
  97081. }
  97082. }
  97083. /*
  97084. ** Generate VDBE code for a BEGIN statement.
  97085. */
  97086. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  97087. sqlite3 *db;
  97088. Vdbe *v;
  97089. int i;
  97090. assert( pParse!=0 );
  97091. db = pParse->db;
  97092. assert( db!=0 );
  97093. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  97094. return;
  97095. }
  97096. v = sqlite3GetVdbe(pParse);
  97097. if( !v ) return;
  97098. if( type!=TK_DEFERRED ){
  97099. for(i=0; i<db->nDb; i++){
  97100. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  97101. sqlite3VdbeUsesBtree(v, i);
  97102. }
  97103. }
  97104. sqlite3VdbeAddOp0(v, OP_AutoCommit);
  97105. }
  97106. /*
  97107. ** Generate VDBE code for a COMMIT statement.
  97108. */
  97109. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  97110. Vdbe *v;
  97111. assert( pParse!=0 );
  97112. assert( pParse->db!=0 );
  97113. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  97114. return;
  97115. }
  97116. v = sqlite3GetVdbe(pParse);
  97117. if( v ){
  97118. sqlite3VdbeAddOp1(v, OP_AutoCommit, 1);
  97119. }
  97120. }
  97121. /*
  97122. ** Generate VDBE code for a ROLLBACK statement.
  97123. */
  97124. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  97125. Vdbe *v;
  97126. assert( pParse!=0 );
  97127. assert( pParse->db!=0 );
  97128. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  97129. return;
  97130. }
  97131. v = sqlite3GetVdbe(pParse);
  97132. if( v ){
  97133. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  97134. }
  97135. }
  97136. /*
  97137. ** This function is called by the parser when it parses a command to create,
  97138. ** release or rollback an SQL savepoint.
  97139. */
  97140. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  97141. char *zName = sqlite3NameFromToken(pParse->db, pName);
  97142. if( zName ){
  97143. Vdbe *v = sqlite3GetVdbe(pParse);
  97144. #ifndef SQLITE_OMIT_AUTHORIZATION
  97145. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  97146. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  97147. #endif
  97148. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  97149. sqlite3DbFree(pParse->db, zName);
  97150. return;
  97151. }
  97152. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  97153. }
  97154. }
  97155. /*
  97156. ** Make sure the TEMP database is open and available for use. Return
  97157. ** the number of errors. Leave any error messages in the pParse structure.
  97158. */
  97159. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  97160. sqlite3 *db = pParse->db;
  97161. if( db->aDb[1].pBt==0 && !pParse->explain ){
  97162. int rc;
  97163. Btree *pBt;
  97164. static const int flags =
  97165. SQLITE_OPEN_READWRITE |
  97166. SQLITE_OPEN_CREATE |
  97167. SQLITE_OPEN_EXCLUSIVE |
  97168. SQLITE_OPEN_DELETEONCLOSE |
  97169. SQLITE_OPEN_TEMP_DB;
  97170. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  97171. if( rc!=SQLITE_OK ){
  97172. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  97173. "file for storing temporary tables");
  97174. pParse->rc = rc;
  97175. return 1;
  97176. }
  97177. db->aDb[1].pBt = pBt;
  97178. assert( db->aDb[1].pSchema );
  97179. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  97180. sqlite3OomFault(db);
  97181. return 1;
  97182. }
  97183. }
  97184. return 0;
  97185. }
  97186. /*
  97187. ** Record the fact that the schema cookie will need to be verified
  97188. ** for database iDb. The code to actually verify the schema cookie
  97189. ** will occur at the end of the top-level VDBE and will be generated
  97190. ** later, by sqlite3FinishCoding().
  97191. */
  97192. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  97193. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  97194. assert( iDb>=0 && iDb<pParse->db->nDb );
  97195. assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
  97196. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  97197. assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
  97198. if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
  97199. DbMaskSet(pToplevel->cookieMask, iDb);
  97200. if( !OMIT_TEMPDB && iDb==1 ){
  97201. sqlite3OpenTempDatabase(pToplevel);
  97202. }
  97203. }
  97204. }
  97205. /*
  97206. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  97207. ** attached database. Otherwise, invoke it for the database named zDb only.
  97208. */
  97209. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  97210. sqlite3 *db = pParse->db;
  97211. int i;
  97212. for(i=0; i<db->nDb; i++){
  97213. Db *pDb = &db->aDb[i];
  97214. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
  97215. sqlite3CodeVerifySchema(pParse, i);
  97216. }
  97217. }
  97218. }
  97219. /*
  97220. ** Generate VDBE code that prepares for doing an operation that
  97221. ** might change the database.
  97222. **
  97223. ** This routine starts a new transaction if we are not already within
  97224. ** a transaction. If we are already within a transaction, then a checkpoint
  97225. ** is set if the setStatement parameter is true. A checkpoint should
  97226. ** be set for operations that might fail (due to a constraint) part of
  97227. ** the way through and which will need to undo some writes without having to
  97228. ** rollback the whole transaction. For operations where all constraints
  97229. ** can be checked before any changes are made to the database, it is never
  97230. ** necessary to undo a write and the checkpoint should not be set.
  97231. */
  97232. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  97233. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  97234. sqlite3CodeVerifySchema(pParse, iDb);
  97235. DbMaskSet(pToplevel->writeMask, iDb);
  97236. pToplevel->isMultiWrite |= setStatement;
  97237. }
  97238. /*
  97239. ** Indicate that the statement currently under construction might write
  97240. ** more than one entry (example: deleting one row then inserting another,
  97241. ** inserting multiple rows in a table, or inserting a row and index entries.)
  97242. ** If an abort occurs after some of these writes have completed, then it will
  97243. ** be necessary to undo the completed writes.
  97244. */
  97245. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  97246. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  97247. pToplevel->isMultiWrite = 1;
  97248. }
  97249. /*
  97250. ** The code generator calls this routine if is discovers that it is
  97251. ** possible to abort a statement prior to completion. In order to
  97252. ** perform this abort without corrupting the database, we need to make
  97253. ** sure that the statement is protected by a statement transaction.
  97254. **
  97255. ** Technically, we only need to set the mayAbort flag if the
  97256. ** isMultiWrite flag was previously set. There is a time dependency
  97257. ** such that the abort must occur after the multiwrite. This makes
  97258. ** some statements involving the REPLACE conflict resolution algorithm
  97259. ** go a little faster. But taking advantage of this time dependency
  97260. ** makes it more difficult to prove that the code is correct (in
  97261. ** particular, it prevents us from writing an effective
  97262. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  97263. ** to take the safe route and skip the optimization.
  97264. */
  97265. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  97266. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  97267. pToplevel->mayAbort = 1;
  97268. }
  97269. /*
  97270. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  97271. ** error. The onError parameter determines which (if any) of the statement
  97272. ** and/or current transaction is rolled back.
  97273. */
  97274. SQLITE_PRIVATE void sqlite3HaltConstraint(
  97275. Parse *pParse, /* Parsing context */
  97276. int errCode, /* extended error code */
  97277. int onError, /* Constraint type */
  97278. char *p4, /* Error message */
  97279. i8 p4type, /* P4_STATIC or P4_TRANSIENT */
  97280. u8 p5Errmsg /* P5_ErrMsg type */
  97281. ){
  97282. Vdbe *v = sqlite3GetVdbe(pParse);
  97283. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  97284. if( onError==OE_Abort ){
  97285. sqlite3MayAbort(pParse);
  97286. }
  97287. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  97288. sqlite3VdbeChangeP5(v, p5Errmsg);
  97289. }
  97290. /*
  97291. ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
  97292. */
  97293. SQLITE_PRIVATE void sqlite3UniqueConstraint(
  97294. Parse *pParse, /* Parsing context */
  97295. int onError, /* Constraint type */
  97296. Index *pIdx /* The index that triggers the constraint */
  97297. ){
  97298. char *zErr;
  97299. int j;
  97300. StrAccum errMsg;
  97301. Table *pTab = pIdx->pTable;
  97302. sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
  97303. if( pIdx->aColExpr ){
  97304. sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName);
  97305. }else{
  97306. for(j=0; j<pIdx->nKeyCol; j++){
  97307. char *zCol;
  97308. assert( pIdx->aiColumn[j]>=0 );
  97309. zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  97310. if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
  97311. sqlite3XPrintf(&errMsg, "%s.%s", pTab->zName, zCol);
  97312. }
  97313. }
  97314. zErr = sqlite3StrAccumFinish(&errMsg);
  97315. sqlite3HaltConstraint(pParse,
  97316. IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
  97317. : SQLITE_CONSTRAINT_UNIQUE,
  97318. onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
  97319. }
  97320. /*
  97321. ** Code an OP_Halt due to non-unique rowid.
  97322. */
  97323. SQLITE_PRIVATE void sqlite3RowidConstraint(
  97324. Parse *pParse, /* Parsing context */
  97325. int onError, /* Conflict resolution algorithm */
  97326. Table *pTab /* The table with the non-unique rowid */
  97327. ){
  97328. char *zMsg;
  97329. int rc;
  97330. if( pTab->iPKey>=0 ){
  97331. zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
  97332. pTab->aCol[pTab->iPKey].zName);
  97333. rc = SQLITE_CONSTRAINT_PRIMARYKEY;
  97334. }else{
  97335. zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
  97336. rc = SQLITE_CONSTRAINT_ROWID;
  97337. }
  97338. sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
  97339. P5_ConstraintUnique);
  97340. }
  97341. /*
  97342. ** Check to see if pIndex uses the collating sequence pColl. Return
  97343. ** true if it does and false if it does not.
  97344. */
  97345. #ifndef SQLITE_OMIT_REINDEX
  97346. static int collationMatch(const char *zColl, Index *pIndex){
  97347. int i;
  97348. assert( zColl!=0 );
  97349. for(i=0; i<pIndex->nColumn; i++){
  97350. const char *z = pIndex->azColl[i];
  97351. assert( z!=0 || pIndex->aiColumn[i]<0 );
  97352. if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
  97353. return 1;
  97354. }
  97355. }
  97356. return 0;
  97357. }
  97358. #endif
  97359. /*
  97360. ** Recompute all indices of pTab that use the collating sequence pColl.
  97361. ** If pColl==0 then recompute all indices of pTab.
  97362. */
  97363. #ifndef SQLITE_OMIT_REINDEX
  97364. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  97365. Index *pIndex; /* An index associated with pTab */
  97366. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  97367. if( zColl==0 || collationMatch(zColl, pIndex) ){
  97368. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  97369. sqlite3BeginWriteOperation(pParse, 0, iDb);
  97370. sqlite3RefillIndex(pParse, pIndex, -1);
  97371. }
  97372. }
  97373. }
  97374. #endif
  97375. /*
  97376. ** Recompute all indices of all tables in all databases where the
  97377. ** indices use the collating sequence pColl. If pColl==0 then recompute
  97378. ** all indices everywhere.
  97379. */
  97380. #ifndef SQLITE_OMIT_REINDEX
  97381. static void reindexDatabases(Parse *pParse, char const *zColl){
  97382. Db *pDb; /* A single database */
  97383. int iDb; /* The database index number */
  97384. sqlite3 *db = pParse->db; /* The database connection */
  97385. HashElem *k; /* For looping over tables in pDb */
  97386. Table *pTab; /* A table in the database */
  97387. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  97388. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  97389. assert( pDb!=0 );
  97390. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  97391. pTab = (Table*)sqliteHashData(k);
  97392. reindexTable(pParse, pTab, zColl);
  97393. }
  97394. }
  97395. }
  97396. #endif
  97397. /*
  97398. ** Generate code for the REINDEX command.
  97399. **
  97400. ** REINDEX -- 1
  97401. ** REINDEX <collation> -- 2
  97402. ** REINDEX ?<database>.?<tablename> -- 3
  97403. ** REINDEX ?<database>.?<indexname> -- 4
  97404. **
  97405. ** Form 1 causes all indices in all attached databases to be rebuilt.
  97406. ** Form 2 rebuilds all indices in all databases that use the named
  97407. ** collating function. Forms 3 and 4 rebuild the named index or all
  97408. ** indices associated with the named table.
  97409. */
  97410. #ifndef SQLITE_OMIT_REINDEX
  97411. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  97412. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  97413. char *z; /* Name of a table or index */
  97414. const char *zDb; /* Name of the database */
  97415. Table *pTab; /* A table in the database */
  97416. Index *pIndex; /* An index associated with pTab */
  97417. int iDb; /* The database index number */
  97418. sqlite3 *db = pParse->db; /* The database connection */
  97419. Token *pObjName; /* Name of the table or index to be reindexed */
  97420. /* Read the database schema. If an error occurs, leave an error message
  97421. ** and code in pParse and return NULL. */
  97422. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  97423. return;
  97424. }
  97425. if( pName1==0 ){
  97426. reindexDatabases(pParse, 0);
  97427. return;
  97428. }else if( NEVER(pName2==0) || pName2->z==0 ){
  97429. char *zColl;
  97430. assert( pName1->z );
  97431. zColl = sqlite3NameFromToken(pParse->db, pName1);
  97432. if( !zColl ) return;
  97433. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  97434. if( pColl ){
  97435. reindexDatabases(pParse, zColl);
  97436. sqlite3DbFree(db, zColl);
  97437. return;
  97438. }
  97439. sqlite3DbFree(db, zColl);
  97440. }
  97441. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  97442. if( iDb<0 ) return;
  97443. z = sqlite3NameFromToken(db, pObjName);
  97444. if( z==0 ) return;
  97445. zDb = db->aDb[iDb].zDbSName;
  97446. pTab = sqlite3FindTable(db, z, zDb);
  97447. if( pTab ){
  97448. reindexTable(pParse, pTab, 0);
  97449. sqlite3DbFree(db, z);
  97450. return;
  97451. }
  97452. pIndex = sqlite3FindIndex(db, z, zDb);
  97453. sqlite3DbFree(db, z);
  97454. if( pIndex ){
  97455. sqlite3BeginWriteOperation(pParse, 0, iDb);
  97456. sqlite3RefillIndex(pParse, pIndex, -1);
  97457. return;
  97458. }
  97459. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  97460. }
  97461. #endif
  97462. /*
  97463. ** Return a KeyInfo structure that is appropriate for the given Index.
  97464. **
  97465. ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
  97466. ** when it has finished using it.
  97467. */
  97468. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
  97469. int i;
  97470. int nCol = pIdx->nColumn;
  97471. int nKey = pIdx->nKeyCol;
  97472. KeyInfo *pKey;
  97473. if( pParse->nErr ) return 0;
  97474. if( pIdx->uniqNotNull ){
  97475. pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
  97476. }else{
  97477. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
  97478. }
  97479. if( pKey ){
  97480. assert( sqlite3KeyInfoIsWriteable(pKey) );
  97481. for(i=0; i<nCol; i++){
  97482. const char *zColl = pIdx->azColl[i];
  97483. pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
  97484. sqlite3LocateCollSeq(pParse, zColl);
  97485. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  97486. }
  97487. if( pParse->nErr ){
  97488. sqlite3KeyInfoUnref(pKey);
  97489. pKey = 0;
  97490. }
  97491. }
  97492. return pKey;
  97493. }
  97494. #ifndef SQLITE_OMIT_CTE
  97495. /*
  97496. ** This routine is invoked once per CTE by the parser while parsing a
  97497. ** WITH clause.
  97498. */
  97499. SQLITE_PRIVATE With *sqlite3WithAdd(
  97500. Parse *pParse, /* Parsing context */
  97501. With *pWith, /* Existing WITH clause, or NULL */
  97502. Token *pName, /* Name of the common-table */
  97503. ExprList *pArglist, /* Optional column name list for the table */
  97504. Select *pQuery /* Query used to initialize the table */
  97505. ){
  97506. sqlite3 *db = pParse->db;
  97507. With *pNew;
  97508. char *zName;
  97509. /* Check that the CTE name is unique within this WITH clause. If
  97510. ** not, store an error in the Parse structure. */
  97511. zName = sqlite3NameFromToken(pParse->db, pName);
  97512. if( zName && pWith ){
  97513. int i;
  97514. for(i=0; i<pWith->nCte; i++){
  97515. if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
  97516. sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
  97517. }
  97518. }
  97519. }
  97520. if( pWith ){
  97521. int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
  97522. pNew = sqlite3DbRealloc(db, pWith, nByte);
  97523. }else{
  97524. pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
  97525. }
  97526. assert( (pNew!=0 && zName!=0) || db->mallocFailed );
  97527. if( db->mallocFailed ){
  97528. sqlite3ExprListDelete(db, pArglist);
  97529. sqlite3SelectDelete(db, pQuery);
  97530. sqlite3DbFree(db, zName);
  97531. pNew = pWith;
  97532. }else{
  97533. pNew->a[pNew->nCte].pSelect = pQuery;
  97534. pNew->a[pNew->nCte].pCols = pArglist;
  97535. pNew->a[pNew->nCte].zName = zName;
  97536. pNew->a[pNew->nCte].zCteErr = 0;
  97537. pNew->nCte++;
  97538. }
  97539. return pNew;
  97540. }
  97541. /*
  97542. ** Free the contents of the With object passed as the second argument.
  97543. */
  97544. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
  97545. if( pWith ){
  97546. int i;
  97547. for(i=0; i<pWith->nCte; i++){
  97548. struct Cte *pCte = &pWith->a[i];
  97549. sqlite3ExprListDelete(db, pCte->pCols);
  97550. sqlite3SelectDelete(db, pCte->pSelect);
  97551. sqlite3DbFree(db, pCte->zName);
  97552. }
  97553. sqlite3DbFree(db, pWith);
  97554. }
  97555. }
  97556. #endif /* !defined(SQLITE_OMIT_CTE) */
  97557. /************** End of build.c ***********************************************/
  97558. /************** Begin file callback.c ****************************************/
  97559. /*
  97560. ** 2005 May 23
  97561. **
  97562. ** The author disclaims copyright to this source code. In place of
  97563. ** a legal notice, here is a blessing:
  97564. **
  97565. ** May you do good and not evil.
  97566. ** May you find forgiveness for yourself and forgive others.
  97567. ** May you share freely, never taking more than you give.
  97568. **
  97569. *************************************************************************
  97570. **
  97571. ** This file contains functions used to access the internal hash tables
  97572. ** of user defined functions and collation sequences.
  97573. */
  97574. /* #include "sqliteInt.h" */
  97575. /*
  97576. ** Invoke the 'collation needed' callback to request a collation sequence
  97577. ** in the encoding enc of name zName, length nName.
  97578. */
  97579. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  97580. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  97581. if( db->xCollNeeded ){
  97582. char *zExternal = sqlite3DbStrDup(db, zName);
  97583. if( !zExternal ) return;
  97584. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  97585. sqlite3DbFree(db, zExternal);
  97586. }
  97587. #ifndef SQLITE_OMIT_UTF16
  97588. if( db->xCollNeeded16 ){
  97589. char const *zExternal;
  97590. sqlite3_value *pTmp = sqlite3ValueNew(db);
  97591. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  97592. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  97593. if( zExternal ){
  97594. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  97595. }
  97596. sqlite3ValueFree(pTmp);
  97597. }
  97598. #endif
  97599. }
  97600. /*
  97601. ** This routine is called if the collation factory fails to deliver a
  97602. ** collation function in the best encoding but there may be other versions
  97603. ** of this collation function (for other text encodings) available. Use one
  97604. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  97605. ** possible.
  97606. */
  97607. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  97608. CollSeq *pColl2;
  97609. char *z = pColl->zName;
  97610. int i;
  97611. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  97612. for(i=0; i<3; i++){
  97613. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  97614. if( pColl2->xCmp!=0 ){
  97615. memcpy(pColl, pColl2, sizeof(CollSeq));
  97616. pColl->xDel = 0; /* Do not copy the destructor */
  97617. return SQLITE_OK;
  97618. }
  97619. }
  97620. return SQLITE_ERROR;
  97621. }
  97622. /*
  97623. ** This function is responsible for invoking the collation factory callback
  97624. ** or substituting a collation sequence of a different encoding when the
  97625. ** requested collation sequence is not available in the desired encoding.
  97626. **
  97627. ** If it is not NULL, then pColl must point to the database native encoding
  97628. ** collation sequence with name zName, length nName.
  97629. **
  97630. ** The return value is either the collation sequence to be used in database
  97631. ** db for collation type name zName, length nName, or NULL, if no collation
  97632. ** sequence can be found. If no collation is found, leave an error message.
  97633. **
  97634. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  97635. */
  97636. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  97637. Parse *pParse, /* Parsing context */
  97638. u8 enc, /* The desired encoding for the collating sequence */
  97639. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  97640. const char *zName /* Collating sequence name */
  97641. ){
  97642. CollSeq *p;
  97643. sqlite3 *db = pParse->db;
  97644. p = pColl;
  97645. if( !p ){
  97646. p = sqlite3FindCollSeq(db, enc, zName, 0);
  97647. }
  97648. if( !p || !p->xCmp ){
  97649. /* No collation sequence of this type for this encoding is registered.
  97650. ** Call the collation factory to see if it can supply us with one.
  97651. */
  97652. callCollNeeded(db, enc, zName);
  97653. p = sqlite3FindCollSeq(db, enc, zName, 0);
  97654. }
  97655. if( p && !p->xCmp && synthCollSeq(db, p) ){
  97656. p = 0;
  97657. }
  97658. assert( !p || p->xCmp );
  97659. if( p==0 ){
  97660. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  97661. }
  97662. return p;
  97663. }
  97664. /*
  97665. ** This routine is called on a collation sequence before it is used to
  97666. ** check that it is defined. An undefined collation sequence exists when
  97667. ** a database is loaded that contains references to collation sequences
  97668. ** that have not been defined by sqlite3_create_collation() etc.
  97669. **
  97670. ** If required, this routine calls the 'collation needed' callback to
  97671. ** request a definition of the collating sequence. If this doesn't work,
  97672. ** an equivalent collating sequence that uses a text encoding different
  97673. ** from the main database is substituted, if one is available.
  97674. */
  97675. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  97676. if( pColl ){
  97677. const char *zName = pColl->zName;
  97678. sqlite3 *db = pParse->db;
  97679. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  97680. if( !p ){
  97681. return SQLITE_ERROR;
  97682. }
  97683. assert( p==pColl );
  97684. }
  97685. return SQLITE_OK;
  97686. }
  97687. /*
  97688. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  97689. ** specified by zName and nName is not found and parameter 'create' is
  97690. ** true, then create a new entry. Otherwise return NULL.
  97691. **
  97692. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  97693. ** array of three CollSeq structures. The first is the collation sequence
  97694. ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  97695. **
  97696. ** Stored immediately after the three collation sequences is a copy of
  97697. ** the collation sequence name. A pointer to this string is stored in
  97698. ** each collation sequence structure.
  97699. */
  97700. static CollSeq *findCollSeqEntry(
  97701. sqlite3 *db, /* Database connection */
  97702. const char *zName, /* Name of the collating sequence */
  97703. int create /* Create a new entry if true */
  97704. ){
  97705. CollSeq *pColl;
  97706. pColl = sqlite3HashFind(&db->aCollSeq, zName);
  97707. if( 0==pColl && create ){
  97708. int nName = sqlite3Strlen30(zName);
  97709. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
  97710. if( pColl ){
  97711. CollSeq *pDel = 0;
  97712. pColl[0].zName = (char*)&pColl[3];
  97713. pColl[0].enc = SQLITE_UTF8;
  97714. pColl[1].zName = (char*)&pColl[3];
  97715. pColl[1].enc = SQLITE_UTF16LE;
  97716. pColl[2].zName = (char*)&pColl[3];
  97717. pColl[2].enc = SQLITE_UTF16BE;
  97718. memcpy(pColl[0].zName, zName, nName);
  97719. pColl[0].zName[nName] = 0;
  97720. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
  97721. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  97722. ** return the pColl pointer to be deleted (because it wasn't added
  97723. ** to the hash table).
  97724. */
  97725. assert( pDel==0 || pDel==pColl );
  97726. if( pDel!=0 ){
  97727. sqlite3OomFault(db);
  97728. sqlite3DbFree(db, pDel);
  97729. pColl = 0;
  97730. }
  97731. }
  97732. }
  97733. return pColl;
  97734. }
  97735. /*
  97736. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  97737. ** Return the CollSeq* pointer for the collation sequence named zName
  97738. ** for the encoding 'enc' from the database 'db'.
  97739. **
  97740. ** If the entry specified is not found and 'create' is true, then create a
  97741. ** new entry. Otherwise return NULL.
  97742. **
  97743. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  97744. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  97745. ** if necessary and generates an error message if the collating sequence
  97746. ** cannot be found.
  97747. **
  97748. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  97749. */
  97750. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  97751. sqlite3 *db,
  97752. u8 enc,
  97753. const char *zName,
  97754. int create
  97755. ){
  97756. CollSeq *pColl;
  97757. if( zName ){
  97758. pColl = findCollSeqEntry(db, zName, create);
  97759. }else{
  97760. pColl = db->pDfltColl;
  97761. }
  97762. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  97763. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  97764. if( pColl ) pColl += enc-1;
  97765. return pColl;
  97766. }
  97767. /* During the search for the best function definition, this procedure
  97768. ** is called to test how well the function passed as the first argument
  97769. ** matches the request for a function with nArg arguments in a system
  97770. ** that uses encoding enc. The value returned indicates how well the
  97771. ** request is matched. A higher value indicates a better match.
  97772. **
  97773. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  97774. ** is also -1. In other words, we are searching for a function that
  97775. ** takes a variable number of arguments.
  97776. **
  97777. ** If nArg is -2 that means that we are searching for any function
  97778. ** regardless of the number of arguments it uses, so return a positive
  97779. ** match score for any
  97780. **
  97781. ** The returned value is always between 0 and 6, as follows:
  97782. **
  97783. ** 0: Not a match.
  97784. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  97785. ** 2: UTF16 byte order change required and function takes any number of args.
  97786. ** 3: encoding matches and function takes any number of arguments
  97787. ** 4: UTF8/16 conversion required - argument count matches exactly
  97788. ** 5: UTF16 byte order conversion required - argument count matches exactly
  97789. ** 6: Perfect match: encoding and argument count match exactly.
  97790. **
  97791. ** If nArg==(-2) then any function with a non-null xSFunc is
  97792. ** a perfect match and any function with xSFunc NULL is
  97793. ** a non-match.
  97794. */
  97795. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  97796. static int matchQuality(
  97797. FuncDef *p, /* The function we are evaluating for match quality */
  97798. int nArg, /* Desired number of arguments. (-1)==any */
  97799. u8 enc /* Desired text encoding */
  97800. ){
  97801. int match;
  97802. /* nArg of -2 is a special case */
  97803. if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
  97804. /* Wrong number of arguments means "no match" */
  97805. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  97806. /* Give a better score to a function with a specific number of arguments
  97807. ** than to function that accepts any number of arguments. */
  97808. if( p->nArg==nArg ){
  97809. match = 4;
  97810. }else{
  97811. match = 1;
  97812. }
  97813. /* Bonus points if the text encoding matches */
  97814. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  97815. match += 2; /* Exact encoding match */
  97816. }else if( (enc & p->funcFlags & 2)!=0 ){
  97817. match += 1; /* Both are UTF16, but with different byte orders */
  97818. }
  97819. return match;
  97820. }
  97821. /*
  97822. ** Search a FuncDefHash for a function with the given name. Return
  97823. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  97824. */
  97825. static FuncDef *functionSearch(
  97826. int h, /* Hash of the name */
  97827. const char *zFunc /* Name of function */
  97828. ){
  97829. FuncDef *p;
  97830. for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
  97831. if( sqlite3StrICmp(p->zName, zFunc)==0 ){
  97832. return p;
  97833. }
  97834. }
  97835. return 0;
  97836. }
  97837. /*
  97838. ** Insert a new FuncDef into a FuncDefHash hash table.
  97839. */
  97840. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
  97841. FuncDef *aDef, /* List of global functions to be inserted */
  97842. int nDef /* Length of the apDef[] list */
  97843. ){
  97844. int i;
  97845. for(i=0; i<nDef; i++){
  97846. FuncDef *pOther;
  97847. const char *zName = aDef[i].zName;
  97848. int nName = sqlite3Strlen30(zName);
  97849. int h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
  97850. pOther = functionSearch(h, zName);
  97851. if( pOther ){
  97852. assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
  97853. aDef[i].pNext = pOther->pNext;
  97854. pOther->pNext = &aDef[i];
  97855. }else{
  97856. aDef[i].pNext = 0;
  97857. aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
  97858. sqlite3BuiltinFunctions.a[h] = &aDef[i];
  97859. }
  97860. }
  97861. }
  97862. /*
  97863. ** Locate a user function given a name, a number of arguments and a flag
  97864. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  97865. ** pointer to the FuncDef structure that defines that function, or return
  97866. ** NULL if the function does not exist.
  97867. **
  97868. ** If the createFlag argument is true, then a new (blank) FuncDef
  97869. ** structure is created and liked into the "db" structure if a
  97870. ** no matching function previously existed.
  97871. **
  97872. ** If nArg is -2, then the first valid function found is returned. A
  97873. ** function is valid if xSFunc is non-zero. The nArg==(-2)
  97874. ** case is used to see if zName is a valid function name for some number
  97875. ** of arguments. If nArg is -2, then createFlag must be 0.
  97876. **
  97877. ** If createFlag is false, then a function with the required name and
  97878. ** number of arguments may be returned even if the eTextRep flag does not
  97879. ** match that requested.
  97880. */
  97881. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  97882. sqlite3 *db, /* An open database */
  97883. const char *zName, /* Name of the function. zero-terminated */
  97884. int nArg, /* Number of arguments. -1 means any number */
  97885. u8 enc, /* Preferred text encoding */
  97886. u8 createFlag /* Create new entry if true and does not otherwise exist */
  97887. ){
  97888. FuncDef *p; /* Iterator variable */
  97889. FuncDef *pBest = 0; /* Best match found so far */
  97890. int bestScore = 0; /* Score of best match */
  97891. int h; /* Hash value */
  97892. int nName; /* Length of the name */
  97893. assert( nArg>=(-2) );
  97894. assert( nArg>=(-1) || createFlag==0 );
  97895. nName = sqlite3Strlen30(zName);
  97896. /* First search for a match amongst the application-defined functions.
  97897. */
  97898. p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
  97899. while( p ){
  97900. int score = matchQuality(p, nArg, enc);
  97901. if( score>bestScore ){
  97902. pBest = p;
  97903. bestScore = score;
  97904. }
  97905. p = p->pNext;
  97906. }
  97907. /* If no match is found, search the built-in functions.
  97908. **
  97909. ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  97910. ** functions even if a prior app-defined function was found. And give
  97911. ** priority to built-in functions.
  97912. **
  97913. ** Except, if createFlag is true, that means that we are trying to
  97914. ** install a new function. Whatever FuncDef structure is returned it will
  97915. ** have fields overwritten with new information appropriate for the
  97916. ** new function. But the FuncDefs for built-in functions are read-only.
  97917. ** So we must not search for built-ins when creating a new function.
  97918. */
  97919. if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
  97920. bestScore = 0;
  97921. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
  97922. p = functionSearch(h, zName);
  97923. while( p ){
  97924. int score = matchQuality(p, nArg, enc);
  97925. if( score>bestScore ){
  97926. pBest = p;
  97927. bestScore = score;
  97928. }
  97929. p = p->pNext;
  97930. }
  97931. }
  97932. /* If the createFlag parameter is true and the search did not reveal an
  97933. ** exact match for the name, number of arguments and encoding, then add a
  97934. ** new entry to the hash table and return it.
  97935. */
  97936. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  97937. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  97938. FuncDef *pOther;
  97939. pBest->zName = (const char*)&pBest[1];
  97940. pBest->nArg = (u16)nArg;
  97941. pBest->funcFlags = enc;
  97942. memcpy((char*)&pBest[1], zName, nName+1);
  97943. pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
  97944. if( pOther==pBest ){
  97945. sqlite3DbFree(db, pBest);
  97946. sqlite3OomFault(db);
  97947. return 0;
  97948. }else{
  97949. pBest->pNext = pOther;
  97950. }
  97951. }
  97952. if( pBest && (pBest->xSFunc || createFlag) ){
  97953. return pBest;
  97954. }
  97955. return 0;
  97956. }
  97957. /*
  97958. ** Free all resources held by the schema structure. The void* argument points
  97959. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  97960. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  97961. ** of the schema hash tables).
  97962. **
  97963. ** The Schema.cache_size variable is not cleared.
  97964. */
  97965. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  97966. Hash temp1;
  97967. Hash temp2;
  97968. HashElem *pElem;
  97969. Schema *pSchema = (Schema *)p;
  97970. temp1 = pSchema->tblHash;
  97971. temp2 = pSchema->trigHash;
  97972. sqlite3HashInit(&pSchema->trigHash);
  97973. sqlite3HashClear(&pSchema->idxHash);
  97974. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  97975. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  97976. }
  97977. sqlite3HashClear(&temp2);
  97978. sqlite3HashInit(&pSchema->tblHash);
  97979. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  97980. Table *pTab = sqliteHashData(pElem);
  97981. sqlite3DeleteTable(0, pTab);
  97982. }
  97983. sqlite3HashClear(&temp1);
  97984. sqlite3HashClear(&pSchema->fkeyHash);
  97985. pSchema->pSeqTab = 0;
  97986. if( pSchema->schemaFlags & DB_SchemaLoaded ){
  97987. pSchema->iGeneration++;
  97988. pSchema->schemaFlags &= ~DB_SchemaLoaded;
  97989. }
  97990. }
  97991. /*
  97992. ** Find and return the schema associated with a BTree. Create
  97993. ** a new one if necessary.
  97994. */
  97995. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  97996. Schema * p;
  97997. if( pBt ){
  97998. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  97999. }else{
  98000. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  98001. }
  98002. if( !p ){
  98003. sqlite3OomFault(db);
  98004. }else if ( 0==p->file_format ){
  98005. sqlite3HashInit(&p->tblHash);
  98006. sqlite3HashInit(&p->idxHash);
  98007. sqlite3HashInit(&p->trigHash);
  98008. sqlite3HashInit(&p->fkeyHash);
  98009. p->enc = SQLITE_UTF8;
  98010. }
  98011. return p;
  98012. }
  98013. /************** End of callback.c ********************************************/
  98014. /************** Begin file delete.c ******************************************/
  98015. /*
  98016. ** 2001 September 15
  98017. **
  98018. ** The author disclaims copyright to this source code. In place of
  98019. ** a legal notice, here is a blessing:
  98020. **
  98021. ** May you do good and not evil.
  98022. ** May you find forgiveness for yourself and forgive others.
  98023. ** May you share freely, never taking more than you give.
  98024. **
  98025. *************************************************************************
  98026. ** This file contains C code routines that are called by the parser
  98027. ** in order to generate code for DELETE FROM statements.
  98028. */
  98029. /* #include "sqliteInt.h" */
  98030. /*
  98031. ** While a SrcList can in general represent multiple tables and subqueries
  98032. ** (as in the FROM clause of a SELECT statement) in this case it contains
  98033. ** the name of a single table, as one might find in an INSERT, DELETE,
  98034. ** or UPDATE statement. Look up that table in the symbol table and
  98035. ** return a pointer. Set an error message and return NULL if the table
  98036. ** name is not found or if any other error occurs.
  98037. **
  98038. ** The following fields are initialized appropriate in pSrc:
  98039. **
  98040. ** pSrc->a[0].pTab Pointer to the Table object
  98041. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  98042. **
  98043. */
  98044. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  98045. struct SrcList_item *pItem = pSrc->a;
  98046. Table *pTab;
  98047. assert( pItem && pSrc->nSrc==1 );
  98048. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  98049. sqlite3DeleteTable(pParse->db, pItem->pTab);
  98050. pItem->pTab = pTab;
  98051. if( pTab ){
  98052. pTab->nTabRef++;
  98053. }
  98054. if( sqlite3IndexedByLookup(pParse, pItem) ){
  98055. pTab = 0;
  98056. }
  98057. return pTab;
  98058. }
  98059. /*
  98060. ** Check to make sure the given table is writable. If it is not
  98061. ** writable, generate an error message and return 1. If it is
  98062. ** writable return 0;
  98063. */
  98064. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  98065. /* A table is not writable under the following circumstances:
  98066. **
  98067. ** 1) It is a virtual table and no implementation of the xUpdate method
  98068. ** has been provided, or
  98069. ** 2) It is a system table (i.e. sqlite_master), this call is not
  98070. ** part of a nested parse and writable_schema pragma has not
  98071. ** been specified.
  98072. **
  98073. ** In either case leave an error message in pParse and return non-zero.
  98074. */
  98075. if( ( IsVirtual(pTab)
  98076. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  98077. || ( (pTab->tabFlags & TF_Readonly)!=0
  98078. && (pParse->db->flags & SQLITE_WriteSchema)==0
  98079. && pParse->nested==0 )
  98080. ){
  98081. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  98082. return 1;
  98083. }
  98084. #ifndef SQLITE_OMIT_VIEW
  98085. if( !viewOk && pTab->pSelect ){
  98086. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  98087. return 1;
  98088. }
  98089. #endif
  98090. return 0;
  98091. }
  98092. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  98093. /*
  98094. ** Evaluate a view and store its result in an ephemeral table. The
  98095. ** pWhere argument is an optional WHERE clause that restricts the
  98096. ** set of rows in the view that are to be added to the ephemeral table.
  98097. */
  98098. SQLITE_PRIVATE void sqlite3MaterializeView(
  98099. Parse *pParse, /* Parsing context */
  98100. Table *pView, /* View definition */
  98101. Expr *pWhere, /* Optional WHERE clause to be added */
  98102. int iCur /* Cursor number for ephemeral table */
  98103. ){
  98104. SelectDest dest;
  98105. Select *pSel;
  98106. SrcList *pFrom;
  98107. sqlite3 *db = pParse->db;
  98108. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  98109. pWhere = sqlite3ExprDup(db, pWhere, 0);
  98110. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  98111. if( pFrom ){
  98112. assert( pFrom->nSrc==1 );
  98113. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  98114. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
  98115. assert( pFrom->a[0].pOn==0 );
  98116. assert( pFrom->a[0].pUsing==0 );
  98117. }
  98118. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0,
  98119. SF_IncludeHidden, 0, 0);
  98120. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  98121. sqlite3Select(pParse, pSel, &dest);
  98122. sqlite3SelectDelete(db, pSel);
  98123. }
  98124. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  98125. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  98126. /*
  98127. ** Generate an expression tree to implement the WHERE, ORDER BY,
  98128. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  98129. **
  98130. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  98131. ** \__________________________/
  98132. ** pLimitWhere (pInClause)
  98133. */
  98134. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  98135. Parse *pParse, /* The parser context */
  98136. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  98137. Expr *pWhere, /* The WHERE clause. May be null */
  98138. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  98139. Expr *pLimit, /* The LIMIT clause. May be null */
  98140. Expr *pOffset, /* The OFFSET clause. May be null */
  98141. char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
  98142. ){
  98143. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  98144. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  98145. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  98146. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  98147. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  98148. Select *pSelect = NULL; /* Complete SELECT tree */
  98149. /* Check that there isn't an ORDER BY without a LIMIT clause.
  98150. */
  98151. if( pOrderBy && (pLimit == 0) ) {
  98152. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  98153. goto limit_where_cleanup;
  98154. }
  98155. /* We only need to generate a select expression if there
  98156. ** is a limit/offset term to enforce.
  98157. */
  98158. if( pLimit == 0 ) {
  98159. /* if pLimit is null, pOffset will always be null as well. */
  98160. assert( pOffset == 0 );
  98161. return pWhere;
  98162. }
  98163. /* Generate a select expression tree to enforce the limit/offset
  98164. ** term for the DELETE or UPDATE statement. For example:
  98165. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  98166. ** becomes:
  98167. ** DELETE FROM table_a WHERE rowid IN (
  98168. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  98169. ** );
  98170. */
  98171. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0);
  98172. if( pSelectRowid == 0 ) goto limit_where_cleanup;
  98173. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  98174. if( pEList == 0 ) goto limit_where_cleanup;
  98175. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  98176. ** and the SELECT subtree. */
  98177. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  98178. if( pSelectSrc == 0 ) {
  98179. sqlite3ExprListDelete(pParse->db, pEList);
  98180. goto limit_where_cleanup;
  98181. }
  98182. /* generate the SELECT expression tree. */
  98183. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  98184. pOrderBy,0,pLimit,pOffset);
  98185. if( pSelect == 0 ) return 0;
  98186. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  98187. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0);
  98188. pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0) : 0;
  98189. sqlite3PExprAddSelect(pParse, pInClause, pSelect);
  98190. return pInClause;
  98191. limit_where_cleanup:
  98192. sqlite3ExprDelete(pParse->db, pWhere);
  98193. sqlite3ExprListDelete(pParse->db, pOrderBy);
  98194. sqlite3ExprDelete(pParse->db, pLimit);
  98195. sqlite3ExprDelete(pParse->db, pOffset);
  98196. return 0;
  98197. }
  98198. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
  98199. /* && !defined(SQLITE_OMIT_SUBQUERY) */
  98200. /*
  98201. ** Generate code for a DELETE FROM statement.
  98202. **
  98203. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  98204. ** \________/ \________________/
  98205. ** pTabList pWhere
  98206. */
  98207. SQLITE_PRIVATE void sqlite3DeleteFrom(
  98208. Parse *pParse, /* The parser context */
  98209. SrcList *pTabList, /* The table from which we should delete things */
  98210. Expr *pWhere /* The WHERE clause. May be null */
  98211. ){
  98212. Vdbe *v; /* The virtual database engine */
  98213. Table *pTab; /* The table from which records will be deleted */
  98214. int i; /* Loop counter */
  98215. WhereInfo *pWInfo; /* Information about the WHERE clause */
  98216. Index *pIdx; /* For looping over indices of the table */
  98217. int iTabCur; /* Cursor number for the table */
  98218. int iDataCur = 0; /* VDBE cursor for the canonical data source */
  98219. int iIdxCur = 0; /* Cursor number of the first index */
  98220. int nIdx; /* Number of indices */
  98221. sqlite3 *db; /* Main database structure */
  98222. AuthContext sContext; /* Authorization context */
  98223. NameContext sNC; /* Name context to resolve expressions in */
  98224. int iDb; /* Database number */
  98225. int memCnt = -1; /* Memory cell used for change counting */
  98226. int rcauth; /* Value returned by authorization callback */
  98227. int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */
  98228. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  98229. u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
  98230. Index *pPk; /* The PRIMARY KEY index on the table */
  98231. int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
  98232. i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
  98233. int iKey; /* Memory cell holding key of row to be deleted */
  98234. i16 nKey; /* Number of memory cells in the row key */
  98235. int iEphCur = 0; /* Ephemeral table holding all primary key values */
  98236. int iRowSet = 0; /* Register for rowset of rows to delete */
  98237. int addrBypass = 0; /* Address of jump over the delete logic */
  98238. int addrLoop = 0; /* Top of the delete loop */
  98239. int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
  98240. int bComplex; /* True if there are triggers or FKs or
  98241. ** subqueries in the WHERE clause */
  98242. #ifndef SQLITE_OMIT_TRIGGER
  98243. int isView; /* True if attempting to delete from a view */
  98244. Trigger *pTrigger; /* List of table triggers, if required */
  98245. #endif
  98246. memset(&sContext, 0, sizeof(sContext));
  98247. db = pParse->db;
  98248. if( pParse->nErr || db->mallocFailed ){
  98249. goto delete_from_cleanup;
  98250. }
  98251. assert( pTabList->nSrc==1 );
  98252. /* Locate the table which we want to delete. This table has to be
  98253. ** put in an SrcList structure because some of the subroutines we
  98254. ** will be calling are designed to work with multiple tables and expect
  98255. ** an SrcList* parameter instead of just a Table* parameter.
  98256. */
  98257. pTab = sqlite3SrcListLookup(pParse, pTabList);
  98258. if( pTab==0 ) goto delete_from_cleanup;
  98259. /* Figure out if we have any triggers and if the table being
  98260. ** deleted from is a view
  98261. */
  98262. #ifndef SQLITE_OMIT_TRIGGER
  98263. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  98264. isView = pTab->pSelect!=0;
  98265. bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
  98266. #else
  98267. # define pTrigger 0
  98268. # define isView 0
  98269. #endif
  98270. #ifdef SQLITE_OMIT_VIEW
  98271. # undef isView
  98272. # define isView 0
  98273. #endif
  98274. /* If pTab is really a view, make sure it has been initialized.
  98275. */
  98276. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  98277. goto delete_from_cleanup;
  98278. }
  98279. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  98280. goto delete_from_cleanup;
  98281. }
  98282. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  98283. assert( iDb<db->nDb );
  98284. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
  98285. db->aDb[iDb].zDbSName);
  98286. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  98287. if( rcauth==SQLITE_DENY ){
  98288. goto delete_from_cleanup;
  98289. }
  98290. assert(!isView || pTrigger);
  98291. /* Assign cursor numbers to the table and all its indices.
  98292. */
  98293. assert( pTabList->nSrc==1 );
  98294. iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
  98295. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  98296. pParse->nTab++;
  98297. }
  98298. /* Start the view context
  98299. */
  98300. if( isView ){
  98301. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  98302. }
  98303. /* Begin generating code.
  98304. */
  98305. v = sqlite3GetVdbe(pParse);
  98306. if( v==0 ){
  98307. goto delete_from_cleanup;
  98308. }
  98309. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  98310. sqlite3BeginWriteOperation(pParse, 1, iDb);
  98311. /* If we are trying to delete from a view, realize that view into
  98312. ** an ephemeral table.
  98313. */
  98314. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  98315. if( isView ){
  98316. sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
  98317. iDataCur = iIdxCur = iTabCur;
  98318. }
  98319. #endif
  98320. /* Resolve the column names in the WHERE clause.
  98321. */
  98322. memset(&sNC, 0, sizeof(sNC));
  98323. sNC.pParse = pParse;
  98324. sNC.pSrcList = pTabList;
  98325. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  98326. goto delete_from_cleanup;
  98327. }
  98328. /* Initialize the counter of the number of rows deleted, if
  98329. ** we are counting rows.
  98330. */
  98331. if( db->flags & SQLITE_CountRows ){
  98332. memCnt = ++pParse->nMem;
  98333. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  98334. }
  98335. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  98336. /* Special case: A DELETE without a WHERE clause deletes everything.
  98337. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  98338. ** this optimization caused the row change count (the value returned by
  98339. ** API function sqlite3_count_changes) to be set incorrectly.
  98340. **
  98341. ** The "rcauth==SQLITE_OK" terms is the
  98342. ** IMPLEMENATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
  98343. ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
  98344. ** the truncate optimization is disabled and all rows are deleted
  98345. ** individually.
  98346. */
  98347. if( rcauth==SQLITE_OK
  98348. && pWhere==0
  98349. && !bComplex
  98350. && !IsVirtual(pTab)
  98351. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  98352. && db->xPreUpdateCallback==0
  98353. #endif
  98354. ){
  98355. assert( !isView );
  98356. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  98357. if( HasRowid(pTab) ){
  98358. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  98359. pTab->zName, P4_STATIC);
  98360. }
  98361. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  98362. assert( pIdx->pSchema==pTab->pSchema );
  98363. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  98364. }
  98365. }else
  98366. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  98367. {
  98368. u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
  98369. if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
  98370. wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
  98371. if( HasRowid(pTab) ){
  98372. /* For a rowid table, initialize the RowSet to an empty set */
  98373. pPk = 0;
  98374. nPk = 1;
  98375. iRowSet = ++pParse->nMem;
  98376. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  98377. }else{
  98378. /* For a WITHOUT ROWID table, create an ephemeral table used to
  98379. ** hold all primary keys for rows to be deleted. */
  98380. pPk = sqlite3PrimaryKeyIndex(pTab);
  98381. assert( pPk!=0 );
  98382. nPk = pPk->nKeyCol;
  98383. iPk = pParse->nMem+1;
  98384. pParse->nMem += nPk;
  98385. iEphCur = pParse->nTab++;
  98386. addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
  98387. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  98388. }
  98389. /* Construct a query to find the rowid or primary key for every row
  98390. ** to be deleted, based on the WHERE clause. Set variable eOnePass
  98391. ** to indicate the strategy used to implement this delete:
  98392. **
  98393. ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
  98394. ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
  98395. ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
  98396. */
  98397. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
  98398. if( pWInfo==0 ) goto delete_from_cleanup;
  98399. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  98400. assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
  98401. assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
  98402. /* Keep track of the number of rows to be deleted */
  98403. if( db->flags & SQLITE_CountRows ){
  98404. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  98405. }
  98406. /* Extract the rowid or primary key for the current row */
  98407. if( pPk ){
  98408. for(i=0; i<nPk; i++){
  98409. assert( pPk->aiColumn[i]>=0 );
  98410. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  98411. pPk->aiColumn[i], iPk+i);
  98412. }
  98413. iKey = iPk;
  98414. }else{
  98415. iKey = pParse->nMem + 1;
  98416. iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
  98417. if( iKey>pParse->nMem ) pParse->nMem = iKey;
  98418. }
  98419. if( eOnePass!=ONEPASS_OFF ){
  98420. /* For ONEPASS, no need to store the rowid/primary-key. There is only
  98421. ** one, so just keep it in its register(s) and fall through to the
  98422. ** delete code. */
  98423. nKey = nPk; /* OP_Found will use an unpacked key */
  98424. aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
  98425. if( aToOpen==0 ){
  98426. sqlite3WhereEnd(pWInfo);
  98427. goto delete_from_cleanup;
  98428. }
  98429. memset(aToOpen, 1, nIdx+1);
  98430. aToOpen[nIdx+1] = 0;
  98431. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
  98432. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
  98433. if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
  98434. }else{
  98435. if( pPk ){
  98436. /* Add the PK key for this row to the temporary table */
  98437. iKey = ++pParse->nMem;
  98438. nKey = 0; /* Zero tells OP_Found to use a composite key */
  98439. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
  98440. sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
  98441. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
  98442. }else{
  98443. /* Add the rowid of the row to be deleted to the RowSet */
  98444. nKey = 1; /* OP_Seek always uses a single rowid */
  98445. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
  98446. }
  98447. }
  98448. /* If this DELETE cannot use the ONEPASS strategy, this is the
  98449. ** end of the WHERE loop */
  98450. if( eOnePass!=ONEPASS_OFF ){
  98451. addrBypass = sqlite3VdbeMakeLabel(v);
  98452. }else{
  98453. sqlite3WhereEnd(pWInfo);
  98454. }
  98455. /* Unless this is a view, open cursors for the table we are
  98456. ** deleting from and all its indices. If this is a view, then the
  98457. ** only effect this statement has is to fire the INSTEAD OF
  98458. ** triggers.
  98459. */
  98460. if( !isView ){
  98461. int iAddrOnce = 0;
  98462. if( eOnePass==ONEPASS_MULTI ){
  98463. iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  98464. }
  98465. testcase( IsVirtual(pTab) );
  98466. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
  98467. iTabCur, aToOpen, &iDataCur, &iIdxCur);
  98468. assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
  98469. assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
  98470. if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
  98471. }
  98472. /* Set up a loop over the rowids/primary-keys that were found in the
  98473. ** where-clause loop above.
  98474. */
  98475. if( eOnePass!=ONEPASS_OFF ){
  98476. assert( nKey==nPk ); /* OP_Found will use an unpacked key */
  98477. if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
  98478. assert( pPk!=0 || pTab->pSelect!=0 );
  98479. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
  98480. VdbeCoverage(v);
  98481. }
  98482. }else if( pPk ){
  98483. addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
  98484. sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
  98485. assert( nKey==0 ); /* OP_Found will use a composite key */
  98486. }else{
  98487. addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
  98488. VdbeCoverage(v);
  98489. assert( nKey==1 );
  98490. }
  98491. /* Delete the row */
  98492. #ifndef SQLITE_OMIT_VIRTUALTABLE
  98493. if( IsVirtual(pTab) ){
  98494. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  98495. sqlite3VtabMakeWritable(pParse, pTab);
  98496. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
  98497. sqlite3VdbeChangeP5(v, OE_Abort);
  98498. assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
  98499. sqlite3MayAbort(pParse);
  98500. if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
  98501. pParse->isMultiWrite = 0;
  98502. }
  98503. }else
  98504. #endif
  98505. {
  98506. int count = (pParse->nested==0); /* True to count changes */
  98507. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  98508. iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
  98509. }
  98510. /* End of the loop over all rowids/primary-keys. */
  98511. if( eOnePass!=ONEPASS_OFF ){
  98512. sqlite3VdbeResolveLabel(v, addrBypass);
  98513. sqlite3WhereEnd(pWInfo);
  98514. }else if( pPk ){
  98515. sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
  98516. sqlite3VdbeJumpHere(v, addrLoop);
  98517. }else{
  98518. sqlite3VdbeGoto(v, addrLoop);
  98519. sqlite3VdbeJumpHere(v, addrLoop);
  98520. }
  98521. } /* End non-truncate path */
  98522. /* Update the sqlite_sequence table by storing the content of the
  98523. ** maximum rowid counter values recorded while inserting into
  98524. ** autoincrement tables.
  98525. */
  98526. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  98527. sqlite3AutoincrementEnd(pParse);
  98528. }
  98529. /* Return the number of rows that were deleted. If this routine is
  98530. ** generating code because of a call to sqlite3NestedParse(), do not
  98531. ** invoke the callback function.
  98532. */
  98533. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  98534. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  98535. sqlite3VdbeSetNumCols(v, 1);
  98536. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  98537. }
  98538. delete_from_cleanup:
  98539. sqlite3AuthContextPop(&sContext);
  98540. sqlite3SrcListDelete(db, pTabList);
  98541. sqlite3ExprDelete(db, pWhere);
  98542. sqlite3DbFree(db, aToOpen);
  98543. return;
  98544. }
  98545. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  98546. ** they may interfere with compilation of other functions in this file
  98547. ** (or in another file, if this file becomes part of the amalgamation). */
  98548. #ifdef isView
  98549. #undef isView
  98550. #endif
  98551. #ifdef pTrigger
  98552. #undef pTrigger
  98553. #endif
  98554. /*
  98555. ** This routine generates VDBE code that causes a single row of a
  98556. ** single table to be deleted. Both the original table entry and
  98557. ** all indices are removed.
  98558. **
  98559. ** Preconditions:
  98560. **
  98561. ** 1. iDataCur is an open cursor on the btree that is the canonical data
  98562. ** store for the table. (This will be either the table itself,
  98563. ** in the case of a rowid table, or the PRIMARY KEY index in the case
  98564. ** of a WITHOUT ROWID table.)
  98565. **
  98566. ** 2. Read/write cursors for all indices of pTab must be open as
  98567. ** cursor number iIdxCur+i for the i-th index.
  98568. **
  98569. ** 3. The primary key for the row to be deleted must be stored in a
  98570. ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
  98571. ** that a search record formed from OP_MakeRecord is contained in the
  98572. ** single memory location iPk.
  98573. **
  98574. ** eMode:
  98575. ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
  98576. ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
  98577. ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
  98578. ** then this function must seek iDataCur to the entry identified by iPk
  98579. ** and nPk before reading from it.
  98580. **
  98581. ** If eMode is ONEPASS_MULTI, then this call is being made as part
  98582. ** of a ONEPASS delete that affects multiple rows. In this case, if
  98583. ** iIdxNoSeek is a valid cursor number (>=0) and is not the same as
  98584. ** iDataCur, then its position should be preserved following the delete
  98585. ** operation. Or, if iIdxNoSeek is not a valid cursor number, the
  98586. ** position of iDataCur should be preserved instead.
  98587. **
  98588. ** iIdxNoSeek:
  98589. ** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
  98590. ** then it identifies an index cursor (from within array of cursors
  98591. ** starting at iIdxCur) that already points to the index entry to be deleted.
  98592. ** Except, this optimization is disabled if there are BEFORE triggers since
  98593. ** the trigger body might have moved the cursor.
  98594. */
  98595. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  98596. Parse *pParse, /* Parsing context */
  98597. Table *pTab, /* Table containing the row to be deleted */
  98598. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  98599. int iDataCur, /* Cursor from which column data is extracted */
  98600. int iIdxCur, /* First index cursor */
  98601. int iPk, /* First memory cell containing the PRIMARY KEY */
  98602. i16 nPk, /* Number of PRIMARY KEY memory cells */
  98603. u8 count, /* If non-zero, increment the row change counter */
  98604. u8 onconf, /* Default ON CONFLICT policy for triggers */
  98605. u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
  98606. int iIdxNoSeek /* Cursor number of cursor that does not need seeking */
  98607. ){
  98608. Vdbe *v = pParse->pVdbe; /* Vdbe */
  98609. int iOld = 0; /* First register in OLD.* array */
  98610. int iLabel; /* Label resolved to end of generated code */
  98611. u8 opSeek; /* Seek opcode */
  98612. /* Vdbe is guaranteed to have been allocated by this stage. */
  98613. assert( v );
  98614. VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
  98615. iDataCur, iIdxCur, iPk, (int)nPk));
  98616. /* Seek cursor iCur to the row to delete. If this row no longer exists
  98617. ** (this can happen if a trigger program has already deleted it), do
  98618. ** not attempt to delete it or fire any DELETE triggers. */
  98619. iLabel = sqlite3VdbeMakeLabel(v);
  98620. opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  98621. if( eMode==ONEPASS_OFF ){
  98622. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  98623. VdbeCoverageIf(v, opSeek==OP_NotExists);
  98624. VdbeCoverageIf(v, opSeek==OP_NotFound);
  98625. }
  98626. /* If there are any triggers to fire, allocate a range of registers to
  98627. ** use for the old.* references in the triggers. */
  98628. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  98629. u32 mask; /* Mask of OLD.* columns in use */
  98630. int iCol; /* Iterator used while populating OLD.* */
  98631. int addrStart; /* Start of BEFORE trigger programs */
  98632. /* TODO: Could use temporary registers here. Also could attempt to
  98633. ** avoid copying the contents of the rowid register. */
  98634. mask = sqlite3TriggerColmask(
  98635. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  98636. );
  98637. mask |= sqlite3FkOldmask(pParse, pTab);
  98638. iOld = pParse->nMem+1;
  98639. pParse->nMem += (1 + pTab->nCol);
  98640. /* Populate the OLD.* pseudo-table register array. These values will be
  98641. ** used by any BEFORE and AFTER triggers that exist. */
  98642. sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
  98643. for(iCol=0; iCol<pTab->nCol; iCol++){
  98644. testcase( mask!=0xffffffff && iCol==31 );
  98645. testcase( mask!=0xffffffff && iCol==32 );
  98646. if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
  98647. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
  98648. }
  98649. }
  98650. /* Invoke BEFORE DELETE trigger programs. */
  98651. addrStart = sqlite3VdbeCurrentAddr(v);
  98652. sqlite3CodeRowTrigger(pParse, pTrigger,
  98653. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  98654. );
  98655. /* If any BEFORE triggers were coded, then seek the cursor to the
  98656. ** row to be deleted again. It may be that the BEFORE triggers moved
  98657. ** the cursor or already deleted the row that the cursor was
  98658. ** pointing to.
  98659. **
  98660. ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
  98661. ** may have moved that cursor.
  98662. */
  98663. if( addrStart<sqlite3VdbeCurrentAddr(v) ){
  98664. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  98665. VdbeCoverageIf(v, opSeek==OP_NotExists);
  98666. VdbeCoverageIf(v, opSeek==OP_NotFound);
  98667. testcase( iIdxNoSeek>=0 );
  98668. iIdxNoSeek = -1;
  98669. }
  98670. /* Do FK processing. This call checks that any FK constraints that
  98671. ** refer to this table (i.e. constraints attached to other tables)
  98672. ** are not violated by deleting this row. */
  98673. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  98674. }
  98675. /* Delete the index and table entries. Skip this step if pTab is really
  98676. ** a view (in which case the only effect of the DELETE statement is to
  98677. ** fire the INSTEAD OF triggers).
  98678. **
  98679. ** If variable 'count' is non-zero, then this OP_Delete instruction should
  98680. ** invoke the update-hook. The pre-update-hook, on the other hand should
  98681. ** be invoked unless table pTab is a system table. The difference is that
  98682. ** the update-hook is not invoked for rows removed by REPLACE, but the
  98683. ** pre-update-hook is.
  98684. */
  98685. if( pTab->pSelect==0 ){
  98686. u8 p5 = 0;
  98687. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
  98688. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
  98689. if( pParse->nested==0 ){
  98690. sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
  98691. }
  98692. if( eMode!=ONEPASS_OFF ){
  98693. sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
  98694. }
  98695. if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
  98696. sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
  98697. }
  98698. if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
  98699. sqlite3VdbeChangeP5(v, p5);
  98700. }
  98701. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  98702. ** handle rows (possibly in other tables) that refer via a foreign key
  98703. ** to the row just deleted. */
  98704. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  98705. /* Invoke AFTER DELETE trigger programs. */
  98706. sqlite3CodeRowTrigger(pParse, pTrigger,
  98707. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  98708. );
  98709. /* Jump here if the row had already been deleted before any BEFORE
  98710. ** trigger programs were invoked. Or if a trigger program throws a
  98711. ** RAISE(IGNORE) exception. */
  98712. sqlite3VdbeResolveLabel(v, iLabel);
  98713. VdbeModuleComment((v, "END: GenRowDel()"));
  98714. }
  98715. /*
  98716. ** This routine generates VDBE code that causes the deletion of all
  98717. ** index entries associated with a single row of a single table, pTab
  98718. **
  98719. ** Preconditions:
  98720. **
  98721. ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
  98722. ** btree for the table pTab. (This will be either the table itself
  98723. ** for rowid tables or to the primary key index for WITHOUT ROWID
  98724. ** tables.)
  98725. **
  98726. ** 2. Read/write cursors for all indices of pTab must be open as
  98727. ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
  98728. ** index is the 0-th index.)
  98729. **
  98730. ** 3. The "iDataCur" cursor must be already be positioned on the row
  98731. ** that is to be deleted.
  98732. */
  98733. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  98734. Parse *pParse, /* Parsing and code generating context */
  98735. Table *pTab, /* Table containing the row to be deleted */
  98736. int iDataCur, /* Cursor of table holding data. */
  98737. int iIdxCur, /* First index cursor */
  98738. int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  98739. int iIdxNoSeek /* Do not delete from this cursor */
  98740. ){
  98741. int i; /* Index loop counter */
  98742. int r1 = -1; /* Register holding an index key */
  98743. int iPartIdxLabel; /* Jump destination for skipping partial index entries */
  98744. Index *pIdx; /* Current index */
  98745. Index *pPrior = 0; /* Prior index */
  98746. Vdbe *v; /* The prepared statement under construction */
  98747. Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
  98748. v = pParse->pVdbe;
  98749. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  98750. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  98751. assert( iIdxCur+i!=iDataCur || pPk==pIdx );
  98752. if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
  98753. if( pIdx==pPk ) continue;
  98754. if( iIdxCur+i==iIdxNoSeek ) continue;
  98755. VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
  98756. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
  98757. &iPartIdxLabel, pPrior, r1);
  98758. sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
  98759. pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
  98760. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  98761. pPrior = pIdx;
  98762. }
  98763. }
  98764. /*
  98765. ** Generate code that will assemble an index key and stores it in register
  98766. ** regOut. The key with be for index pIdx which is an index on pTab.
  98767. ** iCur is the index of a cursor open on the pTab table and pointing to
  98768. ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
  98769. ** iCur must be the cursor of the PRIMARY KEY index.
  98770. **
  98771. ** Return a register number which is the first in a block of
  98772. ** registers that holds the elements of the index key. The
  98773. ** block of registers has already been deallocated by the time
  98774. ** this routine returns.
  98775. **
  98776. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  98777. ** to that label if pIdx is a partial index that should be skipped.
  98778. ** The label should be resolved using sqlite3ResolvePartIdxLabel().
  98779. ** A partial index should be skipped if its WHERE clause evaluates
  98780. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  98781. ** will be set to zero which is an empty label that is ignored by
  98782. ** sqlite3ResolvePartIdxLabel().
  98783. **
  98784. ** The pPrior and regPrior parameters are used to implement a cache to
  98785. ** avoid unnecessary register loads. If pPrior is not NULL, then it is
  98786. ** a pointer to a different index for which an index key has just been
  98787. ** computed into register regPrior. If the current pIdx index is generating
  98788. ** its key into the same sequence of registers and if pPrior and pIdx share
  98789. ** a column in common, then the register corresponding to that column already
  98790. ** holds the correct value and the loading of that register is skipped.
  98791. ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
  98792. ** on a table with multiple indices, and especially with the ROWID or
  98793. ** PRIMARY KEY columns of the index.
  98794. */
  98795. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  98796. Parse *pParse, /* Parsing context */
  98797. Index *pIdx, /* The index for which to generate a key */
  98798. int iDataCur, /* Cursor number from which to take column data */
  98799. int regOut, /* Put the new key into this register if not 0 */
  98800. int prefixOnly, /* Compute only a unique prefix of the key */
  98801. int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
  98802. Index *pPrior, /* Previously generated index key */
  98803. int regPrior /* Register holding previous generated key */
  98804. ){
  98805. Vdbe *v = pParse->pVdbe;
  98806. int j;
  98807. int regBase;
  98808. int nCol;
  98809. if( piPartIdxLabel ){
  98810. if( pIdx->pPartIdxWhere ){
  98811. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  98812. pParse->iSelfTab = iDataCur;
  98813. sqlite3ExprCachePush(pParse);
  98814. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  98815. SQLITE_JUMPIFNULL);
  98816. }else{
  98817. *piPartIdxLabel = 0;
  98818. }
  98819. }
  98820. nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
  98821. regBase = sqlite3GetTempRange(pParse, nCol);
  98822. if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
  98823. for(j=0; j<nCol; j++){
  98824. if( pPrior
  98825. && pPrior->aiColumn[j]==pIdx->aiColumn[j]
  98826. && pPrior->aiColumn[j]!=XN_EXPR
  98827. ){
  98828. /* This column was already computed by the previous index */
  98829. continue;
  98830. }
  98831. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
  98832. /* If the column affinity is REAL but the number is an integer, then it
  98833. ** might be stored in the table as an integer (using a compact
  98834. ** representation) then converted to REAL by an OP_RealAffinity opcode.
  98835. ** But we are getting ready to store this value back into an index, where
  98836. ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
  98837. ** opcode if it is present */
  98838. sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
  98839. }
  98840. if( regOut ){
  98841. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
  98842. if( pIdx->pTable->pSelect ){
  98843. const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
  98844. sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
  98845. }
  98846. }
  98847. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  98848. return regBase;
  98849. }
  98850. /*
  98851. ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
  98852. ** because it was a partial index, then this routine should be called to
  98853. ** resolve that label.
  98854. */
  98855. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
  98856. if( iLabel ){
  98857. sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
  98858. sqlite3ExprCachePop(pParse);
  98859. }
  98860. }
  98861. /************** End of delete.c **********************************************/
  98862. /************** Begin file func.c ********************************************/
  98863. /*
  98864. ** 2002 February 23
  98865. **
  98866. ** The author disclaims copyright to this source code. In place of
  98867. ** a legal notice, here is a blessing:
  98868. **
  98869. ** May you do good and not evil.
  98870. ** May you find forgiveness for yourself and forgive others.
  98871. ** May you share freely, never taking more than you give.
  98872. **
  98873. *************************************************************************
  98874. ** This file contains the C-language implementations for many of the SQL
  98875. ** functions of SQLite. (Some function, and in particular the date and
  98876. ** time functions, are implemented separately.)
  98877. */
  98878. /* #include "sqliteInt.h" */
  98879. /* #include <stdlib.h> */
  98880. /* #include <assert.h> */
  98881. /* #include "vdbeInt.h" */
  98882. /*
  98883. ** Return the collating function associated with a function.
  98884. */
  98885. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  98886. VdbeOp *pOp;
  98887. assert( context->pVdbe!=0 );
  98888. pOp = &context->pVdbe->aOp[context->iOp-1];
  98889. assert( pOp->opcode==OP_CollSeq );
  98890. assert( pOp->p4type==P4_COLLSEQ );
  98891. return pOp->p4.pColl;
  98892. }
  98893. /*
  98894. ** Indicate that the accumulator load should be skipped on this
  98895. ** iteration of the aggregate loop.
  98896. */
  98897. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  98898. context->skipFlag = 1;
  98899. }
  98900. /*
  98901. ** Implementation of the non-aggregate min() and max() functions
  98902. */
  98903. static void minmaxFunc(
  98904. sqlite3_context *context,
  98905. int argc,
  98906. sqlite3_value **argv
  98907. ){
  98908. int i;
  98909. int mask; /* 0 for min() or 0xffffffff for max() */
  98910. int iBest;
  98911. CollSeq *pColl;
  98912. assert( argc>1 );
  98913. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  98914. pColl = sqlite3GetFuncCollSeq(context);
  98915. assert( pColl );
  98916. assert( mask==-1 || mask==0 );
  98917. iBest = 0;
  98918. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  98919. for(i=1; i<argc; i++){
  98920. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  98921. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  98922. testcase( mask==0 );
  98923. iBest = i;
  98924. }
  98925. }
  98926. sqlite3_result_value(context, argv[iBest]);
  98927. }
  98928. /*
  98929. ** Return the type of the argument.
  98930. */
  98931. static void typeofFunc(
  98932. sqlite3_context *context,
  98933. int NotUsed,
  98934. sqlite3_value **argv
  98935. ){
  98936. const char *z = 0;
  98937. UNUSED_PARAMETER(NotUsed);
  98938. switch( sqlite3_value_type(argv[0]) ){
  98939. case SQLITE_INTEGER: z = "integer"; break;
  98940. case SQLITE_TEXT: z = "text"; break;
  98941. case SQLITE_FLOAT: z = "real"; break;
  98942. case SQLITE_BLOB: z = "blob"; break;
  98943. default: z = "null"; break;
  98944. }
  98945. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  98946. }
  98947. /*
  98948. ** Implementation of the length() function
  98949. */
  98950. static void lengthFunc(
  98951. sqlite3_context *context,
  98952. int argc,
  98953. sqlite3_value **argv
  98954. ){
  98955. int len;
  98956. assert( argc==1 );
  98957. UNUSED_PARAMETER(argc);
  98958. switch( sqlite3_value_type(argv[0]) ){
  98959. case SQLITE_BLOB:
  98960. case SQLITE_INTEGER:
  98961. case SQLITE_FLOAT: {
  98962. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  98963. break;
  98964. }
  98965. case SQLITE_TEXT: {
  98966. const unsigned char *z = sqlite3_value_text(argv[0]);
  98967. if( z==0 ) return;
  98968. len = 0;
  98969. while( *z ){
  98970. len++;
  98971. SQLITE_SKIP_UTF8(z);
  98972. }
  98973. sqlite3_result_int(context, len);
  98974. break;
  98975. }
  98976. default: {
  98977. sqlite3_result_null(context);
  98978. break;
  98979. }
  98980. }
  98981. }
  98982. /*
  98983. ** Implementation of the abs() function.
  98984. **
  98985. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  98986. ** the numeric argument X.
  98987. */
  98988. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  98989. assert( argc==1 );
  98990. UNUSED_PARAMETER(argc);
  98991. switch( sqlite3_value_type(argv[0]) ){
  98992. case SQLITE_INTEGER: {
  98993. i64 iVal = sqlite3_value_int64(argv[0]);
  98994. if( iVal<0 ){
  98995. if( iVal==SMALLEST_INT64 ){
  98996. /* IMP: R-31676-45509 If X is the integer -9223372036854775808
  98997. ** then abs(X) throws an integer overflow error since there is no
  98998. ** equivalent positive 64-bit two complement value. */
  98999. sqlite3_result_error(context, "integer overflow", -1);
  99000. return;
  99001. }
  99002. iVal = -iVal;
  99003. }
  99004. sqlite3_result_int64(context, iVal);
  99005. break;
  99006. }
  99007. case SQLITE_NULL: {
  99008. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  99009. sqlite3_result_null(context);
  99010. break;
  99011. }
  99012. default: {
  99013. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  99014. ** something that can be converted into a number, we have:
  99015. ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
  99016. ** that cannot be converted to a numeric value.
  99017. */
  99018. double rVal = sqlite3_value_double(argv[0]);
  99019. if( rVal<0 ) rVal = -rVal;
  99020. sqlite3_result_double(context, rVal);
  99021. break;
  99022. }
  99023. }
  99024. }
  99025. /*
  99026. ** Implementation of the instr() function.
  99027. **
  99028. ** instr(haystack,needle) finds the first occurrence of needle
  99029. ** in haystack and returns the number of previous characters plus 1,
  99030. ** or 0 if needle does not occur within haystack.
  99031. **
  99032. ** If both haystack and needle are BLOBs, then the result is one more than
  99033. ** the number of bytes in haystack prior to the first occurrence of needle,
  99034. ** or 0 if needle never occurs in haystack.
  99035. */
  99036. static void instrFunc(
  99037. sqlite3_context *context,
  99038. int argc,
  99039. sqlite3_value **argv
  99040. ){
  99041. const unsigned char *zHaystack;
  99042. const unsigned char *zNeedle;
  99043. int nHaystack;
  99044. int nNeedle;
  99045. int typeHaystack, typeNeedle;
  99046. int N = 1;
  99047. int isText;
  99048. UNUSED_PARAMETER(argc);
  99049. typeHaystack = sqlite3_value_type(argv[0]);
  99050. typeNeedle = sqlite3_value_type(argv[1]);
  99051. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  99052. nHaystack = sqlite3_value_bytes(argv[0]);
  99053. nNeedle = sqlite3_value_bytes(argv[1]);
  99054. if( nNeedle>0 ){
  99055. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  99056. zHaystack = sqlite3_value_blob(argv[0]);
  99057. zNeedle = sqlite3_value_blob(argv[1]);
  99058. isText = 0;
  99059. }else{
  99060. zHaystack = sqlite3_value_text(argv[0]);
  99061. zNeedle = sqlite3_value_text(argv[1]);
  99062. isText = 1;
  99063. }
  99064. if( zNeedle==0 || (nHaystack && zHaystack==0) ) return;
  99065. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  99066. N++;
  99067. do{
  99068. nHaystack--;
  99069. zHaystack++;
  99070. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  99071. }
  99072. if( nNeedle>nHaystack ) N = 0;
  99073. }
  99074. sqlite3_result_int(context, N);
  99075. }
  99076. /*
  99077. ** Implementation of the printf() function.
  99078. */
  99079. static void printfFunc(
  99080. sqlite3_context *context,
  99081. int argc,
  99082. sqlite3_value **argv
  99083. ){
  99084. PrintfArguments x;
  99085. StrAccum str;
  99086. const char *zFormat;
  99087. int n;
  99088. sqlite3 *db = sqlite3_context_db_handle(context);
  99089. if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  99090. x.nArg = argc-1;
  99091. x.nUsed = 0;
  99092. x.apArg = argv+1;
  99093. sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
  99094. str.printfFlags = SQLITE_PRINTF_SQLFUNC;
  99095. sqlite3XPrintf(&str, zFormat, &x);
  99096. n = str.nChar;
  99097. sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
  99098. SQLITE_DYNAMIC);
  99099. }
  99100. }
  99101. /*
  99102. ** Implementation of the substr() function.
  99103. **
  99104. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  99105. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  99106. ** of x. If x is text, then we actually count UTF-8 characters.
  99107. ** If x is a blob, then we count bytes.
  99108. **
  99109. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  99110. **
  99111. ** If p2 is negative, return the p2 characters preceding p1.
  99112. */
  99113. static void substrFunc(
  99114. sqlite3_context *context,
  99115. int argc,
  99116. sqlite3_value **argv
  99117. ){
  99118. const unsigned char *z;
  99119. const unsigned char *z2;
  99120. int len;
  99121. int p0type;
  99122. i64 p1, p2;
  99123. int negP2 = 0;
  99124. assert( argc==3 || argc==2 );
  99125. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  99126. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  99127. ){
  99128. return;
  99129. }
  99130. p0type = sqlite3_value_type(argv[0]);
  99131. p1 = sqlite3_value_int(argv[1]);
  99132. if( p0type==SQLITE_BLOB ){
  99133. len = sqlite3_value_bytes(argv[0]);
  99134. z = sqlite3_value_blob(argv[0]);
  99135. if( z==0 ) return;
  99136. assert( len==sqlite3_value_bytes(argv[0]) );
  99137. }else{
  99138. z = sqlite3_value_text(argv[0]);
  99139. if( z==0 ) return;
  99140. len = 0;
  99141. if( p1<0 ){
  99142. for(z2=z; *z2; len++){
  99143. SQLITE_SKIP_UTF8(z2);
  99144. }
  99145. }
  99146. }
  99147. #ifdef SQLITE_SUBSTR_COMPATIBILITY
  99148. /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
  99149. ** as substr(X,1,N) - it returns the first N characters of X. This
  99150. ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
  99151. ** from 2009-02-02 for compatibility of applications that exploited the
  99152. ** old buggy behavior. */
  99153. if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
  99154. #endif
  99155. if( argc==3 ){
  99156. p2 = sqlite3_value_int(argv[2]);
  99157. if( p2<0 ){
  99158. p2 = -p2;
  99159. negP2 = 1;
  99160. }
  99161. }else{
  99162. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  99163. }
  99164. if( p1<0 ){
  99165. p1 += len;
  99166. if( p1<0 ){
  99167. p2 += p1;
  99168. if( p2<0 ) p2 = 0;
  99169. p1 = 0;
  99170. }
  99171. }else if( p1>0 ){
  99172. p1--;
  99173. }else if( p2>0 ){
  99174. p2--;
  99175. }
  99176. if( negP2 ){
  99177. p1 -= p2;
  99178. if( p1<0 ){
  99179. p2 += p1;
  99180. p1 = 0;
  99181. }
  99182. }
  99183. assert( p1>=0 && p2>=0 );
  99184. if( p0type!=SQLITE_BLOB ){
  99185. while( *z && p1 ){
  99186. SQLITE_SKIP_UTF8(z);
  99187. p1--;
  99188. }
  99189. for(z2=z; *z2 && p2; p2--){
  99190. SQLITE_SKIP_UTF8(z2);
  99191. }
  99192. sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
  99193. SQLITE_UTF8);
  99194. }else{
  99195. if( p1+p2>len ){
  99196. p2 = len-p1;
  99197. if( p2<0 ) p2 = 0;
  99198. }
  99199. sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
  99200. }
  99201. }
  99202. /*
  99203. ** Implementation of the round() function
  99204. */
  99205. #ifndef SQLITE_OMIT_FLOATING_POINT
  99206. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  99207. int n = 0;
  99208. double r;
  99209. char *zBuf;
  99210. assert( argc==1 || argc==2 );
  99211. if( argc==2 ){
  99212. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  99213. n = sqlite3_value_int(argv[1]);
  99214. if( n>30 ) n = 30;
  99215. if( n<0 ) n = 0;
  99216. }
  99217. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  99218. r = sqlite3_value_double(argv[0]);
  99219. /* If Y==0 and X will fit in a 64-bit int,
  99220. ** handle the rounding directly,
  99221. ** otherwise use printf.
  99222. */
  99223. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  99224. r = (double)((sqlite_int64)(r+0.5));
  99225. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  99226. r = -(double)((sqlite_int64)((-r)+0.5));
  99227. }else{
  99228. zBuf = sqlite3_mprintf("%.*f",n,r);
  99229. if( zBuf==0 ){
  99230. sqlite3_result_error_nomem(context);
  99231. return;
  99232. }
  99233. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  99234. sqlite3_free(zBuf);
  99235. }
  99236. sqlite3_result_double(context, r);
  99237. }
  99238. #endif
  99239. /*
  99240. ** Allocate nByte bytes of space using sqlite3Malloc(). If the
  99241. ** allocation fails, call sqlite3_result_error_nomem() to notify
  99242. ** the database handle that malloc() has failed and return NULL.
  99243. ** If nByte is larger than the maximum string or blob length, then
  99244. ** raise an SQLITE_TOOBIG exception and return NULL.
  99245. */
  99246. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  99247. char *z;
  99248. sqlite3 *db = sqlite3_context_db_handle(context);
  99249. assert( nByte>0 );
  99250. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  99251. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  99252. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  99253. sqlite3_result_error_toobig(context);
  99254. z = 0;
  99255. }else{
  99256. z = sqlite3Malloc(nByte);
  99257. if( !z ){
  99258. sqlite3_result_error_nomem(context);
  99259. }
  99260. }
  99261. return z;
  99262. }
  99263. /*
  99264. ** Implementation of the upper() and lower() SQL functions.
  99265. */
  99266. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  99267. char *z1;
  99268. const char *z2;
  99269. int i, n;
  99270. UNUSED_PARAMETER(argc);
  99271. z2 = (char*)sqlite3_value_text(argv[0]);
  99272. n = sqlite3_value_bytes(argv[0]);
  99273. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  99274. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  99275. if( z2 ){
  99276. z1 = contextMalloc(context, ((i64)n)+1);
  99277. if( z1 ){
  99278. for(i=0; i<n; i++){
  99279. z1[i] = (char)sqlite3Toupper(z2[i]);
  99280. }
  99281. sqlite3_result_text(context, z1, n, sqlite3_free);
  99282. }
  99283. }
  99284. }
  99285. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  99286. char *z1;
  99287. const char *z2;
  99288. int i, n;
  99289. UNUSED_PARAMETER(argc);
  99290. z2 = (char*)sqlite3_value_text(argv[0]);
  99291. n = sqlite3_value_bytes(argv[0]);
  99292. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  99293. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  99294. if( z2 ){
  99295. z1 = contextMalloc(context, ((i64)n)+1);
  99296. if( z1 ){
  99297. for(i=0; i<n; i++){
  99298. z1[i] = sqlite3Tolower(z2[i]);
  99299. }
  99300. sqlite3_result_text(context, z1, n, sqlite3_free);
  99301. }
  99302. }
  99303. }
  99304. /*
  99305. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  99306. ** as VDBE code so that unused argument values do not have to be computed.
  99307. ** However, we still need some kind of function implementation for this
  99308. ** routines in the function table. The noopFunc macro provides this.
  99309. ** noopFunc will never be called so it doesn't matter what the implementation
  99310. ** is. We might as well use the "version()" function as a substitute.
  99311. */
  99312. #define noopFunc versionFunc /* Substitute function - never called */
  99313. /*
  99314. ** Implementation of random(). Return a random integer.
  99315. */
  99316. static void randomFunc(
  99317. sqlite3_context *context,
  99318. int NotUsed,
  99319. sqlite3_value **NotUsed2
  99320. ){
  99321. sqlite_int64 r;
  99322. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  99323. sqlite3_randomness(sizeof(r), &r);
  99324. if( r<0 ){
  99325. /* We need to prevent a random number of 0x8000000000000000
  99326. ** (or -9223372036854775808) since when you do abs() of that
  99327. ** number of you get the same value back again. To do this
  99328. ** in a way that is testable, mask the sign bit off of negative
  99329. ** values, resulting in a positive value. Then take the
  99330. ** 2s complement of that positive value. The end result can
  99331. ** therefore be no less than -9223372036854775807.
  99332. */
  99333. r = -(r & LARGEST_INT64);
  99334. }
  99335. sqlite3_result_int64(context, r);
  99336. }
  99337. /*
  99338. ** Implementation of randomblob(N). Return a random blob
  99339. ** that is N bytes long.
  99340. */
  99341. static void randomBlob(
  99342. sqlite3_context *context,
  99343. int argc,
  99344. sqlite3_value **argv
  99345. ){
  99346. int n;
  99347. unsigned char *p;
  99348. assert( argc==1 );
  99349. UNUSED_PARAMETER(argc);
  99350. n = sqlite3_value_int(argv[0]);
  99351. if( n<1 ){
  99352. n = 1;
  99353. }
  99354. p = contextMalloc(context, n);
  99355. if( p ){
  99356. sqlite3_randomness(n, p);
  99357. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  99358. }
  99359. }
  99360. /*
  99361. ** Implementation of the last_insert_rowid() SQL function. The return
  99362. ** value is the same as the sqlite3_last_insert_rowid() API function.
  99363. */
  99364. static void last_insert_rowid(
  99365. sqlite3_context *context,
  99366. int NotUsed,
  99367. sqlite3_value **NotUsed2
  99368. ){
  99369. sqlite3 *db = sqlite3_context_db_handle(context);
  99370. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  99371. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  99372. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  99373. ** function. */
  99374. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  99375. }
  99376. /*
  99377. ** Implementation of the changes() SQL function.
  99378. **
  99379. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  99380. ** around the sqlite3_changes() C/C++ function and hence follows the same
  99381. ** rules for counting changes.
  99382. */
  99383. static void changes(
  99384. sqlite3_context *context,
  99385. int NotUsed,
  99386. sqlite3_value **NotUsed2
  99387. ){
  99388. sqlite3 *db = sqlite3_context_db_handle(context);
  99389. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  99390. sqlite3_result_int(context, sqlite3_changes(db));
  99391. }
  99392. /*
  99393. ** Implementation of the total_changes() SQL function. The return value is
  99394. ** the same as the sqlite3_total_changes() API function.
  99395. */
  99396. static void total_changes(
  99397. sqlite3_context *context,
  99398. int NotUsed,
  99399. sqlite3_value **NotUsed2
  99400. ){
  99401. sqlite3 *db = sqlite3_context_db_handle(context);
  99402. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  99403. /* IMP: R-52756-41993 This function is a wrapper around the
  99404. ** sqlite3_total_changes() C/C++ interface. */
  99405. sqlite3_result_int(context, sqlite3_total_changes(db));
  99406. }
  99407. /*
  99408. ** A structure defining how to do GLOB-style comparisons.
  99409. */
  99410. struct compareInfo {
  99411. u8 matchAll; /* "*" or "%" */
  99412. u8 matchOne; /* "?" or "_" */
  99413. u8 matchSet; /* "[" or 0 */
  99414. u8 noCase; /* true to ignore case differences */
  99415. };
  99416. /*
  99417. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  99418. ** character is exactly one byte in size. Also, provde the Utf8Read()
  99419. ** macro for fast reading of the next character in the common case where
  99420. ** the next character is ASCII.
  99421. */
  99422. #if defined(SQLITE_EBCDIC)
  99423. # define sqlite3Utf8Read(A) (*((*A)++))
  99424. # define Utf8Read(A) (*(A++))
  99425. #else
  99426. # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
  99427. #endif
  99428. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  99429. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  99430. ** case. Thus 'a' LIKE 'A' would be true. */
  99431. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  99432. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  99433. ** is case sensitive causing 'a' LIKE 'A' to be false */
  99434. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  99435. /*
  99436. ** Possible error returns from patternMatch()
  99437. */
  99438. #define SQLITE_MATCH 0
  99439. #define SQLITE_NOMATCH 1
  99440. #define SQLITE_NOWILDCARDMATCH 2
  99441. /*
  99442. ** Compare two UTF-8 strings for equality where the first string is
  99443. ** a GLOB or LIKE expression. Return values:
  99444. **
  99445. ** SQLITE_MATCH: Match
  99446. ** SQLITE_NOMATCH: No match
  99447. ** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards.
  99448. **
  99449. ** Globbing rules:
  99450. **
  99451. ** '*' Matches any sequence of zero or more characters.
  99452. **
  99453. ** '?' Matches exactly one character.
  99454. **
  99455. ** [...] Matches one character from the enclosed list of
  99456. ** characters.
  99457. **
  99458. ** [^...] Matches one character not in the enclosed list.
  99459. **
  99460. ** With the [...] and [^...] matching, a ']' character can be included
  99461. ** in the list by making it the first character after '[' or '^'. A
  99462. ** range of characters can be specified using '-'. Example:
  99463. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  99464. ** it the last character in the list.
  99465. **
  99466. ** Like matching rules:
  99467. **
  99468. ** '%' Matches any sequence of zero or more characters
  99469. **
  99470. *** '_' Matches any one character
  99471. **
  99472. ** Ec Where E is the "esc" character and c is any other
  99473. ** character, including '%', '_', and esc, match exactly c.
  99474. **
  99475. ** The comments within this routine usually assume glob matching.
  99476. **
  99477. ** This routine is usually quick, but can be N**2 in the worst case.
  99478. */
  99479. static int patternCompare(
  99480. const u8 *zPattern, /* The glob pattern */
  99481. const u8 *zString, /* The string to compare against the glob */
  99482. const struct compareInfo *pInfo, /* Information about how to do the compare */
  99483. u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */
  99484. ){
  99485. u32 c, c2; /* Next pattern and input string chars */
  99486. u32 matchOne = pInfo->matchOne; /* "?" or "_" */
  99487. u32 matchAll = pInfo->matchAll; /* "*" or "%" */
  99488. u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
  99489. const u8 *zEscaped = 0; /* One past the last escaped input char */
  99490. while( (c = Utf8Read(zPattern))!=0 ){
  99491. if( c==matchAll ){ /* Match "*" */
  99492. /* Skip over multiple "*" characters in the pattern. If there
  99493. ** are also "?" characters, skip those as well, but consume a
  99494. ** single character of the input string for each "?" skipped */
  99495. while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
  99496. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  99497. return SQLITE_NOWILDCARDMATCH;
  99498. }
  99499. }
  99500. if( c==0 ){
  99501. return SQLITE_MATCH; /* "*" at the end of the pattern matches */
  99502. }else if( c==matchOther ){
  99503. if( pInfo->matchSet==0 ){
  99504. c = sqlite3Utf8Read(&zPattern);
  99505. if( c==0 ) return SQLITE_NOWILDCARDMATCH;
  99506. }else{
  99507. /* "[...]" immediately follows the "*". We have to do a slow
  99508. ** recursive search in this case, but it is an unusual case. */
  99509. assert( matchOther<0x80 ); /* '[' is a single-byte character */
  99510. while( *zString ){
  99511. int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
  99512. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  99513. SQLITE_SKIP_UTF8(zString);
  99514. }
  99515. return SQLITE_NOWILDCARDMATCH;
  99516. }
  99517. }
  99518. /* At this point variable c contains the first character of the
  99519. ** pattern string past the "*". Search in the input string for the
  99520. ** first matching character and recursively continue the match from
  99521. ** that point.
  99522. **
  99523. ** For a case-insensitive search, set variable cx to be the same as
  99524. ** c but in the other case and search the input string for either
  99525. ** c or cx.
  99526. */
  99527. if( c<=0x80 ){
  99528. u32 cx;
  99529. int bMatch;
  99530. if( noCase ){
  99531. cx = sqlite3Toupper(c);
  99532. c = sqlite3Tolower(c);
  99533. }else{
  99534. cx = c;
  99535. }
  99536. while( (c2 = *(zString++))!=0 ){
  99537. if( c2!=c && c2!=cx ) continue;
  99538. bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
  99539. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  99540. }
  99541. }else{
  99542. int bMatch;
  99543. while( (c2 = Utf8Read(zString))!=0 ){
  99544. if( c2!=c ) continue;
  99545. bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
  99546. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  99547. }
  99548. }
  99549. return SQLITE_NOWILDCARDMATCH;
  99550. }
  99551. if( c==matchOther ){
  99552. if( pInfo->matchSet==0 ){
  99553. c = sqlite3Utf8Read(&zPattern);
  99554. if( c==0 ) return SQLITE_NOMATCH;
  99555. zEscaped = zPattern;
  99556. }else{
  99557. u32 prior_c = 0;
  99558. int seen = 0;
  99559. int invert = 0;
  99560. c = sqlite3Utf8Read(&zString);
  99561. if( c==0 ) return SQLITE_NOMATCH;
  99562. c2 = sqlite3Utf8Read(&zPattern);
  99563. if( c2=='^' ){
  99564. invert = 1;
  99565. c2 = sqlite3Utf8Read(&zPattern);
  99566. }
  99567. if( c2==']' ){
  99568. if( c==']' ) seen = 1;
  99569. c2 = sqlite3Utf8Read(&zPattern);
  99570. }
  99571. while( c2 && c2!=']' ){
  99572. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  99573. c2 = sqlite3Utf8Read(&zPattern);
  99574. if( c>=prior_c && c<=c2 ) seen = 1;
  99575. prior_c = 0;
  99576. }else{
  99577. if( c==c2 ){
  99578. seen = 1;
  99579. }
  99580. prior_c = c2;
  99581. }
  99582. c2 = sqlite3Utf8Read(&zPattern);
  99583. }
  99584. if( c2==0 || (seen ^ invert)==0 ){
  99585. return SQLITE_NOMATCH;
  99586. }
  99587. continue;
  99588. }
  99589. }
  99590. c2 = Utf8Read(zString);
  99591. if( c==c2 ) continue;
  99592. if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
  99593. continue;
  99594. }
  99595. if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
  99596. return SQLITE_NOMATCH;
  99597. }
  99598. return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
  99599. }
  99600. /*
  99601. ** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and
  99602. ** non-zero if there is no match.
  99603. */
  99604. SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
  99605. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
  99606. }
  99607. /*
  99608. ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for
  99609. ** a miss - like strcmp().
  99610. */
  99611. SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
  99612. return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
  99613. }
  99614. /*
  99615. ** Count the number of times that the LIKE operator (or GLOB which is
  99616. ** just a variation of LIKE) gets called. This is used for testing
  99617. ** only.
  99618. */
  99619. #ifdef SQLITE_TEST
  99620. SQLITE_API int sqlite3_like_count = 0;
  99621. #endif
  99622. /*
  99623. ** Implementation of the like() SQL function. This function implements
  99624. ** the build-in LIKE operator. The first argument to the function is the
  99625. ** pattern and the second argument is the string. So, the SQL statements:
  99626. **
  99627. ** A LIKE B
  99628. **
  99629. ** is implemented as like(B,A).
  99630. **
  99631. ** This same function (with a different compareInfo structure) computes
  99632. ** the GLOB operator.
  99633. */
  99634. static void likeFunc(
  99635. sqlite3_context *context,
  99636. int argc,
  99637. sqlite3_value **argv
  99638. ){
  99639. const unsigned char *zA, *zB;
  99640. u32 escape;
  99641. int nPat;
  99642. sqlite3 *db = sqlite3_context_db_handle(context);
  99643. struct compareInfo *pInfo = sqlite3_user_data(context);
  99644. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  99645. if( sqlite3_value_type(argv[0])==SQLITE_BLOB
  99646. || sqlite3_value_type(argv[1])==SQLITE_BLOB
  99647. ){
  99648. #ifdef SQLITE_TEST
  99649. sqlite3_like_count++;
  99650. #endif
  99651. sqlite3_result_int(context, 0);
  99652. return;
  99653. }
  99654. #endif
  99655. zB = sqlite3_value_text(argv[0]);
  99656. zA = sqlite3_value_text(argv[1]);
  99657. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  99658. ** of deep recursion and N*N behavior in patternCompare().
  99659. */
  99660. nPat = sqlite3_value_bytes(argv[0]);
  99661. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  99662. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  99663. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  99664. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  99665. return;
  99666. }
  99667. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  99668. if( argc==3 ){
  99669. /* The escape character string must consist of a single UTF-8 character.
  99670. ** Otherwise, return an error.
  99671. */
  99672. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  99673. if( zEsc==0 ) return;
  99674. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  99675. sqlite3_result_error(context,
  99676. "ESCAPE expression must be a single character", -1);
  99677. return;
  99678. }
  99679. escape = sqlite3Utf8Read(&zEsc);
  99680. }else{
  99681. escape = pInfo->matchSet;
  99682. }
  99683. if( zA && zB ){
  99684. #ifdef SQLITE_TEST
  99685. sqlite3_like_count++;
  99686. #endif
  99687. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
  99688. }
  99689. }
  99690. /*
  99691. ** Implementation of the NULLIF(x,y) function. The result is the first
  99692. ** argument if the arguments are different. The result is NULL if the
  99693. ** arguments are equal to each other.
  99694. */
  99695. static void nullifFunc(
  99696. sqlite3_context *context,
  99697. int NotUsed,
  99698. sqlite3_value **argv
  99699. ){
  99700. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  99701. UNUSED_PARAMETER(NotUsed);
  99702. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  99703. sqlite3_result_value(context, argv[0]);
  99704. }
  99705. }
  99706. /*
  99707. ** Implementation of the sqlite_version() function. The result is the version
  99708. ** of the SQLite library that is running.
  99709. */
  99710. static void versionFunc(
  99711. sqlite3_context *context,
  99712. int NotUsed,
  99713. sqlite3_value **NotUsed2
  99714. ){
  99715. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  99716. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  99717. ** sqlite3_libversion() C-interface. */
  99718. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  99719. }
  99720. /*
  99721. ** Implementation of the sqlite_source_id() function. The result is a string
  99722. ** that identifies the particular version of the source code used to build
  99723. ** SQLite.
  99724. */
  99725. static void sourceidFunc(
  99726. sqlite3_context *context,
  99727. int NotUsed,
  99728. sqlite3_value **NotUsed2
  99729. ){
  99730. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  99731. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  99732. ** sqlite3_sourceid() C interface. */
  99733. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  99734. }
  99735. /*
  99736. ** Implementation of the sqlite_log() function. This is a wrapper around
  99737. ** sqlite3_log(). The return value is NULL. The function exists purely for
  99738. ** its side-effects.
  99739. */
  99740. static void errlogFunc(
  99741. sqlite3_context *context,
  99742. int argc,
  99743. sqlite3_value **argv
  99744. ){
  99745. UNUSED_PARAMETER(argc);
  99746. UNUSED_PARAMETER(context);
  99747. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  99748. }
  99749. /*
  99750. ** Implementation of the sqlite_compileoption_used() function.
  99751. ** The result is an integer that identifies if the compiler option
  99752. ** was used to build SQLite.
  99753. */
  99754. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  99755. static void compileoptionusedFunc(
  99756. sqlite3_context *context,
  99757. int argc,
  99758. sqlite3_value **argv
  99759. ){
  99760. const char *zOptName;
  99761. assert( argc==1 );
  99762. UNUSED_PARAMETER(argc);
  99763. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  99764. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  99765. ** function.
  99766. */
  99767. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  99768. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  99769. }
  99770. }
  99771. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  99772. /*
  99773. ** Implementation of the sqlite_compileoption_get() function.
  99774. ** The result is a string that identifies the compiler options
  99775. ** used to build SQLite.
  99776. */
  99777. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  99778. static void compileoptiongetFunc(
  99779. sqlite3_context *context,
  99780. int argc,
  99781. sqlite3_value **argv
  99782. ){
  99783. int n;
  99784. assert( argc==1 );
  99785. UNUSED_PARAMETER(argc);
  99786. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  99787. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  99788. */
  99789. n = sqlite3_value_int(argv[0]);
  99790. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  99791. }
  99792. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  99793. /* Array for converting from half-bytes (nybbles) into ASCII hex
  99794. ** digits. */
  99795. static const char hexdigits[] = {
  99796. '0', '1', '2', '3', '4', '5', '6', '7',
  99797. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  99798. };
  99799. /*
  99800. ** Implementation of the QUOTE() function. This function takes a single
  99801. ** argument. If the argument is numeric, the return value is the same as
  99802. ** the argument. If the argument is NULL, the return value is the string
  99803. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  99804. ** single-quote escapes.
  99805. */
  99806. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  99807. assert( argc==1 );
  99808. UNUSED_PARAMETER(argc);
  99809. switch( sqlite3_value_type(argv[0]) ){
  99810. case SQLITE_FLOAT: {
  99811. double r1, r2;
  99812. char zBuf[50];
  99813. r1 = sqlite3_value_double(argv[0]);
  99814. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  99815. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  99816. if( r1!=r2 ){
  99817. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  99818. }
  99819. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  99820. break;
  99821. }
  99822. case SQLITE_INTEGER: {
  99823. sqlite3_result_value(context, argv[0]);
  99824. break;
  99825. }
  99826. case SQLITE_BLOB: {
  99827. char *zText = 0;
  99828. char const *zBlob = sqlite3_value_blob(argv[0]);
  99829. int nBlob = sqlite3_value_bytes(argv[0]);
  99830. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  99831. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  99832. if( zText ){
  99833. int i;
  99834. for(i=0; i<nBlob; i++){
  99835. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  99836. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  99837. }
  99838. zText[(nBlob*2)+2] = '\'';
  99839. zText[(nBlob*2)+3] = '\0';
  99840. zText[0] = 'X';
  99841. zText[1] = '\'';
  99842. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  99843. sqlite3_free(zText);
  99844. }
  99845. break;
  99846. }
  99847. case SQLITE_TEXT: {
  99848. int i,j;
  99849. u64 n;
  99850. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  99851. char *z;
  99852. if( zArg==0 ) return;
  99853. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  99854. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  99855. if( z ){
  99856. z[0] = '\'';
  99857. for(i=0, j=1; zArg[i]; i++){
  99858. z[j++] = zArg[i];
  99859. if( zArg[i]=='\'' ){
  99860. z[j++] = '\'';
  99861. }
  99862. }
  99863. z[j++] = '\'';
  99864. z[j] = 0;
  99865. sqlite3_result_text(context, z, j, sqlite3_free);
  99866. }
  99867. break;
  99868. }
  99869. default: {
  99870. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  99871. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  99872. break;
  99873. }
  99874. }
  99875. }
  99876. /*
  99877. ** The unicode() function. Return the integer unicode code-point value
  99878. ** for the first character of the input string.
  99879. */
  99880. static void unicodeFunc(
  99881. sqlite3_context *context,
  99882. int argc,
  99883. sqlite3_value **argv
  99884. ){
  99885. const unsigned char *z = sqlite3_value_text(argv[0]);
  99886. (void)argc;
  99887. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  99888. }
  99889. /*
  99890. ** The char() function takes zero or more arguments, each of which is
  99891. ** an integer. It constructs a string where each character of the string
  99892. ** is the unicode character for the corresponding integer argument.
  99893. */
  99894. static void charFunc(
  99895. sqlite3_context *context,
  99896. int argc,
  99897. sqlite3_value **argv
  99898. ){
  99899. unsigned char *z, *zOut;
  99900. int i;
  99901. zOut = z = sqlite3_malloc64( argc*4+1 );
  99902. if( z==0 ){
  99903. sqlite3_result_error_nomem(context);
  99904. return;
  99905. }
  99906. for(i=0; i<argc; i++){
  99907. sqlite3_int64 x;
  99908. unsigned c;
  99909. x = sqlite3_value_int64(argv[i]);
  99910. if( x<0 || x>0x10ffff ) x = 0xfffd;
  99911. c = (unsigned)(x & 0x1fffff);
  99912. if( c<0x00080 ){
  99913. *zOut++ = (u8)(c&0xFF);
  99914. }else if( c<0x00800 ){
  99915. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  99916. *zOut++ = 0x80 + (u8)(c & 0x3F);
  99917. }else if( c<0x10000 ){
  99918. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  99919. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  99920. *zOut++ = 0x80 + (u8)(c & 0x3F);
  99921. }else{
  99922. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  99923. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  99924. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  99925. *zOut++ = 0x80 + (u8)(c & 0x3F);
  99926. } \
  99927. }
  99928. sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
  99929. }
  99930. /*
  99931. ** The hex() function. Interpret the argument as a blob. Return
  99932. ** a hexadecimal rendering as text.
  99933. */
  99934. static void hexFunc(
  99935. sqlite3_context *context,
  99936. int argc,
  99937. sqlite3_value **argv
  99938. ){
  99939. int i, n;
  99940. const unsigned char *pBlob;
  99941. char *zHex, *z;
  99942. assert( argc==1 );
  99943. UNUSED_PARAMETER(argc);
  99944. pBlob = sqlite3_value_blob(argv[0]);
  99945. n = sqlite3_value_bytes(argv[0]);
  99946. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  99947. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  99948. if( zHex ){
  99949. for(i=0; i<n; i++, pBlob++){
  99950. unsigned char c = *pBlob;
  99951. *(z++) = hexdigits[(c>>4)&0xf];
  99952. *(z++) = hexdigits[c&0xf];
  99953. }
  99954. *z = 0;
  99955. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  99956. }
  99957. }
  99958. /*
  99959. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  99960. */
  99961. static void zeroblobFunc(
  99962. sqlite3_context *context,
  99963. int argc,
  99964. sqlite3_value **argv
  99965. ){
  99966. i64 n;
  99967. int rc;
  99968. assert( argc==1 );
  99969. UNUSED_PARAMETER(argc);
  99970. n = sqlite3_value_int64(argv[0]);
  99971. if( n<0 ) n = 0;
  99972. rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
  99973. if( rc ){
  99974. sqlite3_result_error_code(context, rc);
  99975. }
  99976. }
  99977. /*
  99978. ** The replace() function. Three arguments are all strings: call
  99979. ** them A, B, and C. The result is also a string which is derived
  99980. ** from A by replacing every occurrence of B with C. The match
  99981. ** must be exact. Collating sequences are not used.
  99982. */
  99983. static void replaceFunc(
  99984. sqlite3_context *context,
  99985. int argc,
  99986. sqlite3_value **argv
  99987. ){
  99988. const unsigned char *zStr; /* The input string A */
  99989. const unsigned char *zPattern; /* The pattern string B */
  99990. const unsigned char *zRep; /* The replacement string C */
  99991. unsigned char *zOut; /* The output */
  99992. int nStr; /* Size of zStr */
  99993. int nPattern; /* Size of zPattern */
  99994. int nRep; /* Size of zRep */
  99995. i64 nOut; /* Maximum size of zOut */
  99996. int loopLimit; /* Last zStr[] that might match zPattern[] */
  99997. int i, j; /* Loop counters */
  99998. assert( argc==3 );
  99999. UNUSED_PARAMETER(argc);
  100000. zStr = sqlite3_value_text(argv[0]);
  100001. if( zStr==0 ) return;
  100002. nStr = sqlite3_value_bytes(argv[0]);
  100003. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  100004. zPattern = sqlite3_value_text(argv[1]);
  100005. if( zPattern==0 ){
  100006. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  100007. || sqlite3_context_db_handle(context)->mallocFailed );
  100008. return;
  100009. }
  100010. if( zPattern[0]==0 ){
  100011. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  100012. sqlite3_result_value(context, argv[0]);
  100013. return;
  100014. }
  100015. nPattern = sqlite3_value_bytes(argv[1]);
  100016. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  100017. zRep = sqlite3_value_text(argv[2]);
  100018. if( zRep==0 ) return;
  100019. nRep = sqlite3_value_bytes(argv[2]);
  100020. assert( zRep==sqlite3_value_text(argv[2]) );
  100021. nOut = nStr + 1;
  100022. assert( nOut<SQLITE_MAX_LENGTH );
  100023. zOut = contextMalloc(context, (i64)nOut);
  100024. if( zOut==0 ){
  100025. return;
  100026. }
  100027. loopLimit = nStr - nPattern;
  100028. for(i=j=0; i<=loopLimit; i++){
  100029. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  100030. zOut[j++] = zStr[i];
  100031. }else{
  100032. u8 *zOld;
  100033. sqlite3 *db = sqlite3_context_db_handle(context);
  100034. nOut += nRep - nPattern;
  100035. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  100036. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  100037. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  100038. sqlite3_result_error_toobig(context);
  100039. sqlite3_free(zOut);
  100040. return;
  100041. }
  100042. zOld = zOut;
  100043. zOut = sqlite3_realloc64(zOut, (int)nOut);
  100044. if( zOut==0 ){
  100045. sqlite3_result_error_nomem(context);
  100046. sqlite3_free(zOld);
  100047. return;
  100048. }
  100049. memcpy(&zOut[j], zRep, nRep);
  100050. j += nRep;
  100051. i += nPattern-1;
  100052. }
  100053. }
  100054. assert( j+nStr-i+1==nOut );
  100055. memcpy(&zOut[j], &zStr[i], nStr-i);
  100056. j += nStr - i;
  100057. assert( j<=nOut );
  100058. zOut[j] = 0;
  100059. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  100060. }
  100061. /*
  100062. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  100063. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  100064. */
  100065. static void trimFunc(
  100066. sqlite3_context *context,
  100067. int argc,
  100068. sqlite3_value **argv
  100069. ){
  100070. const unsigned char *zIn; /* Input string */
  100071. const unsigned char *zCharSet; /* Set of characters to trim */
  100072. int nIn; /* Number of bytes in input */
  100073. int flags; /* 1: trimleft 2: trimright 3: trim */
  100074. int i; /* Loop counter */
  100075. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  100076. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  100077. int nChar; /* Number of characters in zCharSet */
  100078. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  100079. return;
  100080. }
  100081. zIn = sqlite3_value_text(argv[0]);
  100082. if( zIn==0 ) return;
  100083. nIn = sqlite3_value_bytes(argv[0]);
  100084. assert( zIn==sqlite3_value_text(argv[0]) );
  100085. if( argc==1 ){
  100086. static const unsigned char lenOne[] = { 1 };
  100087. static unsigned char * const azOne[] = { (u8*)" " };
  100088. nChar = 1;
  100089. aLen = (u8*)lenOne;
  100090. azChar = (unsigned char **)azOne;
  100091. zCharSet = 0;
  100092. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  100093. return;
  100094. }else{
  100095. const unsigned char *z;
  100096. for(z=zCharSet, nChar=0; *z; nChar++){
  100097. SQLITE_SKIP_UTF8(z);
  100098. }
  100099. if( nChar>0 ){
  100100. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  100101. if( azChar==0 ){
  100102. return;
  100103. }
  100104. aLen = (unsigned char*)&azChar[nChar];
  100105. for(z=zCharSet, nChar=0; *z; nChar++){
  100106. azChar[nChar] = (unsigned char *)z;
  100107. SQLITE_SKIP_UTF8(z);
  100108. aLen[nChar] = (u8)(z - azChar[nChar]);
  100109. }
  100110. }
  100111. }
  100112. if( nChar>0 ){
  100113. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  100114. if( flags & 1 ){
  100115. while( nIn>0 ){
  100116. int len = 0;
  100117. for(i=0; i<nChar; i++){
  100118. len = aLen[i];
  100119. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  100120. }
  100121. if( i>=nChar ) break;
  100122. zIn += len;
  100123. nIn -= len;
  100124. }
  100125. }
  100126. if( flags & 2 ){
  100127. while( nIn>0 ){
  100128. int len = 0;
  100129. for(i=0; i<nChar; i++){
  100130. len = aLen[i];
  100131. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  100132. }
  100133. if( i>=nChar ) break;
  100134. nIn -= len;
  100135. }
  100136. }
  100137. if( zCharSet ){
  100138. sqlite3_free(azChar);
  100139. }
  100140. }
  100141. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  100142. }
  100143. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  100144. /*
  100145. ** The "unknown" function is automatically substituted in place of
  100146. ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
  100147. ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
  100148. ** When the "sqlite3" command-line shell is built using this functionality,
  100149. ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
  100150. ** involving application-defined functions to be examined in a generic
  100151. ** sqlite3 shell.
  100152. */
  100153. static void unknownFunc(
  100154. sqlite3_context *context,
  100155. int argc,
  100156. sqlite3_value **argv
  100157. ){
  100158. /* no-op */
  100159. }
  100160. #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
  100161. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  100162. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  100163. ** when SQLite is built.
  100164. */
  100165. #ifdef SQLITE_SOUNDEX
  100166. /*
  100167. ** Compute the soundex encoding of a word.
  100168. **
  100169. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  100170. ** soundex encoding of the string X.
  100171. */
  100172. static void soundexFunc(
  100173. sqlite3_context *context,
  100174. int argc,
  100175. sqlite3_value **argv
  100176. ){
  100177. char zResult[8];
  100178. const u8 *zIn;
  100179. int i, j;
  100180. static const unsigned char iCode[] = {
  100181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  100182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  100183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  100184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  100185. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  100186. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  100187. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  100188. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  100189. };
  100190. assert( argc==1 );
  100191. zIn = (u8*)sqlite3_value_text(argv[0]);
  100192. if( zIn==0 ) zIn = (u8*)"";
  100193. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  100194. if( zIn[i] ){
  100195. u8 prevcode = iCode[zIn[i]&0x7f];
  100196. zResult[0] = sqlite3Toupper(zIn[i]);
  100197. for(j=1; j<4 && zIn[i]; i++){
  100198. int code = iCode[zIn[i]&0x7f];
  100199. if( code>0 ){
  100200. if( code!=prevcode ){
  100201. prevcode = code;
  100202. zResult[j++] = code + '0';
  100203. }
  100204. }else{
  100205. prevcode = 0;
  100206. }
  100207. }
  100208. while( j<4 ){
  100209. zResult[j++] = '0';
  100210. }
  100211. zResult[j] = 0;
  100212. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  100213. }else{
  100214. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  100215. ** is NULL or contains no ASCII alphabetic characters. */
  100216. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  100217. }
  100218. }
  100219. #endif /* SQLITE_SOUNDEX */
  100220. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  100221. /*
  100222. ** A function that loads a shared-library extension then returns NULL.
  100223. */
  100224. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  100225. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  100226. const char *zProc;
  100227. sqlite3 *db = sqlite3_context_db_handle(context);
  100228. char *zErrMsg = 0;
  100229. /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
  100230. ** flag is set. See the sqlite3_enable_load_extension() API.
  100231. */
  100232. if( (db->flags & SQLITE_LoadExtFunc)==0 ){
  100233. sqlite3_result_error(context, "not authorized", -1);
  100234. return;
  100235. }
  100236. if( argc==2 ){
  100237. zProc = (const char *)sqlite3_value_text(argv[1]);
  100238. }else{
  100239. zProc = 0;
  100240. }
  100241. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  100242. sqlite3_result_error(context, zErrMsg, -1);
  100243. sqlite3_free(zErrMsg);
  100244. }
  100245. }
  100246. #endif
  100247. /*
  100248. ** An instance of the following structure holds the context of a
  100249. ** sum() or avg() aggregate computation.
  100250. */
  100251. typedef struct SumCtx SumCtx;
  100252. struct SumCtx {
  100253. double rSum; /* Floating point sum */
  100254. i64 iSum; /* Integer sum */
  100255. i64 cnt; /* Number of elements summed */
  100256. u8 overflow; /* True if integer overflow seen */
  100257. u8 approx; /* True if non-integer value was input to the sum */
  100258. };
  100259. /*
  100260. ** Routines used to compute the sum, average, and total.
  100261. **
  100262. ** The SUM() function follows the (broken) SQL standard which means
  100263. ** that it returns NULL if it sums over no inputs. TOTAL returns
  100264. ** 0.0 in that case. In addition, TOTAL always returns a float where
  100265. ** SUM might return an integer if it never encounters a floating point
  100266. ** value. TOTAL never fails, but SUM might through an exception if
  100267. ** it overflows an integer.
  100268. */
  100269. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  100270. SumCtx *p;
  100271. int type;
  100272. assert( argc==1 );
  100273. UNUSED_PARAMETER(argc);
  100274. p = sqlite3_aggregate_context(context, sizeof(*p));
  100275. type = sqlite3_value_numeric_type(argv[0]);
  100276. if( p && type!=SQLITE_NULL ){
  100277. p->cnt++;
  100278. if( type==SQLITE_INTEGER ){
  100279. i64 v = sqlite3_value_int64(argv[0]);
  100280. p->rSum += v;
  100281. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  100282. p->overflow = 1;
  100283. }
  100284. }else{
  100285. p->rSum += sqlite3_value_double(argv[0]);
  100286. p->approx = 1;
  100287. }
  100288. }
  100289. }
  100290. static void sumFinalize(sqlite3_context *context){
  100291. SumCtx *p;
  100292. p = sqlite3_aggregate_context(context, 0);
  100293. if( p && p->cnt>0 ){
  100294. if( p->overflow ){
  100295. sqlite3_result_error(context,"integer overflow",-1);
  100296. }else if( p->approx ){
  100297. sqlite3_result_double(context, p->rSum);
  100298. }else{
  100299. sqlite3_result_int64(context, p->iSum);
  100300. }
  100301. }
  100302. }
  100303. static void avgFinalize(sqlite3_context *context){
  100304. SumCtx *p;
  100305. p = sqlite3_aggregate_context(context, 0);
  100306. if( p && p->cnt>0 ){
  100307. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  100308. }
  100309. }
  100310. static void totalFinalize(sqlite3_context *context){
  100311. SumCtx *p;
  100312. p = sqlite3_aggregate_context(context, 0);
  100313. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  100314. sqlite3_result_double(context, p ? p->rSum : (double)0);
  100315. }
  100316. /*
  100317. ** The following structure keeps track of state information for the
  100318. ** count() aggregate function.
  100319. */
  100320. typedef struct CountCtx CountCtx;
  100321. struct CountCtx {
  100322. i64 n;
  100323. };
  100324. /*
  100325. ** Routines to implement the count() aggregate function.
  100326. */
  100327. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  100328. CountCtx *p;
  100329. p = sqlite3_aggregate_context(context, sizeof(*p));
  100330. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  100331. p->n++;
  100332. }
  100333. #ifndef SQLITE_OMIT_DEPRECATED
  100334. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  100335. ** sure it still operates correctly, verify that its count agrees with our
  100336. ** internal count when using count(*) and when the total count can be
  100337. ** expressed as a 32-bit integer. */
  100338. assert( argc==1 || p==0 || p->n>0x7fffffff
  100339. || p->n==sqlite3_aggregate_count(context) );
  100340. #endif
  100341. }
  100342. static void countFinalize(sqlite3_context *context){
  100343. CountCtx *p;
  100344. p = sqlite3_aggregate_context(context, 0);
  100345. sqlite3_result_int64(context, p ? p->n : 0);
  100346. }
  100347. /*
  100348. ** Routines to implement min() and max() aggregate functions.
  100349. */
  100350. static void minmaxStep(
  100351. sqlite3_context *context,
  100352. int NotUsed,
  100353. sqlite3_value **argv
  100354. ){
  100355. Mem *pArg = (Mem *)argv[0];
  100356. Mem *pBest;
  100357. UNUSED_PARAMETER(NotUsed);
  100358. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  100359. if( !pBest ) return;
  100360. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  100361. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  100362. }else if( pBest->flags ){
  100363. int max;
  100364. int cmp;
  100365. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  100366. /* This step function is used for both the min() and max() aggregates,
  100367. ** the only difference between the two being that the sense of the
  100368. ** comparison is inverted. For the max() aggregate, the
  100369. ** sqlite3_user_data() function returns (void *)-1. For min() it
  100370. ** returns (void *)db, where db is the sqlite3* database pointer.
  100371. ** Therefore the next statement sets variable 'max' to 1 for the max()
  100372. ** aggregate, or 0 for min().
  100373. */
  100374. max = sqlite3_user_data(context)!=0;
  100375. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  100376. if( (max && cmp<0) || (!max && cmp>0) ){
  100377. sqlite3VdbeMemCopy(pBest, pArg);
  100378. }else{
  100379. sqlite3SkipAccumulatorLoad(context);
  100380. }
  100381. }else{
  100382. pBest->db = sqlite3_context_db_handle(context);
  100383. sqlite3VdbeMemCopy(pBest, pArg);
  100384. }
  100385. }
  100386. static void minMaxFinalize(sqlite3_context *context){
  100387. sqlite3_value *pRes;
  100388. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  100389. if( pRes ){
  100390. if( pRes->flags ){
  100391. sqlite3_result_value(context, pRes);
  100392. }
  100393. sqlite3VdbeMemRelease(pRes);
  100394. }
  100395. }
  100396. /*
  100397. ** group_concat(EXPR, ?SEPARATOR?)
  100398. */
  100399. static void groupConcatStep(
  100400. sqlite3_context *context,
  100401. int argc,
  100402. sqlite3_value **argv
  100403. ){
  100404. const char *zVal;
  100405. StrAccum *pAccum;
  100406. const char *zSep;
  100407. int nVal, nSep;
  100408. assert( argc==1 || argc==2 );
  100409. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  100410. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  100411. if( pAccum ){
  100412. sqlite3 *db = sqlite3_context_db_handle(context);
  100413. int firstTerm = pAccum->mxAlloc==0;
  100414. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  100415. if( !firstTerm ){
  100416. if( argc==2 ){
  100417. zSep = (char*)sqlite3_value_text(argv[1]);
  100418. nSep = sqlite3_value_bytes(argv[1]);
  100419. }else{
  100420. zSep = ",";
  100421. nSep = 1;
  100422. }
  100423. if( zSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
  100424. }
  100425. zVal = (char*)sqlite3_value_text(argv[0]);
  100426. nVal = sqlite3_value_bytes(argv[0]);
  100427. if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
  100428. }
  100429. }
  100430. static void groupConcatFinalize(sqlite3_context *context){
  100431. StrAccum *pAccum;
  100432. pAccum = sqlite3_aggregate_context(context, 0);
  100433. if( pAccum ){
  100434. if( pAccum->accError==STRACCUM_TOOBIG ){
  100435. sqlite3_result_error_toobig(context);
  100436. }else if( pAccum->accError==STRACCUM_NOMEM ){
  100437. sqlite3_result_error_nomem(context);
  100438. }else{
  100439. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  100440. sqlite3_free);
  100441. }
  100442. }
  100443. }
  100444. /*
  100445. ** This routine does per-connection function registration. Most
  100446. ** of the built-in functions above are part of the global function set.
  100447. ** This routine only deals with those that are not global.
  100448. */
  100449. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
  100450. int rc = sqlite3_overload_function(db, "MATCH", 2);
  100451. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  100452. if( rc==SQLITE_NOMEM ){
  100453. sqlite3OomFault(db);
  100454. }
  100455. }
  100456. /*
  100457. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  100458. */
  100459. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  100460. FuncDef *pDef;
  100461. pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
  100462. if( ALWAYS(pDef) ){
  100463. pDef->funcFlags |= flagVal;
  100464. }
  100465. }
  100466. /*
  100467. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  100468. ** parameter determines whether or not the LIKE operator is case
  100469. ** sensitive. GLOB is always case sensitive.
  100470. */
  100471. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  100472. struct compareInfo *pInfo;
  100473. if( caseSensitive ){
  100474. pInfo = (struct compareInfo*)&likeInfoAlt;
  100475. }else{
  100476. pInfo = (struct compareInfo*)&likeInfoNorm;
  100477. }
  100478. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  100479. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  100480. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  100481. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  100482. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  100483. setLikeOptFlag(db, "like",
  100484. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  100485. }
  100486. /*
  100487. ** pExpr points to an expression which implements a function. If
  100488. ** it is appropriate to apply the LIKE optimization to that function
  100489. ** then set aWc[0] through aWc[2] to the wildcard characters and
  100490. ** return TRUE. If the function is not a LIKE-style function then
  100491. ** return FALSE.
  100492. **
  100493. ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
  100494. ** the function (default for LIKE). If the function makes the distinction
  100495. ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
  100496. ** false.
  100497. */
  100498. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  100499. FuncDef *pDef;
  100500. if( pExpr->op!=TK_FUNCTION
  100501. || !pExpr->x.pList
  100502. || pExpr->x.pList->nExpr!=2
  100503. ){
  100504. return 0;
  100505. }
  100506. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  100507. pDef = sqlite3FindFunction(db, pExpr->u.zToken, 2, SQLITE_UTF8, 0);
  100508. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  100509. return 0;
  100510. }
  100511. /* The memcpy() statement assumes that the wildcard characters are
  100512. ** the first three statements in the compareInfo structure. The
  100513. ** asserts() that follow verify that assumption
  100514. */
  100515. memcpy(aWc, pDef->pUserData, 3);
  100516. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  100517. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  100518. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  100519. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  100520. return 1;
  100521. }
  100522. /*
  100523. ** All of the FuncDef structures in the aBuiltinFunc[] array above
  100524. ** to the global function hash table. This occurs at start-time (as
  100525. ** a consequence of calling sqlite3_initialize()).
  100526. **
  100527. ** After this routine runs
  100528. */
  100529. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
  100530. /*
  100531. ** The following array holds FuncDef structures for all of the functions
  100532. ** defined in this file.
  100533. **
  100534. ** The array cannot be constant since changes are made to the
  100535. ** FuncDef.pHash elements at start-time. The elements of this array
  100536. ** are read-only after initialization is complete.
  100537. **
  100538. ** For peak efficiency, put the most frequently used function last.
  100539. */
  100540. static FuncDef aBuiltinFunc[] = {
  100541. #ifdef SQLITE_SOUNDEX
  100542. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  100543. #endif
  100544. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  100545. VFUNCTION(load_extension, 1, 0, 0, loadExt ),
  100546. VFUNCTION(load_extension, 2, 0, 0, loadExt ),
  100547. #endif
  100548. #if SQLITE_USER_AUTHENTICATION
  100549. FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
  100550. #endif
  100551. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  100552. DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  100553. DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  100554. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  100555. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  100556. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  100557. FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  100558. #ifdef SQLITE_DEBUG
  100559. FUNCTION2(affinity, 1, 0, 0, noopFunc, SQLITE_FUNC_AFFINITY),
  100560. #endif
  100561. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  100562. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  100563. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  100564. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  100565. FUNCTION(trim, 1, 3, 0, trimFunc ),
  100566. FUNCTION(trim, 2, 3, 0, trimFunc ),
  100567. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  100568. FUNCTION(min, 0, 0, 1, 0 ),
  100569. AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize,
  100570. SQLITE_FUNC_MINMAX ),
  100571. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  100572. FUNCTION(max, 0, 1, 1, 0 ),
  100573. AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize,
  100574. SQLITE_FUNC_MINMAX ),
  100575. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  100576. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  100577. FUNCTION(instr, 2, 0, 0, instrFunc ),
  100578. FUNCTION(printf, -1, 0, 0, printfFunc ),
  100579. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  100580. FUNCTION(char, -1, 0, 0, charFunc ),
  100581. FUNCTION(abs, 1, 0, 0, absFunc ),
  100582. #ifndef SQLITE_OMIT_FLOATING_POINT
  100583. FUNCTION(round, 1, 0, 0, roundFunc ),
  100584. FUNCTION(round, 2, 0, 0, roundFunc ),
  100585. #endif
  100586. FUNCTION(upper, 1, 0, 0, upperFunc ),
  100587. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  100588. FUNCTION(hex, 1, 0, 0, hexFunc ),
  100589. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  100590. VFUNCTION(random, 0, 0, 0, randomFunc ),
  100591. VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
  100592. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  100593. DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  100594. DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  100595. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  100596. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  100597. VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  100598. VFUNCTION(changes, 0, 0, 0, changes ),
  100599. VFUNCTION(total_changes, 0, 0, 0, total_changes ),
  100600. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  100601. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  100602. FUNCTION(substr, 2, 0, 0, substrFunc ),
  100603. FUNCTION(substr, 3, 0, 0, substrFunc ),
  100604. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  100605. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  100606. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  100607. AGGREGATE2(count, 0, 0, 0, countStep, countFinalize,
  100608. SQLITE_FUNC_COUNT ),
  100609. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  100610. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  100611. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  100612. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  100613. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  100614. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  100615. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  100616. #else
  100617. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  100618. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  100619. #endif
  100620. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  100621. FUNCTION(unknown, -1, 0, 0, unknownFunc ),
  100622. #endif
  100623. FUNCTION(coalesce, 1, 0, 0, 0 ),
  100624. FUNCTION(coalesce, 0, 0, 0, 0 ),
  100625. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  100626. };
  100627. #ifndef SQLITE_OMIT_ALTERTABLE
  100628. sqlite3AlterFunctions();
  100629. #endif
  100630. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  100631. sqlite3AnalyzeFunctions();
  100632. #endif
  100633. sqlite3RegisterDateTimeFunctions();
  100634. sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
  100635. #if 0 /* Enable to print out how the built-in functions are hashed */
  100636. {
  100637. int i;
  100638. FuncDef *p;
  100639. for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
  100640. printf("FUNC-HASH %02d:", i);
  100641. for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
  100642. int n = sqlite3Strlen30(p->zName);
  100643. int h = p->zName[0] + n;
  100644. printf(" %s(%d)", p->zName, h);
  100645. }
  100646. printf("\n");
  100647. }
  100648. }
  100649. #endif
  100650. }
  100651. /************** End of func.c ************************************************/
  100652. /************** Begin file fkey.c ********************************************/
  100653. /*
  100654. **
  100655. ** The author disclaims copyright to this source code. In place of
  100656. ** a legal notice, here is a blessing:
  100657. **
  100658. ** May you do good and not evil.
  100659. ** May you find forgiveness for yourself and forgive others.
  100660. ** May you share freely, never taking more than you give.
  100661. **
  100662. *************************************************************************
  100663. ** This file contains code used by the compiler to add foreign key
  100664. ** support to compiled SQL statements.
  100665. */
  100666. /* #include "sqliteInt.h" */
  100667. #ifndef SQLITE_OMIT_FOREIGN_KEY
  100668. #ifndef SQLITE_OMIT_TRIGGER
  100669. /*
  100670. ** Deferred and Immediate FKs
  100671. ** --------------------------
  100672. **
  100673. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  100674. ** If an immediate foreign key constraint is violated,
  100675. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  100676. ** statement transaction rolled back. If a
  100677. ** deferred foreign key constraint is violated, no action is taken
  100678. ** immediately. However if the application attempts to commit the
  100679. ** transaction before fixing the constraint violation, the attempt fails.
  100680. **
  100681. ** Deferred constraints are implemented using a simple counter associated
  100682. ** with the database handle. The counter is set to zero each time a
  100683. ** database transaction is opened. Each time a statement is executed
  100684. ** that causes a foreign key violation, the counter is incremented. Each
  100685. ** time a statement is executed that removes an existing violation from
  100686. ** the database, the counter is decremented. When the transaction is
  100687. ** committed, the commit fails if the current value of the counter is
  100688. ** greater than zero. This scheme has two big drawbacks:
  100689. **
  100690. ** * When a commit fails due to a deferred foreign key constraint,
  100691. ** there is no way to tell which foreign constraint is not satisfied,
  100692. ** or which row it is not satisfied for.
  100693. **
  100694. ** * If the database contains foreign key violations when the
  100695. ** transaction is opened, this may cause the mechanism to malfunction.
  100696. **
  100697. ** Despite these problems, this approach is adopted as it seems simpler
  100698. ** than the alternatives.
  100699. **
  100700. ** INSERT operations:
  100701. **
  100702. ** I.1) For each FK for which the table is the child table, search
  100703. ** the parent table for a match. If none is found increment the
  100704. ** constraint counter.
  100705. **
  100706. ** I.2) For each FK for which the table is the parent table,
  100707. ** search the child table for rows that correspond to the new
  100708. ** row in the parent table. Decrement the counter for each row
  100709. ** found (as the constraint is now satisfied).
  100710. **
  100711. ** DELETE operations:
  100712. **
  100713. ** D.1) For each FK for which the table is the child table,
  100714. ** search the parent table for a row that corresponds to the
  100715. ** deleted row in the child table. If such a row is not found,
  100716. ** decrement the counter.
  100717. **
  100718. ** D.2) For each FK for which the table is the parent table, search
  100719. ** the child table for rows that correspond to the deleted row
  100720. ** in the parent table. For each found increment the counter.
  100721. **
  100722. ** UPDATE operations:
  100723. **
  100724. ** An UPDATE command requires that all 4 steps above are taken, but only
  100725. ** for FK constraints for which the affected columns are actually
  100726. ** modified (values must be compared at runtime).
  100727. **
  100728. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  100729. ** This simplifies the implementation a bit.
  100730. **
  100731. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  100732. ** resolution is considered to delete rows before the new row is inserted.
  100733. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  100734. ** is thrown, even if the FK constraint would be satisfied after the new
  100735. ** row is inserted.
  100736. **
  100737. ** Immediate constraints are usually handled similarly. The only difference
  100738. ** is that the counter used is stored as part of each individual statement
  100739. ** object (struct Vdbe). If, after the statement has run, its immediate
  100740. ** constraint counter is greater than zero,
  100741. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  100742. ** and the statement transaction is rolled back. An exception is an INSERT
  100743. ** statement that inserts a single row only (no triggers). In this case,
  100744. ** instead of using a counter, an exception is thrown immediately if the
  100745. ** INSERT violates a foreign key constraint. This is necessary as such
  100746. ** an INSERT does not open a statement transaction.
  100747. **
  100748. ** TODO: How should dropping a table be handled? How should renaming a
  100749. ** table be handled?
  100750. **
  100751. **
  100752. ** Query API Notes
  100753. ** ---------------
  100754. **
  100755. ** Before coding an UPDATE or DELETE row operation, the code-generator
  100756. ** for those two operations needs to know whether or not the operation
  100757. ** requires any FK processing and, if so, which columns of the original
  100758. ** row are required by the FK processing VDBE code (i.e. if FKs were
  100759. ** implemented using triggers, which of the old.* columns would be
  100760. ** accessed). No information is required by the code-generator before
  100761. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  100762. ** generation code to query for this information are:
  100763. **
  100764. ** sqlite3FkRequired() - Test to see if FK processing is required.
  100765. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  100766. **
  100767. **
  100768. ** Externally accessible module functions
  100769. ** --------------------------------------
  100770. **
  100771. ** sqlite3FkCheck() - Check for foreign key violations.
  100772. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  100773. ** sqlite3FkDelete() - Delete an FKey structure.
  100774. */
  100775. /*
  100776. ** VDBE Calling Convention
  100777. ** -----------------------
  100778. **
  100779. ** Example:
  100780. **
  100781. ** For the following INSERT statement:
  100782. **
  100783. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  100784. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  100785. **
  100786. ** Register (x): 2 (type integer)
  100787. ** Register (x+1): 1 (type integer)
  100788. ** Register (x+2): NULL (type NULL)
  100789. ** Register (x+3): 3.1 (type real)
  100790. */
  100791. /*
  100792. ** A foreign key constraint requires that the key columns in the parent
  100793. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  100794. ** Given that pParent is the parent table for foreign key constraint pFKey,
  100795. ** search the schema for a unique index on the parent key columns.
  100796. **
  100797. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  100798. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  100799. ** is set to point to the unique index.
  100800. **
  100801. ** If the parent key consists of a single column (the foreign key constraint
  100802. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  100803. ** Otherwise, it is set to point to an allocated array of size N, where
  100804. ** N is the number of columns in the parent key. The first element of the
  100805. ** array is the index of the child table column that is mapped by the FK
  100806. ** constraint to the parent table column stored in the left-most column
  100807. ** of index *ppIdx. The second element of the array is the index of the
  100808. ** child table column that corresponds to the second left-most column of
  100809. ** *ppIdx, and so on.
  100810. **
  100811. ** If the required index cannot be found, either because:
  100812. **
  100813. ** 1) The named parent key columns do not exist, or
  100814. **
  100815. ** 2) The named parent key columns do exist, but are not subject to a
  100816. ** UNIQUE or PRIMARY KEY constraint, or
  100817. **
  100818. ** 3) No parent key columns were provided explicitly as part of the
  100819. ** foreign key definition, and the parent table does not have a
  100820. ** PRIMARY KEY, or
  100821. **
  100822. ** 4) No parent key columns were provided explicitly as part of the
  100823. ** foreign key definition, and the PRIMARY KEY of the parent table
  100824. ** consists of a different number of columns to the child key in
  100825. ** the child table.
  100826. **
  100827. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  100828. ** into pParse. If an OOM error occurs, non-zero is returned and the
  100829. ** pParse->db->mallocFailed flag is set.
  100830. */
  100831. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  100832. Parse *pParse, /* Parse context to store any error in */
  100833. Table *pParent, /* Parent table of FK constraint pFKey */
  100834. FKey *pFKey, /* Foreign key to find index for */
  100835. Index **ppIdx, /* OUT: Unique index on parent table */
  100836. int **paiCol /* OUT: Map of index columns in pFKey */
  100837. ){
  100838. Index *pIdx = 0; /* Value to return via *ppIdx */
  100839. int *aiCol = 0; /* Value to return via *paiCol */
  100840. int nCol = pFKey->nCol; /* Number of columns in parent key */
  100841. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  100842. /* The caller is responsible for zeroing output parameters. */
  100843. assert( ppIdx && *ppIdx==0 );
  100844. assert( !paiCol || *paiCol==0 );
  100845. assert( pParse );
  100846. /* If this is a non-composite (single column) foreign key, check if it
  100847. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  100848. ** and *paiCol set to zero and return early.
  100849. **
  100850. ** Otherwise, for a composite foreign key (more than one column), allocate
  100851. ** space for the aiCol array (returned via output parameter *paiCol).
  100852. ** Non-composite foreign keys do not require the aiCol array.
  100853. */
  100854. if( nCol==1 ){
  100855. /* The FK maps to the IPK if any of the following are true:
  100856. **
  100857. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  100858. ** mapped to the primary key of table pParent, or
  100859. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  100860. ** PRIMARY KEY.
  100861. */
  100862. if( pParent->iPKey>=0 ){
  100863. if( !zKey ) return 0;
  100864. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  100865. }
  100866. }else if( paiCol ){
  100867. assert( nCol>1 );
  100868. aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
  100869. if( !aiCol ) return 1;
  100870. *paiCol = aiCol;
  100871. }
  100872. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  100873. if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
  100874. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  100875. ** of columns. If each indexed column corresponds to a foreign key
  100876. ** column of pFKey, then this index is a winner. */
  100877. if( zKey==0 ){
  100878. /* If zKey is NULL, then this foreign key is implicitly mapped to
  100879. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  100880. ** identified by the test. */
  100881. if( IsPrimaryKeyIndex(pIdx) ){
  100882. if( aiCol ){
  100883. int i;
  100884. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  100885. }
  100886. break;
  100887. }
  100888. }else{
  100889. /* If zKey is non-NULL, then this foreign key was declared to
  100890. ** map to an explicit list of columns in table pParent. Check if this
  100891. ** index matches those columns. Also, check that the index uses
  100892. ** the default collation sequences for each column. */
  100893. int i, j;
  100894. for(i=0; i<nCol; i++){
  100895. i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  100896. const char *zDfltColl; /* Def. collation for column */
  100897. char *zIdxCol; /* Name of indexed column */
  100898. if( iCol<0 ) break; /* No foreign keys against expression indexes */
  100899. /* If the index uses a collation sequence that is different from
  100900. ** the default collation sequence for the column, this index is
  100901. ** unusable. Bail out early in this case. */
  100902. zDfltColl = pParent->aCol[iCol].zColl;
  100903. if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
  100904. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  100905. zIdxCol = pParent->aCol[iCol].zName;
  100906. for(j=0; j<nCol; j++){
  100907. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  100908. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  100909. break;
  100910. }
  100911. }
  100912. if( j==nCol ) break;
  100913. }
  100914. if( i==nCol ) break; /* pIdx is usable */
  100915. }
  100916. }
  100917. }
  100918. if( !pIdx ){
  100919. if( !pParse->disableTriggers ){
  100920. sqlite3ErrorMsg(pParse,
  100921. "foreign key mismatch - \"%w\" referencing \"%w\"",
  100922. pFKey->pFrom->zName, pFKey->zTo);
  100923. }
  100924. sqlite3DbFree(pParse->db, aiCol);
  100925. return 1;
  100926. }
  100927. *ppIdx = pIdx;
  100928. return 0;
  100929. }
  100930. /*
  100931. ** This function is called when a row is inserted into or deleted from the
  100932. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  100933. ** on the child table of pFKey, this function is invoked twice for each row
  100934. ** affected - once to "delete" the old row, and then again to "insert" the
  100935. ** new row.
  100936. **
  100937. ** Each time it is called, this function generates VDBE code to locate the
  100938. ** row in the parent table that corresponds to the row being inserted into
  100939. ** or deleted from the child table. If the parent row can be found, no
  100940. ** special action is taken. Otherwise, if the parent row can *not* be
  100941. ** found in the parent table:
  100942. **
  100943. ** Operation | FK type | Action taken
  100944. ** --------------------------------------------------------------------------
  100945. ** INSERT immediate Increment the "immediate constraint counter".
  100946. **
  100947. ** DELETE immediate Decrement the "immediate constraint counter".
  100948. **
  100949. ** INSERT deferred Increment the "deferred constraint counter".
  100950. **
  100951. ** DELETE deferred Decrement the "deferred constraint counter".
  100952. **
  100953. ** These operations are identified in the comment at the top of this file
  100954. ** (fkey.c) as "I.1" and "D.1".
  100955. */
  100956. static void fkLookupParent(
  100957. Parse *pParse, /* Parse context */
  100958. int iDb, /* Index of database housing pTab */
  100959. Table *pTab, /* Parent table of FK pFKey */
  100960. Index *pIdx, /* Unique index on parent key columns in pTab */
  100961. FKey *pFKey, /* Foreign key constraint */
  100962. int *aiCol, /* Map from parent key columns to child table columns */
  100963. int regData, /* Address of array containing child table row */
  100964. int nIncr, /* Increment constraint counter by this */
  100965. int isIgnore /* If true, pretend pTab contains all NULL values */
  100966. ){
  100967. int i; /* Iterator variable */
  100968. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  100969. int iCur = pParse->nTab - 1; /* Cursor number to use */
  100970. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  100971. /* If nIncr is less than zero, then check at runtime if there are any
  100972. ** outstanding constraints to resolve. If there are not, there is no need
  100973. ** to check if deleting this row resolves any outstanding violations.
  100974. **
  100975. ** Check if any of the key columns in the child table row are NULL. If
  100976. ** any are, then the constraint is considered satisfied. No need to
  100977. ** search for a matching row in the parent table. */
  100978. if( nIncr<0 ){
  100979. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  100980. VdbeCoverage(v);
  100981. }
  100982. for(i=0; i<pFKey->nCol; i++){
  100983. int iReg = aiCol[i] + regData + 1;
  100984. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
  100985. }
  100986. if( isIgnore==0 ){
  100987. if( pIdx==0 ){
  100988. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  100989. ** column of the parent table (table pTab). */
  100990. int iMustBeInt; /* Address of MustBeInt instruction */
  100991. int regTemp = sqlite3GetTempReg(pParse);
  100992. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  100993. ** apply the affinity of the parent key). If this fails, then there
  100994. ** is no matching parent key. Before using MustBeInt, make a copy of
  100995. ** the value. Otherwise, the value inserted into the child key column
  100996. ** will have INTEGER affinity applied to it, which may not be correct. */
  100997. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  100998. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  100999. VdbeCoverage(v);
  101000. /* If the parent table is the same as the child table, and we are about
  101001. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  101002. ** then check if the row being inserted matches itself. If so, do not
  101003. ** increment the constraint-counter. */
  101004. if( pTab==pFKey->pFrom && nIncr==1 ){
  101005. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
  101006. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  101007. }
  101008. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  101009. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
  101010. sqlite3VdbeGoto(v, iOk);
  101011. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  101012. sqlite3VdbeJumpHere(v, iMustBeInt);
  101013. sqlite3ReleaseTempReg(pParse, regTemp);
  101014. }else{
  101015. int nCol = pFKey->nCol;
  101016. int regTemp = sqlite3GetTempRange(pParse, nCol);
  101017. int regRec = sqlite3GetTempReg(pParse);
  101018. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  101019. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  101020. for(i=0; i<nCol; i++){
  101021. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  101022. }
  101023. /* If the parent table is the same as the child table, and we are about
  101024. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  101025. ** then check if the row being inserted matches itself. If so, do not
  101026. ** increment the constraint-counter.
  101027. **
  101028. ** If any of the parent-key values are NULL, then the row cannot match
  101029. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  101030. ** of the parent-key values are NULL (at this point it is known that
  101031. ** none of the child key values are).
  101032. */
  101033. if( pTab==pFKey->pFrom && nIncr==1 ){
  101034. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  101035. for(i=0; i<nCol; i++){
  101036. int iChild = aiCol[i]+1+regData;
  101037. int iParent = pIdx->aiColumn[i]+1+regData;
  101038. assert( pIdx->aiColumn[i]>=0 );
  101039. assert( aiCol[i]!=pTab->iPKey );
  101040. if( pIdx->aiColumn[i]==pTab->iPKey ){
  101041. /* The parent key is a composite key that includes the IPK column */
  101042. iParent = regData;
  101043. }
  101044. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
  101045. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  101046. }
  101047. sqlite3VdbeGoto(v, iOk);
  101048. }
  101049. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
  101050. sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
  101051. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
  101052. sqlite3ReleaseTempReg(pParse, regRec);
  101053. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  101054. }
  101055. }
  101056. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  101057. && !pParse->pToplevel
  101058. && !pParse->isMultiWrite
  101059. ){
  101060. /* Special case: If this is an INSERT statement that will insert exactly
  101061. ** one row into the table, raise a constraint immediately instead of
  101062. ** incrementing a counter. This is necessary as the VM code is being
  101063. ** generated for will not open a statement transaction. */
  101064. assert( nIncr==1 );
  101065. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  101066. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  101067. }else{
  101068. if( nIncr>0 && pFKey->isDeferred==0 ){
  101069. sqlite3MayAbort(pParse);
  101070. }
  101071. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  101072. }
  101073. sqlite3VdbeResolveLabel(v, iOk);
  101074. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  101075. }
  101076. /*
  101077. ** Return an Expr object that refers to a memory register corresponding
  101078. ** to column iCol of table pTab.
  101079. **
  101080. ** regBase is the first of an array of register that contains the data
  101081. ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
  101082. ** column. regBase+2 holds the second column, and so forth.
  101083. */
  101084. static Expr *exprTableRegister(
  101085. Parse *pParse, /* Parsing and code generating context */
  101086. Table *pTab, /* The table whose content is at r[regBase]... */
  101087. int regBase, /* Contents of table pTab */
  101088. i16 iCol /* Which column of pTab is desired */
  101089. ){
  101090. Expr *pExpr;
  101091. Column *pCol;
  101092. const char *zColl;
  101093. sqlite3 *db = pParse->db;
  101094. pExpr = sqlite3Expr(db, TK_REGISTER, 0);
  101095. if( pExpr ){
  101096. if( iCol>=0 && iCol!=pTab->iPKey ){
  101097. pCol = &pTab->aCol[iCol];
  101098. pExpr->iTable = regBase + iCol + 1;
  101099. pExpr->affinity = pCol->affinity;
  101100. zColl = pCol->zColl;
  101101. if( zColl==0 ) zColl = db->pDfltColl->zName;
  101102. pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
  101103. }else{
  101104. pExpr->iTable = regBase;
  101105. pExpr->affinity = SQLITE_AFF_INTEGER;
  101106. }
  101107. }
  101108. return pExpr;
  101109. }
  101110. /*
  101111. ** Return an Expr object that refers to column iCol of table pTab which
  101112. ** has cursor iCur.
  101113. */
  101114. static Expr *exprTableColumn(
  101115. sqlite3 *db, /* The database connection */
  101116. Table *pTab, /* The table whose column is desired */
  101117. int iCursor, /* The open cursor on the table */
  101118. i16 iCol /* The column that is wanted */
  101119. ){
  101120. Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
  101121. if( pExpr ){
  101122. pExpr->pTab = pTab;
  101123. pExpr->iTable = iCursor;
  101124. pExpr->iColumn = iCol;
  101125. }
  101126. return pExpr;
  101127. }
  101128. /*
  101129. ** This function is called to generate code executed when a row is deleted
  101130. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  101131. ** deferred, when a row is inserted into the same table. When generating
  101132. ** code for an SQL UPDATE operation, this function may be called twice -
  101133. ** once to "delete" the old row and once to "insert" the new row.
  101134. **
  101135. ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
  101136. ** the number of FK violations in the db) or +1 when deleting one (as this
  101137. ** may increase the number of FK constraint problems).
  101138. **
  101139. ** The code generated by this function scans through the rows in the child
  101140. ** table that correspond to the parent table row being deleted or inserted.
  101141. ** For each child row found, one of the following actions is taken:
  101142. **
  101143. ** Operation | FK type | Action taken
  101144. ** --------------------------------------------------------------------------
  101145. ** DELETE immediate Increment the "immediate constraint counter".
  101146. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  101147. ** throw a "FOREIGN KEY constraint failed" exception.
  101148. **
  101149. ** INSERT immediate Decrement the "immediate constraint counter".
  101150. **
  101151. ** DELETE deferred Increment the "deferred constraint counter".
  101152. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  101153. ** throw a "FOREIGN KEY constraint failed" exception.
  101154. **
  101155. ** INSERT deferred Decrement the "deferred constraint counter".
  101156. **
  101157. ** These operations are identified in the comment at the top of this file
  101158. ** (fkey.c) as "I.2" and "D.2".
  101159. */
  101160. static void fkScanChildren(
  101161. Parse *pParse, /* Parse context */
  101162. SrcList *pSrc, /* The child table to be scanned */
  101163. Table *pTab, /* The parent table */
  101164. Index *pIdx, /* Index on parent covering the foreign key */
  101165. FKey *pFKey, /* The foreign key linking pSrc to pTab */
  101166. int *aiCol, /* Map from pIdx cols to child table cols */
  101167. int regData, /* Parent row data starts here */
  101168. int nIncr /* Amount to increment deferred counter by */
  101169. ){
  101170. sqlite3 *db = pParse->db; /* Database handle */
  101171. int i; /* Iterator variable */
  101172. Expr *pWhere = 0; /* WHERE clause to scan with */
  101173. NameContext sNameContext; /* Context used to resolve WHERE clause */
  101174. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  101175. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  101176. Vdbe *v = sqlite3GetVdbe(pParse);
  101177. assert( pIdx==0 || pIdx->pTable==pTab );
  101178. assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
  101179. assert( pIdx!=0 || pFKey->nCol==1 );
  101180. assert( pIdx!=0 || HasRowid(pTab) );
  101181. if( nIncr<0 ){
  101182. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  101183. VdbeCoverage(v);
  101184. }
  101185. /* Create an Expr object representing an SQL expression like:
  101186. **
  101187. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  101188. **
  101189. ** The collation sequence used for the comparison should be that of
  101190. ** the parent key columns. The affinity of the parent key column should
  101191. ** be applied to each child key value before the comparison takes place.
  101192. */
  101193. for(i=0; i<pFKey->nCol; i++){
  101194. Expr *pLeft; /* Value from parent table row */
  101195. Expr *pRight; /* Column ref to child table */
  101196. Expr *pEq; /* Expression (pLeft = pRight) */
  101197. i16 iCol; /* Index of column in child table */
  101198. const char *zCol; /* Name of column in child table */
  101199. iCol = pIdx ? pIdx->aiColumn[i] : -1;
  101200. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  101201. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  101202. assert( iCol>=0 );
  101203. zCol = pFKey->pFrom->aCol[iCol].zName;
  101204. pRight = sqlite3Expr(db, TK_ID, zCol);
  101205. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
  101206. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  101207. }
  101208. /* If the child table is the same as the parent table, then add terms
  101209. ** to the WHERE clause that prevent this entry from being scanned.
  101210. ** The added WHERE clause terms are like this:
  101211. **
  101212. ** $current_rowid!=rowid
  101213. ** NOT( $current_a==a AND $current_b==b AND ... )
  101214. **
  101215. ** The first form is used for rowid tables. The second form is used
  101216. ** for WITHOUT ROWID tables. In the second form, the primary key is
  101217. ** (a,b,...)
  101218. */
  101219. if( pTab==pFKey->pFrom && nIncr>0 ){
  101220. Expr *pNe; /* Expression (pLeft != pRight) */
  101221. Expr *pLeft; /* Value from parent table row */
  101222. Expr *pRight; /* Column ref to child table */
  101223. if( HasRowid(pTab) ){
  101224. pLeft = exprTableRegister(pParse, pTab, regData, -1);
  101225. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
  101226. pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);
  101227. }else{
  101228. Expr *pEq, *pAll = 0;
  101229. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  101230. assert( pIdx!=0 );
  101231. for(i=0; i<pPk->nKeyCol; i++){
  101232. i16 iCol = pIdx->aiColumn[i];
  101233. assert( iCol>=0 );
  101234. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  101235. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
  101236. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
  101237. pAll = sqlite3ExprAnd(db, pAll, pEq);
  101238. }
  101239. pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);
  101240. }
  101241. pWhere = sqlite3ExprAnd(db, pWhere, pNe);
  101242. }
  101243. /* Resolve the references in the WHERE clause. */
  101244. memset(&sNameContext, 0, sizeof(NameContext));
  101245. sNameContext.pSrcList = pSrc;
  101246. sNameContext.pParse = pParse;
  101247. sqlite3ResolveExprNames(&sNameContext, pWhere);
  101248. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  101249. ** clause. For each row found, increment either the deferred or immediate
  101250. ** foreign key constraint counter. */
  101251. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  101252. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  101253. if( pWInfo ){
  101254. sqlite3WhereEnd(pWInfo);
  101255. }
  101256. /* Clean up the WHERE clause constructed above. */
  101257. sqlite3ExprDelete(db, pWhere);
  101258. if( iFkIfZero ){
  101259. sqlite3VdbeJumpHere(v, iFkIfZero);
  101260. }
  101261. }
  101262. /*
  101263. ** This function returns a linked list of FKey objects (connected by
  101264. ** FKey.pNextTo) holding all children of table pTab. For example,
  101265. ** given the following schema:
  101266. **
  101267. ** CREATE TABLE t1(a PRIMARY KEY);
  101268. ** CREATE TABLE t2(b REFERENCES t1(a);
  101269. **
  101270. ** Calling this function with table "t1" as an argument returns a pointer
  101271. ** to the FKey structure representing the foreign key constraint on table
  101272. ** "t2". Calling this function with "t2" as the argument would return a
  101273. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  101274. ** table).
  101275. */
  101276. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  101277. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
  101278. }
  101279. /*
  101280. ** The second argument is a Trigger structure allocated by the
  101281. ** fkActionTrigger() routine. This function deletes the Trigger structure
  101282. ** and all of its sub-components.
  101283. **
  101284. ** The Trigger structure or any of its sub-components may be allocated from
  101285. ** the lookaside buffer belonging to database handle dbMem.
  101286. */
  101287. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  101288. if( p ){
  101289. TriggerStep *pStep = p->step_list;
  101290. sqlite3ExprDelete(dbMem, pStep->pWhere);
  101291. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  101292. sqlite3SelectDelete(dbMem, pStep->pSelect);
  101293. sqlite3ExprDelete(dbMem, p->pWhen);
  101294. sqlite3DbFree(dbMem, p);
  101295. }
  101296. }
  101297. /*
  101298. ** This function is called to generate code that runs when table pTab is
  101299. ** being dropped from the database. The SrcList passed as the second argument
  101300. ** to this function contains a single entry guaranteed to resolve to
  101301. ** table pTab.
  101302. **
  101303. ** Normally, no code is required. However, if either
  101304. **
  101305. ** (a) The table is the parent table of a FK constraint, or
  101306. ** (b) The table is the child table of a deferred FK constraint and it is
  101307. ** determined at runtime that there are outstanding deferred FK
  101308. ** constraint violations in the database,
  101309. **
  101310. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  101311. ** the table from the database. Triggers are disabled while running this
  101312. ** DELETE, but foreign key actions are not.
  101313. */
  101314. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  101315. sqlite3 *db = pParse->db;
  101316. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  101317. int iSkip = 0;
  101318. Vdbe *v = sqlite3GetVdbe(pParse);
  101319. assert( v ); /* VDBE has already been allocated */
  101320. if( sqlite3FkReferences(pTab)==0 ){
  101321. /* Search for a deferred foreign key constraint for which this table
  101322. ** is the child table. If one cannot be found, return without
  101323. ** generating any VDBE code. If one can be found, then jump over
  101324. ** the entire DELETE if there are no outstanding deferred constraints
  101325. ** when this statement is run. */
  101326. FKey *p;
  101327. for(p=pTab->pFKey; p; p=p->pNextFrom){
  101328. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  101329. }
  101330. if( !p ) return;
  101331. iSkip = sqlite3VdbeMakeLabel(v);
  101332. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
  101333. }
  101334. pParse->disableTriggers = 1;
  101335. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  101336. pParse->disableTriggers = 0;
  101337. /* If the DELETE has generated immediate foreign key constraint
  101338. ** violations, halt the VDBE and return an error at this point, before
  101339. ** any modifications to the schema are made. This is because statement
  101340. ** transactions are not able to rollback schema changes.
  101341. **
  101342. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  101343. ** the statement transaction will not be rolled back even if FK
  101344. ** constraints are violated.
  101345. */
  101346. if( (db->flags & SQLITE_DeferFKs)==0 ){
  101347. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  101348. VdbeCoverage(v);
  101349. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  101350. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  101351. }
  101352. if( iSkip ){
  101353. sqlite3VdbeResolveLabel(v, iSkip);
  101354. }
  101355. }
  101356. }
  101357. /*
  101358. ** The second argument points to an FKey object representing a foreign key
  101359. ** for which pTab is the child table. An UPDATE statement against pTab
  101360. ** is currently being processed. For each column of the table that is
  101361. ** actually updated, the corresponding element in the aChange[] array
  101362. ** is zero or greater (if a column is unmodified the corresponding element
  101363. ** is set to -1). If the rowid column is modified by the UPDATE statement
  101364. ** the bChngRowid argument is non-zero.
  101365. **
  101366. ** This function returns true if any of the columns that are part of the
  101367. ** child key for FK constraint *p are modified.
  101368. */
  101369. static int fkChildIsModified(
  101370. Table *pTab, /* Table being updated */
  101371. FKey *p, /* Foreign key for which pTab is the child */
  101372. int *aChange, /* Array indicating modified columns */
  101373. int bChngRowid /* True if rowid is modified by this update */
  101374. ){
  101375. int i;
  101376. for(i=0; i<p->nCol; i++){
  101377. int iChildKey = p->aCol[i].iFrom;
  101378. if( aChange[iChildKey]>=0 ) return 1;
  101379. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  101380. }
  101381. return 0;
  101382. }
  101383. /*
  101384. ** The second argument points to an FKey object representing a foreign key
  101385. ** for which pTab is the parent table. An UPDATE statement against pTab
  101386. ** is currently being processed. For each column of the table that is
  101387. ** actually updated, the corresponding element in the aChange[] array
  101388. ** is zero or greater (if a column is unmodified the corresponding element
  101389. ** is set to -1). If the rowid column is modified by the UPDATE statement
  101390. ** the bChngRowid argument is non-zero.
  101391. **
  101392. ** This function returns true if any of the columns that are part of the
  101393. ** parent key for FK constraint *p are modified.
  101394. */
  101395. static int fkParentIsModified(
  101396. Table *pTab,
  101397. FKey *p,
  101398. int *aChange,
  101399. int bChngRowid
  101400. ){
  101401. int i;
  101402. for(i=0; i<p->nCol; i++){
  101403. char *zKey = p->aCol[i].zCol;
  101404. int iKey;
  101405. for(iKey=0; iKey<pTab->nCol; iKey++){
  101406. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  101407. Column *pCol = &pTab->aCol[iKey];
  101408. if( zKey ){
  101409. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  101410. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  101411. return 1;
  101412. }
  101413. }
  101414. }
  101415. }
  101416. return 0;
  101417. }
  101418. /*
  101419. ** Return true if the parser passed as the first argument is being
  101420. ** used to code a trigger that is really a "SET NULL" action belonging
  101421. ** to trigger pFKey.
  101422. */
  101423. static int isSetNullAction(Parse *pParse, FKey *pFKey){
  101424. Parse *pTop = sqlite3ParseToplevel(pParse);
  101425. if( pTop->pTriggerPrg ){
  101426. Trigger *p = pTop->pTriggerPrg->pTrigger;
  101427. if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
  101428. || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
  101429. ){
  101430. return 1;
  101431. }
  101432. }
  101433. return 0;
  101434. }
  101435. /*
  101436. ** This function is called when inserting, deleting or updating a row of
  101437. ** table pTab to generate VDBE code to perform foreign key constraint
  101438. ** processing for the operation.
  101439. **
  101440. ** For a DELETE operation, parameter regOld is passed the index of the
  101441. ** first register in an array of (pTab->nCol+1) registers containing the
  101442. ** rowid of the row being deleted, followed by each of the column values
  101443. ** of the row being deleted, from left to right. Parameter regNew is passed
  101444. ** zero in this case.
  101445. **
  101446. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  101447. ** first register of an array of (pTab->nCol+1) registers containing the new
  101448. ** row data.
  101449. **
  101450. ** For an UPDATE operation, this function is called twice. Once before
  101451. ** the original record is deleted from the table using the calling convention
  101452. ** described for DELETE. Then again after the original record is deleted
  101453. ** but before the new record is inserted using the INSERT convention.
  101454. */
  101455. SQLITE_PRIVATE void sqlite3FkCheck(
  101456. Parse *pParse, /* Parse context */
  101457. Table *pTab, /* Row is being deleted from this table */
  101458. int regOld, /* Previous row data is stored here */
  101459. int regNew, /* New row data is stored here */
  101460. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  101461. int bChngRowid /* True if rowid is UPDATEd */
  101462. ){
  101463. sqlite3 *db = pParse->db; /* Database handle */
  101464. FKey *pFKey; /* Used to iterate through FKs */
  101465. int iDb; /* Index of database containing pTab */
  101466. const char *zDb; /* Name of database containing pTab */
  101467. int isIgnoreErrors = pParse->disableTriggers;
  101468. /* Exactly one of regOld and regNew should be non-zero. */
  101469. assert( (regOld==0)!=(regNew==0) );
  101470. /* If foreign-keys are disabled, this function is a no-op. */
  101471. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  101472. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  101473. zDb = db->aDb[iDb].zDbSName;
  101474. /* Loop through all the foreign key constraints for which pTab is the
  101475. ** child table (the table that the foreign key definition is part of). */
  101476. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  101477. Table *pTo; /* Parent table of foreign key pFKey */
  101478. Index *pIdx = 0; /* Index on key columns in pTo */
  101479. int *aiFree = 0;
  101480. int *aiCol;
  101481. int iCol;
  101482. int i;
  101483. int bIgnore = 0;
  101484. if( aChange
  101485. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  101486. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  101487. ){
  101488. continue;
  101489. }
  101490. /* Find the parent table of this foreign key. Also find a unique index
  101491. ** on the parent key columns in the parent table. If either of these
  101492. ** schema items cannot be located, set an error in pParse and return
  101493. ** early. */
  101494. if( pParse->disableTriggers ){
  101495. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  101496. }else{
  101497. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  101498. }
  101499. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  101500. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  101501. if( !isIgnoreErrors || db->mallocFailed ) return;
  101502. if( pTo==0 ){
  101503. /* If isIgnoreErrors is true, then a table is being dropped. In this
  101504. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  101505. ** before actually dropping it in order to check FK constraints.
  101506. ** If the parent table of an FK constraint on the current table is
  101507. ** missing, behave as if it is empty. i.e. decrement the relevant
  101508. ** FK counter for each row of the current table with non-NULL keys.
  101509. */
  101510. Vdbe *v = sqlite3GetVdbe(pParse);
  101511. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  101512. for(i=0; i<pFKey->nCol; i++){
  101513. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  101514. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
  101515. }
  101516. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  101517. }
  101518. continue;
  101519. }
  101520. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  101521. if( aiFree ){
  101522. aiCol = aiFree;
  101523. }else{
  101524. iCol = pFKey->aCol[0].iFrom;
  101525. aiCol = &iCol;
  101526. }
  101527. for(i=0; i<pFKey->nCol; i++){
  101528. if( aiCol[i]==pTab->iPKey ){
  101529. aiCol[i] = -1;
  101530. }
  101531. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  101532. #ifndef SQLITE_OMIT_AUTHORIZATION
  101533. /* Request permission to read the parent key columns. If the
  101534. ** authorization callback returns SQLITE_IGNORE, behave as if any
  101535. ** values read from the parent table are NULL. */
  101536. if( db->xAuth ){
  101537. int rcauth;
  101538. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  101539. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  101540. bIgnore = (rcauth==SQLITE_IGNORE);
  101541. }
  101542. #endif
  101543. }
  101544. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  101545. ** a cursor to use to search the unique index on the parent key columns
  101546. ** in the parent table. */
  101547. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  101548. pParse->nTab++;
  101549. if( regOld!=0 ){
  101550. /* A row is being removed from the child table. Search for the parent.
  101551. ** If the parent does not exist, removing the child row resolves an
  101552. ** outstanding foreign key constraint violation. */
  101553. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
  101554. }
  101555. if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
  101556. /* A row is being added to the child table. If a parent row cannot
  101557. ** be found, adding the child row has violated the FK constraint.
  101558. **
  101559. ** If this operation is being performed as part of a trigger program
  101560. ** that is actually a "SET NULL" action belonging to this very
  101561. ** foreign key, then omit this scan altogether. As all child key
  101562. ** values are guaranteed to be NULL, it is not possible for adding
  101563. ** this row to cause an FK violation. */
  101564. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
  101565. }
  101566. sqlite3DbFree(db, aiFree);
  101567. }
  101568. /* Loop through all the foreign key constraints that refer to this table.
  101569. ** (the "child" constraints) */
  101570. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  101571. Index *pIdx = 0; /* Foreign key index for pFKey */
  101572. SrcList *pSrc;
  101573. int *aiCol = 0;
  101574. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  101575. continue;
  101576. }
  101577. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  101578. && !pParse->pToplevel && !pParse->isMultiWrite
  101579. ){
  101580. assert( regOld==0 && regNew!=0 );
  101581. /* Inserting a single row into a parent table cannot cause (or fix)
  101582. ** an immediate foreign key violation. So do nothing in this case. */
  101583. continue;
  101584. }
  101585. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  101586. if( !isIgnoreErrors || db->mallocFailed ) return;
  101587. continue;
  101588. }
  101589. assert( aiCol || pFKey->nCol==1 );
  101590. /* Create a SrcList structure containing the child table. We need the
  101591. ** child table as a SrcList for sqlite3WhereBegin() */
  101592. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  101593. if( pSrc ){
  101594. struct SrcList_item *pItem = pSrc->a;
  101595. pItem->pTab = pFKey->pFrom;
  101596. pItem->zName = pFKey->pFrom->zName;
  101597. pItem->pTab->nTabRef++;
  101598. pItem->iCursor = pParse->nTab++;
  101599. if( regNew!=0 ){
  101600. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  101601. }
  101602. if( regOld!=0 ){
  101603. int eAction = pFKey->aAction[aChange!=0];
  101604. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  101605. /* If this is a deferred FK constraint, or a CASCADE or SET NULL
  101606. ** action applies, then any foreign key violations caused by
  101607. ** removing the parent key will be rectified by the action trigger.
  101608. ** So do not set the "may-abort" flag in this case.
  101609. **
  101610. ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
  101611. ** may-abort flag will eventually be set on this statement anyway
  101612. ** (when this function is called as part of processing the UPDATE
  101613. ** within the action trigger).
  101614. **
  101615. ** Note 2: At first glance it may seem like SQLite could simply omit
  101616. ** all OP_FkCounter related scans when either CASCADE or SET NULL
  101617. ** applies. The trouble starts if the CASCADE or SET NULL action
  101618. ** trigger causes other triggers or action rules attached to the
  101619. ** child table to fire. In these cases the fk constraint counters
  101620. ** might be set incorrectly if any OP_FkCounter related scans are
  101621. ** omitted. */
  101622. if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
  101623. sqlite3MayAbort(pParse);
  101624. }
  101625. }
  101626. pItem->zName = 0;
  101627. sqlite3SrcListDelete(db, pSrc);
  101628. }
  101629. sqlite3DbFree(db, aiCol);
  101630. }
  101631. }
  101632. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  101633. /*
  101634. ** This function is called before generating code to update or delete a
  101635. ** row contained in table pTab.
  101636. */
  101637. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  101638. Parse *pParse, /* Parse context */
  101639. Table *pTab /* Table being modified */
  101640. ){
  101641. u32 mask = 0;
  101642. if( pParse->db->flags&SQLITE_ForeignKeys ){
  101643. FKey *p;
  101644. int i;
  101645. for(p=pTab->pFKey; p; p=p->pNextFrom){
  101646. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  101647. }
  101648. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  101649. Index *pIdx = 0;
  101650. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  101651. if( pIdx ){
  101652. for(i=0; i<pIdx->nKeyCol; i++){
  101653. assert( pIdx->aiColumn[i]>=0 );
  101654. mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  101655. }
  101656. }
  101657. }
  101658. }
  101659. return mask;
  101660. }
  101661. /*
  101662. ** This function is called before generating code to update or delete a
  101663. ** row contained in table pTab. If the operation is a DELETE, then
  101664. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  101665. ** to an array of size N, where N is the number of columns in table pTab.
  101666. ** If the i'th column is not modified by the UPDATE, then the corresponding
  101667. ** entry in the aChange[] array is set to -1. If the column is modified,
  101668. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  101669. ** UPDATE statement modifies the rowid fields of the table.
  101670. **
  101671. ** If any foreign key processing will be required, this function returns
  101672. ** non-zero. If there is no foreign key related processing, this function
  101673. ** returns zero.
  101674. **
  101675. ** For an UPDATE, this function returns 2 if:
  101676. **
  101677. ** * There are any FKs for which pTab is the child and the parent table, or
  101678. ** * the UPDATE modifies one or more parent keys for which the action is
  101679. ** not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
  101680. **
  101681. ** Or, assuming some other foreign key processing is required, 1.
  101682. */
  101683. SQLITE_PRIVATE int sqlite3FkRequired(
  101684. Parse *pParse, /* Parse context */
  101685. Table *pTab, /* Table being modified */
  101686. int *aChange, /* Non-NULL for UPDATE operations */
  101687. int chngRowid /* True for UPDATE that affects rowid */
  101688. ){
  101689. int eRet = 0;
  101690. if( pParse->db->flags&SQLITE_ForeignKeys ){
  101691. if( !aChange ){
  101692. /* A DELETE operation. Foreign key processing is required if the
  101693. ** table in question is either the child or parent table for any
  101694. ** foreign key constraint. */
  101695. eRet = (sqlite3FkReferences(pTab) || pTab->pFKey);
  101696. }else{
  101697. /* This is an UPDATE. Foreign key processing is only required if the
  101698. ** operation modifies one or more child or parent key columns. */
  101699. FKey *p;
  101700. /* Check if any child key columns are being modified. */
  101701. for(p=pTab->pFKey; p; p=p->pNextFrom){
  101702. if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) return 2;
  101703. if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
  101704. eRet = 1;
  101705. }
  101706. }
  101707. /* Check if any parent key columns are being modified. */
  101708. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  101709. if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
  101710. if( p->aAction[1]!=OE_None ) return 2;
  101711. eRet = 1;
  101712. }
  101713. }
  101714. }
  101715. }
  101716. return eRet;
  101717. }
  101718. /*
  101719. ** This function is called when an UPDATE or DELETE operation is being
  101720. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  101721. ** If the current operation is an UPDATE, then the pChanges parameter is
  101722. ** passed a pointer to the list of columns being modified. If it is a
  101723. ** DELETE, pChanges is passed a NULL pointer.
  101724. **
  101725. ** It returns a pointer to a Trigger structure containing a trigger
  101726. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  101727. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  101728. ** returned (these actions require no special handling by the triggers
  101729. ** sub-system, code for them is created by fkScanChildren()).
  101730. **
  101731. ** For example, if pFKey is the foreign key and pTab is table "p" in
  101732. ** the following schema:
  101733. **
  101734. ** CREATE TABLE p(pk PRIMARY KEY);
  101735. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  101736. **
  101737. ** then the returned trigger structure is equivalent to:
  101738. **
  101739. ** CREATE TRIGGER ... DELETE ON p BEGIN
  101740. ** DELETE FROM c WHERE ck = old.pk;
  101741. ** END;
  101742. **
  101743. ** The returned pointer is cached as part of the foreign key object. It
  101744. ** is eventually freed along with the rest of the foreign key object by
  101745. ** sqlite3FkDelete().
  101746. */
  101747. static Trigger *fkActionTrigger(
  101748. Parse *pParse, /* Parse context */
  101749. Table *pTab, /* Table being updated or deleted from */
  101750. FKey *pFKey, /* Foreign key to get action for */
  101751. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  101752. ){
  101753. sqlite3 *db = pParse->db; /* Database handle */
  101754. int action; /* One of OE_None, OE_Cascade etc. */
  101755. Trigger *pTrigger; /* Trigger definition to return */
  101756. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  101757. action = pFKey->aAction[iAction];
  101758. if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
  101759. return 0;
  101760. }
  101761. pTrigger = pFKey->apTrigger[iAction];
  101762. if( action!=OE_None && !pTrigger ){
  101763. char const *zFrom; /* Name of child table */
  101764. int nFrom; /* Length in bytes of zFrom */
  101765. Index *pIdx = 0; /* Parent key index for this FK */
  101766. int *aiCol = 0; /* child table cols -> parent key cols */
  101767. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  101768. Expr *pWhere = 0; /* WHERE clause of trigger step */
  101769. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  101770. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  101771. int i; /* Iterator variable */
  101772. Expr *pWhen = 0; /* WHEN clause for the trigger */
  101773. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  101774. assert( aiCol || pFKey->nCol==1 );
  101775. for(i=0; i<pFKey->nCol; i++){
  101776. Token tOld = { "old", 3 }; /* Literal "old" token */
  101777. Token tNew = { "new", 3 }; /* Literal "new" token */
  101778. Token tFromCol; /* Name of column in child table */
  101779. Token tToCol; /* Name of column in parent table */
  101780. int iFromCol; /* Idx of column in child table */
  101781. Expr *pEq; /* tFromCol = OLD.tToCol */
  101782. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  101783. assert( iFromCol>=0 );
  101784. assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
  101785. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  101786. sqlite3TokenInit(&tToCol,
  101787. pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
  101788. sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
  101789. /* Create the expression "OLD.zToCol = zFromCol". It is important
  101790. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  101791. ** that the affinity and collation sequence associated with the
  101792. ** parent table are used for the comparison. */
  101793. pEq = sqlite3PExpr(pParse, TK_EQ,
  101794. sqlite3PExpr(pParse, TK_DOT,
  101795. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  101796. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
  101797. sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
  101798. );
  101799. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  101800. /* For ON UPDATE, construct the next term of the WHEN clause.
  101801. ** The final WHEN clause will be like this:
  101802. **
  101803. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  101804. */
  101805. if( pChanges ){
  101806. pEq = sqlite3PExpr(pParse, TK_IS,
  101807. sqlite3PExpr(pParse, TK_DOT,
  101808. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  101809. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
  101810. sqlite3PExpr(pParse, TK_DOT,
  101811. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  101812. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
  101813. );
  101814. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  101815. }
  101816. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  101817. Expr *pNew;
  101818. if( action==OE_Cascade ){
  101819. pNew = sqlite3PExpr(pParse, TK_DOT,
  101820. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  101821. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
  101822. }else if( action==OE_SetDflt ){
  101823. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  101824. if( pDflt ){
  101825. pNew = sqlite3ExprDup(db, pDflt, 0);
  101826. }else{
  101827. pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  101828. }
  101829. }else{
  101830. pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  101831. }
  101832. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  101833. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  101834. }
  101835. }
  101836. sqlite3DbFree(db, aiCol);
  101837. zFrom = pFKey->pFrom->zName;
  101838. nFrom = sqlite3Strlen30(zFrom);
  101839. if( action==OE_Restrict ){
  101840. Token tFrom;
  101841. Expr *pRaise;
  101842. tFrom.z = zFrom;
  101843. tFrom.n = nFrom;
  101844. pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
  101845. if( pRaise ){
  101846. pRaise->affinity = OE_Abort;
  101847. }
  101848. pSelect = sqlite3SelectNew(pParse,
  101849. sqlite3ExprListAppend(pParse, 0, pRaise),
  101850. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  101851. pWhere,
  101852. 0, 0, 0, 0, 0, 0
  101853. );
  101854. pWhere = 0;
  101855. }
  101856. /* Disable lookaside memory allocation */
  101857. db->lookaside.bDisable++;
  101858. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  101859. sizeof(Trigger) + /* struct Trigger */
  101860. sizeof(TriggerStep) + /* Single step in trigger program */
  101861. nFrom + 1 /* Space for pStep->zTarget */
  101862. );
  101863. if( pTrigger ){
  101864. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  101865. pStep->zTarget = (char *)&pStep[1];
  101866. memcpy((char *)pStep->zTarget, zFrom, nFrom);
  101867. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  101868. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  101869. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  101870. if( pWhen ){
  101871. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);
  101872. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  101873. }
  101874. }
  101875. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  101876. db->lookaside.bDisable--;
  101877. sqlite3ExprDelete(db, pWhere);
  101878. sqlite3ExprDelete(db, pWhen);
  101879. sqlite3ExprListDelete(db, pList);
  101880. sqlite3SelectDelete(db, pSelect);
  101881. if( db->mallocFailed==1 ){
  101882. fkTriggerDelete(db, pTrigger);
  101883. return 0;
  101884. }
  101885. assert( pStep!=0 );
  101886. switch( action ){
  101887. case OE_Restrict:
  101888. pStep->op = TK_SELECT;
  101889. break;
  101890. case OE_Cascade:
  101891. if( !pChanges ){
  101892. pStep->op = TK_DELETE;
  101893. break;
  101894. }
  101895. default:
  101896. pStep->op = TK_UPDATE;
  101897. }
  101898. pStep->pTrig = pTrigger;
  101899. pTrigger->pSchema = pTab->pSchema;
  101900. pTrigger->pTabSchema = pTab->pSchema;
  101901. pFKey->apTrigger[iAction] = pTrigger;
  101902. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  101903. }
  101904. return pTrigger;
  101905. }
  101906. /*
  101907. ** This function is called when deleting or updating a row to implement
  101908. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  101909. */
  101910. SQLITE_PRIVATE void sqlite3FkActions(
  101911. Parse *pParse, /* Parse context */
  101912. Table *pTab, /* Table being updated or deleted from */
  101913. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  101914. int regOld, /* Address of array containing old row */
  101915. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  101916. int bChngRowid /* True if rowid is UPDATEd */
  101917. ){
  101918. /* If foreign-key support is enabled, iterate through all FKs that
  101919. ** refer to table pTab. If there is an action associated with the FK
  101920. ** for this operation (either update or delete), invoke the associated
  101921. ** trigger sub-program. */
  101922. if( pParse->db->flags&SQLITE_ForeignKeys ){
  101923. FKey *pFKey; /* Iterator variable */
  101924. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  101925. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  101926. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  101927. if( pAct ){
  101928. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  101929. }
  101930. }
  101931. }
  101932. }
  101933. }
  101934. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  101935. /*
  101936. ** Free all memory associated with foreign key definitions attached to
  101937. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  101938. ** hash table.
  101939. */
  101940. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  101941. FKey *pFKey; /* Iterator variable */
  101942. FKey *pNext; /* Copy of pFKey->pNextFrom */
  101943. assert( db==0 || IsVirtual(pTab)
  101944. || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  101945. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  101946. /* Remove the FK from the fkeyHash hash table. */
  101947. if( !db || db->pnBytesFreed==0 ){
  101948. if( pFKey->pPrevTo ){
  101949. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  101950. }else{
  101951. void *p = (void *)pFKey->pNextTo;
  101952. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  101953. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
  101954. }
  101955. if( pFKey->pNextTo ){
  101956. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  101957. }
  101958. }
  101959. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  101960. ** classified as either immediate or deferred.
  101961. */
  101962. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  101963. /* Delete any triggers created to implement actions for this FK. */
  101964. #ifndef SQLITE_OMIT_TRIGGER
  101965. fkTriggerDelete(db, pFKey->apTrigger[0]);
  101966. fkTriggerDelete(db, pFKey->apTrigger[1]);
  101967. #endif
  101968. pNext = pFKey->pNextFrom;
  101969. sqlite3DbFree(db, pFKey);
  101970. }
  101971. }
  101972. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  101973. /************** End of fkey.c ************************************************/
  101974. /************** Begin file insert.c ******************************************/
  101975. /*
  101976. ** 2001 September 15
  101977. **
  101978. ** The author disclaims copyright to this source code. In place of
  101979. ** a legal notice, here is a blessing:
  101980. **
  101981. ** May you do good and not evil.
  101982. ** May you find forgiveness for yourself and forgive others.
  101983. ** May you share freely, never taking more than you give.
  101984. **
  101985. *************************************************************************
  101986. ** This file contains C code routines that are called by the parser
  101987. ** to handle INSERT statements in SQLite.
  101988. */
  101989. /* #include "sqliteInt.h" */
  101990. /*
  101991. ** Generate code that will
  101992. **
  101993. ** (1) acquire a lock for table pTab then
  101994. ** (2) open pTab as cursor iCur.
  101995. **
  101996. ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
  101997. ** for that table that is actually opened.
  101998. */
  101999. SQLITE_PRIVATE void sqlite3OpenTable(
  102000. Parse *pParse, /* Generate code into this VDBE */
  102001. int iCur, /* The cursor number of the table */
  102002. int iDb, /* The database index in sqlite3.aDb[] */
  102003. Table *pTab, /* The table to be opened */
  102004. int opcode /* OP_OpenRead or OP_OpenWrite */
  102005. ){
  102006. Vdbe *v;
  102007. assert( !IsVirtual(pTab) );
  102008. v = sqlite3GetVdbe(pParse);
  102009. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  102010. sqlite3TableLock(pParse, iDb, pTab->tnum,
  102011. (opcode==OP_OpenWrite)?1:0, pTab->zName);
  102012. if( HasRowid(pTab) ){
  102013. sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
  102014. VdbeComment((v, "%s", pTab->zName));
  102015. }else{
  102016. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  102017. assert( pPk!=0 );
  102018. assert( pPk->tnum==pTab->tnum );
  102019. sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
  102020. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  102021. VdbeComment((v, "%s", pTab->zName));
  102022. }
  102023. }
  102024. /*
  102025. ** Return a pointer to the column affinity string associated with index
  102026. ** pIdx. A column affinity string has one character for each column in
  102027. ** the table, according to the affinity of the column:
  102028. **
  102029. ** Character Column affinity
  102030. ** ------------------------------
  102031. ** 'A' BLOB
  102032. ** 'B' TEXT
  102033. ** 'C' NUMERIC
  102034. ** 'D' INTEGER
  102035. ** 'F' REAL
  102036. **
  102037. ** An extra 'D' is appended to the end of the string to cover the
  102038. ** rowid that appears as the last column in every index.
  102039. **
  102040. ** Memory for the buffer containing the column index affinity string
  102041. ** is managed along with the rest of the Index structure. It will be
  102042. ** released when sqlite3DeleteIndex() is called.
  102043. */
  102044. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
  102045. if( !pIdx->zColAff ){
  102046. /* The first time a column affinity string for a particular index is
  102047. ** required, it is allocated and populated here. It is then stored as
  102048. ** a member of the Index structure for subsequent use.
  102049. **
  102050. ** The column affinity string will eventually be deleted by
  102051. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  102052. ** up.
  102053. */
  102054. int n;
  102055. Table *pTab = pIdx->pTable;
  102056. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
  102057. if( !pIdx->zColAff ){
  102058. sqlite3OomFault(db);
  102059. return 0;
  102060. }
  102061. for(n=0; n<pIdx->nColumn; n++){
  102062. i16 x = pIdx->aiColumn[n];
  102063. if( x>=0 ){
  102064. pIdx->zColAff[n] = pTab->aCol[x].affinity;
  102065. }else if( x==XN_ROWID ){
  102066. pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
  102067. }else{
  102068. char aff;
  102069. assert( x==XN_EXPR );
  102070. assert( pIdx->aColExpr!=0 );
  102071. aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
  102072. if( aff==0 ) aff = SQLITE_AFF_BLOB;
  102073. pIdx->zColAff[n] = aff;
  102074. }
  102075. }
  102076. pIdx->zColAff[n] = 0;
  102077. }
  102078. return pIdx->zColAff;
  102079. }
  102080. /*
  102081. ** Compute the affinity string for table pTab, if it has not already been
  102082. ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
  102083. **
  102084. ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
  102085. ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
  102086. ** for register iReg and following. Or if affinities exists and iReg==0,
  102087. ** then just set the P4 operand of the previous opcode (which should be
  102088. ** an OP_MakeRecord) to the affinity string.
  102089. **
  102090. ** A column affinity string has one character per column:
  102091. **
  102092. ** Character Column affinity
  102093. ** ------------------------------
  102094. ** 'A' BLOB
  102095. ** 'B' TEXT
  102096. ** 'C' NUMERIC
  102097. ** 'D' INTEGER
  102098. ** 'E' REAL
  102099. */
  102100. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
  102101. int i;
  102102. char *zColAff = pTab->zColAff;
  102103. if( zColAff==0 ){
  102104. sqlite3 *db = sqlite3VdbeDb(v);
  102105. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  102106. if( !zColAff ){
  102107. sqlite3OomFault(db);
  102108. return;
  102109. }
  102110. for(i=0; i<pTab->nCol; i++){
  102111. zColAff[i] = pTab->aCol[i].affinity;
  102112. }
  102113. do{
  102114. zColAff[i--] = 0;
  102115. }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
  102116. pTab->zColAff = zColAff;
  102117. }
  102118. i = sqlite3Strlen30(zColAff);
  102119. if( i ){
  102120. if( iReg ){
  102121. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
  102122. }else{
  102123. sqlite3VdbeChangeP4(v, -1, zColAff, i);
  102124. }
  102125. }
  102126. }
  102127. /*
  102128. ** Return non-zero if the table pTab in database iDb or any of its indices
  102129. ** have been opened at any point in the VDBE program. This is used to see if
  102130. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  102131. ** run without using a temporary table for the results of the SELECT.
  102132. */
  102133. static int readsTable(Parse *p, int iDb, Table *pTab){
  102134. Vdbe *v = sqlite3GetVdbe(p);
  102135. int i;
  102136. int iEnd = sqlite3VdbeCurrentAddr(v);
  102137. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102138. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  102139. #endif
  102140. for(i=1; i<iEnd; i++){
  102141. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  102142. assert( pOp!=0 );
  102143. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  102144. Index *pIndex;
  102145. int tnum = pOp->p2;
  102146. if( tnum==pTab->tnum ){
  102147. return 1;
  102148. }
  102149. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  102150. if( tnum==pIndex->tnum ){
  102151. return 1;
  102152. }
  102153. }
  102154. }
  102155. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102156. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  102157. assert( pOp->p4.pVtab!=0 );
  102158. assert( pOp->p4type==P4_VTAB );
  102159. return 1;
  102160. }
  102161. #endif
  102162. }
  102163. return 0;
  102164. }
  102165. #ifndef SQLITE_OMIT_AUTOINCREMENT
  102166. /*
  102167. ** Locate or create an AutoincInfo structure associated with table pTab
  102168. ** which is in database iDb. Return the register number for the register
  102169. ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
  102170. ** table. (Also return zero when doing a VACUUM since we do not want to
  102171. ** update the AUTOINCREMENT counters during a VACUUM.)
  102172. **
  102173. ** There is at most one AutoincInfo structure per table even if the
  102174. ** same table is autoincremented multiple times due to inserts within
  102175. ** triggers. A new AutoincInfo structure is created if this is the
  102176. ** first use of table pTab. On 2nd and subsequent uses, the original
  102177. ** AutoincInfo structure is used.
  102178. **
  102179. ** Three memory locations are allocated:
  102180. **
  102181. ** (1) Register to hold the name of the pTab table.
  102182. ** (2) Register to hold the maximum ROWID of pTab.
  102183. ** (3) Register to hold the rowid in sqlite_sequence of pTab
  102184. **
  102185. ** The 2nd register is the one that is returned. That is all the
  102186. ** insert routine needs to know about.
  102187. */
  102188. static int autoIncBegin(
  102189. Parse *pParse, /* Parsing context */
  102190. int iDb, /* Index of the database holding pTab */
  102191. Table *pTab /* The table we are writing to */
  102192. ){
  102193. int memId = 0; /* Register holding maximum rowid */
  102194. if( (pTab->tabFlags & TF_Autoincrement)!=0
  102195. && (pParse->db->flags & SQLITE_Vacuum)==0
  102196. ){
  102197. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  102198. AutoincInfo *pInfo;
  102199. pInfo = pToplevel->pAinc;
  102200. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  102201. if( pInfo==0 ){
  102202. pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
  102203. if( pInfo==0 ) return 0;
  102204. pInfo->pNext = pToplevel->pAinc;
  102205. pToplevel->pAinc = pInfo;
  102206. pInfo->pTab = pTab;
  102207. pInfo->iDb = iDb;
  102208. pToplevel->nMem++; /* Register to hold name of table */
  102209. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  102210. pToplevel->nMem++; /* Rowid in sqlite_sequence */
  102211. }
  102212. memId = pInfo->regCtr;
  102213. }
  102214. return memId;
  102215. }
  102216. /*
  102217. ** This routine generates code that will initialize all of the
  102218. ** register used by the autoincrement tracker.
  102219. */
  102220. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  102221. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  102222. sqlite3 *db = pParse->db; /* The database connection */
  102223. Db *pDb; /* Database only autoinc table */
  102224. int memId; /* Register holding max rowid */
  102225. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  102226. /* This routine is never called during trigger-generation. It is
  102227. ** only called from the top-level */
  102228. assert( pParse->pTriggerTab==0 );
  102229. assert( sqlite3IsToplevel(pParse) );
  102230. assert( v ); /* We failed long ago if this is not so */
  102231. for(p = pParse->pAinc; p; p = p->pNext){
  102232. static const int iLn = VDBE_OFFSET_LINENO(2);
  102233. static const VdbeOpList autoInc[] = {
  102234. /* 0 */ {OP_Null, 0, 0, 0},
  102235. /* 1 */ {OP_Rewind, 0, 9, 0},
  102236. /* 2 */ {OP_Column, 0, 0, 0},
  102237. /* 3 */ {OP_Ne, 0, 7, 0},
  102238. /* 4 */ {OP_Rowid, 0, 0, 0},
  102239. /* 5 */ {OP_Column, 0, 1, 0},
  102240. /* 6 */ {OP_Goto, 0, 9, 0},
  102241. /* 7 */ {OP_Next, 0, 2, 0},
  102242. /* 8 */ {OP_Integer, 0, 0, 0},
  102243. /* 9 */ {OP_Close, 0, 0, 0}
  102244. };
  102245. VdbeOp *aOp;
  102246. pDb = &db->aDb[p->iDb];
  102247. memId = p->regCtr;
  102248. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  102249. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  102250. sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
  102251. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
  102252. if( aOp==0 ) break;
  102253. aOp[0].p2 = memId;
  102254. aOp[0].p3 = memId+1;
  102255. aOp[2].p3 = memId;
  102256. aOp[3].p1 = memId-1;
  102257. aOp[3].p3 = memId;
  102258. aOp[3].p5 = SQLITE_JUMPIFNULL;
  102259. aOp[4].p2 = memId+1;
  102260. aOp[5].p3 = memId;
  102261. aOp[8].p2 = memId;
  102262. }
  102263. }
  102264. /*
  102265. ** Update the maximum rowid for an autoincrement calculation.
  102266. **
  102267. ** This routine should be called when the regRowid register holds a
  102268. ** new rowid that is about to be inserted. If that new rowid is
  102269. ** larger than the maximum rowid in the memId memory cell, then the
  102270. ** memory cell is updated.
  102271. */
  102272. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  102273. if( memId>0 ){
  102274. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  102275. }
  102276. }
  102277. /*
  102278. ** This routine generates the code needed to write autoincrement
  102279. ** maximum rowid values back into the sqlite_sequence register.
  102280. ** Every statement that might do an INSERT into an autoincrement
  102281. ** table (either directly or through triggers) needs to call this
  102282. ** routine just before the "exit" code.
  102283. */
  102284. static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
  102285. AutoincInfo *p;
  102286. Vdbe *v = pParse->pVdbe;
  102287. sqlite3 *db = pParse->db;
  102288. assert( v );
  102289. for(p = pParse->pAinc; p; p = p->pNext){
  102290. static const int iLn = VDBE_OFFSET_LINENO(2);
  102291. static const VdbeOpList autoIncEnd[] = {
  102292. /* 0 */ {OP_NotNull, 0, 2, 0},
  102293. /* 1 */ {OP_NewRowid, 0, 0, 0},
  102294. /* 2 */ {OP_MakeRecord, 0, 2, 0},
  102295. /* 3 */ {OP_Insert, 0, 0, 0},
  102296. /* 4 */ {OP_Close, 0, 0, 0}
  102297. };
  102298. VdbeOp *aOp;
  102299. Db *pDb = &db->aDb[p->iDb];
  102300. int iRec;
  102301. int memId = p->regCtr;
  102302. iRec = sqlite3GetTempReg(pParse);
  102303. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  102304. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  102305. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
  102306. if( aOp==0 ) break;
  102307. aOp[0].p1 = memId+1;
  102308. aOp[1].p2 = memId+1;
  102309. aOp[2].p1 = memId-1;
  102310. aOp[2].p3 = iRec;
  102311. aOp[3].p2 = iRec;
  102312. aOp[3].p3 = memId+1;
  102313. aOp[3].p5 = OPFLAG_APPEND;
  102314. sqlite3ReleaseTempReg(pParse, iRec);
  102315. }
  102316. }
  102317. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  102318. if( pParse->pAinc ) autoIncrementEnd(pParse);
  102319. }
  102320. #else
  102321. /*
  102322. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  102323. ** above are all no-ops
  102324. */
  102325. # define autoIncBegin(A,B,C) (0)
  102326. # define autoIncStep(A,B,C)
  102327. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  102328. /* Forward declaration */
  102329. static int xferOptimization(
  102330. Parse *pParse, /* Parser context */
  102331. Table *pDest, /* The table we are inserting into */
  102332. Select *pSelect, /* A SELECT statement to use as the data source */
  102333. int onError, /* How to handle constraint errors */
  102334. int iDbDest /* The database of pDest */
  102335. );
  102336. /*
  102337. ** This routine is called to handle SQL of the following forms:
  102338. **
  102339. ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
  102340. ** insert into TABLE (IDLIST) select
  102341. ** insert into TABLE (IDLIST) default values
  102342. **
  102343. ** The IDLIST following the table name is always optional. If omitted,
  102344. ** then a list of all (non-hidden) columns for the table is substituted.
  102345. ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
  102346. ** is omitted.
  102347. **
  102348. ** For the pSelect parameter holds the values to be inserted for the
  102349. ** first two forms shown above. A VALUES clause is really just short-hand
  102350. ** for a SELECT statement that omits the FROM clause and everything else
  102351. ** that follows. If the pSelect parameter is NULL, that means that the
  102352. ** DEFAULT VALUES form of the INSERT statement is intended.
  102353. **
  102354. ** The code generated follows one of four templates. For a simple
  102355. ** insert with data coming from a single-row VALUES clause, the code executes
  102356. ** once straight down through. Pseudo-code follows (we call this
  102357. ** the "1st template"):
  102358. **
  102359. ** open write cursor to <table> and its indices
  102360. ** put VALUES clause expressions into registers
  102361. ** write the resulting record into <table>
  102362. ** cleanup
  102363. **
  102364. ** The three remaining templates assume the statement is of the form
  102365. **
  102366. ** INSERT INTO <table> SELECT ...
  102367. **
  102368. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  102369. ** in other words if the SELECT pulls all columns from a single table
  102370. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  102371. ** if <table2> and <table1> are distinct tables but have identical
  102372. ** schemas, including all the same indices, then a special optimization
  102373. ** is invoked that copies raw records from <table2> over to <table1>.
  102374. ** See the xferOptimization() function for the implementation of this
  102375. ** template. This is the 2nd template.
  102376. **
  102377. ** open a write cursor to <table>
  102378. ** open read cursor on <table2>
  102379. ** transfer all records in <table2> over to <table>
  102380. ** close cursors
  102381. ** foreach index on <table>
  102382. ** open a write cursor on the <table> index
  102383. ** open a read cursor on the corresponding <table2> index
  102384. ** transfer all records from the read to the write cursors
  102385. ** close cursors
  102386. ** end foreach
  102387. **
  102388. ** The 3rd template is for when the second template does not apply
  102389. ** and the SELECT clause does not read from <table> at any time.
  102390. ** The generated code follows this template:
  102391. **
  102392. ** X <- A
  102393. ** goto B
  102394. ** A: setup for the SELECT
  102395. ** loop over the rows in the SELECT
  102396. ** load values into registers R..R+n
  102397. ** yield X
  102398. ** end loop
  102399. ** cleanup after the SELECT
  102400. ** end-coroutine X
  102401. ** B: open write cursor to <table> and its indices
  102402. ** C: yield X, at EOF goto D
  102403. ** insert the select result into <table> from R..R+n
  102404. ** goto C
  102405. ** D: cleanup
  102406. **
  102407. ** The 4th template is used if the insert statement takes its
  102408. ** values from a SELECT but the data is being inserted into a table
  102409. ** that is also read as part of the SELECT. In the third form,
  102410. ** we have to use an intermediate table to store the results of
  102411. ** the select. The template is like this:
  102412. **
  102413. ** X <- A
  102414. ** goto B
  102415. ** A: setup for the SELECT
  102416. ** loop over the tables in the SELECT
  102417. ** load value into register R..R+n
  102418. ** yield X
  102419. ** end loop
  102420. ** cleanup after the SELECT
  102421. ** end co-routine R
  102422. ** B: open temp table
  102423. ** L: yield X, at EOF goto M
  102424. ** insert row from R..R+n into temp table
  102425. ** goto L
  102426. ** M: open write cursor to <table> and its indices
  102427. ** rewind temp table
  102428. ** C: loop over rows of intermediate table
  102429. ** transfer values form intermediate table into <table>
  102430. ** end loop
  102431. ** D: cleanup
  102432. */
  102433. SQLITE_PRIVATE void sqlite3Insert(
  102434. Parse *pParse, /* Parser context */
  102435. SrcList *pTabList, /* Name of table into which we are inserting */
  102436. Select *pSelect, /* A SELECT statement to use as the data source */
  102437. IdList *pColumn, /* Column names corresponding to IDLIST. */
  102438. int onError /* How to handle constraint errors */
  102439. ){
  102440. sqlite3 *db; /* The main database structure */
  102441. Table *pTab; /* The table to insert into. aka TABLE */
  102442. char *zTab; /* Name of the table into which we are inserting */
  102443. int i, j; /* Loop counters */
  102444. Vdbe *v; /* Generate code into this virtual machine */
  102445. Index *pIdx; /* For looping over indices of the table */
  102446. int nColumn; /* Number of columns in the data */
  102447. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  102448. int iDataCur = 0; /* VDBE cursor that is the main data repository */
  102449. int iIdxCur = 0; /* First index cursor */
  102450. int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  102451. int endOfLoop; /* Label for the end of the insertion loop */
  102452. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  102453. int addrInsTop = 0; /* Jump to label "D" */
  102454. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  102455. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  102456. int iDb; /* Index of database holding TABLE */
  102457. u8 useTempTable = 0; /* Store SELECT results in intermediate table */
  102458. u8 appendFlag = 0; /* True if the insert is likely to be an append */
  102459. u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
  102460. u8 bIdListInOrder; /* True if IDLIST is in table order */
  102461. ExprList *pList = 0; /* List of VALUES() to be inserted */
  102462. /* Register allocations */
  102463. int regFromSelect = 0;/* Base register for data coming from SELECT */
  102464. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  102465. int regRowCount = 0; /* Memory cell used for the row counter */
  102466. int regIns; /* Block of regs holding rowid+data being inserted */
  102467. int regRowid; /* registers holding insert rowid */
  102468. int regData; /* register holding first column to insert */
  102469. int *aRegIdx = 0; /* One register allocated to each index */
  102470. #ifndef SQLITE_OMIT_TRIGGER
  102471. int isView; /* True if attempting to insert into a view */
  102472. Trigger *pTrigger; /* List of triggers on pTab, if required */
  102473. int tmask; /* Mask of trigger times */
  102474. #endif
  102475. db = pParse->db;
  102476. memset(&dest, 0, sizeof(dest));
  102477. if( pParse->nErr || db->mallocFailed ){
  102478. goto insert_cleanup;
  102479. }
  102480. /* If the Select object is really just a simple VALUES() list with a
  102481. ** single row (the common case) then keep that one row of values
  102482. ** and discard the other (unused) parts of the pSelect object
  102483. */
  102484. if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
  102485. pList = pSelect->pEList;
  102486. pSelect->pEList = 0;
  102487. sqlite3SelectDelete(db, pSelect);
  102488. pSelect = 0;
  102489. }
  102490. /* Locate the table into which we will be inserting new information.
  102491. */
  102492. assert( pTabList->nSrc==1 );
  102493. zTab = pTabList->a[0].zName;
  102494. if( NEVER(zTab==0) ) goto insert_cleanup;
  102495. pTab = sqlite3SrcListLookup(pParse, pTabList);
  102496. if( pTab==0 ){
  102497. goto insert_cleanup;
  102498. }
  102499. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  102500. assert( iDb<db->nDb );
  102501. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
  102502. db->aDb[iDb].zDbSName) ){
  102503. goto insert_cleanup;
  102504. }
  102505. withoutRowid = !HasRowid(pTab);
  102506. /* Figure out if we have any triggers and if the table being
  102507. ** inserted into is a view
  102508. */
  102509. #ifndef SQLITE_OMIT_TRIGGER
  102510. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  102511. isView = pTab->pSelect!=0;
  102512. #else
  102513. # define pTrigger 0
  102514. # define tmask 0
  102515. # define isView 0
  102516. #endif
  102517. #ifdef SQLITE_OMIT_VIEW
  102518. # undef isView
  102519. # define isView 0
  102520. #endif
  102521. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  102522. /* If pTab is really a view, make sure it has been initialized.
  102523. ** ViewGetColumnNames() is a no-op if pTab is not a view.
  102524. */
  102525. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  102526. goto insert_cleanup;
  102527. }
  102528. /* Cannot insert into a read-only table.
  102529. */
  102530. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  102531. goto insert_cleanup;
  102532. }
  102533. /* Allocate a VDBE
  102534. */
  102535. v = sqlite3GetVdbe(pParse);
  102536. if( v==0 ) goto insert_cleanup;
  102537. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  102538. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  102539. #ifndef SQLITE_OMIT_XFER_OPT
  102540. /* If the statement is of the form
  102541. **
  102542. ** INSERT INTO <table1> SELECT * FROM <table2>;
  102543. **
  102544. ** Then special optimizations can be applied that make the transfer
  102545. ** very fast and which reduce fragmentation of indices.
  102546. **
  102547. ** This is the 2nd template.
  102548. */
  102549. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  102550. assert( !pTrigger );
  102551. assert( pList==0 );
  102552. goto insert_end;
  102553. }
  102554. #endif /* SQLITE_OMIT_XFER_OPT */
  102555. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  102556. ** sqlite_sequence table and store it in memory cell regAutoinc.
  102557. */
  102558. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  102559. /* Allocate registers for holding the rowid of the new row,
  102560. ** the content of the new row, and the assembled row record.
  102561. */
  102562. regRowid = regIns = pParse->nMem+1;
  102563. pParse->nMem += pTab->nCol + 1;
  102564. if( IsVirtual(pTab) ){
  102565. regRowid++;
  102566. pParse->nMem++;
  102567. }
  102568. regData = regRowid+1;
  102569. /* If the INSERT statement included an IDLIST term, then make sure
  102570. ** all elements of the IDLIST really are columns of the table and
  102571. ** remember the column indices.
  102572. **
  102573. ** If the table has an INTEGER PRIMARY KEY column and that column
  102574. ** is named in the IDLIST, then record in the ipkColumn variable
  102575. ** the index into IDLIST of the primary key column. ipkColumn is
  102576. ** the index of the primary key as it appears in IDLIST, not as
  102577. ** is appears in the original table. (The index of the INTEGER
  102578. ** PRIMARY KEY in the original table is pTab->iPKey.)
  102579. */
  102580. bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
  102581. if( pColumn ){
  102582. for(i=0; i<pColumn->nId; i++){
  102583. pColumn->a[i].idx = -1;
  102584. }
  102585. for(i=0; i<pColumn->nId; i++){
  102586. for(j=0; j<pTab->nCol; j++){
  102587. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  102588. pColumn->a[i].idx = j;
  102589. if( i!=j ) bIdListInOrder = 0;
  102590. if( j==pTab->iPKey ){
  102591. ipkColumn = i; assert( !withoutRowid );
  102592. }
  102593. break;
  102594. }
  102595. }
  102596. if( j>=pTab->nCol ){
  102597. if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
  102598. ipkColumn = i;
  102599. bIdListInOrder = 0;
  102600. }else{
  102601. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  102602. pTabList, 0, pColumn->a[i].zName);
  102603. pParse->checkSchema = 1;
  102604. goto insert_cleanup;
  102605. }
  102606. }
  102607. }
  102608. }
  102609. /* Figure out how many columns of data are supplied. If the data
  102610. ** is coming from a SELECT statement, then generate a co-routine that
  102611. ** produces a single row of the SELECT on each invocation. The
  102612. ** co-routine is the common header to the 3rd and 4th templates.
  102613. */
  102614. if( pSelect ){
  102615. /* Data is coming from a SELECT or from a multi-row VALUES clause.
  102616. ** Generate a co-routine to run the SELECT. */
  102617. int regYield; /* Register holding co-routine entry-point */
  102618. int addrTop; /* Top of the co-routine */
  102619. int rc; /* Result code */
  102620. regYield = ++pParse->nMem;
  102621. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  102622. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  102623. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  102624. dest.iSdst = bIdListInOrder ? regData : 0;
  102625. dest.nSdst = pTab->nCol;
  102626. rc = sqlite3Select(pParse, pSelect, &dest);
  102627. regFromSelect = dest.iSdst;
  102628. if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
  102629. sqlite3VdbeEndCoroutine(v, regYield);
  102630. sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
  102631. assert( pSelect->pEList );
  102632. nColumn = pSelect->pEList->nExpr;
  102633. /* Set useTempTable to TRUE if the result of the SELECT statement
  102634. ** should be written into a temporary table (template 4). Set to
  102635. ** FALSE if each output row of the SELECT can be written directly into
  102636. ** the destination table (template 3).
  102637. **
  102638. ** A temp table must be used if the table being updated is also one
  102639. ** of the tables being read by the SELECT statement. Also use a
  102640. ** temp table in the case of row triggers.
  102641. */
  102642. if( pTrigger || readsTable(pParse, iDb, pTab) ){
  102643. useTempTable = 1;
  102644. }
  102645. if( useTempTable ){
  102646. /* Invoke the coroutine to extract information from the SELECT
  102647. ** and add it to a transient table srcTab. The code generated
  102648. ** here is from the 4th template:
  102649. **
  102650. ** B: open temp table
  102651. ** L: yield X, goto M at EOF
  102652. ** insert row from R..R+n into temp table
  102653. ** goto L
  102654. ** M: ...
  102655. */
  102656. int regRec; /* Register to hold packed record */
  102657. int regTempRowid; /* Register to hold temp table ROWID */
  102658. int addrL; /* Label "L" */
  102659. srcTab = pParse->nTab++;
  102660. regRec = sqlite3GetTempReg(pParse);
  102661. regTempRowid = sqlite3GetTempReg(pParse);
  102662. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  102663. addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
  102664. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  102665. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  102666. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  102667. sqlite3VdbeGoto(v, addrL);
  102668. sqlite3VdbeJumpHere(v, addrL);
  102669. sqlite3ReleaseTempReg(pParse, regRec);
  102670. sqlite3ReleaseTempReg(pParse, regTempRowid);
  102671. }
  102672. }else{
  102673. /* This is the case if the data for the INSERT is coming from a
  102674. ** single-row VALUES clause
  102675. */
  102676. NameContext sNC;
  102677. memset(&sNC, 0, sizeof(sNC));
  102678. sNC.pParse = pParse;
  102679. srcTab = -1;
  102680. assert( useTempTable==0 );
  102681. if( pList ){
  102682. nColumn = pList->nExpr;
  102683. if( sqlite3ResolveExprListNames(&sNC, pList) ){
  102684. goto insert_cleanup;
  102685. }
  102686. }else{
  102687. nColumn = 0;
  102688. }
  102689. }
  102690. /* If there is no IDLIST term but the table has an integer primary
  102691. ** key, the set the ipkColumn variable to the integer primary key
  102692. ** column index in the original table definition.
  102693. */
  102694. if( pColumn==0 && nColumn>0 ){
  102695. ipkColumn = pTab->iPKey;
  102696. }
  102697. /* Make sure the number of columns in the source data matches the number
  102698. ** of columns to be inserted into the table.
  102699. */
  102700. for(i=0; i<pTab->nCol; i++){
  102701. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  102702. }
  102703. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  102704. sqlite3ErrorMsg(pParse,
  102705. "table %S has %d columns but %d values were supplied",
  102706. pTabList, 0, pTab->nCol-nHidden, nColumn);
  102707. goto insert_cleanup;
  102708. }
  102709. if( pColumn!=0 && nColumn!=pColumn->nId ){
  102710. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  102711. goto insert_cleanup;
  102712. }
  102713. /* Initialize the count of rows to be inserted
  102714. */
  102715. if( db->flags & SQLITE_CountRows ){
  102716. regRowCount = ++pParse->nMem;
  102717. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  102718. }
  102719. /* If this is not a view, open the table and and all indices */
  102720. if( !isView ){
  102721. int nIdx;
  102722. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
  102723. &iDataCur, &iIdxCur);
  102724. aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
  102725. if( aRegIdx==0 ){
  102726. goto insert_cleanup;
  102727. }
  102728. for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
  102729. assert( pIdx );
  102730. aRegIdx[i] = ++pParse->nMem;
  102731. pParse->nMem += pIdx->nColumn;
  102732. }
  102733. }
  102734. /* This is the top of the main insertion loop */
  102735. if( useTempTable ){
  102736. /* This block codes the top of loop only. The complete loop is the
  102737. ** following pseudocode (template 4):
  102738. **
  102739. ** rewind temp table, if empty goto D
  102740. ** C: loop over rows of intermediate table
  102741. ** transfer values form intermediate table into <table>
  102742. ** end loop
  102743. ** D: ...
  102744. */
  102745. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
  102746. addrCont = sqlite3VdbeCurrentAddr(v);
  102747. }else if( pSelect ){
  102748. /* This block codes the top of loop only. The complete loop is the
  102749. ** following pseudocode (template 3):
  102750. **
  102751. ** C: yield X, at EOF goto D
  102752. ** insert the select result into <table> from R..R+n
  102753. ** goto C
  102754. ** D: ...
  102755. */
  102756. addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  102757. VdbeCoverage(v);
  102758. }
  102759. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  102760. */
  102761. endOfLoop = sqlite3VdbeMakeLabel(v);
  102762. if( tmask & TRIGGER_BEFORE ){
  102763. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  102764. /* build the NEW.* reference row. Note that if there is an INTEGER
  102765. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  102766. ** translated into a unique ID for the row. But on a BEFORE trigger,
  102767. ** we do not know what the unique ID will be (because the insert has
  102768. ** not happened yet) so we substitute a rowid of -1
  102769. */
  102770. if( ipkColumn<0 ){
  102771. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  102772. }else{
  102773. int addr1;
  102774. assert( !withoutRowid );
  102775. if( useTempTable ){
  102776. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
  102777. }else{
  102778. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  102779. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
  102780. }
  102781. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
  102782. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  102783. sqlite3VdbeJumpHere(v, addr1);
  102784. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
  102785. }
  102786. /* Cannot have triggers on a virtual table. If it were possible,
  102787. ** this block would have to account for hidden column.
  102788. */
  102789. assert( !IsVirtual(pTab) );
  102790. /* Create the new column data
  102791. */
  102792. for(i=j=0; i<pTab->nCol; i++){
  102793. if( pColumn ){
  102794. for(j=0; j<pColumn->nId; j++){
  102795. if( pColumn->a[j].idx==i ) break;
  102796. }
  102797. }
  102798. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
  102799. || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
  102800. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  102801. }else if( useTempTable ){
  102802. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  102803. }else{
  102804. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  102805. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  102806. }
  102807. if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
  102808. }
  102809. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  102810. ** do not attempt any conversions before assembling the record.
  102811. ** If this is a real table, attempt conversions as required by the
  102812. ** table column affinities.
  102813. */
  102814. if( !isView ){
  102815. sqlite3TableAffinity(v, pTab, regCols+1);
  102816. }
  102817. /* Fire BEFORE or INSTEAD OF triggers */
  102818. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  102819. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  102820. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  102821. }
  102822. /* Compute the content of the next row to insert into a range of
  102823. ** registers beginning at regIns.
  102824. */
  102825. if( !isView ){
  102826. if( IsVirtual(pTab) ){
  102827. /* The row that the VUpdate opcode will delete: none */
  102828. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  102829. }
  102830. if( ipkColumn>=0 ){
  102831. if( useTempTable ){
  102832. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
  102833. }else if( pSelect ){
  102834. sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
  102835. }else{
  102836. VdbeOp *pOp;
  102837. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
  102838. pOp = sqlite3VdbeGetOp(v, -1);
  102839. if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  102840. appendFlag = 1;
  102841. pOp->opcode = OP_NewRowid;
  102842. pOp->p1 = iDataCur;
  102843. pOp->p2 = regRowid;
  102844. pOp->p3 = regAutoinc;
  102845. }
  102846. }
  102847. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  102848. ** to generate a unique primary key value.
  102849. */
  102850. if( !appendFlag ){
  102851. int addr1;
  102852. if( !IsVirtual(pTab) ){
  102853. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
  102854. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  102855. sqlite3VdbeJumpHere(v, addr1);
  102856. }else{
  102857. addr1 = sqlite3VdbeCurrentAddr(v);
  102858. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
  102859. }
  102860. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
  102861. }
  102862. }else if( IsVirtual(pTab) || withoutRowid ){
  102863. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  102864. }else{
  102865. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  102866. appendFlag = 1;
  102867. }
  102868. autoIncStep(pParse, regAutoinc, regRowid);
  102869. /* Compute data for all columns of the new entry, beginning
  102870. ** with the first column.
  102871. */
  102872. nHidden = 0;
  102873. for(i=0; i<pTab->nCol; i++){
  102874. int iRegStore = regRowid+1+i;
  102875. if( i==pTab->iPKey ){
  102876. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  102877. ** Whenever this column is read, the rowid will be substituted
  102878. ** in its place. Hence, fill this column with a NULL to avoid
  102879. ** taking up data space with information that will never be used.
  102880. ** As there may be shallow copies of this value, make it a soft-NULL */
  102881. sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
  102882. continue;
  102883. }
  102884. if( pColumn==0 ){
  102885. if( IsHiddenColumn(&pTab->aCol[i]) ){
  102886. j = -1;
  102887. nHidden++;
  102888. }else{
  102889. j = i - nHidden;
  102890. }
  102891. }else{
  102892. for(j=0; j<pColumn->nId; j++){
  102893. if( pColumn->a[j].idx==i ) break;
  102894. }
  102895. }
  102896. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  102897. sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
  102898. }else if( useTempTable ){
  102899. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  102900. }else if( pSelect ){
  102901. if( regFromSelect!=regData ){
  102902. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  102903. }
  102904. }else{
  102905. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  102906. }
  102907. }
  102908. /* Generate code to check constraints and generate index keys and
  102909. ** do the insertion.
  102910. */
  102911. #ifndef SQLITE_OMIT_VIRTUALTABLE
  102912. if( IsVirtual(pTab) ){
  102913. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  102914. sqlite3VtabMakeWritable(pParse, pTab);
  102915. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  102916. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  102917. sqlite3MayAbort(pParse);
  102918. }else
  102919. #endif
  102920. {
  102921. int isReplace; /* Set to true if constraints may cause a replace */
  102922. int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
  102923. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  102924. regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
  102925. );
  102926. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  102927. /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
  102928. ** constraints or (b) there are no triggers and this table is not a
  102929. ** parent table in a foreign key constraint. It is safe to set the
  102930. ** flag in the second case as if any REPLACE constraint is hit, an
  102931. ** OP_Delete or OP_IdxDelete instruction will be executed on each
  102932. ** cursor that is disturbed. And these instructions both clear the
  102933. ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
  102934. ** functionality. */
  102935. bUseSeek = (isReplace==0 || (pTrigger==0 &&
  102936. ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
  102937. ));
  102938. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  102939. regIns, aRegIdx, 0, appendFlag, bUseSeek
  102940. );
  102941. }
  102942. }
  102943. /* Update the count of rows that are inserted
  102944. */
  102945. if( (db->flags & SQLITE_CountRows)!=0 ){
  102946. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  102947. }
  102948. if( pTrigger ){
  102949. /* Code AFTER triggers */
  102950. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  102951. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  102952. }
  102953. /* The bottom of the main insertion loop, if the data source
  102954. ** is a SELECT statement.
  102955. */
  102956. sqlite3VdbeResolveLabel(v, endOfLoop);
  102957. if( useTempTable ){
  102958. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
  102959. sqlite3VdbeJumpHere(v, addrInsTop);
  102960. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  102961. }else if( pSelect ){
  102962. sqlite3VdbeGoto(v, addrCont);
  102963. sqlite3VdbeJumpHere(v, addrInsTop);
  102964. }
  102965. insert_end:
  102966. /* Update the sqlite_sequence table by storing the content of the
  102967. ** maximum rowid counter values recorded while inserting into
  102968. ** autoincrement tables.
  102969. */
  102970. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  102971. sqlite3AutoincrementEnd(pParse);
  102972. }
  102973. /*
  102974. ** Return the number of rows inserted. If this routine is
  102975. ** generating code because of a call to sqlite3NestedParse(), do not
  102976. ** invoke the callback function.
  102977. */
  102978. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  102979. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  102980. sqlite3VdbeSetNumCols(v, 1);
  102981. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  102982. }
  102983. insert_cleanup:
  102984. sqlite3SrcListDelete(db, pTabList);
  102985. sqlite3ExprListDelete(db, pList);
  102986. sqlite3SelectDelete(db, pSelect);
  102987. sqlite3IdListDelete(db, pColumn);
  102988. sqlite3DbFree(db, aRegIdx);
  102989. }
  102990. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  102991. ** they may interfere with compilation of other functions in this file
  102992. ** (or in another file, if this file becomes part of the amalgamation). */
  102993. #ifdef isView
  102994. #undef isView
  102995. #endif
  102996. #ifdef pTrigger
  102997. #undef pTrigger
  102998. #endif
  102999. #ifdef tmask
  103000. #undef tmask
  103001. #endif
  103002. /*
  103003. ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
  103004. */
  103005. #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
  103006. #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
  103007. /* This is the Walker callback from checkConstraintUnchanged(). Set
  103008. ** bit 0x01 of pWalker->eCode if
  103009. ** pWalker->eCode to 0 if this expression node references any of the
  103010. ** columns that are being modifed by an UPDATE statement.
  103011. */
  103012. static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
  103013. if( pExpr->op==TK_COLUMN ){
  103014. assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
  103015. if( pExpr->iColumn>=0 ){
  103016. if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
  103017. pWalker->eCode |= CKCNSTRNT_COLUMN;
  103018. }
  103019. }else{
  103020. pWalker->eCode |= CKCNSTRNT_ROWID;
  103021. }
  103022. }
  103023. return WRC_Continue;
  103024. }
  103025. /*
  103026. ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
  103027. ** only columns that are modified by the UPDATE are those for which
  103028. ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
  103029. **
  103030. ** Return true if CHECK constraint pExpr does not use any of the
  103031. ** changing columns (or the rowid if it is changing). In other words,
  103032. ** return true if this CHECK constraint can be skipped when validating
  103033. ** the new row in the UPDATE statement.
  103034. */
  103035. static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
  103036. Walker w;
  103037. memset(&w, 0, sizeof(w));
  103038. w.eCode = 0;
  103039. w.xExprCallback = checkConstraintExprNode;
  103040. w.u.aiCol = aiChng;
  103041. sqlite3WalkExpr(&w, pExpr);
  103042. if( !chngRowid ){
  103043. testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
  103044. w.eCode &= ~CKCNSTRNT_ROWID;
  103045. }
  103046. testcase( w.eCode==0 );
  103047. testcase( w.eCode==CKCNSTRNT_COLUMN );
  103048. testcase( w.eCode==CKCNSTRNT_ROWID );
  103049. testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
  103050. return !w.eCode;
  103051. }
  103052. /*
  103053. ** Generate code to do constraint checks prior to an INSERT or an UPDATE
  103054. ** on table pTab.
  103055. **
  103056. ** The regNewData parameter is the first register in a range that contains
  103057. ** the data to be inserted or the data after the update. There will be
  103058. ** pTab->nCol+1 registers in this range. The first register (the one
  103059. ** that regNewData points to) will contain the new rowid, or NULL in the
  103060. ** case of a WITHOUT ROWID table. The second register in the range will
  103061. ** contain the content of the first table column. The third register will
  103062. ** contain the content of the second table column. And so forth.
  103063. **
  103064. ** The regOldData parameter is similar to regNewData except that it contains
  103065. ** the data prior to an UPDATE rather than afterwards. regOldData is zero
  103066. ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
  103067. ** checking regOldData for zero.
  103068. **
  103069. ** For an UPDATE, the pkChng boolean is true if the true primary key (the
  103070. ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
  103071. ** might be modified by the UPDATE. If pkChng is false, then the key of
  103072. ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
  103073. **
  103074. ** For an INSERT, the pkChng boolean indicates whether or not the rowid
  103075. ** was explicitly specified as part of the INSERT statement. If pkChng
  103076. ** is zero, it means that the either rowid is computed automatically or
  103077. ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
  103078. ** pkChng will only be true if the INSERT statement provides an integer
  103079. ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
  103080. **
  103081. ** The code generated by this routine will store new index entries into
  103082. ** registers identified by aRegIdx[]. No index entry is created for
  103083. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  103084. ** the same as the order of indices on the linked list of indices
  103085. ** at pTab->pIndex.
  103086. **
  103087. ** The caller must have already opened writeable cursors on the main
  103088. ** table and all applicable indices (that is to say, all indices for which
  103089. ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
  103090. ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
  103091. ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
  103092. ** for the first index in the pTab->pIndex list. Cursors for other indices
  103093. ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
  103094. **
  103095. ** This routine also generates code to check constraints. NOT NULL,
  103096. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  103097. ** then the appropriate action is performed. There are five possible
  103098. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  103099. **
  103100. ** Constraint type Action What Happens
  103101. ** --------------- ---------- ----------------------------------------
  103102. ** any ROLLBACK The current transaction is rolled back and
  103103. ** sqlite3_step() returns immediately with a
  103104. ** return code of SQLITE_CONSTRAINT.
  103105. **
  103106. ** any ABORT Back out changes from the current command
  103107. ** only (do not do a complete rollback) then
  103108. ** cause sqlite3_step() to return immediately
  103109. ** with SQLITE_CONSTRAINT.
  103110. **
  103111. ** any FAIL Sqlite3_step() returns immediately with a
  103112. ** return code of SQLITE_CONSTRAINT. The
  103113. ** transaction is not rolled back and any
  103114. ** changes to prior rows are retained.
  103115. **
  103116. ** any IGNORE The attempt in insert or update the current
  103117. ** row is skipped, without throwing an error.
  103118. ** Processing continues with the next row.
  103119. ** (There is an immediate jump to ignoreDest.)
  103120. **
  103121. ** NOT NULL REPLACE The NULL value is replace by the default
  103122. ** value for that column. If the default value
  103123. ** is NULL, the action is the same as ABORT.
  103124. **
  103125. ** UNIQUE REPLACE The other row that conflicts with the row
  103126. ** being inserted is removed.
  103127. **
  103128. ** CHECK REPLACE Illegal. The results in an exception.
  103129. **
  103130. ** Which action to take is determined by the overrideError parameter.
  103131. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  103132. ** is used. Or if pParse->onError==OE_Default then the onError value
  103133. ** for the constraint is used.
  103134. */
  103135. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  103136. Parse *pParse, /* The parser context */
  103137. Table *pTab, /* The table being inserted or updated */
  103138. int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
  103139. int iDataCur, /* Canonical data cursor (main table or PK index) */
  103140. int iIdxCur, /* First index cursor */
  103141. int regNewData, /* First register in a range holding values to insert */
  103142. int regOldData, /* Previous content. 0 for INSERTs */
  103143. u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
  103144. u8 overrideError, /* Override onError to this if not OE_Default */
  103145. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  103146. int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
  103147. int *aiChng /* column i is unchanged if aiChng[i]<0 */
  103148. ){
  103149. Vdbe *v; /* VDBE under constrution */
  103150. Index *pIdx; /* Pointer to one of the indices */
  103151. Index *pPk = 0; /* The PRIMARY KEY index */
  103152. sqlite3 *db; /* Database connection */
  103153. int i; /* loop counter */
  103154. int ix; /* Index loop counter */
  103155. int nCol; /* Number of columns */
  103156. int onError; /* Conflict resolution strategy */
  103157. int addr1; /* Address of jump instruction */
  103158. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  103159. int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
  103160. int ipkTop = 0; /* Top of the rowid change constraint check */
  103161. int ipkBottom = 0; /* Bottom of the rowid change constraint check */
  103162. u8 isUpdate; /* True if this is an UPDATE operation */
  103163. u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
  103164. isUpdate = regOldData!=0;
  103165. db = pParse->db;
  103166. v = sqlite3GetVdbe(pParse);
  103167. assert( v!=0 );
  103168. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  103169. nCol = pTab->nCol;
  103170. /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
  103171. ** normal rowid tables. nPkField is the number of key fields in the
  103172. ** pPk index or 1 for a rowid table. In other words, nPkField is the
  103173. ** number of fields in the true primary key of the table. */
  103174. if( HasRowid(pTab) ){
  103175. pPk = 0;
  103176. nPkField = 1;
  103177. }else{
  103178. pPk = sqlite3PrimaryKeyIndex(pTab);
  103179. nPkField = pPk->nKeyCol;
  103180. }
  103181. /* Record that this module has started */
  103182. VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
  103183. iDataCur, iIdxCur, regNewData, regOldData, pkChng));
  103184. /* Test all NOT NULL constraints.
  103185. */
  103186. for(i=0; i<nCol; i++){
  103187. if( i==pTab->iPKey ){
  103188. continue; /* ROWID is never NULL */
  103189. }
  103190. if( aiChng && aiChng[i]<0 ){
  103191. /* Don't bother checking for NOT NULL on columns that do not change */
  103192. continue;
  103193. }
  103194. onError = pTab->aCol[i].notNull;
  103195. if( onError==OE_None ) continue; /* This column is allowed to be NULL */
  103196. if( overrideError!=OE_Default ){
  103197. onError = overrideError;
  103198. }else if( onError==OE_Default ){
  103199. onError = OE_Abort;
  103200. }
  103201. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  103202. onError = OE_Abort;
  103203. }
  103204. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  103205. || onError==OE_Ignore || onError==OE_Replace );
  103206. switch( onError ){
  103207. case OE_Abort:
  103208. sqlite3MayAbort(pParse);
  103209. /* Fall through */
  103210. case OE_Rollback:
  103211. case OE_Fail: {
  103212. char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
  103213. pTab->aCol[i].zName);
  103214. sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
  103215. regNewData+1+i);
  103216. sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
  103217. sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
  103218. VdbeCoverage(v);
  103219. break;
  103220. }
  103221. case OE_Ignore: {
  103222. sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
  103223. VdbeCoverage(v);
  103224. break;
  103225. }
  103226. default: {
  103227. assert( onError==OE_Replace );
  103228. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
  103229. VdbeCoverage(v);
  103230. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
  103231. sqlite3VdbeJumpHere(v, addr1);
  103232. break;
  103233. }
  103234. }
  103235. }
  103236. /* Test all CHECK constraints
  103237. */
  103238. #ifndef SQLITE_OMIT_CHECK
  103239. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  103240. ExprList *pCheck = pTab->pCheck;
  103241. pParse->ckBase = regNewData+1;
  103242. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  103243. for(i=0; i<pCheck->nExpr; i++){
  103244. int allOk;
  103245. Expr *pExpr = pCheck->a[i].pExpr;
  103246. if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
  103247. allOk = sqlite3VdbeMakeLabel(v);
  103248. sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
  103249. if( onError==OE_Ignore ){
  103250. sqlite3VdbeGoto(v, ignoreDest);
  103251. }else{
  103252. char *zName = pCheck->a[i].zName;
  103253. if( zName==0 ) zName = pTab->zName;
  103254. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  103255. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  103256. onError, zName, P4_TRANSIENT,
  103257. P5_ConstraintCheck);
  103258. }
  103259. sqlite3VdbeResolveLabel(v, allOk);
  103260. }
  103261. }
  103262. #endif /* !defined(SQLITE_OMIT_CHECK) */
  103263. /* If rowid is changing, make sure the new rowid does not previously
  103264. ** exist in the table.
  103265. */
  103266. if( pkChng && pPk==0 ){
  103267. int addrRowidOk = sqlite3VdbeMakeLabel(v);
  103268. /* Figure out what action to take in case of a rowid collision */
  103269. onError = pTab->keyConf;
  103270. if( overrideError!=OE_Default ){
  103271. onError = overrideError;
  103272. }else if( onError==OE_Default ){
  103273. onError = OE_Abort;
  103274. }
  103275. if( isUpdate ){
  103276. /* pkChng!=0 does not mean that the rowid has changed, only that
  103277. ** it might have changed. Skip the conflict logic below if the rowid
  103278. ** is unchanged. */
  103279. sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
  103280. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  103281. VdbeCoverage(v);
  103282. }
  103283. /* If the response to a rowid conflict is REPLACE but the response
  103284. ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
  103285. ** to defer the running of the rowid conflict checking until after
  103286. ** the UNIQUE constraints have run.
  103287. */
  103288. if( onError==OE_Replace && overrideError!=OE_Replace ){
  103289. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  103290. if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
  103291. ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
  103292. break;
  103293. }
  103294. }
  103295. }
  103296. /* Check to see if the new rowid already exists in the table. Skip
  103297. ** the following conflict logic if it does not. */
  103298. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
  103299. VdbeCoverage(v);
  103300. /* Generate code that deals with a rowid collision */
  103301. switch( onError ){
  103302. default: {
  103303. onError = OE_Abort;
  103304. /* Fall thru into the next case */
  103305. }
  103306. case OE_Rollback:
  103307. case OE_Abort:
  103308. case OE_Fail: {
  103309. sqlite3RowidConstraint(pParse, onError, pTab);
  103310. break;
  103311. }
  103312. case OE_Replace: {
  103313. /* If there are DELETE triggers on this table and the
  103314. ** recursive-triggers flag is set, call GenerateRowDelete() to
  103315. ** remove the conflicting row from the table. This will fire
  103316. ** the triggers and remove both the table and index b-tree entries.
  103317. **
  103318. ** Otherwise, if there are no triggers or the recursive-triggers
  103319. ** flag is not set, but the table has one or more indexes, call
  103320. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  103321. ** only. The table b-tree entry will be replaced by the new entry
  103322. ** when it is inserted.
  103323. **
  103324. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  103325. ** also invoke MultiWrite() to indicate that this VDBE may require
  103326. ** statement rollback (if the statement is aborted after the delete
  103327. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  103328. ** but being more selective here allows statements like:
  103329. **
  103330. ** REPLACE INTO t(rowid) VALUES($newrowid)
  103331. **
  103332. ** to run without a statement journal if there are no indexes on the
  103333. ** table.
  103334. */
  103335. Trigger *pTrigger = 0;
  103336. if( db->flags&SQLITE_RecTriggers ){
  103337. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  103338. }
  103339. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  103340. sqlite3MultiWrite(pParse);
  103341. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  103342. regNewData, 1, 0, OE_Replace, 1, -1);
  103343. }else{
  103344. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  103345. if( HasRowid(pTab) ){
  103346. /* This OP_Delete opcode fires the pre-update-hook only. It does
  103347. ** not modify the b-tree. It is more efficient to let the coming
  103348. ** OP_Insert replace the existing entry than it is to delete the
  103349. ** existing entry and then insert a new one. */
  103350. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
  103351. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  103352. }
  103353. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  103354. if( pTab->pIndex ){
  103355. sqlite3MultiWrite(pParse);
  103356. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
  103357. }
  103358. }
  103359. seenReplace = 1;
  103360. break;
  103361. }
  103362. case OE_Ignore: {
  103363. /*assert( seenReplace==0 );*/
  103364. sqlite3VdbeGoto(v, ignoreDest);
  103365. break;
  103366. }
  103367. }
  103368. sqlite3VdbeResolveLabel(v, addrRowidOk);
  103369. if( ipkTop ){
  103370. ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
  103371. sqlite3VdbeJumpHere(v, ipkTop);
  103372. }
  103373. }
  103374. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  103375. ** index and making sure that duplicate entries do not already exist.
  103376. ** Compute the revised record entries for indices as we go.
  103377. **
  103378. ** This loop also handles the case of the PRIMARY KEY index for a
  103379. ** WITHOUT ROWID table.
  103380. */
  103381. for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
  103382. int regIdx; /* Range of registers hold conent for pIdx */
  103383. int regR; /* Range of registers holding conflicting PK */
  103384. int iThisCur; /* Cursor for this UNIQUE index */
  103385. int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
  103386. if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
  103387. if( bAffinityDone==0 ){
  103388. sqlite3TableAffinity(v, pTab, regNewData+1);
  103389. bAffinityDone = 1;
  103390. }
  103391. iThisCur = iIdxCur+ix;
  103392. addrUniqueOk = sqlite3VdbeMakeLabel(v);
  103393. /* Skip partial indices for which the WHERE clause is not true */
  103394. if( pIdx->pPartIdxWhere ){
  103395. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
  103396. pParse->ckBase = regNewData+1;
  103397. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
  103398. SQLITE_JUMPIFNULL);
  103399. pParse->ckBase = 0;
  103400. }
  103401. /* Create a record for this index entry as it should appear after
  103402. ** the insert or update. Store that record in the aRegIdx[ix] register
  103403. */
  103404. regIdx = aRegIdx[ix]+1;
  103405. for(i=0; i<pIdx->nColumn; i++){
  103406. int iField = pIdx->aiColumn[i];
  103407. int x;
  103408. if( iField==XN_EXPR ){
  103409. pParse->ckBase = regNewData+1;
  103410. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
  103411. pParse->ckBase = 0;
  103412. VdbeComment((v, "%s column %d", pIdx->zName, i));
  103413. }else{
  103414. if( iField==XN_ROWID || iField==pTab->iPKey ){
  103415. x = regNewData;
  103416. }else{
  103417. x = iField + regNewData + 1;
  103418. }
  103419. sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
  103420. VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
  103421. }
  103422. }
  103423. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
  103424. VdbeComment((v, "for %s", pIdx->zName));
  103425. #ifdef SQLITE_ENABLE_NULL_TRIM
  103426. if( pIdx->idxType==2 ) sqlite3SetMakeRecordP5(v, pIdx->pTable);
  103427. #endif
  103428. /* In an UPDATE operation, if this index is the PRIMARY KEY index
  103429. ** of a WITHOUT ROWID table and there has been no change the
  103430. ** primary key, then no collision is possible. The collision detection
  103431. ** logic below can all be skipped. */
  103432. if( isUpdate && pPk==pIdx && pkChng==0 ){
  103433. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  103434. continue;
  103435. }
  103436. /* Find out what action to take in case there is a uniqueness conflict */
  103437. onError = pIdx->onError;
  103438. if( onError==OE_None ){
  103439. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  103440. continue; /* pIdx is not a UNIQUE index */
  103441. }
  103442. if( overrideError!=OE_Default ){
  103443. onError = overrideError;
  103444. }else if( onError==OE_Default ){
  103445. onError = OE_Abort;
  103446. }
  103447. /* Collision detection may be omitted if all of the following are true:
  103448. ** (1) The conflict resolution algorithm is REPLACE
  103449. ** (2) The table is a WITHOUT ROWID table
  103450. ** (3) There are no secondary indexes on the table
  103451. ** (4) No delete triggers need to be fired if there is a conflict
  103452. ** (5) No FK constraint counters need to be updated if a conflict occurs.
  103453. */
  103454. if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
  103455. && pPk==pIdx /* Condition 2 */
  103456. && onError==OE_Replace /* Condition 1 */
  103457. && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
  103458. 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
  103459. && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
  103460. (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
  103461. ){
  103462. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  103463. continue;
  103464. }
  103465. /* Check to see if the new index entry will be unique */
  103466. sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
  103467. regIdx, pIdx->nKeyCol); VdbeCoverage(v);
  103468. /* Generate code to handle collisions */
  103469. regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
  103470. if( isUpdate || onError==OE_Replace ){
  103471. if( HasRowid(pTab) ){
  103472. sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
  103473. /* Conflict only if the rowid of the existing index entry
  103474. ** is different from old-rowid */
  103475. if( isUpdate ){
  103476. sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
  103477. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  103478. VdbeCoverage(v);
  103479. }
  103480. }else{
  103481. int x;
  103482. /* Extract the PRIMARY KEY from the end of the index entry and
  103483. ** store it in registers regR..regR+nPk-1 */
  103484. if( pIdx!=pPk ){
  103485. for(i=0; i<pPk->nKeyCol; i++){
  103486. assert( pPk->aiColumn[i]>=0 );
  103487. x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  103488. sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
  103489. VdbeComment((v, "%s.%s", pTab->zName,
  103490. pTab->aCol[pPk->aiColumn[i]].zName));
  103491. }
  103492. }
  103493. if( isUpdate ){
  103494. /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
  103495. ** table, only conflict if the new PRIMARY KEY values are actually
  103496. ** different from the old.
  103497. **
  103498. ** For a UNIQUE index, only conflict if the PRIMARY KEY values
  103499. ** of the matched index row are different from the original PRIMARY
  103500. ** KEY values of this row before the update. */
  103501. int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
  103502. int op = OP_Ne;
  103503. int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
  103504. for(i=0; i<pPk->nKeyCol; i++){
  103505. char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
  103506. x = pPk->aiColumn[i];
  103507. assert( x>=0 );
  103508. if( i==(pPk->nKeyCol-1) ){
  103509. addrJump = addrUniqueOk;
  103510. op = OP_Eq;
  103511. }
  103512. sqlite3VdbeAddOp4(v, op,
  103513. regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
  103514. );
  103515. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  103516. VdbeCoverageIf(v, op==OP_Eq);
  103517. VdbeCoverageIf(v, op==OP_Ne);
  103518. }
  103519. }
  103520. }
  103521. }
  103522. /* Generate code that executes if the new index entry is not unique */
  103523. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  103524. || onError==OE_Ignore || onError==OE_Replace );
  103525. switch( onError ){
  103526. case OE_Rollback:
  103527. case OE_Abort:
  103528. case OE_Fail: {
  103529. sqlite3UniqueConstraint(pParse, onError, pIdx);
  103530. break;
  103531. }
  103532. case OE_Ignore: {
  103533. sqlite3VdbeGoto(v, ignoreDest);
  103534. break;
  103535. }
  103536. default: {
  103537. Trigger *pTrigger = 0;
  103538. assert( onError==OE_Replace );
  103539. sqlite3MultiWrite(pParse);
  103540. if( db->flags&SQLITE_RecTriggers ){
  103541. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  103542. }
  103543. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  103544. regR, nPkField, 0, OE_Replace,
  103545. (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
  103546. seenReplace = 1;
  103547. break;
  103548. }
  103549. }
  103550. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  103551. if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
  103552. }
  103553. if( ipkTop ){
  103554. sqlite3VdbeGoto(v, ipkTop+1);
  103555. sqlite3VdbeJumpHere(v, ipkBottom);
  103556. }
  103557. *pbMayReplace = seenReplace;
  103558. VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
  103559. }
  103560. #ifdef SQLITE_ENABLE_NULL_TRIM
  103561. /*
  103562. ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
  103563. ** to be the number of columns in table pTab that must not be NULL-trimmed.
  103564. **
  103565. ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
  103566. */
  103567. SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
  103568. u16 i;
  103569. /* Records with omitted columns are only allowed for schema format
  103570. ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
  103571. if( pTab->pSchema->file_format<2 ) return;
  103572. for(i=pTab->nCol-1; i>0; i--){
  103573. if( pTab->aCol[i].pDflt!=0 ) break;
  103574. if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
  103575. }
  103576. sqlite3VdbeChangeP5(v, i+1);
  103577. }
  103578. #endif
  103579. /*
  103580. ** This routine generates code to finish the INSERT or UPDATE operation
  103581. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  103582. ** A consecutive range of registers starting at regNewData contains the
  103583. ** rowid and the content to be inserted.
  103584. **
  103585. ** The arguments to this routine should be the same as the first six
  103586. ** arguments to sqlite3GenerateConstraintChecks.
  103587. */
  103588. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  103589. Parse *pParse, /* The parser context */
  103590. Table *pTab, /* the table into which we are inserting */
  103591. int iDataCur, /* Cursor of the canonical data source */
  103592. int iIdxCur, /* First index cursor */
  103593. int regNewData, /* Range of content */
  103594. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  103595. int update_flags, /* True for UPDATE, False for INSERT */
  103596. int appendBias, /* True if this is likely to be an append */
  103597. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  103598. ){
  103599. Vdbe *v; /* Prepared statements under construction */
  103600. Index *pIdx; /* An index being inserted or updated */
  103601. u8 pik_flags; /* flag values passed to the btree insert */
  103602. int regData; /* Content registers (after the rowid) */
  103603. int regRec; /* Register holding assembled record for the table */
  103604. int i; /* Loop counter */
  103605. u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
  103606. assert( update_flags==0
  103607. || update_flags==OPFLAG_ISUPDATE
  103608. || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
  103609. );
  103610. v = sqlite3GetVdbe(pParse);
  103611. assert( v!=0 );
  103612. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  103613. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  103614. if( aRegIdx[i]==0 ) continue;
  103615. bAffinityDone = 1;
  103616. if( pIdx->pPartIdxWhere ){
  103617. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  103618. VdbeCoverage(v);
  103619. }
  103620. pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
  103621. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  103622. assert( pParse->nested==0 );
  103623. pik_flags |= OPFLAG_NCHANGE;
  103624. pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
  103625. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  103626. if( update_flags==0 ){
  103627. sqlite3VdbeAddOp4(v, OP_InsertInt,
  103628. iIdxCur+i, aRegIdx[i], 0, (char*)pTab, P4_TABLE
  103629. );
  103630. sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
  103631. }
  103632. #endif
  103633. }
  103634. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
  103635. aRegIdx[i]+1,
  103636. pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
  103637. sqlite3VdbeChangeP5(v, pik_flags);
  103638. }
  103639. if( !HasRowid(pTab) ) return;
  103640. regData = regNewData + 1;
  103641. regRec = sqlite3GetTempReg(pParse);
  103642. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  103643. sqlite3SetMakeRecordP5(v, pTab);
  103644. if( !bAffinityDone ){
  103645. sqlite3TableAffinity(v, pTab, 0);
  103646. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  103647. }
  103648. if( pParse->nested ){
  103649. pik_flags = 0;
  103650. }else{
  103651. pik_flags = OPFLAG_NCHANGE;
  103652. pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
  103653. }
  103654. if( appendBias ){
  103655. pik_flags |= OPFLAG_APPEND;
  103656. }
  103657. if( useSeekResult ){
  103658. pik_flags |= OPFLAG_USESEEKRESULT;
  103659. }
  103660. sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
  103661. if( !pParse->nested ){
  103662. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  103663. }
  103664. sqlite3VdbeChangeP5(v, pik_flags);
  103665. }
  103666. /*
  103667. ** Allocate cursors for the pTab table and all its indices and generate
  103668. ** code to open and initialized those cursors.
  103669. **
  103670. ** The cursor for the object that contains the complete data (normally
  103671. ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
  103672. ** ROWID table) is returned in *piDataCur. The first index cursor is
  103673. ** returned in *piIdxCur. The number of indices is returned.
  103674. **
  103675. ** Use iBase as the first cursor (either the *piDataCur for rowid tables
  103676. ** or the first index for WITHOUT ROWID tables) if it is non-negative.
  103677. ** If iBase is negative, then allocate the next available cursor.
  103678. **
  103679. ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
  103680. ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
  103681. ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
  103682. ** pTab->pIndex list.
  103683. **
  103684. ** If pTab is a virtual table, then this routine is a no-op and the
  103685. ** *piDataCur and *piIdxCur values are left uninitialized.
  103686. */
  103687. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  103688. Parse *pParse, /* Parsing context */
  103689. Table *pTab, /* Table to be opened */
  103690. int op, /* OP_OpenRead or OP_OpenWrite */
  103691. u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
  103692. int iBase, /* Use this for the table cursor, if there is one */
  103693. u8 *aToOpen, /* If not NULL: boolean for each table and index */
  103694. int *piDataCur, /* Write the database source cursor number here */
  103695. int *piIdxCur /* Write the first index cursor number here */
  103696. ){
  103697. int i;
  103698. int iDb;
  103699. int iDataCur;
  103700. Index *pIdx;
  103701. Vdbe *v;
  103702. assert( op==OP_OpenRead || op==OP_OpenWrite );
  103703. assert( op==OP_OpenWrite || p5==0 );
  103704. if( IsVirtual(pTab) ){
  103705. /* This routine is a no-op for virtual tables. Leave the output
  103706. ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
  103707. ** can detect if they are used by mistake in the caller. */
  103708. return 0;
  103709. }
  103710. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  103711. v = sqlite3GetVdbe(pParse);
  103712. assert( v!=0 );
  103713. if( iBase<0 ) iBase = pParse->nTab;
  103714. iDataCur = iBase++;
  103715. if( piDataCur ) *piDataCur = iDataCur;
  103716. if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
  103717. sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
  103718. }else{
  103719. sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
  103720. }
  103721. if( piIdxCur ) *piIdxCur = iBase;
  103722. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  103723. int iIdxCur = iBase++;
  103724. assert( pIdx->pSchema==pTab->pSchema );
  103725. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  103726. if( piDataCur ) *piDataCur = iIdxCur;
  103727. p5 = 0;
  103728. }
  103729. if( aToOpen==0 || aToOpen[i+1] ){
  103730. sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
  103731. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  103732. sqlite3VdbeChangeP5(v, p5);
  103733. VdbeComment((v, "%s", pIdx->zName));
  103734. }
  103735. }
  103736. if( iBase>pParse->nTab ) pParse->nTab = iBase;
  103737. return i;
  103738. }
  103739. #ifdef SQLITE_TEST
  103740. /*
  103741. ** The following global variable is incremented whenever the
  103742. ** transfer optimization is used. This is used for testing
  103743. ** purposes only - to make sure the transfer optimization really
  103744. ** is happening when it is supposed to.
  103745. */
  103746. SQLITE_API int sqlite3_xferopt_count;
  103747. #endif /* SQLITE_TEST */
  103748. #ifndef SQLITE_OMIT_XFER_OPT
  103749. /*
  103750. ** Check to see if index pSrc is compatible as a source of data
  103751. ** for index pDest in an insert transfer optimization. The rules
  103752. ** for a compatible index:
  103753. **
  103754. ** * The index is over the same set of columns
  103755. ** * The same DESC and ASC markings occurs on all columns
  103756. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  103757. ** * The same collating sequence on each column
  103758. ** * The index has the exact same WHERE clause
  103759. */
  103760. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  103761. int i;
  103762. assert( pDest && pSrc );
  103763. assert( pDest->pTable!=pSrc->pTable );
  103764. if( pDest->nKeyCol!=pSrc->nKeyCol ){
  103765. return 0; /* Different number of columns */
  103766. }
  103767. if( pDest->onError!=pSrc->onError ){
  103768. return 0; /* Different conflict resolution strategies */
  103769. }
  103770. for(i=0; i<pSrc->nKeyCol; i++){
  103771. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  103772. return 0; /* Different columns indexed */
  103773. }
  103774. if( pSrc->aiColumn[i]==XN_EXPR ){
  103775. assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
  103776. if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr,
  103777. pDest->aColExpr->a[i].pExpr, -1)!=0 ){
  103778. return 0; /* Different expressions in the index */
  103779. }
  103780. }
  103781. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  103782. return 0; /* Different sort orders */
  103783. }
  103784. if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
  103785. return 0; /* Different collating sequences */
  103786. }
  103787. }
  103788. if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  103789. return 0; /* Different WHERE clauses */
  103790. }
  103791. /* If no test above fails then the indices must be compatible */
  103792. return 1;
  103793. }
  103794. /*
  103795. ** Attempt the transfer optimization on INSERTs of the form
  103796. **
  103797. ** INSERT INTO tab1 SELECT * FROM tab2;
  103798. **
  103799. ** The xfer optimization transfers raw records from tab2 over to tab1.
  103800. ** Columns are not decoded and reassembled, which greatly improves
  103801. ** performance. Raw index records are transferred in the same way.
  103802. **
  103803. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  103804. ** There are lots of rules for determining compatibility - see comments
  103805. ** embedded in the code for details.
  103806. **
  103807. ** This routine returns TRUE if the optimization is guaranteed to be used.
  103808. ** Sometimes the xfer optimization will only work if the destination table
  103809. ** is empty - a factor that can only be determined at run-time. In that
  103810. ** case, this routine generates code for the xfer optimization but also
  103811. ** does a test to see if the destination table is empty and jumps over the
  103812. ** xfer optimization code if the test fails. In that case, this routine
  103813. ** returns FALSE so that the caller will know to go ahead and generate
  103814. ** an unoptimized transfer. This routine also returns FALSE if there
  103815. ** is no chance that the xfer optimization can be applied.
  103816. **
  103817. ** This optimization is particularly useful at making VACUUM run faster.
  103818. */
  103819. static int xferOptimization(
  103820. Parse *pParse, /* Parser context */
  103821. Table *pDest, /* The table we are inserting into */
  103822. Select *pSelect, /* A SELECT statement to use as the data source */
  103823. int onError, /* How to handle constraint errors */
  103824. int iDbDest /* The database of pDest */
  103825. ){
  103826. sqlite3 *db = pParse->db;
  103827. ExprList *pEList; /* The result set of the SELECT */
  103828. Table *pSrc; /* The table in the FROM clause of SELECT */
  103829. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  103830. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  103831. int i; /* Loop counter */
  103832. int iDbSrc; /* The database of pSrc */
  103833. int iSrc, iDest; /* Cursors from source and destination */
  103834. int addr1, addr2; /* Loop addresses */
  103835. int emptyDestTest = 0; /* Address of test for empty pDest */
  103836. int emptySrcTest = 0; /* Address of test for empty pSrc */
  103837. Vdbe *v; /* The VDBE we are building */
  103838. int regAutoinc; /* Memory register used by AUTOINC */
  103839. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  103840. int regData, regRowid; /* Registers holding data and rowid */
  103841. if( pSelect==0 ){
  103842. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  103843. }
  103844. if( pParse->pWith || pSelect->pWith ){
  103845. /* Do not attempt to process this query if there are an WITH clauses
  103846. ** attached to it. Proceeding may generate a false "no such table: xxx"
  103847. ** error if pSelect reads from a CTE named "xxx". */
  103848. return 0;
  103849. }
  103850. if( sqlite3TriggerList(pParse, pDest) ){
  103851. return 0; /* tab1 must not have triggers */
  103852. }
  103853. #ifndef SQLITE_OMIT_VIRTUALTABLE
  103854. if( IsVirtual(pDest) ){
  103855. return 0; /* tab1 must not be a virtual table */
  103856. }
  103857. #endif
  103858. if( onError==OE_Default ){
  103859. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  103860. if( onError==OE_Default ) onError = OE_Abort;
  103861. }
  103862. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  103863. if( pSelect->pSrc->nSrc!=1 ){
  103864. return 0; /* FROM clause must have exactly one term */
  103865. }
  103866. if( pSelect->pSrc->a[0].pSelect ){
  103867. return 0; /* FROM clause cannot contain a subquery */
  103868. }
  103869. if( pSelect->pWhere ){
  103870. return 0; /* SELECT may not have a WHERE clause */
  103871. }
  103872. if( pSelect->pOrderBy ){
  103873. return 0; /* SELECT may not have an ORDER BY clause */
  103874. }
  103875. /* Do not need to test for a HAVING clause. If HAVING is present but
  103876. ** there is no ORDER BY, we will get an error. */
  103877. if( pSelect->pGroupBy ){
  103878. return 0; /* SELECT may not have a GROUP BY clause */
  103879. }
  103880. if( pSelect->pLimit ){
  103881. return 0; /* SELECT may not have a LIMIT clause */
  103882. }
  103883. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  103884. if( pSelect->pPrior ){
  103885. return 0; /* SELECT may not be a compound query */
  103886. }
  103887. if( pSelect->selFlags & SF_Distinct ){
  103888. return 0; /* SELECT may not be DISTINCT */
  103889. }
  103890. pEList = pSelect->pEList;
  103891. assert( pEList!=0 );
  103892. if( pEList->nExpr!=1 ){
  103893. return 0; /* The result set must have exactly one column */
  103894. }
  103895. assert( pEList->a[0].pExpr );
  103896. if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
  103897. return 0; /* The result set must be the special operator "*" */
  103898. }
  103899. /* At this point we have established that the statement is of the
  103900. ** correct syntactic form to participate in this optimization. Now
  103901. ** we have to check the semantics.
  103902. */
  103903. pItem = pSelect->pSrc->a;
  103904. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  103905. if( pSrc==0 ){
  103906. return 0; /* FROM clause does not contain a real table */
  103907. }
  103908. if( pSrc==pDest ){
  103909. return 0; /* tab1 and tab2 may not be the same table */
  103910. }
  103911. if( HasRowid(pDest)!=HasRowid(pSrc) ){
  103912. return 0; /* source and destination must both be WITHOUT ROWID or not */
  103913. }
  103914. #ifndef SQLITE_OMIT_VIRTUALTABLE
  103915. if( IsVirtual(pSrc) ){
  103916. return 0; /* tab2 must not be a virtual table */
  103917. }
  103918. #endif
  103919. if( pSrc->pSelect ){
  103920. return 0; /* tab2 may not be a view */
  103921. }
  103922. if( pDest->nCol!=pSrc->nCol ){
  103923. return 0; /* Number of columns must be the same in tab1 and tab2 */
  103924. }
  103925. if( pDest->iPKey!=pSrc->iPKey ){
  103926. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  103927. }
  103928. for(i=0; i<pDest->nCol; i++){
  103929. Column *pDestCol = &pDest->aCol[i];
  103930. Column *pSrcCol = &pSrc->aCol[i];
  103931. #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
  103932. if( (db->flags & SQLITE_Vacuum)==0
  103933. && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
  103934. ){
  103935. return 0; /* Neither table may have __hidden__ columns */
  103936. }
  103937. #endif
  103938. if( pDestCol->affinity!=pSrcCol->affinity ){
  103939. return 0; /* Affinity must be the same on all columns */
  103940. }
  103941. if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
  103942. return 0; /* Collating sequence must be the same on all columns */
  103943. }
  103944. if( pDestCol->notNull && !pSrcCol->notNull ){
  103945. return 0; /* tab2 must be NOT NULL if tab1 is */
  103946. }
  103947. /* Default values for second and subsequent columns need to match. */
  103948. if( i>0 ){
  103949. assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
  103950. assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
  103951. if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
  103952. || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
  103953. pSrcCol->pDflt->u.zToken)!=0)
  103954. ){
  103955. return 0; /* Default values must be the same for all columns */
  103956. }
  103957. }
  103958. }
  103959. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  103960. if( IsUniqueIndex(pDestIdx) ){
  103961. destHasUniqueIdx = 1;
  103962. }
  103963. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  103964. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  103965. }
  103966. if( pSrcIdx==0 ){
  103967. return 0; /* pDestIdx has no corresponding index in pSrc */
  103968. }
  103969. }
  103970. #ifndef SQLITE_OMIT_CHECK
  103971. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  103972. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  103973. }
  103974. #endif
  103975. #ifndef SQLITE_OMIT_FOREIGN_KEY
  103976. /* Disallow the transfer optimization if the destination table constains
  103977. ** any foreign key constraints. This is more restrictive than necessary.
  103978. ** But the main beneficiary of the transfer optimization is the VACUUM
  103979. ** command, and the VACUUM command disables foreign key constraints. So
  103980. ** the extra complication to make this rule less restrictive is probably
  103981. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  103982. */
  103983. if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  103984. return 0;
  103985. }
  103986. #endif
  103987. if( (db->flags & SQLITE_CountRows)!=0 ){
  103988. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  103989. }
  103990. /* If we get this far, it means that the xfer optimization is at
  103991. ** least a possibility, though it might only work if the destination
  103992. ** table (tab1) is initially empty.
  103993. */
  103994. #ifdef SQLITE_TEST
  103995. sqlite3_xferopt_count++;
  103996. #endif
  103997. iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
  103998. v = sqlite3GetVdbe(pParse);
  103999. sqlite3CodeVerifySchema(pParse, iDbSrc);
  104000. iSrc = pParse->nTab++;
  104001. iDest = pParse->nTab++;
  104002. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  104003. regData = sqlite3GetTempReg(pParse);
  104004. regRowid = sqlite3GetTempReg(pParse);
  104005. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  104006. assert( HasRowid(pDest) || destHasUniqueIdx );
  104007. if( (db->flags & SQLITE_Vacuum)==0 && (
  104008. (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  104009. || destHasUniqueIdx /* (2) */
  104010. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  104011. )){
  104012. /* In some circumstances, we are able to run the xfer optimization
  104013. ** only if the destination table is initially empty. Unless the
  104014. ** SQLITE_Vacuum flag is set, this block generates code to make
  104015. ** that determination. If SQLITE_Vacuum is set, then the destination
  104016. ** table is always empty.
  104017. **
  104018. ** Conditions under which the destination must be empty:
  104019. **
  104020. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  104021. ** (If the destination is not initially empty, the rowid fields
  104022. ** of index entries might need to change.)
  104023. **
  104024. ** (2) The destination has a unique index. (The xfer optimization
  104025. ** is unable to test uniqueness.)
  104026. **
  104027. ** (3) onError is something other than OE_Abort and OE_Rollback.
  104028. */
  104029. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
  104030. emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
  104031. sqlite3VdbeJumpHere(v, addr1);
  104032. }
  104033. if( HasRowid(pSrc) ){
  104034. u8 insFlags;
  104035. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  104036. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  104037. if( pDest->iPKey>=0 ){
  104038. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  104039. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  104040. VdbeCoverage(v);
  104041. sqlite3RowidConstraint(pParse, onError, pDest);
  104042. sqlite3VdbeJumpHere(v, addr2);
  104043. autoIncStep(pParse, regAutoinc, regRowid);
  104044. }else if( pDest->pIndex==0 ){
  104045. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  104046. }else{
  104047. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  104048. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  104049. }
  104050. sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
  104051. if( db->flags & SQLITE_Vacuum ){
  104052. sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
  104053. insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
  104054. OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
  104055. }else{
  104056. insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
  104057. }
  104058. sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
  104059. (char*)pDest, P4_TABLE);
  104060. sqlite3VdbeChangeP5(v, insFlags);
  104061. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
  104062. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  104063. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  104064. }else{
  104065. sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
  104066. sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
  104067. }
  104068. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  104069. u8 idxInsFlags = 0;
  104070. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  104071. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  104072. }
  104073. assert( pSrcIdx );
  104074. sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
  104075. sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
  104076. VdbeComment((v, "%s", pSrcIdx->zName));
  104077. sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
  104078. sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
  104079. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  104080. VdbeComment((v, "%s", pDestIdx->zName));
  104081. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  104082. sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
  104083. if( db->flags & SQLITE_Vacuum ){
  104084. /* This INSERT command is part of a VACUUM operation, which guarantees
  104085. ** that the destination table is empty. If all indexed columns use
  104086. ** collation sequence BINARY, then it can also be assumed that the
  104087. ** index will be populated by inserting keys in strictly sorted
  104088. ** order. In this case, instead of seeking within the b-tree as part
  104089. ** of every OP_IdxInsert opcode, an OP_Last is added before the
  104090. ** OP_IdxInsert to seek to the point within the b-tree where each key
  104091. ** should be inserted. This is faster.
  104092. **
  104093. ** If any of the indexed columns use a collation sequence other than
  104094. ** BINARY, this optimization is disabled. This is because the user
  104095. ** might change the definition of a collation sequence and then run
  104096. ** a VACUUM command. In that case keys may not be written in strictly
  104097. ** sorted order. */
  104098. for(i=0; i<pSrcIdx->nColumn; i++){
  104099. const char *zColl = pSrcIdx->azColl[i];
  104100. if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
  104101. }
  104102. if( i==pSrcIdx->nColumn ){
  104103. idxInsFlags = OPFLAG_USESEEKRESULT;
  104104. sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
  104105. }
  104106. }
  104107. if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
  104108. idxInsFlags |= OPFLAG_NCHANGE;
  104109. }
  104110. sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
  104111. sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
  104112. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
  104113. sqlite3VdbeJumpHere(v, addr1);
  104114. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  104115. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  104116. }
  104117. if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
  104118. sqlite3ReleaseTempReg(pParse, regRowid);
  104119. sqlite3ReleaseTempReg(pParse, regData);
  104120. if( emptyDestTest ){
  104121. sqlite3AutoincrementEnd(pParse);
  104122. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  104123. sqlite3VdbeJumpHere(v, emptyDestTest);
  104124. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  104125. return 0;
  104126. }else{
  104127. return 1;
  104128. }
  104129. }
  104130. #endif /* SQLITE_OMIT_XFER_OPT */
  104131. /************** End of insert.c **********************************************/
  104132. /************** Begin file legacy.c ******************************************/
  104133. /*
  104134. ** 2001 September 15
  104135. **
  104136. ** The author disclaims copyright to this source code. In place of
  104137. ** a legal notice, here is a blessing:
  104138. **
  104139. ** May you do good and not evil.
  104140. ** May you find forgiveness for yourself and forgive others.
  104141. ** May you share freely, never taking more than you give.
  104142. **
  104143. *************************************************************************
  104144. ** Main file for the SQLite library. The routines in this file
  104145. ** implement the programmer interface to the library. Routines in
  104146. ** other files are for internal use by SQLite and should not be
  104147. ** accessed by users of the library.
  104148. */
  104149. /* #include "sqliteInt.h" */
  104150. /*
  104151. ** Execute SQL code. Return one of the SQLITE_ success/failure
  104152. ** codes. Also write an error message into memory obtained from
  104153. ** malloc() and make *pzErrMsg point to that message.
  104154. **
  104155. ** If the SQL is a query, then for each row in the query result
  104156. ** the xCallback() function is called. pArg becomes the first
  104157. ** argument to xCallback(). If xCallback=NULL then no callback
  104158. ** is invoked, even for queries.
  104159. */
  104160. SQLITE_API int sqlite3_exec(
  104161. sqlite3 *db, /* The database on which the SQL executes */
  104162. const char *zSql, /* The SQL to be executed */
  104163. sqlite3_callback xCallback, /* Invoke this callback routine */
  104164. void *pArg, /* First argument to xCallback() */
  104165. char **pzErrMsg /* Write error messages here */
  104166. ){
  104167. int rc = SQLITE_OK; /* Return code */
  104168. const char *zLeftover; /* Tail of unprocessed SQL */
  104169. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  104170. char **azCols = 0; /* Names of result columns */
  104171. int callbackIsInit; /* True if callback data is initialized */
  104172. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  104173. if( zSql==0 ) zSql = "";
  104174. sqlite3_mutex_enter(db->mutex);
  104175. sqlite3Error(db, SQLITE_OK);
  104176. while( rc==SQLITE_OK && zSql[0] ){
  104177. int nCol;
  104178. char **azVals = 0;
  104179. pStmt = 0;
  104180. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  104181. assert( rc==SQLITE_OK || pStmt==0 );
  104182. if( rc!=SQLITE_OK ){
  104183. continue;
  104184. }
  104185. if( !pStmt ){
  104186. /* this happens for a comment or white-space */
  104187. zSql = zLeftover;
  104188. continue;
  104189. }
  104190. callbackIsInit = 0;
  104191. nCol = sqlite3_column_count(pStmt);
  104192. while( 1 ){
  104193. int i;
  104194. rc = sqlite3_step(pStmt);
  104195. /* Invoke the callback function if required */
  104196. if( xCallback && (SQLITE_ROW==rc ||
  104197. (SQLITE_DONE==rc && !callbackIsInit
  104198. && db->flags&SQLITE_NullCallback)) ){
  104199. if( !callbackIsInit ){
  104200. azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*));
  104201. if( azCols==0 ){
  104202. goto exec_out;
  104203. }
  104204. for(i=0; i<nCol; i++){
  104205. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  104206. /* sqlite3VdbeSetColName() installs column names as UTF8
  104207. ** strings so there is no way for sqlite3_column_name() to fail. */
  104208. assert( azCols[i]!=0 );
  104209. }
  104210. callbackIsInit = 1;
  104211. }
  104212. if( rc==SQLITE_ROW ){
  104213. azVals = &azCols[nCol];
  104214. for(i=0; i<nCol; i++){
  104215. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  104216. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  104217. sqlite3OomFault(db);
  104218. goto exec_out;
  104219. }
  104220. }
  104221. azVals[i] = 0;
  104222. }
  104223. if( xCallback(pArg, nCol, azVals, azCols) ){
  104224. /* EVIDENCE-OF: R-38229-40159 If the callback function to
  104225. ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
  104226. ** return SQLITE_ABORT. */
  104227. rc = SQLITE_ABORT;
  104228. sqlite3VdbeFinalize((Vdbe *)pStmt);
  104229. pStmt = 0;
  104230. sqlite3Error(db, SQLITE_ABORT);
  104231. goto exec_out;
  104232. }
  104233. }
  104234. if( rc!=SQLITE_ROW ){
  104235. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  104236. pStmt = 0;
  104237. zSql = zLeftover;
  104238. while( sqlite3Isspace(zSql[0]) ) zSql++;
  104239. break;
  104240. }
  104241. }
  104242. sqlite3DbFree(db, azCols);
  104243. azCols = 0;
  104244. }
  104245. exec_out:
  104246. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  104247. sqlite3DbFree(db, azCols);
  104248. rc = sqlite3ApiExit(db, rc);
  104249. if( rc!=SQLITE_OK && pzErrMsg ){
  104250. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  104251. *pzErrMsg = sqlite3Malloc(nErrMsg);
  104252. if( *pzErrMsg ){
  104253. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  104254. }else{
  104255. rc = SQLITE_NOMEM_BKPT;
  104256. sqlite3Error(db, SQLITE_NOMEM);
  104257. }
  104258. }else if( pzErrMsg ){
  104259. *pzErrMsg = 0;
  104260. }
  104261. assert( (rc&db->errMask)==rc );
  104262. sqlite3_mutex_leave(db->mutex);
  104263. return rc;
  104264. }
  104265. /************** End of legacy.c **********************************************/
  104266. /************** Begin file loadext.c *****************************************/
  104267. /*
  104268. ** 2006 June 7
  104269. **
  104270. ** The author disclaims copyright to this source code. In place of
  104271. ** a legal notice, here is a blessing:
  104272. **
  104273. ** May you do good and not evil.
  104274. ** May you find forgiveness for yourself and forgive others.
  104275. ** May you share freely, never taking more than you give.
  104276. **
  104277. *************************************************************************
  104278. ** This file contains code used to dynamically load extensions into
  104279. ** the SQLite library.
  104280. */
  104281. #ifndef SQLITE_CORE
  104282. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  104283. #endif
  104284. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  104285. /************** Begin file sqlite3ext.h **************************************/
  104286. /*
  104287. ** 2006 June 7
  104288. **
  104289. ** The author disclaims copyright to this source code. In place of
  104290. ** a legal notice, here is a blessing:
  104291. **
  104292. ** May you do good and not evil.
  104293. ** May you find forgiveness for yourself and forgive others.
  104294. ** May you share freely, never taking more than you give.
  104295. **
  104296. *************************************************************************
  104297. ** This header file defines the SQLite interface for use by
  104298. ** shared libraries that want to be imported as extensions into
  104299. ** an SQLite instance. Shared libraries that intend to be loaded
  104300. ** as extensions by SQLite should #include this file instead of
  104301. ** sqlite3.h.
  104302. */
  104303. #ifndef SQLITE3EXT_H
  104304. #define SQLITE3EXT_H
  104305. /* #include "sqlite3.h" */
  104306. /*
  104307. ** The following structure holds pointers to all of the SQLite API
  104308. ** routines.
  104309. **
  104310. ** WARNING: In order to maintain backwards compatibility, add new
  104311. ** interfaces to the end of this structure only. If you insert new
  104312. ** interfaces in the middle of this structure, then older different
  104313. ** versions of SQLite will not be able to load each other's shared
  104314. ** libraries!
  104315. */
  104316. struct sqlite3_api_routines {
  104317. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  104318. int (*aggregate_count)(sqlite3_context*);
  104319. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  104320. int (*bind_double)(sqlite3_stmt*,int,double);
  104321. int (*bind_int)(sqlite3_stmt*,int,int);
  104322. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  104323. int (*bind_null)(sqlite3_stmt*,int);
  104324. int (*bind_parameter_count)(sqlite3_stmt*);
  104325. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  104326. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  104327. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  104328. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  104329. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  104330. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  104331. int (*busy_timeout)(sqlite3*,int ms);
  104332. int (*changes)(sqlite3*);
  104333. int (*close)(sqlite3*);
  104334. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  104335. int eTextRep,const char*));
  104336. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  104337. int eTextRep,const void*));
  104338. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  104339. int (*column_bytes)(sqlite3_stmt*,int iCol);
  104340. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  104341. int (*column_count)(sqlite3_stmt*pStmt);
  104342. const char * (*column_database_name)(sqlite3_stmt*,int);
  104343. const void * (*column_database_name16)(sqlite3_stmt*,int);
  104344. const char * (*column_decltype)(sqlite3_stmt*,int i);
  104345. const void * (*column_decltype16)(sqlite3_stmt*,int);
  104346. double (*column_double)(sqlite3_stmt*,int iCol);
  104347. int (*column_int)(sqlite3_stmt*,int iCol);
  104348. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  104349. const char * (*column_name)(sqlite3_stmt*,int);
  104350. const void * (*column_name16)(sqlite3_stmt*,int);
  104351. const char * (*column_origin_name)(sqlite3_stmt*,int);
  104352. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  104353. const char * (*column_table_name)(sqlite3_stmt*,int);
  104354. const void * (*column_table_name16)(sqlite3_stmt*,int);
  104355. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  104356. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  104357. int (*column_type)(sqlite3_stmt*,int iCol);
  104358. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  104359. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  104360. int (*complete)(const char*sql);
  104361. int (*complete16)(const void*sql);
  104362. int (*create_collation)(sqlite3*,const char*,int,void*,
  104363. int(*)(void*,int,const void*,int,const void*));
  104364. int (*create_collation16)(sqlite3*,const void*,int,void*,
  104365. int(*)(void*,int,const void*,int,const void*));
  104366. int (*create_function)(sqlite3*,const char*,int,int,void*,
  104367. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  104368. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  104369. void (*xFinal)(sqlite3_context*));
  104370. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  104371. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  104372. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  104373. void (*xFinal)(sqlite3_context*));
  104374. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  104375. int (*data_count)(sqlite3_stmt*pStmt);
  104376. sqlite3 * (*db_handle)(sqlite3_stmt*);
  104377. int (*declare_vtab)(sqlite3*,const char*);
  104378. int (*enable_shared_cache)(int);
  104379. int (*errcode)(sqlite3*db);
  104380. const char * (*errmsg)(sqlite3*);
  104381. const void * (*errmsg16)(sqlite3*);
  104382. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  104383. int (*expired)(sqlite3_stmt*);
  104384. int (*finalize)(sqlite3_stmt*pStmt);
  104385. void (*free)(void*);
  104386. void (*free_table)(char**result);
  104387. int (*get_autocommit)(sqlite3*);
  104388. void * (*get_auxdata)(sqlite3_context*,int);
  104389. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  104390. int (*global_recover)(void);
  104391. void (*interruptx)(sqlite3*);
  104392. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  104393. const char * (*libversion)(void);
  104394. int (*libversion_number)(void);
  104395. void *(*malloc)(int);
  104396. char * (*mprintf)(const char*,...);
  104397. int (*open)(const char*,sqlite3**);
  104398. int (*open16)(const void*,sqlite3**);
  104399. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  104400. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  104401. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  104402. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  104403. void *(*realloc)(void*,int);
  104404. int (*reset)(sqlite3_stmt*pStmt);
  104405. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  104406. void (*result_double)(sqlite3_context*,double);
  104407. void (*result_error)(sqlite3_context*,const char*,int);
  104408. void (*result_error16)(sqlite3_context*,const void*,int);
  104409. void (*result_int)(sqlite3_context*,int);
  104410. void (*result_int64)(sqlite3_context*,sqlite_int64);
  104411. void (*result_null)(sqlite3_context*);
  104412. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  104413. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  104414. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  104415. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  104416. void (*result_value)(sqlite3_context*,sqlite3_value*);
  104417. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  104418. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  104419. const char*,const char*),void*);
  104420. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  104421. char * (*snprintf)(int,char*,const char*,...);
  104422. int (*step)(sqlite3_stmt*);
  104423. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  104424. char const**,char const**,int*,int*,int*);
  104425. void (*thread_cleanup)(void);
  104426. int (*total_changes)(sqlite3*);
  104427. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  104428. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  104429. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  104430. sqlite_int64),void*);
  104431. void * (*user_data)(sqlite3_context*);
  104432. const void * (*value_blob)(sqlite3_value*);
  104433. int (*value_bytes)(sqlite3_value*);
  104434. int (*value_bytes16)(sqlite3_value*);
  104435. double (*value_double)(sqlite3_value*);
  104436. int (*value_int)(sqlite3_value*);
  104437. sqlite_int64 (*value_int64)(sqlite3_value*);
  104438. int (*value_numeric_type)(sqlite3_value*);
  104439. const unsigned char * (*value_text)(sqlite3_value*);
  104440. const void * (*value_text16)(sqlite3_value*);
  104441. const void * (*value_text16be)(sqlite3_value*);
  104442. const void * (*value_text16le)(sqlite3_value*);
  104443. int (*value_type)(sqlite3_value*);
  104444. char *(*vmprintf)(const char*,va_list);
  104445. /* Added ??? */
  104446. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  104447. /* Added by 3.3.13 */
  104448. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  104449. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  104450. int (*clear_bindings)(sqlite3_stmt*);
  104451. /* Added by 3.4.1 */
  104452. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  104453. void (*xDestroy)(void *));
  104454. /* Added by 3.5.0 */
  104455. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  104456. int (*blob_bytes)(sqlite3_blob*);
  104457. int (*blob_close)(sqlite3_blob*);
  104458. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  104459. int,sqlite3_blob**);
  104460. int (*blob_read)(sqlite3_blob*,void*,int,int);
  104461. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  104462. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  104463. int(*)(void*,int,const void*,int,const void*),
  104464. void(*)(void*));
  104465. int (*file_control)(sqlite3*,const char*,int,void*);
  104466. sqlite3_int64 (*memory_highwater)(int);
  104467. sqlite3_int64 (*memory_used)(void);
  104468. sqlite3_mutex *(*mutex_alloc)(int);
  104469. void (*mutex_enter)(sqlite3_mutex*);
  104470. void (*mutex_free)(sqlite3_mutex*);
  104471. void (*mutex_leave)(sqlite3_mutex*);
  104472. int (*mutex_try)(sqlite3_mutex*);
  104473. int (*open_v2)(const char*,sqlite3**,int,const char*);
  104474. int (*release_memory)(int);
  104475. void (*result_error_nomem)(sqlite3_context*);
  104476. void (*result_error_toobig)(sqlite3_context*);
  104477. int (*sleep)(int);
  104478. void (*soft_heap_limit)(int);
  104479. sqlite3_vfs *(*vfs_find)(const char*);
  104480. int (*vfs_register)(sqlite3_vfs*,int);
  104481. int (*vfs_unregister)(sqlite3_vfs*);
  104482. int (*xthreadsafe)(void);
  104483. void (*result_zeroblob)(sqlite3_context*,int);
  104484. void (*result_error_code)(sqlite3_context*,int);
  104485. int (*test_control)(int, ...);
  104486. void (*randomness)(int,void*);
  104487. sqlite3 *(*context_db_handle)(sqlite3_context*);
  104488. int (*extended_result_codes)(sqlite3*,int);
  104489. int (*limit)(sqlite3*,int,int);
  104490. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  104491. const char *(*sql)(sqlite3_stmt*);
  104492. int (*status)(int,int*,int*,int);
  104493. int (*backup_finish)(sqlite3_backup*);
  104494. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  104495. int (*backup_pagecount)(sqlite3_backup*);
  104496. int (*backup_remaining)(sqlite3_backup*);
  104497. int (*backup_step)(sqlite3_backup*,int);
  104498. const char *(*compileoption_get)(int);
  104499. int (*compileoption_used)(const char*);
  104500. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  104501. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  104502. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  104503. void (*xFinal)(sqlite3_context*),
  104504. void(*xDestroy)(void*));
  104505. int (*db_config)(sqlite3*,int,...);
  104506. sqlite3_mutex *(*db_mutex)(sqlite3*);
  104507. int (*db_status)(sqlite3*,int,int*,int*,int);
  104508. int (*extended_errcode)(sqlite3*);
  104509. void (*log)(int,const char*,...);
  104510. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  104511. const char *(*sourceid)(void);
  104512. int (*stmt_status)(sqlite3_stmt*,int,int);
  104513. int (*strnicmp)(const char*,const char*,int);
  104514. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  104515. int (*wal_autocheckpoint)(sqlite3*,int);
  104516. int (*wal_checkpoint)(sqlite3*,const char*);
  104517. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  104518. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  104519. int (*vtab_config)(sqlite3*,int op,...);
  104520. int (*vtab_on_conflict)(sqlite3*);
  104521. /* Version 3.7.16 and later */
  104522. int (*close_v2)(sqlite3*);
  104523. const char *(*db_filename)(sqlite3*,const char*);
  104524. int (*db_readonly)(sqlite3*,const char*);
  104525. int (*db_release_memory)(sqlite3*);
  104526. const char *(*errstr)(int);
  104527. int (*stmt_busy)(sqlite3_stmt*);
  104528. int (*stmt_readonly)(sqlite3_stmt*);
  104529. int (*stricmp)(const char*,const char*);
  104530. int (*uri_boolean)(const char*,const char*,int);
  104531. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  104532. const char *(*uri_parameter)(const char*,const char*);
  104533. char *(*vsnprintf)(int,char*,const char*,va_list);
  104534. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  104535. /* Version 3.8.7 and later */
  104536. int (*auto_extension)(void(*)(void));
  104537. int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
  104538. void(*)(void*));
  104539. int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
  104540. void(*)(void*),unsigned char);
  104541. int (*cancel_auto_extension)(void(*)(void));
  104542. int (*load_extension)(sqlite3*,const char*,const char*,char**);
  104543. void *(*malloc64)(sqlite3_uint64);
  104544. sqlite3_uint64 (*msize)(void*);
  104545. void *(*realloc64)(void*,sqlite3_uint64);
  104546. void (*reset_auto_extension)(void);
  104547. void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
  104548. void(*)(void*));
  104549. void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
  104550. void(*)(void*), unsigned char);
  104551. int (*strglob)(const char*,const char*);
  104552. /* Version 3.8.11 and later */
  104553. sqlite3_value *(*value_dup)(const sqlite3_value*);
  104554. void (*value_free)(sqlite3_value*);
  104555. int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
  104556. int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
  104557. /* Version 3.9.0 and later */
  104558. unsigned int (*value_subtype)(sqlite3_value*);
  104559. void (*result_subtype)(sqlite3_context*,unsigned int);
  104560. /* Version 3.10.0 and later */
  104561. int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
  104562. int (*strlike)(const char*,const char*,unsigned int);
  104563. int (*db_cacheflush)(sqlite3*);
  104564. /* Version 3.12.0 and later */
  104565. int (*system_errno)(sqlite3*);
  104566. /* Version 3.14.0 and later */
  104567. int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
  104568. char *(*expanded_sql)(sqlite3_stmt*);
  104569. /* Version 3.18.0 and later */
  104570. void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
  104571. };
  104572. /*
  104573. ** This is the function signature used for all extension entry points. It
  104574. ** is also defined in the file "loadext.c".
  104575. */
  104576. typedef int (*sqlite3_loadext_entry)(
  104577. sqlite3 *db, /* Handle to the database. */
  104578. char **pzErrMsg, /* Used to set error string on failure. */
  104579. const sqlite3_api_routines *pThunk /* Extension API function pointers. */
  104580. );
  104581. /*
  104582. ** The following macros redefine the API routines so that they are
  104583. ** redirected through the global sqlite3_api structure.
  104584. **
  104585. ** This header file is also used by the loadext.c source file
  104586. ** (part of the main SQLite library - not an extension) so that
  104587. ** it can get access to the sqlite3_api_routines structure
  104588. ** definition. But the main library does not want to redefine
  104589. ** the API. So the redefinition macros are only valid if the
  104590. ** SQLITE_CORE macros is undefined.
  104591. */
  104592. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  104593. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  104594. #ifndef SQLITE_OMIT_DEPRECATED
  104595. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  104596. #endif
  104597. #define sqlite3_bind_blob sqlite3_api->bind_blob
  104598. #define sqlite3_bind_double sqlite3_api->bind_double
  104599. #define sqlite3_bind_int sqlite3_api->bind_int
  104600. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  104601. #define sqlite3_bind_null sqlite3_api->bind_null
  104602. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  104603. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  104604. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  104605. #define sqlite3_bind_text sqlite3_api->bind_text
  104606. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  104607. #define sqlite3_bind_value sqlite3_api->bind_value
  104608. #define sqlite3_busy_handler sqlite3_api->busy_handler
  104609. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  104610. #define sqlite3_changes sqlite3_api->changes
  104611. #define sqlite3_close sqlite3_api->close
  104612. #define sqlite3_collation_needed sqlite3_api->collation_needed
  104613. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  104614. #define sqlite3_column_blob sqlite3_api->column_blob
  104615. #define sqlite3_column_bytes sqlite3_api->column_bytes
  104616. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  104617. #define sqlite3_column_count sqlite3_api->column_count
  104618. #define sqlite3_column_database_name sqlite3_api->column_database_name
  104619. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  104620. #define sqlite3_column_decltype sqlite3_api->column_decltype
  104621. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  104622. #define sqlite3_column_double sqlite3_api->column_double
  104623. #define sqlite3_column_int sqlite3_api->column_int
  104624. #define sqlite3_column_int64 sqlite3_api->column_int64
  104625. #define sqlite3_column_name sqlite3_api->column_name
  104626. #define sqlite3_column_name16 sqlite3_api->column_name16
  104627. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  104628. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  104629. #define sqlite3_column_table_name sqlite3_api->column_table_name
  104630. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  104631. #define sqlite3_column_text sqlite3_api->column_text
  104632. #define sqlite3_column_text16 sqlite3_api->column_text16
  104633. #define sqlite3_column_type sqlite3_api->column_type
  104634. #define sqlite3_column_value sqlite3_api->column_value
  104635. #define sqlite3_commit_hook sqlite3_api->commit_hook
  104636. #define sqlite3_complete sqlite3_api->complete
  104637. #define sqlite3_complete16 sqlite3_api->complete16
  104638. #define sqlite3_create_collation sqlite3_api->create_collation
  104639. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  104640. #define sqlite3_create_function sqlite3_api->create_function
  104641. #define sqlite3_create_function16 sqlite3_api->create_function16
  104642. #define sqlite3_create_module sqlite3_api->create_module
  104643. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  104644. #define sqlite3_data_count sqlite3_api->data_count
  104645. #define sqlite3_db_handle sqlite3_api->db_handle
  104646. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  104647. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  104648. #define sqlite3_errcode sqlite3_api->errcode
  104649. #define sqlite3_errmsg sqlite3_api->errmsg
  104650. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  104651. #define sqlite3_exec sqlite3_api->exec
  104652. #ifndef SQLITE_OMIT_DEPRECATED
  104653. #define sqlite3_expired sqlite3_api->expired
  104654. #endif
  104655. #define sqlite3_finalize sqlite3_api->finalize
  104656. #define sqlite3_free sqlite3_api->free
  104657. #define sqlite3_free_table sqlite3_api->free_table
  104658. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  104659. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  104660. #define sqlite3_get_table sqlite3_api->get_table
  104661. #ifndef SQLITE_OMIT_DEPRECATED
  104662. #define sqlite3_global_recover sqlite3_api->global_recover
  104663. #endif
  104664. #define sqlite3_interrupt sqlite3_api->interruptx
  104665. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  104666. #define sqlite3_libversion sqlite3_api->libversion
  104667. #define sqlite3_libversion_number sqlite3_api->libversion_number
  104668. #define sqlite3_malloc sqlite3_api->malloc
  104669. #define sqlite3_mprintf sqlite3_api->mprintf
  104670. #define sqlite3_open sqlite3_api->open
  104671. #define sqlite3_open16 sqlite3_api->open16
  104672. #define sqlite3_prepare sqlite3_api->prepare
  104673. #define sqlite3_prepare16 sqlite3_api->prepare16
  104674. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  104675. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  104676. #define sqlite3_profile sqlite3_api->profile
  104677. #define sqlite3_progress_handler sqlite3_api->progress_handler
  104678. #define sqlite3_realloc sqlite3_api->realloc
  104679. #define sqlite3_reset sqlite3_api->reset
  104680. #define sqlite3_result_blob sqlite3_api->result_blob
  104681. #define sqlite3_result_double sqlite3_api->result_double
  104682. #define sqlite3_result_error sqlite3_api->result_error
  104683. #define sqlite3_result_error16 sqlite3_api->result_error16
  104684. #define sqlite3_result_int sqlite3_api->result_int
  104685. #define sqlite3_result_int64 sqlite3_api->result_int64
  104686. #define sqlite3_result_null sqlite3_api->result_null
  104687. #define sqlite3_result_text sqlite3_api->result_text
  104688. #define sqlite3_result_text16 sqlite3_api->result_text16
  104689. #define sqlite3_result_text16be sqlite3_api->result_text16be
  104690. #define sqlite3_result_text16le sqlite3_api->result_text16le
  104691. #define sqlite3_result_value sqlite3_api->result_value
  104692. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  104693. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  104694. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  104695. #define sqlite3_snprintf sqlite3_api->snprintf
  104696. #define sqlite3_step sqlite3_api->step
  104697. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  104698. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  104699. #define sqlite3_total_changes sqlite3_api->total_changes
  104700. #define sqlite3_trace sqlite3_api->trace
  104701. #ifndef SQLITE_OMIT_DEPRECATED
  104702. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  104703. #endif
  104704. #define sqlite3_update_hook sqlite3_api->update_hook
  104705. #define sqlite3_user_data sqlite3_api->user_data
  104706. #define sqlite3_value_blob sqlite3_api->value_blob
  104707. #define sqlite3_value_bytes sqlite3_api->value_bytes
  104708. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  104709. #define sqlite3_value_double sqlite3_api->value_double
  104710. #define sqlite3_value_int sqlite3_api->value_int
  104711. #define sqlite3_value_int64 sqlite3_api->value_int64
  104712. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  104713. #define sqlite3_value_text sqlite3_api->value_text
  104714. #define sqlite3_value_text16 sqlite3_api->value_text16
  104715. #define sqlite3_value_text16be sqlite3_api->value_text16be
  104716. #define sqlite3_value_text16le sqlite3_api->value_text16le
  104717. #define sqlite3_value_type sqlite3_api->value_type
  104718. #define sqlite3_vmprintf sqlite3_api->vmprintf
  104719. #define sqlite3_vsnprintf sqlite3_api->vsnprintf
  104720. #define sqlite3_overload_function sqlite3_api->overload_function
  104721. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  104722. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  104723. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  104724. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  104725. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  104726. #define sqlite3_blob_close sqlite3_api->blob_close
  104727. #define sqlite3_blob_open sqlite3_api->blob_open
  104728. #define sqlite3_blob_read sqlite3_api->blob_read
  104729. #define sqlite3_blob_write sqlite3_api->blob_write
  104730. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  104731. #define sqlite3_file_control sqlite3_api->file_control
  104732. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  104733. #define sqlite3_memory_used sqlite3_api->memory_used
  104734. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  104735. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  104736. #define sqlite3_mutex_free sqlite3_api->mutex_free
  104737. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  104738. #define sqlite3_mutex_try sqlite3_api->mutex_try
  104739. #define sqlite3_open_v2 sqlite3_api->open_v2
  104740. #define sqlite3_release_memory sqlite3_api->release_memory
  104741. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  104742. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  104743. #define sqlite3_sleep sqlite3_api->sleep
  104744. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  104745. #define sqlite3_vfs_find sqlite3_api->vfs_find
  104746. #define sqlite3_vfs_register sqlite3_api->vfs_register
  104747. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  104748. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  104749. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  104750. #define sqlite3_result_error_code sqlite3_api->result_error_code
  104751. #define sqlite3_test_control sqlite3_api->test_control
  104752. #define sqlite3_randomness sqlite3_api->randomness
  104753. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  104754. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  104755. #define sqlite3_limit sqlite3_api->limit
  104756. #define sqlite3_next_stmt sqlite3_api->next_stmt
  104757. #define sqlite3_sql sqlite3_api->sql
  104758. #define sqlite3_status sqlite3_api->status
  104759. #define sqlite3_backup_finish sqlite3_api->backup_finish
  104760. #define sqlite3_backup_init sqlite3_api->backup_init
  104761. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  104762. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  104763. #define sqlite3_backup_step sqlite3_api->backup_step
  104764. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  104765. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  104766. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  104767. #define sqlite3_db_config sqlite3_api->db_config
  104768. #define sqlite3_db_mutex sqlite3_api->db_mutex
  104769. #define sqlite3_db_status sqlite3_api->db_status
  104770. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  104771. #define sqlite3_log sqlite3_api->log
  104772. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  104773. #define sqlite3_sourceid sqlite3_api->sourceid
  104774. #define sqlite3_stmt_status sqlite3_api->stmt_status
  104775. #define sqlite3_strnicmp sqlite3_api->strnicmp
  104776. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  104777. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  104778. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  104779. #define sqlite3_wal_hook sqlite3_api->wal_hook
  104780. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  104781. #define sqlite3_vtab_config sqlite3_api->vtab_config
  104782. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  104783. /* Version 3.7.16 and later */
  104784. #define sqlite3_close_v2 sqlite3_api->close_v2
  104785. #define sqlite3_db_filename sqlite3_api->db_filename
  104786. #define sqlite3_db_readonly sqlite3_api->db_readonly
  104787. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  104788. #define sqlite3_errstr sqlite3_api->errstr
  104789. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  104790. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  104791. #define sqlite3_stricmp sqlite3_api->stricmp
  104792. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  104793. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  104794. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  104795. #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
  104796. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  104797. /* Version 3.8.7 and later */
  104798. #define sqlite3_auto_extension sqlite3_api->auto_extension
  104799. #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
  104800. #define sqlite3_bind_text64 sqlite3_api->bind_text64
  104801. #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
  104802. #define sqlite3_load_extension sqlite3_api->load_extension
  104803. #define sqlite3_malloc64 sqlite3_api->malloc64
  104804. #define sqlite3_msize sqlite3_api->msize
  104805. #define sqlite3_realloc64 sqlite3_api->realloc64
  104806. #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
  104807. #define sqlite3_result_blob64 sqlite3_api->result_blob64
  104808. #define sqlite3_result_text64 sqlite3_api->result_text64
  104809. #define sqlite3_strglob sqlite3_api->strglob
  104810. /* Version 3.8.11 and later */
  104811. #define sqlite3_value_dup sqlite3_api->value_dup
  104812. #define sqlite3_value_free sqlite3_api->value_free
  104813. #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
  104814. #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
  104815. /* Version 3.9.0 and later */
  104816. #define sqlite3_value_subtype sqlite3_api->value_subtype
  104817. #define sqlite3_result_subtype sqlite3_api->result_subtype
  104818. /* Version 3.10.0 and later */
  104819. #define sqlite3_status64 sqlite3_api->status64
  104820. #define sqlite3_strlike sqlite3_api->strlike
  104821. #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
  104822. /* Version 3.12.0 and later */
  104823. #define sqlite3_system_errno sqlite3_api->system_errno
  104824. /* Version 3.14.0 and later */
  104825. #define sqlite3_trace_v2 sqlite3_api->trace_v2
  104826. #define sqlite3_expanded_sql sqlite3_api->expanded_sql
  104827. /* Version 3.18.0 and later */
  104828. #define sqlite3_set_last_insert_rowid sqlite3_api->set_last_insert_rowid
  104829. #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  104830. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  104831. /* This case when the file really is being compiled as a loadable
  104832. ** extension */
  104833. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  104834. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  104835. # define SQLITE_EXTENSION_INIT3 \
  104836. extern const sqlite3_api_routines *sqlite3_api;
  104837. #else
  104838. /* This case when the file is being statically linked into the
  104839. ** application */
  104840. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  104841. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  104842. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  104843. #endif
  104844. #endif /* SQLITE3EXT_H */
  104845. /************** End of sqlite3ext.h ******************************************/
  104846. /************** Continuing where we left off in loadext.c ********************/
  104847. /* #include "sqliteInt.h" */
  104848. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  104849. /*
  104850. ** Some API routines are omitted when various features are
  104851. ** excluded from a build of SQLite. Substitute a NULL pointer
  104852. ** for any missing APIs.
  104853. */
  104854. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  104855. # define sqlite3_column_database_name 0
  104856. # define sqlite3_column_database_name16 0
  104857. # define sqlite3_column_table_name 0
  104858. # define sqlite3_column_table_name16 0
  104859. # define sqlite3_column_origin_name 0
  104860. # define sqlite3_column_origin_name16 0
  104861. #endif
  104862. #ifdef SQLITE_OMIT_AUTHORIZATION
  104863. # define sqlite3_set_authorizer 0
  104864. #endif
  104865. #ifdef SQLITE_OMIT_UTF16
  104866. # define sqlite3_bind_text16 0
  104867. # define sqlite3_collation_needed16 0
  104868. # define sqlite3_column_decltype16 0
  104869. # define sqlite3_column_name16 0
  104870. # define sqlite3_column_text16 0
  104871. # define sqlite3_complete16 0
  104872. # define sqlite3_create_collation16 0
  104873. # define sqlite3_create_function16 0
  104874. # define sqlite3_errmsg16 0
  104875. # define sqlite3_open16 0
  104876. # define sqlite3_prepare16 0
  104877. # define sqlite3_prepare16_v2 0
  104878. # define sqlite3_result_error16 0
  104879. # define sqlite3_result_text16 0
  104880. # define sqlite3_result_text16be 0
  104881. # define sqlite3_result_text16le 0
  104882. # define sqlite3_value_text16 0
  104883. # define sqlite3_value_text16be 0
  104884. # define sqlite3_value_text16le 0
  104885. # define sqlite3_column_database_name16 0
  104886. # define sqlite3_column_table_name16 0
  104887. # define sqlite3_column_origin_name16 0
  104888. #endif
  104889. #ifdef SQLITE_OMIT_COMPLETE
  104890. # define sqlite3_complete 0
  104891. # define sqlite3_complete16 0
  104892. #endif
  104893. #ifdef SQLITE_OMIT_DECLTYPE
  104894. # define sqlite3_column_decltype16 0
  104895. # define sqlite3_column_decltype 0
  104896. #endif
  104897. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  104898. # define sqlite3_progress_handler 0
  104899. #endif
  104900. #ifdef SQLITE_OMIT_VIRTUALTABLE
  104901. # define sqlite3_create_module 0
  104902. # define sqlite3_create_module_v2 0
  104903. # define sqlite3_declare_vtab 0
  104904. # define sqlite3_vtab_config 0
  104905. # define sqlite3_vtab_on_conflict 0
  104906. #endif
  104907. #ifdef SQLITE_OMIT_SHARED_CACHE
  104908. # define sqlite3_enable_shared_cache 0
  104909. #endif
  104910. #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
  104911. # define sqlite3_profile 0
  104912. # define sqlite3_trace 0
  104913. #endif
  104914. #ifdef SQLITE_OMIT_GET_TABLE
  104915. # define sqlite3_free_table 0
  104916. # define sqlite3_get_table 0
  104917. #endif
  104918. #ifdef SQLITE_OMIT_INCRBLOB
  104919. #define sqlite3_bind_zeroblob 0
  104920. #define sqlite3_blob_bytes 0
  104921. #define sqlite3_blob_close 0
  104922. #define sqlite3_blob_open 0
  104923. #define sqlite3_blob_read 0
  104924. #define sqlite3_blob_write 0
  104925. #define sqlite3_blob_reopen 0
  104926. #endif
  104927. #if defined(SQLITE_OMIT_TRACE)
  104928. # define sqlite3_trace_v2 0
  104929. #endif
  104930. /*
  104931. ** The following structure contains pointers to all SQLite API routines.
  104932. ** A pointer to this structure is passed into extensions when they are
  104933. ** loaded so that the extension can make calls back into the SQLite
  104934. ** library.
  104935. **
  104936. ** When adding new APIs, add them to the bottom of this structure
  104937. ** in order to preserve backwards compatibility.
  104938. **
  104939. ** Extensions that use newer APIs should first call the
  104940. ** sqlite3_libversion_number() to make sure that the API they
  104941. ** intend to use is supported by the library. Extensions should
  104942. ** also check to make sure that the pointer to the function is
  104943. ** not NULL before calling it.
  104944. */
  104945. static const sqlite3_api_routines sqlite3Apis = {
  104946. sqlite3_aggregate_context,
  104947. #ifndef SQLITE_OMIT_DEPRECATED
  104948. sqlite3_aggregate_count,
  104949. #else
  104950. 0,
  104951. #endif
  104952. sqlite3_bind_blob,
  104953. sqlite3_bind_double,
  104954. sqlite3_bind_int,
  104955. sqlite3_bind_int64,
  104956. sqlite3_bind_null,
  104957. sqlite3_bind_parameter_count,
  104958. sqlite3_bind_parameter_index,
  104959. sqlite3_bind_parameter_name,
  104960. sqlite3_bind_text,
  104961. sqlite3_bind_text16,
  104962. sqlite3_bind_value,
  104963. sqlite3_busy_handler,
  104964. sqlite3_busy_timeout,
  104965. sqlite3_changes,
  104966. sqlite3_close,
  104967. sqlite3_collation_needed,
  104968. sqlite3_collation_needed16,
  104969. sqlite3_column_blob,
  104970. sqlite3_column_bytes,
  104971. sqlite3_column_bytes16,
  104972. sqlite3_column_count,
  104973. sqlite3_column_database_name,
  104974. sqlite3_column_database_name16,
  104975. sqlite3_column_decltype,
  104976. sqlite3_column_decltype16,
  104977. sqlite3_column_double,
  104978. sqlite3_column_int,
  104979. sqlite3_column_int64,
  104980. sqlite3_column_name,
  104981. sqlite3_column_name16,
  104982. sqlite3_column_origin_name,
  104983. sqlite3_column_origin_name16,
  104984. sqlite3_column_table_name,
  104985. sqlite3_column_table_name16,
  104986. sqlite3_column_text,
  104987. sqlite3_column_text16,
  104988. sqlite3_column_type,
  104989. sqlite3_column_value,
  104990. sqlite3_commit_hook,
  104991. sqlite3_complete,
  104992. sqlite3_complete16,
  104993. sqlite3_create_collation,
  104994. sqlite3_create_collation16,
  104995. sqlite3_create_function,
  104996. sqlite3_create_function16,
  104997. sqlite3_create_module,
  104998. sqlite3_data_count,
  104999. sqlite3_db_handle,
  105000. sqlite3_declare_vtab,
  105001. sqlite3_enable_shared_cache,
  105002. sqlite3_errcode,
  105003. sqlite3_errmsg,
  105004. sqlite3_errmsg16,
  105005. sqlite3_exec,
  105006. #ifndef SQLITE_OMIT_DEPRECATED
  105007. sqlite3_expired,
  105008. #else
  105009. 0,
  105010. #endif
  105011. sqlite3_finalize,
  105012. sqlite3_free,
  105013. sqlite3_free_table,
  105014. sqlite3_get_autocommit,
  105015. sqlite3_get_auxdata,
  105016. sqlite3_get_table,
  105017. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  105018. sqlite3_interrupt,
  105019. sqlite3_last_insert_rowid,
  105020. sqlite3_libversion,
  105021. sqlite3_libversion_number,
  105022. sqlite3_malloc,
  105023. sqlite3_mprintf,
  105024. sqlite3_open,
  105025. sqlite3_open16,
  105026. sqlite3_prepare,
  105027. sqlite3_prepare16,
  105028. sqlite3_profile,
  105029. sqlite3_progress_handler,
  105030. sqlite3_realloc,
  105031. sqlite3_reset,
  105032. sqlite3_result_blob,
  105033. sqlite3_result_double,
  105034. sqlite3_result_error,
  105035. sqlite3_result_error16,
  105036. sqlite3_result_int,
  105037. sqlite3_result_int64,
  105038. sqlite3_result_null,
  105039. sqlite3_result_text,
  105040. sqlite3_result_text16,
  105041. sqlite3_result_text16be,
  105042. sqlite3_result_text16le,
  105043. sqlite3_result_value,
  105044. sqlite3_rollback_hook,
  105045. sqlite3_set_authorizer,
  105046. sqlite3_set_auxdata,
  105047. sqlite3_snprintf,
  105048. sqlite3_step,
  105049. sqlite3_table_column_metadata,
  105050. #ifndef SQLITE_OMIT_DEPRECATED
  105051. sqlite3_thread_cleanup,
  105052. #else
  105053. 0,
  105054. #endif
  105055. sqlite3_total_changes,
  105056. sqlite3_trace,
  105057. #ifndef SQLITE_OMIT_DEPRECATED
  105058. sqlite3_transfer_bindings,
  105059. #else
  105060. 0,
  105061. #endif
  105062. sqlite3_update_hook,
  105063. sqlite3_user_data,
  105064. sqlite3_value_blob,
  105065. sqlite3_value_bytes,
  105066. sqlite3_value_bytes16,
  105067. sqlite3_value_double,
  105068. sqlite3_value_int,
  105069. sqlite3_value_int64,
  105070. sqlite3_value_numeric_type,
  105071. sqlite3_value_text,
  105072. sqlite3_value_text16,
  105073. sqlite3_value_text16be,
  105074. sqlite3_value_text16le,
  105075. sqlite3_value_type,
  105076. sqlite3_vmprintf,
  105077. /*
  105078. ** The original API set ends here. All extensions can call any
  105079. ** of the APIs above provided that the pointer is not NULL. But
  105080. ** before calling APIs that follow, extension should check the
  105081. ** sqlite3_libversion_number() to make sure they are dealing with
  105082. ** a library that is new enough to support that API.
  105083. *************************************************************************
  105084. */
  105085. sqlite3_overload_function,
  105086. /*
  105087. ** Added after 3.3.13
  105088. */
  105089. sqlite3_prepare_v2,
  105090. sqlite3_prepare16_v2,
  105091. sqlite3_clear_bindings,
  105092. /*
  105093. ** Added for 3.4.1
  105094. */
  105095. sqlite3_create_module_v2,
  105096. /*
  105097. ** Added for 3.5.0
  105098. */
  105099. sqlite3_bind_zeroblob,
  105100. sqlite3_blob_bytes,
  105101. sqlite3_blob_close,
  105102. sqlite3_blob_open,
  105103. sqlite3_blob_read,
  105104. sqlite3_blob_write,
  105105. sqlite3_create_collation_v2,
  105106. sqlite3_file_control,
  105107. sqlite3_memory_highwater,
  105108. sqlite3_memory_used,
  105109. #ifdef SQLITE_MUTEX_OMIT
  105110. 0,
  105111. 0,
  105112. 0,
  105113. 0,
  105114. 0,
  105115. #else
  105116. sqlite3_mutex_alloc,
  105117. sqlite3_mutex_enter,
  105118. sqlite3_mutex_free,
  105119. sqlite3_mutex_leave,
  105120. sqlite3_mutex_try,
  105121. #endif
  105122. sqlite3_open_v2,
  105123. sqlite3_release_memory,
  105124. sqlite3_result_error_nomem,
  105125. sqlite3_result_error_toobig,
  105126. sqlite3_sleep,
  105127. sqlite3_soft_heap_limit,
  105128. sqlite3_vfs_find,
  105129. sqlite3_vfs_register,
  105130. sqlite3_vfs_unregister,
  105131. /*
  105132. ** Added for 3.5.8
  105133. */
  105134. sqlite3_threadsafe,
  105135. sqlite3_result_zeroblob,
  105136. sqlite3_result_error_code,
  105137. sqlite3_test_control,
  105138. sqlite3_randomness,
  105139. sqlite3_context_db_handle,
  105140. /*
  105141. ** Added for 3.6.0
  105142. */
  105143. sqlite3_extended_result_codes,
  105144. sqlite3_limit,
  105145. sqlite3_next_stmt,
  105146. sqlite3_sql,
  105147. sqlite3_status,
  105148. /*
  105149. ** Added for 3.7.4
  105150. */
  105151. sqlite3_backup_finish,
  105152. sqlite3_backup_init,
  105153. sqlite3_backup_pagecount,
  105154. sqlite3_backup_remaining,
  105155. sqlite3_backup_step,
  105156. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  105157. sqlite3_compileoption_get,
  105158. sqlite3_compileoption_used,
  105159. #else
  105160. 0,
  105161. 0,
  105162. #endif
  105163. sqlite3_create_function_v2,
  105164. sqlite3_db_config,
  105165. sqlite3_db_mutex,
  105166. sqlite3_db_status,
  105167. sqlite3_extended_errcode,
  105168. sqlite3_log,
  105169. sqlite3_soft_heap_limit64,
  105170. sqlite3_sourceid,
  105171. sqlite3_stmt_status,
  105172. sqlite3_strnicmp,
  105173. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  105174. sqlite3_unlock_notify,
  105175. #else
  105176. 0,
  105177. #endif
  105178. #ifndef SQLITE_OMIT_WAL
  105179. sqlite3_wal_autocheckpoint,
  105180. sqlite3_wal_checkpoint,
  105181. sqlite3_wal_hook,
  105182. #else
  105183. 0,
  105184. 0,
  105185. 0,
  105186. #endif
  105187. sqlite3_blob_reopen,
  105188. sqlite3_vtab_config,
  105189. sqlite3_vtab_on_conflict,
  105190. sqlite3_close_v2,
  105191. sqlite3_db_filename,
  105192. sqlite3_db_readonly,
  105193. sqlite3_db_release_memory,
  105194. sqlite3_errstr,
  105195. sqlite3_stmt_busy,
  105196. sqlite3_stmt_readonly,
  105197. sqlite3_stricmp,
  105198. sqlite3_uri_boolean,
  105199. sqlite3_uri_int64,
  105200. sqlite3_uri_parameter,
  105201. sqlite3_vsnprintf,
  105202. sqlite3_wal_checkpoint_v2,
  105203. /* Version 3.8.7 and later */
  105204. sqlite3_auto_extension,
  105205. sqlite3_bind_blob64,
  105206. sqlite3_bind_text64,
  105207. sqlite3_cancel_auto_extension,
  105208. sqlite3_load_extension,
  105209. sqlite3_malloc64,
  105210. sqlite3_msize,
  105211. sqlite3_realloc64,
  105212. sqlite3_reset_auto_extension,
  105213. sqlite3_result_blob64,
  105214. sqlite3_result_text64,
  105215. sqlite3_strglob,
  105216. /* Version 3.8.11 and later */
  105217. (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
  105218. sqlite3_value_free,
  105219. sqlite3_result_zeroblob64,
  105220. sqlite3_bind_zeroblob64,
  105221. /* Version 3.9.0 and later */
  105222. sqlite3_value_subtype,
  105223. sqlite3_result_subtype,
  105224. /* Version 3.10.0 and later */
  105225. sqlite3_status64,
  105226. sqlite3_strlike,
  105227. sqlite3_db_cacheflush,
  105228. /* Version 3.12.0 and later */
  105229. sqlite3_system_errno,
  105230. /* Version 3.14.0 and later */
  105231. sqlite3_trace_v2,
  105232. sqlite3_expanded_sql,
  105233. /* Version 3.18.0 and later */
  105234. sqlite3_set_last_insert_rowid
  105235. };
  105236. /*
  105237. ** Attempt to load an SQLite extension library contained in the file
  105238. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  105239. ** default entry point name (sqlite3_extension_init) is used. Use
  105240. ** of the default name is recommended.
  105241. **
  105242. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  105243. **
  105244. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  105245. ** error message text. The calling function should free this memory
  105246. ** by calling sqlite3DbFree(db, ).
  105247. */
  105248. static int sqlite3LoadExtension(
  105249. sqlite3 *db, /* Load the extension into this database connection */
  105250. const char *zFile, /* Name of the shared library containing extension */
  105251. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  105252. char **pzErrMsg /* Put error message here if not 0 */
  105253. ){
  105254. sqlite3_vfs *pVfs = db->pVfs;
  105255. void *handle;
  105256. sqlite3_loadext_entry xInit;
  105257. char *zErrmsg = 0;
  105258. const char *zEntry;
  105259. char *zAltEntry = 0;
  105260. void **aHandle;
  105261. u64 nMsg = 300 + sqlite3Strlen30(zFile);
  105262. int ii;
  105263. int rc;
  105264. /* Shared library endings to try if zFile cannot be loaded as written */
  105265. static const char *azEndings[] = {
  105266. #if SQLITE_OS_WIN
  105267. "dll"
  105268. #elif defined(__APPLE__)
  105269. "dylib"
  105270. #else
  105271. "so"
  105272. #endif
  105273. };
  105274. if( pzErrMsg ) *pzErrMsg = 0;
  105275. /* Ticket #1863. To avoid a creating security problems for older
  105276. ** applications that relink against newer versions of SQLite, the
  105277. ** ability to run load_extension is turned off by default. One
  105278. ** must call either sqlite3_enable_load_extension(db) or
  105279. ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
  105280. ** to turn on extension loading.
  105281. */
  105282. if( (db->flags & SQLITE_LoadExtension)==0 ){
  105283. if( pzErrMsg ){
  105284. *pzErrMsg = sqlite3_mprintf("not authorized");
  105285. }
  105286. return SQLITE_ERROR;
  105287. }
  105288. zEntry = zProc ? zProc : "sqlite3_extension_init";
  105289. handle = sqlite3OsDlOpen(pVfs, zFile);
  105290. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  105291. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  105292. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  105293. if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
  105294. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  105295. sqlite3_free(zAltFile);
  105296. }
  105297. #endif
  105298. if( handle==0 ){
  105299. if( pzErrMsg ){
  105300. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  105301. if( zErrmsg ){
  105302. sqlite3_snprintf(nMsg, zErrmsg,
  105303. "unable to open shared library [%s]", zFile);
  105304. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  105305. }
  105306. }
  105307. return SQLITE_ERROR;
  105308. }
  105309. xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
  105310. /* If no entry point was specified and the default legacy
  105311. ** entry point name "sqlite3_extension_init" was not found, then
  105312. ** construct an entry point name "sqlite3_X_init" where the X is
  105313. ** replaced by the lowercase value of every ASCII alphabetic
  105314. ** character in the filename after the last "/" upto the first ".",
  105315. ** and eliding the first three characters if they are "lib".
  105316. ** Examples:
  105317. **
  105318. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  105319. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  105320. */
  105321. if( xInit==0 && zProc==0 ){
  105322. int iFile, iEntry, c;
  105323. int ncFile = sqlite3Strlen30(zFile);
  105324. zAltEntry = sqlite3_malloc64(ncFile+30);
  105325. if( zAltEntry==0 ){
  105326. sqlite3OsDlClose(pVfs, handle);
  105327. return SQLITE_NOMEM_BKPT;
  105328. }
  105329. memcpy(zAltEntry, "sqlite3_", 8);
  105330. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  105331. iFile++;
  105332. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  105333. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  105334. if( sqlite3Isalpha(c) ){
  105335. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  105336. }
  105337. }
  105338. memcpy(zAltEntry+iEntry, "_init", 6);
  105339. zEntry = zAltEntry;
  105340. xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
  105341. }
  105342. if( xInit==0 ){
  105343. if( pzErrMsg ){
  105344. nMsg += sqlite3Strlen30(zEntry);
  105345. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  105346. if( zErrmsg ){
  105347. sqlite3_snprintf(nMsg, zErrmsg,
  105348. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  105349. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  105350. }
  105351. }
  105352. sqlite3OsDlClose(pVfs, handle);
  105353. sqlite3_free(zAltEntry);
  105354. return SQLITE_ERROR;
  105355. }
  105356. sqlite3_free(zAltEntry);
  105357. rc = xInit(db, &zErrmsg, &sqlite3Apis);
  105358. if( rc ){
  105359. if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
  105360. if( pzErrMsg ){
  105361. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  105362. }
  105363. sqlite3_free(zErrmsg);
  105364. sqlite3OsDlClose(pVfs, handle);
  105365. return SQLITE_ERROR;
  105366. }
  105367. /* Append the new shared library handle to the db->aExtension array. */
  105368. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  105369. if( aHandle==0 ){
  105370. return SQLITE_NOMEM_BKPT;
  105371. }
  105372. if( db->nExtension>0 ){
  105373. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  105374. }
  105375. sqlite3DbFree(db, db->aExtension);
  105376. db->aExtension = aHandle;
  105377. db->aExtension[db->nExtension++] = handle;
  105378. return SQLITE_OK;
  105379. }
  105380. SQLITE_API int sqlite3_load_extension(
  105381. sqlite3 *db, /* Load the extension into this database connection */
  105382. const char *zFile, /* Name of the shared library containing extension */
  105383. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  105384. char **pzErrMsg /* Put error message here if not 0 */
  105385. ){
  105386. int rc;
  105387. sqlite3_mutex_enter(db->mutex);
  105388. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  105389. rc = sqlite3ApiExit(db, rc);
  105390. sqlite3_mutex_leave(db->mutex);
  105391. return rc;
  105392. }
  105393. /*
  105394. ** Call this routine when the database connection is closing in order
  105395. ** to clean up loaded extensions
  105396. */
  105397. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  105398. int i;
  105399. assert( sqlite3_mutex_held(db->mutex) );
  105400. for(i=0; i<db->nExtension; i++){
  105401. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  105402. }
  105403. sqlite3DbFree(db, db->aExtension);
  105404. }
  105405. /*
  105406. ** Enable or disable extension loading. Extension loading is disabled by
  105407. ** default so as not to open security holes in older applications.
  105408. */
  105409. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  105410. sqlite3_mutex_enter(db->mutex);
  105411. if( onoff ){
  105412. db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
  105413. }else{
  105414. db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
  105415. }
  105416. sqlite3_mutex_leave(db->mutex);
  105417. return SQLITE_OK;
  105418. }
  105419. #endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  105420. /*
  105421. ** The following object holds the list of automatically loaded
  105422. ** extensions.
  105423. **
  105424. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  105425. ** mutex must be held while accessing this list.
  105426. */
  105427. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  105428. static SQLITE_WSD struct sqlite3AutoExtList {
  105429. u32 nExt; /* Number of entries in aExt[] */
  105430. void (**aExt)(void); /* Pointers to the extension init functions */
  105431. } sqlite3Autoext = { 0, 0 };
  105432. /* The "wsdAutoext" macro will resolve to the autoextension
  105433. ** state vector. If writable static data is unsupported on the target,
  105434. ** we have to locate the state vector at run-time. In the more common
  105435. ** case where writable static data is supported, wsdStat can refer directly
  105436. ** to the "sqlite3Autoext" state vector declared above.
  105437. */
  105438. #ifdef SQLITE_OMIT_WSD
  105439. # define wsdAutoextInit \
  105440. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  105441. # define wsdAutoext x[0]
  105442. #else
  105443. # define wsdAutoextInit
  105444. # define wsdAutoext sqlite3Autoext
  105445. #endif
  105446. /*
  105447. ** Register a statically linked extension that is automatically
  105448. ** loaded by every new database connection.
  105449. */
  105450. SQLITE_API int sqlite3_auto_extension(
  105451. void (*xInit)(void)
  105452. ){
  105453. int rc = SQLITE_OK;
  105454. #ifndef SQLITE_OMIT_AUTOINIT
  105455. rc = sqlite3_initialize();
  105456. if( rc ){
  105457. return rc;
  105458. }else
  105459. #endif
  105460. {
  105461. u32 i;
  105462. #if SQLITE_THREADSAFE
  105463. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  105464. #endif
  105465. wsdAutoextInit;
  105466. sqlite3_mutex_enter(mutex);
  105467. for(i=0; i<wsdAutoext.nExt; i++){
  105468. if( wsdAutoext.aExt[i]==xInit ) break;
  105469. }
  105470. if( i==wsdAutoext.nExt ){
  105471. u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  105472. void (**aNew)(void);
  105473. aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
  105474. if( aNew==0 ){
  105475. rc = SQLITE_NOMEM_BKPT;
  105476. }else{
  105477. wsdAutoext.aExt = aNew;
  105478. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  105479. wsdAutoext.nExt++;
  105480. }
  105481. }
  105482. sqlite3_mutex_leave(mutex);
  105483. assert( (rc&0xff)==rc );
  105484. return rc;
  105485. }
  105486. }
  105487. /*
  105488. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  105489. ** set of routines that is invoked for each new database connection, if it
  105490. ** is currently on the list. If xInit is not on the list, then this
  105491. ** routine is a no-op.
  105492. **
  105493. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  105494. ** was not on the list.
  105495. */
  105496. SQLITE_API int sqlite3_cancel_auto_extension(
  105497. void (*xInit)(void)
  105498. ){
  105499. #if SQLITE_THREADSAFE
  105500. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  105501. #endif
  105502. int i;
  105503. int n = 0;
  105504. wsdAutoextInit;
  105505. sqlite3_mutex_enter(mutex);
  105506. for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
  105507. if( wsdAutoext.aExt[i]==xInit ){
  105508. wsdAutoext.nExt--;
  105509. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  105510. n++;
  105511. break;
  105512. }
  105513. }
  105514. sqlite3_mutex_leave(mutex);
  105515. return n;
  105516. }
  105517. /*
  105518. ** Reset the automatic extension loading mechanism.
  105519. */
  105520. SQLITE_API void sqlite3_reset_auto_extension(void){
  105521. #ifndef SQLITE_OMIT_AUTOINIT
  105522. if( sqlite3_initialize()==SQLITE_OK )
  105523. #endif
  105524. {
  105525. #if SQLITE_THREADSAFE
  105526. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  105527. #endif
  105528. wsdAutoextInit;
  105529. sqlite3_mutex_enter(mutex);
  105530. sqlite3_free(wsdAutoext.aExt);
  105531. wsdAutoext.aExt = 0;
  105532. wsdAutoext.nExt = 0;
  105533. sqlite3_mutex_leave(mutex);
  105534. }
  105535. }
  105536. /*
  105537. ** Load all automatic extensions.
  105538. **
  105539. ** If anything goes wrong, set an error in the database connection.
  105540. */
  105541. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  105542. u32 i;
  105543. int go = 1;
  105544. int rc;
  105545. sqlite3_loadext_entry xInit;
  105546. wsdAutoextInit;
  105547. if( wsdAutoext.nExt==0 ){
  105548. /* Common case: early out without every having to acquire a mutex */
  105549. return;
  105550. }
  105551. for(i=0; go; i++){
  105552. char *zErrmsg;
  105553. #if SQLITE_THREADSAFE
  105554. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  105555. #endif
  105556. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  105557. const sqlite3_api_routines *pThunk = 0;
  105558. #else
  105559. const sqlite3_api_routines *pThunk = &sqlite3Apis;
  105560. #endif
  105561. sqlite3_mutex_enter(mutex);
  105562. if( i>=wsdAutoext.nExt ){
  105563. xInit = 0;
  105564. go = 0;
  105565. }else{
  105566. xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
  105567. }
  105568. sqlite3_mutex_leave(mutex);
  105569. zErrmsg = 0;
  105570. if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
  105571. sqlite3ErrorWithMsg(db, rc,
  105572. "automatic extension loading failed: %s", zErrmsg);
  105573. go = 0;
  105574. }
  105575. sqlite3_free(zErrmsg);
  105576. }
  105577. }
  105578. /************** End of loadext.c *********************************************/
  105579. /************** Begin file pragma.c ******************************************/
  105580. /*
  105581. ** 2003 April 6
  105582. **
  105583. ** The author disclaims copyright to this source code. In place of
  105584. ** a legal notice, here is a blessing:
  105585. **
  105586. ** May you do good and not evil.
  105587. ** May you find forgiveness for yourself and forgive others.
  105588. ** May you share freely, never taking more than you give.
  105589. **
  105590. *************************************************************************
  105591. ** This file contains code used to implement the PRAGMA command.
  105592. */
  105593. /* #include "sqliteInt.h" */
  105594. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  105595. # if defined(__APPLE__)
  105596. # define SQLITE_ENABLE_LOCKING_STYLE 1
  105597. # else
  105598. # define SQLITE_ENABLE_LOCKING_STYLE 0
  105599. # endif
  105600. #endif
  105601. /***************************************************************************
  105602. ** The "pragma.h" include file is an automatically generated file that
  105603. ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
  105604. ** object. This ensures that the aPragmaName[] table is arranged in
  105605. ** lexicographical order to facility a binary search of the pragma name.
  105606. ** Do not edit pragma.h directly. Edit and rerun the script in at
  105607. ** ../tool/mkpragmatab.tcl. */
  105608. /************** Include pragma.h in the middle of pragma.c *******************/
  105609. /************** Begin file pragma.h ******************************************/
  105610. /* DO NOT EDIT!
  105611. ** This file is automatically generated by the script at
  105612. ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
  105613. ** that script and rerun it.
  105614. */
  105615. /* The various pragma types */
  105616. #define PragTyp_HEADER_VALUE 0
  105617. #define PragTyp_AUTO_VACUUM 1
  105618. #define PragTyp_FLAG 2
  105619. #define PragTyp_BUSY_TIMEOUT 3
  105620. #define PragTyp_CACHE_SIZE 4
  105621. #define PragTyp_CACHE_SPILL 5
  105622. #define PragTyp_CASE_SENSITIVE_LIKE 6
  105623. #define PragTyp_COLLATION_LIST 7
  105624. #define PragTyp_COMPILE_OPTIONS 8
  105625. #define PragTyp_DATA_STORE_DIRECTORY 9
  105626. #define PragTyp_DATABASE_LIST 10
  105627. #define PragTyp_DEFAULT_CACHE_SIZE 11
  105628. #define PragTyp_ENCODING 12
  105629. #define PragTyp_FOREIGN_KEY_CHECK 13
  105630. #define PragTyp_FOREIGN_KEY_LIST 14
  105631. #define PragTyp_INCREMENTAL_VACUUM 15
  105632. #define PragTyp_INDEX_INFO 16
  105633. #define PragTyp_INDEX_LIST 17
  105634. #define PragTyp_INTEGRITY_CHECK 18
  105635. #define PragTyp_JOURNAL_MODE 19
  105636. #define PragTyp_JOURNAL_SIZE_LIMIT 20
  105637. #define PragTyp_LOCK_PROXY_FILE 21
  105638. #define PragTyp_LOCKING_MODE 22
  105639. #define PragTyp_PAGE_COUNT 23
  105640. #define PragTyp_MMAP_SIZE 24
  105641. #define PragTyp_OPTIMIZE 25
  105642. #define PragTyp_PAGE_SIZE 26
  105643. #define PragTyp_SECURE_DELETE 27
  105644. #define PragTyp_SHRINK_MEMORY 28
  105645. #define PragTyp_SOFT_HEAP_LIMIT 29
  105646. #define PragTyp_SYNCHRONOUS 30
  105647. #define PragTyp_TABLE_INFO 31
  105648. #define PragTyp_TEMP_STORE 32
  105649. #define PragTyp_TEMP_STORE_DIRECTORY 33
  105650. #define PragTyp_THREADS 34
  105651. #define PragTyp_WAL_AUTOCHECKPOINT 35
  105652. #define PragTyp_WAL_CHECKPOINT 36
  105653. #define PragTyp_ACTIVATE_EXTENSIONS 37
  105654. #define PragTyp_HEXKEY 38
  105655. #define PragTyp_KEY 39
  105656. #define PragTyp_REKEY 40
  105657. #define PragTyp_LOCK_STATUS 41
  105658. #define PragTyp_PARSER_TRACE 42
  105659. #define PragTyp_STATS 43
  105660. /* Property flags associated with various pragma. */
  105661. #define PragFlg_NeedSchema 0x01 /* Force schema load before running */
  105662. #define PragFlg_NoColumns 0x02 /* OP_ResultRow called with zero columns */
  105663. #define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */
  105664. #define PragFlg_ReadOnly 0x08 /* Read-only HEADER_VALUE */
  105665. #define PragFlg_Result0 0x10 /* Acts as query when no argument */
  105666. #define PragFlg_Result1 0x20 /* Acts as query when has one argument */
  105667. #define PragFlg_SchemaOpt 0x40 /* Schema restricts name search if present */
  105668. #define PragFlg_SchemaReq 0x80 /* Schema required - "main" is default */
  105669. /* Names of columns for pragmas that return multi-column result
  105670. ** or that return single-column results where the name of the
  105671. ** result column is different from the name of the pragma
  105672. */
  105673. static const char *const pragCName[] = {
  105674. /* 0 */ "cache_size", /* Used by: default_cache_size */
  105675. /* 1 */ "cid", /* Used by: table_info */
  105676. /* 2 */ "name",
  105677. /* 3 */ "type",
  105678. /* 4 */ "notnull",
  105679. /* 5 */ "dflt_value",
  105680. /* 6 */ "pk",
  105681. /* 7 */ "tbl", /* Used by: stats */
  105682. /* 8 */ "idx",
  105683. /* 9 */ "wdth",
  105684. /* 10 */ "hght",
  105685. /* 11 */ "flgs",
  105686. /* 12 */ "seqno", /* Used by: index_info */
  105687. /* 13 */ "cid",
  105688. /* 14 */ "name",
  105689. /* 15 */ "seqno", /* Used by: index_xinfo */
  105690. /* 16 */ "cid",
  105691. /* 17 */ "name",
  105692. /* 18 */ "desc",
  105693. /* 19 */ "coll",
  105694. /* 20 */ "key",
  105695. /* 21 */ "seq", /* Used by: index_list */
  105696. /* 22 */ "name",
  105697. /* 23 */ "unique",
  105698. /* 24 */ "origin",
  105699. /* 25 */ "partial",
  105700. /* 26 */ "seq", /* Used by: database_list */
  105701. /* 27 */ "name",
  105702. /* 28 */ "file",
  105703. /* 29 */ "seq", /* Used by: collation_list */
  105704. /* 30 */ "name",
  105705. /* 31 */ "id", /* Used by: foreign_key_list */
  105706. /* 32 */ "seq",
  105707. /* 33 */ "table",
  105708. /* 34 */ "from",
  105709. /* 35 */ "to",
  105710. /* 36 */ "on_update",
  105711. /* 37 */ "on_delete",
  105712. /* 38 */ "match",
  105713. /* 39 */ "table", /* Used by: foreign_key_check */
  105714. /* 40 */ "rowid",
  105715. /* 41 */ "parent",
  105716. /* 42 */ "fkid",
  105717. /* 43 */ "busy", /* Used by: wal_checkpoint */
  105718. /* 44 */ "log",
  105719. /* 45 */ "checkpointed",
  105720. /* 46 */ "timeout", /* Used by: busy_timeout */
  105721. /* 47 */ "database", /* Used by: lock_status */
  105722. /* 48 */ "status",
  105723. };
  105724. /* Definitions of all built-in pragmas */
  105725. typedef struct PragmaName {
  105726. const char *const zName; /* Name of pragma */
  105727. u8 ePragTyp; /* PragTyp_XXX value */
  105728. u8 mPragFlg; /* Zero or more PragFlg_XXX values */
  105729. u8 iPragCName; /* Start of column names in pragCName[] */
  105730. u8 nPragCName; /* Num of col names. 0 means use pragma name */
  105731. u32 iArg; /* Extra argument */
  105732. } PragmaName;
  105733. static const PragmaName aPragmaName[] = {
  105734. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  105735. {/* zName: */ "activate_extensions",
  105736. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  105737. /* ePragFlg: */ 0,
  105738. /* ColNames: */ 0, 0,
  105739. /* iArg: */ 0 },
  105740. #endif
  105741. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  105742. {/* zName: */ "application_id",
  105743. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  105744. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  105745. /* ColNames: */ 0, 0,
  105746. /* iArg: */ BTREE_APPLICATION_ID },
  105747. #endif
  105748. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  105749. {/* zName: */ "auto_vacuum",
  105750. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  105751. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  105752. /* ColNames: */ 0, 0,
  105753. /* iArg: */ 0 },
  105754. #endif
  105755. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105756. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  105757. {/* zName: */ "automatic_index",
  105758. /* ePragTyp: */ PragTyp_FLAG,
  105759. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105760. /* ColNames: */ 0, 0,
  105761. /* iArg: */ SQLITE_AutoIndex },
  105762. #endif
  105763. #endif
  105764. {/* zName: */ "busy_timeout",
  105765. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  105766. /* ePragFlg: */ PragFlg_Result0,
  105767. /* ColNames: */ 46, 1,
  105768. /* iArg: */ 0 },
  105769. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  105770. {/* zName: */ "cache_size",
  105771. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  105772. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  105773. /* ColNames: */ 0, 0,
  105774. /* iArg: */ 0 },
  105775. #endif
  105776. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105777. {/* zName: */ "cache_spill",
  105778. /* ePragTyp: */ PragTyp_CACHE_SPILL,
  105779. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  105780. /* ColNames: */ 0, 0,
  105781. /* iArg: */ 0 },
  105782. #endif
  105783. {/* zName: */ "case_sensitive_like",
  105784. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  105785. /* ePragFlg: */ PragFlg_NoColumns,
  105786. /* ColNames: */ 0, 0,
  105787. /* iArg: */ 0 },
  105788. {/* zName: */ "cell_size_check",
  105789. /* ePragTyp: */ PragTyp_FLAG,
  105790. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105791. /* ColNames: */ 0, 0,
  105792. /* iArg: */ SQLITE_CellSizeCk },
  105793. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105794. {/* zName: */ "checkpoint_fullfsync",
  105795. /* ePragTyp: */ PragTyp_FLAG,
  105796. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105797. /* ColNames: */ 0, 0,
  105798. /* iArg: */ SQLITE_CkptFullFSync },
  105799. #endif
  105800. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  105801. {/* zName: */ "collation_list",
  105802. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  105803. /* ePragFlg: */ PragFlg_Result0,
  105804. /* ColNames: */ 29, 2,
  105805. /* iArg: */ 0 },
  105806. #endif
  105807. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  105808. {/* zName: */ "compile_options",
  105809. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  105810. /* ePragFlg: */ PragFlg_Result0,
  105811. /* ColNames: */ 0, 0,
  105812. /* iArg: */ 0 },
  105813. #endif
  105814. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105815. {/* zName: */ "count_changes",
  105816. /* ePragTyp: */ PragTyp_FLAG,
  105817. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105818. /* ColNames: */ 0, 0,
  105819. /* iArg: */ SQLITE_CountRows },
  105820. #endif
  105821. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  105822. {/* zName: */ "data_store_directory",
  105823. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  105824. /* ePragFlg: */ PragFlg_NoColumns1,
  105825. /* ColNames: */ 0, 0,
  105826. /* iArg: */ 0 },
  105827. #endif
  105828. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  105829. {/* zName: */ "data_version",
  105830. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  105831. /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
  105832. /* ColNames: */ 0, 0,
  105833. /* iArg: */ BTREE_DATA_VERSION },
  105834. #endif
  105835. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  105836. {/* zName: */ "database_list",
  105837. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  105838. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
  105839. /* ColNames: */ 26, 3,
  105840. /* iArg: */ 0 },
  105841. #endif
  105842. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  105843. {/* zName: */ "default_cache_size",
  105844. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  105845. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  105846. /* ColNames: */ 0, 1,
  105847. /* iArg: */ 0 },
  105848. #endif
  105849. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105850. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  105851. {/* zName: */ "defer_foreign_keys",
  105852. /* ePragTyp: */ PragTyp_FLAG,
  105853. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105854. /* ColNames: */ 0, 0,
  105855. /* iArg: */ SQLITE_DeferFKs },
  105856. #endif
  105857. #endif
  105858. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105859. {/* zName: */ "empty_result_callbacks",
  105860. /* ePragTyp: */ PragTyp_FLAG,
  105861. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105862. /* ColNames: */ 0, 0,
  105863. /* iArg: */ SQLITE_NullCallback },
  105864. #endif
  105865. #if !defined(SQLITE_OMIT_UTF16)
  105866. {/* zName: */ "encoding",
  105867. /* ePragTyp: */ PragTyp_ENCODING,
  105868. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105869. /* ColNames: */ 0, 0,
  105870. /* iArg: */ 0 },
  105871. #endif
  105872. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  105873. {/* zName: */ "foreign_key_check",
  105874. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  105875. /* ePragFlg: */ PragFlg_NeedSchema,
  105876. /* ColNames: */ 39, 4,
  105877. /* iArg: */ 0 },
  105878. #endif
  105879. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  105880. {/* zName: */ "foreign_key_list",
  105881. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  105882. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  105883. /* ColNames: */ 31, 8,
  105884. /* iArg: */ 0 },
  105885. #endif
  105886. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105887. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  105888. {/* zName: */ "foreign_keys",
  105889. /* ePragTyp: */ PragTyp_FLAG,
  105890. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105891. /* ColNames: */ 0, 0,
  105892. /* iArg: */ SQLITE_ForeignKeys },
  105893. #endif
  105894. #endif
  105895. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  105896. {/* zName: */ "freelist_count",
  105897. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  105898. /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
  105899. /* ColNames: */ 0, 0,
  105900. /* iArg: */ BTREE_FREE_PAGE_COUNT },
  105901. #endif
  105902. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105903. {/* zName: */ "full_column_names",
  105904. /* ePragTyp: */ PragTyp_FLAG,
  105905. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105906. /* ColNames: */ 0, 0,
  105907. /* iArg: */ SQLITE_FullColNames },
  105908. {/* zName: */ "fullfsync",
  105909. /* ePragTyp: */ PragTyp_FLAG,
  105910. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105911. /* ColNames: */ 0, 0,
  105912. /* iArg: */ SQLITE_FullFSync },
  105913. #endif
  105914. #if defined(SQLITE_HAS_CODEC)
  105915. {/* zName: */ "hexkey",
  105916. /* ePragTyp: */ PragTyp_HEXKEY,
  105917. /* ePragFlg: */ 0,
  105918. /* ColNames: */ 0, 0,
  105919. /* iArg: */ 0 },
  105920. {/* zName: */ "hexrekey",
  105921. /* ePragTyp: */ PragTyp_HEXKEY,
  105922. /* ePragFlg: */ 0,
  105923. /* ColNames: */ 0, 0,
  105924. /* iArg: */ 0 },
  105925. #endif
  105926. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105927. #if !defined(SQLITE_OMIT_CHECK)
  105928. {/* zName: */ "ignore_check_constraints",
  105929. /* ePragTyp: */ PragTyp_FLAG,
  105930. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105931. /* ColNames: */ 0, 0,
  105932. /* iArg: */ SQLITE_IgnoreChecks },
  105933. #endif
  105934. #endif
  105935. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  105936. {/* zName: */ "incremental_vacuum",
  105937. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  105938. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_NoColumns,
  105939. /* ColNames: */ 0, 0,
  105940. /* iArg: */ 0 },
  105941. #endif
  105942. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  105943. {/* zName: */ "index_info",
  105944. /* ePragTyp: */ PragTyp_INDEX_INFO,
  105945. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  105946. /* ColNames: */ 12, 3,
  105947. /* iArg: */ 0 },
  105948. {/* zName: */ "index_list",
  105949. /* ePragTyp: */ PragTyp_INDEX_LIST,
  105950. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  105951. /* ColNames: */ 21, 5,
  105952. /* iArg: */ 0 },
  105953. {/* zName: */ "index_xinfo",
  105954. /* ePragTyp: */ PragTyp_INDEX_INFO,
  105955. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  105956. /* ColNames: */ 15, 6,
  105957. /* iArg: */ 1 },
  105958. #endif
  105959. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  105960. {/* zName: */ "integrity_check",
  105961. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  105962. /* ePragFlg: */ PragFlg_NeedSchema,
  105963. /* ColNames: */ 0, 0,
  105964. /* iArg: */ 0 },
  105965. #endif
  105966. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  105967. {/* zName: */ "journal_mode",
  105968. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  105969. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  105970. /* ColNames: */ 0, 0,
  105971. /* iArg: */ 0 },
  105972. {/* zName: */ "journal_size_limit",
  105973. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  105974. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
  105975. /* ColNames: */ 0, 0,
  105976. /* iArg: */ 0 },
  105977. #endif
  105978. #if defined(SQLITE_HAS_CODEC)
  105979. {/* zName: */ "key",
  105980. /* ePragTyp: */ PragTyp_KEY,
  105981. /* ePragFlg: */ 0,
  105982. /* ColNames: */ 0, 0,
  105983. /* iArg: */ 0 },
  105984. #endif
  105985. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  105986. {/* zName: */ "legacy_file_format",
  105987. /* ePragTyp: */ PragTyp_FLAG,
  105988. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  105989. /* ColNames: */ 0, 0,
  105990. /* iArg: */ SQLITE_LegacyFileFmt },
  105991. #endif
  105992. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  105993. {/* zName: */ "lock_proxy_file",
  105994. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  105995. /* ePragFlg: */ PragFlg_NoColumns1,
  105996. /* ColNames: */ 0, 0,
  105997. /* iArg: */ 0 },
  105998. #endif
  105999. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  106000. {/* zName: */ "lock_status",
  106001. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  106002. /* ePragFlg: */ PragFlg_Result0,
  106003. /* ColNames: */ 47, 2,
  106004. /* iArg: */ 0 },
  106005. #endif
  106006. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  106007. {/* zName: */ "locking_mode",
  106008. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  106009. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
  106010. /* ColNames: */ 0, 0,
  106011. /* iArg: */ 0 },
  106012. {/* zName: */ "max_page_count",
  106013. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  106014. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  106015. /* ColNames: */ 0, 0,
  106016. /* iArg: */ 0 },
  106017. {/* zName: */ "mmap_size",
  106018. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  106019. /* ePragFlg: */ 0,
  106020. /* ColNames: */ 0, 0,
  106021. /* iArg: */ 0 },
  106022. #endif
  106023. {/* zName: */ "optimize",
  106024. /* ePragTyp: */ PragTyp_OPTIMIZE,
  106025. /* ePragFlg: */ PragFlg_Result1|PragFlg_NeedSchema,
  106026. /* ColNames: */ 0, 0,
  106027. /* iArg: */ 0 },
  106028. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  106029. {/* zName: */ "page_count",
  106030. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  106031. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  106032. /* ColNames: */ 0, 0,
  106033. /* iArg: */ 0 },
  106034. {/* zName: */ "page_size",
  106035. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  106036. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  106037. /* ColNames: */ 0, 0,
  106038. /* iArg: */ 0 },
  106039. #endif
  106040. #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
  106041. {/* zName: */ "parser_trace",
  106042. /* ePragTyp: */ PragTyp_PARSER_TRACE,
  106043. /* ePragFlg: */ 0,
  106044. /* ColNames: */ 0, 0,
  106045. /* iArg: */ 0 },
  106046. #endif
  106047. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106048. {/* zName: */ "query_only",
  106049. /* ePragTyp: */ PragTyp_FLAG,
  106050. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106051. /* ColNames: */ 0, 0,
  106052. /* iArg: */ SQLITE_QueryOnly },
  106053. #endif
  106054. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  106055. {/* zName: */ "quick_check",
  106056. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  106057. /* ePragFlg: */ PragFlg_NeedSchema,
  106058. /* ColNames: */ 0, 0,
  106059. /* iArg: */ 0 },
  106060. #endif
  106061. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106062. {/* zName: */ "read_uncommitted",
  106063. /* ePragTyp: */ PragTyp_FLAG,
  106064. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106065. /* ColNames: */ 0, 0,
  106066. /* iArg: */ SQLITE_ReadUncommitted },
  106067. {/* zName: */ "recursive_triggers",
  106068. /* ePragTyp: */ PragTyp_FLAG,
  106069. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106070. /* ColNames: */ 0, 0,
  106071. /* iArg: */ SQLITE_RecTriggers },
  106072. #endif
  106073. #if defined(SQLITE_HAS_CODEC)
  106074. {/* zName: */ "rekey",
  106075. /* ePragTyp: */ PragTyp_REKEY,
  106076. /* ePragFlg: */ 0,
  106077. /* ColNames: */ 0, 0,
  106078. /* iArg: */ 0 },
  106079. #endif
  106080. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106081. {/* zName: */ "reverse_unordered_selects",
  106082. /* ePragTyp: */ PragTyp_FLAG,
  106083. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106084. /* ColNames: */ 0, 0,
  106085. /* iArg: */ SQLITE_ReverseOrder },
  106086. #endif
  106087. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  106088. {/* zName: */ "schema_version",
  106089. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  106090. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  106091. /* ColNames: */ 0, 0,
  106092. /* iArg: */ BTREE_SCHEMA_VERSION },
  106093. #endif
  106094. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  106095. {/* zName: */ "secure_delete",
  106096. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  106097. /* ePragFlg: */ PragFlg_Result0,
  106098. /* ColNames: */ 0, 0,
  106099. /* iArg: */ 0 },
  106100. #endif
  106101. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106102. {/* zName: */ "short_column_names",
  106103. /* ePragTyp: */ PragTyp_FLAG,
  106104. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106105. /* ColNames: */ 0, 0,
  106106. /* iArg: */ SQLITE_ShortColNames },
  106107. #endif
  106108. {/* zName: */ "shrink_memory",
  106109. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  106110. /* ePragFlg: */ PragFlg_NoColumns,
  106111. /* ColNames: */ 0, 0,
  106112. /* iArg: */ 0 },
  106113. {/* zName: */ "soft_heap_limit",
  106114. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  106115. /* ePragFlg: */ PragFlg_Result0,
  106116. /* ColNames: */ 0, 0,
  106117. /* iArg: */ 0 },
  106118. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106119. #if defined(SQLITE_DEBUG)
  106120. {/* zName: */ "sql_trace",
  106121. /* ePragTyp: */ PragTyp_FLAG,
  106122. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106123. /* ColNames: */ 0, 0,
  106124. /* iArg: */ SQLITE_SqlTrace },
  106125. #endif
  106126. #endif
  106127. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)
  106128. {/* zName: */ "stats",
  106129. /* ePragTyp: */ PragTyp_STATS,
  106130. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  106131. /* ColNames: */ 7, 5,
  106132. /* iArg: */ 0 },
  106133. #endif
  106134. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  106135. {/* zName: */ "synchronous",
  106136. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  106137. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  106138. /* ColNames: */ 0, 0,
  106139. /* iArg: */ 0 },
  106140. #endif
  106141. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  106142. {/* zName: */ "table_info",
  106143. /* ePragTyp: */ PragTyp_TABLE_INFO,
  106144. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  106145. /* ColNames: */ 1, 6,
  106146. /* iArg: */ 0 },
  106147. #endif
  106148. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  106149. {/* zName: */ "temp_store",
  106150. /* ePragTyp: */ PragTyp_TEMP_STORE,
  106151. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106152. /* ColNames: */ 0, 0,
  106153. /* iArg: */ 0 },
  106154. {/* zName: */ "temp_store_directory",
  106155. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  106156. /* ePragFlg: */ PragFlg_NoColumns1,
  106157. /* ColNames: */ 0, 0,
  106158. /* iArg: */ 0 },
  106159. #endif
  106160. {/* zName: */ "threads",
  106161. /* ePragTyp: */ PragTyp_THREADS,
  106162. /* ePragFlg: */ PragFlg_Result0,
  106163. /* ColNames: */ 0, 0,
  106164. /* iArg: */ 0 },
  106165. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  106166. {/* zName: */ "user_version",
  106167. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  106168. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  106169. /* ColNames: */ 0, 0,
  106170. /* iArg: */ BTREE_USER_VERSION },
  106171. #endif
  106172. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106173. #if defined(SQLITE_DEBUG)
  106174. {/* zName: */ "vdbe_addoptrace",
  106175. /* ePragTyp: */ PragTyp_FLAG,
  106176. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106177. /* ColNames: */ 0, 0,
  106178. /* iArg: */ SQLITE_VdbeAddopTrace },
  106179. {/* zName: */ "vdbe_debug",
  106180. /* ePragTyp: */ PragTyp_FLAG,
  106181. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106182. /* ColNames: */ 0, 0,
  106183. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  106184. {/* zName: */ "vdbe_eqp",
  106185. /* ePragTyp: */ PragTyp_FLAG,
  106186. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106187. /* ColNames: */ 0, 0,
  106188. /* iArg: */ SQLITE_VdbeEQP },
  106189. {/* zName: */ "vdbe_listing",
  106190. /* ePragTyp: */ PragTyp_FLAG,
  106191. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106192. /* ColNames: */ 0, 0,
  106193. /* iArg: */ SQLITE_VdbeListing },
  106194. {/* zName: */ "vdbe_trace",
  106195. /* ePragTyp: */ PragTyp_FLAG,
  106196. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106197. /* ColNames: */ 0, 0,
  106198. /* iArg: */ SQLITE_VdbeTrace },
  106199. #endif
  106200. #endif
  106201. #if !defined(SQLITE_OMIT_WAL)
  106202. {/* zName: */ "wal_autocheckpoint",
  106203. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  106204. /* ePragFlg: */ 0,
  106205. /* ColNames: */ 0, 0,
  106206. /* iArg: */ 0 },
  106207. {/* zName: */ "wal_checkpoint",
  106208. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  106209. /* ePragFlg: */ PragFlg_NeedSchema,
  106210. /* ColNames: */ 43, 3,
  106211. /* iArg: */ 0 },
  106212. #endif
  106213. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  106214. {/* zName: */ "writable_schema",
  106215. /* ePragTyp: */ PragTyp_FLAG,
  106216. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  106217. /* ColNames: */ 0, 0,
  106218. /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
  106219. #endif
  106220. };
  106221. /* Number of pragmas: 60 on by default, 74 total. */
  106222. /************** End of pragma.h **********************************************/
  106223. /************** Continuing where we left off in pragma.c *********************/
  106224. /*
  106225. ** Interpret the given string as a safety level. Return 0 for OFF,
  106226. ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
  106227. ** unrecognized string argument. The FULL and EXTRA option is disallowed
  106228. ** if the omitFull parameter it 1.
  106229. **
  106230. ** Note that the values returned are one less that the values that
  106231. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  106232. ** to support legacy SQL code. The safety level used to be boolean
  106233. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  106234. */
  106235. static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
  106236. /* 123456789 123456789 123 */
  106237. static const char zText[] = "onoffalseyestruextrafull";
  106238. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20};
  106239. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4};
  106240. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2};
  106241. /* on no off false yes true extra full */
  106242. int i, n;
  106243. if( sqlite3Isdigit(*z) ){
  106244. return (u8)sqlite3Atoi(z);
  106245. }
  106246. n = sqlite3Strlen30(z);
  106247. for(i=0; i<ArraySize(iLength); i++){
  106248. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
  106249. && (!omitFull || iValue[i]<=1)
  106250. ){
  106251. return iValue[i];
  106252. }
  106253. }
  106254. return dflt;
  106255. }
  106256. /*
  106257. ** Interpret the given string as a boolean value.
  106258. */
  106259. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
  106260. return getSafetyLevel(z,1,dflt)!=0;
  106261. }
  106262. /* The sqlite3GetBoolean() function is used by other modules but the
  106263. ** remainder of this file is specific to PRAGMA processing. So omit
  106264. ** the rest of the file if PRAGMAs are omitted from the build.
  106265. */
  106266. #if !defined(SQLITE_OMIT_PRAGMA)
  106267. /*
  106268. ** Interpret the given string as a locking mode value.
  106269. */
  106270. static int getLockingMode(const char *z){
  106271. if( z ){
  106272. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  106273. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  106274. }
  106275. return PAGER_LOCKINGMODE_QUERY;
  106276. }
  106277. #ifndef SQLITE_OMIT_AUTOVACUUM
  106278. /*
  106279. ** Interpret the given string as an auto-vacuum mode value.
  106280. **
  106281. ** The following strings, "none", "full" and "incremental" are
  106282. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  106283. */
  106284. static int getAutoVacuum(const char *z){
  106285. int i;
  106286. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  106287. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  106288. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  106289. i = sqlite3Atoi(z);
  106290. return (u8)((i>=0&&i<=2)?i:0);
  106291. }
  106292. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  106293. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  106294. /*
  106295. ** Interpret the given string as a temp db location. Return 1 for file
  106296. ** backed temporary databases, 2 for the Red-Black tree in memory database
  106297. ** and 0 to use the compile-time default.
  106298. */
  106299. static int getTempStore(const char *z){
  106300. if( z[0]>='0' && z[0]<='2' ){
  106301. return z[0] - '0';
  106302. }else if( sqlite3StrICmp(z, "file")==0 ){
  106303. return 1;
  106304. }else if( sqlite3StrICmp(z, "memory")==0 ){
  106305. return 2;
  106306. }else{
  106307. return 0;
  106308. }
  106309. }
  106310. #endif /* SQLITE_PAGER_PRAGMAS */
  106311. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  106312. /*
  106313. ** Invalidate temp storage, either when the temp storage is changed
  106314. ** from default, or when 'file' and the temp_store_directory has changed
  106315. */
  106316. static int invalidateTempStorage(Parse *pParse){
  106317. sqlite3 *db = pParse->db;
  106318. if( db->aDb[1].pBt!=0 ){
  106319. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  106320. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  106321. "from within a transaction");
  106322. return SQLITE_ERROR;
  106323. }
  106324. sqlite3BtreeClose(db->aDb[1].pBt);
  106325. db->aDb[1].pBt = 0;
  106326. sqlite3ResetAllSchemasOfConnection(db);
  106327. }
  106328. return SQLITE_OK;
  106329. }
  106330. #endif /* SQLITE_PAGER_PRAGMAS */
  106331. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  106332. /*
  106333. ** If the TEMP database is open, close it and mark the database schema
  106334. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  106335. ** or DEFAULT_TEMP_STORE pragmas.
  106336. */
  106337. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  106338. int ts = getTempStore(zStorageType);
  106339. sqlite3 *db = pParse->db;
  106340. if( db->temp_store==ts ) return SQLITE_OK;
  106341. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  106342. return SQLITE_ERROR;
  106343. }
  106344. db->temp_store = (u8)ts;
  106345. return SQLITE_OK;
  106346. }
  106347. #endif /* SQLITE_PAGER_PRAGMAS */
  106348. /*
  106349. ** Set result column names for a pragma.
  106350. */
  106351. static void setPragmaResultColumnNames(
  106352. Vdbe *v, /* The query under construction */
  106353. const PragmaName *pPragma /* The pragma */
  106354. ){
  106355. u8 n = pPragma->nPragCName;
  106356. sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
  106357. if( n==0 ){
  106358. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
  106359. }else{
  106360. int i, j;
  106361. for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
  106362. sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
  106363. }
  106364. }
  106365. }
  106366. /*
  106367. ** Generate code to return a single integer value.
  106368. */
  106369. static void returnSingleInt(Vdbe *v, i64 value){
  106370. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
  106371. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  106372. }
  106373. /*
  106374. ** Generate code to return a single text value.
  106375. */
  106376. static void returnSingleText(
  106377. Vdbe *v, /* Prepared statement under construction */
  106378. const char *zValue /* Value to be returned */
  106379. ){
  106380. if( zValue ){
  106381. sqlite3VdbeLoadString(v, 1, (const char*)zValue);
  106382. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  106383. }
  106384. }
  106385. /*
  106386. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  106387. ** set these values for all pagers.
  106388. */
  106389. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  106390. static void setAllPagerFlags(sqlite3 *db){
  106391. if( db->autoCommit ){
  106392. Db *pDb = db->aDb;
  106393. int n = db->nDb;
  106394. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  106395. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  106396. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  106397. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  106398. == PAGER_FLAGS_MASK );
  106399. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  106400. while( (n--) > 0 ){
  106401. if( pDb->pBt ){
  106402. sqlite3BtreeSetPagerFlags(pDb->pBt,
  106403. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  106404. }
  106405. pDb++;
  106406. }
  106407. }
  106408. }
  106409. #else
  106410. # define setAllPagerFlags(X) /* no-op */
  106411. #endif
  106412. /*
  106413. ** Return a human-readable name for a constraint resolution action.
  106414. */
  106415. #ifndef SQLITE_OMIT_FOREIGN_KEY
  106416. static const char *actionName(u8 action){
  106417. const char *zName;
  106418. switch( action ){
  106419. case OE_SetNull: zName = "SET NULL"; break;
  106420. case OE_SetDflt: zName = "SET DEFAULT"; break;
  106421. case OE_Cascade: zName = "CASCADE"; break;
  106422. case OE_Restrict: zName = "RESTRICT"; break;
  106423. default: zName = "NO ACTION";
  106424. assert( action==OE_None ); break;
  106425. }
  106426. return zName;
  106427. }
  106428. #endif
  106429. /*
  106430. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  106431. ** defined in pager.h. This function returns the associated lowercase
  106432. ** journal-mode name.
  106433. */
  106434. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  106435. static char * const azModeName[] = {
  106436. "delete", "persist", "off", "truncate", "memory"
  106437. #ifndef SQLITE_OMIT_WAL
  106438. , "wal"
  106439. #endif
  106440. };
  106441. assert( PAGER_JOURNALMODE_DELETE==0 );
  106442. assert( PAGER_JOURNALMODE_PERSIST==1 );
  106443. assert( PAGER_JOURNALMODE_OFF==2 );
  106444. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  106445. assert( PAGER_JOURNALMODE_MEMORY==4 );
  106446. assert( PAGER_JOURNALMODE_WAL==5 );
  106447. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  106448. if( eMode==ArraySize(azModeName) ) return 0;
  106449. return azModeName[eMode];
  106450. }
  106451. /*
  106452. ** Locate a pragma in the aPragmaName[] array.
  106453. */
  106454. static const PragmaName *pragmaLocate(const char *zName){
  106455. int upr, lwr, mid = 0, rc;
  106456. lwr = 0;
  106457. upr = ArraySize(aPragmaName)-1;
  106458. while( lwr<=upr ){
  106459. mid = (lwr+upr)/2;
  106460. rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
  106461. if( rc==0 ) break;
  106462. if( rc<0 ){
  106463. upr = mid - 1;
  106464. }else{
  106465. lwr = mid + 1;
  106466. }
  106467. }
  106468. return lwr>upr ? 0 : &aPragmaName[mid];
  106469. }
  106470. /*
  106471. ** Helper subroutine for PRAGMA integrity_check:
  106472. **
  106473. ** Generate code to output a single-column result row with the result
  106474. ** held in register regResult. Decrement the result count and halt if
  106475. ** the maximum number of result rows have been issued.
  106476. */
  106477. static int integrityCheckResultRow(Vdbe *v, int regResult){
  106478. int addr;
  106479. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 1);
  106480. addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
  106481. VdbeCoverage(v);
  106482. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  106483. return addr;
  106484. }
  106485. /*
  106486. ** Process a pragma statement.
  106487. **
  106488. ** Pragmas are of this form:
  106489. **
  106490. ** PRAGMA [schema.]id [= value]
  106491. **
  106492. ** The identifier might also be a string. The value is a string, and
  106493. ** identifier, or a number. If minusFlag is true, then the value is
  106494. ** a number that was preceded by a minus sign.
  106495. **
  106496. ** If the left side is "database.id" then pId1 is the database name
  106497. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  106498. ** id and pId2 is any empty string.
  106499. */
  106500. SQLITE_PRIVATE void sqlite3Pragma(
  106501. Parse *pParse,
  106502. Token *pId1, /* First part of [schema.]id field */
  106503. Token *pId2, /* Second part of [schema.]id field, or NULL */
  106504. Token *pValue, /* Token for <value>, or NULL */
  106505. int minusFlag /* True if a '-' sign preceded <value> */
  106506. ){
  106507. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  106508. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  106509. const char *zDb = 0; /* The database name */
  106510. Token *pId; /* Pointer to <id> token */
  106511. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  106512. int iDb; /* Database index for <database> */
  106513. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  106514. sqlite3 *db = pParse->db; /* The database connection */
  106515. Db *pDb; /* The specific database being pragmaed */
  106516. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  106517. const PragmaName *pPragma; /* The pragma */
  106518. if( v==0 ) return;
  106519. sqlite3VdbeRunOnlyOnce(v);
  106520. pParse->nMem = 2;
  106521. /* Interpret the [schema.] part of the pragma statement. iDb is the
  106522. ** index of the database this pragma is being applied to in db.aDb[]. */
  106523. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  106524. if( iDb<0 ) return;
  106525. pDb = &db->aDb[iDb];
  106526. /* If the temp database has been explicitly named as part of the
  106527. ** pragma, make sure it is open.
  106528. */
  106529. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  106530. return;
  106531. }
  106532. zLeft = sqlite3NameFromToken(db, pId);
  106533. if( !zLeft ) return;
  106534. if( minusFlag ){
  106535. zRight = sqlite3MPrintf(db, "-%T", pValue);
  106536. }else{
  106537. zRight = sqlite3NameFromToken(db, pValue);
  106538. }
  106539. assert( pId2 );
  106540. zDb = pId2->n>0 ? pDb->zDbSName : 0;
  106541. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  106542. goto pragma_out;
  106543. }
  106544. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  106545. ** connection. If it returns SQLITE_OK, then assume that the VFS
  106546. ** handled the pragma and generate a no-op prepared statement.
  106547. **
  106548. ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
  106549. ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
  106550. ** object corresponding to the database file to which the pragma
  106551. ** statement refers.
  106552. **
  106553. ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
  106554. ** file control is an array of pointers to strings (char**) in which the
  106555. ** second element of the array is the name of the pragma and the third
  106556. ** element is the argument to the pragma or NULL if the pragma has no
  106557. ** argument.
  106558. */
  106559. aFcntl[0] = 0;
  106560. aFcntl[1] = zLeft;
  106561. aFcntl[2] = zRight;
  106562. aFcntl[3] = 0;
  106563. db->busyHandler.nBusy = 0;
  106564. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  106565. if( rc==SQLITE_OK ){
  106566. sqlite3VdbeSetNumCols(v, 1);
  106567. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
  106568. returnSingleText(v, aFcntl[0]);
  106569. sqlite3_free(aFcntl[0]);
  106570. goto pragma_out;
  106571. }
  106572. if( rc!=SQLITE_NOTFOUND ){
  106573. if( aFcntl[0] ){
  106574. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  106575. sqlite3_free(aFcntl[0]);
  106576. }
  106577. pParse->nErr++;
  106578. pParse->rc = rc;
  106579. goto pragma_out;
  106580. }
  106581. /* Locate the pragma in the lookup table */
  106582. pPragma = pragmaLocate(zLeft);
  106583. if( pPragma==0 ) goto pragma_out;
  106584. /* Make sure the database schema is loaded if the pragma requires that */
  106585. if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
  106586. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  106587. }
  106588. /* Register the result column names for pragmas that return results */
  106589. if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
  106590. && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
  106591. ){
  106592. setPragmaResultColumnNames(v, pPragma);
  106593. }
  106594. /* Jump to the appropriate pragma handler */
  106595. switch( pPragma->ePragTyp ){
  106596. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  106597. /*
  106598. ** PRAGMA [schema.]default_cache_size
  106599. ** PRAGMA [schema.]default_cache_size=N
  106600. **
  106601. ** The first form reports the current persistent setting for the
  106602. ** page cache size. The value returned is the maximum number of
  106603. ** pages in the page cache. The second form sets both the current
  106604. ** page cache size value and the persistent page cache size value
  106605. ** stored in the database file.
  106606. **
  106607. ** Older versions of SQLite would set the default cache size to a
  106608. ** negative number to indicate synchronous=OFF. These days, synchronous
  106609. ** is always on by default regardless of the sign of the default cache
  106610. ** size. But continue to take the absolute value of the default cache
  106611. ** size of historical compatibility.
  106612. */
  106613. case PragTyp_DEFAULT_CACHE_SIZE: {
  106614. static const int iLn = VDBE_OFFSET_LINENO(2);
  106615. static const VdbeOpList getCacheSize[] = {
  106616. { OP_Transaction, 0, 0, 0}, /* 0 */
  106617. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  106618. { OP_IfPos, 1, 8, 0},
  106619. { OP_Integer, 0, 2, 0},
  106620. { OP_Subtract, 1, 2, 1},
  106621. { OP_IfPos, 1, 8, 0},
  106622. { OP_Integer, 0, 1, 0}, /* 6 */
  106623. { OP_Noop, 0, 0, 0},
  106624. { OP_ResultRow, 1, 1, 0},
  106625. };
  106626. VdbeOp *aOp;
  106627. sqlite3VdbeUsesBtree(v, iDb);
  106628. if( !zRight ){
  106629. pParse->nMem += 2;
  106630. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
  106631. aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
  106632. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  106633. aOp[0].p1 = iDb;
  106634. aOp[1].p1 = iDb;
  106635. aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
  106636. }else{
  106637. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  106638. sqlite3BeginWriteOperation(pParse, 0, iDb);
  106639. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
  106640. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  106641. pDb->pSchema->cache_size = size;
  106642. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  106643. }
  106644. break;
  106645. }
  106646. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  106647. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  106648. /*
  106649. ** PRAGMA [schema.]page_size
  106650. ** PRAGMA [schema.]page_size=N
  106651. **
  106652. ** The first form reports the current setting for the
  106653. ** database page size in bytes. The second form sets the
  106654. ** database page size value. The value can only be set if
  106655. ** the database has not yet been created.
  106656. */
  106657. case PragTyp_PAGE_SIZE: {
  106658. Btree *pBt = pDb->pBt;
  106659. assert( pBt!=0 );
  106660. if( !zRight ){
  106661. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  106662. returnSingleInt(v, size);
  106663. }else{
  106664. /* Malloc may fail when setting the page-size, as there is an internal
  106665. ** buffer that the pager module resizes using sqlite3_realloc().
  106666. */
  106667. db->nextPagesize = sqlite3Atoi(zRight);
  106668. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  106669. sqlite3OomFault(db);
  106670. }
  106671. }
  106672. break;
  106673. }
  106674. /*
  106675. ** PRAGMA [schema.]secure_delete
  106676. ** PRAGMA [schema.]secure_delete=ON/OFF
  106677. **
  106678. ** The first form reports the current setting for the
  106679. ** secure_delete flag. The second form changes the secure_delete
  106680. ** flag setting and reports thenew value.
  106681. */
  106682. case PragTyp_SECURE_DELETE: {
  106683. Btree *pBt = pDb->pBt;
  106684. int b = -1;
  106685. assert( pBt!=0 );
  106686. if( zRight ){
  106687. b = sqlite3GetBoolean(zRight, 0);
  106688. }
  106689. if( pId2->n==0 && b>=0 ){
  106690. int ii;
  106691. for(ii=0; ii<db->nDb; ii++){
  106692. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  106693. }
  106694. }
  106695. b = sqlite3BtreeSecureDelete(pBt, b);
  106696. returnSingleInt(v, b);
  106697. break;
  106698. }
  106699. /*
  106700. ** PRAGMA [schema.]max_page_count
  106701. ** PRAGMA [schema.]max_page_count=N
  106702. **
  106703. ** The first form reports the current setting for the
  106704. ** maximum number of pages in the database file. The
  106705. ** second form attempts to change this setting. Both
  106706. ** forms return the current setting.
  106707. **
  106708. ** The absolute value of N is used. This is undocumented and might
  106709. ** change. The only purpose is to provide an easy way to test
  106710. ** the sqlite3AbsInt32() function.
  106711. **
  106712. ** PRAGMA [schema.]page_count
  106713. **
  106714. ** Return the number of pages in the specified database.
  106715. */
  106716. case PragTyp_PAGE_COUNT: {
  106717. int iReg;
  106718. sqlite3CodeVerifySchema(pParse, iDb);
  106719. iReg = ++pParse->nMem;
  106720. if( sqlite3Tolower(zLeft[0])=='p' ){
  106721. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  106722. }else{
  106723. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  106724. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  106725. }
  106726. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  106727. break;
  106728. }
  106729. /*
  106730. ** PRAGMA [schema.]locking_mode
  106731. ** PRAGMA [schema.]locking_mode = (normal|exclusive)
  106732. */
  106733. case PragTyp_LOCKING_MODE: {
  106734. const char *zRet = "normal";
  106735. int eMode = getLockingMode(zRight);
  106736. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  106737. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  106738. ** the current default locking mode (which may be different to
  106739. ** the locking-mode of the main database).
  106740. */
  106741. eMode = db->dfltLockMode;
  106742. }else{
  106743. Pager *pPager;
  106744. if( pId2->n==0 ){
  106745. /* This indicates that no database name was specified as part
  106746. ** of the PRAGMA command. In this case the locking-mode must be
  106747. ** set on all attached databases, as well as the main db file.
  106748. **
  106749. ** Also, the sqlite3.dfltLockMode variable is set so that
  106750. ** any subsequently attached databases also use the specified
  106751. ** locking mode.
  106752. */
  106753. int ii;
  106754. assert(pDb==&db->aDb[0]);
  106755. for(ii=2; ii<db->nDb; ii++){
  106756. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  106757. sqlite3PagerLockingMode(pPager, eMode);
  106758. }
  106759. db->dfltLockMode = (u8)eMode;
  106760. }
  106761. pPager = sqlite3BtreePager(pDb->pBt);
  106762. eMode = sqlite3PagerLockingMode(pPager, eMode);
  106763. }
  106764. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  106765. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  106766. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  106767. zRet = "exclusive";
  106768. }
  106769. returnSingleText(v, zRet);
  106770. break;
  106771. }
  106772. /*
  106773. ** PRAGMA [schema.]journal_mode
  106774. ** PRAGMA [schema.]journal_mode =
  106775. ** (delete|persist|off|truncate|memory|wal|off)
  106776. */
  106777. case PragTyp_JOURNAL_MODE: {
  106778. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  106779. int ii; /* Loop counter */
  106780. if( zRight==0 ){
  106781. /* If there is no "=MODE" part of the pragma, do a query for the
  106782. ** current mode */
  106783. eMode = PAGER_JOURNALMODE_QUERY;
  106784. }else{
  106785. const char *zMode;
  106786. int n = sqlite3Strlen30(zRight);
  106787. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  106788. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  106789. }
  106790. if( !zMode ){
  106791. /* If the "=MODE" part does not match any known journal mode,
  106792. ** then do a query */
  106793. eMode = PAGER_JOURNALMODE_QUERY;
  106794. }
  106795. }
  106796. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  106797. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  106798. iDb = 0;
  106799. pId2->n = 1;
  106800. }
  106801. for(ii=db->nDb-1; ii>=0; ii--){
  106802. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  106803. sqlite3VdbeUsesBtree(v, ii);
  106804. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  106805. }
  106806. }
  106807. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  106808. break;
  106809. }
  106810. /*
  106811. ** PRAGMA [schema.]journal_size_limit
  106812. ** PRAGMA [schema.]journal_size_limit=N
  106813. **
  106814. ** Get or set the size limit on rollback journal files.
  106815. */
  106816. case PragTyp_JOURNAL_SIZE_LIMIT: {
  106817. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  106818. i64 iLimit = -2;
  106819. if( zRight ){
  106820. sqlite3DecOrHexToI64(zRight, &iLimit);
  106821. if( iLimit<-1 ) iLimit = -1;
  106822. }
  106823. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  106824. returnSingleInt(v, iLimit);
  106825. break;
  106826. }
  106827. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  106828. /*
  106829. ** PRAGMA [schema.]auto_vacuum
  106830. ** PRAGMA [schema.]auto_vacuum=N
  106831. **
  106832. ** Get or set the value of the database 'auto-vacuum' parameter.
  106833. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  106834. */
  106835. #ifndef SQLITE_OMIT_AUTOVACUUM
  106836. case PragTyp_AUTO_VACUUM: {
  106837. Btree *pBt = pDb->pBt;
  106838. assert( pBt!=0 );
  106839. if( !zRight ){
  106840. returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
  106841. }else{
  106842. int eAuto = getAutoVacuum(zRight);
  106843. assert( eAuto>=0 && eAuto<=2 );
  106844. db->nextAutovac = (u8)eAuto;
  106845. /* Call SetAutoVacuum() to set initialize the internal auto and
  106846. ** incr-vacuum flags. This is required in case this connection
  106847. ** creates the database file. It is important that it is created
  106848. ** as an auto-vacuum capable db.
  106849. */
  106850. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  106851. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  106852. /* When setting the auto_vacuum mode to either "full" or
  106853. ** "incremental", write the value of meta[6] in the database
  106854. ** file. Before writing to meta[6], check that meta[3] indicates
  106855. ** that this really is an auto-vacuum capable database.
  106856. */
  106857. static const int iLn = VDBE_OFFSET_LINENO(2);
  106858. static const VdbeOpList setMeta6[] = {
  106859. { OP_Transaction, 0, 1, 0}, /* 0 */
  106860. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  106861. { OP_If, 1, 0, 0}, /* 2 */
  106862. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  106863. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */
  106864. };
  106865. VdbeOp *aOp;
  106866. int iAddr = sqlite3VdbeCurrentAddr(v);
  106867. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
  106868. aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
  106869. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  106870. aOp[0].p1 = iDb;
  106871. aOp[1].p1 = iDb;
  106872. aOp[2].p2 = iAddr+4;
  106873. aOp[4].p1 = iDb;
  106874. aOp[4].p3 = eAuto - 1;
  106875. sqlite3VdbeUsesBtree(v, iDb);
  106876. }
  106877. }
  106878. break;
  106879. }
  106880. #endif
  106881. /*
  106882. ** PRAGMA [schema.]incremental_vacuum(N)
  106883. **
  106884. ** Do N steps of incremental vacuuming on a database.
  106885. */
  106886. #ifndef SQLITE_OMIT_AUTOVACUUM
  106887. case PragTyp_INCREMENTAL_VACUUM: {
  106888. int iLimit, addr;
  106889. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  106890. iLimit = 0x7fffffff;
  106891. }
  106892. sqlite3BeginWriteOperation(pParse, 0, iDb);
  106893. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  106894. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
  106895. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  106896. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  106897. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
  106898. sqlite3VdbeJumpHere(v, addr);
  106899. break;
  106900. }
  106901. #endif
  106902. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  106903. /*
  106904. ** PRAGMA [schema.]cache_size
  106905. ** PRAGMA [schema.]cache_size=N
  106906. **
  106907. ** The first form reports the current local setting for the
  106908. ** page cache size. The second form sets the local
  106909. ** page cache size value. If N is positive then that is the
  106910. ** number of pages in the cache. If N is negative, then the
  106911. ** number of pages is adjusted so that the cache uses -N kibibytes
  106912. ** of memory.
  106913. */
  106914. case PragTyp_CACHE_SIZE: {
  106915. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  106916. if( !zRight ){
  106917. returnSingleInt(v, pDb->pSchema->cache_size);
  106918. }else{
  106919. int size = sqlite3Atoi(zRight);
  106920. pDb->pSchema->cache_size = size;
  106921. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  106922. }
  106923. break;
  106924. }
  106925. /*
  106926. ** PRAGMA [schema.]cache_spill
  106927. ** PRAGMA cache_spill=BOOLEAN
  106928. ** PRAGMA [schema.]cache_spill=N
  106929. **
  106930. ** The first form reports the current local setting for the
  106931. ** page cache spill size. The second form turns cache spill on
  106932. ** or off. When turnning cache spill on, the size is set to the
  106933. ** current cache_size. The third form sets a spill size that
  106934. ** may be different form the cache size.
  106935. ** If N is positive then that is the
  106936. ** number of pages in the cache. If N is negative, then the
  106937. ** number of pages is adjusted so that the cache uses -N kibibytes
  106938. ** of memory.
  106939. **
  106940. ** If the number of cache_spill pages is less then the number of
  106941. ** cache_size pages, no spilling occurs until the page count exceeds
  106942. ** the number of cache_size pages.
  106943. **
  106944. ** The cache_spill=BOOLEAN setting applies to all attached schemas,
  106945. ** not just the schema specified.
  106946. */
  106947. case PragTyp_CACHE_SPILL: {
  106948. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  106949. if( !zRight ){
  106950. returnSingleInt(v,
  106951. (db->flags & SQLITE_CacheSpill)==0 ? 0 :
  106952. sqlite3BtreeSetSpillSize(pDb->pBt,0));
  106953. }else{
  106954. int size = 1;
  106955. if( sqlite3GetInt32(zRight, &size) ){
  106956. sqlite3BtreeSetSpillSize(pDb->pBt, size);
  106957. }
  106958. if( sqlite3GetBoolean(zRight, size!=0) ){
  106959. db->flags |= SQLITE_CacheSpill;
  106960. }else{
  106961. db->flags &= ~SQLITE_CacheSpill;
  106962. }
  106963. setAllPagerFlags(db);
  106964. }
  106965. break;
  106966. }
  106967. /*
  106968. ** PRAGMA [schema.]mmap_size(N)
  106969. **
  106970. ** Used to set mapping size limit. The mapping size limit is
  106971. ** used to limit the aggregate size of all memory mapped regions of the
  106972. ** database file. If this parameter is set to zero, then memory mapping
  106973. ** is not used at all. If N is negative, then the default memory map
  106974. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  106975. ** The parameter N is measured in bytes.
  106976. **
  106977. ** This value is advisory. The underlying VFS is free to memory map
  106978. ** as little or as much as it wants. Except, if N is set to 0 then the
  106979. ** upper layers will never invoke the xFetch interfaces to the VFS.
  106980. */
  106981. case PragTyp_MMAP_SIZE: {
  106982. sqlite3_int64 sz;
  106983. #if SQLITE_MAX_MMAP_SIZE>0
  106984. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  106985. if( zRight ){
  106986. int ii;
  106987. sqlite3DecOrHexToI64(zRight, &sz);
  106988. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  106989. if( pId2->n==0 ) db->szMmap = sz;
  106990. for(ii=db->nDb-1; ii>=0; ii--){
  106991. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  106992. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  106993. }
  106994. }
  106995. }
  106996. sz = -1;
  106997. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  106998. #else
  106999. sz = 0;
  107000. rc = SQLITE_OK;
  107001. #endif
  107002. if( rc==SQLITE_OK ){
  107003. returnSingleInt(v, sz);
  107004. }else if( rc!=SQLITE_NOTFOUND ){
  107005. pParse->nErr++;
  107006. pParse->rc = rc;
  107007. }
  107008. break;
  107009. }
  107010. /*
  107011. ** PRAGMA temp_store
  107012. ** PRAGMA temp_store = "default"|"memory"|"file"
  107013. **
  107014. ** Return or set the local value of the temp_store flag. Changing
  107015. ** the local value does not make changes to the disk file and the default
  107016. ** value will be restored the next time the database is opened.
  107017. **
  107018. ** Note that it is possible for the library compile-time options to
  107019. ** override this setting
  107020. */
  107021. case PragTyp_TEMP_STORE: {
  107022. if( !zRight ){
  107023. returnSingleInt(v, db->temp_store);
  107024. }else{
  107025. changeTempStorage(pParse, zRight);
  107026. }
  107027. break;
  107028. }
  107029. /*
  107030. ** PRAGMA temp_store_directory
  107031. ** PRAGMA temp_store_directory = ""|"directory_name"
  107032. **
  107033. ** Return or set the local value of the temp_store_directory flag. Changing
  107034. ** the value sets a specific directory to be used for temporary files.
  107035. ** Setting to a null string reverts to the default temporary directory search.
  107036. ** If temporary directory is changed, then invalidateTempStorage.
  107037. **
  107038. */
  107039. case PragTyp_TEMP_STORE_DIRECTORY: {
  107040. if( !zRight ){
  107041. returnSingleText(v, sqlite3_temp_directory);
  107042. }else{
  107043. #ifndef SQLITE_OMIT_WSD
  107044. if( zRight[0] ){
  107045. int res;
  107046. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  107047. if( rc!=SQLITE_OK || res==0 ){
  107048. sqlite3ErrorMsg(pParse, "not a writable directory");
  107049. goto pragma_out;
  107050. }
  107051. }
  107052. if( SQLITE_TEMP_STORE==0
  107053. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  107054. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  107055. ){
  107056. invalidateTempStorage(pParse);
  107057. }
  107058. sqlite3_free(sqlite3_temp_directory);
  107059. if( zRight[0] ){
  107060. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  107061. }else{
  107062. sqlite3_temp_directory = 0;
  107063. }
  107064. #endif /* SQLITE_OMIT_WSD */
  107065. }
  107066. break;
  107067. }
  107068. #if SQLITE_OS_WIN
  107069. /*
  107070. ** PRAGMA data_store_directory
  107071. ** PRAGMA data_store_directory = ""|"directory_name"
  107072. **
  107073. ** Return or set the local value of the data_store_directory flag. Changing
  107074. ** the value sets a specific directory to be used for database files that
  107075. ** were specified with a relative pathname. Setting to a null string reverts
  107076. ** to the default database directory, which for database files specified with
  107077. ** a relative path will probably be based on the current directory for the
  107078. ** process. Database file specified with an absolute path are not impacted
  107079. ** by this setting, regardless of its value.
  107080. **
  107081. */
  107082. case PragTyp_DATA_STORE_DIRECTORY: {
  107083. if( !zRight ){
  107084. returnSingleText(v, sqlite3_data_directory);
  107085. }else{
  107086. #ifndef SQLITE_OMIT_WSD
  107087. if( zRight[0] ){
  107088. int res;
  107089. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  107090. if( rc!=SQLITE_OK || res==0 ){
  107091. sqlite3ErrorMsg(pParse, "not a writable directory");
  107092. goto pragma_out;
  107093. }
  107094. }
  107095. sqlite3_free(sqlite3_data_directory);
  107096. if( zRight[0] ){
  107097. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  107098. }else{
  107099. sqlite3_data_directory = 0;
  107100. }
  107101. #endif /* SQLITE_OMIT_WSD */
  107102. }
  107103. break;
  107104. }
  107105. #endif
  107106. #if SQLITE_ENABLE_LOCKING_STYLE
  107107. /*
  107108. ** PRAGMA [schema.]lock_proxy_file
  107109. ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
  107110. **
  107111. ** Return or set the value of the lock_proxy_file flag. Changing
  107112. ** the value sets a specific file to be used for database access locks.
  107113. **
  107114. */
  107115. case PragTyp_LOCK_PROXY_FILE: {
  107116. if( !zRight ){
  107117. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  107118. char *proxy_file_path = NULL;
  107119. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  107120. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  107121. &proxy_file_path);
  107122. returnSingleText(v, proxy_file_path);
  107123. }else{
  107124. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  107125. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  107126. int res;
  107127. if( zRight[0] ){
  107128. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  107129. zRight);
  107130. } else {
  107131. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  107132. NULL);
  107133. }
  107134. if( res!=SQLITE_OK ){
  107135. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  107136. goto pragma_out;
  107137. }
  107138. }
  107139. break;
  107140. }
  107141. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  107142. /*
  107143. ** PRAGMA [schema.]synchronous
  107144. ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
  107145. **
  107146. ** Return or set the local value of the synchronous flag. Changing
  107147. ** the local value does not make changes to the disk file and the
  107148. ** default value will be restored the next time the database is
  107149. ** opened.
  107150. */
  107151. case PragTyp_SYNCHRONOUS: {
  107152. if( !zRight ){
  107153. returnSingleInt(v, pDb->safety_level-1);
  107154. }else{
  107155. if( !db->autoCommit ){
  107156. sqlite3ErrorMsg(pParse,
  107157. "Safety level may not be changed inside a transaction");
  107158. }else if( iDb!=1 ){
  107159. int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
  107160. if( iLevel==0 ) iLevel = 1;
  107161. pDb->safety_level = iLevel;
  107162. pDb->bSyncSet = 1;
  107163. setAllPagerFlags(db);
  107164. }
  107165. }
  107166. break;
  107167. }
  107168. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  107169. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  107170. case PragTyp_FLAG: {
  107171. if( zRight==0 ){
  107172. setPragmaResultColumnNames(v, pPragma);
  107173. returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
  107174. }else{
  107175. int mask = pPragma->iArg; /* Mask of bits to set or clear. */
  107176. if( db->autoCommit==0 ){
  107177. /* Foreign key support may not be enabled or disabled while not
  107178. ** in auto-commit mode. */
  107179. mask &= ~(SQLITE_ForeignKeys);
  107180. }
  107181. #if SQLITE_USER_AUTHENTICATION
  107182. if( db->auth.authLevel==UAUTH_User ){
  107183. /* Do not allow non-admin users to modify the schema arbitrarily */
  107184. mask &= ~(SQLITE_WriteSchema);
  107185. }
  107186. #endif
  107187. if( sqlite3GetBoolean(zRight, 0) ){
  107188. db->flags |= mask;
  107189. }else{
  107190. db->flags &= ~mask;
  107191. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  107192. }
  107193. /* Many of the flag-pragmas modify the code generated by the SQL
  107194. ** compiler (eg. count_changes). So add an opcode to expire all
  107195. ** compiled SQL statements after modifying a pragma value.
  107196. */
  107197. sqlite3VdbeAddOp0(v, OP_Expire);
  107198. setAllPagerFlags(db);
  107199. }
  107200. break;
  107201. }
  107202. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  107203. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  107204. /*
  107205. ** PRAGMA table_info(<table>)
  107206. **
  107207. ** Return a single row for each column of the named table. The columns of
  107208. ** the returned data set are:
  107209. **
  107210. ** cid: Column id (numbered from left to right, starting at 0)
  107211. ** name: Column name
  107212. ** type: Column declaration type.
  107213. ** notnull: True if 'NOT NULL' is part of column declaration
  107214. ** dflt_value: The default value for the column, if any.
  107215. */
  107216. case PragTyp_TABLE_INFO: if( zRight ){
  107217. Table *pTab;
  107218. pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
  107219. if( pTab ){
  107220. int i, k;
  107221. int nHidden = 0;
  107222. Column *pCol;
  107223. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  107224. pParse->nMem = 6;
  107225. sqlite3CodeVerifySchema(pParse, iDb);
  107226. sqlite3ViewGetColumnNames(pParse, pTab);
  107227. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  107228. if( IsHiddenColumn(pCol) ){
  107229. nHidden++;
  107230. continue;
  107231. }
  107232. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  107233. k = 0;
  107234. }else if( pPk==0 ){
  107235. k = 1;
  107236. }else{
  107237. for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
  107238. }
  107239. assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
  107240. sqlite3VdbeMultiLoad(v, 1, "issisi",
  107241. i-nHidden,
  107242. pCol->zName,
  107243. sqlite3ColumnType(pCol,""),
  107244. pCol->notNull ? 1 : 0,
  107245. pCol->pDflt ? pCol->pDflt->u.zToken : 0,
  107246. k);
  107247. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  107248. }
  107249. }
  107250. }
  107251. break;
  107252. #ifdef SQLITE_DEBUG
  107253. case PragTyp_STATS: {
  107254. Index *pIdx;
  107255. HashElem *i;
  107256. pParse->nMem = 5;
  107257. sqlite3CodeVerifySchema(pParse, iDb);
  107258. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  107259. Table *pTab = sqliteHashData(i);
  107260. sqlite3VdbeMultiLoad(v, 1, "ssiii",
  107261. pTab->zName,
  107262. 0,
  107263. pTab->szTabRow,
  107264. pTab->nRowLogEst,
  107265. pTab->tabFlags);
  107266. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
  107267. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  107268. sqlite3VdbeMultiLoad(v, 2, "siii",
  107269. pIdx->zName,
  107270. pIdx->szIdxRow,
  107271. pIdx->aiRowLogEst[0],
  107272. pIdx->hasStat1);
  107273. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
  107274. }
  107275. }
  107276. }
  107277. break;
  107278. #endif
  107279. case PragTyp_INDEX_INFO: if( zRight ){
  107280. Index *pIdx;
  107281. Table *pTab;
  107282. pIdx = sqlite3FindIndex(db, zRight, zDb);
  107283. if( pIdx ){
  107284. int i;
  107285. int mx;
  107286. if( pPragma->iArg ){
  107287. /* PRAGMA index_xinfo (newer version with more rows and columns) */
  107288. mx = pIdx->nColumn;
  107289. pParse->nMem = 6;
  107290. }else{
  107291. /* PRAGMA index_info (legacy version) */
  107292. mx = pIdx->nKeyCol;
  107293. pParse->nMem = 3;
  107294. }
  107295. pTab = pIdx->pTable;
  107296. sqlite3CodeVerifySchema(pParse, iDb);
  107297. assert( pParse->nMem<=pPragma->nPragCName );
  107298. for(i=0; i<mx; i++){
  107299. i16 cnum = pIdx->aiColumn[i];
  107300. sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum,
  107301. cnum<0 ? 0 : pTab->aCol[cnum].zName);
  107302. if( pPragma->iArg ){
  107303. sqlite3VdbeMultiLoad(v, 4, "isi",
  107304. pIdx->aSortOrder[i],
  107305. pIdx->azColl[i],
  107306. i<pIdx->nKeyCol);
  107307. }
  107308. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
  107309. }
  107310. }
  107311. }
  107312. break;
  107313. case PragTyp_INDEX_LIST: if( zRight ){
  107314. Index *pIdx;
  107315. Table *pTab;
  107316. int i;
  107317. pTab = sqlite3FindTable(db, zRight, zDb);
  107318. if( pTab ){
  107319. pParse->nMem = 5;
  107320. sqlite3CodeVerifySchema(pParse, iDb);
  107321. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  107322. const char *azOrigin[] = { "c", "u", "pk" };
  107323. sqlite3VdbeMultiLoad(v, 1, "isisi",
  107324. i,
  107325. pIdx->zName,
  107326. IsUniqueIndex(pIdx),
  107327. azOrigin[pIdx->idxType],
  107328. pIdx->pPartIdxWhere!=0);
  107329. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
  107330. }
  107331. }
  107332. }
  107333. break;
  107334. case PragTyp_DATABASE_LIST: {
  107335. int i;
  107336. pParse->nMem = 3;
  107337. for(i=0; i<db->nDb; i++){
  107338. if( db->aDb[i].pBt==0 ) continue;
  107339. assert( db->aDb[i].zDbSName!=0 );
  107340. sqlite3VdbeMultiLoad(v, 1, "iss",
  107341. i,
  107342. db->aDb[i].zDbSName,
  107343. sqlite3BtreeGetFilename(db->aDb[i].pBt));
  107344. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  107345. }
  107346. }
  107347. break;
  107348. case PragTyp_COLLATION_LIST: {
  107349. int i = 0;
  107350. HashElem *p;
  107351. pParse->nMem = 2;
  107352. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  107353. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  107354. sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
  107355. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  107356. }
  107357. }
  107358. break;
  107359. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  107360. #ifndef SQLITE_OMIT_FOREIGN_KEY
  107361. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  107362. FKey *pFK;
  107363. Table *pTab;
  107364. pTab = sqlite3FindTable(db, zRight, zDb);
  107365. if( pTab ){
  107366. pFK = pTab->pFKey;
  107367. if( pFK ){
  107368. int i = 0;
  107369. pParse->nMem = 8;
  107370. sqlite3CodeVerifySchema(pParse, iDb);
  107371. while(pFK){
  107372. int j;
  107373. for(j=0; j<pFK->nCol; j++){
  107374. sqlite3VdbeMultiLoad(v, 1, "iissssss",
  107375. i,
  107376. j,
  107377. pFK->zTo,
  107378. pTab->aCol[pFK->aCol[j].iFrom].zName,
  107379. pFK->aCol[j].zCol,
  107380. actionName(pFK->aAction[1]), /* ON UPDATE */
  107381. actionName(pFK->aAction[0]), /* ON DELETE */
  107382. "NONE");
  107383. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  107384. }
  107385. ++i;
  107386. pFK = pFK->pNextFrom;
  107387. }
  107388. }
  107389. }
  107390. }
  107391. break;
  107392. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  107393. #ifndef SQLITE_OMIT_FOREIGN_KEY
  107394. #ifndef SQLITE_OMIT_TRIGGER
  107395. case PragTyp_FOREIGN_KEY_CHECK: {
  107396. FKey *pFK; /* A foreign key constraint */
  107397. Table *pTab; /* Child table contain "REFERENCES" keyword */
  107398. Table *pParent; /* Parent table that child points to */
  107399. Index *pIdx; /* Index in the parent table */
  107400. int i; /* Loop counter: Foreign key number for pTab */
  107401. int j; /* Loop counter: Field of the foreign key */
  107402. HashElem *k; /* Loop counter: Next table in schema */
  107403. int x; /* result variable */
  107404. int regResult; /* 3 registers to hold a result row */
  107405. int regKey; /* Register to hold key for checking the FK */
  107406. int regRow; /* Registers to hold a row from pTab */
  107407. int addrTop; /* Top of a loop checking foreign keys */
  107408. int addrOk; /* Jump here if the key is OK */
  107409. int *aiCols; /* child to parent column mapping */
  107410. regResult = pParse->nMem+1;
  107411. pParse->nMem += 4;
  107412. regKey = ++pParse->nMem;
  107413. regRow = ++pParse->nMem;
  107414. sqlite3CodeVerifySchema(pParse, iDb);
  107415. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  107416. while( k ){
  107417. if( zRight ){
  107418. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  107419. k = 0;
  107420. }else{
  107421. pTab = (Table*)sqliteHashData(k);
  107422. k = sqliteHashNext(k);
  107423. }
  107424. if( pTab==0 || pTab->pFKey==0 ) continue;
  107425. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  107426. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  107427. sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
  107428. sqlite3VdbeLoadString(v, regResult, pTab->zName);
  107429. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  107430. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  107431. if( pParent==0 ) continue;
  107432. pIdx = 0;
  107433. sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
  107434. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  107435. if( x==0 ){
  107436. if( pIdx==0 ){
  107437. sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
  107438. }else{
  107439. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
  107440. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  107441. }
  107442. }else{
  107443. k = 0;
  107444. break;
  107445. }
  107446. }
  107447. assert( pParse->nErr>0 || pFK==0 );
  107448. if( pFK ) break;
  107449. if( pParse->nTab<i ) pParse->nTab = i;
  107450. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
  107451. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  107452. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  107453. pIdx = 0;
  107454. aiCols = 0;
  107455. if( pParent ){
  107456. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  107457. assert( x==0 );
  107458. }
  107459. addrOk = sqlite3VdbeMakeLabel(v);
  107460. /* Generate code to read the child key values into registers
  107461. ** regRow..regRow+n. If any of the child key values are NULL, this
  107462. ** row cannot cause an FK violation. Jump directly to addrOk in
  107463. ** this case. */
  107464. for(j=0; j<pFK->nCol; j++){
  107465. int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
  107466. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
  107467. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
  107468. }
  107469. /* Generate code to query the parent index for a matching parent
  107470. ** key. If a match is found, jump to addrOk. */
  107471. if( pIdx ){
  107472. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
  107473. sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
  107474. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  107475. VdbeCoverage(v);
  107476. }else if( pParent ){
  107477. int jmp = sqlite3VdbeCurrentAddr(v)+2;
  107478. sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
  107479. sqlite3VdbeGoto(v, addrOk);
  107480. assert( pFK->nCol==1 );
  107481. }
  107482. /* Generate code to report an FK violation to the caller. */
  107483. if( HasRowid(pTab) ){
  107484. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  107485. }else{
  107486. sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
  107487. }
  107488. sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1);
  107489. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  107490. sqlite3VdbeResolveLabel(v, addrOk);
  107491. sqlite3DbFree(db, aiCols);
  107492. }
  107493. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
  107494. sqlite3VdbeJumpHere(v, addrTop);
  107495. }
  107496. }
  107497. break;
  107498. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  107499. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  107500. #ifndef NDEBUG
  107501. case PragTyp_PARSER_TRACE: {
  107502. if( zRight ){
  107503. if( sqlite3GetBoolean(zRight, 0) ){
  107504. sqlite3ParserTrace(stdout, "parser: ");
  107505. }else{
  107506. sqlite3ParserTrace(0, 0);
  107507. }
  107508. }
  107509. }
  107510. break;
  107511. #endif
  107512. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  107513. ** used will be case sensitive or not depending on the RHS.
  107514. */
  107515. case PragTyp_CASE_SENSITIVE_LIKE: {
  107516. if( zRight ){
  107517. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  107518. }
  107519. }
  107520. break;
  107521. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  107522. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  107523. #endif
  107524. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  107525. /* PRAGMA integrity_check
  107526. ** PRAGMA integrity_check(N)
  107527. ** PRAGMA quick_check
  107528. ** PRAGMA quick_check(N)
  107529. **
  107530. ** Verify the integrity of the database.
  107531. **
  107532. ** The "quick_check" is reduced version of
  107533. ** integrity_check designed to detect most database corruption
  107534. ** without the overhead of cross-checking indexes. Quick_check
  107535. ** is linear time wherease integrity_check is O(NlogN).
  107536. */
  107537. case PragTyp_INTEGRITY_CHECK: {
  107538. int i, j, addr, mxErr;
  107539. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  107540. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  107541. ** then iDb is set to the index of the database identified by <db>.
  107542. ** In this case, the integrity of database iDb only is verified by
  107543. ** the VDBE created below.
  107544. **
  107545. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  107546. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  107547. ** to -1 here, to indicate that the VDBE should verify the integrity
  107548. ** of all attached databases. */
  107549. assert( iDb>=0 );
  107550. assert( iDb==0 || pId2->z );
  107551. if( pId2->z==0 ) iDb = -1;
  107552. /* Initialize the VDBE program */
  107553. pParse->nMem = 6;
  107554. /* Set the maximum error count */
  107555. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  107556. if( zRight ){
  107557. sqlite3GetInt32(zRight, &mxErr);
  107558. if( mxErr<=0 ){
  107559. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  107560. }
  107561. }
  107562. sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
  107563. /* Do an integrity check on each database file */
  107564. for(i=0; i<db->nDb; i++){
  107565. HashElem *x;
  107566. Hash *pTbls;
  107567. int *aRoot;
  107568. int cnt = 0;
  107569. int mxIdx = 0;
  107570. int nIdx;
  107571. if( OMIT_TEMPDB && i==1 ) continue;
  107572. if( iDb>=0 && i!=iDb ) continue;
  107573. sqlite3CodeVerifySchema(pParse, i);
  107574. /* Do an integrity check of the B-Tree
  107575. **
  107576. ** Begin by finding the root pages numbers
  107577. ** for all tables and indices in the database.
  107578. */
  107579. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  107580. pTbls = &db->aDb[i].pSchema->tblHash;
  107581. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  107582. Table *pTab = sqliteHashData(x);
  107583. Index *pIdx;
  107584. if( HasRowid(pTab) ) cnt++;
  107585. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
  107586. if( nIdx>mxIdx ) mxIdx = nIdx;
  107587. }
  107588. aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
  107589. if( aRoot==0 ) break;
  107590. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  107591. Table *pTab = sqliteHashData(x);
  107592. Index *pIdx;
  107593. if( HasRowid(pTab) ) aRoot[cnt++] = pTab->tnum;
  107594. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  107595. aRoot[cnt++] = pIdx->tnum;
  107596. }
  107597. }
  107598. aRoot[cnt] = 0;
  107599. /* Make sure sufficient number of registers have been allocated */
  107600. pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
  107601. /* Do the b-tree integrity checks */
  107602. sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
  107603. sqlite3VdbeChangeP5(v, (u8)i);
  107604. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
  107605. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  107606. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
  107607. P4_DYNAMIC);
  107608. sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
  107609. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  107610. integrityCheckResultRow(v, 2);
  107611. sqlite3VdbeJumpHere(v, addr);
  107612. /* Make sure all the indices are constructed correctly.
  107613. */
  107614. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  107615. Table *pTab = sqliteHashData(x);
  107616. Index *pIdx, *pPk;
  107617. Index *pPrior = 0;
  107618. int loopTop;
  107619. int iDataCur, iIdxCur;
  107620. int r1 = -1;
  107621. if( pTab->tnum<1 ) continue; /* Skip VIEWs or VIRTUAL TABLEs */
  107622. if( pTab->pCheck==0
  107623. && (pTab->tabFlags & TF_HasNotNull)==0
  107624. && (pTab->pIndex==0 || isQuick)
  107625. ){
  107626. continue; /* No additional checks needed for this table */
  107627. }
  107628. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  107629. sqlite3ExprCacheClear(pParse);
  107630. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
  107631. 1, 0, &iDataCur, &iIdxCur);
  107632. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
  107633. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  107634. sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
  107635. }
  107636. assert( pParse->nMem>=8+j );
  107637. assert( sqlite3NoTempsInRange(pParse,1,7+j) );
  107638. sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
  107639. loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
  107640. /* Verify that all NOT NULL columns really are NOT NULL */
  107641. for(j=0; j<pTab->nCol; j++){
  107642. char *zErr;
  107643. int jmp2;
  107644. if( j==pTab->iPKey ) continue;
  107645. if( pTab->aCol[j].notNull==0 ) continue;
  107646. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
  107647. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  107648. jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
  107649. zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
  107650. pTab->aCol[j].zName);
  107651. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  107652. integrityCheckResultRow(v, 3);
  107653. sqlite3VdbeJumpHere(v, jmp2);
  107654. }
  107655. /* Verify CHECK constraints */
  107656. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  107657. ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
  107658. if( db->mallocFailed==0 ){
  107659. int addrCkFault = sqlite3VdbeMakeLabel(v);
  107660. int addrCkOk = sqlite3VdbeMakeLabel(v);
  107661. char *zErr;
  107662. int k;
  107663. pParse->iSelfTab = iDataCur;
  107664. sqlite3ExprCachePush(pParse);
  107665. for(k=pCheck->nExpr-1; k>0; k--){
  107666. sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
  107667. }
  107668. sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
  107669. SQLITE_JUMPIFNULL);
  107670. sqlite3VdbeResolveLabel(v, addrCkFault);
  107671. zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
  107672. pTab->zName);
  107673. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  107674. integrityCheckResultRow(v, 3);
  107675. sqlite3VdbeResolveLabel(v, addrCkOk);
  107676. sqlite3ExprCachePop(pParse);
  107677. }
  107678. sqlite3ExprListDelete(db, pCheck);
  107679. }
  107680. /* Validate index entries for the current row */
  107681. for(j=0, pIdx=pTab->pIndex; pIdx && !isQuick; pIdx=pIdx->pNext, j++){
  107682. int jmp2, jmp3, jmp4, jmp5;
  107683. int ckUniq = sqlite3VdbeMakeLabel(v);
  107684. if( pPk==pIdx ) continue;
  107685. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
  107686. pPrior, r1);
  107687. pPrior = pIdx;
  107688. sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */
  107689. /* Verify that an index entry exists for the current table row */
  107690. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
  107691. pIdx->nColumn); VdbeCoverage(v);
  107692. sqlite3VdbeLoadString(v, 3, "row ");
  107693. sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
  107694. sqlite3VdbeLoadString(v, 4, " missing from index ");
  107695. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  107696. jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
  107697. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  107698. jmp4 = integrityCheckResultRow(v, 3);
  107699. sqlite3VdbeJumpHere(v, jmp2);
  107700. /* For UNIQUE indexes, verify that only one entry exists with the
  107701. ** current key. The entry is unique if (1) any column is NULL
  107702. ** or (2) the next entry has a different key */
  107703. if( IsUniqueIndex(pIdx) ){
  107704. int uniqOk = sqlite3VdbeMakeLabel(v);
  107705. int jmp6;
  107706. int kk;
  107707. for(kk=0; kk<pIdx->nKeyCol; kk++){
  107708. int iCol = pIdx->aiColumn[kk];
  107709. assert( iCol!=XN_ROWID && iCol<pTab->nCol );
  107710. if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
  107711. sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
  107712. VdbeCoverage(v);
  107713. }
  107714. jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
  107715. sqlite3VdbeGoto(v, uniqOk);
  107716. sqlite3VdbeJumpHere(v, jmp6);
  107717. sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
  107718. pIdx->nKeyCol); VdbeCoverage(v);
  107719. sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
  107720. sqlite3VdbeGoto(v, jmp5);
  107721. sqlite3VdbeResolveLabel(v, uniqOk);
  107722. }
  107723. sqlite3VdbeJumpHere(v, jmp4);
  107724. sqlite3ResolvePartIdxLabel(pParse, jmp3);
  107725. }
  107726. sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
  107727. sqlite3VdbeJumpHere(v, loopTop-1);
  107728. #ifndef SQLITE_OMIT_BTREECOUNT
  107729. if( !isQuick ){
  107730. sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
  107731. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  107732. if( pPk==pIdx ) continue;
  107733. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
  107734. addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
  107735. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  107736. sqlite3VdbeLoadString(v, 3, pIdx->zName);
  107737. sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
  107738. integrityCheckResultRow(v, 7);
  107739. sqlite3VdbeJumpHere(v, addr);
  107740. }
  107741. }
  107742. #endif /* SQLITE_OMIT_BTREECOUNT */
  107743. }
  107744. }
  107745. {
  107746. static const int iLn = VDBE_OFFSET_LINENO(2);
  107747. static const VdbeOpList endCode[] = {
  107748. { OP_AddImm, 1, 0, 0}, /* 0 */
  107749. { OP_IfNotZero, 1, 4, 0}, /* 1 */
  107750. { OP_String8, 0, 3, 0}, /* 2 */
  107751. { OP_ResultRow, 3, 1, 0}, /* 3 */
  107752. };
  107753. VdbeOp *aOp;
  107754. aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
  107755. if( aOp ){
  107756. aOp[0].p2 = 1-mxErr;
  107757. aOp[2].p4type = P4_STATIC;
  107758. aOp[2].p4.z = "ok";
  107759. }
  107760. }
  107761. }
  107762. break;
  107763. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  107764. #ifndef SQLITE_OMIT_UTF16
  107765. /*
  107766. ** PRAGMA encoding
  107767. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  107768. **
  107769. ** In its first form, this pragma returns the encoding of the main
  107770. ** database. If the database is not initialized, it is initialized now.
  107771. **
  107772. ** The second form of this pragma is a no-op if the main database file
  107773. ** has not already been initialized. In this case it sets the default
  107774. ** encoding that will be used for the main database file if a new file
  107775. ** is created. If an existing main database file is opened, then the
  107776. ** default text encoding for the existing database is used.
  107777. **
  107778. ** In all cases new databases created using the ATTACH command are
  107779. ** created to use the same default text encoding as the main database. If
  107780. ** the main database has not been initialized and/or created when ATTACH
  107781. ** is executed, this is done before the ATTACH operation.
  107782. **
  107783. ** In the second form this pragma sets the text encoding to be used in
  107784. ** new database files created using this database handle. It is only
  107785. ** useful if invoked immediately after the main database i
  107786. */
  107787. case PragTyp_ENCODING: {
  107788. static const struct EncName {
  107789. char *zName;
  107790. u8 enc;
  107791. } encnames[] = {
  107792. { "UTF8", SQLITE_UTF8 },
  107793. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  107794. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  107795. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  107796. { "UTF16le", SQLITE_UTF16LE },
  107797. { "UTF16be", SQLITE_UTF16BE },
  107798. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  107799. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  107800. { 0, 0 }
  107801. };
  107802. const struct EncName *pEnc;
  107803. if( !zRight ){ /* "PRAGMA encoding" */
  107804. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  107805. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  107806. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  107807. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  107808. returnSingleText(v, encnames[ENC(pParse->db)].zName);
  107809. }else{ /* "PRAGMA encoding = XXX" */
  107810. /* Only change the value of sqlite.enc if the database handle is not
  107811. ** initialized. If the main database exists, the new sqlite.enc value
  107812. ** will be overwritten when the schema is next loaded. If it does not
  107813. ** already exists, it will be created to use the new encoding value.
  107814. */
  107815. if(
  107816. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  107817. DbHasProperty(db, 0, DB_Empty)
  107818. ){
  107819. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  107820. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  107821. SCHEMA_ENC(db) = ENC(db) =
  107822. pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  107823. break;
  107824. }
  107825. }
  107826. if( !pEnc->zName ){
  107827. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  107828. }
  107829. }
  107830. }
  107831. }
  107832. break;
  107833. #endif /* SQLITE_OMIT_UTF16 */
  107834. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  107835. /*
  107836. ** PRAGMA [schema.]schema_version
  107837. ** PRAGMA [schema.]schema_version = <integer>
  107838. **
  107839. ** PRAGMA [schema.]user_version
  107840. ** PRAGMA [schema.]user_version = <integer>
  107841. **
  107842. ** PRAGMA [schema.]freelist_count
  107843. **
  107844. ** PRAGMA [schema.]data_version
  107845. **
  107846. ** PRAGMA [schema.]application_id
  107847. ** PRAGMA [schema.]application_id = <integer>
  107848. **
  107849. ** The pragma's schema_version and user_version are used to set or get
  107850. ** the value of the schema-version and user-version, respectively. Both
  107851. ** the schema-version and the user-version are 32-bit signed integers
  107852. ** stored in the database header.
  107853. **
  107854. ** The schema-cookie is usually only manipulated internally by SQLite. It
  107855. ** is incremented by SQLite whenever the database schema is modified (by
  107856. ** creating or dropping a table or index). The schema version is used by
  107857. ** SQLite each time a query is executed to ensure that the internal cache
  107858. ** of the schema used when compiling the SQL query matches the schema of
  107859. ** the database against which the compiled query is actually executed.
  107860. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  107861. ** the schema-version is potentially dangerous and may lead to program
  107862. ** crashes or database corruption. Use with caution!
  107863. **
  107864. ** The user-version is not used internally by SQLite. It may be used by
  107865. ** applications for any purpose.
  107866. */
  107867. case PragTyp_HEADER_VALUE: {
  107868. int iCookie = pPragma->iArg; /* Which cookie to read or write */
  107869. sqlite3VdbeUsesBtree(v, iDb);
  107870. if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
  107871. /* Write the specified cookie value */
  107872. static const VdbeOpList setCookie[] = {
  107873. { OP_Transaction, 0, 1, 0}, /* 0 */
  107874. { OP_SetCookie, 0, 0, 0}, /* 1 */
  107875. };
  107876. VdbeOp *aOp;
  107877. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
  107878. aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
  107879. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  107880. aOp[0].p1 = iDb;
  107881. aOp[1].p1 = iDb;
  107882. aOp[1].p2 = iCookie;
  107883. aOp[1].p3 = sqlite3Atoi(zRight);
  107884. }else{
  107885. /* Read the specified cookie value */
  107886. static const VdbeOpList readCookie[] = {
  107887. { OP_Transaction, 0, 0, 0}, /* 0 */
  107888. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  107889. { OP_ResultRow, 1, 1, 0}
  107890. };
  107891. VdbeOp *aOp;
  107892. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
  107893. aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
  107894. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  107895. aOp[0].p1 = iDb;
  107896. aOp[1].p1 = iDb;
  107897. aOp[1].p3 = iCookie;
  107898. sqlite3VdbeReusable(v);
  107899. }
  107900. }
  107901. break;
  107902. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  107903. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  107904. /*
  107905. ** PRAGMA compile_options
  107906. **
  107907. ** Return the names of all compile-time options used in this build,
  107908. ** one option per row.
  107909. */
  107910. case PragTyp_COMPILE_OPTIONS: {
  107911. int i = 0;
  107912. const char *zOpt;
  107913. pParse->nMem = 1;
  107914. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  107915. sqlite3VdbeLoadString(v, 1, zOpt);
  107916. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  107917. }
  107918. sqlite3VdbeReusable(v);
  107919. }
  107920. break;
  107921. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  107922. #ifndef SQLITE_OMIT_WAL
  107923. /*
  107924. ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
  107925. **
  107926. ** Checkpoint the database.
  107927. */
  107928. case PragTyp_WAL_CHECKPOINT: {
  107929. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  107930. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  107931. if( zRight ){
  107932. if( sqlite3StrICmp(zRight, "full")==0 ){
  107933. eMode = SQLITE_CHECKPOINT_FULL;
  107934. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  107935. eMode = SQLITE_CHECKPOINT_RESTART;
  107936. }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
  107937. eMode = SQLITE_CHECKPOINT_TRUNCATE;
  107938. }
  107939. }
  107940. pParse->nMem = 3;
  107941. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  107942. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  107943. }
  107944. break;
  107945. /*
  107946. ** PRAGMA wal_autocheckpoint
  107947. ** PRAGMA wal_autocheckpoint = N
  107948. **
  107949. ** Configure a database connection to automatically checkpoint a database
  107950. ** after accumulating N frames in the log. Or query for the current value
  107951. ** of N.
  107952. */
  107953. case PragTyp_WAL_AUTOCHECKPOINT: {
  107954. if( zRight ){
  107955. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  107956. }
  107957. returnSingleInt(v,
  107958. db->xWalCallback==sqlite3WalDefaultHook ?
  107959. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  107960. }
  107961. break;
  107962. #endif
  107963. /*
  107964. ** PRAGMA shrink_memory
  107965. **
  107966. ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
  107967. ** connection on which it is invoked to free up as much memory as it
  107968. ** can, by calling sqlite3_db_release_memory().
  107969. */
  107970. case PragTyp_SHRINK_MEMORY: {
  107971. sqlite3_db_release_memory(db);
  107972. break;
  107973. }
  107974. /*
  107975. ** PRAGMA optimize
  107976. ** PRAGMA optimize(MASK)
  107977. ** PRAGMA schema.optimize
  107978. ** PRAGMA schema.optimize(MASK)
  107979. **
  107980. ** Attempt to optimize the database. All schemas are optimized in the first
  107981. ** two forms, and only the specified schema is optimized in the latter two.
  107982. **
  107983. ** The details of optimizations performed by this pragma are expected
  107984. ** to change and improve over time. Applications should anticipate that
  107985. ** this pragma will perform new optimizations in future releases.
  107986. **
  107987. ** The optional argument is a bitmask of optimizations to perform:
  107988. **
  107989. ** 0x0001 Debugging mode. Do not actually perform any optimizations
  107990. ** but instead return one line of text for each optimization
  107991. ** that would have been done. Off by default.
  107992. **
  107993. ** 0x0002 Run ANALYZE on tables that might benefit. On by default.
  107994. ** See below for additional information.
  107995. **
  107996. ** 0x0004 (Not yet implemented) Record usage and performance
  107997. ** information from the current session in the
  107998. ** database file so that it will be available to "optimize"
  107999. ** pragmas run by future database connections.
  108000. **
  108001. ** 0x0008 (Not yet implemented) Create indexes that might have
  108002. ** been helpful to recent queries
  108003. **
  108004. ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all ** of the optimizations listed above except Debug Mode, including new
  108005. ** optimizations that have not yet been invented. If new optimizations are
  108006. ** ever added that should be off by default, those off-by-default
  108007. ** optimizations will have bitmasks of 0x10000 or larger.
  108008. **
  108009. ** DETERMINATION OF WHEN TO RUN ANALYZE
  108010. **
  108011. ** In the current implementation, a table is analyzed if only if all of
  108012. ** the following are true:
  108013. **
  108014. ** (1) MASK bit 0x02 is set.
  108015. **
  108016. ** (2) The query planner used sqlite_stat1-style statistics for one or
  108017. ** more indexes of the table at some point during the lifetime of
  108018. ** the current connection.
  108019. **
  108020. ** (3) One or more indexes of the table are currently unanalyzed OR
  108021. ** the number of rows in the table has increased by 25 times or more
  108022. ** since the last time ANALYZE was run.
  108023. **
  108024. ** The rules for when tables are analyzed are likely to change in
  108025. ** future releases.
  108026. */
  108027. case PragTyp_OPTIMIZE: {
  108028. int iDbLast; /* Loop termination point for the schema loop */
  108029. int iTabCur; /* Cursor for a table whose size needs checking */
  108030. HashElem *k; /* Loop over tables of a schema */
  108031. Schema *pSchema; /* The current schema */
  108032. Table *pTab; /* A table in the schema */
  108033. Index *pIdx; /* An index of the table */
  108034. LogEst szThreshold; /* Size threshold above which reanalysis is needd */
  108035. char *zSubSql; /* SQL statement for the OP_SqlExec opcode */
  108036. u32 opMask; /* Mask of operations to perform */
  108037. if( zRight ){
  108038. opMask = (u32)sqlite3Atoi(zRight);
  108039. if( (opMask & 0x02)==0 ) break;
  108040. }else{
  108041. opMask = 0xfffe;
  108042. }
  108043. iTabCur = pParse->nTab++;
  108044. for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
  108045. if( iDb==1 ) continue;
  108046. sqlite3CodeVerifySchema(pParse, iDb);
  108047. pSchema = db->aDb[iDb].pSchema;
  108048. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  108049. pTab = (Table*)sqliteHashData(k);
  108050. /* If table pTab has not been used in a way that would benefit from
  108051. ** having analysis statistics during the current session, then skip it.
  108052. ** This also has the effect of skipping virtual tables and views */
  108053. if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
  108054. /* Reanalyze if the table is 25 times larger than the last analysis */
  108055. szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
  108056. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  108057. if( !pIdx->hasStat1 ){
  108058. szThreshold = 0; /* Always analyze if any index lacks statistics */
  108059. break;
  108060. }
  108061. }
  108062. if( szThreshold ){
  108063. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  108064. sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
  108065. sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
  108066. VdbeCoverage(v);
  108067. }
  108068. zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
  108069. db->aDb[iDb].zDbSName, pTab->zName);
  108070. if( opMask & 0x01 ){
  108071. int r1 = sqlite3GetTempReg(pParse);
  108072. sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
  108073. sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
  108074. }else{
  108075. sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
  108076. }
  108077. }
  108078. }
  108079. sqlite3VdbeAddOp0(v, OP_Expire);
  108080. break;
  108081. }
  108082. /*
  108083. ** PRAGMA busy_timeout
  108084. ** PRAGMA busy_timeout = N
  108085. **
  108086. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  108087. ** if one is set. If no busy handler or a different busy handler is set
  108088. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  108089. ** disables the timeout.
  108090. */
  108091. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  108092. assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
  108093. if( zRight ){
  108094. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  108095. }
  108096. returnSingleInt(v, db->busyTimeout);
  108097. break;
  108098. }
  108099. /*
  108100. ** PRAGMA soft_heap_limit
  108101. ** PRAGMA soft_heap_limit = N
  108102. **
  108103. ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
  108104. ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
  108105. ** specified and is a non-negative integer.
  108106. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
  108107. ** returns the same integer that would be returned by the
  108108. ** sqlite3_soft_heap_limit64(-1) C-language function.
  108109. */
  108110. case PragTyp_SOFT_HEAP_LIMIT: {
  108111. sqlite3_int64 N;
  108112. if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
  108113. sqlite3_soft_heap_limit64(N);
  108114. }
  108115. returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
  108116. break;
  108117. }
  108118. /*
  108119. ** PRAGMA threads
  108120. ** PRAGMA threads = N
  108121. **
  108122. ** Configure the maximum number of worker threads. Return the new
  108123. ** maximum, which might be less than requested.
  108124. */
  108125. case PragTyp_THREADS: {
  108126. sqlite3_int64 N;
  108127. if( zRight
  108128. && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
  108129. && N>=0
  108130. ){
  108131. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
  108132. }
  108133. returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
  108134. break;
  108135. }
  108136. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  108137. /*
  108138. ** Report the current state of file logs for all databases
  108139. */
  108140. case PragTyp_LOCK_STATUS: {
  108141. static const char *const azLockName[] = {
  108142. "unlocked", "shared", "reserved", "pending", "exclusive"
  108143. };
  108144. int i;
  108145. pParse->nMem = 2;
  108146. for(i=0; i<db->nDb; i++){
  108147. Btree *pBt;
  108148. const char *zState = "unknown";
  108149. int j;
  108150. if( db->aDb[i].zDbSName==0 ) continue;
  108151. pBt = db->aDb[i].pBt;
  108152. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  108153. zState = "closed";
  108154. }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
  108155. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  108156. zState = azLockName[j];
  108157. }
  108158. sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
  108159. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  108160. }
  108161. break;
  108162. }
  108163. #endif
  108164. #ifdef SQLITE_HAS_CODEC
  108165. case PragTyp_KEY: {
  108166. if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  108167. break;
  108168. }
  108169. case PragTyp_REKEY: {
  108170. if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  108171. break;
  108172. }
  108173. case PragTyp_HEXKEY: {
  108174. if( zRight ){
  108175. u8 iByte;
  108176. int i;
  108177. char zKey[40];
  108178. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  108179. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  108180. if( (i&1)!=0 ) zKey[i/2] = iByte;
  108181. }
  108182. if( (zLeft[3] & 0xf)==0xb ){
  108183. sqlite3_key_v2(db, zDb, zKey, i/2);
  108184. }else{
  108185. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  108186. }
  108187. }
  108188. break;
  108189. }
  108190. #endif
  108191. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  108192. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  108193. #ifdef SQLITE_HAS_CODEC
  108194. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  108195. sqlite3_activate_see(&zRight[4]);
  108196. }
  108197. #endif
  108198. #ifdef SQLITE_ENABLE_CEROD
  108199. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  108200. sqlite3_activate_cerod(&zRight[6]);
  108201. }
  108202. #endif
  108203. }
  108204. break;
  108205. #endif
  108206. } /* End of the PRAGMA switch */
  108207. /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
  108208. ** purpose is to execute assert() statements to verify that if the
  108209. ** PragFlg_NoColumns1 flag is set and the caller specified an argument
  108210. ** to the PRAGMA, the implementation has not added any OP_ResultRow
  108211. ** instructions to the VM. */
  108212. if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
  108213. sqlite3VdbeVerifyNoResultRow(v);
  108214. }
  108215. pragma_out:
  108216. sqlite3DbFree(db, zLeft);
  108217. sqlite3DbFree(db, zRight);
  108218. }
  108219. #ifndef SQLITE_OMIT_VIRTUALTABLE
  108220. /*****************************************************************************
  108221. ** Implementation of an eponymous virtual table that runs a pragma.
  108222. **
  108223. */
  108224. typedef struct PragmaVtab PragmaVtab;
  108225. typedef struct PragmaVtabCursor PragmaVtabCursor;
  108226. struct PragmaVtab {
  108227. sqlite3_vtab base; /* Base class. Must be first */
  108228. sqlite3 *db; /* The database connection to which it belongs */
  108229. const PragmaName *pName; /* Name of the pragma */
  108230. u8 nHidden; /* Number of hidden columns */
  108231. u8 iHidden; /* Index of the first hidden column */
  108232. };
  108233. struct PragmaVtabCursor {
  108234. sqlite3_vtab_cursor base; /* Base class. Must be first */
  108235. sqlite3_stmt *pPragma; /* The pragma statement to run */
  108236. sqlite_int64 iRowid; /* Current rowid */
  108237. char *azArg[2]; /* Value of the argument and schema */
  108238. };
  108239. /*
  108240. ** Pragma virtual table module xConnect method.
  108241. */
  108242. static int pragmaVtabConnect(
  108243. sqlite3 *db,
  108244. void *pAux,
  108245. int argc, const char *const*argv,
  108246. sqlite3_vtab **ppVtab,
  108247. char **pzErr
  108248. ){
  108249. const PragmaName *pPragma = (const PragmaName*)pAux;
  108250. PragmaVtab *pTab = 0;
  108251. int rc;
  108252. int i, j;
  108253. char cSep = '(';
  108254. StrAccum acc;
  108255. char zBuf[200];
  108256. UNUSED_PARAMETER(argc);
  108257. UNUSED_PARAMETER(argv);
  108258. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  108259. sqlite3StrAccumAppendAll(&acc, "CREATE TABLE x");
  108260. for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
  108261. sqlite3XPrintf(&acc, "%c\"%s\"", cSep, pragCName[j]);
  108262. cSep = ',';
  108263. }
  108264. if( i==0 ){
  108265. sqlite3XPrintf(&acc, "(\"%s\"", pPragma->zName);
  108266. cSep = ',';
  108267. i++;
  108268. }
  108269. j = 0;
  108270. if( pPragma->mPragFlg & PragFlg_Result1 ){
  108271. sqlite3StrAccumAppendAll(&acc, ",arg HIDDEN");
  108272. j++;
  108273. }
  108274. if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
  108275. sqlite3StrAccumAppendAll(&acc, ",schema HIDDEN");
  108276. j++;
  108277. }
  108278. sqlite3StrAccumAppend(&acc, ")", 1);
  108279. sqlite3StrAccumFinish(&acc);
  108280. assert( strlen(zBuf) < sizeof(zBuf)-1 );
  108281. rc = sqlite3_declare_vtab(db, zBuf);
  108282. if( rc==SQLITE_OK ){
  108283. pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
  108284. if( pTab==0 ){
  108285. rc = SQLITE_NOMEM;
  108286. }else{
  108287. memset(pTab, 0, sizeof(PragmaVtab));
  108288. pTab->pName = pPragma;
  108289. pTab->db = db;
  108290. pTab->iHidden = i;
  108291. pTab->nHidden = j;
  108292. }
  108293. }else{
  108294. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  108295. }
  108296. *ppVtab = (sqlite3_vtab*)pTab;
  108297. return rc;
  108298. }
  108299. /*
  108300. ** Pragma virtual table module xDisconnect method.
  108301. */
  108302. static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
  108303. PragmaVtab *pTab = (PragmaVtab*)pVtab;
  108304. sqlite3_free(pTab);
  108305. return SQLITE_OK;
  108306. }
  108307. /* Figure out the best index to use to search a pragma virtual table.
  108308. **
  108309. ** There are not really any index choices. But we want to encourage the
  108310. ** query planner to give == constraints on as many hidden parameters as
  108311. ** possible, and especially on the first hidden parameter. So return a
  108312. ** high cost if hidden parameters are unconstrained.
  108313. */
  108314. static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  108315. PragmaVtab *pTab = (PragmaVtab*)tab;
  108316. const struct sqlite3_index_constraint *pConstraint;
  108317. int i, j;
  108318. int seen[2];
  108319. pIdxInfo->estimatedCost = (double)1;
  108320. if( pTab->nHidden==0 ){ return SQLITE_OK; }
  108321. pConstraint = pIdxInfo->aConstraint;
  108322. seen[0] = 0;
  108323. seen[1] = 0;
  108324. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  108325. if( pConstraint->usable==0 ) continue;
  108326. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  108327. if( pConstraint->iColumn < pTab->iHidden ) continue;
  108328. j = pConstraint->iColumn - pTab->iHidden;
  108329. assert( j < 2 );
  108330. seen[j] = i+1;
  108331. }
  108332. if( seen[0]==0 ){
  108333. pIdxInfo->estimatedCost = (double)2147483647;
  108334. pIdxInfo->estimatedRows = 2147483647;
  108335. return SQLITE_OK;
  108336. }
  108337. j = seen[0]-1;
  108338. pIdxInfo->aConstraintUsage[j].argvIndex = 1;
  108339. pIdxInfo->aConstraintUsage[j].omit = 1;
  108340. if( seen[1]==0 ) return SQLITE_OK;
  108341. pIdxInfo->estimatedCost = (double)20;
  108342. pIdxInfo->estimatedRows = 20;
  108343. j = seen[1]-1;
  108344. pIdxInfo->aConstraintUsage[j].argvIndex = 2;
  108345. pIdxInfo->aConstraintUsage[j].omit = 1;
  108346. return SQLITE_OK;
  108347. }
  108348. /* Create a new cursor for the pragma virtual table */
  108349. static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
  108350. PragmaVtabCursor *pCsr;
  108351. pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
  108352. if( pCsr==0 ) return SQLITE_NOMEM;
  108353. memset(pCsr, 0, sizeof(PragmaVtabCursor));
  108354. pCsr->base.pVtab = pVtab;
  108355. *ppCursor = &pCsr->base;
  108356. return SQLITE_OK;
  108357. }
  108358. /* Clear all content from pragma virtual table cursor. */
  108359. static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
  108360. int i;
  108361. sqlite3_finalize(pCsr->pPragma);
  108362. pCsr->pPragma = 0;
  108363. for(i=0; i<ArraySize(pCsr->azArg); i++){
  108364. sqlite3_free(pCsr->azArg[i]);
  108365. pCsr->azArg[i] = 0;
  108366. }
  108367. }
  108368. /* Close a pragma virtual table cursor */
  108369. static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
  108370. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
  108371. pragmaVtabCursorClear(pCsr);
  108372. sqlite3_free(pCsr);
  108373. return SQLITE_OK;
  108374. }
  108375. /* Advance the pragma virtual table cursor to the next row */
  108376. static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
  108377. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  108378. int rc = SQLITE_OK;
  108379. /* Increment the xRowid value */
  108380. pCsr->iRowid++;
  108381. assert( pCsr->pPragma );
  108382. if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
  108383. rc = sqlite3_finalize(pCsr->pPragma);
  108384. pCsr->pPragma = 0;
  108385. pragmaVtabCursorClear(pCsr);
  108386. }
  108387. return rc;
  108388. }
  108389. /*
  108390. ** Pragma virtual table module xFilter method.
  108391. */
  108392. static int pragmaVtabFilter(
  108393. sqlite3_vtab_cursor *pVtabCursor,
  108394. int idxNum, const char *idxStr,
  108395. int argc, sqlite3_value **argv
  108396. ){
  108397. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  108398. PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
  108399. int rc;
  108400. int i, j;
  108401. StrAccum acc;
  108402. char *zSql;
  108403. UNUSED_PARAMETER(idxNum);
  108404. UNUSED_PARAMETER(idxStr);
  108405. pragmaVtabCursorClear(pCsr);
  108406. j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
  108407. for(i=0; i<argc; i++, j++){
  108408. assert( j<ArraySize(pCsr->azArg) );
  108409. pCsr->azArg[j] = sqlite3_mprintf("%s", sqlite3_value_text(argv[i]));
  108410. if( pCsr->azArg[j]==0 ){
  108411. return SQLITE_NOMEM;
  108412. }
  108413. }
  108414. sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
  108415. sqlite3StrAccumAppendAll(&acc, "PRAGMA ");
  108416. if( pCsr->azArg[1] ){
  108417. sqlite3XPrintf(&acc, "%Q.", pCsr->azArg[1]);
  108418. }
  108419. sqlite3StrAccumAppendAll(&acc, pTab->pName->zName);
  108420. if( pCsr->azArg[0] ){
  108421. sqlite3XPrintf(&acc, "=%Q", pCsr->azArg[0]);
  108422. }
  108423. zSql = sqlite3StrAccumFinish(&acc);
  108424. if( zSql==0 ) return SQLITE_NOMEM;
  108425. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
  108426. sqlite3_free(zSql);
  108427. if( rc!=SQLITE_OK ){
  108428. pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
  108429. return rc;
  108430. }
  108431. return pragmaVtabNext(pVtabCursor);
  108432. }
  108433. /*
  108434. ** Pragma virtual table module xEof method.
  108435. */
  108436. static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
  108437. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  108438. return (pCsr->pPragma==0);
  108439. }
  108440. /* The xColumn method simply returns the corresponding column from
  108441. ** the PRAGMA.
  108442. */
  108443. static int pragmaVtabColumn(
  108444. sqlite3_vtab_cursor *pVtabCursor,
  108445. sqlite3_context *ctx,
  108446. int i
  108447. ){
  108448. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  108449. PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
  108450. if( i<pTab->iHidden ){
  108451. sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
  108452. }else{
  108453. sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
  108454. }
  108455. return SQLITE_OK;
  108456. }
  108457. /*
  108458. ** Pragma virtual table module xRowid method.
  108459. */
  108460. static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
  108461. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  108462. *p = pCsr->iRowid;
  108463. return SQLITE_OK;
  108464. }
  108465. /* The pragma virtual table object */
  108466. static const sqlite3_module pragmaVtabModule = {
  108467. 0, /* iVersion */
  108468. 0, /* xCreate - create a table */
  108469. pragmaVtabConnect, /* xConnect - connect to an existing table */
  108470. pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */
  108471. pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */
  108472. 0, /* xDestroy - Drop a table */
  108473. pragmaVtabOpen, /* xOpen - open a cursor */
  108474. pragmaVtabClose, /* xClose - close a cursor */
  108475. pragmaVtabFilter, /* xFilter - configure scan constraints */
  108476. pragmaVtabNext, /* xNext - advance a cursor */
  108477. pragmaVtabEof, /* xEof */
  108478. pragmaVtabColumn, /* xColumn - read data */
  108479. pragmaVtabRowid, /* xRowid - read data */
  108480. 0, /* xUpdate - write data */
  108481. 0, /* xBegin - begin transaction */
  108482. 0, /* xSync - sync transaction */
  108483. 0, /* xCommit - commit transaction */
  108484. 0, /* xRollback - rollback transaction */
  108485. 0, /* xFindFunction - function overloading */
  108486. 0, /* xRename - rename the table */
  108487. 0, /* xSavepoint */
  108488. 0, /* xRelease */
  108489. 0 /* xRollbackTo */
  108490. };
  108491. /*
  108492. ** Check to see if zTabName is really the name of a pragma. If it is,
  108493. ** then register an eponymous virtual table for that pragma and return
  108494. ** a pointer to the Module object for the new virtual table.
  108495. */
  108496. SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
  108497. const PragmaName *pName;
  108498. assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
  108499. pName = pragmaLocate(zName+7);
  108500. if( pName==0 ) return 0;
  108501. if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
  108502. assert( sqlite3HashFind(&db->aModule, zName)==0 );
  108503. return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
  108504. }
  108505. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  108506. #endif /* SQLITE_OMIT_PRAGMA */
  108507. /************** End of pragma.c **********************************************/
  108508. /************** Begin file prepare.c *****************************************/
  108509. /*
  108510. ** 2005 May 25
  108511. **
  108512. ** The author disclaims copyright to this source code. In place of
  108513. ** a legal notice, here is a blessing:
  108514. **
  108515. ** May you do good and not evil.
  108516. ** May you find forgiveness for yourself and forgive others.
  108517. ** May you share freely, never taking more than you give.
  108518. **
  108519. *************************************************************************
  108520. ** This file contains the implementation of the sqlite3_prepare()
  108521. ** interface, and routines that contribute to loading the database schema
  108522. ** from disk.
  108523. */
  108524. /* #include "sqliteInt.h" */
  108525. /*
  108526. ** Fill the InitData structure with an error message that indicates
  108527. ** that the database is corrupt.
  108528. */
  108529. static void corruptSchema(
  108530. InitData *pData, /* Initialization context */
  108531. const char *zObj, /* Object being parsed at the point of error */
  108532. const char *zExtra /* Error information */
  108533. ){
  108534. sqlite3 *db = pData->db;
  108535. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  108536. char *z;
  108537. if( zObj==0 ) zObj = "?";
  108538. z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
  108539. if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
  108540. sqlite3DbFree(db, *pData->pzErrMsg);
  108541. *pData->pzErrMsg = z;
  108542. }
  108543. pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT;
  108544. }
  108545. /*
  108546. ** This is the callback routine for the code that initializes the
  108547. ** database. See sqlite3Init() below for additional information.
  108548. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  108549. **
  108550. ** Each callback contains the following information:
  108551. **
  108552. ** argv[0] = name of thing being created
  108553. ** argv[1] = root page number for table or index. 0 for trigger or view.
  108554. ** argv[2] = SQL text for the CREATE statement.
  108555. **
  108556. */
  108557. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  108558. InitData *pData = (InitData*)pInit;
  108559. sqlite3 *db = pData->db;
  108560. int iDb = pData->iDb;
  108561. assert( argc==3 );
  108562. UNUSED_PARAMETER2(NotUsed, argc);
  108563. assert( sqlite3_mutex_held(db->mutex) );
  108564. DbClearProperty(db, iDb, DB_Empty);
  108565. if( db->mallocFailed ){
  108566. corruptSchema(pData, argv[0], 0);
  108567. return 1;
  108568. }
  108569. assert( iDb>=0 && iDb<db->nDb );
  108570. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  108571. if( argv[1]==0 ){
  108572. corruptSchema(pData, argv[0], 0);
  108573. }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
  108574. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  108575. ** But because db->init.busy is set to 1, no VDBE code is generated
  108576. ** or executed. All the parser does is build the internal data
  108577. ** structures that describe the table, index, or view.
  108578. */
  108579. int rc;
  108580. u8 saved_iDb = db->init.iDb;
  108581. sqlite3_stmt *pStmt;
  108582. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  108583. assert( db->init.busy );
  108584. db->init.iDb = iDb;
  108585. db->init.newTnum = sqlite3Atoi(argv[1]);
  108586. db->init.orphanTrigger = 0;
  108587. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  108588. rc = db->errCode;
  108589. assert( (rc&0xFF)==(rcp&0xFF) );
  108590. db->init.iDb = saved_iDb;
  108591. assert( saved_iDb==0 || (db->flags & SQLITE_Vacuum)!=0 );
  108592. if( SQLITE_OK!=rc ){
  108593. if( db->init.orphanTrigger ){
  108594. assert( iDb==1 );
  108595. }else{
  108596. pData->rc = rc;
  108597. if( rc==SQLITE_NOMEM ){
  108598. sqlite3OomFault(db);
  108599. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  108600. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  108601. }
  108602. }
  108603. }
  108604. sqlite3_finalize(pStmt);
  108605. }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
  108606. corruptSchema(pData, argv[0], 0);
  108607. }else{
  108608. /* If the SQL column is blank it means this is an index that
  108609. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  108610. ** constraint for a CREATE TABLE. The index should have already
  108611. ** been created when we processed the CREATE TABLE. All we have
  108612. ** to do here is record the root page number for that index.
  108613. */
  108614. Index *pIndex;
  108615. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName);
  108616. if( pIndex==0 ){
  108617. /* This can occur if there exists an index on a TEMP table which
  108618. ** has the same name as another index on a permanent index. Since
  108619. ** the permanent table is hidden by the TEMP table, we can also
  108620. ** safely ignore the index on the permanent table.
  108621. */
  108622. /* Do Nothing */;
  108623. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  108624. corruptSchema(pData, argv[0], "invalid rootpage");
  108625. }
  108626. }
  108627. return 0;
  108628. }
  108629. /*
  108630. ** Attempt to read the database schema and initialize internal
  108631. ** data structures for a single database file. The index of the
  108632. ** database file is given by iDb. iDb==0 is used for the main
  108633. ** database. iDb==1 should never be used. iDb>=2 is used for
  108634. ** auxiliary databases. Return one of the SQLITE_ error codes to
  108635. ** indicate success or failure.
  108636. */
  108637. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  108638. int rc;
  108639. int i;
  108640. #ifndef SQLITE_OMIT_DEPRECATED
  108641. int size;
  108642. #endif
  108643. Db *pDb;
  108644. char const *azArg[4];
  108645. int meta[5];
  108646. InitData initData;
  108647. const char *zMasterName;
  108648. int openedTransaction = 0;
  108649. assert( iDb>=0 && iDb<db->nDb );
  108650. assert( db->aDb[iDb].pSchema );
  108651. assert( sqlite3_mutex_held(db->mutex) );
  108652. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  108653. /* Construct the in-memory representation schema tables (sqlite_master or
  108654. ** sqlite_temp_master) by invoking the parser directly. The appropriate
  108655. ** table name will be inserted automatically by the parser so we can just
  108656. ** use the abbreviation "x" here. The parser will also automatically tag
  108657. ** the schema table as read-only. */
  108658. azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
  108659. azArg[1] = "1";
  108660. azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
  108661. "rootpage integer,sql text)";
  108662. azArg[3] = 0;
  108663. initData.db = db;
  108664. initData.iDb = iDb;
  108665. initData.rc = SQLITE_OK;
  108666. initData.pzErrMsg = pzErrMsg;
  108667. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  108668. if( initData.rc ){
  108669. rc = initData.rc;
  108670. goto error_out;
  108671. }
  108672. /* Create a cursor to hold the database open
  108673. */
  108674. pDb = &db->aDb[iDb];
  108675. if( pDb->pBt==0 ){
  108676. if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
  108677. DbSetProperty(db, 1, DB_SchemaLoaded);
  108678. }
  108679. return SQLITE_OK;
  108680. }
  108681. /* If there is not already a read-only (or read-write) transaction opened
  108682. ** on the b-tree database, open one now. If a transaction is opened, it
  108683. ** will be closed before this function returns. */
  108684. sqlite3BtreeEnter(pDb->pBt);
  108685. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  108686. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  108687. if( rc!=SQLITE_OK ){
  108688. sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
  108689. goto initone_error_out;
  108690. }
  108691. openedTransaction = 1;
  108692. }
  108693. /* Get the database meta information.
  108694. **
  108695. ** Meta values are as follows:
  108696. ** meta[0] Schema cookie. Changes with each schema change.
  108697. ** meta[1] File format of schema layer.
  108698. ** meta[2] Size of the page cache.
  108699. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  108700. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  108701. ** meta[5] User version
  108702. ** meta[6] Incremental vacuum mode
  108703. ** meta[7] unused
  108704. ** meta[8] unused
  108705. ** meta[9] unused
  108706. **
  108707. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  108708. ** the possible values of meta[4].
  108709. */
  108710. for(i=0; i<ArraySize(meta); i++){
  108711. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  108712. }
  108713. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  108714. /* If opening a non-empty database, check the text encoding. For the
  108715. ** main database, set sqlite3.enc to the encoding of the main database.
  108716. ** For an attached db, it is an error if the encoding is not the same
  108717. ** as sqlite3.enc.
  108718. */
  108719. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  108720. if( iDb==0 ){
  108721. #ifndef SQLITE_OMIT_UTF16
  108722. u8 encoding;
  108723. /* If opening the main database, set ENC(db). */
  108724. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  108725. if( encoding==0 ) encoding = SQLITE_UTF8;
  108726. ENC(db) = encoding;
  108727. #else
  108728. ENC(db) = SQLITE_UTF8;
  108729. #endif
  108730. }else{
  108731. /* If opening an attached database, the encoding much match ENC(db) */
  108732. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  108733. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  108734. " text encoding as main database");
  108735. rc = SQLITE_ERROR;
  108736. goto initone_error_out;
  108737. }
  108738. }
  108739. }else{
  108740. DbSetProperty(db, iDb, DB_Empty);
  108741. }
  108742. pDb->pSchema->enc = ENC(db);
  108743. if( pDb->pSchema->cache_size==0 ){
  108744. #ifndef SQLITE_OMIT_DEPRECATED
  108745. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  108746. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  108747. pDb->pSchema->cache_size = size;
  108748. #else
  108749. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  108750. #endif
  108751. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  108752. }
  108753. /*
  108754. ** file_format==1 Version 3.0.0.
  108755. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  108756. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  108757. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  108758. */
  108759. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  108760. if( pDb->pSchema->file_format==0 ){
  108761. pDb->pSchema->file_format = 1;
  108762. }
  108763. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  108764. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  108765. rc = SQLITE_ERROR;
  108766. goto initone_error_out;
  108767. }
  108768. /* Ticket #2804: When we open a database in the newer file format,
  108769. ** clear the legacy_file_format pragma flag so that a VACUUM will
  108770. ** not downgrade the database and thus invalidate any descending
  108771. ** indices that the user might have created.
  108772. */
  108773. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  108774. db->flags &= ~SQLITE_LegacyFileFmt;
  108775. }
  108776. /* Read the schema information out of the schema tables
  108777. */
  108778. assert( db->init.busy );
  108779. {
  108780. char *zSql;
  108781. zSql = sqlite3MPrintf(db,
  108782. "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
  108783. db->aDb[iDb].zDbSName, zMasterName);
  108784. #ifndef SQLITE_OMIT_AUTHORIZATION
  108785. {
  108786. sqlite3_xauth xAuth;
  108787. xAuth = db->xAuth;
  108788. db->xAuth = 0;
  108789. #endif
  108790. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  108791. #ifndef SQLITE_OMIT_AUTHORIZATION
  108792. db->xAuth = xAuth;
  108793. }
  108794. #endif
  108795. if( rc==SQLITE_OK ) rc = initData.rc;
  108796. sqlite3DbFree(db, zSql);
  108797. #ifndef SQLITE_OMIT_ANALYZE
  108798. if( rc==SQLITE_OK ){
  108799. sqlite3AnalysisLoad(db, iDb);
  108800. }
  108801. #endif
  108802. }
  108803. if( db->mallocFailed ){
  108804. rc = SQLITE_NOMEM_BKPT;
  108805. sqlite3ResetAllSchemasOfConnection(db);
  108806. }
  108807. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  108808. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  108809. ** the schema loaded, even if errors occurred. In this situation the
  108810. ** current sqlite3_prepare() operation will fail, but the following one
  108811. ** will attempt to compile the supplied statement against whatever subset
  108812. ** of the schema was loaded before the error occurred. The primary
  108813. ** purpose of this is to allow access to the sqlite_master table
  108814. ** even when its contents have been corrupted.
  108815. */
  108816. DbSetProperty(db, iDb, DB_SchemaLoaded);
  108817. rc = SQLITE_OK;
  108818. }
  108819. /* Jump here for an error that occurs after successfully allocating
  108820. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  108821. ** before that point, jump to error_out.
  108822. */
  108823. initone_error_out:
  108824. if( openedTransaction ){
  108825. sqlite3BtreeCommit(pDb->pBt);
  108826. }
  108827. sqlite3BtreeLeave(pDb->pBt);
  108828. error_out:
  108829. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  108830. sqlite3OomFault(db);
  108831. }
  108832. return rc;
  108833. }
  108834. /*
  108835. ** Initialize all database files - the main database file, the file
  108836. ** used to store temporary tables, and any additional database files
  108837. ** created using ATTACH statements. Return a success code. If an
  108838. ** error occurs, write an error message into *pzErrMsg.
  108839. **
  108840. ** After a database is initialized, the DB_SchemaLoaded bit is set
  108841. ** bit is set in the flags field of the Db structure. If the database
  108842. ** file was of zero-length, then the DB_Empty flag is also set.
  108843. */
  108844. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  108845. int i, rc;
  108846. int commit_internal = !(db->flags&SQLITE_InternChanges);
  108847. assert( sqlite3_mutex_held(db->mutex) );
  108848. assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
  108849. assert( db->init.busy==0 );
  108850. rc = SQLITE_OK;
  108851. db->init.busy = 1;
  108852. ENC(db) = SCHEMA_ENC(db);
  108853. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  108854. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  108855. rc = sqlite3InitOne(db, i, pzErrMsg);
  108856. if( rc ){
  108857. sqlite3ResetOneSchema(db, i);
  108858. }
  108859. }
  108860. /* Once all the other databases have been initialized, load the schema
  108861. ** for the TEMP database. This is loaded last, as the TEMP database
  108862. ** schema may contain references to objects in other databases.
  108863. */
  108864. #ifndef SQLITE_OMIT_TEMPDB
  108865. assert( db->nDb>1 );
  108866. if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  108867. rc = sqlite3InitOne(db, 1, pzErrMsg);
  108868. if( rc ){
  108869. sqlite3ResetOneSchema(db, 1);
  108870. }
  108871. }
  108872. #endif
  108873. db->init.busy = 0;
  108874. if( rc==SQLITE_OK && commit_internal ){
  108875. sqlite3CommitInternalChanges(db);
  108876. }
  108877. return rc;
  108878. }
  108879. /*
  108880. ** This routine is a no-op if the database schema is already initialized.
  108881. ** Otherwise, the schema is loaded. An error code is returned.
  108882. */
  108883. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  108884. int rc = SQLITE_OK;
  108885. sqlite3 *db = pParse->db;
  108886. assert( sqlite3_mutex_held(db->mutex) );
  108887. if( !db->init.busy ){
  108888. rc = sqlite3Init(db, &pParse->zErrMsg);
  108889. }
  108890. if( rc!=SQLITE_OK ){
  108891. pParse->rc = rc;
  108892. pParse->nErr++;
  108893. }
  108894. return rc;
  108895. }
  108896. /*
  108897. ** Check schema cookies in all databases. If any cookie is out
  108898. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  108899. ** make no changes to pParse->rc.
  108900. */
  108901. static void schemaIsValid(Parse *pParse){
  108902. sqlite3 *db = pParse->db;
  108903. int iDb;
  108904. int rc;
  108905. int cookie;
  108906. assert( pParse->checkSchema );
  108907. assert( sqlite3_mutex_held(db->mutex) );
  108908. for(iDb=0; iDb<db->nDb; iDb++){
  108909. int openedTransaction = 0; /* True if a transaction is opened */
  108910. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  108911. if( pBt==0 ) continue;
  108912. /* If there is not already a read-only (or read-write) transaction opened
  108913. ** on the b-tree database, open one now. If a transaction is opened, it
  108914. ** will be closed immediately after reading the meta-value. */
  108915. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  108916. rc = sqlite3BtreeBeginTrans(pBt, 0);
  108917. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  108918. sqlite3OomFault(db);
  108919. }
  108920. if( rc!=SQLITE_OK ) return;
  108921. openedTransaction = 1;
  108922. }
  108923. /* Read the schema cookie from the database. If it does not match the
  108924. ** value stored as part of the in-memory schema representation,
  108925. ** set Parse.rc to SQLITE_SCHEMA. */
  108926. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  108927. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  108928. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  108929. sqlite3ResetOneSchema(db, iDb);
  108930. pParse->rc = SQLITE_SCHEMA;
  108931. }
  108932. /* Close the transaction, if one was opened. */
  108933. if( openedTransaction ){
  108934. sqlite3BtreeCommit(pBt);
  108935. }
  108936. }
  108937. }
  108938. /*
  108939. ** Convert a schema pointer into the iDb index that indicates
  108940. ** which database file in db->aDb[] the schema refers to.
  108941. **
  108942. ** If the same database is attached more than once, the first
  108943. ** attached database is returned.
  108944. */
  108945. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  108946. int i = -1000000;
  108947. /* If pSchema is NULL, then return -1000000. This happens when code in
  108948. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  108949. ** created by a sub-select). In this case the return value of this
  108950. ** function should never be used.
  108951. **
  108952. ** We return -1000000 instead of the more usual -1 simply because using
  108953. ** -1000000 as the incorrect index into db->aDb[] is much
  108954. ** more likely to cause a segfault than -1 (of course there are assert()
  108955. ** statements too, but it never hurts to play the odds).
  108956. */
  108957. assert( sqlite3_mutex_held(db->mutex) );
  108958. if( pSchema ){
  108959. for(i=0; ALWAYS(i<db->nDb); i++){
  108960. if( db->aDb[i].pSchema==pSchema ){
  108961. break;
  108962. }
  108963. }
  108964. assert( i>=0 && i<db->nDb );
  108965. }
  108966. return i;
  108967. }
  108968. /*
  108969. ** Free all memory allocations in the pParse object
  108970. */
  108971. SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
  108972. if( pParse ){
  108973. sqlite3 *db = pParse->db;
  108974. sqlite3DbFree(db, pParse->aLabel);
  108975. sqlite3ExprListDelete(db, pParse->pConstExpr);
  108976. if( db ){
  108977. assert( db->lookaside.bDisable >= pParse->disableLookaside );
  108978. db->lookaside.bDisable -= pParse->disableLookaside;
  108979. }
  108980. pParse->disableLookaside = 0;
  108981. }
  108982. }
  108983. /*
  108984. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  108985. */
  108986. static int sqlite3Prepare(
  108987. sqlite3 *db, /* Database handle. */
  108988. const char *zSql, /* UTF-8 encoded SQL statement. */
  108989. int nBytes, /* Length of zSql in bytes. */
  108990. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  108991. Vdbe *pReprepare, /* VM being reprepared */
  108992. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  108993. const char **pzTail /* OUT: End of parsed string */
  108994. ){
  108995. char *zErrMsg = 0; /* Error message */
  108996. int rc = SQLITE_OK; /* Result code */
  108997. int i; /* Loop counter */
  108998. Parse sParse; /* Parsing context */
  108999. memset(&sParse, 0, PARSE_HDR_SZ);
  109000. memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
  109001. sParse.pReprepare = pReprepare;
  109002. assert( ppStmt && *ppStmt==0 );
  109003. /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
  109004. assert( sqlite3_mutex_held(db->mutex) );
  109005. /* Check to verify that it is possible to get a read lock on all
  109006. ** database schemas. The inability to get a read lock indicates that
  109007. ** some other database connection is holding a write-lock, which in
  109008. ** turn means that the other connection has made uncommitted changes
  109009. ** to the schema.
  109010. **
  109011. ** Were we to proceed and prepare the statement against the uncommitted
  109012. ** schema changes and if those schema changes are subsequently rolled
  109013. ** back and different changes are made in their place, then when this
  109014. ** prepared statement goes to run the schema cookie would fail to detect
  109015. ** the schema change. Disaster would follow.
  109016. **
  109017. ** This thread is currently holding mutexes on all Btrees (because
  109018. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  109019. ** is not possible for another thread to start a new schema change
  109020. ** while this routine is running. Hence, we do not need to hold
  109021. ** locks on the schema, we just need to make sure nobody else is
  109022. ** holding them.
  109023. **
  109024. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  109025. ** but it does *not* override schema lock detection, so this all still
  109026. ** works even if READ_UNCOMMITTED is set.
  109027. */
  109028. for(i=0; i<db->nDb; i++) {
  109029. Btree *pBt = db->aDb[i].pBt;
  109030. if( pBt ){
  109031. assert( sqlite3BtreeHoldsMutex(pBt) );
  109032. rc = sqlite3BtreeSchemaLocked(pBt);
  109033. if( rc ){
  109034. const char *zDb = db->aDb[i].zDbSName;
  109035. sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
  109036. testcase( db->flags & SQLITE_ReadUncommitted );
  109037. goto end_prepare;
  109038. }
  109039. }
  109040. }
  109041. sqlite3VtabUnlockList(db);
  109042. sParse.db = db;
  109043. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  109044. char *zSqlCopy;
  109045. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  109046. testcase( nBytes==mxLen );
  109047. testcase( nBytes==mxLen+1 );
  109048. if( nBytes>mxLen ){
  109049. sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
  109050. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  109051. goto end_prepare;
  109052. }
  109053. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  109054. if( zSqlCopy ){
  109055. sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
  109056. sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
  109057. sqlite3DbFree(db, zSqlCopy);
  109058. }else{
  109059. sParse.zTail = &zSql[nBytes];
  109060. }
  109061. }else{
  109062. sqlite3RunParser(&sParse, zSql, &zErrMsg);
  109063. }
  109064. assert( 0==sParse.nQueryLoop );
  109065. if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
  109066. if( sParse.checkSchema ){
  109067. schemaIsValid(&sParse);
  109068. }
  109069. if( db->mallocFailed ){
  109070. sParse.rc = SQLITE_NOMEM_BKPT;
  109071. }
  109072. if( pzTail ){
  109073. *pzTail = sParse.zTail;
  109074. }
  109075. rc = sParse.rc;
  109076. #ifndef SQLITE_OMIT_EXPLAIN
  109077. if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
  109078. static const char * const azColName[] = {
  109079. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  109080. "selectid", "order", "from", "detail"
  109081. };
  109082. int iFirst, mx;
  109083. if( sParse.explain==2 ){
  109084. sqlite3VdbeSetNumCols(sParse.pVdbe, 4);
  109085. iFirst = 8;
  109086. mx = 12;
  109087. }else{
  109088. sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
  109089. iFirst = 0;
  109090. mx = 8;
  109091. }
  109092. for(i=iFirst; i<mx; i++){
  109093. sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME,
  109094. azColName[i], SQLITE_STATIC);
  109095. }
  109096. }
  109097. #endif
  109098. if( db->init.busy==0 ){
  109099. Vdbe *pVdbe = sParse.pVdbe;
  109100. sqlite3VdbeSetSql(pVdbe, zSql, (int)(sParse.zTail-zSql), saveSqlFlag);
  109101. }
  109102. if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  109103. sqlite3VdbeFinalize(sParse.pVdbe);
  109104. assert(!(*ppStmt));
  109105. }else{
  109106. *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
  109107. }
  109108. if( zErrMsg ){
  109109. sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
  109110. sqlite3DbFree(db, zErrMsg);
  109111. }else{
  109112. sqlite3Error(db, rc);
  109113. }
  109114. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  109115. while( sParse.pTriggerPrg ){
  109116. TriggerPrg *pT = sParse.pTriggerPrg;
  109117. sParse.pTriggerPrg = pT->pNext;
  109118. sqlite3DbFree(db, pT);
  109119. }
  109120. end_prepare:
  109121. sqlite3ParserReset(&sParse);
  109122. rc = sqlite3ApiExit(db, rc);
  109123. assert( (rc&db->errMask)==rc );
  109124. return rc;
  109125. }
  109126. static int sqlite3LockAndPrepare(
  109127. sqlite3 *db, /* Database handle. */
  109128. const char *zSql, /* UTF-8 encoded SQL statement. */
  109129. int nBytes, /* Length of zSql in bytes. */
  109130. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  109131. Vdbe *pOld, /* VM being reprepared */
  109132. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  109133. const char **pzTail /* OUT: End of parsed string */
  109134. ){
  109135. int rc;
  109136. #ifdef SQLITE_ENABLE_API_ARMOR
  109137. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  109138. #endif
  109139. *ppStmt = 0;
  109140. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  109141. return SQLITE_MISUSE_BKPT;
  109142. }
  109143. sqlite3_mutex_enter(db->mutex);
  109144. sqlite3BtreeEnterAll(db);
  109145. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  109146. if( rc==SQLITE_SCHEMA ){
  109147. sqlite3_finalize(*ppStmt);
  109148. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  109149. }
  109150. sqlite3BtreeLeaveAll(db);
  109151. sqlite3_mutex_leave(db->mutex);
  109152. assert( rc==SQLITE_OK || *ppStmt==0 );
  109153. return rc;
  109154. }
  109155. /*
  109156. ** Rerun the compilation of a statement after a schema change.
  109157. **
  109158. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  109159. ** if the statement cannot be recompiled because another connection has
  109160. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  109161. ** occurs, return SQLITE_SCHEMA.
  109162. */
  109163. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  109164. int rc;
  109165. sqlite3_stmt *pNew;
  109166. const char *zSql;
  109167. sqlite3 *db;
  109168. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  109169. zSql = sqlite3_sql((sqlite3_stmt *)p);
  109170. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  109171. db = sqlite3VdbeDb(p);
  109172. assert( sqlite3_mutex_held(db->mutex) );
  109173. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  109174. if( rc ){
  109175. if( rc==SQLITE_NOMEM ){
  109176. sqlite3OomFault(db);
  109177. }
  109178. assert( pNew==0 );
  109179. return rc;
  109180. }else{
  109181. assert( pNew!=0 );
  109182. }
  109183. sqlite3VdbeSwap((Vdbe*)pNew, p);
  109184. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  109185. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  109186. sqlite3VdbeFinalize((Vdbe*)pNew);
  109187. return SQLITE_OK;
  109188. }
  109189. /*
  109190. ** Two versions of the official API. Legacy and new use. In the legacy
  109191. ** version, the original SQL text is not saved in the prepared statement
  109192. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  109193. ** sqlite3_step(). In the new version, the original SQL text is retained
  109194. ** and the statement is automatically recompiled if an schema change
  109195. ** occurs.
  109196. */
  109197. SQLITE_API int sqlite3_prepare(
  109198. sqlite3 *db, /* Database handle. */
  109199. const char *zSql, /* UTF-8 encoded SQL statement. */
  109200. int nBytes, /* Length of zSql in bytes. */
  109201. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  109202. const char **pzTail /* OUT: End of parsed string */
  109203. ){
  109204. int rc;
  109205. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  109206. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  109207. return rc;
  109208. }
  109209. SQLITE_API int sqlite3_prepare_v2(
  109210. sqlite3 *db, /* Database handle. */
  109211. const char *zSql, /* UTF-8 encoded SQL statement. */
  109212. int nBytes, /* Length of zSql in bytes. */
  109213. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  109214. const char **pzTail /* OUT: End of parsed string */
  109215. ){
  109216. int rc;
  109217. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  109218. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  109219. return rc;
  109220. }
  109221. #ifndef SQLITE_OMIT_UTF16
  109222. /*
  109223. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  109224. */
  109225. static int sqlite3Prepare16(
  109226. sqlite3 *db, /* Database handle. */
  109227. const void *zSql, /* UTF-16 encoded SQL statement. */
  109228. int nBytes, /* Length of zSql in bytes. */
  109229. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  109230. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  109231. const void **pzTail /* OUT: End of parsed string */
  109232. ){
  109233. /* This function currently works by first transforming the UTF-16
  109234. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  109235. ** tricky bit is figuring out the pointer to return in *pzTail.
  109236. */
  109237. char *zSql8;
  109238. const char *zTail8 = 0;
  109239. int rc = SQLITE_OK;
  109240. #ifdef SQLITE_ENABLE_API_ARMOR
  109241. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  109242. #endif
  109243. *ppStmt = 0;
  109244. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  109245. return SQLITE_MISUSE_BKPT;
  109246. }
  109247. if( nBytes>=0 ){
  109248. int sz;
  109249. const char *z = (const char*)zSql;
  109250. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  109251. nBytes = sz;
  109252. }
  109253. sqlite3_mutex_enter(db->mutex);
  109254. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  109255. if( zSql8 ){
  109256. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  109257. }
  109258. if( zTail8 && pzTail ){
  109259. /* If sqlite3_prepare returns a tail pointer, we calculate the
  109260. ** equivalent pointer into the UTF-16 string by counting the unicode
  109261. ** characters between zSql8 and zTail8, and then returning a pointer
  109262. ** the same number of characters into the UTF-16 string.
  109263. */
  109264. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  109265. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  109266. }
  109267. sqlite3DbFree(db, zSql8);
  109268. rc = sqlite3ApiExit(db, rc);
  109269. sqlite3_mutex_leave(db->mutex);
  109270. return rc;
  109271. }
  109272. /*
  109273. ** Two versions of the official API. Legacy and new use. In the legacy
  109274. ** version, the original SQL text is not saved in the prepared statement
  109275. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  109276. ** sqlite3_step(). In the new version, the original SQL text is retained
  109277. ** and the statement is automatically recompiled if an schema change
  109278. ** occurs.
  109279. */
  109280. SQLITE_API int sqlite3_prepare16(
  109281. sqlite3 *db, /* Database handle. */
  109282. const void *zSql, /* UTF-16 encoded SQL statement. */
  109283. int nBytes, /* Length of zSql in bytes. */
  109284. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  109285. const void **pzTail /* OUT: End of parsed string */
  109286. ){
  109287. int rc;
  109288. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  109289. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  109290. return rc;
  109291. }
  109292. SQLITE_API int sqlite3_prepare16_v2(
  109293. sqlite3 *db, /* Database handle. */
  109294. const void *zSql, /* UTF-16 encoded SQL statement. */
  109295. int nBytes, /* Length of zSql in bytes. */
  109296. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  109297. const void **pzTail /* OUT: End of parsed string */
  109298. ){
  109299. int rc;
  109300. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  109301. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  109302. return rc;
  109303. }
  109304. #endif /* SQLITE_OMIT_UTF16 */
  109305. /************** End of prepare.c *********************************************/
  109306. /************** Begin file select.c ******************************************/
  109307. /*
  109308. ** 2001 September 15
  109309. **
  109310. ** The author disclaims copyright to this source code. In place of
  109311. ** a legal notice, here is a blessing:
  109312. **
  109313. ** May you do good and not evil.
  109314. ** May you find forgiveness for yourself and forgive others.
  109315. ** May you share freely, never taking more than you give.
  109316. **
  109317. *************************************************************************
  109318. ** This file contains C code routines that are called by the parser
  109319. ** to handle SELECT statements in SQLite.
  109320. */
  109321. /* #include "sqliteInt.h" */
  109322. /*
  109323. ** Trace output macros
  109324. */
  109325. #if SELECTTRACE_ENABLED
  109326. /***/ int sqlite3SelectTrace = 0;
  109327. # define SELECTTRACE(K,P,S,X) \
  109328. if(sqlite3SelectTrace&(K)) \
  109329. sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
  109330. (S)->zSelName,(S)),\
  109331. sqlite3DebugPrintf X
  109332. #else
  109333. # define SELECTTRACE(K,P,S,X)
  109334. #endif
  109335. /*
  109336. ** An instance of the following object is used to record information about
  109337. ** how to process the DISTINCT keyword, to simplify passing that information
  109338. ** into the selectInnerLoop() routine.
  109339. */
  109340. typedef struct DistinctCtx DistinctCtx;
  109341. struct DistinctCtx {
  109342. u8 isTnct; /* True if the DISTINCT keyword is present */
  109343. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  109344. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  109345. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  109346. };
  109347. /*
  109348. ** An instance of the following object is used to record information about
  109349. ** the ORDER BY (or GROUP BY) clause of query is being coded.
  109350. */
  109351. typedef struct SortCtx SortCtx;
  109352. struct SortCtx {
  109353. ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
  109354. int nOBSat; /* Number of ORDER BY terms satisfied by indices */
  109355. int iECursor; /* Cursor number for the sorter */
  109356. int regReturn; /* Register holding block-output return address */
  109357. int labelBkOut; /* Start label for the block-output subroutine */
  109358. int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
  109359. int labelDone; /* Jump here when done, ex: LIMIT reached */
  109360. u8 sortFlags; /* Zero or more SORTFLAG_* bits */
  109361. u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */
  109362. };
  109363. #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
  109364. /*
  109365. ** Delete all the content of a Select structure. Deallocate the structure
  109366. ** itself only if bFree is true.
  109367. */
  109368. static void clearSelect(sqlite3 *db, Select *p, int bFree){
  109369. while( p ){
  109370. Select *pPrior = p->pPrior;
  109371. sqlite3ExprListDelete(db, p->pEList);
  109372. sqlite3SrcListDelete(db, p->pSrc);
  109373. sqlite3ExprDelete(db, p->pWhere);
  109374. sqlite3ExprListDelete(db, p->pGroupBy);
  109375. sqlite3ExprDelete(db, p->pHaving);
  109376. sqlite3ExprListDelete(db, p->pOrderBy);
  109377. sqlite3ExprDelete(db, p->pLimit);
  109378. sqlite3ExprDelete(db, p->pOffset);
  109379. if( p->pWith ) sqlite3WithDelete(db, p->pWith);
  109380. if( bFree ) sqlite3DbFreeNN(db, p);
  109381. p = pPrior;
  109382. bFree = 1;
  109383. }
  109384. }
  109385. /*
  109386. ** Initialize a SelectDest structure.
  109387. */
  109388. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  109389. pDest->eDest = (u8)eDest;
  109390. pDest->iSDParm = iParm;
  109391. pDest->zAffSdst = 0;
  109392. pDest->iSdst = 0;
  109393. pDest->nSdst = 0;
  109394. }
  109395. /*
  109396. ** Allocate a new Select structure and return a pointer to that
  109397. ** structure.
  109398. */
  109399. SQLITE_PRIVATE Select *sqlite3SelectNew(
  109400. Parse *pParse, /* Parsing context */
  109401. ExprList *pEList, /* which columns to include in the result */
  109402. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  109403. Expr *pWhere, /* the WHERE clause */
  109404. ExprList *pGroupBy, /* the GROUP BY clause */
  109405. Expr *pHaving, /* the HAVING clause */
  109406. ExprList *pOrderBy, /* the ORDER BY clause */
  109407. u32 selFlags, /* Flag parameters, such as SF_Distinct */
  109408. Expr *pLimit, /* LIMIT value. NULL means not used */
  109409. Expr *pOffset /* OFFSET value. NULL means no offset */
  109410. ){
  109411. Select *pNew;
  109412. Select standin;
  109413. pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
  109414. if( pNew==0 ){
  109415. assert( pParse->db->mallocFailed );
  109416. pNew = &standin;
  109417. }
  109418. if( pEList==0 ){
  109419. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(pParse->db,TK_ASTERISK,0));
  109420. }
  109421. pNew->pEList = pEList;
  109422. pNew->op = TK_SELECT;
  109423. pNew->selFlags = selFlags;
  109424. pNew->iLimit = 0;
  109425. pNew->iOffset = 0;
  109426. #if SELECTTRACE_ENABLED
  109427. pNew->zSelName[0] = 0;
  109428. #endif
  109429. pNew->addrOpenEphm[0] = -1;
  109430. pNew->addrOpenEphm[1] = -1;
  109431. pNew->nSelectRow = 0;
  109432. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
  109433. pNew->pSrc = pSrc;
  109434. pNew->pWhere = pWhere;
  109435. pNew->pGroupBy = pGroupBy;
  109436. pNew->pHaving = pHaving;
  109437. pNew->pOrderBy = pOrderBy;
  109438. pNew->pPrior = 0;
  109439. pNew->pNext = 0;
  109440. pNew->pLimit = pLimit;
  109441. pNew->pOffset = pOffset;
  109442. pNew->pWith = 0;
  109443. assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || pParse->db->mallocFailed!=0 );
  109444. if( pParse->db->mallocFailed ) {
  109445. clearSelect(pParse->db, pNew, pNew!=&standin);
  109446. pNew = 0;
  109447. }else{
  109448. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  109449. }
  109450. assert( pNew!=&standin );
  109451. return pNew;
  109452. }
  109453. #if SELECTTRACE_ENABLED
  109454. /*
  109455. ** Set the name of a Select object
  109456. */
  109457. SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
  109458. if( p && zName ){
  109459. sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
  109460. }
  109461. }
  109462. #endif
  109463. /*
  109464. ** Delete the given Select structure and all of its substructures.
  109465. */
  109466. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  109467. if( p ) clearSelect(db, p, 1);
  109468. }
  109469. /*
  109470. ** Return a pointer to the right-most SELECT statement in a compound.
  109471. */
  109472. static Select *findRightmost(Select *p){
  109473. while( p->pNext ) p = p->pNext;
  109474. return p;
  109475. }
  109476. /*
  109477. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  109478. ** type of join. Return an integer constant that expresses that type
  109479. ** in terms of the following bit values:
  109480. **
  109481. ** JT_INNER
  109482. ** JT_CROSS
  109483. ** JT_OUTER
  109484. ** JT_NATURAL
  109485. ** JT_LEFT
  109486. ** JT_RIGHT
  109487. **
  109488. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  109489. **
  109490. ** If an illegal or unsupported join type is seen, then still return
  109491. ** a join type, but put an error in the pParse structure.
  109492. */
  109493. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  109494. int jointype = 0;
  109495. Token *apAll[3];
  109496. Token *p;
  109497. /* 0123456789 123456789 123456789 123 */
  109498. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  109499. static const struct {
  109500. u8 i; /* Beginning of keyword text in zKeyText[] */
  109501. u8 nChar; /* Length of the keyword in characters */
  109502. u8 code; /* Join type mask */
  109503. } aKeyword[] = {
  109504. /* natural */ { 0, 7, JT_NATURAL },
  109505. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  109506. /* outer */ { 10, 5, JT_OUTER },
  109507. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  109508. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  109509. /* inner */ { 23, 5, JT_INNER },
  109510. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  109511. };
  109512. int i, j;
  109513. apAll[0] = pA;
  109514. apAll[1] = pB;
  109515. apAll[2] = pC;
  109516. for(i=0; i<3 && apAll[i]; i++){
  109517. p = apAll[i];
  109518. for(j=0; j<ArraySize(aKeyword); j++){
  109519. if( p->n==aKeyword[j].nChar
  109520. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  109521. jointype |= aKeyword[j].code;
  109522. break;
  109523. }
  109524. }
  109525. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  109526. if( j>=ArraySize(aKeyword) ){
  109527. jointype |= JT_ERROR;
  109528. break;
  109529. }
  109530. }
  109531. if(
  109532. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  109533. (jointype & JT_ERROR)!=0
  109534. ){
  109535. const char *zSp = " ";
  109536. assert( pB!=0 );
  109537. if( pC==0 ){ zSp++; }
  109538. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  109539. "%T %T%s%T", pA, pB, zSp, pC);
  109540. jointype = JT_INNER;
  109541. }else if( (jointype & JT_OUTER)!=0
  109542. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  109543. sqlite3ErrorMsg(pParse,
  109544. "RIGHT and FULL OUTER JOINs are not currently supported");
  109545. jointype = JT_INNER;
  109546. }
  109547. return jointype;
  109548. }
  109549. /*
  109550. ** Return the index of a column in a table. Return -1 if the column
  109551. ** is not contained in the table.
  109552. */
  109553. static int columnIndex(Table *pTab, const char *zCol){
  109554. int i;
  109555. for(i=0; i<pTab->nCol; i++){
  109556. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  109557. }
  109558. return -1;
  109559. }
  109560. /*
  109561. ** Search the first N tables in pSrc, from left to right, looking for a
  109562. ** table that has a column named zCol.
  109563. **
  109564. ** When found, set *piTab and *piCol to the table index and column index
  109565. ** of the matching column and return TRUE.
  109566. **
  109567. ** If not found, return FALSE.
  109568. */
  109569. static int tableAndColumnIndex(
  109570. SrcList *pSrc, /* Array of tables to search */
  109571. int N, /* Number of tables in pSrc->a[] to search */
  109572. const char *zCol, /* Name of the column we are looking for */
  109573. int *piTab, /* Write index of pSrc->a[] here */
  109574. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  109575. ){
  109576. int i; /* For looping over tables in pSrc */
  109577. int iCol; /* Index of column matching zCol */
  109578. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  109579. for(i=0; i<N; i++){
  109580. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  109581. if( iCol>=0 ){
  109582. if( piTab ){
  109583. *piTab = i;
  109584. *piCol = iCol;
  109585. }
  109586. return 1;
  109587. }
  109588. }
  109589. return 0;
  109590. }
  109591. /*
  109592. ** This function is used to add terms implied by JOIN syntax to the
  109593. ** WHERE clause expression of a SELECT statement. The new term, which
  109594. ** is ANDed with the existing WHERE clause, is of the form:
  109595. **
  109596. ** (tab1.col1 = tab2.col2)
  109597. **
  109598. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  109599. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  109600. ** column iColRight of tab2.
  109601. */
  109602. static void addWhereTerm(
  109603. Parse *pParse, /* Parsing context */
  109604. SrcList *pSrc, /* List of tables in FROM clause */
  109605. int iLeft, /* Index of first table to join in pSrc */
  109606. int iColLeft, /* Index of column in first table */
  109607. int iRight, /* Index of second table in pSrc */
  109608. int iColRight, /* Index of column in second table */
  109609. int isOuterJoin, /* True if this is an OUTER join */
  109610. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  109611. ){
  109612. sqlite3 *db = pParse->db;
  109613. Expr *pE1;
  109614. Expr *pE2;
  109615. Expr *pEq;
  109616. assert( iLeft<iRight );
  109617. assert( pSrc->nSrc>iRight );
  109618. assert( pSrc->a[iLeft].pTab );
  109619. assert( pSrc->a[iRight].pTab );
  109620. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  109621. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  109622. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
  109623. if( pEq && isOuterJoin ){
  109624. ExprSetProperty(pEq, EP_FromJoin);
  109625. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  109626. ExprSetVVAProperty(pEq, EP_NoReduce);
  109627. pEq->iRightJoinTable = (i16)pE2->iTable;
  109628. }
  109629. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  109630. }
  109631. /*
  109632. ** Set the EP_FromJoin property on all terms of the given expression.
  109633. ** And set the Expr.iRightJoinTable to iTable for every term in the
  109634. ** expression.
  109635. **
  109636. ** The EP_FromJoin property is used on terms of an expression to tell
  109637. ** the LEFT OUTER JOIN processing logic that this term is part of the
  109638. ** join restriction specified in the ON or USING clause and not a part
  109639. ** of the more general WHERE clause. These terms are moved over to the
  109640. ** WHERE clause during join processing but we need to remember that they
  109641. ** originated in the ON or USING clause.
  109642. **
  109643. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  109644. ** expression depends on table iRightJoinTable even if that table is not
  109645. ** explicitly mentioned in the expression. That information is needed
  109646. ** for cases like this:
  109647. **
  109648. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  109649. **
  109650. ** The where clause needs to defer the handling of the t1.x=5
  109651. ** term until after the t2 loop of the join. In that way, a
  109652. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  109653. ** defer the handling of t1.x=5, it will be processed immediately
  109654. ** after the t1 loop and rows with t1.x!=5 will never appear in
  109655. ** the output, which is incorrect.
  109656. */
  109657. static void setJoinExpr(Expr *p, int iTable){
  109658. while( p ){
  109659. ExprSetProperty(p, EP_FromJoin);
  109660. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  109661. ExprSetVVAProperty(p, EP_NoReduce);
  109662. p->iRightJoinTable = (i16)iTable;
  109663. if( p->op==TK_FUNCTION && p->x.pList ){
  109664. int i;
  109665. for(i=0; i<p->x.pList->nExpr; i++){
  109666. setJoinExpr(p->x.pList->a[i].pExpr, iTable);
  109667. }
  109668. }
  109669. setJoinExpr(p->pLeft, iTable);
  109670. p = p->pRight;
  109671. }
  109672. }
  109673. /*
  109674. ** This routine processes the join information for a SELECT statement.
  109675. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  109676. ** NATURAL joins also create extra WHERE clause terms.
  109677. **
  109678. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  109679. ** The left most table is the first entry in Select.pSrc. The right-most
  109680. ** table is the last entry. The join operator is held in the entry to
  109681. ** the left. Thus entry 0 contains the join operator for the join between
  109682. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  109683. ** also attached to the left entry.
  109684. **
  109685. ** This routine returns the number of errors encountered.
  109686. */
  109687. static int sqliteProcessJoin(Parse *pParse, Select *p){
  109688. SrcList *pSrc; /* All tables in the FROM clause */
  109689. int i, j; /* Loop counters */
  109690. struct SrcList_item *pLeft; /* Left table being joined */
  109691. struct SrcList_item *pRight; /* Right table being joined */
  109692. pSrc = p->pSrc;
  109693. pLeft = &pSrc->a[0];
  109694. pRight = &pLeft[1];
  109695. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  109696. Table *pLeftTab = pLeft->pTab;
  109697. Table *pRightTab = pRight->pTab;
  109698. int isOuter;
  109699. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  109700. isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
  109701. /* When the NATURAL keyword is present, add WHERE clause terms for
  109702. ** every column that the two tables have in common.
  109703. */
  109704. if( pRight->fg.jointype & JT_NATURAL ){
  109705. if( pRight->pOn || pRight->pUsing ){
  109706. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  109707. "an ON or USING clause", 0);
  109708. return 1;
  109709. }
  109710. for(j=0; j<pRightTab->nCol; j++){
  109711. char *zName; /* Name of column in the right table */
  109712. int iLeft; /* Matching left table */
  109713. int iLeftCol; /* Matching column in the left table */
  109714. zName = pRightTab->aCol[j].zName;
  109715. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  109716. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  109717. isOuter, &p->pWhere);
  109718. }
  109719. }
  109720. }
  109721. /* Disallow both ON and USING clauses in the same join
  109722. */
  109723. if( pRight->pOn && pRight->pUsing ){
  109724. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  109725. "clauses in the same join");
  109726. return 1;
  109727. }
  109728. /* Add the ON clause to the end of the WHERE clause, connected by
  109729. ** an AND operator.
  109730. */
  109731. if( pRight->pOn ){
  109732. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  109733. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  109734. pRight->pOn = 0;
  109735. }
  109736. /* Create extra terms on the WHERE clause for each column named
  109737. ** in the USING clause. Example: If the two tables to be joined are
  109738. ** A and B and the USING clause names X, Y, and Z, then add this
  109739. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  109740. ** Report an error if any column mentioned in the USING clause is
  109741. ** not contained in both tables to be joined.
  109742. */
  109743. if( pRight->pUsing ){
  109744. IdList *pList = pRight->pUsing;
  109745. for(j=0; j<pList->nId; j++){
  109746. char *zName; /* Name of the term in the USING clause */
  109747. int iLeft; /* Table on the left with matching column name */
  109748. int iLeftCol; /* Column number of matching column on the left */
  109749. int iRightCol; /* Column number of matching column on the right */
  109750. zName = pList->a[j].zName;
  109751. iRightCol = columnIndex(pRightTab, zName);
  109752. if( iRightCol<0
  109753. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  109754. ){
  109755. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  109756. "not present in both tables", zName);
  109757. return 1;
  109758. }
  109759. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  109760. isOuter, &p->pWhere);
  109761. }
  109762. }
  109763. }
  109764. return 0;
  109765. }
  109766. /* Forward reference */
  109767. static KeyInfo *keyInfoFromExprList(
  109768. Parse *pParse, /* Parsing context */
  109769. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  109770. int iStart, /* Begin with this column of pList */
  109771. int nExtra /* Add this many extra columns to the end */
  109772. );
  109773. /*
  109774. ** Generate code that will push the record in registers regData
  109775. ** through regData+nData-1 onto the sorter.
  109776. */
  109777. static void pushOntoSorter(
  109778. Parse *pParse, /* Parser context */
  109779. SortCtx *pSort, /* Information about the ORDER BY clause */
  109780. Select *pSelect, /* The whole SELECT statement */
  109781. int regData, /* First register holding data to be sorted */
  109782. int regOrigData, /* First register holding data before packing */
  109783. int nData, /* Number of elements in the data array */
  109784. int nPrefixReg /* No. of reg prior to regData available for use */
  109785. ){
  109786. Vdbe *v = pParse->pVdbe; /* Stmt under construction */
  109787. int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
  109788. int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
  109789. int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
  109790. int regBase; /* Regs for sorter record */
  109791. int regRecord = ++pParse->nMem; /* Assembled sorter record */
  109792. int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
  109793. int op; /* Opcode to add sorter record to sorter */
  109794. int iLimit; /* LIMIT counter */
  109795. assert( bSeq==0 || bSeq==1 );
  109796. assert( nData==1 || regData==regOrigData || regOrigData==0 );
  109797. if( nPrefixReg ){
  109798. assert( nPrefixReg==nExpr+bSeq );
  109799. regBase = regData - nExpr - bSeq;
  109800. }else{
  109801. regBase = pParse->nMem + 1;
  109802. pParse->nMem += nBase;
  109803. }
  109804. assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
  109805. iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
  109806. pSort->labelDone = sqlite3VdbeMakeLabel(v);
  109807. sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
  109808. SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
  109809. if( bSeq ){
  109810. sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
  109811. }
  109812. if( nPrefixReg==0 && nData>0 ){
  109813. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
  109814. }
  109815. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
  109816. if( nOBSat>0 ){
  109817. int regPrevKey; /* The first nOBSat columns of the previous row */
  109818. int addrFirst; /* Address of the OP_IfNot opcode */
  109819. int addrJmp; /* Address of the OP_Jump opcode */
  109820. VdbeOp *pOp; /* Opcode that opens the sorter */
  109821. int nKey; /* Number of sorting key columns, including OP_Sequence */
  109822. KeyInfo *pKI; /* Original KeyInfo on the sorter table */
  109823. regPrevKey = pParse->nMem+1;
  109824. pParse->nMem += pSort->nOBSat;
  109825. nKey = nExpr - pSort->nOBSat + bSeq;
  109826. if( bSeq ){
  109827. addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
  109828. }else{
  109829. addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
  109830. }
  109831. VdbeCoverage(v);
  109832. sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
  109833. pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  109834. if( pParse->db->mallocFailed ) return;
  109835. pOp->p2 = nKey + nData;
  109836. pKI = pOp->p4.pKeyInfo;
  109837. memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
  109838. sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
  109839. testcase( pKI->nXField>2 );
  109840. pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
  109841. pKI->nXField-1);
  109842. addrJmp = sqlite3VdbeCurrentAddr(v);
  109843. sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
  109844. pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
  109845. pSort->regReturn = ++pParse->nMem;
  109846. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  109847. sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
  109848. if( iLimit ){
  109849. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
  109850. VdbeCoverage(v);
  109851. }
  109852. sqlite3VdbeJumpHere(v, addrFirst);
  109853. sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
  109854. sqlite3VdbeJumpHere(v, addrJmp);
  109855. }
  109856. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  109857. op = OP_SorterInsert;
  109858. }else{
  109859. op = OP_IdxInsert;
  109860. }
  109861. sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
  109862. regBase+nOBSat, nBase-nOBSat);
  109863. if( iLimit ){
  109864. int addr;
  109865. int r1 = 0;
  109866. /* Fill the sorter until it contains LIMIT+OFFSET entries. (The iLimit
  109867. ** register is initialized with value of LIMIT+OFFSET.) After the sorter
  109868. ** fills up, delete the least entry in the sorter after each insert.
  109869. ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */
  109870. addr = sqlite3VdbeAddOp1(v, OP_IfNotZero, iLimit); VdbeCoverage(v);
  109871. sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
  109872. if( pSort->bOrderedInnerLoop ){
  109873. r1 = ++pParse->nMem;
  109874. sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1);
  109875. VdbeComment((v, "seq"));
  109876. }
  109877. sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
  109878. if( pSort->bOrderedInnerLoop ){
  109879. /* If the inner loop is driven by an index such that values from
  109880. ** the same iteration of the inner loop are in sorted order, then
  109881. ** immediately jump to the next iteration of an inner loop if the
  109882. ** entry from the current iteration does not fit into the top
  109883. ** LIMIT+OFFSET entries of the sorter. */
  109884. int iBrk = sqlite3VdbeCurrentAddr(v) + 2;
  109885. sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1);
  109886. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  109887. VdbeCoverage(v);
  109888. }
  109889. sqlite3VdbeJumpHere(v, addr);
  109890. }
  109891. }
  109892. /*
  109893. ** Add code to implement the OFFSET
  109894. */
  109895. static void codeOffset(
  109896. Vdbe *v, /* Generate code into this VM */
  109897. int iOffset, /* Register holding the offset counter */
  109898. int iContinue /* Jump here to skip the current record */
  109899. ){
  109900. if( iOffset>0 ){
  109901. sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
  109902. VdbeComment((v, "OFFSET"));
  109903. }
  109904. }
  109905. /*
  109906. ** Add code that will check to make sure the N registers starting at iMem
  109907. ** form a distinct entry. iTab is a sorting index that holds previously
  109908. ** seen combinations of the N values. A new entry is made in iTab
  109909. ** if the current N values are new.
  109910. **
  109911. ** A jump to addrRepeat is made and the N+1 values are popped from the
  109912. ** stack if the top N elements are not distinct.
  109913. */
  109914. static void codeDistinct(
  109915. Parse *pParse, /* Parsing and code generating context */
  109916. int iTab, /* A sorting index used to test for distinctness */
  109917. int addrRepeat, /* Jump to here if not distinct */
  109918. int N, /* Number of elements */
  109919. int iMem /* First element */
  109920. ){
  109921. Vdbe *v;
  109922. int r1;
  109923. v = pParse->pVdbe;
  109924. r1 = sqlite3GetTempReg(pParse);
  109925. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
  109926. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  109927. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
  109928. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  109929. sqlite3ReleaseTempReg(pParse, r1);
  109930. }
  109931. /*
  109932. ** This routine generates the code for the inside of the inner loop
  109933. ** of a SELECT.
  109934. **
  109935. ** If srcTab is negative, then the pEList expressions
  109936. ** are evaluated in order to get the data for this row. If srcTab is
  109937. ** zero or more, then data is pulled from srcTab and pEList is used only
  109938. ** to get the number of columns and the collation sequence for each column.
  109939. */
  109940. static void selectInnerLoop(
  109941. Parse *pParse, /* The parser context */
  109942. Select *p, /* The complete select statement being coded */
  109943. ExprList *pEList, /* List of values being extracted */
  109944. int srcTab, /* Pull data from this table */
  109945. SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
  109946. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  109947. SelectDest *pDest, /* How to dispose of the results */
  109948. int iContinue, /* Jump here to continue with next row */
  109949. int iBreak /* Jump here to break out of the inner loop */
  109950. ){
  109951. Vdbe *v = pParse->pVdbe;
  109952. int i;
  109953. int hasDistinct; /* True if the DISTINCT keyword is present */
  109954. int eDest = pDest->eDest; /* How to dispose of results */
  109955. int iParm = pDest->iSDParm; /* First argument to disposal method */
  109956. int nResultCol; /* Number of result columns */
  109957. int nPrefixReg = 0; /* Number of extra registers before regResult */
  109958. /* Usually, regResult is the first cell in an array of memory cells
  109959. ** containing the current result row. In this case regOrig is set to the
  109960. ** same value. However, if the results are being sent to the sorter, the
  109961. ** values for any expressions that are also part of the sort-key are omitted
  109962. ** from this array. In this case regOrig is set to zero. */
  109963. int regResult; /* Start of memory holding current results */
  109964. int regOrig; /* Start of memory holding full result (or 0) */
  109965. assert( v );
  109966. assert( pEList!=0 );
  109967. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  109968. if( pSort && pSort->pOrderBy==0 ) pSort = 0;
  109969. if( pSort==0 && !hasDistinct ){
  109970. assert( iContinue!=0 );
  109971. codeOffset(v, p->iOffset, iContinue);
  109972. }
  109973. /* Pull the requested columns.
  109974. */
  109975. nResultCol = pEList->nExpr;
  109976. if( pDest->iSdst==0 ){
  109977. if( pSort ){
  109978. nPrefixReg = pSort->pOrderBy->nExpr;
  109979. if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
  109980. pParse->nMem += nPrefixReg;
  109981. }
  109982. pDest->iSdst = pParse->nMem+1;
  109983. pParse->nMem += nResultCol;
  109984. }else if( pDest->iSdst+nResultCol > pParse->nMem ){
  109985. /* This is an error condition that can result, for example, when a SELECT
  109986. ** on the right-hand side of an INSERT contains more result columns than
  109987. ** there are columns in the table on the left. The error will be caught
  109988. ** and reported later. But we need to make sure enough memory is allocated
  109989. ** to avoid other spurious errors in the meantime. */
  109990. pParse->nMem += nResultCol;
  109991. }
  109992. pDest->nSdst = nResultCol;
  109993. regOrig = regResult = pDest->iSdst;
  109994. if( srcTab>=0 ){
  109995. for(i=0; i<nResultCol; i++){
  109996. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  109997. VdbeComment((v, "%s", pEList->a[i].zName));
  109998. }
  109999. }else if( eDest!=SRT_Exists ){
  110000. /* If the destination is an EXISTS(...) expression, the actual
  110001. ** values returned by the SELECT are not required.
  110002. */
  110003. u8 ecelFlags;
  110004. if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
  110005. ecelFlags = SQLITE_ECEL_DUP;
  110006. }else{
  110007. ecelFlags = 0;
  110008. }
  110009. if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
  110010. /* For each expression in pEList that is a copy of an expression in
  110011. ** the ORDER BY clause (pSort->pOrderBy), set the associated
  110012. ** iOrderByCol value to one more than the index of the ORDER BY
  110013. ** expression within the sort-key that pushOntoSorter() will generate.
  110014. ** This allows the pEList field to be omitted from the sorted record,
  110015. ** saving space and CPU cycles. */
  110016. ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
  110017. for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
  110018. int j;
  110019. if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
  110020. pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
  110021. }
  110022. }
  110023. regOrig = 0;
  110024. assert( eDest==SRT_Set || eDest==SRT_Mem
  110025. || eDest==SRT_Coroutine || eDest==SRT_Output );
  110026. }
  110027. nResultCol = sqlite3ExprCodeExprList(pParse,pEList,regResult,0,ecelFlags);
  110028. }
  110029. /* If the DISTINCT keyword was present on the SELECT statement
  110030. ** and this row has been seen before, then do not make this row
  110031. ** part of the result.
  110032. */
  110033. if( hasDistinct ){
  110034. switch( pDistinct->eTnctType ){
  110035. case WHERE_DISTINCT_ORDERED: {
  110036. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  110037. int iJump; /* Jump destination */
  110038. int regPrev; /* Previous row content */
  110039. /* Allocate space for the previous row */
  110040. regPrev = pParse->nMem+1;
  110041. pParse->nMem += nResultCol;
  110042. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  110043. ** sets the MEM_Cleared bit on the first register of the
  110044. ** previous value. This will cause the OP_Ne below to always
  110045. ** fail on the first iteration of the loop even if the first
  110046. ** row is all NULLs.
  110047. */
  110048. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  110049. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  110050. pOp->opcode = OP_Null;
  110051. pOp->p1 = 1;
  110052. pOp->p2 = regPrev;
  110053. iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
  110054. for(i=0; i<nResultCol; i++){
  110055. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
  110056. if( i<nResultCol-1 ){
  110057. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  110058. VdbeCoverage(v);
  110059. }else{
  110060. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  110061. VdbeCoverage(v);
  110062. }
  110063. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  110064. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  110065. }
  110066. assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
  110067. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
  110068. break;
  110069. }
  110070. case WHERE_DISTINCT_UNIQUE: {
  110071. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  110072. break;
  110073. }
  110074. default: {
  110075. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  110076. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
  110077. regResult);
  110078. break;
  110079. }
  110080. }
  110081. if( pSort==0 ){
  110082. codeOffset(v, p->iOffset, iContinue);
  110083. }
  110084. }
  110085. switch( eDest ){
  110086. /* In this mode, write each query result to the key of the temporary
  110087. ** table iParm.
  110088. */
  110089. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  110090. case SRT_Union: {
  110091. int r1;
  110092. r1 = sqlite3GetTempReg(pParse);
  110093. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
  110094. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
  110095. sqlite3ReleaseTempReg(pParse, r1);
  110096. break;
  110097. }
  110098. /* Construct a record from the query result, but instead of
  110099. ** saving that record, use it as a key to delete elements from
  110100. ** the temporary table iParm.
  110101. */
  110102. case SRT_Except: {
  110103. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
  110104. break;
  110105. }
  110106. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  110107. /* Store the result as data using a unique key.
  110108. */
  110109. case SRT_Fifo:
  110110. case SRT_DistFifo:
  110111. case SRT_Table:
  110112. case SRT_EphemTab: {
  110113. int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
  110114. testcase( eDest==SRT_Table );
  110115. testcase( eDest==SRT_EphemTab );
  110116. testcase( eDest==SRT_Fifo );
  110117. testcase( eDest==SRT_DistFifo );
  110118. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
  110119. #ifndef SQLITE_OMIT_CTE
  110120. if( eDest==SRT_DistFifo ){
  110121. /* If the destination is DistFifo, then cursor (iParm+1) is open
  110122. ** on an ephemeral index. If the current row is already present
  110123. ** in the index, do not write it to the output. If not, add the
  110124. ** current row to the index and proceed with writing it to the
  110125. ** output table as well. */
  110126. int addr = sqlite3VdbeCurrentAddr(v) + 4;
  110127. sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
  110128. VdbeCoverage(v);
  110129. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
  110130. assert( pSort==0 );
  110131. }
  110132. #endif
  110133. if( pSort ){
  110134. pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
  110135. }else{
  110136. int r2 = sqlite3GetTempReg(pParse);
  110137. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  110138. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  110139. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  110140. sqlite3ReleaseTempReg(pParse, r2);
  110141. }
  110142. sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
  110143. break;
  110144. }
  110145. #ifndef SQLITE_OMIT_SUBQUERY
  110146. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  110147. ** then there should be a single item on the stack. Write this
  110148. ** item into the set table with bogus data.
  110149. */
  110150. case SRT_Set: {
  110151. if( pSort ){
  110152. /* At first glance you would think we could optimize out the
  110153. ** ORDER BY in this case since the order of entries in the set
  110154. ** does not matter. But there might be a LIMIT clause, in which
  110155. ** case the order does matter */
  110156. pushOntoSorter(
  110157. pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
  110158. }else{
  110159. int r1 = sqlite3GetTempReg(pParse);
  110160. assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
  110161. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
  110162. r1, pDest->zAffSdst, nResultCol);
  110163. sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
  110164. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
  110165. sqlite3ReleaseTempReg(pParse, r1);
  110166. }
  110167. break;
  110168. }
  110169. /* If any row exist in the result set, record that fact and abort.
  110170. */
  110171. case SRT_Exists: {
  110172. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  110173. /* The LIMIT clause will terminate the loop for us */
  110174. break;
  110175. }
  110176. /* If this is a scalar select that is part of an expression, then
  110177. ** store the results in the appropriate memory cell or array of
  110178. ** memory cells and break out of the scan loop.
  110179. */
  110180. case SRT_Mem: {
  110181. if( pSort ){
  110182. assert( nResultCol<=pDest->nSdst );
  110183. pushOntoSorter(
  110184. pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
  110185. }else{
  110186. assert( nResultCol==pDest->nSdst );
  110187. assert( regResult==iParm );
  110188. /* The LIMIT clause will jump out of the loop for us */
  110189. }
  110190. break;
  110191. }
  110192. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  110193. case SRT_Coroutine: /* Send data to a co-routine */
  110194. case SRT_Output: { /* Return the results */
  110195. testcase( eDest==SRT_Coroutine );
  110196. testcase( eDest==SRT_Output );
  110197. if( pSort ){
  110198. pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
  110199. nPrefixReg);
  110200. }else if( eDest==SRT_Coroutine ){
  110201. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  110202. }else{
  110203. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
  110204. sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
  110205. }
  110206. break;
  110207. }
  110208. #ifndef SQLITE_OMIT_CTE
  110209. /* Write the results into a priority queue that is order according to
  110210. ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
  110211. ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
  110212. ** pSO->nExpr columns, then make sure all keys are unique by adding a
  110213. ** final OP_Sequence column. The last column is the record as a blob.
  110214. */
  110215. case SRT_DistQueue:
  110216. case SRT_Queue: {
  110217. int nKey;
  110218. int r1, r2, r3;
  110219. int addrTest = 0;
  110220. ExprList *pSO;
  110221. pSO = pDest->pOrderBy;
  110222. assert( pSO );
  110223. nKey = pSO->nExpr;
  110224. r1 = sqlite3GetTempReg(pParse);
  110225. r2 = sqlite3GetTempRange(pParse, nKey+2);
  110226. r3 = r2+nKey+1;
  110227. if( eDest==SRT_DistQueue ){
  110228. /* If the destination is DistQueue, then cursor (iParm+1) is open
  110229. ** on a second ephemeral index that holds all values every previously
  110230. ** added to the queue. */
  110231. addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
  110232. regResult, nResultCol);
  110233. VdbeCoverage(v);
  110234. }
  110235. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
  110236. if( eDest==SRT_DistQueue ){
  110237. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
  110238. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  110239. }
  110240. for(i=0; i<nKey; i++){
  110241. sqlite3VdbeAddOp2(v, OP_SCopy,
  110242. regResult + pSO->a[i].u.x.iOrderByCol - 1,
  110243. r2+i);
  110244. }
  110245. sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
  110246. sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
  110247. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
  110248. if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
  110249. sqlite3ReleaseTempReg(pParse, r1);
  110250. sqlite3ReleaseTempRange(pParse, r2, nKey+2);
  110251. break;
  110252. }
  110253. #endif /* SQLITE_OMIT_CTE */
  110254. #if !defined(SQLITE_OMIT_TRIGGER)
  110255. /* Discard the results. This is used for SELECT statements inside
  110256. ** the body of a TRIGGER. The purpose of such selects is to call
  110257. ** user-defined functions that have side effects. We do not care
  110258. ** about the actual results of the select.
  110259. */
  110260. default: {
  110261. assert( eDest==SRT_Discard );
  110262. break;
  110263. }
  110264. #endif
  110265. }
  110266. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  110267. ** there is a sorter, in which case the sorter has already limited
  110268. ** the output for us.
  110269. */
  110270. if( pSort==0 && p->iLimit ){
  110271. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  110272. }
  110273. }
  110274. /*
  110275. ** Allocate a KeyInfo object sufficient for an index of N key columns and
  110276. ** X extra columns.
  110277. */
  110278. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
  110279. int nExtra = (N+X)*(sizeof(CollSeq*)+1);
  110280. KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
  110281. if( p ){
  110282. p->aSortOrder = (u8*)&p->aColl[N+X];
  110283. p->nField = (u16)N;
  110284. p->nXField = (u16)X;
  110285. p->enc = ENC(db);
  110286. p->db = db;
  110287. p->nRef = 1;
  110288. memset(&p[1], 0, nExtra);
  110289. }else{
  110290. sqlite3OomFault(db);
  110291. }
  110292. return p;
  110293. }
  110294. /*
  110295. ** Deallocate a KeyInfo object
  110296. */
  110297. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
  110298. if( p ){
  110299. assert( p->nRef>0 );
  110300. p->nRef--;
  110301. if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
  110302. }
  110303. }
  110304. /*
  110305. ** Make a new pointer to a KeyInfo object
  110306. */
  110307. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
  110308. if( p ){
  110309. assert( p->nRef>0 );
  110310. p->nRef++;
  110311. }
  110312. return p;
  110313. }
  110314. #ifdef SQLITE_DEBUG
  110315. /*
  110316. ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
  110317. ** can only be changed if this is just a single reference to the object.
  110318. **
  110319. ** This routine is used only inside of assert() statements.
  110320. */
  110321. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
  110322. #endif /* SQLITE_DEBUG */
  110323. /*
  110324. ** Given an expression list, generate a KeyInfo structure that records
  110325. ** the collating sequence for each expression in that expression list.
  110326. **
  110327. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  110328. ** KeyInfo structure is appropriate for initializing a virtual index to
  110329. ** implement that clause. If the ExprList is the result set of a SELECT
  110330. ** then the KeyInfo structure is appropriate for initializing a virtual
  110331. ** index to implement a DISTINCT test.
  110332. **
  110333. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  110334. ** function is responsible for seeing that this structure is eventually
  110335. ** freed.
  110336. */
  110337. static KeyInfo *keyInfoFromExprList(
  110338. Parse *pParse, /* Parsing context */
  110339. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  110340. int iStart, /* Begin with this column of pList */
  110341. int nExtra /* Add this many extra columns to the end */
  110342. ){
  110343. int nExpr;
  110344. KeyInfo *pInfo;
  110345. struct ExprList_item *pItem;
  110346. sqlite3 *db = pParse->db;
  110347. int i;
  110348. nExpr = pList->nExpr;
  110349. pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
  110350. if( pInfo ){
  110351. assert( sqlite3KeyInfoIsWriteable(pInfo) );
  110352. for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
  110353. CollSeq *pColl;
  110354. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  110355. if( !pColl ) pColl = db->pDfltColl;
  110356. pInfo->aColl[i-iStart] = pColl;
  110357. pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
  110358. }
  110359. }
  110360. return pInfo;
  110361. }
  110362. /*
  110363. ** Name of the connection operator, used for error messages.
  110364. */
  110365. static const char *selectOpName(int id){
  110366. char *z;
  110367. switch( id ){
  110368. case TK_ALL: z = "UNION ALL"; break;
  110369. case TK_INTERSECT: z = "INTERSECT"; break;
  110370. case TK_EXCEPT: z = "EXCEPT"; break;
  110371. default: z = "UNION"; break;
  110372. }
  110373. return z;
  110374. }
  110375. #ifndef SQLITE_OMIT_EXPLAIN
  110376. /*
  110377. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  110378. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  110379. ** where the caption is of the form:
  110380. **
  110381. ** "USE TEMP B-TREE FOR xxx"
  110382. **
  110383. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  110384. ** is determined by the zUsage argument.
  110385. */
  110386. static void explainTempTable(Parse *pParse, const char *zUsage){
  110387. if( pParse->explain==2 ){
  110388. Vdbe *v = pParse->pVdbe;
  110389. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  110390. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  110391. }
  110392. }
  110393. /*
  110394. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  110395. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  110396. ** in sqlite3Select() to assign values to structure member variables that
  110397. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  110398. ** code with #ifndef directives.
  110399. */
  110400. # define explainSetInteger(a, b) a = b
  110401. #else
  110402. /* No-op versions of the explainXXX() functions and macros. */
  110403. # define explainTempTable(y,z)
  110404. # define explainSetInteger(y,z)
  110405. #endif
  110406. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  110407. /*
  110408. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  110409. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  110410. ** where the caption is of one of the two forms:
  110411. **
  110412. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  110413. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  110414. **
  110415. ** where iSub1 and iSub2 are the integers passed as the corresponding
  110416. ** function parameters, and op is the text representation of the parameter
  110417. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  110418. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  110419. ** false, or the second form if it is true.
  110420. */
  110421. static void explainComposite(
  110422. Parse *pParse, /* Parse context */
  110423. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  110424. int iSub1, /* Subquery id 1 */
  110425. int iSub2, /* Subquery id 2 */
  110426. int bUseTmp /* True if a temp table was used */
  110427. ){
  110428. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  110429. if( pParse->explain==2 ){
  110430. Vdbe *v = pParse->pVdbe;
  110431. char *zMsg = sqlite3MPrintf(
  110432. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  110433. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  110434. );
  110435. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  110436. }
  110437. }
  110438. #else
  110439. /* No-op versions of the explainXXX() functions and macros. */
  110440. # define explainComposite(v,w,x,y,z)
  110441. #endif
  110442. /*
  110443. ** If the inner loop was generated using a non-null pOrderBy argument,
  110444. ** then the results were placed in a sorter. After the loop is terminated
  110445. ** we need to run the sorter and output the results. The following
  110446. ** routine generates the code needed to do that.
  110447. */
  110448. static void generateSortTail(
  110449. Parse *pParse, /* Parsing context */
  110450. Select *p, /* The SELECT statement */
  110451. SortCtx *pSort, /* Information on the ORDER BY clause */
  110452. int nColumn, /* Number of columns of data */
  110453. SelectDest *pDest /* Write the sorted results here */
  110454. ){
  110455. Vdbe *v = pParse->pVdbe; /* The prepared statement */
  110456. int addrBreak = pSort->labelDone; /* Jump here to exit loop */
  110457. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  110458. int addr;
  110459. int addrOnce = 0;
  110460. int iTab;
  110461. ExprList *pOrderBy = pSort->pOrderBy;
  110462. int eDest = pDest->eDest;
  110463. int iParm = pDest->iSDParm;
  110464. int regRow;
  110465. int regRowid;
  110466. int iCol;
  110467. int nKey;
  110468. int iSortTab; /* Sorter cursor to read from */
  110469. int nSortData; /* Trailing values to read from sorter */
  110470. int i;
  110471. int bSeq; /* True if sorter record includes seq. no. */
  110472. struct ExprList_item *aOutEx = p->pEList->a;
  110473. assert( addrBreak<0 );
  110474. if( pSort->labelBkOut ){
  110475. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  110476. sqlite3VdbeGoto(v, addrBreak);
  110477. sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
  110478. }
  110479. iTab = pSort->iECursor;
  110480. if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
  110481. regRowid = 0;
  110482. regRow = pDest->iSdst;
  110483. nSortData = nColumn;
  110484. }else{
  110485. regRowid = sqlite3GetTempReg(pParse);
  110486. regRow = sqlite3GetTempRange(pParse, nColumn);
  110487. nSortData = nColumn;
  110488. }
  110489. nKey = pOrderBy->nExpr - pSort->nOBSat;
  110490. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  110491. int regSortOut = ++pParse->nMem;
  110492. iSortTab = pParse->nTab++;
  110493. if( pSort->labelBkOut ){
  110494. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  110495. }
  110496. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
  110497. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  110498. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  110499. VdbeCoverage(v);
  110500. codeOffset(v, p->iOffset, addrContinue);
  110501. sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
  110502. bSeq = 0;
  110503. }else{
  110504. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
  110505. codeOffset(v, p->iOffset, addrContinue);
  110506. iSortTab = iTab;
  110507. bSeq = 1;
  110508. }
  110509. for(i=0, iCol=nKey+bSeq; i<nSortData; i++){
  110510. int iRead;
  110511. if( aOutEx[i].u.x.iOrderByCol ){
  110512. iRead = aOutEx[i].u.x.iOrderByCol-1;
  110513. }else{
  110514. iRead = iCol++;
  110515. }
  110516. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
  110517. VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
  110518. }
  110519. switch( eDest ){
  110520. case SRT_Table:
  110521. case SRT_EphemTab: {
  110522. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  110523. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  110524. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  110525. break;
  110526. }
  110527. #ifndef SQLITE_OMIT_SUBQUERY
  110528. case SRT_Set: {
  110529. assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
  110530. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
  110531. pDest->zAffSdst, nColumn);
  110532. sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn);
  110533. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
  110534. break;
  110535. }
  110536. case SRT_Mem: {
  110537. /* The LIMIT clause will terminate the loop for us */
  110538. break;
  110539. }
  110540. #endif
  110541. default: {
  110542. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  110543. testcase( eDest==SRT_Output );
  110544. testcase( eDest==SRT_Coroutine );
  110545. if( eDest==SRT_Output ){
  110546. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  110547. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  110548. }else{
  110549. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  110550. }
  110551. break;
  110552. }
  110553. }
  110554. if( regRowid ){
  110555. if( eDest==SRT_Set ){
  110556. sqlite3ReleaseTempRange(pParse, regRow, nColumn);
  110557. }else{
  110558. sqlite3ReleaseTempReg(pParse, regRow);
  110559. }
  110560. sqlite3ReleaseTempReg(pParse, regRowid);
  110561. }
  110562. /* The bottom of the loop
  110563. */
  110564. sqlite3VdbeResolveLabel(v, addrContinue);
  110565. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  110566. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
  110567. }else{
  110568. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
  110569. }
  110570. if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
  110571. sqlite3VdbeResolveLabel(v, addrBreak);
  110572. }
  110573. /*
  110574. ** Return a pointer to a string containing the 'declaration type' of the
  110575. ** expression pExpr. The string may be treated as static by the caller.
  110576. **
  110577. ** Also try to estimate the size of the returned value and return that
  110578. ** result in *pEstWidth.
  110579. **
  110580. ** The declaration type is the exact datatype definition extracted from the
  110581. ** original CREATE TABLE statement if the expression is a column. The
  110582. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  110583. ** is considered a column can be complex in the presence of subqueries. The
  110584. ** result-set expression in all of the following SELECT statements is
  110585. ** considered a column by this function.
  110586. **
  110587. ** SELECT col FROM tbl;
  110588. ** SELECT (SELECT col FROM tbl;
  110589. ** SELECT (SELECT col FROM tbl);
  110590. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  110591. **
  110592. ** The declaration type for any expression other than a column is NULL.
  110593. **
  110594. ** This routine has either 3 or 6 parameters depending on whether or not
  110595. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  110596. */
  110597. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  110598. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
  110599. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  110600. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
  110601. #endif
  110602. static const char *columnTypeImpl(
  110603. NameContext *pNC,
  110604. Expr *pExpr,
  110605. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  110606. const char **pzOrigDb,
  110607. const char **pzOrigTab,
  110608. const char **pzOrigCol,
  110609. #endif
  110610. u8 *pEstWidth
  110611. ){
  110612. char const *zType = 0;
  110613. int j;
  110614. u8 estWidth = 1;
  110615. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  110616. char const *zOrigDb = 0;
  110617. char const *zOrigTab = 0;
  110618. char const *zOrigCol = 0;
  110619. #endif
  110620. assert( pExpr!=0 );
  110621. assert( pNC->pSrcList!=0 );
  110622. switch( pExpr->op ){
  110623. case TK_AGG_COLUMN:
  110624. case TK_COLUMN: {
  110625. /* The expression is a column. Locate the table the column is being
  110626. ** extracted from in NameContext.pSrcList. This table may be real
  110627. ** database table or a subquery.
  110628. */
  110629. Table *pTab = 0; /* Table structure column is extracted from */
  110630. Select *pS = 0; /* Select the column is extracted from */
  110631. int iCol = pExpr->iColumn; /* Index of column in pTab */
  110632. testcase( pExpr->op==TK_AGG_COLUMN );
  110633. testcase( pExpr->op==TK_COLUMN );
  110634. while( pNC && !pTab ){
  110635. SrcList *pTabList = pNC->pSrcList;
  110636. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  110637. if( j<pTabList->nSrc ){
  110638. pTab = pTabList->a[j].pTab;
  110639. pS = pTabList->a[j].pSelect;
  110640. }else{
  110641. pNC = pNC->pNext;
  110642. }
  110643. }
  110644. if( pTab==0 ){
  110645. /* At one time, code such as "SELECT new.x" within a trigger would
  110646. ** cause this condition to run. Since then, we have restructured how
  110647. ** trigger code is generated and so this condition is no longer
  110648. ** possible. However, it can still be true for statements like
  110649. ** the following:
  110650. **
  110651. ** CREATE TABLE t1(col INTEGER);
  110652. ** SELECT (SELECT t1.col) FROM FROM t1;
  110653. **
  110654. ** when columnType() is called on the expression "t1.col" in the
  110655. ** sub-select. In this case, set the column type to NULL, even
  110656. ** though it should really be "INTEGER".
  110657. **
  110658. ** This is not a problem, as the column type of "t1.col" is never
  110659. ** used. When columnType() is called on the expression
  110660. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  110661. ** branch below. */
  110662. break;
  110663. }
  110664. assert( pTab && pExpr->pTab==pTab );
  110665. if( pS ){
  110666. /* The "table" is actually a sub-select or a view in the FROM clause
  110667. ** of the SELECT statement. Return the declaration type and origin
  110668. ** data for the result-set column of the sub-select.
  110669. */
  110670. if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
  110671. /* If iCol is less than zero, then the expression requests the
  110672. ** rowid of the sub-select or view. This expression is legal (see
  110673. ** test case misc2.2.2) - it always evaluates to NULL.
  110674. **
  110675. ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
  110676. ** caught already by name resolution.
  110677. */
  110678. NameContext sNC;
  110679. Expr *p = pS->pEList->a[iCol].pExpr;
  110680. sNC.pSrcList = pS->pSrc;
  110681. sNC.pNext = pNC;
  110682. sNC.pParse = pNC->pParse;
  110683. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
  110684. }
  110685. }else if( pTab->pSchema ){
  110686. /* A real table */
  110687. assert( !pS );
  110688. if( iCol<0 ) iCol = pTab->iPKey;
  110689. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  110690. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  110691. if( iCol<0 ){
  110692. zType = "INTEGER";
  110693. zOrigCol = "rowid";
  110694. }else{
  110695. zOrigCol = pTab->aCol[iCol].zName;
  110696. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  110697. estWidth = pTab->aCol[iCol].szEst;
  110698. }
  110699. zOrigTab = pTab->zName;
  110700. if( pNC->pParse ){
  110701. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  110702. zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
  110703. }
  110704. #else
  110705. if( iCol<0 ){
  110706. zType = "INTEGER";
  110707. }else{
  110708. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  110709. estWidth = pTab->aCol[iCol].szEst;
  110710. }
  110711. #endif
  110712. }
  110713. break;
  110714. }
  110715. #ifndef SQLITE_OMIT_SUBQUERY
  110716. case TK_SELECT: {
  110717. /* The expression is a sub-select. Return the declaration type and
  110718. ** origin info for the single column in the result set of the SELECT
  110719. ** statement.
  110720. */
  110721. NameContext sNC;
  110722. Select *pS = pExpr->x.pSelect;
  110723. Expr *p = pS->pEList->a[0].pExpr;
  110724. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  110725. sNC.pSrcList = pS->pSrc;
  110726. sNC.pNext = pNC;
  110727. sNC.pParse = pNC->pParse;
  110728. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
  110729. break;
  110730. }
  110731. #endif
  110732. }
  110733. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  110734. if( pzOrigDb ){
  110735. assert( pzOrigTab && pzOrigCol );
  110736. *pzOrigDb = zOrigDb;
  110737. *pzOrigTab = zOrigTab;
  110738. *pzOrigCol = zOrigCol;
  110739. }
  110740. #endif
  110741. if( pEstWidth ) *pEstWidth = estWidth;
  110742. return zType;
  110743. }
  110744. /*
  110745. ** Generate code that will tell the VDBE the declaration types of columns
  110746. ** in the result set.
  110747. */
  110748. static void generateColumnTypes(
  110749. Parse *pParse, /* Parser context */
  110750. SrcList *pTabList, /* List of tables */
  110751. ExprList *pEList /* Expressions defining the result set */
  110752. ){
  110753. #ifndef SQLITE_OMIT_DECLTYPE
  110754. Vdbe *v = pParse->pVdbe;
  110755. int i;
  110756. NameContext sNC;
  110757. sNC.pSrcList = pTabList;
  110758. sNC.pParse = pParse;
  110759. sNC.pNext = 0;
  110760. for(i=0; i<pEList->nExpr; i++){
  110761. Expr *p = pEList->a[i].pExpr;
  110762. const char *zType;
  110763. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  110764. const char *zOrigDb = 0;
  110765. const char *zOrigTab = 0;
  110766. const char *zOrigCol = 0;
  110767. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
  110768. /* The vdbe must make its own copy of the column-type and other
  110769. ** column specific strings, in case the schema is reset before this
  110770. ** virtual machine is deleted.
  110771. */
  110772. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  110773. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  110774. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  110775. #else
  110776. zType = columnType(&sNC, p, 0, 0, 0, 0);
  110777. #endif
  110778. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  110779. }
  110780. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  110781. }
  110782. /*
  110783. ** Return the Table objecct in the SrcList that has cursor iCursor.
  110784. ** Or return NULL if no such Table object exists in the SrcList.
  110785. */
  110786. static Table *tableWithCursor(SrcList *pList, int iCursor){
  110787. int j;
  110788. for(j=0; j<pList->nSrc; j++){
  110789. if( pList->a[j].iCursor==iCursor ) return pList->a[j].pTab;
  110790. }
  110791. return 0;
  110792. }
  110793. /*
  110794. ** Generate code that will tell the VDBE the names of columns
  110795. ** in the result set. This information is used to provide the
  110796. ** azCol[] values in the callback.
  110797. */
  110798. static void generateColumnNames(
  110799. Parse *pParse, /* Parser context */
  110800. SrcList *pTabList, /* List of tables */
  110801. ExprList *pEList /* Expressions defining the result set */
  110802. ){
  110803. Vdbe *v = pParse->pVdbe;
  110804. int i;
  110805. Table *pTab;
  110806. sqlite3 *db = pParse->db;
  110807. int fullNames, shortNames;
  110808. #ifndef SQLITE_OMIT_EXPLAIN
  110809. /* If this is an EXPLAIN, skip this step */
  110810. if( pParse->explain ){
  110811. return;
  110812. }
  110813. #endif
  110814. if( pParse->colNamesSet || db->mallocFailed ) return;
  110815. assert( v!=0 );
  110816. assert( pTabList!=0 );
  110817. pParse->colNamesSet = 1;
  110818. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  110819. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  110820. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  110821. for(i=0; i<pEList->nExpr; i++){
  110822. Expr *p;
  110823. p = pEList->a[i].pExpr;
  110824. if( NEVER(p==0) ) continue;
  110825. if( pEList->a[i].zName ){
  110826. char *zName = pEList->a[i].zName;
  110827. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  110828. }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN)
  110829. && (pTab = tableWithCursor(pTabList, p->iTable))!=0
  110830. ){
  110831. char *zCol;
  110832. int iCol = p->iColumn;
  110833. if( iCol<0 ) iCol = pTab->iPKey;
  110834. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  110835. if( iCol<0 ){
  110836. zCol = "rowid";
  110837. }else{
  110838. zCol = pTab->aCol[iCol].zName;
  110839. }
  110840. if( !shortNames && !fullNames ){
  110841. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  110842. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  110843. }else if( fullNames ){
  110844. char *zName = 0;
  110845. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  110846. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  110847. }else{
  110848. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  110849. }
  110850. }else{
  110851. const char *z = pEList->a[i].zSpan;
  110852. z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
  110853. sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
  110854. }
  110855. }
  110856. generateColumnTypes(pParse, pTabList, pEList);
  110857. }
  110858. /*
  110859. ** Given an expression list (which is really the list of expressions
  110860. ** that form the result set of a SELECT statement) compute appropriate
  110861. ** column names for a table that would hold the expression list.
  110862. **
  110863. ** All column names will be unique.
  110864. **
  110865. ** Only the column names are computed. Column.zType, Column.zColl,
  110866. ** and other fields of Column are zeroed.
  110867. **
  110868. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  110869. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  110870. */
  110871. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
  110872. Parse *pParse, /* Parsing context */
  110873. ExprList *pEList, /* Expr list from which to derive column names */
  110874. i16 *pnCol, /* Write the number of columns here */
  110875. Column **paCol /* Write the new column list here */
  110876. ){
  110877. sqlite3 *db = pParse->db; /* Database connection */
  110878. int i, j; /* Loop counters */
  110879. u32 cnt; /* Index added to make the name unique */
  110880. Column *aCol, *pCol; /* For looping over result columns */
  110881. int nCol; /* Number of columns in the result set */
  110882. Expr *p; /* Expression for a single result column */
  110883. char *zName; /* Column name */
  110884. int nName; /* Size of name in zName[] */
  110885. Hash ht; /* Hash table of column names */
  110886. sqlite3HashInit(&ht);
  110887. if( pEList ){
  110888. nCol = pEList->nExpr;
  110889. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  110890. testcase( aCol==0 );
  110891. }else{
  110892. nCol = 0;
  110893. aCol = 0;
  110894. }
  110895. assert( nCol==(i16)nCol );
  110896. *pnCol = nCol;
  110897. *paCol = aCol;
  110898. for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
  110899. /* Get an appropriate name for the column
  110900. */
  110901. p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  110902. if( (zName = pEList->a[i].zName)!=0 ){
  110903. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  110904. }else{
  110905. Expr *pColExpr = p; /* The expression that is the result column name */
  110906. Table *pTab; /* Table associated with this expression */
  110907. while( pColExpr->op==TK_DOT ){
  110908. pColExpr = pColExpr->pRight;
  110909. assert( pColExpr!=0 );
  110910. }
  110911. if( pColExpr->op==TK_COLUMN && pColExpr->pTab!=0 ){
  110912. /* For columns use the column name name */
  110913. int iCol = pColExpr->iColumn;
  110914. pTab = pColExpr->pTab;
  110915. if( iCol<0 ) iCol = pTab->iPKey;
  110916. zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
  110917. }else if( pColExpr->op==TK_ID ){
  110918. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  110919. zName = pColExpr->u.zToken;
  110920. }else{
  110921. /* Use the original text of the column expression as its name */
  110922. zName = pEList->a[i].zSpan;
  110923. }
  110924. }
  110925. zName = sqlite3MPrintf(db, "%s", zName);
  110926. /* Make sure the column name is unique. If the name is not unique,
  110927. ** append an integer to the name so that it becomes unique.
  110928. */
  110929. cnt = 0;
  110930. while( zName && sqlite3HashFind(&ht, zName)!=0 ){
  110931. nName = sqlite3Strlen30(zName);
  110932. if( nName>0 ){
  110933. for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
  110934. if( zName[j]==':' ) nName = j;
  110935. }
  110936. zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
  110937. if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
  110938. }
  110939. pCol->zName = zName;
  110940. sqlite3ColumnPropertiesFromName(0, pCol);
  110941. if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
  110942. sqlite3OomFault(db);
  110943. }
  110944. }
  110945. sqlite3HashClear(&ht);
  110946. if( db->mallocFailed ){
  110947. for(j=0; j<i; j++){
  110948. sqlite3DbFree(db, aCol[j].zName);
  110949. }
  110950. sqlite3DbFree(db, aCol);
  110951. *paCol = 0;
  110952. *pnCol = 0;
  110953. return SQLITE_NOMEM_BKPT;
  110954. }
  110955. return SQLITE_OK;
  110956. }
  110957. /*
  110958. ** Add type and collation information to a column list based on
  110959. ** a SELECT statement.
  110960. **
  110961. ** The column list presumably came from selectColumnNamesFromExprList().
  110962. ** The column list has only names, not types or collations. This
  110963. ** routine goes through and adds the types and collations.
  110964. **
  110965. ** This routine requires that all identifiers in the SELECT
  110966. ** statement be resolved.
  110967. */
  110968. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
  110969. Parse *pParse, /* Parsing contexts */
  110970. Table *pTab, /* Add column type information to this table */
  110971. Select *pSelect /* SELECT used to determine types and collations */
  110972. ){
  110973. sqlite3 *db = pParse->db;
  110974. NameContext sNC;
  110975. Column *pCol;
  110976. CollSeq *pColl;
  110977. int i;
  110978. Expr *p;
  110979. struct ExprList_item *a;
  110980. u64 szAll = 0;
  110981. assert( pSelect!=0 );
  110982. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  110983. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  110984. if( db->mallocFailed ) return;
  110985. memset(&sNC, 0, sizeof(sNC));
  110986. sNC.pSrcList = pSelect->pSrc;
  110987. a = pSelect->pEList->a;
  110988. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  110989. const char *zType;
  110990. int n, m;
  110991. p = a[i].pExpr;
  110992. zType = columnType(&sNC, p, 0, 0, 0, &pCol->szEst);
  110993. szAll += pCol->szEst;
  110994. pCol->affinity = sqlite3ExprAffinity(p);
  110995. if( zType && (m = sqlite3Strlen30(zType))>0 ){
  110996. n = sqlite3Strlen30(pCol->zName);
  110997. pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
  110998. if( pCol->zName ){
  110999. memcpy(&pCol->zName[n+1], zType, m+1);
  111000. pCol->colFlags |= COLFLAG_HASTYPE;
  111001. }
  111002. }
  111003. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
  111004. pColl = sqlite3ExprCollSeq(pParse, p);
  111005. if( pColl && pCol->zColl==0 ){
  111006. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  111007. }
  111008. }
  111009. pTab->szTabRow = sqlite3LogEst(szAll*4);
  111010. }
  111011. /*
  111012. ** Given a SELECT statement, generate a Table structure that describes
  111013. ** the result set of that SELECT.
  111014. */
  111015. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  111016. Table *pTab;
  111017. sqlite3 *db = pParse->db;
  111018. int savedFlags;
  111019. savedFlags = db->flags;
  111020. db->flags &= ~SQLITE_FullColNames;
  111021. db->flags |= SQLITE_ShortColNames;
  111022. sqlite3SelectPrep(pParse, pSelect, 0);
  111023. if( pParse->nErr ) return 0;
  111024. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  111025. db->flags = savedFlags;
  111026. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  111027. if( pTab==0 ){
  111028. return 0;
  111029. }
  111030. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  111031. ** is disabled */
  111032. assert( db->lookaside.bDisable );
  111033. pTab->nTabRef = 1;
  111034. pTab->zName = 0;
  111035. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  111036. sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  111037. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  111038. pTab->iPKey = -1;
  111039. if( db->mallocFailed ){
  111040. sqlite3DeleteTable(db, pTab);
  111041. return 0;
  111042. }
  111043. return pTab;
  111044. }
  111045. /*
  111046. ** Get a VDBE for the given parser context. Create a new one if necessary.
  111047. ** If an error occurs, return NULL and leave a message in pParse.
  111048. */
  111049. static SQLITE_NOINLINE Vdbe *allocVdbe(Parse *pParse){
  111050. Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
  111051. if( v ) sqlite3VdbeAddOp2(v, OP_Init, 0, 1);
  111052. if( pParse->pToplevel==0
  111053. && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
  111054. ){
  111055. pParse->okConstFactor = 1;
  111056. }
  111057. return v;
  111058. }
  111059. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  111060. Vdbe *v = pParse->pVdbe;
  111061. return v ? v : allocVdbe(pParse);
  111062. }
  111063. /*
  111064. ** Compute the iLimit and iOffset fields of the SELECT based on the
  111065. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  111066. ** that appear in the original SQL statement after the LIMIT and OFFSET
  111067. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  111068. ** are the integer memory register numbers for counters used to compute
  111069. ** the limit and offset. If there is no limit and/or offset, then
  111070. ** iLimit and iOffset are negative.
  111071. **
  111072. ** This routine changes the values of iLimit and iOffset only if
  111073. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  111074. ** iOffset should have been preset to appropriate default values (zero)
  111075. ** prior to calling this routine.
  111076. **
  111077. ** The iOffset register (if it exists) is initialized to the value
  111078. ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
  111079. ** iOffset+1 is initialized to LIMIT+OFFSET.
  111080. **
  111081. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  111082. ** redefined. The UNION ALL operator uses this property to force
  111083. ** the reuse of the same limit and offset registers across multiple
  111084. ** SELECT statements.
  111085. */
  111086. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  111087. Vdbe *v = 0;
  111088. int iLimit = 0;
  111089. int iOffset;
  111090. int n;
  111091. if( p->iLimit ) return;
  111092. /*
  111093. ** "LIMIT -1" always shows all rows. There is some
  111094. ** controversy about what the correct behavior should be.
  111095. ** The current implementation interprets "LIMIT 0" to mean
  111096. ** no rows.
  111097. */
  111098. sqlite3ExprCacheClear(pParse);
  111099. assert( p->pOffset==0 || p->pLimit!=0 );
  111100. if( p->pLimit ){
  111101. p->iLimit = iLimit = ++pParse->nMem;
  111102. v = sqlite3GetVdbe(pParse);
  111103. assert( v!=0 );
  111104. if( sqlite3ExprIsInteger(p->pLimit, &n) ){
  111105. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  111106. VdbeComment((v, "LIMIT counter"));
  111107. if( n==0 ){
  111108. sqlite3VdbeGoto(v, iBreak);
  111109. }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
  111110. p->nSelectRow = sqlite3LogEst((u64)n);
  111111. p->selFlags |= SF_FixedLimit;
  111112. }
  111113. }else{
  111114. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  111115. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
  111116. VdbeComment((v, "LIMIT counter"));
  111117. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
  111118. }
  111119. if( p->pOffset ){
  111120. p->iOffset = iOffset = ++pParse->nMem;
  111121. pParse->nMem++; /* Allocate an extra register for limit+offset */
  111122. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  111123. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
  111124. VdbeComment((v, "OFFSET counter"));
  111125. sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
  111126. VdbeComment((v, "LIMIT+OFFSET"));
  111127. }
  111128. }
  111129. }
  111130. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  111131. /*
  111132. ** Return the appropriate collating sequence for the iCol-th column of
  111133. ** the result set for the compound-select statement "p". Return NULL if
  111134. ** the column has no default collating sequence.
  111135. **
  111136. ** The collating sequence for the compound select is taken from the
  111137. ** left-most term of the select that has a collating sequence.
  111138. */
  111139. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  111140. CollSeq *pRet;
  111141. if( p->pPrior ){
  111142. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  111143. }else{
  111144. pRet = 0;
  111145. }
  111146. assert( iCol>=0 );
  111147. /* iCol must be less than p->pEList->nExpr. Otherwise an error would
  111148. ** have been thrown during name resolution and we would not have gotten
  111149. ** this far */
  111150. if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
  111151. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  111152. }
  111153. return pRet;
  111154. }
  111155. /*
  111156. ** The select statement passed as the second parameter is a compound SELECT
  111157. ** with an ORDER BY clause. This function allocates and returns a KeyInfo
  111158. ** structure suitable for implementing the ORDER BY.
  111159. **
  111160. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  111161. ** function is responsible for ensuring that this structure is eventually
  111162. ** freed.
  111163. */
  111164. static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
  111165. ExprList *pOrderBy = p->pOrderBy;
  111166. int nOrderBy = p->pOrderBy->nExpr;
  111167. sqlite3 *db = pParse->db;
  111168. KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
  111169. if( pRet ){
  111170. int i;
  111171. for(i=0; i<nOrderBy; i++){
  111172. struct ExprList_item *pItem = &pOrderBy->a[i];
  111173. Expr *pTerm = pItem->pExpr;
  111174. CollSeq *pColl;
  111175. if( pTerm->flags & EP_Collate ){
  111176. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  111177. }else{
  111178. pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
  111179. if( pColl==0 ) pColl = db->pDfltColl;
  111180. pOrderBy->a[i].pExpr =
  111181. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  111182. }
  111183. assert( sqlite3KeyInfoIsWriteable(pRet) );
  111184. pRet->aColl[i] = pColl;
  111185. pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  111186. }
  111187. }
  111188. return pRet;
  111189. }
  111190. #ifndef SQLITE_OMIT_CTE
  111191. /*
  111192. ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
  111193. ** query of the form:
  111194. **
  111195. ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
  111196. ** \___________/ \_______________/
  111197. ** p->pPrior p
  111198. **
  111199. **
  111200. ** There is exactly one reference to the recursive-table in the FROM clause
  111201. ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
  111202. **
  111203. ** The setup-query runs once to generate an initial set of rows that go
  111204. ** into a Queue table. Rows are extracted from the Queue table one by
  111205. ** one. Each row extracted from Queue is output to pDest. Then the single
  111206. ** extracted row (now in the iCurrent table) becomes the content of the
  111207. ** recursive-table for a recursive-query run. The output of the recursive-query
  111208. ** is added back into the Queue table. Then another row is extracted from Queue
  111209. ** and the iteration continues until the Queue table is empty.
  111210. **
  111211. ** If the compound query operator is UNION then no duplicate rows are ever
  111212. ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
  111213. ** that have ever been inserted into Queue and causes duplicates to be
  111214. ** discarded. If the operator is UNION ALL, then duplicates are allowed.
  111215. **
  111216. ** If the query has an ORDER BY, then entries in the Queue table are kept in
  111217. ** ORDER BY order and the first entry is extracted for each cycle. Without
  111218. ** an ORDER BY, the Queue table is just a FIFO.
  111219. **
  111220. ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
  111221. ** have been output to pDest. A LIMIT of zero means to output no rows and a
  111222. ** negative LIMIT means to output all rows. If there is also an OFFSET clause
  111223. ** with a positive value, then the first OFFSET outputs are discarded rather
  111224. ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
  111225. ** rows have been skipped.
  111226. */
  111227. static void generateWithRecursiveQuery(
  111228. Parse *pParse, /* Parsing context */
  111229. Select *p, /* The recursive SELECT to be coded */
  111230. SelectDest *pDest /* What to do with query results */
  111231. ){
  111232. SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
  111233. int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
  111234. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  111235. Select *pSetup = p->pPrior; /* The setup query */
  111236. int addrTop; /* Top of the loop */
  111237. int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
  111238. int iCurrent = 0; /* The Current table */
  111239. int regCurrent; /* Register holding Current table */
  111240. int iQueue; /* The Queue table */
  111241. int iDistinct = 0; /* To ensure unique results if UNION */
  111242. int eDest = SRT_Fifo; /* How to write to Queue */
  111243. SelectDest destQueue; /* SelectDest targetting the Queue table */
  111244. int i; /* Loop counter */
  111245. int rc; /* Result code */
  111246. ExprList *pOrderBy; /* The ORDER BY clause */
  111247. Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */
  111248. int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
  111249. /* Obtain authorization to do a recursive query */
  111250. if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
  111251. /* Process the LIMIT and OFFSET clauses, if they exist */
  111252. addrBreak = sqlite3VdbeMakeLabel(v);
  111253. p->nSelectRow = 320; /* 4 billion rows */
  111254. computeLimitRegisters(pParse, p, addrBreak);
  111255. pLimit = p->pLimit;
  111256. pOffset = p->pOffset;
  111257. regLimit = p->iLimit;
  111258. regOffset = p->iOffset;
  111259. p->pLimit = p->pOffset = 0;
  111260. p->iLimit = p->iOffset = 0;
  111261. pOrderBy = p->pOrderBy;
  111262. /* Locate the cursor number of the Current table */
  111263. for(i=0; ALWAYS(i<pSrc->nSrc); i++){
  111264. if( pSrc->a[i].fg.isRecursive ){
  111265. iCurrent = pSrc->a[i].iCursor;
  111266. break;
  111267. }
  111268. }
  111269. /* Allocate cursors numbers for Queue and Distinct. The cursor number for
  111270. ** the Distinct table must be exactly one greater than Queue in order
  111271. ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
  111272. iQueue = pParse->nTab++;
  111273. if( p->op==TK_UNION ){
  111274. eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
  111275. iDistinct = pParse->nTab++;
  111276. }else{
  111277. eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
  111278. }
  111279. sqlite3SelectDestInit(&destQueue, eDest, iQueue);
  111280. /* Allocate cursors for Current, Queue, and Distinct. */
  111281. regCurrent = ++pParse->nMem;
  111282. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
  111283. if( pOrderBy ){
  111284. KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
  111285. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
  111286. (char*)pKeyInfo, P4_KEYINFO);
  111287. destQueue.pOrderBy = pOrderBy;
  111288. }else{
  111289. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
  111290. }
  111291. VdbeComment((v, "Queue table"));
  111292. if( iDistinct ){
  111293. p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
  111294. p->selFlags |= SF_UsesEphemeral;
  111295. }
  111296. /* Detach the ORDER BY clause from the compound SELECT */
  111297. p->pOrderBy = 0;
  111298. /* Store the results of the setup-query in Queue. */
  111299. pSetup->pNext = 0;
  111300. rc = sqlite3Select(pParse, pSetup, &destQueue);
  111301. pSetup->pNext = p;
  111302. if( rc ) goto end_of_recursive_query;
  111303. /* Find the next row in the Queue and output that row */
  111304. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
  111305. /* Transfer the next row in Queue over to Current */
  111306. sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
  111307. if( pOrderBy ){
  111308. sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
  111309. }else{
  111310. sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
  111311. }
  111312. sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
  111313. /* Output the single row in Current */
  111314. addrCont = sqlite3VdbeMakeLabel(v);
  111315. codeOffset(v, regOffset, addrCont);
  111316. selectInnerLoop(pParse, p, p->pEList, iCurrent,
  111317. 0, 0, pDest, addrCont, addrBreak);
  111318. if( regLimit ){
  111319. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
  111320. VdbeCoverage(v);
  111321. }
  111322. sqlite3VdbeResolveLabel(v, addrCont);
  111323. /* Execute the recursive SELECT taking the single row in Current as
  111324. ** the value for the recursive-table. Store the results in the Queue.
  111325. */
  111326. if( p->selFlags & SF_Aggregate ){
  111327. sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
  111328. }else{
  111329. p->pPrior = 0;
  111330. sqlite3Select(pParse, p, &destQueue);
  111331. assert( p->pPrior==0 );
  111332. p->pPrior = pSetup;
  111333. }
  111334. /* Keep running the loop until the Queue is empty */
  111335. sqlite3VdbeGoto(v, addrTop);
  111336. sqlite3VdbeResolveLabel(v, addrBreak);
  111337. end_of_recursive_query:
  111338. sqlite3ExprListDelete(pParse->db, p->pOrderBy);
  111339. p->pOrderBy = pOrderBy;
  111340. p->pLimit = pLimit;
  111341. p->pOffset = pOffset;
  111342. return;
  111343. }
  111344. #endif /* SQLITE_OMIT_CTE */
  111345. /* Forward references */
  111346. static int multiSelectOrderBy(
  111347. Parse *pParse, /* Parsing context */
  111348. Select *p, /* The right-most of SELECTs to be coded */
  111349. SelectDest *pDest /* What to do with query results */
  111350. );
  111351. /*
  111352. ** Handle the special case of a compound-select that originates from a
  111353. ** VALUES clause. By handling this as a special case, we avoid deep
  111354. ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
  111355. ** on a VALUES clause.
  111356. **
  111357. ** Because the Select object originates from a VALUES clause:
  111358. ** (1) It has no LIMIT or OFFSET
  111359. ** (2) All terms are UNION ALL
  111360. ** (3) There is no ORDER BY clause
  111361. */
  111362. static int multiSelectValues(
  111363. Parse *pParse, /* Parsing context */
  111364. Select *p, /* The right-most of SELECTs to be coded */
  111365. SelectDest *pDest /* What to do with query results */
  111366. ){
  111367. Select *pPrior;
  111368. int nRow = 1;
  111369. int rc = 0;
  111370. assert( p->selFlags & SF_MultiValue );
  111371. do{
  111372. assert( p->selFlags & SF_Values );
  111373. assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
  111374. assert( p->pLimit==0 );
  111375. assert( p->pOffset==0 );
  111376. assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
  111377. if( p->pPrior==0 ) break;
  111378. assert( p->pPrior->pNext==p );
  111379. p = p->pPrior;
  111380. nRow++;
  111381. }while(1);
  111382. while( p ){
  111383. pPrior = p->pPrior;
  111384. p->pPrior = 0;
  111385. rc = sqlite3Select(pParse, p, pDest);
  111386. p->pPrior = pPrior;
  111387. if( rc ) break;
  111388. p->nSelectRow = nRow;
  111389. p = p->pNext;
  111390. }
  111391. return rc;
  111392. }
  111393. /*
  111394. ** This routine is called to process a compound query form from
  111395. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  111396. ** INTERSECT
  111397. **
  111398. ** "p" points to the right-most of the two queries. the query on the
  111399. ** left is p->pPrior. The left query could also be a compound query
  111400. ** in which case this routine will be called recursively.
  111401. **
  111402. ** The results of the total query are to be written into a destination
  111403. ** of type eDest with parameter iParm.
  111404. **
  111405. ** Example 1: Consider a three-way compound SQL statement.
  111406. **
  111407. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  111408. **
  111409. ** This statement is parsed up as follows:
  111410. **
  111411. ** SELECT c FROM t3
  111412. ** |
  111413. ** `-----> SELECT b FROM t2
  111414. ** |
  111415. ** `------> SELECT a FROM t1
  111416. **
  111417. ** The arrows in the diagram above represent the Select.pPrior pointer.
  111418. ** So if this routine is called with p equal to the t3 query, then
  111419. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  111420. **
  111421. ** Notice that because of the way SQLite parses compound SELECTs, the
  111422. ** individual selects always group from left to right.
  111423. */
  111424. static int multiSelect(
  111425. Parse *pParse, /* Parsing context */
  111426. Select *p, /* The right-most of SELECTs to be coded */
  111427. SelectDest *pDest /* What to do with query results */
  111428. ){
  111429. int rc = SQLITE_OK; /* Success code from a subroutine */
  111430. Select *pPrior; /* Another SELECT immediately to our left */
  111431. Vdbe *v; /* Generate code to this VDBE */
  111432. SelectDest dest; /* Alternative data destination */
  111433. Select *pDelete = 0; /* Chain of simple selects to delete */
  111434. sqlite3 *db; /* Database connection */
  111435. #ifndef SQLITE_OMIT_EXPLAIN
  111436. int iSub1 = 0; /* EQP id of left-hand query */
  111437. int iSub2 = 0; /* EQP id of right-hand query */
  111438. #endif
  111439. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  111440. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  111441. */
  111442. assert( p && p->pPrior ); /* Calling function guarantees this much */
  111443. assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
  111444. db = pParse->db;
  111445. pPrior = p->pPrior;
  111446. dest = *pDest;
  111447. if( pPrior->pOrderBy ){
  111448. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  111449. selectOpName(p->op));
  111450. rc = 1;
  111451. goto multi_select_end;
  111452. }
  111453. if( pPrior->pLimit ){
  111454. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  111455. selectOpName(p->op));
  111456. rc = 1;
  111457. goto multi_select_end;
  111458. }
  111459. v = sqlite3GetVdbe(pParse);
  111460. assert( v!=0 ); /* The VDBE already created by calling function */
  111461. /* Create the destination temporary table if necessary
  111462. */
  111463. if( dest.eDest==SRT_EphemTab ){
  111464. assert( p->pEList );
  111465. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  111466. dest.eDest = SRT_Table;
  111467. }
  111468. /* Special handling for a compound-select that originates as a VALUES clause.
  111469. */
  111470. if( p->selFlags & SF_MultiValue ){
  111471. rc = multiSelectValues(pParse, p, &dest);
  111472. goto multi_select_end;
  111473. }
  111474. /* Make sure all SELECTs in the statement have the same number of elements
  111475. ** in their result sets.
  111476. */
  111477. assert( p->pEList && pPrior->pEList );
  111478. assert( p->pEList->nExpr==pPrior->pEList->nExpr );
  111479. #ifndef SQLITE_OMIT_CTE
  111480. if( p->selFlags & SF_Recursive ){
  111481. generateWithRecursiveQuery(pParse, p, &dest);
  111482. }else
  111483. #endif
  111484. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  111485. */
  111486. if( p->pOrderBy ){
  111487. return multiSelectOrderBy(pParse, p, pDest);
  111488. }else
  111489. /* Generate code for the left and right SELECT statements.
  111490. */
  111491. switch( p->op ){
  111492. case TK_ALL: {
  111493. int addr = 0;
  111494. int nLimit;
  111495. assert( !pPrior->pLimit );
  111496. pPrior->iLimit = p->iLimit;
  111497. pPrior->iOffset = p->iOffset;
  111498. pPrior->pLimit = p->pLimit;
  111499. pPrior->pOffset = p->pOffset;
  111500. explainSetInteger(iSub1, pParse->iNextSelectId);
  111501. rc = sqlite3Select(pParse, pPrior, &dest);
  111502. p->pLimit = 0;
  111503. p->pOffset = 0;
  111504. if( rc ){
  111505. goto multi_select_end;
  111506. }
  111507. p->pPrior = 0;
  111508. p->iLimit = pPrior->iLimit;
  111509. p->iOffset = pPrior->iOffset;
  111510. if( p->iLimit ){
  111511. addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
  111512. VdbeComment((v, "Jump ahead if LIMIT reached"));
  111513. if( p->iOffset ){
  111514. sqlite3VdbeAddOp3(v, OP_OffsetLimit,
  111515. p->iLimit, p->iOffset+1, p->iOffset);
  111516. }
  111517. }
  111518. explainSetInteger(iSub2, pParse->iNextSelectId);
  111519. rc = sqlite3Select(pParse, p, &dest);
  111520. testcase( rc!=SQLITE_OK );
  111521. pDelete = p->pPrior;
  111522. p->pPrior = pPrior;
  111523. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  111524. if( pPrior->pLimit
  111525. && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
  111526. && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
  111527. ){
  111528. p->nSelectRow = sqlite3LogEst((u64)nLimit);
  111529. }
  111530. if( addr ){
  111531. sqlite3VdbeJumpHere(v, addr);
  111532. }
  111533. break;
  111534. }
  111535. case TK_EXCEPT:
  111536. case TK_UNION: {
  111537. int unionTab; /* Cursor number of the temporary table holding result */
  111538. u8 op = 0; /* One of the SRT_ operations to apply to self */
  111539. int priorOp; /* The SRT_ operation to apply to prior selects */
  111540. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  111541. int addr;
  111542. SelectDest uniondest;
  111543. testcase( p->op==TK_EXCEPT );
  111544. testcase( p->op==TK_UNION );
  111545. priorOp = SRT_Union;
  111546. if( dest.eDest==priorOp ){
  111547. /* We can reuse a temporary table generated by a SELECT to our
  111548. ** right.
  111549. */
  111550. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  111551. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  111552. unionTab = dest.iSDParm;
  111553. }else{
  111554. /* We will need to create our own temporary table to hold the
  111555. ** intermediate results.
  111556. */
  111557. unionTab = pParse->nTab++;
  111558. assert( p->pOrderBy==0 );
  111559. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  111560. assert( p->addrOpenEphm[0] == -1 );
  111561. p->addrOpenEphm[0] = addr;
  111562. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  111563. assert( p->pEList );
  111564. }
  111565. /* Code the SELECT statements to our left
  111566. */
  111567. assert( !pPrior->pOrderBy );
  111568. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  111569. explainSetInteger(iSub1, pParse->iNextSelectId);
  111570. rc = sqlite3Select(pParse, pPrior, &uniondest);
  111571. if( rc ){
  111572. goto multi_select_end;
  111573. }
  111574. /* Code the current SELECT statement
  111575. */
  111576. if( p->op==TK_EXCEPT ){
  111577. op = SRT_Except;
  111578. }else{
  111579. assert( p->op==TK_UNION );
  111580. op = SRT_Union;
  111581. }
  111582. p->pPrior = 0;
  111583. pLimit = p->pLimit;
  111584. p->pLimit = 0;
  111585. pOffset = p->pOffset;
  111586. p->pOffset = 0;
  111587. uniondest.eDest = op;
  111588. explainSetInteger(iSub2, pParse->iNextSelectId);
  111589. rc = sqlite3Select(pParse, p, &uniondest);
  111590. testcase( rc!=SQLITE_OK );
  111591. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  111592. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  111593. sqlite3ExprListDelete(db, p->pOrderBy);
  111594. pDelete = p->pPrior;
  111595. p->pPrior = pPrior;
  111596. p->pOrderBy = 0;
  111597. if( p->op==TK_UNION ){
  111598. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  111599. }
  111600. sqlite3ExprDelete(db, p->pLimit);
  111601. p->pLimit = pLimit;
  111602. p->pOffset = pOffset;
  111603. p->iLimit = 0;
  111604. p->iOffset = 0;
  111605. /* Convert the data in the temporary table into whatever form
  111606. ** it is that we currently need.
  111607. */
  111608. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  111609. if( dest.eDest!=priorOp ){
  111610. int iCont, iBreak, iStart;
  111611. assert( p->pEList );
  111612. if( dest.eDest==SRT_Output ){
  111613. Select *pFirst = p;
  111614. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  111615. generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
  111616. }
  111617. iBreak = sqlite3VdbeMakeLabel(v);
  111618. iCont = sqlite3VdbeMakeLabel(v);
  111619. computeLimitRegisters(pParse, p, iBreak);
  111620. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
  111621. iStart = sqlite3VdbeCurrentAddr(v);
  111622. selectInnerLoop(pParse, p, p->pEList, unionTab,
  111623. 0, 0, &dest, iCont, iBreak);
  111624. sqlite3VdbeResolveLabel(v, iCont);
  111625. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
  111626. sqlite3VdbeResolveLabel(v, iBreak);
  111627. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  111628. }
  111629. break;
  111630. }
  111631. default: assert( p->op==TK_INTERSECT ); {
  111632. int tab1, tab2;
  111633. int iCont, iBreak, iStart;
  111634. Expr *pLimit, *pOffset;
  111635. int addr;
  111636. SelectDest intersectdest;
  111637. int r1;
  111638. /* INTERSECT is different from the others since it requires
  111639. ** two temporary tables. Hence it has its own case. Begin
  111640. ** by allocating the tables we will need.
  111641. */
  111642. tab1 = pParse->nTab++;
  111643. tab2 = pParse->nTab++;
  111644. assert( p->pOrderBy==0 );
  111645. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  111646. assert( p->addrOpenEphm[0] == -1 );
  111647. p->addrOpenEphm[0] = addr;
  111648. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  111649. assert( p->pEList );
  111650. /* Code the SELECTs to our left into temporary table "tab1".
  111651. */
  111652. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  111653. explainSetInteger(iSub1, pParse->iNextSelectId);
  111654. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  111655. if( rc ){
  111656. goto multi_select_end;
  111657. }
  111658. /* Code the current SELECT into temporary table "tab2"
  111659. */
  111660. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  111661. assert( p->addrOpenEphm[1] == -1 );
  111662. p->addrOpenEphm[1] = addr;
  111663. p->pPrior = 0;
  111664. pLimit = p->pLimit;
  111665. p->pLimit = 0;
  111666. pOffset = p->pOffset;
  111667. p->pOffset = 0;
  111668. intersectdest.iSDParm = tab2;
  111669. explainSetInteger(iSub2, pParse->iNextSelectId);
  111670. rc = sqlite3Select(pParse, p, &intersectdest);
  111671. testcase( rc!=SQLITE_OK );
  111672. pDelete = p->pPrior;
  111673. p->pPrior = pPrior;
  111674. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  111675. sqlite3ExprDelete(db, p->pLimit);
  111676. p->pLimit = pLimit;
  111677. p->pOffset = pOffset;
  111678. /* Generate code to take the intersection of the two temporary
  111679. ** tables.
  111680. */
  111681. assert( p->pEList );
  111682. if( dest.eDest==SRT_Output ){
  111683. Select *pFirst = p;
  111684. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  111685. generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
  111686. }
  111687. iBreak = sqlite3VdbeMakeLabel(v);
  111688. iCont = sqlite3VdbeMakeLabel(v);
  111689. computeLimitRegisters(pParse, p, iBreak);
  111690. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
  111691. r1 = sqlite3GetTempReg(pParse);
  111692. iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
  111693. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
  111694. sqlite3ReleaseTempReg(pParse, r1);
  111695. selectInnerLoop(pParse, p, p->pEList, tab1,
  111696. 0, 0, &dest, iCont, iBreak);
  111697. sqlite3VdbeResolveLabel(v, iCont);
  111698. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
  111699. sqlite3VdbeResolveLabel(v, iBreak);
  111700. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  111701. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  111702. break;
  111703. }
  111704. }
  111705. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  111706. /* Compute collating sequences used by
  111707. ** temporary tables needed to implement the compound select.
  111708. ** Attach the KeyInfo structure to all temporary tables.
  111709. **
  111710. ** This section is run by the right-most SELECT statement only.
  111711. ** SELECT statements to the left always skip this part. The right-most
  111712. ** SELECT might also skip this part if it has no ORDER BY clause and
  111713. ** no temp tables are required.
  111714. */
  111715. if( p->selFlags & SF_UsesEphemeral ){
  111716. int i; /* Loop counter */
  111717. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  111718. Select *pLoop; /* For looping through SELECT statements */
  111719. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  111720. int nCol; /* Number of columns in result set */
  111721. assert( p->pNext==0 );
  111722. nCol = p->pEList->nExpr;
  111723. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
  111724. if( !pKeyInfo ){
  111725. rc = SQLITE_NOMEM_BKPT;
  111726. goto multi_select_end;
  111727. }
  111728. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  111729. *apColl = multiSelectCollSeq(pParse, p, i);
  111730. if( 0==*apColl ){
  111731. *apColl = db->pDfltColl;
  111732. }
  111733. }
  111734. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  111735. for(i=0; i<2; i++){
  111736. int addr = pLoop->addrOpenEphm[i];
  111737. if( addr<0 ){
  111738. /* If [0] is unused then [1] is also unused. So we can
  111739. ** always safely abort as soon as the first unused slot is found */
  111740. assert( pLoop->addrOpenEphm[1]<0 );
  111741. break;
  111742. }
  111743. sqlite3VdbeChangeP2(v, addr, nCol);
  111744. sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
  111745. P4_KEYINFO);
  111746. pLoop->addrOpenEphm[i] = -1;
  111747. }
  111748. }
  111749. sqlite3KeyInfoUnref(pKeyInfo);
  111750. }
  111751. multi_select_end:
  111752. pDest->iSdst = dest.iSdst;
  111753. pDest->nSdst = dest.nSdst;
  111754. sqlite3SelectDelete(db, pDelete);
  111755. return rc;
  111756. }
  111757. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  111758. /*
  111759. ** Error message for when two or more terms of a compound select have different
  111760. ** size result sets.
  111761. */
  111762. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
  111763. if( p->selFlags & SF_Values ){
  111764. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  111765. }else{
  111766. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  111767. " do not have the same number of result columns", selectOpName(p->op));
  111768. }
  111769. }
  111770. /*
  111771. ** Code an output subroutine for a coroutine implementation of a
  111772. ** SELECT statment.
  111773. **
  111774. ** The data to be output is contained in pIn->iSdst. There are
  111775. ** pIn->nSdst columns to be output. pDest is where the output should
  111776. ** be sent.
  111777. **
  111778. ** regReturn is the number of the register holding the subroutine
  111779. ** return address.
  111780. **
  111781. ** If regPrev>0 then it is the first register in a vector that
  111782. ** records the previous output. mem[regPrev] is a flag that is false
  111783. ** if there has been no previous output. If regPrev>0 then code is
  111784. ** generated to suppress duplicates. pKeyInfo is used for comparing
  111785. ** keys.
  111786. **
  111787. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  111788. ** iBreak.
  111789. */
  111790. static int generateOutputSubroutine(
  111791. Parse *pParse, /* Parsing context */
  111792. Select *p, /* The SELECT statement */
  111793. SelectDest *pIn, /* Coroutine supplying data */
  111794. SelectDest *pDest, /* Where to send the data */
  111795. int regReturn, /* The return address register */
  111796. int regPrev, /* Previous result register. No uniqueness if 0 */
  111797. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  111798. int iBreak /* Jump here if we hit the LIMIT */
  111799. ){
  111800. Vdbe *v = pParse->pVdbe;
  111801. int iContinue;
  111802. int addr;
  111803. addr = sqlite3VdbeCurrentAddr(v);
  111804. iContinue = sqlite3VdbeMakeLabel(v);
  111805. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  111806. */
  111807. if( regPrev ){
  111808. int addr1, addr2;
  111809. addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
  111810. addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  111811. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  111812. sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
  111813. sqlite3VdbeJumpHere(v, addr1);
  111814. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  111815. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  111816. }
  111817. if( pParse->db->mallocFailed ) return 0;
  111818. /* Suppress the first OFFSET entries if there is an OFFSET clause
  111819. */
  111820. codeOffset(v, p->iOffset, iContinue);
  111821. assert( pDest->eDest!=SRT_Exists );
  111822. assert( pDest->eDest!=SRT_Table );
  111823. switch( pDest->eDest ){
  111824. /* Store the result as data using a unique key.
  111825. */
  111826. case SRT_EphemTab: {
  111827. int r1 = sqlite3GetTempReg(pParse);
  111828. int r2 = sqlite3GetTempReg(pParse);
  111829. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  111830. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  111831. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  111832. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  111833. sqlite3ReleaseTempReg(pParse, r2);
  111834. sqlite3ReleaseTempReg(pParse, r1);
  111835. break;
  111836. }
  111837. #ifndef SQLITE_OMIT_SUBQUERY
  111838. /* If we are creating a set for an "expr IN (SELECT ...)".
  111839. */
  111840. case SRT_Set: {
  111841. int r1;
  111842. testcase( pIn->nSdst>1 );
  111843. r1 = sqlite3GetTempReg(pParse);
  111844. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
  111845. r1, pDest->zAffSdst, pIn->nSdst);
  111846. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  111847. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
  111848. pIn->iSdst, pIn->nSdst);
  111849. sqlite3ReleaseTempReg(pParse, r1);
  111850. break;
  111851. }
  111852. /* If this is a scalar select that is part of an expression, then
  111853. ** store the results in the appropriate memory cell and break out
  111854. ** of the scan loop.
  111855. */
  111856. case SRT_Mem: {
  111857. assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
  111858. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  111859. /* The LIMIT clause will jump out of the loop for us */
  111860. break;
  111861. }
  111862. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  111863. /* The results are stored in a sequence of registers
  111864. ** starting at pDest->iSdst. Then the co-routine yields.
  111865. */
  111866. case SRT_Coroutine: {
  111867. if( pDest->iSdst==0 ){
  111868. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  111869. pDest->nSdst = pIn->nSdst;
  111870. }
  111871. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
  111872. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  111873. break;
  111874. }
  111875. /* If none of the above, then the result destination must be
  111876. ** SRT_Output. This routine is never called with any other
  111877. ** destination other than the ones handled above or SRT_Output.
  111878. **
  111879. ** For SRT_Output, results are stored in a sequence of registers.
  111880. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  111881. ** return the next row of result.
  111882. */
  111883. default: {
  111884. assert( pDest->eDest==SRT_Output );
  111885. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  111886. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  111887. break;
  111888. }
  111889. }
  111890. /* Jump to the end of the loop if the LIMIT is reached.
  111891. */
  111892. if( p->iLimit ){
  111893. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  111894. }
  111895. /* Generate the subroutine return
  111896. */
  111897. sqlite3VdbeResolveLabel(v, iContinue);
  111898. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  111899. return addr;
  111900. }
  111901. /*
  111902. ** Alternative compound select code generator for cases when there
  111903. ** is an ORDER BY clause.
  111904. **
  111905. ** We assume a query of the following form:
  111906. **
  111907. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  111908. **
  111909. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  111910. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  111911. ** co-routines. Then run the co-routines in parallel and merge the results
  111912. ** into the output. In addition to the two coroutines (called selectA and
  111913. ** selectB) there are 7 subroutines:
  111914. **
  111915. ** outA: Move the output of the selectA coroutine into the output
  111916. ** of the compound query.
  111917. **
  111918. ** outB: Move the output of the selectB coroutine into the output
  111919. ** of the compound query. (Only generated for UNION and
  111920. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  111921. ** appears only in B.)
  111922. **
  111923. ** AltB: Called when there is data from both coroutines and A<B.
  111924. **
  111925. ** AeqB: Called when there is data from both coroutines and A==B.
  111926. **
  111927. ** AgtB: Called when there is data from both coroutines and A>B.
  111928. **
  111929. ** EofA: Called when data is exhausted from selectA.
  111930. **
  111931. ** EofB: Called when data is exhausted from selectB.
  111932. **
  111933. ** The implementation of the latter five subroutines depend on which
  111934. ** <operator> is used:
  111935. **
  111936. **
  111937. ** UNION ALL UNION EXCEPT INTERSECT
  111938. ** ------------- ----------------- -------------- -----------------
  111939. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  111940. **
  111941. ** AeqB: outA, nextA nextA nextA outA, nextA
  111942. **
  111943. ** AgtB: outB, nextB outB, nextB nextB nextB
  111944. **
  111945. ** EofA: outB, nextB outB, nextB halt halt
  111946. **
  111947. ** EofB: outA, nextA outA, nextA outA, nextA halt
  111948. **
  111949. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  111950. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  111951. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  111952. ** following nextX causes a jump to the end of the select processing.
  111953. **
  111954. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  111955. ** within the output subroutine. The regPrev register set holds the previously
  111956. ** output value. A comparison is made against this value and the output
  111957. ** is skipped if the next results would be the same as the previous.
  111958. **
  111959. ** The implementation plan is to implement the two coroutines and seven
  111960. ** subroutines first, then put the control logic at the bottom. Like this:
  111961. **
  111962. ** goto Init
  111963. ** coA: coroutine for left query (A)
  111964. ** coB: coroutine for right query (B)
  111965. ** outA: output one row of A
  111966. ** outB: output one row of B (UNION and UNION ALL only)
  111967. ** EofA: ...
  111968. ** EofB: ...
  111969. ** AltB: ...
  111970. ** AeqB: ...
  111971. ** AgtB: ...
  111972. ** Init: initialize coroutine registers
  111973. ** yield coA
  111974. ** if eof(A) goto EofA
  111975. ** yield coB
  111976. ** if eof(B) goto EofB
  111977. ** Cmpr: Compare A, B
  111978. ** Jump AltB, AeqB, AgtB
  111979. ** End: ...
  111980. **
  111981. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  111982. ** actually called using Gosub and they do not Return. EofA and EofB loop
  111983. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  111984. ** and AgtB jump to either L2 or to one of EofA or EofB.
  111985. */
  111986. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  111987. static int multiSelectOrderBy(
  111988. Parse *pParse, /* Parsing context */
  111989. Select *p, /* The right-most of SELECTs to be coded */
  111990. SelectDest *pDest /* What to do with query results */
  111991. ){
  111992. int i, j; /* Loop counters */
  111993. Select *pPrior; /* Another SELECT immediately to our left */
  111994. Vdbe *v; /* Generate code to this VDBE */
  111995. SelectDest destA; /* Destination for coroutine A */
  111996. SelectDest destB; /* Destination for coroutine B */
  111997. int regAddrA; /* Address register for select-A coroutine */
  111998. int regAddrB; /* Address register for select-B coroutine */
  111999. int addrSelectA; /* Address of the select-A coroutine */
  112000. int addrSelectB; /* Address of the select-B coroutine */
  112001. int regOutA; /* Address register for the output-A subroutine */
  112002. int regOutB; /* Address register for the output-B subroutine */
  112003. int addrOutA; /* Address of the output-A subroutine */
  112004. int addrOutB = 0; /* Address of the output-B subroutine */
  112005. int addrEofA; /* Address of the select-A-exhausted subroutine */
  112006. int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
  112007. int addrEofB; /* Address of the select-B-exhausted subroutine */
  112008. int addrAltB; /* Address of the A<B subroutine */
  112009. int addrAeqB; /* Address of the A==B subroutine */
  112010. int addrAgtB; /* Address of the A>B subroutine */
  112011. int regLimitA; /* Limit register for select-A */
  112012. int regLimitB; /* Limit register for select-A */
  112013. int regPrev; /* A range of registers to hold previous output */
  112014. int savedLimit; /* Saved value of p->iLimit */
  112015. int savedOffset; /* Saved value of p->iOffset */
  112016. int labelCmpr; /* Label for the start of the merge algorithm */
  112017. int labelEnd; /* Label for the end of the overall SELECT stmt */
  112018. int addr1; /* Jump instructions that get retargetted */
  112019. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  112020. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  112021. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  112022. sqlite3 *db; /* Database connection */
  112023. ExprList *pOrderBy; /* The ORDER BY clause */
  112024. int nOrderBy; /* Number of terms in the ORDER BY clause */
  112025. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  112026. #ifndef SQLITE_OMIT_EXPLAIN
  112027. int iSub1; /* EQP id of left-hand query */
  112028. int iSub2; /* EQP id of right-hand query */
  112029. #endif
  112030. assert( p->pOrderBy!=0 );
  112031. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  112032. db = pParse->db;
  112033. v = pParse->pVdbe;
  112034. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  112035. labelEnd = sqlite3VdbeMakeLabel(v);
  112036. labelCmpr = sqlite3VdbeMakeLabel(v);
  112037. /* Patch up the ORDER BY clause
  112038. */
  112039. op = p->op;
  112040. pPrior = p->pPrior;
  112041. assert( pPrior->pOrderBy==0 );
  112042. pOrderBy = p->pOrderBy;
  112043. assert( pOrderBy );
  112044. nOrderBy = pOrderBy->nExpr;
  112045. /* For operators other than UNION ALL we have to make sure that
  112046. ** the ORDER BY clause covers every term of the result set. Add
  112047. ** terms to the ORDER BY clause as necessary.
  112048. */
  112049. if( op!=TK_ALL ){
  112050. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  112051. struct ExprList_item *pItem;
  112052. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  112053. assert( pItem->u.x.iOrderByCol>0 );
  112054. if( pItem->u.x.iOrderByCol==i ) break;
  112055. }
  112056. if( j==nOrderBy ){
  112057. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  112058. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  112059. pNew->flags |= EP_IntValue;
  112060. pNew->u.iValue = i;
  112061. p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  112062. if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
  112063. }
  112064. }
  112065. }
  112066. /* Compute the comparison permutation and keyinfo that is used with
  112067. ** the permutation used to determine if the next
  112068. ** row of results comes from selectA or selectB. Also add explicit
  112069. ** collations to the ORDER BY clause terms so that when the subqueries
  112070. ** to the right and the left are evaluated, they use the correct
  112071. ** collation.
  112072. */
  112073. aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
  112074. if( aPermute ){
  112075. struct ExprList_item *pItem;
  112076. aPermute[0] = nOrderBy;
  112077. for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
  112078. assert( pItem->u.x.iOrderByCol>0 );
  112079. assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
  112080. aPermute[i] = pItem->u.x.iOrderByCol - 1;
  112081. }
  112082. pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
  112083. }else{
  112084. pKeyMerge = 0;
  112085. }
  112086. /* Reattach the ORDER BY clause to the query.
  112087. */
  112088. p->pOrderBy = pOrderBy;
  112089. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  112090. /* Allocate a range of temporary registers and the KeyInfo needed
  112091. ** for the logic that removes duplicate result rows when the
  112092. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  112093. */
  112094. if( op==TK_ALL ){
  112095. regPrev = 0;
  112096. }else{
  112097. int nExpr = p->pEList->nExpr;
  112098. assert( nOrderBy>=nExpr || db->mallocFailed );
  112099. regPrev = pParse->nMem+1;
  112100. pParse->nMem += nExpr+1;
  112101. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  112102. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
  112103. if( pKeyDup ){
  112104. assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
  112105. for(i=0; i<nExpr; i++){
  112106. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  112107. pKeyDup->aSortOrder[i] = 0;
  112108. }
  112109. }
  112110. }
  112111. /* Separate the left and the right query from one another
  112112. */
  112113. p->pPrior = 0;
  112114. pPrior->pNext = 0;
  112115. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  112116. if( pPrior->pPrior==0 ){
  112117. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  112118. }
  112119. /* Compute the limit registers */
  112120. computeLimitRegisters(pParse, p, labelEnd);
  112121. if( p->iLimit && op==TK_ALL ){
  112122. regLimitA = ++pParse->nMem;
  112123. regLimitB = ++pParse->nMem;
  112124. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  112125. regLimitA);
  112126. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  112127. }else{
  112128. regLimitA = regLimitB = 0;
  112129. }
  112130. sqlite3ExprDelete(db, p->pLimit);
  112131. p->pLimit = 0;
  112132. sqlite3ExprDelete(db, p->pOffset);
  112133. p->pOffset = 0;
  112134. regAddrA = ++pParse->nMem;
  112135. regAddrB = ++pParse->nMem;
  112136. regOutA = ++pParse->nMem;
  112137. regOutB = ++pParse->nMem;
  112138. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  112139. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  112140. /* Generate a coroutine to evaluate the SELECT statement to the
  112141. ** left of the compound operator - the "A" select.
  112142. */
  112143. addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
  112144. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
  112145. VdbeComment((v, "left SELECT"));
  112146. pPrior->iLimit = regLimitA;
  112147. explainSetInteger(iSub1, pParse->iNextSelectId);
  112148. sqlite3Select(pParse, pPrior, &destA);
  112149. sqlite3VdbeEndCoroutine(v, regAddrA);
  112150. sqlite3VdbeJumpHere(v, addr1);
  112151. /* Generate a coroutine to evaluate the SELECT statement on
  112152. ** the right - the "B" select
  112153. */
  112154. addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
  112155. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
  112156. VdbeComment((v, "right SELECT"));
  112157. savedLimit = p->iLimit;
  112158. savedOffset = p->iOffset;
  112159. p->iLimit = regLimitB;
  112160. p->iOffset = 0;
  112161. explainSetInteger(iSub2, pParse->iNextSelectId);
  112162. sqlite3Select(pParse, p, &destB);
  112163. p->iLimit = savedLimit;
  112164. p->iOffset = savedOffset;
  112165. sqlite3VdbeEndCoroutine(v, regAddrB);
  112166. /* Generate a subroutine that outputs the current row of the A
  112167. ** select as the next output row of the compound select.
  112168. */
  112169. VdbeNoopComment((v, "Output routine for A"));
  112170. addrOutA = generateOutputSubroutine(pParse,
  112171. p, &destA, pDest, regOutA,
  112172. regPrev, pKeyDup, labelEnd);
  112173. /* Generate a subroutine that outputs the current row of the B
  112174. ** select as the next output row of the compound select.
  112175. */
  112176. if( op==TK_ALL || op==TK_UNION ){
  112177. VdbeNoopComment((v, "Output routine for B"));
  112178. addrOutB = generateOutputSubroutine(pParse,
  112179. p, &destB, pDest, regOutB,
  112180. regPrev, pKeyDup, labelEnd);
  112181. }
  112182. sqlite3KeyInfoUnref(pKeyDup);
  112183. /* Generate a subroutine to run when the results from select A
  112184. ** are exhausted and only data in select B remains.
  112185. */
  112186. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  112187. addrEofA_noB = addrEofA = labelEnd;
  112188. }else{
  112189. VdbeNoopComment((v, "eof-A subroutine"));
  112190. addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  112191. addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
  112192. VdbeCoverage(v);
  112193. sqlite3VdbeGoto(v, addrEofA);
  112194. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  112195. }
  112196. /* Generate a subroutine to run when the results from select B
  112197. ** are exhausted and only data in select A remains.
  112198. */
  112199. if( op==TK_INTERSECT ){
  112200. addrEofB = addrEofA;
  112201. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  112202. }else{
  112203. VdbeNoopComment((v, "eof-B subroutine"));
  112204. addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  112205. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
  112206. sqlite3VdbeGoto(v, addrEofB);
  112207. }
  112208. /* Generate code to handle the case of A<B
  112209. */
  112210. VdbeNoopComment((v, "A-lt-B subroutine"));
  112211. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  112212. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  112213. sqlite3VdbeGoto(v, labelCmpr);
  112214. /* Generate code to handle the case of A==B
  112215. */
  112216. if( op==TK_ALL ){
  112217. addrAeqB = addrAltB;
  112218. }else if( op==TK_INTERSECT ){
  112219. addrAeqB = addrAltB;
  112220. addrAltB++;
  112221. }else{
  112222. VdbeNoopComment((v, "A-eq-B subroutine"));
  112223. addrAeqB =
  112224. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  112225. sqlite3VdbeGoto(v, labelCmpr);
  112226. }
  112227. /* Generate code to handle the case of A>B
  112228. */
  112229. VdbeNoopComment((v, "A-gt-B subroutine"));
  112230. addrAgtB = sqlite3VdbeCurrentAddr(v);
  112231. if( op==TK_ALL || op==TK_UNION ){
  112232. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  112233. }
  112234. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  112235. sqlite3VdbeGoto(v, labelCmpr);
  112236. /* This code runs once to initialize everything.
  112237. */
  112238. sqlite3VdbeJumpHere(v, addr1);
  112239. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
  112240. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  112241. /* Implement the main merge loop
  112242. */
  112243. sqlite3VdbeResolveLabel(v, labelCmpr);
  112244. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  112245. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  112246. (char*)pKeyMerge, P4_KEYINFO);
  112247. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  112248. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
  112249. /* Jump to the this point in order to terminate the query.
  112250. */
  112251. sqlite3VdbeResolveLabel(v, labelEnd);
  112252. /* Set the number of output columns
  112253. */
  112254. if( pDest->eDest==SRT_Output ){
  112255. Select *pFirst = pPrior;
  112256. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  112257. generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
  112258. }
  112259. /* Reassembly the compound query so that it will be freed correctly
  112260. ** by the calling function */
  112261. if( p->pPrior ){
  112262. sqlite3SelectDelete(db, p->pPrior);
  112263. }
  112264. p->pPrior = pPrior;
  112265. pPrior->pNext = p;
  112266. /*** TBD: Insert subroutine calls to close cursors on incomplete
  112267. **** subqueries ****/
  112268. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  112269. return pParse->nErr!=0;
  112270. }
  112271. #endif
  112272. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  112273. /* An instance of the SubstContext object describes an substitution edit
  112274. ** to be performed on a parse tree.
  112275. **
  112276. ** All references to columns in table iTable are to be replaced by corresponding
  112277. ** expressions in pEList.
  112278. */
  112279. typedef struct SubstContext {
  112280. Parse *pParse; /* The parsing context */
  112281. int iTable; /* Replace references to this table */
  112282. int iNewTable; /* New table number */
  112283. int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */
  112284. ExprList *pEList; /* Replacement expressions */
  112285. } SubstContext;
  112286. /* Forward Declarations */
  112287. static void substExprList(SubstContext*, ExprList*);
  112288. static void substSelect(SubstContext*, Select*, int);
  112289. /*
  112290. ** Scan through the expression pExpr. Replace every reference to
  112291. ** a column in table number iTable with a copy of the iColumn-th
  112292. ** entry in pEList. (But leave references to the ROWID column
  112293. ** unchanged.)
  112294. **
  112295. ** This routine is part of the flattening procedure. A subquery
  112296. ** whose result set is defined by pEList appears as entry in the
  112297. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  112298. ** FORM clause entry is iTable. This routine makes the necessary
  112299. ** changes to pExpr so that it refers directly to the source table
  112300. ** of the subquery rather the result set of the subquery.
  112301. */
  112302. static Expr *substExpr(
  112303. SubstContext *pSubst, /* Description of the substitution */
  112304. Expr *pExpr /* Expr in which substitution occurs */
  112305. ){
  112306. if( pExpr==0 ) return 0;
  112307. if( ExprHasProperty(pExpr, EP_FromJoin) && pExpr->iRightJoinTable==pSubst->iTable ){
  112308. pExpr->iRightJoinTable = pSubst->iNewTable;
  112309. }
  112310. if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){
  112311. if( pExpr->iColumn<0 ){
  112312. pExpr->op = TK_NULL;
  112313. }else{
  112314. Expr *pNew;
  112315. Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
  112316. Expr ifNullRow;
  112317. assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
  112318. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  112319. if( sqlite3ExprIsVector(pCopy) ){
  112320. sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
  112321. }else{
  112322. sqlite3 *db = pSubst->pParse->db;
  112323. if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
  112324. memset(&ifNullRow, 0, sizeof(ifNullRow));
  112325. ifNullRow.op = TK_IF_NULL_ROW;
  112326. ifNullRow.pLeft = pCopy;
  112327. ifNullRow.iTable = pSubst->iNewTable;
  112328. pCopy = &ifNullRow;
  112329. }
  112330. pNew = sqlite3ExprDup(db, pCopy, 0);
  112331. if( pNew && (pExpr->flags & EP_FromJoin) ){
  112332. pNew->iRightJoinTable = pExpr->iRightJoinTable;
  112333. pNew->flags |= EP_FromJoin;
  112334. }
  112335. sqlite3ExprDelete(db, pExpr);
  112336. pExpr = pNew;
  112337. }
  112338. }
  112339. }else{
  112340. if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
  112341. pExpr->iTable = pSubst->iNewTable;
  112342. }
  112343. pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
  112344. pExpr->pRight = substExpr(pSubst, pExpr->pRight);
  112345. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  112346. substSelect(pSubst, pExpr->x.pSelect, 1);
  112347. }else{
  112348. substExprList(pSubst, pExpr->x.pList);
  112349. }
  112350. }
  112351. return pExpr;
  112352. }
  112353. static void substExprList(
  112354. SubstContext *pSubst, /* Description of the substitution */
  112355. ExprList *pList /* List to scan and in which to make substitutes */
  112356. ){
  112357. int i;
  112358. if( pList==0 ) return;
  112359. for(i=0; i<pList->nExpr; i++){
  112360. pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
  112361. }
  112362. }
  112363. static void substSelect(
  112364. SubstContext *pSubst, /* Description of the substitution */
  112365. Select *p, /* SELECT statement in which to make substitutions */
  112366. int doPrior /* Do substitutes on p->pPrior too */
  112367. ){
  112368. SrcList *pSrc;
  112369. struct SrcList_item *pItem;
  112370. int i;
  112371. if( !p ) return;
  112372. do{
  112373. substExprList(pSubst, p->pEList);
  112374. substExprList(pSubst, p->pGroupBy);
  112375. substExprList(pSubst, p->pOrderBy);
  112376. p->pHaving = substExpr(pSubst, p->pHaving);
  112377. p->pWhere = substExpr(pSubst, p->pWhere);
  112378. pSrc = p->pSrc;
  112379. assert( pSrc!=0 );
  112380. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  112381. substSelect(pSubst, pItem->pSelect, 1);
  112382. if( pItem->fg.isTabFunc ){
  112383. substExprList(pSubst, pItem->u1.pFuncArg);
  112384. }
  112385. }
  112386. }while( doPrior && (p = p->pPrior)!=0 );
  112387. }
  112388. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  112389. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  112390. /*
  112391. ** This routine attempts to flatten subqueries as a performance optimization.
  112392. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  112393. **
  112394. ** To understand the concept of flattening, consider the following
  112395. ** query:
  112396. **
  112397. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  112398. **
  112399. ** The default way of implementing this query is to execute the
  112400. ** subquery first and store the results in a temporary table, then
  112401. ** run the outer query on that temporary table. This requires two
  112402. ** passes over the data. Furthermore, because the temporary table
  112403. ** has no indices, the WHERE clause on the outer query cannot be
  112404. ** optimized.
  112405. **
  112406. ** This routine attempts to rewrite queries such as the above into
  112407. ** a single flat select, like this:
  112408. **
  112409. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  112410. **
  112411. ** The code generated for this simplification gives the same result
  112412. ** but only has to scan the data once. And because indices might
  112413. ** exist on the table t1, a complete scan of the data might be
  112414. ** avoided.
  112415. **
  112416. ** Flattening is only attempted if all of the following are true:
  112417. **
  112418. ** (1) The subquery and the outer query do not both use aggregates.
  112419. **
  112420. ** (2) The subquery is not an aggregate or (2a) the outer query is not a join
  112421. ** and (2b) the outer query does not use subqueries other than the one
  112422. ** FROM-clause subquery that is a candidate for flattening. (2b is
  112423. ** due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
  112424. **
  112425. ** (3) The subquery is not the right operand of a LEFT JOIN
  112426. ** or the subquery is not itself a join and the outer query is not
  112427. ** an aggregate.
  112428. **
  112429. ** (4) The subquery is not DISTINCT.
  112430. **
  112431. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  112432. ** sub-queries that were excluded from this optimization. Restriction
  112433. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  112434. **
  112435. ** (6) The subquery does not use aggregates or the outer query is not
  112436. ** DISTINCT.
  112437. **
  112438. ** (7) The subquery has a FROM clause. TODO: For subqueries without
  112439. ** A FROM clause, consider adding a FROM clause with the special
  112440. ** table sqlite_once that consists of a single row containing a
  112441. ** single NULL.
  112442. **
  112443. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  112444. **
  112445. ** (9) The subquery does not use LIMIT or the outer query does not use
  112446. ** aggregates.
  112447. **
  112448. ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
  112449. ** accidently carried the comment forward until 2014-09-15. Original
  112450. ** text: "The subquery does not use aggregates or the outer query
  112451. ** does not use LIMIT."
  112452. **
  112453. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  112454. **
  112455. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  112456. ** a separate restriction deriving from ticket #350.
  112457. **
  112458. ** (13) The subquery and outer query do not both use LIMIT.
  112459. **
  112460. ** (14) The subquery does not use OFFSET.
  112461. **
  112462. ** (15) The outer query is not part of a compound select or the
  112463. ** subquery does not have a LIMIT clause.
  112464. ** (See ticket #2339 and ticket [02a8e81d44]).
  112465. **
  112466. ** (16) The outer query is not an aggregate or the subquery does
  112467. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  112468. ** until we introduced the group_concat() function.
  112469. **
  112470. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  112471. ** compound clause made up entirely of non-aggregate queries, and
  112472. ** the parent query:
  112473. **
  112474. ** * is not itself part of a compound select,
  112475. ** * is not an aggregate or DISTINCT query, and
  112476. ** * is not a join
  112477. **
  112478. ** The parent and sub-query may contain WHERE clauses. Subject to
  112479. ** rules (11), (13) and (14), they may also contain ORDER BY,
  112480. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  112481. ** operator other than UNION ALL because all the other compound
  112482. ** operators have an implied DISTINCT which is disallowed by
  112483. ** restriction (4).
  112484. **
  112485. ** Also, each component of the sub-query must return the same number
  112486. ** of result columns. This is actually a requirement for any compound
  112487. ** SELECT statement, but all the code here does is make sure that no
  112488. ** such (illegal) sub-query is flattened. The caller will detect the
  112489. ** syntax error and return a detailed message.
  112490. **
  112491. ** (18) If the sub-query is a compound select, then all terms of the
  112492. ** ORDER by clause of the parent must be simple references to
  112493. ** columns of the sub-query.
  112494. **
  112495. ** (19) The subquery does not use LIMIT or the outer query does not
  112496. ** have a WHERE clause.
  112497. **
  112498. ** (20) If the sub-query is a compound select, then it must not use
  112499. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  112500. ** somewhat by saying that the terms of the ORDER BY clause must
  112501. ** appear as unmodified result columns in the outer query. But we
  112502. ** have other optimizations in mind to deal with that case.
  112503. **
  112504. ** (21) The subquery does not use LIMIT or the outer query is not
  112505. ** DISTINCT. (See ticket [752e1646fc]).
  112506. **
  112507. ** (22) The subquery is not a recursive CTE.
  112508. **
  112509. ** (23) The parent is not a recursive CTE, or the sub-query is not a
  112510. ** compound query. This restriction is because transforming the
  112511. ** parent to a compound query confuses the code that handles
  112512. ** recursive queries in multiSelect().
  112513. **
  112514. ** (24) The subquery is not an aggregate that uses the built-in min() or
  112515. ** or max() functions. (Without this restriction, a query like:
  112516. ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
  112517. ** return the value X for which Y was maximal.)
  112518. **
  112519. **
  112520. ** In this routine, the "p" parameter is a pointer to the outer query.
  112521. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  112522. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  112523. **
  112524. ** If flattening is not attempted, this routine is a no-op and returns 0.
  112525. ** If flattening is attempted this routine returns 1.
  112526. **
  112527. ** All of the expression analysis must occur on both the outer query and
  112528. ** the subquery before this routine runs.
  112529. */
  112530. static int flattenSubquery(
  112531. Parse *pParse, /* Parsing context */
  112532. Select *p, /* The parent or outer SELECT statement */
  112533. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  112534. int isAgg, /* True if outer SELECT uses aggregate functions */
  112535. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  112536. ){
  112537. const char *zSavedAuthContext = pParse->zAuthContext;
  112538. Select *pParent; /* Current UNION ALL term of the other query */
  112539. Select *pSub; /* The inner query or "subquery" */
  112540. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  112541. SrcList *pSrc; /* The FROM clause of the outer query */
  112542. SrcList *pSubSrc; /* The FROM clause of the subquery */
  112543. ExprList *pList; /* The result set of the outer query */
  112544. int iParent; /* VDBE cursor number of the pSub result set temp table */
  112545. int iNewParent = -1;/* Replacement table for iParent */
  112546. int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
  112547. int i; /* Loop counter */
  112548. Expr *pWhere; /* The WHERE clause */
  112549. struct SrcList_item *pSubitem; /* The subquery */
  112550. sqlite3 *db = pParse->db;
  112551. /* Check to see if flattening is permitted. Return 0 if not.
  112552. */
  112553. assert( p!=0 );
  112554. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  112555. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  112556. pSrc = p->pSrc;
  112557. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  112558. pSubitem = &pSrc->a[iFrom];
  112559. iParent = pSubitem->iCursor;
  112560. pSub = pSubitem->pSelect;
  112561. assert( pSub!=0 );
  112562. if( subqueryIsAgg ){
  112563. if( isAgg ) return 0; /* Restriction (1) */
  112564. if( pSrc->nSrc>1 ) return 0; /* Restriction (2a) */
  112565. if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
  112566. || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
  112567. || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
  112568. ){
  112569. return 0; /* Restriction (2b) */
  112570. }
  112571. }
  112572. pSubSrc = pSub->pSrc;
  112573. assert( pSubSrc );
  112574. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  112575. ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
  112576. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  112577. ** became arbitrary expressions, we were forced to add restrictions (13)
  112578. ** and (14). */
  112579. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  112580. if( pSub->pOffset ) return 0; /* Restriction (14) */
  112581. if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
  112582. return 0; /* Restriction (15) */
  112583. }
  112584. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  112585. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
  112586. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  112587. return 0; /* Restrictions (8)(9) */
  112588. }
  112589. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  112590. return 0; /* Restriction (6) */
  112591. }
  112592. if( p->pOrderBy && pSub->pOrderBy ){
  112593. return 0; /* Restriction (11) */
  112594. }
  112595. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  112596. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  112597. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  112598. return 0; /* Restriction (21) */
  112599. }
  112600. testcase( pSub->selFlags & SF_Recursive );
  112601. testcase( pSub->selFlags & SF_MinMaxAgg );
  112602. if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
  112603. return 0; /* Restrictions (22) and (24) */
  112604. }
  112605. if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
  112606. return 0; /* Restriction (23) */
  112607. }
  112608. /*
  112609. ** If the subquery is the right operand of a LEFT JOIN, then the
  112610. ** subquery may not be a join itself. Example of why this is not allowed:
  112611. **
  112612. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  112613. **
  112614. ** If we flatten the above, we would get
  112615. **
  112616. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  112617. **
  112618. ** which is not at all the same thing.
  112619. **
  112620. ** If the subquery is the right operand of a LEFT JOIN, then the outer
  112621. ** query cannot be an aggregate. This is an artifact of the way aggregates
  112622. ** are processed - there is not mechanism to determine if the LEFT JOIN
  112623. ** table should be all-NULL.
  112624. **
  112625. ** See also tickets #306, #350, and #3300.
  112626. */
  112627. if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
  112628. isLeftJoin = 1;
  112629. if( pSubSrc->nSrc>1 || isAgg ){
  112630. return 0; /* Restriction (3) */
  112631. }
  112632. }
  112633. #ifdef SQLITE_EXTRA_IFNULLROW
  112634. else if( iFrom>0 && !isAgg ){
  112635. /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
  112636. ** every reference to any result column from subquery in a join, even though
  112637. ** they are not necessary. This will stress-test the OP_IfNullRow opcode. */
  112638. isLeftJoin = -1;
  112639. }
  112640. #endif
  112641. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  112642. ** use only the UNION ALL operator. And none of the simple select queries
  112643. ** that make up the compound SELECT are allowed to be aggregate or distinct
  112644. ** queries.
  112645. */
  112646. if( pSub->pPrior ){
  112647. if( pSub->pOrderBy ){
  112648. return 0; /* Restriction 20 */
  112649. }
  112650. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  112651. return 0;
  112652. }
  112653. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  112654. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  112655. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  112656. assert( pSub->pSrc!=0 );
  112657. assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
  112658. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  112659. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  112660. || pSub1->pSrc->nSrc<1
  112661. ){
  112662. return 0;
  112663. }
  112664. testcase( pSub1->pSrc->nSrc>1 );
  112665. }
  112666. /* Restriction 18. */
  112667. if( p->pOrderBy ){
  112668. int ii;
  112669. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  112670. if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
  112671. }
  112672. }
  112673. }
  112674. /***** If we reach this point, flattening is permitted. *****/
  112675. SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
  112676. pSub->zSelName, pSub, iFrom));
  112677. /* Authorize the subquery */
  112678. pParse->zAuthContext = pSubitem->zName;
  112679. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  112680. testcase( i==SQLITE_DENY );
  112681. pParse->zAuthContext = zSavedAuthContext;
  112682. /* If the sub-query is a compound SELECT statement, then (by restrictions
  112683. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  112684. ** be of the form:
  112685. **
  112686. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  112687. **
  112688. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  112689. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  112690. ** OFFSET clauses and joins them to the left-hand-side of the original
  112691. ** using UNION ALL operators. In this case N is the number of simple
  112692. ** select statements in the compound sub-query.
  112693. **
  112694. ** Example:
  112695. **
  112696. ** SELECT a+1 FROM (
  112697. ** SELECT x FROM tab
  112698. ** UNION ALL
  112699. ** SELECT y FROM tab
  112700. ** UNION ALL
  112701. ** SELECT abs(z*2) FROM tab2
  112702. ** ) WHERE a!=5 ORDER BY 1
  112703. **
  112704. ** Transformed into:
  112705. **
  112706. ** SELECT x+1 FROM tab WHERE x+1!=5
  112707. ** UNION ALL
  112708. ** SELECT y+1 FROM tab WHERE y+1!=5
  112709. ** UNION ALL
  112710. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  112711. ** ORDER BY 1
  112712. **
  112713. ** We call this the "compound-subquery flattening".
  112714. */
  112715. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  112716. Select *pNew;
  112717. ExprList *pOrderBy = p->pOrderBy;
  112718. Expr *pLimit = p->pLimit;
  112719. Expr *pOffset = p->pOffset;
  112720. Select *pPrior = p->pPrior;
  112721. p->pOrderBy = 0;
  112722. p->pSrc = 0;
  112723. p->pPrior = 0;
  112724. p->pLimit = 0;
  112725. p->pOffset = 0;
  112726. pNew = sqlite3SelectDup(db, p, 0);
  112727. sqlite3SelectSetName(pNew, pSub->zSelName);
  112728. p->pOffset = pOffset;
  112729. p->pLimit = pLimit;
  112730. p->pOrderBy = pOrderBy;
  112731. p->pSrc = pSrc;
  112732. p->op = TK_ALL;
  112733. if( pNew==0 ){
  112734. p->pPrior = pPrior;
  112735. }else{
  112736. pNew->pPrior = pPrior;
  112737. if( pPrior ) pPrior->pNext = pNew;
  112738. pNew->pNext = p;
  112739. p->pPrior = pNew;
  112740. SELECTTRACE(2,pParse,p,
  112741. ("compound-subquery flattener creates %s.%p as peer\n",
  112742. pNew->zSelName, pNew));
  112743. }
  112744. if( db->mallocFailed ) return 1;
  112745. }
  112746. /* Begin flattening the iFrom-th entry of the FROM clause
  112747. ** in the outer query.
  112748. */
  112749. pSub = pSub1 = pSubitem->pSelect;
  112750. /* Delete the transient table structure associated with the
  112751. ** subquery
  112752. */
  112753. sqlite3DbFree(db, pSubitem->zDatabase);
  112754. sqlite3DbFree(db, pSubitem->zName);
  112755. sqlite3DbFree(db, pSubitem->zAlias);
  112756. pSubitem->zDatabase = 0;
  112757. pSubitem->zName = 0;
  112758. pSubitem->zAlias = 0;
  112759. pSubitem->pSelect = 0;
  112760. /* Defer deleting the Table object associated with the
  112761. ** subquery until code generation is
  112762. ** complete, since there may still exist Expr.pTab entries that
  112763. ** refer to the subquery even after flattening. Ticket #3346.
  112764. **
  112765. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  112766. */
  112767. if( ALWAYS(pSubitem->pTab!=0) ){
  112768. Table *pTabToDel = pSubitem->pTab;
  112769. if( pTabToDel->nTabRef==1 ){
  112770. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  112771. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  112772. pToplevel->pZombieTab = pTabToDel;
  112773. }else{
  112774. pTabToDel->nTabRef--;
  112775. }
  112776. pSubitem->pTab = 0;
  112777. }
  112778. /* The following loop runs once for each term in a compound-subquery
  112779. ** flattening (as described above). If we are doing a different kind
  112780. ** of flattening - a flattening other than a compound-subquery flattening -
  112781. ** then this loop only runs once.
  112782. **
  112783. ** This loop moves all of the FROM elements of the subquery into the
  112784. ** the FROM clause of the outer query. Before doing this, remember
  112785. ** the cursor number for the original outer query FROM element in
  112786. ** iParent. The iParent cursor will never be used. Subsequent code
  112787. ** will scan expressions looking for iParent references and replace
  112788. ** those references with expressions that resolve to the subquery FROM
  112789. ** elements we are now copying in.
  112790. */
  112791. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  112792. int nSubSrc;
  112793. u8 jointype = 0;
  112794. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  112795. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  112796. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  112797. if( pSrc ){
  112798. assert( pParent==p ); /* First time through the loop */
  112799. jointype = pSubitem->fg.jointype;
  112800. }else{
  112801. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  112802. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  112803. if( pSrc==0 ){
  112804. assert( db->mallocFailed );
  112805. break;
  112806. }
  112807. }
  112808. /* The subquery uses a single slot of the FROM clause of the outer
  112809. ** query. If the subquery has more than one element in its FROM clause,
  112810. ** then expand the outer query to make space for it to hold all elements
  112811. ** of the subquery.
  112812. **
  112813. ** Example:
  112814. **
  112815. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  112816. **
  112817. ** The outer query has 3 slots in its FROM clause. One slot of the
  112818. ** outer query (the middle slot) is used by the subquery. The next
  112819. ** block of code will expand the outer query FROM clause to 4 slots.
  112820. ** The middle slot is expanded to two slots in order to make space
  112821. ** for the two elements in the FROM clause of the subquery.
  112822. */
  112823. if( nSubSrc>1 ){
  112824. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  112825. if( db->mallocFailed ){
  112826. break;
  112827. }
  112828. }
  112829. /* Transfer the FROM clause terms from the subquery into the
  112830. ** outer query.
  112831. */
  112832. for(i=0; i<nSubSrc; i++){
  112833. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  112834. assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
  112835. pSrc->a[i+iFrom] = pSubSrc->a[i];
  112836. iNewParent = pSubSrc->a[i].iCursor;
  112837. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  112838. }
  112839. pSrc->a[iFrom].fg.jointype = jointype;
  112840. /* Now begin substituting subquery result set expressions for
  112841. ** references to the iParent in the outer query.
  112842. **
  112843. ** Example:
  112844. **
  112845. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  112846. ** \ \_____________ subquery __________/ /
  112847. ** \_____________________ outer query ______________________________/
  112848. **
  112849. ** We look at every expression in the outer query and every place we see
  112850. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  112851. */
  112852. pList = pParent->pEList;
  112853. for(i=0; i<pList->nExpr; i++){
  112854. if( pList->a[i].zName==0 ){
  112855. char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
  112856. sqlite3Dequote(zName);
  112857. pList->a[i].zName = zName;
  112858. }
  112859. }
  112860. if( pSub->pOrderBy ){
  112861. /* At this point, any non-zero iOrderByCol values indicate that the
  112862. ** ORDER BY column expression is identical to the iOrderByCol'th
  112863. ** expression returned by SELECT statement pSub. Since these values
  112864. ** do not necessarily correspond to columns in SELECT statement pParent,
  112865. ** zero them before transfering the ORDER BY clause.
  112866. **
  112867. ** Not doing this may cause an error if a subsequent call to this
  112868. ** function attempts to flatten a compound sub-query into pParent
  112869. ** (the only way this can happen is if the compound sub-query is
  112870. ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
  112871. ExprList *pOrderBy = pSub->pOrderBy;
  112872. for(i=0; i<pOrderBy->nExpr; i++){
  112873. pOrderBy->a[i].u.x.iOrderByCol = 0;
  112874. }
  112875. assert( pParent->pOrderBy==0 );
  112876. assert( pSub->pPrior==0 );
  112877. pParent->pOrderBy = pOrderBy;
  112878. pSub->pOrderBy = 0;
  112879. }
  112880. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  112881. if( isLeftJoin>0 ){
  112882. setJoinExpr(pWhere, iNewParent);
  112883. }
  112884. if( subqueryIsAgg ){
  112885. assert( pParent->pHaving==0 );
  112886. pParent->pHaving = pParent->pWhere;
  112887. pParent->pWhere = pWhere;
  112888. pParent->pHaving = sqlite3ExprAnd(db,
  112889. sqlite3ExprDup(db, pSub->pHaving, 0), pParent->pHaving
  112890. );
  112891. assert( pParent->pGroupBy==0 );
  112892. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
  112893. }else{
  112894. pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere);
  112895. }
  112896. if( db->mallocFailed==0 ){
  112897. SubstContext x;
  112898. x.pParse = pParse;
  112899. x.iTable = iParent;
  112900. x.iNewTable = iNewParent;
  112901. x.isLeftJoin = isLeftJoin;
  112902. x.pEList = pSub->pEList;
  112903. substSelect(&x, pParent, 0);
  112904. }
  112905. /* The flattened query is distinct if either the inner or the
  112906. ** outer query is distinct.
  112907. */
  112908. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  112909. /*
  112910. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  112911. **
  112912. ** One is tempted to try to add a and b to combine the limits. But this
  112913. ** does not work if either limit is negative.
  112914. */
  112915. if( pSub->pLimit ){
  112916. pParent->pLimit = pSub->pLimit;
  112917. pSub->pLimit = 0;
  112918. }
  112919. }
  112920. /* Finially, delete what is left of the subquery and return
  112921. ** success.
  112922. */
  112923. sqlite3SelectDelete(db, pSub1);
  112924. #if SELECTTRACE_ENABLED
  112925. if( sqlite3SelectTrace & 0x100 ){
  112926. SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
  112927. sqlite3TreeViewSelect(0, p, 0);
  112928. }
  112929. #endif
  112930. return 1;
  112931. }
  112932. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  112933. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  112934. /*
  112935. ** Make copies of relevant WHERE clause terms of the outer query into
  112936. ** the WHERE clause of subquery. Example:
  112937. **
  112938. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
  112939. **
  112940. ** Transformed into:
  112941. **
  112942. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
  112943. ** WHERE x=5 AND y=10;
  112944. **
  112945. ** The hope is that the terms added to the inner query will make it more
  112946. ** efficient.
  112947. **
  112948. ** Do not attempt this optimization if:
  112949. **
  112950. ** (1) The inner query is an aggregate. (In that case, we'd really want
  112951. ** to copy the outer WHERE-clause terms onto the HAVING clause of the
  112952. ** inner query. But they probably won't help there so do not bother.)
  112953. **
  112954. ** (2) The inner query is the recursive part of a common table expression.
  112955. **
  112956. ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
  112957. ** close would change the meaning of the LIMIT).
  112958. **
  112959. ** (4) The inner query is the right operand of a LEFT JOIN. (The caller
  112960. ** enforces this restriction since this routine does not have enough
  112961. ** information to know.)
  112962. **
  112963. ** (5) The WHERE clause expression originates in the ON or USING clause
  112964. ** of a LEFT JOIN.
  112965. **
  112966. ** Return 0 if no changes are made and non-zero if one or more WHERE clause
  112967. ** terms are duplicated into the subquery.
  112968. */
  112969. static int pushDownWhereTerms(
  112970. Parse *pParse, /* Parse context (for malloc() and error reporting) */
  112971. Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
  112972. Expr *pWhere, /* The WHERE clause of the outer query */
  112973. int iCursor /* Cursor number of the subquery */
  112974. ){
  112975. Expr *pNew;
  112976. int nChng = 0;
  112977. Select *pX; /* For looping over compound SELECTs in pSubq */
  112978. if( pWhere==0 ) return 0;
  112979. for(pX=pSubq; pX; pX=pX->pPrior){
  112980. if( (pX->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
  112981. testcase( pX->selFlags & SF_Aggregate );
  112982. testcase( pX->selFlags & SF_Recursive );
  112983. testcase( pX!=pSubq );
  112984. return 0; /* restrictions (1) and (2) */
  112985. }
  112986. }
  112987. if( pSubq->pLimit!=0 ){
  112988. return 0; /* restriction (3) */
  112989. }
  112990. while( pWhere->op==TK_AND ){
  112991. nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, iCursor);
  112992. pWhere = pWhere->pLeft;
  112993. }
  112994. if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
  112995. if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
  112996. nChng++;
  112997. while( pSubq ){
  112998. SubstContext x;
  112999. pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
  113000. x.pParse = pParse;
  113001. x.iTable = iCursor;
  113002. x.iNewTable = iCursor;
  113003. x.isLeftJoin = 0;
  113004. x.pEList = pSubq->pEList;
  113005. pNew = substExpr(&x, pNew);
  113006. pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew);
  113007. pSubq = pSubq->pPrior;
  113008. }
  113009. }
  113010. return nChng;
  113011. }
  113012. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  113013. /*
  113014. ** Based on the contents of the AggInfo structure indicated by the first
  113015. ** argument, this function checks if the following are true:
  113016. **
  113017. ** * the query contains just a single aggregate function,
  113018. ** * the aggregate function is either min() or max(), and
  113019. ** * the argument to the aggregate function is a column value.
  113020. **
  113021. ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
  113022. ** is returned as appropriate. Also, *ppMinMax is set to point to the
  113023. ** list of arguments passed to the aggregate before returning.
  113024. **
  113025. ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
  113026. ** WHERE_ORDERBY_NORMAL is returned.
  113027. */
  113028. static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
  113029. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  113030. *ppMinMax = 0;
  113031. if( pAggInfo->nFunc==1 ){
  113032. Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
  113033. ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
  113034. assert( pExpr->op==TK_AGG_FUNCTION );
  113035. if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
  113036. const char *zFunc = pExpr->u.zToken;
  113037. if( sqlite3StrICmp(zFunc, "min")==0 ){
  113038. eRet = WHERE_ORDERBY_MIN;
  113039. *ppMinMax = pEList;
  113040. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  113041. eRet = WHERE_ORDERBY_MAX;
  113042. *ppMinMax = pEList;
  113043. }
  113044. }
  113045. }
  113046. assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
  113047. return eRet;
  113048. }
  113049. /*
  113050. ** The select statement passed as the first argument is an aggregate query.
  113051. ** The second argument is the associated aggregate-info object. This
  113052. ** function tests if the SELECT is of the form:
  113053. **
  113054. ** SELECT count(*) FROM <tbl>
  113055. **
  113056. ** where table is a database table, not a sub-select or view. If the query
  113057. ** does match this pattern, then a pointer to the Table object representing
  113058. ** <tbl> is returned. Otherwise, 0 is returned.
  113059. */
  113060. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  113061. Table *pTab;
  113062. Expr *pExpr;
  113063. assert( !p->pGroupBy );
  113064. if( p->pWhere || p->pEList->nExpr!=1
  113065. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  113066. ){
  113067. return 0;
  113068. }
  113069. pTab = p->pSrc->a[0].pTab;
  113070. pExpr = p->pEList->a[0].pExpr;
  113071. assert( pTab && !pTab->pSelect && pExpr );
  113072. if( IsVirtual(pTab) ) return 0;
  113073. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  113074. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  113075. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  113076. if( pExpr->flags&EP_Distinct ) return 0;
  113077. return pTab;
  113078. }
  113079. /*
  113080. ** If the source-list item passed as an argument was augmented with an
  113081. ** INDEXED BY clause, then try to locate the specified index. If there
  113082. ** was such a clause and the named index cannot be found, return
  113083. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  113084. ** pFrom->pIndex and return SQLITE_OK.
  113085. */
  113086. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  113087. if( pFrom->pTab && pFrom->fg.isIndexedBy ){
  113088. Table *pTab = pFrom->pTab;
  113089. char *zIndexedBy = pFrom->u1.zIndexedBy;
  113090. Index *pIdx;
  113091. for(pIdx=pTab->pIndex;
  113092. pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
  113093. pIdx=pIdx->pNext
  113094. );
  113095. if( !pIdx ){
  113096. sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
  113097. pParse->checkSchema = 1;
  113098. return SQLITE_ERROR;
  113099. }
  113100. pFrom->pIBIndex = pIdx;
  113101. }
  113102. return SQLITE_OK;
  113103. }
  113104. /*
  113105. ** Detect compound SELECT statements that use an ORDER BY clause with
  113106. ** an alternative collating sequence.
  113107. **
  113108. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  113109. **
  113110. ** These are rewritten as a subquery:
  113111. **
  113112. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  113113. ** ORDER BY ... COLLATE ...
  113114. **
  113115. ** This transformation is necessary because the multiSelectOrderBy() routine
  113116. ** above that generates the code for a compound SELECT with an ORDER BY clause
  113117. ** uses a merge algorithm that requires the same collating sequence on the
  113118. ** result columns as on the ORDER BY clause. See ticket
  113119. ** http://www.sqlite.org/src/info/6709574d2a
  113120. **
  113121. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  113122. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  113123. ** there are COLLATE terms in the ORDER BY.
  113124. */
  113125. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  113126. int i;
  113127. Select *pNew;
  113128. Select *pX;
  113129. sqlite3 *db;
  113130. struct ExprList_item *a;
  113131. SrcList *pNewSrc;
  113132. Parse *pParse;
  113133. Token dummy;
  113134. if( p->pPrior==0 ) return WRC_Continue;
  113135. if( p->pOrderBy==0 ) return WRC_Continue;
  113136. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  113137. if( pX==0 ) return WRC_Continue;
  113138. a = p->pOrderBy->a;
  113139. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  113140. if( a[i].pExpr->flags & EP_Collate ) break;
  113141. }
  113142. if( i<0 ) return WRC_Continue;
  113143. /* If we reach this point, that means the transformation is required. */
  113144. pParse = pWalker->pParse;
  113145. db = pParse->db;
  113146. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  113147. if( pNew==0 ) return WRC_Abort;
  113148. memset(&dummy, 0, sizeof(dummy));
  113149. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  113150. if( pNewSrc==0 ) return WRC_Abort;
  113151. *pNew = *p;
  113152. p->pSrc = pNewSrc;
  113153. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
  113154. p->op = TK_SELECT;
  113155. p->pWhere = 0;
  113156. pNew->pGroupBy = 0;
  113157. pNew->pHaving = 0;
  113158. pNew->pOrderBy = 0;
  113159. p->pPrior = 0;
  113160. p->pNext = 0;
  113161. p->pWith = 0;
  113162. p->selFlags &= ~SF_Compound;
  113163. assert( (p->selFlags & SF_Converted)==0 );
  113164. p->selFlags |= SF_Converted;
  113165. assert( pNew->pPrior!=0 );
  113166. pNew->pPrior->pNext = pNew;
  113167. pNew->pLimit = 0;
  113168. pNew->pOffset = 0;
  113169. return WRC_Continue;
  113170. }
  113171. /*
  113172. ** Check to see if the FROM clause term pFrom has table-valued function
  113173. ** arguments. If it does, leave an error message in pParse and return
  113174. ** non-zero, since pFrom is not allowed to be a table-valued function.
  113175. */
  113176. static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
  113177. if( pFrom->fg.isTabFunc ){
  113178. sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
  113179. return 1;
  113180. }
  113181. return 0;
  113182. }
  113183. #ifndef SQLITE_OMIT_CTE
  113184. /*
  113185. ** Argument pWith (which may be NULL) points to a linked list of nested
  113186. ** WITH contexts, from inner to outermost. If the table identified by
  113187. ** FROM clause element pItem is really a common-table-expression (CTE)
  113188. ** then return a pointer to the CTE definition for that table. Otherwise
  113189. ** return NULL.
  113190. **
  113191. ** If a non-NULL value is returned, set *ppContext to point to the With
  113192. ** object that the returned CTE belongs to.
  113193. */
  113194. static struct Cte *searchWith(
  113195. With *pWith, /* Current innermost WITH clause */
  113196. struct SrcList_item *pItem, /* FROM clause element to resolve */
  113197. With **ppContext /* OUT: WITH clause return value belongs to */
  113198. ){
  113199. const char *zName;
  113200. if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
  113201. With *p;
  113202. for(p=pWith; p; p=p->pOuter){
  113203. int i;
  113204. for(i=0; i<p->nCte; i++){
  113205. if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
  113206. *ppContext = p;
  113207. return &p->a[i];
  113208. }
  113209. }
  113210. }
  113211. }
  113212. return 0;
  113213. }
  113214. /* The code generator maintains a stack of active WITH clauses
  113215. ** with the inner-most WITH clause being at the top of the stack.
  113216. **
  113217. ** This routine pushes the WITH clause passed as the second argument
  113218. ** onto the top of the stack. If argument bFree is true, then this
  113219. ** WITH clause will never be popped from the stack. In this case it
  113220. ** should be freed along with the Parse object. In other cases, when
  113221. ** bFree==0, the With object will be freed along with the SELECT
  113222. ** statement with which it is associated.
  113223. */
  113224. SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
  113225. assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
  113226. if( pWith ){
  113227. assert( pParse->pWith!=pWith );
  113228. pWith->pOuter = pParse->pWith;
  113229. pParse->pWith = pWith;
  113230. if( bFree ) pParse->pWithToFree = pWith;
  113231. }
  113232. }
  113233. /*
  113234. ** This function checks if argument pFrom refers to a CTE declared by
  113235. ** a WITH clause on the stack currently maintained by the parser. And,
  113236. ** if currently processing a CTE expression, if it is a recursive
  113237. ** reference to the current CTE.
  113238. **
  113239. ** If pFrom falls into either of the two categories above, pFrom->pTab
  113240. ** and other fields are populated accordingly. The caller should check
  113241. ** (pFrom->pTab!=0) to determine whether or not a successful match
  113242. ** was found.
  113243. **
  113244. ** Whether or not a match is found, SQLITE_OK is returned if no error
  113245. ** occurs. If an error does occur, an error message is stored in the
  113246. ** parser and some error code other than SQLITE_OK returned.
  113247. */
  113248. static int withExpand(
  113249. Walker *pWalker,
  113250. struct SrcList_item *pFrom
  113251. ){
  113252. Parse *pParse = pWalker->pParse;
  113253. sqlite3 *db = pParse->db;
  113254. struct Cte *pCte; /* Matched CTE (or NULL if no match) */
  113255. With *pWith; /* WITH clause that pCte belongs to */
  113256. assert( pFrom->pTab==0 );
  113257. pCte = searchWith(pParse->pWith, pFrom, &pWith);
  113258. if( pCte ){
  113259. Table *pTab;
  113260. ExprList *pEList;
  113261. Select *pSel;
  113262. Select *pLeft; /* Left-most SELECT statement */
  113263. int bMayRecursive; /* True if compound joined by UNION [ALL] */
  113264. With *pSavedWith; /* Initial value of pParse->pWith */
  113265. /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
  113266. ** recursive reference to CTE pCte. Leave an error in pParse and return
  113267. ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
  113268. ** In this case, proceed. */
  113269. if( pCte->zCteErr ){
  113270. sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
  113271. return SQLITE_ERROR;
  113272. }
  113273. if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
  113274. assert( pFrom->pTab==0 );
  113275. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  113276. if( pTab==0 ) return WRC_Abort;
  113277. pTab->nTabRef = 1;
  113278. pTab->zName = sqlite3DbStrDup(db, pCte->zName);
  113279. pTab->iPKey = -1;
  113280. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  113281. pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
  113282. pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
  113283. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  113284. assert( pFrom->pSelect );
  113285. /* Check if this is a recursive CTE. */
  113286. pSel = pFrom->pSelect;
  113287. bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
  113288. if( bMayRecursive ){
  113289. int i;
  113290. SrcList *pSrc = pFrom->pSelect->pSrc;
  113291. for(i=0; i<pSrc->nSrc; i++){
  113292. struct SrcList_item *pItem = &pSrc->a[i];
  113293. if( pItem->zDatabase==0
  113294. && pItem->zName!=0
  113295. && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
  113296. ){
  113297. pItem->pTab = pTab;
  113298. pItem->fg.isRecursive = 1;
  113299. pTab->nTabRef++;
  113300. pSel->selFlags |= SF_Recursive;
  113301. }
  113302. }
  113303. }
  113304. /* Only one recursive reference is permitted. */
  113305. if( pTab->nTabRef>2 ){
  113306. sqlite3ErrorMsg(
  113307. pParse, "multiple references to recursive table: %s", pCte->zName
  113308. );
  113309. return SQLITE_ERROR;
  113310. }
  113311. assert( pTab->nTabRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
  113312. pCte->zCteErr = "circular reference: %s";
  113313. pSavedWith = pParse->pWith;
  113314. pParse->pWith = pWith;
  113315. if( bMayRecursive ){
  113316. Select *pPrior = pSel->pPrior;
  113317. assert( pPrior->pWith==0 );
  113318. pPrior->pWith = pSel->pWith;
  113319. sqlite3WalkSelect(pWalker, pPrior);
  113320. pPrior->pWith = 0;
  113321. }else{
  113322. sqlite3WalkSelect(pWalker, pSel);
  113323. }
  113324. pParse->pWith = pWith;
  113325. for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
  113326. pEList = pLeft->pEList;
  113327. if( pCte->pCols ){
  113328. if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
  113329. sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
  113330. pCte->zName, pEList->nExpr, pCte->pCols->nExpr
  113331. );
  113332. pParse->pWith = pSavedWith;
  113333. return SQLITE_ERROR;
  113334. }
  113335. pEList = pCte->pCols;
  113336. }
  113337. sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
  113338. if( bMayRecursive ){
  113339. if( pSel->selFlags & SF_Recursive ){
  113340. pCte->zCteErr = "multiple recursive references: %s";
  113341. }else{
  113342. pCte->zCteErr = "recursive reference in a subquery: %s";
  113343. }
  113344. sqlite3WalkSelect(pWalker, pSel);
  113345. }
  113346. pCte->zCteErr = 0;
  113347. pParse->pWith = pSavedWith;
  113348. }
  113349. return SQLITE_OK;
  113350. }
  113351. #endif
  113352. #ifndef SQLITE_OMIT_CTE
  113353. /*
  113354. ** If the SELECT passed as the second argument has an associated WITH
  113355. ** clause, pop it from the stack stored as part of the Parse object.
  113356. **
  113357. ** This function is used as the xSelectCallback2() callback by
  113358. ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
  113359. ** names and other FROM clause elements.
  113360. */
  113361. static void selectPopWith(Walker *pWalker, Select *p){
  113362. Parse *pParse = pWalker->pParse;
  113363. if( pParse->pWith && p->pPrior==0 ){
  113364. With *pWith = findRightmost(p)->pWith;
  113365. if( pWith!=0 ){
  113366. assert( pParse->pWith==pWith );
  113367. pParse->pWith = pWith->pOuter;
  113368. }
  113369. }
  113370. }
  113371. #else
  113372. #define selectPopWith 0
  113373. #endif
  113374. /*
  113375. ** This routine is a Walker callback for "expanding" a SELECT statement.
  113376. ** "Expanding" means to do the following:
  113377. **
  113378. ** (1) Make sure VDBE cursor numbers have been assigned to every
  113379. ** element of the FROM clause.
  113380. **
  113381. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  113382. ** defines FROM clause. When views appear in the FROM clause,
  113383. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  113384. ** that implements the view. A copy is made of the view's SELECT
  113385. ** statement so that we can freely modify or delete that statement
  113386. ** without worrying about messing up the persistent representation
  113387. ** of the view.
  113388. **
  113389. ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
  113390. ** on joins and the ON and USING clause of joins.
  113391. **
  113392. ** (4) Scan the list of columns in the result set (pEList) looking
  113393. ** for instances of the "*" operator or the TABLE.* operator.
  113394. ** If found, expand each "*" to be every column in every table
  113395. ** and TABLE.* to be every column in TABLE.
  113396. **
  113397. */
  113398. static int selectExpander(Walker *pWalker, Select *p){
  113399. Parse *pParse = pWalker->pParse;
  113400. int i, j, k;
  113401. SrcList *pTabList;
  113402. ExprList *pEList;
  113403. struct SrcList_item *pFrom;
  113404. sqlite3 *db = pParse->db;
  113405. Expr *pE, *pRight, *pExpr;
  113406. u16 selFlags = p->selFlags;
  113407. p->selFlags |= SF_Expanded;
  113408. if( db->mallocFailed ){
  113409. return WRC_Abort;
  113410. }
  113411. if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
  113412. return WRC_Prune;
  113413. }
  113414. pTabList = p->pSrc;
  113415. pEList = p->pEList;
  113416. if( p->pWith ){
  113417. sqlite3WithPush(pParse, p->pWith, 0);
  113418. }
  113419. /* Make sure cursor numbers have been assigned to all entries in
  113420. ** the FROM clause of the SELECT statement.
  113421. */
  113422. sqlite3SrcListAssignCursors(pParse, pTabList);
  113423. /* Look up every table named in the FROM clause of the select. If
  113424. ** an entry of the FROM clause is a subquery instead of a table or view,
  113425. ** then create a transient table structure to describe the subquery.
  113426. */
  113427. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  113428. Table *pTab;
  113429. assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
  113430. if( pFrom->fg.isRecursive ) continue;
  113431. assert( pFrom->pTab==0 );
  113432. #ifndef SQLITE_OMIT_CTE
  113433. if( withExpand(pWalker, pFrom) ) return WRC_Abort;
  113434. if( pFrom->pTab ) {} else
  113435. #endif
  113436. if( pFrom->zName==0 ){
  113437. #ifndef SQLITE_OMIT_SUBQUERY
  113438. Select *pSel = pFrom->pSelect;
  113439. /* A sub-query in the FROM clause of a SELECT */
  113440. assert( pSel!=0 );
  113441. assert( pFrom->pTab==0 );
  113442. if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
  113443. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  113444. if( pTab==0 ) return WRC_Abort;
  113445. pTab->nTabRef = 1;
  113446. pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
  113447. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  113448. sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
  113449. pTab->iPKey = -1;
  113450. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  113451. pTab->tabFlags |= TF_Ephemeral;
  113452. #endif
  113453. }else{
  113454. /* An ordinary table or view name in the FROM clause */
  113455. assert( pFrom->pTab==0 );
  113456. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  113457. if( pTab==0 ) return WRC_Abort;
  113458. if( pTab->nTabRef>=0xffff ){
  113459. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  113460. pTab->zName);
  113461. pFrom->pTab = 0;
  113462. return WRC_Abort;
  113463. }
  113464. pTab->nTabRef++;
  113465. if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
  113466. return WRC_Abort;
  113467. }
  113468. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  113469. if( IsVirtual(pTab) || pTab->pSelect ){
  113470. i16 nCol;
  113471. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  113472. assert( pFrom->pSelect==0 );
  113473. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  113474. sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
  113475. nCol = pTab->nCol;
  113476. pTab->nCol = -1;
  113477. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  113478. pTab->nCol = nCol;
  113479. }
  113480. #endif
  113481. }
  113482. /* Locate the index named by the INDEXED BY clause, if any. */
  113483. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  113484. return WRC_Abort;
  113485. }
  113486. }
  113487. /* Process NATURAL keywords, and ON and USING clauses of joins.
  113488. */
  113489. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  113490. return WRC_Abort;
  113491. }
  113492. /* For every "*" that occurs in the column list, insert the names of
  113493. ** all columns in all tables. And for every TABLE.* insert the names
  113494. ** of all columns in TABLE. The parser inserted a special expression
  113495. ** with the TK_ASTERISK operator for each "*" that it found in the column
  113496. ** list. The following code just has to locate the TK_ASTERISK
  113497. ** expressions and expand each one to the list of all columns in
  113498. ** all tables.
  113499. **
  113500. ** The first loop just checks to see if there are any "*" operators
  113501. ** that need expanding.
  113502. */
  113503. for(k=0; k<pEList->nExpr; k++){
  113504. pE = pEList->a[k].pExpr;
  113505. if( pE->op==TK_ASTERISK ) break;
  113506. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  113507. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  113508. if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
  113509. }
  113510. if( k<pEList->nExpr ){
  113511. /*
  113512. ** If we get here it means the result set contains one or more "*"
  113513. ** operators that need to be expanded. Loop through each expression
  113514. ** in the result set and expand them one by one.
  113515. */
  113516. struct ExprList_item *a = pEList->a;
  113517. ExprList *pNew = 0;
  113518. int flags = pParse->db->flags;
  113519. int longNames = (flags & SQLITE_FullColNames)!=0
  113520. && (flags & SQLITE_ShortColNames)==0;
  113521. for(k=0; k<pEList->nExpr; k++){
  113522. pE = a[k].pExpr;
  113523. pRight = pE->pRight;
  113524. assert( pE->op!=TK_DOT || pRight!=0 );
  113525. if( pE->op!=TK_ASTERISK
  113526. && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
  113527. ){
  113528. /* This particular expression does not need to be expanded.
  113529. */
  113530. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  113531. if( pNew ){
  113532. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  113533. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  113534. a[k].zName = 0;
  113535. a[k].zSpan = 0;
  113536. }
  113537. a[k].pExpr = 0;
  113538. }else{
  113539. /* This expression is a "*" or a "TABLE.*" and needs to be
  113540. ** expanded. */
  113541. int tableSeen = 0; /* Set to 1 when TABLE matches */
  113542. char *zTName = 0; /* text of name of TABLE */
  113543. if( pE->op==TK_DOT ){
  113544. assert( pE->pLeft!=0 );
  113545. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  113546. zTName = pE->pLeft->u.zToken;
  113547. }
  113548. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  113549. Table *pTab = pFrom->pTab;
  113550. Select *pSub = pFrom->pSelect;
  113551. char *zTabName = pFrom->zAlias;
  113552. const char *zSchemaName = 0;
  113553. int iDb;
  113554. if( zTabName==0 ){
  113555. zTabName = pTab->zName;
  113556. }
  113557. if( db->mallocFailed ) break;
  113558. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  113559. pSub = 0;
  113560. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  113561. continue;
  113562. }
  113563. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  113564. zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
  113565. }
  113566. for(j=0; j<pTab->nCol; j++){
  113567. char *zName = pTab->aCol[j].zName;
  113568. char *zColname; /* The computed column name */
  113569. char *zToFree; /* Malloced string that needs to be freed */
  113570. Token sColname; /* Computed column name as a token */
  113571. assert( zName );
  113572. if( zTName && pSub
  113573. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  113574. ){
  113575. continue;
  113576. }
  113577. /* If a column is marked as 'hidden', omit it from the expanded
  113578. ** result-set list unless the SELECT has the SF_IncludeHidden
  113579. ** bit set.
  113580. */
  113581. if( (p->selFlags & SF_IncludeHidden)==0
  113582. && IsHiddenColumn(&pTab->aCol[j])
  113583. ){
  113584. continue;
  113585. }
  113586. tableSeen = 1;
  113587. if( i>0 && zTName==0 ){
  113588. if( (pFrom->fg.jointype & JT_NATURAL)!=0
  113589. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  113590. ){
  113591. /* In a NATURAL join, omit the join columns from the
  113592. ** table to the right of the join */
  113593. continue;
  113594. }
  113595. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  113596. /* In a join with a USING clause, omit columns in the
  113597. ** using clause from the table on the right. */
  113598. continue;
  113599. }
  113600. }
  113601. pRight = sqlite3Expr(db, TK_ID, zName);
  113602. zColname = zName;
  113603. zToFree = 0;
  113604. if( longNames || pTabList->nSrc>1 ){
  113605. Expr *pLeft;
  113606. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  113607. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  113608. if( zSchemaName ){
  113609. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  113610. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
  113611. }
  113612. if( longNames ){
  113613. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  113614. zToFree = zColname;
  113615. }
  113616. }else{
  113617. pExpr = pRight;
  113618. }
  113619. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  113620. sqlite3TokenInit(&sColname, zColname);
  113621. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  113622. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  113623. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  113624. if( pSub ){
  113625. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  113626. testcase( pX->zSpan==0 );
  113627. }else{
  113628. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  113629. zSchemaName, zTabName, zColname);
  113630. testcase( pX->zSpan==0 );
  113631. }
  113632. pX->bSpanIsTab = 1;
  113633. }
  113634. sqlite3DbFree(db, zToFree);
  113635. }
  113636. }
  113637. if( !tableSeen ){
  113638. if( zTName ){
  113639. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  113640. }else{
  113641. sqlite3ErrorMsg(pParse, "no tables specified");
  113642. }
  113643. }
  113644. }
  113645. }
  113646. sqlite3ExprListDelete(db, pEList);
  113647. p->pEList = pNew;
  113648. }
  113649. #if SQLITE_MAX_COLUMN
  113650. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  113651. sqlite3ErrorMsg(pParse, "too many columns in result set");
  113652. return WRC_Abort;
  113653. }
  113654. #endif
  113655. return WRC_Continue;
  113656. }
  113657. /*
  113658. ** No-op routine for the parse-tree walker.
  113659. **
  113660. ** When this routine is the Walker.xExprCallback then expression trees
  113661. ** are walked without any actions being taken at each node. Presumably,
  113662. ** when this routine is used for Walker.xExprCallback then
  113663. ** Walker.xSelectCallback is set to do something useful for every
  113664. ** subquery in the parser tree.
  113665. */
  113666. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  113667. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  113668. return WRC_Continue;
  113669. }
  113670. /*
  113671. ** This routine "expands" a SELECT statement and all of its subqueries.
  113672. ** For additional information on what it means to "expand" a SELECT
  113673. ** statement, see the comment on the selectExpand worker callback above.
  113674. **
  113675. ** Expanding a SELECT statement is the first step in processing a
  113676. ** SELECT statement. The SELECT statement must be expanded before
  113677. ** name resolution is performed.
  113678. **
  113679. ** If anything goes wrong, an error message is written into pParse.
  113680. ** The calling function can detect the problem by looking at pParse->nErr
  113681. ** and/or pParse->db->mallocFailed.
  113682. */
  113683. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  113684. Walker w;
  113685. memset(&w, 0, sizeof(w));
  113686. w.xExprCallback = sqlite3ExprWalkNoop;
  113687. w.pParse = pParse;
  113688. if( pParse->hasCompound ){
  113689. w.xSelectCallback = convertCompoundSelectToSubquery;
  113690. sqlite3WalkSelect(&w, pSelect);
  113691. }
  113692. w.xSelectCallback = selectExpander;
  113693. w.xSelectCallback2 = selectPopWith;
  113694. sqlite3WalkSelect(&w, pSelect);
  113695. }
  113696. #ifndef SQLITE_OMIT_SUBQUERY
  113697. /*
  113698. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  113699. ** interface.
  113700. **
  113701. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  113702. ** information to the Table structure that represents the result set
  113703. ** of that subquery.
  113704. **
  113705. ** The Table structure that represents the result set was constructed
  113706. ** by selectExpander() but the type and collation information was omitted
  113707. ** at that point because identifiers had not yet been resolved. This
  113708. ** routine is called after identifier resolution.
  113709. */
  113710. static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  113711. Parse *pParse;
  113712. int i;
  113713. SrcList *pTabList;
  113714. struct SrcList_item *pFrom;
  113715. assert( p->selFlags & SF_Resolved );
  113716. assert( (p->selFlags & SF_HasTypeInfo)==0 );
  113717. p->selFlags |= SF_HasTypeInfo;
  113718. pParse = pWalker->pParse;
  113719. pTabList = p->pSrc;
  113720. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  113721. Table *pTab = pFrom->pTab;
  113722. assert( pTab!=0 );
  113723. if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
  113724. /* A sub-query in the FROM clause of a SELECT */
  113725. Select *pSel = pFrom->pSelect;
  113726. if( pSel ){
  113727. while( pSel->pPrior ) pSel = pSel->pPrior;
  113728. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
  113729. }
  113730. }
  113731. }
  113732. }
  113733. #endif
  113734. /*
  113735. ** This routine adds datatype and collating sequence information to
  113736. ** the Table structures of all FROM-clause subqueries in a
  113737. ** SELECT statement.
  113738. **
  113739. ** Use this routine after name resolution.
  113740. */
  113741. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  113742. #ifndef SQLITE_OMIT_SUBQUERY
  113743. Walker w;
  113744. memset(&w, 0, sizeof(w));
  113745. w.xSelectCallback2 = selectAddSubqueryTypeInfo;
  113746. w.xExprCallback = sqlite3ExprWalkNoop;
  113747. w.pParse = pParse;
  113748. sqlite3WalkSelect(&w, pSelect);
  113749. #endif
  113750. }
  113751. /*
  113752. ** This routine sets up a SELECT statement for processing. The
  113753. ** following is accomplished:
  113754. **
  113755. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  113756. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  113757. ** * ON and USING clauses are shifted into WHERE statements
  113758. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  113759. ** * Identifiers in expression are matched to tables.
  113760. **
  113761. ** This routine acts recursively on all subqueries within the SELECT.
  113762. */
  113763. SQLITE_PRIVATE void sqlite3SelectPrep(
  113764. Parse *pParse, /* The parser context */
  113765. Select *p, /* The SELECT statement being coded. */
  113766. NameContext *pOuterNC /* Name context for container */
  113767. ){
  113768. sqlite3 *db;
  113769. if( NEVER(p==0) ) return;
  113770. db = pParse->db;
  113771. if( db->mallocFailed ) return;
  113772. if( p->selFlags & SF_HasTypeInfo ) return;
  113773. sqlite3SelectExpand(pParse, p);
  113774. if( pParse->nErr || db->mallocFailed ) return;
  113775. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  113776. if( pParse->nErr || db->mallocFailed ) return;
  113777. sqlite3SelectAddTypeInfo(pParse, p);
  113778. }
  113779. /*
  113780. ** Reset the aggregate accumulator.
  113781. **
  113782. ** The aggregate accumulator is a set of memory cells that hold
  113783. ** intermediate results while calculating an aggregate. This
  113784. ** routine generates code that stores NULLs in all of those memory
  113785. ** cells.
  113786. */
  113787. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  113788. Vdbe *v = pParse->pVdbe;
  113789. int i;
  113790. struct AggInfo_func *pFunc;
  113791. int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
  113792. if( nReg==0 ) return;
  113793. #ifdef SQLITE_DEBUG
  113794. /* Verify that all AggInfo registers are within the range specified by
  113795. ** AggInfo.mnReg..AggInfo.mxReg */
  113796. assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
  113797. for(i=0; i<pAggInfo->nColumn; i++){
  113798. assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
  113799. && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
  113800. }
  113801. for(i=0; i<pAggInfo->nFunc; i++){
  113802. assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
  113803. && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
  113804. }
  113805. #endif
  113806. sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
  113807. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  113808. if( pFunc->iDistinct>=0 ){
  113809. Expr *pE = pFunc->pExpr;
  113810. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  113811. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  113812. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  113813. "argument");
  113814. pFunc->iDistinct = -1;
  113815. }else{
  113816. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
  113817. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  113818. (char*)pKeyInfo, P4_KEYINFO);
  113819. }
  113820. }
  113821. }
  113822. }
  113823. /*
  113824. ** Invoke the OP_AggFinalize opcode for every aggregate function
  113825. ** in the AggInfo structure.
  113826. */
  113827. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  113828. Vdbe *v = pParse->pVdbe;
  113829. int i;
  113830. struct AggInfo_func *pF;
  113831. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  113832. ExprList *pList = pF->pExpr->x.pList;
  113833. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  113834. sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
  113835. sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  113836. }
  113837. }
  113838. /*
  113839. ** Update the accumulator memory cells for an aggregate based on
  113840. ** the current cursor position.
  113841. */
  113842. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  113843. Vdbe *v = pParse->pVdbe;
  113844. int i;
  113845. int regHit = 0;
  113846. int addrHitTest = 0;
  113847. struct AggInfo_func *pF;
  113848. struct AggInfo_col *pC;
  113849. pAggInfo->directMode = 1;
  113850. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  113851. int nArg;
  113852. int addrNext = 0;
  113853. int regAgg;
  113854. ExprList *pList = pF->pExpr->x.pList;
  113855. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  113856. if( pList ){
  113857. nArg = pList->nExpr;
  113858. regAgg = sqlite3GetTempRange(pParse, nArg);
  113859. sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
  113860. }else{
  113861. nArg = 0;
  113862. regAgg = 0;
  113863. }
  113864. if( pF->iDistinct>=0 ){
  113865. addrNext = sqlite3VdbeMakeLabel(v);
  113866. testcase( nArg==0 ); /* Error condition */
  113867. testcase( nArg>1 ); /* Also an error */
  113868. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  113869. }
  113870. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  113871. CollSeq *pColl = 0;
  113872. struct ExprList_item *pItem;
  113873. int j;
  113874. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  113875. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  113876. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  113877. }
  113878. if( !pColl ){
  113879. pColl = pParse->db->pDfltColl;
  113880. }
  113881. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  113882. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  113883. }
  113884. sqlite3VdbeAddOp3(v, OP_AggStep0, 0, regAgg, pF->iMem);
  113885. sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  113886. sqlite3VdbeChangeP5(v, (u8)nArg);
  113887. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  113888. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  113889. if( addrNext ){
  113890. sqlite3VdbeResolveLabel(v, addrNext);
  113891. sqlite3ExprCacheClear(pParse);
  113892. }
  113893. }
  113894. /* Before populating the accumulator registers, clear the column cache.
  113895. ** Otherwise, if any of the required column values are already present
  113896. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  113897. ** to pC->iMem. But by the time the value is used, the original register
  113898. ** may have been used, invalidating the underlying buffer holding the
  113899. ** text or blob value. See ticket [883034dcb5].
  113900. **
  113901. ** Another solution would be to change the OP_SCopy used to copy cached
  113902. ** values to an OP_Copy.
  113903. */
  113904. if( regHit ){
  113905. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
  113906. }
  113907. sqlite3ExprCacheClear(pParse);
  113908. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  113909. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  113910. }
  113911. pAggInfo->directMode = 0;
  113912. sqlite3ExprCacheClear(pParse);
  113913. if( addrHitTest ){
  113914. sqlite3VdbeJumpHere(v, addrHitTest);
  113915. }
  113916. }
  113917. /*
  113918. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  113919. ** count(*) query ("SELECT count(*) FROM pTab").
  113920. */
  113921. #ifndef SQLITE_OMIT_EXPLAIN
  113922. static void explainSimpleCount(
  113923. Parse *pParse, /* Parse context */
  113924. Table *pTab, /* Table being queried */
  113925. Index *pIdx /* Index used to optimize scan, or NULL */
  113926. ){
  113927. if( pParse->explain==2 ){
  113928. int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
  113929. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
  113930. pTab->zName,
  113931. bCover ? " USING COVERING INDEX " : "",
  113932. bCover ? pIdx->zName : ""
  113933. );
  113934. sqlite3VdbeAddOp4(
  113935. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  113936. );
  113937. }
  113938. }
  113939. #else
  113940. # define explainSimpleCount(a,b,c)
  113941. #endif
  113942. /*
  113943. ** Context object for havingToWhereExprCb().
  113944. */
  113945. struct HavingToWhereCtx {
  113946. Expr **ppWhere;
  113947. ExprList *pGroupBy;
  113948. };
  113949. /*
  113950. ** sqlite3WalkExpr() callback used by havingToWhere().
  113951. **
  113952. ** If the node passed to the callback is a TK_AND node, return
  113953. ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
  113954. **
  113955. ** Otherwise, return WRC_Prune. In this case, also check if the
  113956. ** sub-expression matches the criteria for being moved to the WHERE
  113957. ** clause. If so, add it to the WHERE clause and replace the sub-expression
  113958. ** within the HAVING expression with a constant "1".
  113959. */
  113960. static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
  113961. if( pExpr->op!=TK_AND ){
  113962. struct HavingToWhereCtx *p = pWalker->u.pHavingCtx;
  113963. if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, p->pGroupBy) ){
  113964. sqlite3 *db = pWalker->pParse->db;
  113965. Expr *pNew = sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[1], 0);
  113966. if( pNew ){
  113967. Expr *pWhere = *(p->ppWhere);
  113968. SWAP(Expr, *pNew, *pExpr);
  113969. pNew = sqlite3ExprAnd(db, pWhere, pNew);
  113970. *(p->ppWhere) = pNew;
  113971. }
  113972. }
  113973. return WRC_Prune;
  113974. }
  113975. return WRC_Continue;
  113976. }
  113977. /*
  113978. ** Transfer eligible terms from the HAVING clause of a query, which is
  113979. ** processed after grouping, to the WHERE clause, which is processed before
  113980. ** grouping. For example, the query:
  113981. **
  113982. ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
  113983. **
  113984. ** can be rewritten as:
  113985. **
  113986. ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
  113987. **
  113988. ** A term of the HAVING expression is eligible for transfer if it consists
  113989. ** entirely of constants and expressions that are also GROUP BY terms that
  113990. ** use the "BINARY" collation sequence.
  113991. */
  113992. static void havingToWhere(
  113993. Parse *pParse,
  113994. ExprList *pGroupBy,
  113995. Expr *pHaving,
  113996. Expr **ppWhere
  113997. ){
  113998. struct HavingToWhereCtx sCtx;
  113999. Walker sWalker;
  114000. sCtx.ppWhere = ppWhere;
  114001. sCtx.pGroupBy = pGroupBy;
  114002. memset(&sWalker, 0, sizeof(sWalker));
  114003. sWalker.pParse = pParse;
  114004. sWalker.xExprCallback = havingToWhereExprCb;
  114005. sWalker.u.pHavingCtx = &sCtx;
  114006. sqlite3WalkExpr(&sWalker, pHaving);
  114007. }
  114008. /*
  114009. ** Check to see if the pThis entry of pTabList is a self-join of a prior view.
  114010. ** If it is, then return the SrcList_item for the prior view. If it is not,
  114011. ** then return 0.
  114012. */
  114013. static struct SrcList_item *isSelfJoinView(
  114014. SrcList *pTabList, /* Search for self-joins in this FROM clause */
  114015. struct SrcList_item *pThis /* Search for prior reference to this subquery */
  114016. ){
  114017. struct SrcList_item *pItem;
  114018. for(pItem = pTabList->a; pItem<pThis; pItem++){
  114019. if( pItem->pSelect==0 ) continue;
  114020. if( pItem->fg.viaCoroutine ) continue;
  114021. if( pItem->zName==0 ) continue;
  114022. if( sqlite3_stricmp(pItem->zDatabase, pThis->zDatabase)!=0 ) continue;
  114023. if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
  114024. if( sqlite3ExprCompare(pThis->pSelect->pWhere, pItem->pSelect->pWhere, -1) ){
  114025. /* The view was modified by some other optimization such as
  114026. ** pushDownWhereTerms() */
  114027. continue;
  114028. }
  114029. return pItem;
  114030. }
  114031. return 0;
  114032. }
  114033. /*
  114034. ** Generate code for the SELECT statement given in the p argument.
  114035. **
  114036. ** The results are returned according to the SelectDest structure.
  114037. ** See comments in sqliteInt.h for further information.
  114038. **
  114039. ** This routine returns the number of errors. If any errors are
  114040. ** encountered, then an appropriate error message is left in
  114041. ** pParse->zErrMsg.
  114042. **
  114043. ** This routine does NOT free the Select structure passed in. The
  114044. ** calling function needs to do that.
  114045. */
  114046. SQLITE_PRIVATE int sqlite3Select(
  114047. Parse *pParse, /* The parser context */
  114048. Select *p, /* The SELECT statement being coded. */
  114049. SelectDest *pDest /* What to do with the query results */
  114050. ){
  114051. int i, j; /* Loop counters */
  114052. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  114053. Vdbe *v; /* The virtual machine under construction */
  114054. int isAgg; /* True for select lists like "count(*)" */
  114055. ExprList *pEList = 0; /* List of columns to extract. */
  114056. SrcList *pTabList; /* List of tables to select from */
  114057. Expr *pWhere; /* The WHERE clause. May be NULL */
  114058. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  114059. Expr *pHaving; /* The HAVING clause. May be NULL */
  114060. int rc = 1; /* Value to return from this function */
  114061. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  114062. SortCtx sSort; /* Info on how to code the ORDER BY clause */
  114063. AggInfo sAggInfo; /* Information used by aggregate queries */
  114064. int iEnd; /* Address of the end of the query */
  114065. sqlite3 *db; /* The database connection */
  114066. #ifndef SQLITE_OMIT_EXPLAIN
  114067. int iRestoreSelectId = pParse->iSelectId;
  114068. pParse->iSelectId = pParse->iNextSelectId++;
  114069. #endif
  114070. db = pParse->db;
  114071. if( p==0 || db->mallocFailed || pParse->nErr ){
  114072. return 1;
  114073. }
  114074. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  114075. memset(&sAggInfo, 0, sizeof(sAggInfo));
  114076. #if SELECTTRACE_ENABLED
  114077. pParse->nSelectIndent++;
  114078. SELECTTRACE(1,pParse,p, ("begin processing:\n"));
  114079. if( sqlite3SelectTrace & 0x100 ){
  114080. sqlite3TreeViewSelect(0, p, 0);
  114081. }
  114082. #endif
  114083. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
  114084. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
  114085. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
  114086. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
  114087. if( IgnorableOrderby(pDest) ){
  114088. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  114089. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
  114090. pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
  114091. pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
  114092. /* If ORDER BY makes no difference in the output then neither does
  114093. ** DISTINCT so it can be removed too. */
  114094. sqlite3ExprListDelete(db, p->pOrderBy);
  114095. p->pOrderBy = 0;
  114096. p->selFlags &= ~SF_Distinct;
  114097. }
  114098. sqlite3SelectPrep(pParse, p, 0);
  114099. memset(&sSort, 0, sizeof(sSort));
  114100. sSort.pOrderBy = p->pOrderBy;
  114101. pTabList = p->pSrc;
  114102. if( pParse->nErr || db->mallocFailed ){
  114103. goto select_end;
  114104. }
  114105. assert( p->pEList!=0 );
  114106. isAgg = (p->selFlags & SF_Aggregate)!=0;
  114107. #if SELECTTRACE_ENABLED
  114108. if( sqlite3SelectTrace & 0x100 ){
  114109. SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
  114110. sqlite3TreeViewSelect(0, p, 0);
  114111. }
  114112. #endif
  114113. /* Try to flatten subqueries in the FROM clause up into the main query
  114114. */
  114115. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  114116. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  114117. struct SrcList_item *pItem = &pTabList->a[i];
  114118. Select *pSub = pItem->pSelect;
  114119. int isAggSub;
  114120. Table *pTab = pItem->pTab;
  114121. if( pSub==0 ) continue;
  114122. /* Catch mismatch in the declared columns of a view and the number of
  114123. ** columns in the SELECT on the RHS */
  114124. if( pTab->nCol!=pSub->pEList->nExpr ){
  114125. sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
  114126. pTab->nCol, pTab->zName, pSub->pEList->nExpr);
  114127. goto select_end;
  114128. }
  114129. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  114130. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  114131. /* This subquery can be absorbed into its parent. */
  114132. if( isAggSub ){
  114133. isAgg = 1;
  114134. p->selFlags |= SF_Aggregate;
  114135. }
  114136. i = -1;
  114137. }
  114138. pTabList = p->pSrc;
  114139. if( db->mallocFailed ) goto select_end;
  114140. if( !IgnorableOrderby(pDest) ){
  114141. sSort.pOrderBy = p->pOrderBy;
  114142. }
  114143. }
  114144. #endif
  114145. /* Get a pointer the VDBE under construction, allocating a new VDBE if one
  114146. ** does not already exist */
  114147. v = sqlite3GetVdbe(pParse);
  114148. if( v==0 ) goto select_end;
  114149. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  114150. /* Handle compound SELECT statements using the separate multiSelect()
  114151. ** procedure.
  114152. */
  114153. if( p->pPrior ){
  114154. rc = multiSelect(pParse, p, pDest);
  114155. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  114156. #if SELECTTRACE_ENABLED
  114157. SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
  114158. pParse->nSelectIndent--;
  114159. #endif
  114160. return rc;
  114161. }
  114162. #endif
  114163. /* For each term in the FROM clause, do two things:
  114164. ** (1) Authorized unreferenced tables
  114165. ** (2) Generate code for all sub-queries
  114166. */
  114167. for(i=0; i<pTabList->nSrc; i++){
  114168. struct SrcList_item *pItem = &pTabList->a[i];
  114169. SelectDest dest;
  114170. Select *pSub;
  114171. /* Issue SQLITE_READ authorizations with a fake column name for any tables that
  114172. ** are referenced but from which no values are extracted. Examples of where these
  114173. ** kinds of null SQLITE_READ authorizations would occur:
  114174. **
  114175. ** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
  114176. ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
  114177. **
  114178. ** The fake column name is an empty string. It is possible for a table to
  114179. ** have a column named by the empty string, in which case there is no way to
  114180. ** distinguish between an unreferenced table and an actual reference to the
  114181. ** "" column. The original design was for the fake column name to be a NULL,
  114182. ** which would be unambiguous. But legacy authorization callbacks might
  114183. ** assume the column name is non-NULL and segfault. The use of an empty string
  114184. ** for the fake column name seems safer.
  114185. */
  114186. if( pItem->colUsed==0 ){
  114187. sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
  114188. }
  114189. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  114190. /* Generate code for all sub-queries in the FROM clause
  114191. */
  114192. pSub = pItem->pSelect;
  114193. if( pSub==0 ) continue;
  114194. /* Sometimes the code for a subquery will be generated more than
  114195. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  114196. ** for example. In that case, do not regenerate the code to manifest
  114197. ** a view or the co-routine to implement a view. The first instance
  114198. ** is sufficient, though the subroutine to manifest the view does need
  114199. ** to be invoked again. */
  114200. if( pItem->addrFillSub ){
  114201. if( pItem->fg.viaCoroutine==0 ){
  114202. /* The subroutine that manifests the view might be a one-time routine,
  114203. ** or it might need to be rerun on each iteration because it
  114204. ** encodes a correlated subquery. */
  114205. testcase( sqlite3VdbeGetOp(v, pItem->addrFillSub)->opcode==OP_Once );
  114206. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  114207. }
  114208. continue;
  114209. }
  114210. /* Increment Parse.nHeight by the height of the largest expression
  114211. ** tree referred to by this, the parent select. The child select
  114212. ** may contain expression trees of at most
  114213. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  114214. ** more conservative than necessary, but much easier than enforcing
  114215. ** an exact limit.
  114216. */
  114217. pParse->nHeight += sqlite3SelectExprHeight(p);
  114218. /* Make copies of constant WHERE-clause terms in the outer query down
  114219. ** inside the subquery. This can help the subquery to run more efficiently.
  114220. */
  114221. if( (pItem->fg.jointype & JT_OUTER)==0
  114222. && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor)
  114223. ){
  114224. #if SELECTTRACE_ENABLED
  114225. if( sqlite3SelectTrace & 0x100 ){
  114226. SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
  114227. sqlite3TreeViewSelect(0, p, 0);
  114228. }
  114229. #endif
  114230. }
  114231. /* Generate code to implement the subquery
  114232. **
  114233. ** The subquery is implemented as a co-routine if all of these are true:
  114234. ** (1) The subquery is guaranteed to be the outer loop (so that it
  114235. ** does not need to be computed more than once)
  114236. ** (2) The ALL keyword after SELECT is omitted. (Applications are
  114237. ** allowed to say "SELECT ALL" instead of just "SELECT" to disable
  114238. ** the use of co-routines.)
  114239. ** (3) Co-routines are not disabled using sqlite3_test_control()
  114240. ** with SQLITE_TESTCTRL_OPTIMIZATIONS.
  114241. **
  114242. ** TODO: Are there other reasons beside (1) to use a co-routine
  114243. ** implementation?
  114244. */
  114245. if( i==0
  114246. && (pTabList->nSrc==1
  114247. || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */
  114248. && (p->selFlags & SF_All)==0 /* (2) */
  114249. && OptimizationEnabled(db, SQLITE_SubqCoroutine) /* (3) */
  114250. ){
  114251. /* Implement a co-routine that will return a single row of the result
  114252. ** set on each invocation.
  114253. */
  114254. int addrTop = sqlite3VdbeCurrentAddr(v)+1;
  114255. pItem->regReturn = ++pParse->nMem;
  114256. sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
  114257. VdbeComment((v, "%s", pItem->pTab->zName));
  114258. pItem->addrFillSub = addrTop;
  114259. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  114260. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  114261. sqlite3Select(pParse, pSub, &dest);
  114262. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  114263. pItem->fg.viaCoroutine = 1;
  114264. pItem->regResult = dest.iSdst;
  114265. sqlite3VdbeEndCoroutine(v, pItem->regReturn);
  114266. sqlite3VdbeJumpHere(v, addrTop-1);
  114267. sqlite3ClearTempRegCache(pParse);
  114268. }else{
  114269. /* Generate a subroutine that will fill an ephemeral table with
  114270. ** the content of this subquery. pItem->addrFillSub will point
  114271. ** to the address of the generated subroutine. pItem->regReturn
  114272. ** is a register allocated to hold the subroutine return address
  114273. */
  114274. int topAddr;
  114275. int onceAddr = 0;
  114276. int retAddr;
  114277. struct SrcList_item *pPrior;
  114278. assert( pItem->addrFillSub==0 );
  114279. pItem->regReturn = ++pParse->nMem;
  114280. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  114281. pItem->addrFillSub = topAddr+1;
  114282. if( pItem->fg.isCorrelated==0 ){
  114283. /* If the subquery is not correlated and if we are not inside of
  114284. ** a trigger, then we only need to compute the value of the subquery
  114285. ** once. */
  114286. onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  114287. VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
  114288. }else{
  114289. VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
  114290. }
  114291. pPrior = isSelfJoinView(pTabList, pItem);
  114292. if( pPrior ){
  114293. sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
  114294. }else{
  114295. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  114296. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  114297. sqlite3Select(pParse, pSub, &dest);
  114298. }
  114299. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  114300. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  114301. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  114302. VdbeComment((v, "end %s", pItem->pTab->zName));
  114303. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  114304. sqlite3ClearTempRegCache(pParse);
  114305. }
  114306. if( db->mallocFailed ) goto select_end;
  114307. pParse->nHeight -= sqlite3SelectExprHeight(p);
  114308. #endif
  114309. }
  114310. /* Various elements of the SELECT copied into local variables for
  114311. ** convenience */
  114312. pEList = p->pEList;
  114313. pWhere = p->pWhere;
  114314. pGroupBy = p->pGroupBy;
  114315. pHaving = p->pHaving;
  114316. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  114317. #if SELECTTRACE_ENABLED
  114318. if( sqlite3SelectTrace & 0x400 ){
  114319. SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
  114320. sqlite3TreeViewSelect(0, p, 0);
  114321. }
  114322. #endif
  114323. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  114324. ** if the select-list is the same as the ORDER BY list, then this query
  114325. ** can be rewritten as a GROUP BY. In other words, this:
  114326. **
  114327. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  114328. **
  114329. ** is transformed to:
  114330. **
  114331. ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
  114332. **
  114333. ** The second form is preferred as a single index (or temp-table) may be
  114334. ** used for both the ORDER BY and DISTINCT processing. As originally
  114335. ** written the query must use a temp-table for at least one of the ORDER
  114336. ** BY and DISTINCT, and an index or separate temp-table for the other.
  114337. */
  114338. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  114339. && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
  114340. ){
  114341. p->selFlags &= ~SF_Distinct;
  114342. pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
  114343. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  114344. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  114345. ** original setting of the SF_Distinct flag, not the current setting */
  114346. assert( sDistinct.isTnct );
  114347. #if SELECTTRACE_ENABLED
  114348. if( sqlite3SelectTrace & 0x400 ){
  114349. SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
  114350. sqlite3TreeViewSelect(0, p, 0);
  114351. }
  114352. #endif
  114353. }
  114354. /* If there is an ORDER BY clause, then create an ephemeral index to
  114355. ** do the sorting. But this sorting ephemeral index might end up
  114356. ** being unused if the data can be extracted in pre-sorted order.
  114357. ** If that is the case, then the OP_OpenEphemeral instruction will be
  114358. ** changed to an OP_Noop once we figure out that the sorting index is
  114359. ** not needed. The sSort.addrSortIndex variable is used to facilitate
  114360. ** that change.
  114361. */
  114362. if( sSort.pOrderBy ){
  114363. KeyInfo *pKeyInfo;
  114364. pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
  114365. sSort.iECursor = pParse->nTab++;
  114366. sSort.addrSortIndex =
  114367. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  114368. sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
  114369. (char*)pKeyInfo, P4_KEYINFO
  114370. );
  114371. }else{
  114372. sSort.addrSortIndex = -1;
  114373. }
  114374. /* If the output is destined for a temporary table, open that table.
  114375. */
  114376. if( pDest->eDest==SRT_EphemTab ){
  114377. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  114378. }
  114379. /* Set the limiter.
  114380. */
  114381. iEnd = sqlite3VdbeMakeLabel(v);
  114382. if( (p->selFlags & SF_FixedLimit)==0 ){
  114383. p->nSelectRow = 320; /* 4 billion rows */
  114384. }
  114385. computeLimitRegisters(pParse, p, iEnd);
  114386. if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
  114387. sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
  114388. sSort.sortFlags |= SORTFLAG_UseSorter;
  114389. }
  114390. /* Open an ephemeral index to use for the distinct set.
  114391. */
  114392. if( p->selFlags & SF_Distinct ){
  114393. sDistinct.tabTnct = pParse->nTab++;
  114394. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  114395. sDistinct.tabTnct, 0, 0,
  114396. (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
  114397. P4_KEYINFO);
  114398. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  114399. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  114400. }else{
  114401. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  114402. }
  114403. if( !isAgg && pGroupBy==0 ){
  114404. /* No aggregate functions and no GROUP BY clause */
  114405. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
  114406. assert( WHERE_USE_LIMIT==SF_FixedLimit );
  114407. wctrlFlags |= p->selFlags & SF_FixedLimit;
  114408. /* Begin the database scan. */
  114409. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
  114410. p->pEList, wctrlFlags, p->nSelectRow);
  114411. if( pWInfo==0 ) goto select_end;
  114412. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  114413. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  114414. }
  114415. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  114416. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  114417. }
  114418. if( sSort.pOrderBy ){
  114419. sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
  114420. sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo);
  114421. if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
  114422. sSort.pOrderBy = 0;
  114423. }
  114424. }
  114425. /* If sorting index that was created by a prior OP_OpenEphemeral
  114426. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  114427. ** into an OP_Noop.
  114428. */
  114429. if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
  114430. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  114431. }
  114432. /* Use the standard inner loop. */
  114433. selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
  114434. sqlite3WhereContinueLabel(pWInfo),
  114435. sqlite3WhereBreakLabel(pWInfo));
  114436. /* End the database scan loop.
  114437. */
  114438. sqlite3WhereEnd(pWInfo);
  114439. }else{
  114440. /* This case when there exist aggregate functions or a GROUP BY clause
  114441. ** or both */
  114442. NameContext sNC; /* Name context for processing aggregate information */
  114443. int iAMem; /* First Mem address for storing current GROUP BY */
  114444. int iBMem; /* First Mem address for previous GROUP BY */
  114445. int iUseFlag; /* Mem address holding flag indicating that at least
  114446. ** one row of the input to the aggregator has been
  114447. ** processed */
  114448. int iAbortFlag; /* Mem address which causes query abort if positive */
  114449. int groupBySort; /* Rows come from source in GROUP BY order */
  114450. int addrEnd; /* End of processing for this SELECT */
  114451. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  114452. int sortOut = 0; /* Output register from the sorter */
  114453. int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
  114454. /* Remove any and all aliases between the result set and the
  114455. ** GROUP BY clause.
  114456. */
  114457. if( pGroupBy ){
  114458. int k; /* Loop counter */
  114459. struct ExprList_item *pItem; /* For looping over expression in a list */
  114460. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  114461. pItem->u.x.iAlias = 0;
  114462. }
  114463. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  114464. pItem->u.x.iAlias = 0;
  114465. }
  114466. assert( 66==sqlite3LogEst(100) );
  114467. if( p->nSelectRow>66 ) p->nSelectRow = 66;
  114468. }else{
  114469. assert( 0==sqlite3LogEst(1) );
  114470. p->nSelectRow = 0;
  114471. }
  114472. /* If there is both a GROUP BY and an ORDER BY clause and they are
  114473. ** identical, then it may be possible to disable the ORDER BY clause
  114474. ** on the grounds that the GROUP BY will cause elements to come out
  114475. ** in the correct order. It also may not - the GROUP BY might use a
  114476. ** database index that causes rows to be grouped together as required
  114477. ** but not actually sorted. Either way, record the fact that the
  114478. ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
  114479. ** variable. */
  114480. if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
  114481. orderByGrp = 1;
  114482. }
  114483. /* Create a label to jump to when we want to abort the query */
  114484. addrEnd = sqlite3VdbeMakeLabel(v);
  114485. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  114486. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  114487. ** SELECT statement.
  114488. */
  114489. memset(&sNC, 0, sizeof(sNC));
  114490. sNC.pParse = pParse;
  114491. sNC.pSrcList = pTabList;
  114492. sNC.pAggInfo = &sAggInfo;
  114493. sAggInfo.mnReg = pParse->nMem+1;
  114494. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
  114495. sAggInfo.pGroupBy = pGroupBy;
  114496. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  114497. sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
  114498. if( pHaving ){
  114499. if( pGroupBy ){
  114500. assert( pWhere==p->pWhere );
  114501. havingToWhere(pParse, pGroupBy, pHaving, &p->pWhere);
  114502. pWhere = p->pWhere;
  114503. }
  114504. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  114505. }
  114506. sAggInfo.nAccumulator = sAggInfo.nColumn;
  114507. for(i=0; i<sAggInfo.nFunc; i++){
  114508. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  114509. sNC.ncFlags |= NC_InAggFunc;
  114510. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  114511. sNC.ncFlags &= ~NC_InAggFunc;
  114512. }
  114513. sAggInfo.mxReg = pParse->nMem;
  114514. if( db->mallocFailed ) goto select_end;
  114515. /* Processing for aggregates with GROUP BY is very different and
  114516. ** much more complex than aggregates without a GROUP BY.
  114517. */
  114518. if( pGroupBy ){
  114519. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  114520. int addr1; /* A-vs-B comparision jump */
  114521. int addrOutputRow; /* Start of subroutine that outputs a result row */
  114522. int regOutputRow; /* Return address register for output subroutine */
  114523. int addrSetAbort; /* Set the abort flag and return */
  114524. int addrTopOfLoop; /* Top of the input loop */
  114525. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  114526. int addrReset; /* Subroutine for resetting the accumulator */
  114527. int regReset; /* Return address register for reset subroutine */
  114528. /* If there is a GROUP BY clause we might need a sorting index to
  114529. ** implement it. Allocate that sorting index now. If it turns out
  114530. ** that we do not need it after all, the OP_SorterOpen instruction
  114531. ** will be converted into a Noop.
  114532. */
  114533. sAggInfo.sortingIdx = pParse->nTab++;
  114534. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
  114535. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  114536. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  114537. 0, (char*)pKeyInfo, P4_KEYINFO);
  114538. /* Initialize memory locations used by GROUP BY aggregate processing
  114539. */
  114540. iUseFlag = ++pParse->nMem;
  114541. iAbortFlag = ++pParse->nMem;
  114542. regOutputRow = ++pParse->nMem;
  114543. addrOutputRow = sqlite3VdbeMakeLabel(v);
  114544. regReset = ++pParse->nMem;
  114545. addrReset = sqlite3VdbeMakeLabel(v);
  114546. iAMem = pParse->nMem + 1;
  114547. pParse->nMem += pGroupBy->nExpr;
  114548. iBMem = pParse->nMem + 1;
  114549. pParse->nMem += pGroupBy->nExpr;
  114550. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  114551. VdbeComment((v, "clear abort flag"));
  114552. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  114553. VdbeComment((v, "indicate accumulator empty"));
  114554. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  114555. /* Begin a loop that will extract all source rows in GROUP BY order.
  114556. ** This might involve two separate loops with an OP_Sort in between, or
  114557. ** it might be a single loop that uses an index to extract information
  114558. ** in the right order to begin with.
  114559. */
  114560. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  114561. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  114562. WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
  114563. );
  114564. if( pWInfo==0 ) goto select_end;
  114565. if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
  114566. /* The optimizer is able to deliver rows in group by order so
  114567. ** we do not have to sort. The OP_OpenEphemeral table will be
  114568. ** cancelled later because we still need to use the pKeyInfo
  114569. */
  114570. groupBySort = 0;
  114571. }else{
  114572. /* Rows are coming out in undetermined order. We have to push
  114573. ** each row into a sorting index, terminate the first loop,
  114574. ** then loop over the sorting index in order to get the output
  114575. ** in sorted order
  114576. */
  114577. int regBase;
  114578. int regRecord;
  114579. int nCol;
  114580. int nGroupBy;
  114581. explainTempTable(pParse,
  114582. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  114583. "DISTINCT" : "GROUP BY");
  114584. groupBySort = 1;
  114585. nGroupBy = pGroupBy->nExpr;
  114586. nCol = nGroupBy;
  114587. j = nGroupBy;
  114588. for(i=0; i<sAggInfo.nColumn; i++){
  114589. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  114590. nCol++;
  114591. j++;
  114592. }
  114593. }
  114594. regBase = sqlite3GetTempRange(pParse, nCol);
  114595. sqlite3ExprCacheClear(pParse);
  114596. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
  114597. j = nGroupBy;
  114598. for(i=0; i<sAggInfo.nColumn; i++){
  114599. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  114600. if( pCol->iSorterColumn>=j ){
  114601. int r1 = j + regBase;
  114602. sqlite3ExprCodeGetColumnToReg(pParse,
  114603. pCol->pTab, pCol->iColumn, pCol->iTable, r1);
  114604. j++;
  114605. }
  114606. }
  114607. regRecord = sqlite3GetTempReg(pParse);
  114608. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  114609. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  114610. sqlite3ReleaseTempReg(pParse, regRecord);
  114611. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  114612. sqlite3WhereEnd(pWInfo);
  114613. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  114614. sortOut = sqlite3GetTempReg(pParse);
  114615. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  114616. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  114617. VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
  114618. sAggInfo.useSortingIdx = 1;
  114619. sqlite3ExprCacheClear(pParse);
  114620. }
  114621. /* If the index or temporary table used by the GROUP BY sort
  114622. ** will naturally deliver rows in the order required by the ORDER BY
  114623. ** clause, cancel the ephemeral table open coded earlier.
  114624. **
  114625. ** This is an optimization - the correct answer should result regardless.
  114626. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
  114627. ** disable this optimization for testing purposes. */
  114628. if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
  114629. && (groupBySort || sqlite3WhereIsSorted(pWInfo))
  114630. ){
  114631. sSort.pOrderBy = 0;
  114632. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  114633. }
  114634. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  114635. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  114636. ** Then compare the current GROUP BY terms against the GROUP BY terms
  114637. ** from the previous row currently stored in a0, a1, a2...
  114638. */
  114639. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  114640. sqlite3ExprCacheClear(pParse);
  114641. if( groupBySort ){
  114642. sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
  114643. sortOut, sortPTab);
  114644. }
  114645. for(j=0; j<pGroupBy->nExpr; j++){
  114646. if( groupBySort ){
  114647. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  114648. }else{
  114649. sAggInfo.directMode = 1;
  114650. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  114651. }
  114652. }
  114653. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  114654. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  114655. addr1 = sqlite3VdbeCurrentAddr(v);
  114656. sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
  114657. /* Generate code that runs whenever the GROUP BY changes.
  114658. ** Changes in the GROUP BY are detected by the previous code
  114659. ** block. If there were no changes, this block is skipped.
  114660. **
  114661. ** This code copies current group by terms in b0,b1,b2,...
  114662. ** over to a0,a1,a2. It then calls the output subroutine
  114663. ** and resets the aggregate accumulator registers in preparation
  114664. ** for the next GROUP BY batch.
  114665. */
  114666. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  114667. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  114668. VdbeComment((v, "output one row"));
  114669. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
  114670. VdbeComment((v, "check abort flag"));
  114671. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  114672. VdbeComment((v, "reset accumulator"));
  114673. /* Update the aggregate accumulators based on the content of
  114674. ** the current row
  114675. */
  114676. sqlite3VdbeJumpHere(v, addr1);
  114677. updateAccumulator(pParse, &sAggInfo);
  114678. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  114679. VdbeComment((v, "indicate data in accumulator"));
  114680. /* End of the loop
  114681. */
  114682. if( groupBySort ){
  114683. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  114684. VdbeCoverage(v);
  114685. }else{
  114686. sqlite3WhereEnd(pWInfo);
  114687. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  114688. }
  114689. /* Output the final row of result
  114690. */
  114691. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  114692. VdbeComment((v, "output final row"));
  114693. /* Jump over the subroutines
  114694. */
  114695. sqlite3VdbeGoto(v, addrEnd);
  114696. /* Generate a subroutine that outputs a single row of the result
  114697. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  114698. ** is less than or equal to zero, the subroutine is a no-op. If
  114699. ** the processing calls for the query to abort, this subroutine
  114700. ** increments the iAbortFlag memory location before returning in
  114701. ** order to signal the caller to abort.
  114702. */
  114703. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  114704. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  114705. VdbeComment((v, "set abort flag"));
  114706. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  114707. sqlite3VdbeResolveLabel(v, addrOutputRow);
  114708. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  114709. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  114710. VdbeCoverage(v);
  114711. VdbeComment((v, "Groupby result generator entry point"));
  114712. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  114713. finalizeAggFunctions(pParse, &sAggInfo);
  114714. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  114715. selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
  114716. &sDistinct, pDest,
  114717. addrOutputRow+1, addrSetAbort);
  114718. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  114719. VdbeComment((v, "end groupby result generator"));
  114720. /* Generate a subroutine that will reset the group-by accumulator
  114721. */
  114722. sqlite3VdbeResolveLabel(v, addrReset);
  114723. resetAccumulator(pParse, &sAggInfo);
  114724. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  114725. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  114726. else {
  114727. ExprList *pDel = 0;
  114728. #ifndef SQLITE_OMIT_BTREECOUNT
  114729. Table *pTab;
  114730. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  114731. /* If isSimpleCount() returns a pointer to a Table structure, then
  114732. ** the SQL statement is of the form:
  114733. **
  114734. ** SELECT count(*) FROM <tbl>
  114735. **
  114736. ** where the Table structure returned represents table <tbl>.
  114737. **
  114738. ** This statement is so common that it is optimized specially. The
  114739. ** OP_Count instruction is executed either on the intkey table that
  114740. ** contains the data for table <tbl> or on one of its indexes. It
  114741. ** is better to execute the op on an index, as indexes are almost
  114742. ** always spread across less pages than their corresponding tables.
  114743. */
  114744. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  114745. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  114746. Index *pIdx; /* Iterator variable */
  114747. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  114748. Index *pBest = 0; /* Best index found so far */
  114749. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  114750. sqlite3CodeVerifySchema(pParse, iDb);
  114751. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  114752. /* Search for the index that has the lowest scan cost.
  114753. **
  114754. ** (2011-04-15) Do not do a full scan of an unordered index.
  114755. **
  114756. ** (2013-10-03) Do not count the entries in a partial index.
  114757. **
  114758. ** In practice the KeyInfo structure will not be used. It is only
  114759. ** passed to keep OP_OpenRead happy.
  114760. */
  114761. if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
  114762. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  114763. if( pIdx->bUnordered==0
  114764. && pIdx->szIdxRow<pTab->szTabRow
  114765. && pIdx->pPartIdxWhere==0
  114766. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  114767. ){
  114768. pBest = pIdx;
  114769. }
  114770. }
  114771. if( pBest ){
  114772. iRoot = pBest->tnum;
  114773. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
  114774. }
  114775. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  114776. sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
  114777. if( pKeyInfo ){
  114778. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
  114779. }
  114780. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  114781. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  114782. explainSimpleCount(pParse, pTab, pBest);
  114783. }else
  114784. #endif /* SQLITE_OMIT_BTREECOUNT */
  114785. {
  114786. /* Check if the query is of one of the following forms:
  114787. **
  114788. ** SELECT min(x) FROM ...
  114789. ** SELECT max(x) FROM ...
  114790. **
  114791. ** If it is, then ask the code in where.c to attempt to sort results
  114792. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  114793. ** If where.c is able to produce results sorted in this order, then
  114794. ** add vdbe code to break out of the processing loop after the
  114795. ** first iteration (since the first iteration of the loop is
  114796. ** guaranteed to operate on the row with the minimum or maximum
  114797. ** value of x, the only row required).
  114798. **
  114799. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  114800. ** modify behavior as follows:
  114801. **
  114802. ** + If the query is a "SELECT min(x)", then the loop coded by
  114803. ** where.c should not iterate over any values with a NULL value
  114804. ** for x.
  114805. **
  114806. ** + The optimizer code in where.c (the thing that decides which
  114807. ** index or indices to use) should place a different priority on
  114808. ** satisfying the 'ORDER BY' clause than it does in other cases.
  114809. ** Refer to code and comments in where.c for details.
  114810. */
  114811. ExprList *pMinMax = 0;
  114812. u8 flag = WHERE_ORDERBY_NORMAL;
  114813. assert( p->pGroupBy==0 );
  114814. assert( flag==0 );
  114815. if( p->pHaving==0 ){
  114816. flag = minMaxQuery(&sAggInfo, &pMinMax);
  114817. }
  114818. assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
  114819. if( flag ){
  114820. pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
  114821. pDel = pMinMax;
  114822. assert( db->mallocFailed || pMinMax!=0 );
  114823. if( !db->mallocFailed ){
  114824. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  114825. pMinMax->a[0].pExpr->op = TK_COLUMN;
  114826. }
  114827. }
  114828. /* This case runs if the aggregate has no GROUP BY clause. The
  114829. ** processing is much simpler since there is only a single row
  114830. ** of output.
  114831. */
  114832. resetAccumulator(pParse, &sAggInfo);
  114833. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax, 0,flag,0);
  114834. if( pWInfo==0 ){
  114835. sqlite3ExprListDelete(db, pDel);
  114836. goto select_end;
  114837. }
  114838. updateAccumulator(pParse, &sAggInfo);
  114839. assert( pMinMax==0 || pMinMax->nExpr==1 );
  114840. if( sqlite3WhereIsOrdered(pWInfo)>0 ){
  114841. sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
  114842. VdbeComment((v, "%s() by index",
  114843. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  114844. }
  114845. sqlite3WhereEnd(pWInfo);
  114846. finalizeAggFunctions(pParse, &sAggInfo);
  114847. }
  114848. sSort.pOrderBy = 0;
  114849. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  114850. selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
  114851. pDest, addrEnd, addrEnd);
  114852. sqlite3ExprListDelete(db, pDel);
  114853. }
  114854. sqlite3VdbeResolveLabel(v, addrEnd);
  114855. } /* endif aggregate query */
  114856. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  114857. explainTempTable(pParse, "DISTINCT");
  114858. }
  114859. /* If there is an ORDER BY clause, then we need to sort the results
  114860. ** and send them to the callback one by one.
  114861. */
  114862. if( sSort.pOrderBy ){
  114863. explainTempTable(pParse,
  114864. sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
  114865. generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
  114866. }
  114867. /* Jump here to skip this query
  114868. */
  114869. sqlite3VdbeResolveLabel(v, iEnd);
  114870. /* The SELECT has been coded. If there is an error in the Parse structure,
  114871. ** set the return code to 1. Otherwise 0. */
  114872. rc = (pParse->nErr>0);
  114873. /* Control jumps to here if an error is encountered above, or upon
  114874. ** successful coding of the SELECT.
  114875. */
  114876. select_end:
  114877. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  114878. /* Identify column names if results of the SELECT are to be output.
  114879. */
  114880. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  114881. generateColumnNames(pParse, pTabList, pEList);
  114882. }
  114883. sqlite3DbFree(db, sAggInfo.aCol);
  114884. sqlite3DbFree(db, sAggInfo.aFunc);
  114885. #if SELECTTRACE_ENABLED
  114886. SELECTTRACE(1,pParse,p,("end processing\n"));
  114887. pParse->nSelectIndent--;
  114888. #endif
  114889. return rc;
  114890. }
  114891. /************** End of select.c **********************************************/
  114892. /************** Begin file table.c *******************************************/
  114893. /*
  114894. ** 2001 September 15
  114895. **
  114896. ** The author disclaims copyright to this source code. In place of
  114897. ** a legal notice, here is a blessing:
  114898. **
  114899. ** May you do good and not evil.
  114900. ** May you find forgiveness for yourself and forgive others.
  114901. ** May you share freely, never taking more than you give.
  114902. **
  114903. *************************************************************************
  114904. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  114905. ** interface routines. These are just wrappers around the main
  114906. ** interface routine of sqlite3_exec().
  114907. **
  114908. ** These routines are in a separate files so that they will not be linked
  114909. ** if they are not used.
  114910. */
  114911. /* #include "sqliteInt.h" */
  114912. #ifndef SQLITE_OMIT_GET_TABLE
  114913. /*
  114914. ** This structure is used to pass data from sqlite3_get_table() through
  114915. ** to the callback function is uses to build the result.
  114916. */
  114917. typedef struct TabResult {
  114918. char **azResult; /* Accumulated output */
  114919. char *zErrMsg; /* Error message text, if an error occurs */
  114920. u32 nAlloc; /* Slots allocated for azResult[] */
  114921. u32 nRow; /* Number of rows in the result */
  114922. u32 nColumn; /* Number of columns in the result */
  114923. u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  114924. int rc; /* Return code from sqlite3_exec() */
  114925. } TabResult;
  114926. /*
  114927. ** This routine is called once for each row in the result table. Its job
  114928. ** is to fill in the TabResult structure appropriately, allocating new
  114929. ** memory as necessary.
  114930. */
  114931. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  114932. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  114933. int need; /* Slots needed in p->azResult[] */
  114934. int i; /* Loop counter */
  114935. char *z; /* A single column of result */
  114936. /* Make sure there is enough space in p->azResult to hold everything
  114937. ** we need to remember from this invocation of the callback.
  114938. */
  114939. if( p->nRow==0 && argv!=0 ){
  114940. need = nCol*2;
  114941. }else{
  114942. need = nCol;
  114943. }
  114944. if( p->nData + need > p->nAlloc ){
  114945. char **azNew;
  114946. p->nAlloc = p->nAlloc*2 + need;
  114947. azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
  114948. if( azNew==0 ) goto malloc_failed;
  114949. p->azResult = azNew;
  114950. }
  114951. /* If this is the first row, then generate an extra row containing
  114952. ** the names of all columns.
  114953. */
  114954. if( p->nRow==0 ){
  114955. p->nColumn = nCol;
  114956. for(i=0; i<nCol; i++){
  114957. z = sqlite3_mprintf("%s", colv[i]);
  114958. if( z==0 ) goto malloc_failed;
  114959. p->azResult[p->nData++] = z;
  114960. }
  114961. }else if( (int)p->nColumn!=nCol ){
  114962. sqlite3_free(p->zErrMsg);
  114963. p->zErrMsg = sqlite3_mprintf(
  114964. "sqlite3_get_table() called with two or more incompatible queries"
  114965. );
  114966. p->rc = SQLITE_ERROR;
  114967. return 1;
  114968. }
  114969. /* Copy over the row data
  114970. */
  114971. if( argv!=0 ){
  114972. for(i=0; i<nCol; i++){
  114973. if( argv[i]==0 ){
  114974. z = 0;
  114975. }else{
  114976. int n = sqlite3Strlen30(argv[i])+1;
  114977. z = sqlite3_malloc64( n );
  114978. if( z==0 ) goto malloc_failed;
  114979. memcpy(z, argv[i], n);
  114980. }
  114981. p->azResult[p->nData++] = z;
  114982. }
  114983. p->nRow++;
  114984. }
  114985. return 0;
  114986. malloc_failed:
  114987. p->rc = SQLITE_NOMEM_BKPT;
  114988. return 1;
  114989. }
  114990. /*
  114991. ** Query the database. But instead of invoking a callback for each row,
  114992. ** malloc() for space to hold the result and return the entire results
  114993. ** at the conclusion of the call.
  114994. **
  114995. ** The result that is written to ***pazResult is held in memory obtained
  114996. ** from malloc(). But the caller cannot free this memory directly.
  114997. ** Instead, the entire table should be passed to sqlite3_free_table() when
  114998. ** the calling procedure is finished using it.
  114999. */
  115000. SQLITE_API int sqlite3_get_table(
  115001. sqlite3 *db, /* The database on which the SQL executes */
  115002. const char *zSql, /* The SQL to be executed */
  115003. char ***pazResult, /* Write the result table here */
  115004. int *pnRow, /* Write the number of rows in the result here */
  115005. int *pnColumn, /* Write the number of columns of result here */
  115006. char **pzErrMsg /* Write error messages here */
  115007. ){
  115008. int rc;
  115009. TabResult res;
  115010. #ifdef SQLITE_ENABLE_API_ARMOR
  115011. if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
  115012. #endif
  115013. *pazResult = 0;
  115014. if( pnColumn ) *pnColumn = 0;
  115015. if( pnRow ) *pnRow = 0;
  115016. if( pzErrMsg ) *pzErrMsg = 0;
  115017. res.zErrMsg = 0;
  115018. res.nRow = 0;
  115019. res.nColumn = 0;
  115020. res.nData = 1;
  115021. res.nAlloc = 20;
  115022. res.rc = SQLITE_OK;
  115023. res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
  115024. if( res.azResult==0 ){
  115025. db->errCode = SQLITE_NOMEM;
  115026. return SQLITE_NOMEM_BKPT;
  115027. }
  115028. res.azResult[0] = 0;
  115029. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  115030. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  115031. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  115032. if( (rc&0xff)==SQLITE_ABORT ){
  115033. sqlite3_free_table(&res.azResult[1]);
  115034. if( res.zErrMsg ){
  115035. if( pzErrMsg ){
  115036. sqlite3_free(*pzErrMsg);
  115037. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  115038. }
  115039. sqlite3_free(res.zErrMsg);
  115040. }
  115041. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  115042. return res.rc;
  115043. }
  115044. sqlite3_free(res.zErrMsg);
  115045. if( rc!=SQLITE_OK ){
  115046. sqlite3_free_table(&res.azResult[1]);
  115047. return rc;
  115048. }
  115049. if( res.nAlloc>res.nData ){
  115050. char **azNew;
  115051. azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
  115052. if( azNew==0 ){
  115053. sqlite3_free_table(&res.azResult[1]);
  115054. db->errCode = SQLITE_NOMEM;
  115055. return SQLITE_NOMEM_BKPT;
  115056. }
  115057. res.azResult = azNew;
  115058. }
  115059. *pazResult = &res.azResult[1];
  115060. if( pnColumn ) *pnColumn = res.nColumn;
  115061. if( pnRow ) *pnRow = res.nRow;
  115062. return rc;
  115063. }
  115064. /*
  115065. ** This routine frees the space the sqlite3_get_table() malloced.
  115066. */
  115067. SQLITE_API void sqlite3_free_table(
  115068. char **azResult /* Result returned from sqlite3_get_table() */
  115069. ){
  115070. if( azResult ){
  115071. int i, n;
  115072. azResult--;
  115073. assert( azResult!=0 );
  115074. n = SQLITE_PTR_TO_INT(azResult[0]);
  115075. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  115076. sqlite3_free(azResult);
  115077. }
  115078. }
  115079. #endif /* SQLITE_OMIT_GET_TABLE */
  115080. /************** End of table.c ***********************************************/
  115081. /************** Begin file trigger.c *****************************************/
  115082. /*
  115083. **
  115084. ** The author disclaims copyright to this source code. In place of
  115085. ** a legal notice, here is a blessing:
  115086. **
  115087. ** May you do good and not evil.
  115088. ** May you find forgiveness for yourself and forgive others.
  115089. ** May you share freely, never taking more than you give.
  115090. **
  115091. *************************************************************************
  115092. ** This file contains the implementation for TRIGGERs
  115093. */
  115094. /* #include "sqliteInt.h" */
  115095. #ifndef SQLITE_OMIT_TRIGGER
  115096. /*
  115097. ** Delete a linked list of TriggerStep structures.
  115098. */
  115099. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  115100. while( pTriggerStep ){
  115101. TriggerStep * pTmp = pTriggerStep;
  115102. pTriggerStep = pTriggerStep->pNext;
  115103. sqlite3ExprDelete(db, pTmp->pWhere);
  115104. sqlite3ExprListDelete(db, pTmp->pExprList);
  115105. sqlite3SelectDelete(db, pTmp->pSelect);
  115106. sqlite3IdListDelete(db, pTmp->pIdList);
  115107. sqlite3DbFree(db, pTmp);
  115108. }
  115109. }
  115110. /*
  115111. ** Given table pTab, return a list of all the triggers attached to
  115112. ** the table. The list is connected by Trigger.pNext pointers.
  115113. **
  115114. ** All of the triggers on pTab that are in the same database as pTab
  115115. ** are already attached to pTab->pTrigger. But there might be additional
  115116. ** triggers on pTab in the TEMP schema. This routine prepends all
  115117. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  115118. ** and returns the combined list.
  115119. **
  115120. ** To state it another way: This routine returns a list of all triggers
  115121. ** that fire off of pTab. The list will include any TEMP triggers on
  115122. ** pTab as well as the triggers lised in pTab->pTrigger.
  115123. */
  115124. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  115125. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  115126. Trigger *pList = 0; /* List of triggers to return */
  115127. if( pParse->disableTriggers ){
  115128. return 0;
  115129. }
  115130. if( pTmpSchema!=pTab->pSchema ){
  115131. HashElem *p;
  115132. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  115133. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  115134. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  115135. if( pTrig->pTabSchema==pTab->pSchema
  115136. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  115137. ){
  115138. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  115139. pList = pTrig;
  115140. }
  115141. }
  115142. }
  115143. return (pList ? pList : pTab->pTrigger);
  115144. }
  115145. /*
  115146. ** This is called by the parser when it sees a CREATE TRIGGER statement
  115147. ** up to the point of the BEGIN before the trigger actions. A Trigger
  115148. ** structure is generated based on the information available and stored
  115149. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  115150. ** sqlite3FinishTrigger() function is called to complete the trigger
  115151. ** construction process.
  115152. */
  115153. SQLITE_PRIVATE void sqlite3BeginTrigger(
  115154. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  115155. Token *pName1, /* The name of the trigger */
  115156. Token *pName2, /* The name of the trigger */
  115157. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  115158. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  115159. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  115160. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  115161. Expr *pWhen, /* WHEN clause */
  115162. int isTemp, /* True if the TEMPORARY keyword is present */
  115163. int noErr /* Suppress errors if the trigger already exists */
  115164. ){
  115165. Trigger *pTrigger = 0; /* The new trigger */
  115166. Table *pTab; /* Table that the trigger fires off of */
  115167. char *zName = 0; /* Name of the trigger */
  115168. sqlite3 *db = pParse->db; /* The database connection */
  115169. int iDb; /* The database to store the trigger in */
  115170. Token *pName; /* The unqualified db name */
  115171. DbFixer sFix; /* State vector for the DB fixer */
  115172. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  115173. assert( pName2!=0 );
  115174. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  115175. assert( op>0 && op<0xff );
  115176. if( isTemp ){
  115177. /* If TEMP was specified, then the trigger name may not be qualified. */
  115178. if( pName2->n>0 ){
  115179. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  115180. goto trigger_cleanup;
  115181. }
  115182. iDb = 1;
  115183. pName = pName1;
  115184. }else{
  115185. /* Figure out the db that the trigger will be created in */
  115186. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  115187. if( iDb<0 ){
  115188. goto trigger_cleanup;
  115189. }
  115190. }
  115191. if( !pTableName || db->mallocFailed ){
  115192. goto trigger_cleanup;
  115193. }
  115194. /* A long-standing parser bug is that this syntax was allowed:
  115195. **
  115196. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  115197. ** ^^^^^^^^
  115198. **
  115199. ** To maintain backwards compatibility, ignore the database
  115200. ** name on pTableName if we are reparsing out of SQLITE_MASTER.
  115201. */
  115202. if( db->init.busy && iDb!=1 ){
  115203. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  115204. pTableName->a[0].zDatabase = 0;
  115205. }
  115206. /* If the trigger name was unqualified, and the table is a temp table,
  115207. ** then set iDb to 1 to create the trigger in the temporary database.
  115208. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  115209. ** exist, the error is caught by the block below.
  115210. */
  115211. pTab = sqlite3SrcListLookup(pParse, pTableName);
  115212. if( db->init.busy==0 && pName2->n==0 && pTab
  115213. && pTab->pSchema==db->aDb[1].pSchema ){
  115214. iDb = 1;
  115215. }
  115216. /* Ensure the table name matches database name and that the table exists */
  115217. if( db->mallocFailed ) goto trigger_cleanup;
  115218. assert( pTableName->nSrc==1 );
  115219. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  115220. if( sqlite3FixSrcList(&sFix, pTableName) ){
  115221. goto trigger_cleanup;
  115222. }
  115223. pTab = sqlite3SrcListLookup(pParse, pTableName);
  115224. if( !pTab ){
  115225. /* The table does not exist. */
  115226. if( db->init.iDb==1 ){
  115227. /* Ticket #3810.
  115228. ** Normally, whenever a table is dropped, all associated triggers are
  115229. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  115230. ** and the table is dropped by a different database connection, the
  115231. ** trigger is not visible to the database connection that does the
  115232. ** drop so the trigger cannot be dropped. This results in an
  115233. ** "orphaned trigger" - a trigger whose associated table is missing.
  115234. */
  115235. db->init.orphanTrigger = 1;
  115236. }
  115237. goto trigger_cleanup;
  115238. }
  115239. if( IsVirtual(pTab) ){
  115240. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  115241. goto trigger_cleanup;
  115242. }
  115243. /* Check that the trigger name is not reserved and that no trigger of the
  115244. ** specified name exists */
  115245. zName = sqlite3NameFromToken(db, pName);
  115246. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  115247. goto trigger_cleanup;
  115248. }
  115249. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  115250. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
  115251. if( !noErr ){
  115252. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  115253. }else{
  115254. assert( !db->init.busy );
  115255. sqlite3CodeVerifySchema(pParse, iDb);
  115256. }
  115257. goto trigger_cleanup;
  115258. }
  115259. /* Do not create a trigger on a system table */
  115260. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  115261. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  115262. goto trigger_cleanup;
  115263. }
  115264. /* INSTEAD of triggers are only for views and views only support INSTEAD
  115265. ** of triggers.
  115266. */
  115267. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  115268. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  115269. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  115270. goto trigger_cleanup;
  115271. }
  115272. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  115273. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  115274. " trigger on table: %S", pTableName, 0);
  115275. goto trigger_cleanup;
  115276. }
  115277. #ifndef SQLITE_OMIT_AUTHORIZATION
  115278. {
  115279. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  115280. int code = SQLITE_CREATE_TRIGGER;
  115281. const char *zDb = db->aDb[iTabDb].zDbSName;
  115282. const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
  115283. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  115284. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  115285. goto trigger_cleanup;
  115286. }
  115287. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  115288. goto trigger_cleanup;
  115289. }
  115290. }
  115291. #endif
  115292. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  115293. ** cannot appear on views. So we might as well translate every
  115294. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  115295. ** elsewhere.
  115296. */
  115297. if (tr_tm == TK_INSTEAD){
  115298. tr_tm = TK_BEFORE;
  115299. }
  115300. /* Build the Trigger object */
  115301. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  115302. if( pTrigger==0 ) goto trigger_cleanup;
  115303. pTrigger->zName = zName;
  115304. zName = 0;
  115305. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  115306. pTrigger->pSchema = db->aDb[iDb].pSchema;
  115307. pTrigger->pTabSchema = pTab->pSchema;
  115308. pTrigger->op = (u8)op;
  115309. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  115310. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  115311. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  115312. assert( pParse->pNewTrigger==0 );
  115313. pParse->pNewTrigger = pTrigger;
  115314. trigger_cleanup:
  115315. sqlite3DbFree(db, zName);
  115316. sqlite3SrcListDelete(db, pTableName);
  115317. sqlite3IdListDelete(db, pColumns);
  115318. sqlite3ExprDelete(db, pWhen);
  115319. if( !pParse->pNewTrigger ){
  115320. sqlite3DeleteTrigger(db, pTrigger);
  115321. }else{
  115322. assert( pParse->pNewTrigger==pTrigger );
  115323. }
  115324. }
  115325. /*
  115326. ** This routine is called after all of the trigger actions have been parsed
  115327. ** in order to complete the process of building the trigger.
  115328. */
  115329. SQLITE_PRIVATE void sqlite3FinishTrigger(
  115330. Parse *pParse, /* Parser context */
  115331. TriggerStep *pStepList, /* The triggered program */
  115332. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  115333. ){
  115334. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  115335. char *zName; /* Name of trigger */
  115336. sqlite3 *db = pParse->db; /* The database */
  115337. DbFixer sFix; /* Fixer object */
  115338. int iDb; /* Database containing the trigger */
  115339. Token nameToken; /* Trigger name for error reporting */
  115340. pParse->pNewTrigger = 0;
  115341. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  115342. zName = pTrig->zName;
  115343. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  115344. pTrig->step_list = pStepList;
  115345. while( pStepList ){
  115346. pStepList->pTrig = pTrig;
  115347. pStepList = pStepList->pNext;
  115348. }
  115349. sqlite3TokenInit(&nameToken, pTrig->zName);
  115350. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  115351. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  115352. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  115353. ){
  115354. goto triggerfinish_cleanup;
  115355. }
  115356. /* if we are not initializing,
  115357. ** build the sqlite_master entry
  115358. */
  115359. if( !db->init.busy ){
  115360. Vdbe *v;
  115361. char *z;
  115362. /* Make an entry in the sqlite_master table */
  115363. v = sqlite3GetVdbe(pParse);
  115364. if( v==0 ) goto triggerfinish_cleanup;
  115365. sqlite3BeginWriteOperation(pParse, 0, iDb);
  115366. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  115367. sqlite3NestedParse(pParse,
  115368. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  115369. db->aDb[iDb].zDbSName, MASTER_NAME, zName,
  115370. pTrig->table, z);
  115371. sqlite3DbFree(db, z);
  115372. sqlite3ChangeCookie(pParse, iDb);
  115373. sqlite3VdbeAddParseSchemaOp(v, iDb,
  115374. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  115375. }
  115376. if( db->init.busy ){
  115377. Trigger *pLink = pTrig;
  115378. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  115379. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  115380. pTrig = sqlite3HashInsert(pHash, zName, pTrig);
  115381. if( pTrig ){
  115382. sqlite3OomFault(db);
  115383. }else if( pLink->pSchema==pLink->pTabSchema ){
  115384. Table *pTab;
  115385. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
  115386. assert( pTab!=0 );
  115387. pLink->pNext = pTab->pTrigger;
  115388. pTab->pTrigger = pLink;
  115389. }
  115390. }
  115391. triggerfinish_cleanup:
  115392. sqlite3DeleteTrigger(db, pTrig);
  115393. assert( !pParse->pNewTrigger );
  115394. sqlite3DeleteTriggerStep(db, pStepList);
  115395. }
  115396. /*
  115397. ** Turn a SELECT statement (that the pSelect parameter points to) into
  115398. ** a trigger step. Return a pointer to a TriggerStep structure.
  115399. **
  115400. ** The parser calls this routine when it finds a SELECT statement in
  115401. ** body of a TRIGGER.
  115402. */
  115403. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  115404. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  115405. if( pTriggerStep==0 ) {
  115406. sqlite3SelectDelete(db, pSelect);
  115407. return 0;
  115408. }
  115409. pTriggerStep->op = TK_SELECT;
  115410. pTriggerStep->pSelect = pSelect;
  115411. pTriggerStep->orconf = OE_Default;
  115412. return pTriggerStep;
  115413. }
  115414. /*
  115415. ** Allocate space to hold a new trigger step. The allocated space
  115416. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  115417. **
  115418. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  115419. */
  115420. static TriggerStep *triggerStepAllocate(
  115421. sqlite3 *db, /* Database connection */
  115422. u8 op, /* Trigger opcode */
  115423. Token *pName /* The target name */
  115424. ){
  115425. TriggerStep *pTriggerStep;
  115426. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
  115427. if( pTriggerStep ){
  115428. char *z = (char*)&pTriggerStep[1];
  115429. memcpy(z, pName->z, pName->n);
  115430. sqlite3Dequote(z);
  115431. pTriggerStep->zTarget = z;
  115432. pTriggerStep->op = op;
  115433. }
  115434. return pTriggerStep;
  115435. }
  115436. /*
  115437. ** Build a trigger step out of an INSERT statement. Return a pointer
  115438. ** to the new trigger step.
  115439. **
  115440. ** The parser calls this routine when it sees an INSERT inside the
  115441. ** body of a trigger.
  115442. */
  115443. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  115444. sqlite3 *db, /* The database connection */
  115445. Token *pTableName, /* Name of the table into which we insert */
  115446. IdList *pColumn, /* List of columns in pTableName to insert into */
  115447. Select *pSelect, /* A SELECT statement that supplies values */
  115448. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  115449. ){
  115450. TriggerStep *pTriggerStep;
  115451. assert(pSelect != 0 || db->mallocFailed);
  115452. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  115453. if( pTriggerStep ){
  115454. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  115455. pTriggerStep->pIdList = pColumn;
  115456. pTriggerStep->orconf = orconf;
  115457. }else{
  115458. sqlite3IdListDelete(db, pColumn);
  115459. }
  115460. sqlite3SelectDelete(db, pSelect);
  115461. return pTriggerStep;
  115462. }
  115463. /*
  115464. ** Construct a trigger step that implements an UPDATE statement and return
  115465. ** a pointer to that trigger step. The parser calls this routine when it
  115466. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  115467. */
  115468. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  115469. sqlite3 *db, /* The database connection */
  115470. Token *pTableName, /* Name of the table to be updated */
  115471. ExprList *pEList, /* The SET clause: list of column and new values */
  115472. Expr *pWhere, /* The WHERE clause */
  115473. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  115474. ){
  115475. TriggerStep *pTriggerStep;
  115476. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  115477. if( pTriggerStep ){
  115478. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  115479. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  115480. pTriggerStep->orconf = orconf;
  115481. }
  115482. sqlite3ExprListDelete(db, pEList);
  115483. sqlite3ExprDelete(db, pWhere);
  115484. return pTriggerStep;
  115485. }
  115486. /*
  115487. ** Construct a trigger step that implements a DELETE statement and return
  115488. ** a pointer to that trigger step. The parser calls this routine when it
  115489. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  115490. */
  115491. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  115492. sqlite3 *db, /* Database connection */
  115493. Token *pTableName, /* The table from which rows are deleted */
  115494. Expr *pWhere /* The WHERE clause */
  115495. ){
  115496. TriggerStep *pTriggerStep;
  115497. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  115498. if( pTriggerStep ){
  115499. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  115500. pTriggerStep->orconf = OE_Default;
  115501. }
  115502. sqlite3ExprDelete(db, pWhere);
  115503. return pTriggerStep;
  115504. }
  115505. /*
  115506. ** Recursively delete a Trigger structure
  115507. */
  115508. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  115509. if( pTrigger==0 ) return;
  115510. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  115511. sqlite3DbFree(db, pTrigger->zName);
  115512. sqlite3DbFree(db, pTrigger->table);
  115513. sqlite3ExprDelete(db, pTrigger->pWhen);
  115514. sqlite3IdListDelete(db, pTrigger->pColumns);
  115515. sqlite3DbFree(db, pTrigger);
  115516. }
  115517. /*
  115518. ** This function is called to drop a trigger from the database schema.
  115519. **
  115520. ** This may be called directly from the parser and therefore identifies
  115521. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  115522. ** same job as this routine except it takes a pointer to the trigger
  115523. ** instead of the trigger name.
  115524. **/
  115525. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  115526. Trigger *pTrigger = 0;
  115527. int i;
  115528. const char *zDb;
  115529. const char *zName;
  115530. sqlite3 *db = pParse->db;
  115531. if( db->mallocFailed ) goto drop_trigger_cleanup;
  115532. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  115533. goto drop_trigger_cleanup;
  115534. }
  115535. assert( pName->nSrc==1 );
  115536. zDb = pName->a[0].zDatabase;
  115537. zName = pName->a[0].zName;
  115538. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  115539. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  115540. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  115541. if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue;
  115542. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  115543. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
  115544. if( pTrigger ) break;
  115545. }
  115546. if( !pTrigger ){
  115547. if( !noErr ){
  115548. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  115549. }else{
  115550. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  115551. }
  115552. pParse->checkSchema = 1;
  115553. goto drop_trigger_cleanup;
  115554. }
  115555. sqlite3DropTriggerPtr(pParse, pTrigger);
  115556. drop_trigger_cleanup:
  115557. sqlite3SrcListDelete(db, pName);
  115558. }
  115559. /*
  115560. ** Return a pointer to the Table structure for the table that a trigger
  115561. ** is set on.
  115562. */
  115563. static Table *tableOfTrigger(Trigger *pTrigger){
  115564. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
  115565. }
  115566. /*
  115567. ** Drop a trigger given a pointer to that trigger.
  115568. */
  115569. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  115570. Table *pTable;
  115571. Vdbe *v;
  115572. sqlite3 *db = pParse->db;
  115573. int iDb;
  115574. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  115575. assert( iDb>=0 && iDb<db->nDb );
  115576. pTable = tableOfTrigger(pTrigger);
  115577. assert( pTable );
  115578. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  115579. #ifndef SQLITE_OMIT_AUTHORIZATION
  115580. {
  115581. int code = SQLITE_DROP_TRIGGER;
  115582. const char *zDb = db->aDb[iDb].zDbSName;
  115583. const char *zTab = SCHEMA_TABLE(iDb);
  115584. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  115585. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  115586. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  115587. return;
  115588. }
  115589. }
  115590. #endif
  115591. /* Generate code to destroy the database record of the trigger.
  115592. */
  115593. assert( pTable!=0 );
  115594. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  115595. sqlite3NestedParse(pParse,
  115596. "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
  115597. db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName
  115598. );
  115599. sqlite3ChangeCookie(pParse, iDb);
  115600. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  115601. }
  115602. }
  115603. /*
  115604. ** Remove a trigger from the hash tables of the sqlite* pointer.
  115605. */
  115606. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  115607. Trigger *pTrigger;
  115608. Hash *pHash;
  115609. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  115610. pHash = &(db->aDb[iDb].pSchema->trigHash);
  115611. pTrigger = sqlite3HashInsert(pHash, zName, 0);
  115612. if( ALWAYS(pTrigger) ){
  115613. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  115614. Table *pTab = tableOfTrigger(pTrigger);
  115615. Trigger **pp;
  115616. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  115617. *pp = (*pp)->pNext;
  115618. }
  115619. sqlite3DeleteTrigger(db, pTrigger);
  115620. db->flags |= SQLITE_InternChanges;
  115621. }
  115622. }
  115623. /*
  115624. ** pEList is the SET clause of an UPDATE statement. Each entry
  115625. ** in pEList is of the format <id>=<expr>. If any of the entries
  115626. ** in pEList have an <id> which matches an identifier in pIdList,
  115627. ** then return TRUE. If pIdList==NULL, then it is considered a
  115628. ** wildcard that matches anything. Likewise if pEList==NULL then
  115629. ** it matches anything so always return true. Return false only
  115630. ** if there is no match.
  115631. */
  115632. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  115633. int e;
  115634. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  115635. for(e=0; e<pEList->nExpr; e++){
  115636. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  115637. }
  115638. return 0;
  115639. }
  115640. /*
  115641. ** Return a list of all triggers on table pTab if there exists at least
  115642. ** one trigger that must be fired when an operation of type 'op' is
  115643. ** performed on the table, and, if that operation is an UPDATE, if at
  115644. ** least one of the columns in pChanges is being modified.
  115645. */
  115646. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  115647. Parse *pParse, /* Parse context */
  115648. Table *pTab, /* The table the contains the triggers */
  115649. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  115650. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  115651. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  115652. ){
  115653. int mask = 0;
  115654. Trigger *pList = 0;
  115655. Trigger *p;
  115656. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  115657. pList = sqlite3TriggerList(pParse, pTab);
  115658. }
  115659. assert( pList==0 || IsVirtual(pTab)==0 );
  115660. for(p=pList; p; p=p->pNext){
  115661. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  115662. mask |= p->tr_tm;
  115663. }
  115664. }
  115665. if( pMask ){
  115666. *pMask = mask;
  115667. }
  115668. return (mask ? pList : 0);
  115669. }
  115670. /*
  115671. ** Convert the pStep->zTarget string into a SrcList and return a pointer
  115672. ** to that SrcList.
  115673. **
  115674. ** This routine adds a specific database name, if needed, to the target when
  115675. ** forming the SrcList. This prevents a trigger in one database from
  115676. ** referring to a target in another database. An exception is when the
  115677. ** trigger is in TEMP in which case it can refer to any other database it
  115678. ** wants.
  115679. */
  115680. static SrcList *targetSrcList(
  115681. Parse *pParse, /* The parsing context */
  115682. TriggerStep *pStep /* The trigger containing the target token */
  115683. ){
  115684. sqlite3 *db = pParse->db;
  115685. int iDb; /* Index of the database to use */
  115686. SrcList *pSrc; /* SrcList to be returned */
  115687. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  115688. if( pSrc ){
  115689. assert( pSrc->nSrc>0 );
  115690. pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
  115691. iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
  115692. if( iDb==0 || iDb>=2 ){
  115693. const char *zDb;
  115694. assert( iDb<db->nDb );
  115695. zDb = db->aDb[iDb].zDbSName;
  115696. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, zDb);
  115697. }
  115698. }
  115699. return pSrc;
  115700. }
  115701. /*
  115702. ** Generate VDBE code for the statements inside the body of a single
  115703. ** trigger.
  115704. */
  115705. static int codeTriggerProgram(
  115706. Parse *pParse, /* The parser context */
  115707. TriggerStep *pStepList, /* List of statements inside the trigger body */
  115708. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  115709. ){
  115710. TriggerStep *pStep;
  115711. Vdbe *v = pParse->pVdbe;
  115712. sqlite3 *db = pParse->db;
  115713. assert( pParse->pTriggerTab && pParse->pToplevel );
  115714. assert( pStepList );
  115715. assert( v!=0 );
  115716. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  115717. /* Figure out the ON CONFLICT policy that will be used for this step
  115718. ** of the trigger program. If the statement that caused this trigger
  115719. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  115720. ** the ON CONFLICT policy that was specified as part of the trigger
  115721. ** step statement. Example:
  115722. **
  115723. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  115724. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  115725. ** END;
  115726. **
  115727. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  115728. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  115729. */
  115730. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  115731. assert( pParse->okConstFactor==0 );
  115732. switch( pStep->op ){
  115733. case TK_UPDATE: {
  115734. sqlite3Update(pParse,
  115735. targetSrcList(pParse, pStep),
  115736. sqlite3ExprListDup(db, pStep->pExprList, 0),
  115737. sqlite3ExprDup(db, pStep->pWhere, 0),
  115738. pParse->eOrconf
  115739. );
  115740. break;
  115741. }
  115742. case TK_INSERT: {
  115743. sqlite3Insert(pParse,
  115744. targetSrcList(pParse, pStep),
  115745. sqlite3SelectDup(db, pStep->pSelect, 0),
  115746. sqlite3IdListDup(db, pStep->pIdList),
  115747. pParse->eOrconf
  115748. );
  115749. break;
  115750. }
  115751. case TK_DELETE: {
  115752. sqlite3DeleteFrom(pParse,
  115753. targetSrcList(pParse, pStep),
  115754. sqlite3ExprDup(db, pStep->pWhere, 0)
  115755. );
  115756. break;
  115757. }
  115758. default: assert( pStep->op==TK_SELECT ); {
  115759. SelectDest sDest;
  115760. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  115761. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  115762. sqlite3Select(pParse, pSelect, &sDest);
  115763. sqlite3SelectDelete(db, pSelect);
  115764. break;
  115765. }
  115766. }
  115767. if( pStep->op!=TK_SELECT ){
  115768. sqlite3VdbeAddOp0(v, OP_ResetCount);
  115769. }
  115770. }
  115771. return 0;
  115772. }
  115773. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  115774. /*
  115775. ** This function is used to add VdbeComment() annotations to a VDBE
  115776. ** program. It is not used in production code, only for debugging.
  115777. */
  115778. static const char *onErrorText(int onError){
  115779. switch( onError ){
  115780. case OE_Abort: return "abort";
  115781. case OE_Rollback: return "rollback";
  115782. case OE_Fail: return "fail";
  115783. case OE_Replace: return "replace";
  115784. case OE_Ignore: return "ignore";
  115785. case OE_Default: return "default";
  115786. }
  115787. return "n/a";
  115788. }
  115789. #endif
  115790. /*
  115791. ** Parse context structure pFrom has just been used to create a sub-vdbe
  115792. ** (trigger program). If an error has occurred, transfer error information
  115793. ** from pFrom to pTo.
  115794. */
  115795. static void transferParseError(Parse *pTo, Parse *pFrom){
  115796. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  115797. assert( pTo->zErrMsg==0 || pTo->nErr );
  115798. if( pTo->nErr==0 ){
  115799. pTo->zErrMsg = pFrom->zErrMsg;
  115800. pTo->nErr = pFrom->nErr;
  115801. pTo->rc = pFrom->rc;
  115802. }else{
  115803. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  115804. }
  115805. }
  115806. /*
  115807. ** Create and populate a new TriggerPrg object with a sub-program
  115808. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  115809. */
  115810. static TriggerPrg *codeRowTrigger(
  115811. Parse *pParse, /* Current parse context */
  115812. Trigger *pTrigger, /* Trigger to code */
  115813. Table *pTab, /* The table pTrigger is attached to */
  115814. int orconf /* ON CONFLICT policy to code trigger program with */
  115815. ){
  115816. Parse *pTop = sqlite3ParseToplevel(pParse);
  115817. sqlite3 *db = pParse->db; /* Database handle */
  115818. TriggerPrg *pPrg; /* Value to return */
  115819. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  115820. Vdbe *v; /* Temporary VM */
  115821. NameContext sNC; /* Name context for sub-vdbe */
  115822. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  115823. Parse *pSubParse; /* Parse context for sub-vdbe */
  115824. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  115825. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  115826. assert( pTop->pVdbe );
  115827. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  115828. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  115829. ** list of the top-level Parse object sooner rather than later. */
  115830. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  115831. if( !pPrg ) return 0;
  115832. pPrg->pNext = pTop->pTriggerPrg;
  115833. pTop->pTriggerPrg = pPrg;
  115834. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  115835. if( !pProgram ) return 0;
  115836. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  115837. pPrg->pTrigger = pTrigger;
  115838. pPrg->orconf = orconf;
  115839. pPrg->aColmask[0] = 0xffffffff;
  115840. pPrg->aColmask[1] = 0xffffffff;
  115841. /* Allocate and populate a new Parse context to use for coding the
  115842. ** trigger sub-program. */
  115843. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  115844. if( !pSubParse ) return 0;
  115845. memset(&sNC, 0, sizeof(sNC));
  115846. sNC.pParse = pSubParse;
  115847. pSubParse->db = db;
  115848. pSubParse->pTriggerTab = pTab;
  115849. pSubParse->pToplevel = pTop;
  115850. pSubParse->zAuthContext = pTrigger->zName;
  115851. pSubParse->eTriggerOp = pTrigger->op;
  115852. pSubParse->nQueryLoop = pParse->nQueryLoop;
  115853. v = sqlite3GetVdbe(pSubParse);
  115854. if( v ){
  115855. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  115856. pTrigger->zName, onErrorText(orconf),
  115857. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  115858. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  115859. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  115860. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  115861. pTab->zName
  115862. ));
  115863. #ifndef SQLITE_OMIT_TRACE
  115864. sqlite3VdbeChangeP4(v, -1,
  115865. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  115866. );
  115867. #endif
  115868. /* If one was specified, code the WHEN clause. If it evaluates to false
  115869. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  115870. ** OP_Halt inserted at the end of the program. */
  115871. if( pTrigger->pWhen ){
  115872. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  115873. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  115874. && db->mallocFailed==0
  115875. ){
  115876. iEndTrigger = sqlite3VdbeMakeLabel(v);
  115877. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  115878. }
  115879. sqlite3ExprDelete(db, pWhen);
  115880. }
  115881. /* Code the trigger program into the sub-vdbe. */
  115882. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  115883. /* Insert an OP_Halt at the end of the sub-program. */
  115884. if( iEndTrigger ){
  115885. sqlite3VdbeResolveLabel(v, iEndTrigger);
  115886. }
  115887. sqlite3VdbeAddOp0(v, OP_Halt);
  115888. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  115889. transferParseError(pParse, pSubParse);
  115890. if( db->mallocFailed==0 ){
  115891. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  115892. }
  115893. pProgram->nMem = pSubParse->nMem;
  115894. pProgram->nCsr = pSubParse->nTab;
  115895. pProgram->token = (void *)pTrigger;
  115896. pPrg->aColmask[0] = pSubParse->oldmask;
  115897. pPrg->aColmask[1] = pSubParse->newmask;
  115898. sqlite3VdbeDelete(v);
  115899. }
  115900. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  115901. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  115902. sqlite3ParserReset(pSubParse);
  115903. sqlite3StackFree(db, pSubParse);
  115904. return pPrg;
  115905. }
  115906. /*
  115907. ** Return a pointer to a TriggerPrg object containing the sub-program for
  115908. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  115909. ** TriggerPrg object exists, a new object is allocated and populated before
  115910. ** being returned.
  115911. */
  115912. static TriggerPrg *getRowTrigger(
  115913. Parse *pParse, /* Current parse context */
  115914. Trigger *pTrigger, /* Trigger to code */
  115915. Table *pTab, /* The table trigger pTrigger is attached to */
  115916. int orconf /* ON CONFLICT algorithm. */
  115917. ){
  115918. Parse *pRoot = sqlite3ParseToplevel(pParse);
  115919. TriggerPrg *pPrg;
  115920. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  115921. /* It may be that this trigger has already been coded (or is in the
  115922. ** process of being coded). If this is the case, then an entry with
  115923. ** a matching TriggerPrg.pTrigger field will be present somewhere
  115924. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  115925. for(pPrg=pRoot->pTriggerPrg;
  115926. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  115927. pPrg=pPrg->pNext
  115928. );
  115929. /* If an existing TriggerPrg could not be located, create a new one. */
  115930. if( !pPrg ){
  115931. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  115932. }
  115933. return pPrg;
  115934. }
  115935. /*
  115936. ** Generate code for the trigger program associated with trigger p on
  115937. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  115938. ** function are the same as those described in the header function for
  115939. ** sqlite3CodeRowTrigger()
  115940. */
  115941. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  115942. Parse *pParse, /* Parse context */
  115943. Trigger *p, /* Trigger to code */
  115944. Table *pTab, /* The table to code triggers from */
  115945. int reg, /* Reg array containing OLD.* and NEW.* values */
  115946. int orconf, /* ON CONFLICT policy */
  115947. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  115948. ){
  115949. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  115950. TriggerPrg *pPrg;
  115951. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  115952. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  115953. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  115954. ** is a pointer to the sub-vdbe containing the trigger program. */
  115955. if( pPrg ){
  115956. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  115957. sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
  115958. (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  115959. VdbeComment(
  115960. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  115961. /* Set the P5 operand of the OP_Program instruction to non-zero if
  115962. ** recursive invocation of this trigger program is disallowed. Recursive
  115963. ** invocation is disallowed if (a) the sub-program is really a trigger,
  115964. ** not a foreign key action, and (b) the flag to enable recursive triggers
  115965. ** is clear. */
  115966. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  115967. }
  115968. }
  115969. /*
  115970. ** This is called to code the required FOR EACH ROW triggers for an operation
  115971. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  115972. ** is given by the op parameter. The tr_tm parameter determines whether the
  115973. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  115974. ** parameter pChanges is passed the list of columns being modified.
  115975. **
  115976. ** If there are no triggers that fire at the specified time for the specified
  115977. ** operation on pTab, this function is a no-op.
  115978. **
  115979. ** The reg argument is the address of the first in an array of registers
  115980. ** that contain the values substituted for the new.* and old.* references
  115981. ** in the trigger program. If N is the number of columns in table pTab
  115982. ** (a copy of pTab->nCol), then registers are populated as follows:
  115983. **
  115984. ** Register Contains
  115985. ** ------------------------------------------------------
  115986. ** reg+0 OLD.rowid
  115987. ** reg+1 OLD.* value of left-most column of pTab
  115988. ** ... ...
  115989. ** reg+N OLD.* value of right-most column of pTab
  115990. ** reg+N+1 NEW.rowid
  115991. ** reg+N+2 OLD.* value of left-most column of pTab
  115992. ** ... ...
  115993. ** reg+N+N+1 NEW.* value of right-most column of pTab
  115994. **
  115995. ** For ON DELETE triggers, the registers containing the NEW.* values will
  115996. ** never be accessed by the trigger program, so they are not allocated or
  115997. ** populated by the caller (there is no data to populate them with anyway).
  115998. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  115999. ** are never accessed, and so are not allocated by the caller. So, for an
  116000. ** ON INSERT trigger, the value passed to this function as parameter reg
  116001. ** is not a readable register, although registers (reg+N) through
  116002. ** (reg+N+N+1) are.
  116003. **
  116004. ** Parameter orconf is the default conflict resolution algorithm for the
  116005. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  116006. ** is the instruction that control should jump to if a trigger program
  116007. ** raises an IGNORE exception.
  116008. */
  116009. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  116010. Parse *pParse, /* Parse context */
  116011. Trigger *pTrigger, /* List of triggers on table pTab */
  116012. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  116013. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  116014. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  116015. Table *pTab, /* The table to code triggers from */
  116016. int reg, /* The first in an array of registers (see above) */
  116017. int orconf, /* ON CONFLICT policy */
  116018. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  116019. ){
  116020. Trigger *p; /* Used to iterate through pTrigger list */
  116021. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  116022. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  116023. assert( (op==TK_UPDATE)==(pChanges!=0) );
  116024. for(p=pTrigger; p; p=p->pNext){
  116025. /* Sanity checking: The schema for the trigger and for the table are
  116026. ** always defined. The trigger must be in the same schema as the table
  116027. ** or else it must be a TEMP trigger. */
  116028. assert( p->pSchema!=0 );
  116029. assert( p->pTabSchema!=0 );
  116030. assert( p->pSchema==p->pTabSchema
  116031. || p->pSchema==pParse->db->aDb[1].pSchema );
  116032. /* Determine whether we should code this trigger */
  116033. if( p->op==op
  116034. && p->tr_tm==tr_tm
  116035. && checkColumnOverlap(p->pColumns, pChanges)
  116036. ){
  116037. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  116038. }
  116039. }
  116040. }
  116041. /*
  116042. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  116043. ** This function returns a 32-bit bitmask indicating which columns of the
  116044. ** old.* or new.* tables actually are used by triggers. This information
  116045. ** may be used by the caller, for example, to avoid having to load the entire
  116046. ** old.* record into memory when executing an UPDATE or DELETE command.
  116047. **
  116048. ** Bit 0 of the returned mask is set if the left-most column of the
  116049. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  116050. ** the second leftmost column value is required, and so on. If there
  116051. ** are more than 32 columns in the table, and at least one of the columns
  116052. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  116053. **
  116054. ** It is not possible to determine if the old.rowid or new.rowid column is
  116055. ** accessed by triggers. The caller must always assume that it is.
  116056. **
  116057. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  116058. ** applies to the old.* table. If 1, the new.* table.
  116059. **
  116060. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  116061. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  116062. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  116063. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  116064. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  116065. */
  116066. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  116067. Parse *pParse, /* Parse context */
  116068. Trigger *pTrigger, /* List of triggers on table pTab */
  116069. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  116070. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  116071. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  116072. Table *pTab, /* The table to code triggers from */
  116073. int orconf /* Default ON CONFLICT policy for trigger steps */
  116074. ){
  116075. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  116076. u32 mask = 0;
  116077. Trigger *p;
  116078. assert( isNew==1 || isNew==0 );
  116079. for(p=pTrigger; p; p=p->pNext){
  116080. if( p->op==op && (tr_tm&p->tr_tm)
  116081. && checkColumnOverlap(p->pColumns,pChanges)
  116082. ){
  116083. TriggerPrg *pPrg;
  116084. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  116085. if( pPrg ){
  116086. mask |= pPrg->aColmask[isNew];
  116087. }
  116088. }
  116089. }
  116090. return mask;
  116091. }
  116092. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  116093. /************** End of trigger.c *********************************************/
  116094. /************** Begin file update.c ******************************************/
  116095. /*
  116096. ** 2001 September 15
  116097. **
  116098. ** The author disclaims copyright to this source code. In place of
  116099. ** a legal notice, here is a blessing:
  116100. **
  116101. ** May you do good and not evil.
  116102. ** May you find forgiveness for yourself and forgive others.
  116103. ** May you share freely, never taking more than you give.
  116104. **
  116105. *************************************************************************
  116106. ** This file contains C code routines that are called by the parser
  116107. ** to handle UPDATE statements.
  116108. */
  116109. /* #include "sqliteInt.h" */
  116110. #ifndef SQLITE_OMIT_VIRTUALTABLE
  116111. /* Forward declaration */
  116112. static void updateVirtualTable(
  116113. Parse *pParse, /* The parsing context */
  116114. SrcList *pSrc, /* The virtual table to be modified */
  116115. Table *pTab, /* The virtual table */
  116116. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  116117. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  116118. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  116119. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  116120. int onError /* ON CONFLICT strategy */
  116121. );
  116122. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  116123. /*
  116124. ** The most recently coded instruction was an OP_Column to retrieve the
  116125. ** i-th column of table pTab. This routine sets the P4 parameter of the
  116126. ** OP_Column to the default value, if any.
  116127. **
  116128. ** The default value of a column is specified by a DEFAULT clause in the
  116129. ** column definition. This was either supplied by the user when the table
  116130. ** was created, or added later to the table definition by an ALTER TABLE
  116131. ** command. If the latter, then the row-records in the table btree on disk
  116132. ** may not contain a value for the column and the default value, taken
  116133. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  116134. ** If the former, then all row-records are guaranteed to include a value
  116135. ** for the column and the P4 value is not required.
  116136. **
  116137. ** Column definitions created by an ALTER TABLE command may only have
  116138. ** literal default values specified: a number, null or a string. (If a more
  116139. ** complicated default expression value was provided, it is evaluated
  116140. ** when the ALTER TABLE is executed and one of the literal values written
  116141. ** into the sqlite_master table.)
  116142. **
  116143. ** Therefore, the P4 parameter is only required if the default value for
  116144. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  116145. ** function is capable of transforming these types of expressions into
  116146. ** sqlite3_value objects.
  116147. **
  116148. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  116149. ** on register iReg. This is used when an equivalent integer value is
  116150. ** stored in place of an 8-byte floating point value in order to save
  116151. ** space.
  116152. */
  116153. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  116154. assert( pTab!=0 );
  116155. if( !pTab->pSelect ){
  116156. sqlite3_value *pValue = 0;
  116157. u8 enc = ENC(sqlite3VdbeDb(v));
  116158. Column *pCol = &pTab->aCol[i];
  116159. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  116160. assert( i<pTab->nCol );
  116161. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  116162. pCol->affinity, &pValue);
  116163. if( pValue ){
  116164. sqlite3VdbeAppendP4(v, pValue, P4_MEM);
  116165. }
  116166. }
  116167. #ifndef SQLITE_OMIT_FLOATING_POINT
  116168. if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  116169. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  116170. }
  116171. #endif
  116172. }
  116173. /*
  116174. ** Process an UPDATE statement.
  116175. **
  116176. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  116177. ** \_______/ \________/ \______/ \________________/
  116178. * onError pTabList pChanges pWhere
  116179. */
  116180. SQLITE_PRIVATE void sqlite3Update(
  116181. Parse *pParse, /* The parser context */
  116182. SrcList *pTabList, /* The table in which we should change things */
  116183. ExprList *pChanges, /* Things to be changed */
  116184. Expr *pWhere, /* The WHERE clause. May be null */
  116185. int onError /* How to handle constraint errors */
  116186. ){
  116187. int i, j; /* Loop counters */
  116188. Table *pTab; /* The table to be updated */
  116189. int addrTop = 0; /* VDBE instruction address of the start of the loop */
  116190. WhereInfo *pWInfo; /* Information about the WHERE clause */
  116191. Vdbe *v; /* The virtual database engine */
  116192. Index *pIdx; /* For looping over indices */
  116193. Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
  116194. int nIdx; /* Number of indices that need updating */
  116195. int iBaseCur; /* Base cursor number */
  116196. int iDataCur; /* Cursor for the canonical data btree */
  116197. int iIdxCur; /* Cursor for the first index */
  116198. sqlite3 *db; /* The database structure */
  116199. int *aRegIdx = 0; /* First register in array assigned to each index */
  116200. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  116201. ** an expression for the i-th column of the table.
  116202. ** aXRef[i]==-1 if the i-th column is not changed. */
  116203. u8 *aToOpen; /* 1 for tables and indices to be opened */
  116204. u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
  116205. u8 chngRowid; /* Rowid changed in a normal table */
  116206. u8 chngKey; /* Either chngPk or chngRowid */
  116207. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  116208. AuthContext sContext; /* The authorization context */
  116209. NameContext sNC; /* The name-context to resolve expressions in */
  116210. int iDb; /* Database containing the table being updated */
  116211. int eOnePass; /* ONEPASS_XXX value from where.c */
  116212. int hasFK; /* True if foreign key processing is required */
  116213. int labelBreak; /* Jump here to break out of UPDATE loop */
  116214. int labelContinue; /* Jump here to continue next step of UPDATE loop */
  116215. int flags; /* Flags for sqlite3WhereBegin() */
  116216. #ifndef SQLITE_OMIT_TRIGGER
  116217. int isView; /* True when updating a view (INSTEAD OF trigger) */
  116218. Trigger *pTrigger; /* List of triggers on pTab, if required */
  116219. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  116220. #endif
  116221. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  116222. int iEph = 0; /* Ephemeral table holding all primary key values */
  116223. int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
  116224. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  116225. int addrOpen = 0; /* Address of OP_OpenEphemeral */
  116226. int iPk = 0; /* First of nPk cells holding PRIMARY KEY value */
  116227. i16 nPk = 0; /* Number of components of the PRIMARY KEY */
  116228. int bReplace = 0; /* True if REPLACE conflict resolution might happen */
  116229. /* Register Allocations */
  116230. int regRowCount = 0; /* A count of rows changed */
  116231. int regOldRowid = 0; /* The old rowid */
  116232. int regNewRowid = 0; /* The new rowid */
  116233. int regNew = 0; /* Content of the NEW.* table in triggers */
  116234. int regOld = 0; /* Content of OLD.* table in triggers */
  116235. int regRowSet = 0; /* Rowset of rows to be updated */
  116236. int regKey = 0; /* composite PRIMARY KEY value */
  116237. memset(&sContext, 0, sizeof(sContext));
  116238. db = pParse->db;
  116239. if( pParse->nErr || db->mallocFailed ){
  116240. goto update_cleanup;
  116241. }
  116242. assert( pTabList->nSrc==1 );
  116243. /* Locate the table which we want to update.
  116244. */
  116245. pTab = sqlite3SrcListLookup(pParse, pTabList);
  116246. if( pTab==0 ) goto update_cleanup;
  116247. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  116248. /* Figure out if we have any triggers and if the table being
  116249. ** updated is a view.
  116250. */
  116251. #ifndef SQLITE_OMIT_TRIGGER
  116252. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  116253. isView = pTab->pSelect!=0;
  116254. assert( pTrigger || tmask==0 );
  116255. #else
  116256. # define pTrigger 0
  116257. # define isView 0
  116258. # define tmask 0
  116259. #endif
  116260. #ifdef SQLITE_OMIT_VIEW
  116261. # undef isView
  116262. # define isView 0
  116263. #endif
  116264. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  116265. goto update_cleanup;
  116266. }
  116267. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  116268. goto update_cleanup;
  116269. }
  116270. /* Allocate a cursors for the main database table and for all indices.
  116271. ** The index cursors might not be used, but if they are used they
  116272. ** need to occur right after the database cursor. So go ahead and
  116273. ** allocate enough space, just in case.
  116274. */
  116275. pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
  116276. iIdxCur = iDataCur+1;
  116277. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  116278. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  116279. if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
  116280. iDataCur = pParse->nTab;
  116281. pTabList->a[0].iCursor = iDataCur;
  116282. }
  116283. pParse->nTab++;
  116284. }
  116285. /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
  116286. ** Initialize aXRef[] and aToOpen[] to their default values.
  116287. */
  116288. aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
  116289. if( aXRef==0 ) goto update_cleanup;
  116290. aRegIdx = aXRef+pTab->nCol;
  116291. aToOpen = (u8*)(aRegIdx+nIdx);
  116292. memset(aToOpen, 1, nIdx+1);
  116293. aToOpen[nIdx+1] = 0;
  116294. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  116295. /* Initialize the name-context */
  116296. memset(&sNC, 0, sizeof(sNC));
  116297. sNC.pParse = pParse;
  116298. sNC.pSrcList = pTabList;
  116299. /* Resolve the column names in all the expressions of the
  116300. ** of the UPDATE statement. Also find the column index
  116301. ** for each column to be updated in the pChanges array. For each
  116302. ** column to be updated, make sure we have authorization to change
  116303. ** that column.
  116304. */
  116305. chngRowid = chngPk = 0;
  116306. for(i=0; i<pChanges->nExpr; i++){
  116307. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  116308. goto update_cleanup;
  116309. }
  116310. for(j=0; j<pTab->nCol; j++){
  116311. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  116312. if( j==pTab->iPKey ){
  116313. chngRowid = 1;
  116314. pRowidExpr = pChanges->a[i].pExpr;
  116315. }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
  116316. chngPk = 1;
  116317. }
  116318. aXRef[j] = i;
  116319. break;
  116320. }
  116321. }
  116322. if( j>=pTab->nCol ){
  116323. if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
  116324. j = -1;
  116325. chngRowid = 1;
  116326. pRowidExpr = pChanges->a[i].pExpr;
  116327. }else{
  116328. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  116329. pParse->checkSchema = 1;
  116330. goto update_cleanup;
  116331. }
  116332. }
  116333. #ifndef SQLITE_OMIT_AUTHORIZATION
  116334. {
  116335. int rc;
  116336. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  116337. j<0 ? "ROWID" : pTab->aCol[j].zName,
  116338. db->aDb[iDb].zDbSName);
  116339. if( rc==SQLITE_DENY ){
  116340. goto update_cleanup;
  116341. }else if( rc==SQLITE_IGNORE ){
  116342. aXRef[j] = -1;
  116343. }
  116344. }
  116345. #endif
  116346. }
  116347. assert( (chngRowid & chngPk)==0 );
  116348. assert( chngRowid==0 || chngRowid==1 );
  116349. assert( chngPk==0 || chngPk==1 );
  116350. chngKey = chngRowid + chngPk;
  116351. /* The SET expressions are not actually used inside the WHERE loop.
  116352. ** So reset the colUsed mask. Unless this is a virtual table. In that
  116353. ** case, set all bits of the colUsed mask (to ensure that the virtual
  116354. ** table implementation makes all columns available).
  116355. */
  116356. pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
  116357. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
  116358. /* There is one entry in the aRegIdx[] array for each index on the table
  116359. ** being updated. Fill in aRegIdx[] with a register number that will hold
  116360. ** the key for accessing each index.
  116361. **
  116362. ** FIXME: Be smarter about omitting indexes that use expressions.
  116363. */
  116364. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  116365. int reg;
  116366. if( chngKey || hasFK>1 || pIdx->pPartIdxWhere || pIdx==pPk ){
  116367. reg = ++pParse->nMem;
  116368. pParse->nMem += pIdx->nColumn;
  116369. }else{
  116370. reg = 0;
  116371. for(i=0; i<pIdx->nKeyCol; i++){
  116372. i16 iIdxCol = pIdx->aiColumn[i];
  116373. if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
  116374. reg = ++pParse->nMem;
  116375. pParse->nMem += pIdx->nColumn;
  116376. if( (onError==OE_Replace)
  116377. || (onError==OE_Default && pIdx->onError==OE_Replace)
  116378. ){
  116379. bReplace = 1;
  116380. }
  116381. break;
  116382. }
  116383. }
  116384. }
  116385. if( reg==0 ) aToOpen[j+1] = 0;
  116386. aRegIdx[j] = reg;
  116387. }
  116388. if( bReplace ){
  116389. /* If REPLACE conflict resolution might be invoked, open cursors on all
  116390. ** indexes in case they are needed to delete records. */
  116391. memset(aToOpen, 1, nIdx+1);
  116392. }
  116393. /* Begin generating code. */
  116394. v = sqlite3GetVdbe(pParse);
  116395. if( v==0 ) goto update_cleanup;
  116396. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  116397. sqlite3BeginWriteOperation(pParse, 1, iDb);
  116398. /* Allocate required registers. */
  116399. if( !IsVirtual(pTab) ){
  116400. regRowSet = ++pParse->nMem;
  116401. regOldRowid = regNewRowid = ++pParse->nMem;
  116402. if( chngPk || pTrigger || hasFK ){
  116403. regOld = pParse->nMem + 1;
  116404. pParse->nMem += pTab->nCol;
  116405. }
  116406. if( chngKey || pTrigger || hasFK ){
  116407. regNewRowid = ++pParse->nMem;
  116408. }
  116409. regNew = pParse->nMem + 1;
  116410. pParse->nMem += pTab->nCol;
  116411. }
  116412. /* Start the view context. */
  116413. if( isView ){
  116414. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  116415. }
  116416. /* If we are trying to update a view, realize that view into
  116417. ** an ephemeral table.
  116418. */
  116419. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  116420. if( isView ){
  116421. sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
  116422. }
  116423. #endif
  116424. /* Resolve the column names in all the expressions in the
  116425. ** WHERE clause.
  116426. */
  116427. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  116428. goto update_cleanup;
  116429. }
  116430. #ifndef SQLITE_OMIT_VIRTUALTABLE
  116431. /* Virtual tables must be handled separately */
  116432. if( IsVirtual(pTab) ){
  116433. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  116434. pWhere, onError);
  116435. goto update_cleanup;
  116436. }
  116437. #endif
  116438. /* Initialize the count of updated rows */
  116439. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  116440. regRowCount = ++pParse->nMem;
  116441. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  116442. }
  116443. if( HasRowid(pTab) ){
  116444. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  116445. }else{
  116446. assert( pPk!=0 );
  116447. nPk = pPk->nKeyCol;
  116448. iPk = pParse->nMem+1;
  116449. pParse->nMem += nPk;
  116450. regKey = ++pParse->nMem;
  116451. iEph = pParse->nTab++;
  116452. sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
  116453. addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
  116454. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  116455. }
  116456. /* Begin the database scan.
  116457. **
  116458. ** Do not consider a single-pass strategy for a multi-row update if
  116459. ** there are any triggers or foreign keys to process, or rows may
  116460. ** be deleted as a result of REPLACE conflict handling. Any of these
  116461. ** things might disturb a cursor being used to scan through the table
  116462. ** or index, causing a single-pass approach to malfunction. */
  116463. flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;
  116464. if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
  116465. flags |= WHERE_ONEPASS_MULTIROW;
  116466. }
  116467. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);
  116468. if( pWInfo==0 ) goto update_cleanup;
  116469. /* A one-pass strategy that might update more than one row may not
  116470. ** be used if any column of the index used for the scan is being
  116471. ** updated. Otherwise, if there is an index on "b", statements like
  116472. ** the following could create an infinite loop:
  116473. **
  116474. ** UPDATE t1 SET b=b+1 WHERE b>?
  116475. **
  116476. ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
  116477. ** strategy that uses an index for which one or more columns are being
  116478. ** updated. */
  116479. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  116480. if( eOnePass==ONEPASS_MULTI ){
  116481. int iCur = aiCurOnePass[1];
  116482. if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
  116483. eOnePass = ONEPASS_OFF;
  116484. }
  116485. assert( iCur!=iDataCur || !HasRowid(pTab) );
  116486. }
  116487. if( HasRowid(pTab) ){
  116488. /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
  116489. ** mode, write the rowid into the FIFO. In either of the one-pass modes,
  116490. ** leave it in register regOldRowid. */
  116491. sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
  116492. if( eOnePass==ONEPASS_OFF ){
  116493. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  116494. }
  116495. }else{
  116496. /* Read the PK of the current row into an array of registers. In
  116497. ** ONEPASS_OFF mode, serialize the array into a record and store it in
  116498. ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
  116499. ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
  116500. ** is not required) and leave the PK fields in the array of registers. */
  116501. for(i=0; i<nPk; i++){
  116502. assert( pPk->aiColumn[i]>=0 );
  116503. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,pPk->aiColumn[i],iPk+i);
  116504. }
  116505. if( eOnePass ){
  116506. sqlite3VdbeChangeToNoop(v, addrOpen);
  116507. nKey = nPk;
  116508. regKey = iPk;
  116509. }else{
  116510. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
  116511. sqlite3IndexAffinityStr(db, pPk), nPk);
  116512. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
  116513. }
  116514. }
  116515. if( eOnePass!=ONEPASS_MULTI ){
  116516. sqlite3WhereEnd(pWInfo);
  116517. }
  116518. labelBreak = sqlite3VdbeMakeLabel(v);
  116519. if( !isView ){
  116520. int addrOnce = 0;
  116521. /* Open every index that needs updating. */
  116522. if( eOnePass!=ONEPASS_OFF ){
  116523. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
  116524. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
  116525. }
  116526. if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
  116527. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  116528. }
  116529. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
  116530. 0, 0);
  116531. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  116532. }
  116533. /* Top of the update loop */
  116534. if( eOnePass!=ONEPASS_OFF ){
  116535. if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
  116536. assert( pPk );
  116537. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
  116538. VdbeCoverageNeverTaken(v);
  116539. }
  116540. if( eOnePass==ONEPASS_SINGLE ){
  116541. labelContinue = labelBreak;
  116542. }else{
  116543. labelContinue = sqlite3VdbeMakeLabel(v);
  116544. }
  116545. sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
  116546. VdbeCoverageIf(v, pPk==0);
  116547. VdbeCoverageIf(v, pPk!=0);
  116548. }else if( pPk ){
  116549. labelContinue = sqlite3VdbeMakeLabel(v);
  116550. sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
  116551. addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
  116552. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
  116553. VdbeCoverage(v);
  116554. }else{
  116555. labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
  116556. regOldRowid);
  116557. VdbeCoverage(v);
  116558. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  116559. VdbeCoverage(v);
  116560. }
  116561. /* If the record number will change, set register regNewRowid to
  116562. ** contain the new value. If the record number is not being modified,
  116563. ** then regNewRowid is the same register as regOldRowid, which is
  116564. ** already populated. */
  116565. assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
  116566. if( chngRowid ){
  116567. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  116568. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
  116569. }
  116570. /* Compute the old pre-UPDATE content of the row being changed, if that
  116571. ** information is needed */
  116572. if( chngPk || hasFK || pTrigger ){
  116573. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  116574. oldmask |= sqlite3TriggerColmask(pParse,
  116575. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  116576. );
  116577. for(i=0; i<pTab->nCol; i++){
  116578. if( oldmask==0xffffffff
  116579. || (i<32 && (oldmask & MASKBIT32(i))!=0)
  116580. || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
  116581. ){
  116582. testcase( oldmask!=0xffffffff && i==31 );
  116583. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
  116584. }else{
  116585. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  116586. }
  116587. }
  116588. if( chngRowid==0 && pPk==0 ){
  116589. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  116590. }
  116591. }
  116592. /* Populate the array of registers beginning at regNew with the new
  116593. ** row data. This array is used to check constants, create the new
  116594. ** table and index records, and as the values for any new.* references
  116595. ** made by triggers.
  116596. **
  116597. ** If there are one or more BEFORE triggers, then do not populate the
  116598. ** registers associated with columns that are (a) not modified by
  116599. ** this UPDATE statement and (b) not accessed by new.* references. The
  116600. ** values for registers not modified by the UPDATE must be reloaded from
  116601. ** the database after the BEFORE triggers are fired anyway (as the trigger
  116602. ** may have modified them). So not loading those that are not going to
  116603. ** be used eliminates some redundant opcodes.
  116604. */
  116605. newmask = sqlite3TriggerColmask(
  116606. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  116607. );
  116608. for(i=0; i<pTab->nCol; i++){
  116609. if( i==pTab->iPKey ){
  116610. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  116611. }else{
  116612. j = aXRef[i];
  116613. if( j>=0 ){
  116614. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  116615. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
  116616. /* This branch loads the value of a column that will not be changed
  116617. ** into a register. This is done if there are no BEFORE triggers, or
  116618. ** if there are one or more BEFORE triggers that use this value via
  116619. ** a new.* reference in a trigger program.
  116620. */
  116621. testcase( i==31 );
  116622. testcase( i==32 );
  116623. sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
  116624. }else{
  116625. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  116626. }
  116627. }
  116628. }
  116629. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  116630. ** verified. One could argue that this is wrong.
  116631. */
  116632. if( tmask&TRIGGER_BEFORE ){
  116633. sqlite3TableAffinity(v, pTab, regNew);
  116634. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  116635. TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
  116636. /* The row-trigger may have deleted the row being updated. In this
  116637. ** case, jump to the next row. No updates or AFTER triggers are
  116638. ** required. This behavior - what happens when the row being updated
  116639. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  116640. ** documentation.
  116641. */
  116642. if( pPk ){
  116643. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
  116644. VdbeCoverage(v);
  116645. }else{
  116646. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  116647. VdbeCoverage(v);
  116648. }
  116649. /* If it did not delete it, the row-trigger may still have modified
  116650. ** some of the columns of the row being updated. Load the values for
  116651. ** all columns not modified by the update statement into their
  116652. ** registers in case this has happened.
  116653. */
  116654. for(i=0; i<pTab->nCol; i++){
  116655. if( aXRef[i]<0 && i!=pTab->iPKey ){
  116656. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  116657. }
  116658. }
  116659. }
  116660. if( !isView ){
  116661. int addr1 = 0; /* Address of jump instruction */
  116662. /* Do constraint checks. */
  116663. assert( regOldRowid>0 );
  116664. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  116665. regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
  116666. aXRef);
  116667. /* Do FK constraint checks. */
  116668. if( hasFK ){
  116669. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
  116670. }
  116671. /* Delete the index entries associated with the current record. */
  116672. if( bReplace || chngKey ){
  116673. if( pPk ){
  116674. addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
  116675. }else{
  116676. addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
  116677. }
  116678. VdbeCoverageNeverTaken(v);
  116679. }
  116680. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
  116681. /* If changing the rowid value, or if there are foreign key constraints
  116682. ** to process, delete the old record. Otherwise, add a noop OP_Delete
  116683. ** to invoke the pre-update hook.
  116684. **
  116685. ** That (regNew==regnewRowid+1) is true is also important for the
  116686. ** pre-update hook. If the caller invokes preupdate_new(), the returned
  116687. ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
  116688. ** is the column index supplied by the user.
  116689. */
  116690. assert( regNew==regNewRowid+1 );
  116691. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  116692. sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
  116693. OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
  116694. regNewRowid
  116695. );
  116696. if( eOnePass==ONEPASS_MULTI ){
  116697. assert( hasFK==0 && chngKey==0 );
  116698. sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
  116699. }
  116700. if( !pParse->nested ){
  116701. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  116702. }
  116703. #else
  116704. if( hasFK>1 || chngKey ){
  116705. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
  116706. }
  116707. #endif
  116708. if( bReplace || chngKey ){
  116709. sqlite3VdbeJumpHere(v, addr1);
  116710. }
  116711. if( hasFK ){
  116712. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
  116713. }
  116714. /* Insert the new index entries and the new record. */
  116715. sqlite3CompleteInsertion(
  116716. pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
  116717. OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
  116718. 0, 0
  116719. );
  116720. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  116721. ** handle rows (possibly in other tables) that refer via a foreign key
  116722. ** to the row just updated. */
  116723. if( hasFK ){
  116724. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
  116725. }
  116726. }
  116727. /* Increment the row counter
  116728. */
  116729. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  116730. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  116731. }
  116732. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  116733. TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
  116734. /* Repeat the above with the next record to be updated, until
  116735. ** all record selected by the WHERE clause have been updated.
  116736. */
  116737. if( eOnePass==ONEPASS_SINGLE ){
  116738. /* Nothing to do at end-of-loop for a single-pass */
  116739. }else if( eOnePass==ONEPASS_MULTI ){
  116740. sqlite3VdbeResolveLabel(v, labelContinue);
  116741. sqlite3WhereEnd(pWInfo);
  116742. }else if( pPk ){
  116743. sqlite3VdbeResolveLabel(v, labelContinue);
  116744. sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
  116745. }else{
  116746. sqlite3VdbeGoto(v, labelContinue);
  116747. }
  116748. sqlite3VdbeResolveLabel(v, labelBreak);
  116749. /* Update the sqlite_sequence table by storing the content of the
  116750. ** maximum rowid counter values recorded while inserting into
  116751. ** autoincrement tables.
  116752. */
  116753. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  116754. sqlite3AutoincrementEnd(pParse);
  116755. }
  116756. /*
  116757. ** Return the number of rows that were changed. If this routine is
  116758. ** generating code because of a call to sqlite3NestedParse(), do not
  116759. ** invoke the callback function.
  116760. */
  116761. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  116762. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  116763. sqlite3VdbeSetNumCols(v, 1);
  116764. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  116765. }
  116766. update_cleanup:
  116767. sqlite3AuthContextPop(&sContext);
  116768. sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
  116769. sqlite3SrcListDelete(db, pTabList);
  116770. sqlite3ExprListDelete(db, pChanges);
  116771. sqlite3ExprDelete(db, pWhere);
  116772. return;
  116773. }
  116774. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  116775. ** they may interfere with compilation of other functions in this file
  116776. ** (or in another file, if this file becomes part of the amalgamation). */
  116777. #ifdef isView
  116778. #undef isView
  116779. #endif
  116780. #ifdef pTrigger
  116781. #undef pTrigger
  116782. #endif
  116783. #ifndef SQLITE_OMIT_VIRTUALTABLE
  116784. /*
  116785. ** Generate code for an UPDATE of a virtual table.
  116786. **
  116787. ** There are two possible strategies - the default and the special
  116788. ** "onepass" strategy. Onepass is only used if the virtual table
  116789. ** implementation indicates that pWhere may match at most one row.
  116790. **
  116791. ** The default strategy is to create an ephemeral table that contains
  116792. ** for each row to be changed:
  116793. **
  116794. ** (A) The original rowid of that row.
  116795. ** (B) The revised rowid for the row.
  116796. ** (C) The content of every column in the row.
  116797. **
  116798. ** Then loop through the contents of this ephemeral table executing a
  116799. ** VUpdate for each row. When finished, drop the ephemeral table.
  116800. **
  116801. ** The "onepass" strategy does not use an ephemeral table. Instead, it
  116802. ** stores the same values (A, B and C above) in a register array and
  116803. ** makes a single invocation of VUpdate.
  116804. */
  116805. static void updateVirtualTable(
  116806. Parse *pParse, /* The parsing context */
  116807. SrcList *pSrc, /* The virtual table to be modified */
  116808. Table *pTab, /* The virtual table */
  116809. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  116810. Expr *pRowid, /* Expression used to recompute the rowid */
  116811. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  116812. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  116813. int onError /* ON CONFLICT strategy */
  116814. ){
  116815. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  116816. int ephemTab; /* Table holding the result of the SELECT */
  116817. int i; /* Loop counter */
  116818. sqlite3 *db = pParse->db; /* Database connection */
  116819. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  116820. WhereInfo *pWInfo;
  116821. int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
  116822. int regArg; /* First register in VUpdate arg array */
  116823. int regRec; /* Register in which to assemble record */
  116824. int regRowid; /* Register for ephem table rowid */
  116825. int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
  116826. int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
  116827. int bOnePass; /* True to use onepass strategy */
  116828. int addr; /* Address of OP_OpenEphemeral */
  116829. /* Allocate nArg registers to martial the arguments to VUpdate. Then
  116830. ** create and open the ephemeral table in which the records created from
  116831. ** these arguments will be temporarily stored. */
  116832. assert( v );
  116833. ephemTab = pParse->nTab++;
  116834. addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
  116835. regArg = pParse->nMem + 1;
  116836. pParse->nMem += nArg;
  116837. regRec = ++pParse->nMem;
  116838. regRowid = ++pParse->nMem;
  116839. /* Start scanning the virtual table */
  116840. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
  116841. if( pWInfo==0 ) return;
  116842. /* Populate the argument registers. */
  116843. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
  116844. if( pRowid ){
  116845. sqlite3ExprCode(pParse, pRowid, regArg+1);
  116846. }else{
  116847. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
  116848. }
  116849. for(i=0; i<pTab->nCol; i++){
  116850. if( aXRef[i]>=0 ){
  116851. sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
  116852. }else{
  116853. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
  116854. }
  116855. }
  116856. bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
  116857. if( bOnePass ){
  116858. /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
  116859. ** above. Also, if this is a top-level parse (not a trigger), clear the
  116860. ** multi-write flag so that the VM does not open a statement journal */
  116861. sqlite3VdbeChangeToNoop(v, addr);
  116862. if( sqlite3IsToplevel(pParse) ){
  116863. pParse->isMultiWrite = 0;
  116864. }
  116865. }else{
  116866. /* Create a record from the argument register contents and insert it into
  116867. ** the ephemeral table. */
  116868. sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
  116869. sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
  116870. sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
  116871. }
  116872. if( bOnePass==0 ){
  116873. /* End the virtual table scan */
  116874. sqlite3WhereEnd(pWInfo);
  116875. /* Begin scannning through the ephemeral table. */
  116876. addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
  116877. /* Extract arguments from the current row of the ephemeral table and
  116878. ** invoke the VUpdate method. */
  116879. for(i=0; i<nArg; i++){
  116880. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
  116881. }
  116882. }
  116883. sqlite3VtabMakeWritable(pParse, pTab);
  116884. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
  116885. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  116886. sqlite3MayAbort(pParse);
  116887. /* End of the ephemeral table scan. Or, if using the onepass strategy,
  116888. ** jump to here if the scan visited zero rows. */
  116889. if( bOnePass==0 ){
  116890. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
  116891. sqlite3VdbeJumpHere(v, addr);
  116892. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  116893. }else{
  116894. sqlite3WhereEnd(pWInfo);
  116895. }
  116896. }
  116897. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  116898. /************** End of update.c **********************************************/
  116899. /************** Begin file vacuum.c ******************************************/
  116900. /*
  116901. ** 2003 April 6
  116902. **
  116903. ** The author disclaims copyright to this source code. In place of
  116904. ** a legal notice, here is a blessing:
  116905. **
  116906. ** May you do good and not evil.
  116907. ** May you find forgiveness for yourself and forgive others.
  116908. ** May you share freely, never taking more than you give.
  116909. **
  116910. *************************************************************************
  116911. ** This file contains code used to implement the VACUUM command.
  116912. **
  116913. ** Most of the code in this file may be omitted by defining the
  116914. ** SQLITE_OMIT_VACUUM macro.
  116915. */
  116916. /* #include "sqliteInt.h" */
  116917. /* #include "vdbeInt.h" */
  116918. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  116919. /*
  116920. ** Execute zSql on database db.
  116921. **
  116922. ** If zSql returns rows, then each row will have exactly one
  116923. ** column. (This will only happen if zSql begins with "SELECT".)
  116924. ** Take each row of result and call execSql() again recursively.
  116925. **
  116926. ** The execSqlF() routine does the same thing, except it accepts
  116927. ** a format string as its third argument
  116928. */
  116929. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  116930. sqlite3_stmt *pStmt;
  116931. int rc;
  116932. /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
  116933. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  116934. if( rc!=SQLITE_OK ) return rc;
  116935. while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  116936. const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
  116937. assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
  116938. if( zSubSql ){
  116939. assert( zSubSql[0]!='S' );
  116940. rc = execSql(db, pzErrMsg, zSubSql);
  116941. if( rc!=SQLITE_OK ) break;
  116942. }
  116943. }
  116944. assert( rc!=SQLITE_ROW );
  116945. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  116946. if( rc ){
  116947. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  116948. }
  116949. (void)sqlite3_finalize(pStmt);
  116950. return rc;
  116951. }
  116952. static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
  116953. char *z;
  116954. va_list ap;
  116955. int rc;
  116956. va_start(ap, zSql);
  116957. z = sqlite3VMPrintf(db, zSql, ap);
  116958. va_end(ap);
  116959. if( z==0 ) return SQLITE_NOMEM;
  116960. rc = execSql(db, pzErrMsg, z);
  116961. sqlite3DbFree(db, z);
  116962. return rc;
  116963. }
  116964. /*
  116965. ** The VACUUM command is used to clean up the database,
  116966. ** collapse free space, etc. It is modelled after the VACUUM command
  116967. ** in PostgreSQL. The VACUUM command works as follows:
  116968. **
  116969. ** (1) Create a new transient database file
  116970. ** (2) Copy all content from the database being vacuumed into
  116971. ** the new transient database file
  116972. ** (3) Copy content from the transient database back into the
  116973. ** original database.
  116974. **
  116975. ** The transient database requires temporary disk space approximately
  116976. ** equal to the size of the original database. The copy operation of
  116977. ** step (3) requires additional temporary disk space approximately equal
  116978. ** to the size of the original database for the rollback journal.
  116979. ** Hence, temporary disk space that is approximately 2x the size of the
  116980. ** original database is required. Every page of the database is written
  116981. ** approximately 3 times: Once for step (2) and twice for step (3).
  116982. ** Two writes per page are required in step (3) because the original
  116983. ** database content must be written into the rollback journal prior to
  116984. ** overwriting the database with the vacuumed content.
  116985. **
  116986. ** Only 1x temporary space and only 1x writes would be required if
  116987. ** the copy of step (3) were replaced by deleting the original database
  116988. ** and renaming the transient database as the original. But that will
  116989. ** not work if other processes are attached to the original database.
  116990. ** And a power loss in between deleting the original and renaming the
  116991. ** transient would cause the database file to appear to be deleted
  116992. ** following reboot.
  116993. */
  116994. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm){
  116995. Vdbe *v = sqlite3GetVdbe(pParse);
  116996. int iDb = 0;
  116997. if( v==0 ) return;
  116998. if( pNm ){
  116999. #ifndef SQLITE_BUG_COMPATIBLE_20160819
  117000. /* Default behavior: Report an error if the argument to VACUUM is
  117001. ** not recognized */
  117002. iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);
  117003. if( iDb<0 ) return;
  117004. #else
  117005. /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments
  117006. ** to VACUUM are silently ignored. This is a back-out of a bug fix that
  117007. ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
  117008. ** The buggy behavior is required for binary compatibility with some
  117009. ** legacy applications. */
  117010. iDb = sqlite3FindDb(pParse->db, pNm);
  117011. if( iDb<0 ) iDb = 0;
  117012. #endif
  117013. }
  117014. if( iDb!=1 ){
  117015. sqlite3VdbeAddOp1(v, OP_Vacuum, iDb);
  117016. sqlite3VdbeUsesBtree(v, iDb);
  117017. }
  117018. return;
  117019. }
  117020. /*
  117021. ** This routine implements the OP_Vacuum opcode of the VDBE.
  117022. */
  117023. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){
  117024. int rc = SQLITE_OK; /* Return code from service routines */
  117025. Btree *pMain; /* The database being vacuumed */
  117026. Btree *pTemp; /* The temporary database we vacuum into */
  117027. int saved_flags; /* Saved value of the db->flags */
  117028. int saved_nChange; /* Saved value of db->nChange */
  117029. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  117030. u8 saved_mTrace; /* Saved trace settings */
  117031. Db *pDb = 0; /* Database to detach at end of vacuum */
  117032. int isMemDb; /* True if vacuuming a :memory: database */
  117033. int nRes; /* Bytes of reserved space at the end of each page */
  117034. int nDb; /* Number of attached databases */
  117035. const char *zDbMain; /* Schema name of database to vacuum */
  117036. if( !db->autoCommit ){
  117037. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  117038. return SQLITE_ERROR;
  117039. }
  117040. if( db->nVdbeActive>1 ){
  117041. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  117042. return SQLITE_ERROR;
  117043. }
  117044. /* Save the current value of the database flags so that it can be
  117045. ** restored before returning. Then set the writable-schema flag, and
  117046. ** disable CHECK and foreign key constraints. */
  117047. saved_flags = db->flags;
  117048. saved_nChange = db->nChange;
  117049. saved_nTotalChange = db->nTotalChange;
  117050. saved_mTrace = db->mTrace;
  117051. db->flags |= (SQLITE_WriteSchema | SQLITE_IgnoreChecks
  117052. | SQLITE_PreferBuiltin | SQLITE_Vacuum);
  117053. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_CountRows);
  117054. db->mTrace = 0;
  117055. zDbMain = db->aDb[iDb].zDbSName;
  117056. pMain = db->aDb[iDb].pBt;
  117057. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  117058. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  117059. ** can be set to 'off' for this file, as it is not recovered if a crash
  117060. ** occurs anyway. The integrity of the database is maintained by a
  117061. ** (possibly synchronous) transaction opened on the main database before
  117062. ** sqlite3BtreeCopyFile() is called.
  117063. **
  117064. ** An optimisation would be to use a non-journaled pager.
  117065. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  117066. ** that actually made the VACUUM run slower. Very little journalling
  117067. ** actually occurs when doing a vacuum since the vacuum_db is initially
  117068. ** empty. Only the journal header is written. Apparently it takes more
  117069. ** time to parse and run the PRAGMA to turn journalling off than it does
  117070. ** to write the journal header file.
  117071. */
  117072. nDb = db->nDb;
  117073. rc = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db");
  117074. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  117075. assert( (db->nDb-1)==nDb );
  117076. pDb = &db->aDb[nDb];
  117077. assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
  117078. pTemp = pDb->pBt;
  117079. /* The call to execSql() to attach the temp database has left the file
  117080. ** locked (as there was more than one active statement when the transaction
  117081. ** to read the schema was concluded. Unlock it here so that this doesn't
  117082. ** cause problems for the call to BtreeSetPageSize() below. */
  117083. sqlite3BtreeCommit(pTemp);
  117084. nRes = sqlite3BtreeGetOptimalReserve(pMain);
  117085. /* A VACUUM cannot change the pagesize of an encrypted database. */
  117086. #ifdef SQLITE_HAS_CODEC
  117087. if( db->nextPagesize ){
  117088. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  117089. int nKey;
  117090. char *zKey;
  117091. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  117092. if( nKey ) db->nextPagesize = 0;
  117093. }
  117094. #endif
  117095. sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
  117096. sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
  117097. sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);
  117098. /* Begin a transaction and take an exclusive lock on the main database
  117099. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  117100. ** to ensure that we do not try to change the page-size on a WAL database.
  117101. */
  117102. rc = execSql(db, pzErrMsg, "BEGIN");
  117103. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  117104. rc = sqlite3BtreeBeginTrans(pMain, 2);
  117105. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  117106. /* Do not attempt to change the page size for a WAL database */
  117107. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  117108. ==PAGER_JOURNALMODE_WAL ){
  117109. db->nextPagesize = 0;
  117110. }
  117111. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  117112. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  117113. || NEVER(db->mallocFailed)
  117114. ){
  117115. rc = SQLITE_NOMEM_BKPT;
  117116. goto end_of_vacuum;
  117117. }
  117118. #ifndef SQLITE_OMIT_AUTOVACUUM
  117119. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  117120. sqlite3BtreeGetAutoVacuum(pMain));
  117121. #endif
  117122. /* Query the schema of the main database. Create a mirror schema
  117123. ** in the temporary database.
  117124. */
  117125. db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
  117126. rc = execSqlF(db, pzErrMsg,
  117127. "SELECT sql FROM \"%w\".sqlite_master"
  117128. " WHERE type='table'AND name<>'sqlite_sequence'"
  117129. " AND coalesce(rootpage,1)>0",
  117130. zDbMain
  117131. );
  117132. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  117133. rc = execSqlF(db, pzErrMsg,
  117134. "SELECT sql FROM \"%w\".sqlite_master"
  117135. " WHERE type='index' AND length(sql)>10",
  117136. zDbMain
  117137. );
  117138. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  117139. db->init.iDb = 0;
  117140. /* Loop through the tables in the main database. For each, do
  117141. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  117142. ** the contents to the temporary database.
  117143. */
  117144. rc = execSqlF(db, pzErrMsg,
  117145. "SELECT'INSERT INTO vacuum_db.'||quote(name)"
  117146. "||' SELECT*FROM\"%w\".'||quote(name)"
  117147. "FROM vacuum_db.sqlite_master "
  117148. "WHERE type='table'AND coalesce(rootpage,1)>0",
  117149. zDbMain
  117150. );
  117151. assert( (db->flags & SQLITE_Vacuum)!=0 );
  117152. db->flags &= ~SQLITE_Vacuum;
  117153. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  117154. /* Copy the triggers, views, and virtual tables from the main database
  117155. ** over to the temporary database. None of these objects has any
  117156. ** associated storage, so all we have to do is copy their entries
  117157. ** from the SQLITE_MASTER table.
  117158. */
  117159. rc = execSqlF(db, pzErrMsg,
  117160. "INSERT INTO vacuum_db.sqlite_master"
  117161. " SELECT*FROM \"%w\".sqlite_master"
  117162. " WHERE type IN('view','trigger')"
  117163. " OR(type='table'AND rootpage=0)",
  117164. zDbMain
  117165. );
  117166. if( rc ) goto end_of_vacuum;
  117167. /* At this point, there is a write transaction open on both the
  117168. ** vacuum database and the main database. Assuming no error occurs,
  117169. ** both transactions are closed by this block - the main database
  117170. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  117171. ** call to sqlite3BtreeCommit().
  117172. */
  117173. {
  117174. u32 meta;
  117175. int i;
  117176. /* This array determines which meta meta values are preserved in the
  117177. ** vacuum. Even entries are the meta value number and odd entries
  117178. ** are an increment to apply to the meta value after the vacuum.
  117179. ** The increment is used to increase the schema cookie so that other
  117180. ** connections to the same database will know to reread the schema.
  117181. */
  117182. static const unsigned char aCopy[] = {
  117183. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  117184. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  117185. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  117186. BTREE_USER_VERSION, 0, /* Preserve the user version */
  117187. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  117188. };
  117189. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  117190. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  117191. /* Copy Btree meta values */
  117192. for(i=0; i<ArraySize(aCopy); i+=2){
  117193. /* GetMeta() and UpdateMeta() cannot fail in this context because
  117194. ** we already have page 1 loaded into cache and marked dirty. */
  117195. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  117196. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  117197. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  117198. }
  117199. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  117200. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  117201. rc = sqlite3BtreeCommit(pTemp);
  117202. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  117203. #ifndef SQLITE_OMIT_AUTOVACUUM
  117204. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  117205. #endif
  117206. }
  117207. assert( rc==SQLITE_OK );
  117208. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  117209. end_of_vacuum:
  117210. /* Restore the original value of db->flags */
  117211. db->init.iDb = 0;
  117212. db->flags = saved_flags;
  117213. db->nChange = saved_nChange;
  117214. db->nTotalChange = saved_nTotalChange;
  117215. db->mTrace = saved_mTrace;
  117216. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  117217. /* Currently there is an SQL level transaction open on the vacuum
  117218. ** database. No locks are held on any other files (since the main file
  117219. ** was committed at the btree level). So it safe to end the transaction
  117220. ** by manually setting the autoCommit flag to true and detaching the
  117221. ** vacuum database. The vacuum_db journal file is deleted when the pager
  117222. ** is closed by the DETACH.
  117223. */
  117224. db->autoCommit = 1;
  117225. if( pDb ){
  117226. sqlite3BtreeClose(pDb->pBt);
  117227. pDb->pBt = 0;
  117228. pDb->pSchema = 0;
  117229. }
  117230. /* This both clears the schemas and reduces the size of the db->aDb[]
  117231. ** array. */
  117232. sqlite3ResetAllSchemasOfConnection(db);
  117233. return rc;
  117234. }
  117235. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  117236. /************** End of vacuum.c **********************************************/
  117237. /************** Begin file vtab.c ********************************************/
  117238. /*
  117239. ** 2006 June 10
  117240. **
  117241. ** The author disclaims copyright to this source code. In place of
  117242. ** a legal notice, here is a blessing:
  117243. **
  117244. ** May you do good and not evil.
  117245. ** May you find forgiveness for yourself and forgive others.
  117246. ** May you share freely, never taking more than you give.
  117247. **
  117248. *************************************************************************
  117249. ** This file contains code used to help implement virtual tables.
  117250. */
  117251. #ifndef SQLITE_OMIT_VIRTUALTABLE
  117252. /* #include "sqliteInt.h" */
  117253. /*
  117254. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  117255. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  117256. ** this struct allocated on the stack. It is used by the implementation of
  117257. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  117258. ** are invoked only from within xCreate and xConnect methods.
  117259. */
  117260. struct VtabCtx {
  117261. VTable *pVTable; /* The virtual table being constructed */
  117262. Table *pTab; /* The Table object to which the virtual table belongs */
  117263. VtabCtx *pPrior; /* Parent context (if any) */
  117264. int bDeclared; /* True after sqlite3_declare_vtab() is called */
  117265. };
  117266. /*
  117267. ** Construct and install a Module object for a virtual table. When this
  117268. ** routine is called, it is guaranteed that all appropriate locks are held
  117269. ** and the module is not already part of the connection.
  117270. */
  117271. SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
  117272. sqlite3 *db, /* Database in which module is registered */
  117273. const char *zName, /* Name assigned to this module */
  117274. const sqlite3_module *pModule, /* The definition of the module */
  117275. void *pAux, /* Context pointer for xCreate/xConnect */
  117276. void (*xDestroy)(void *) /* Module destructor function */
  117277. ){
  117278. Module *pMod;
  117279. int nName = sqlite3Strlen30(zName);
  117280. pMod = (Module *)sqlite3DbMallocRawNN(db, sizeof(Module) + nName + 1);
  117281. if( pMod ){
  117282. Module *pDel;
  117283. char *zCopy = (char *)(&pMod[1]);
  117284. memcpy(zCopy, zName, nName+1);
  117285. pMod->zName = zCopy;
  117286. pMod->pModule = pModule;
  117287. pMod->pAux = pAux;
  117288. pMod->xDestroy = xDestroy;
  117289. pMod->pEpoTab = 0;
  117290. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
  117291. assert( pDel==0 || pDel==pMod );
  117292. if( pDel ){
  117293. sqlite3OomFault(db);
  117294. sqlite3DbFree(db, pDel);
  117295. pMod = 0;
  117296. }
  117297. }
  117298. return pMod;
  117299. }
  117300. /*
  117301. ** The actual function that does the work of creating a new module.
  117302. ** This function implements the sqlite3_create_module() and
  117303. ** sqlite3_create_module_v2() interfaces.
  117304. */
  117305. static int createModule(
  117306. sqlite3 *db, /* Database in which module is registered */
  117307. const char *zName, /* Name assigned to this module */
  117308. const sqlite3_module *pModule, /* The definition of the module */
  117309. void *pAux, /* Context pointer for xCreate/xConnect */
  117310. void (*xDestroy)(void *) /* Module destructor function */
  117311. ){
  117312. int rc = SQLITE_OK;
  117313. sqlite3_mutex_enter(db->mutex);
  117314. if( sqlite3HashFind(&db->aModule, zName) ){
  117315. rc = SQLITE_MISUSE_BKPT;
  117316. }else{
  117317. (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy);
  117318. }
  117319. rc = sqlite3ApiExit(db, rc);
  117320. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  117321. sqlite3_mutex_leave(db->mutex);
  117322. return rc;
  117323. }
  117324. /*
  117325. ** External API function used to create a new virtual-table module.
  117326. */
  117327. SQLITE_API int sqlite3_create_module(
  117328. sqlite3 *db, /* Database in which module is registered */
  117329. const char *zName, /* Name assigned to this module */
  117330. const sqlite3_module *pModule, /* The definition of the module */
  117331. void *pAux /* Context pointer for xCreate/xConnect */
  117332. ){
  117333. #ifdef SQLITE_ENABLE_API_ARMOR
  117334. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  117335. #endif
  117336. return createModule(db, zName, pModule, pAux, 0);
  117337. }
  117338. /*
  117339. ** External API function used to create a new virtual-table module.
  117340. */
  117341. SQLITE_API int sqlite3_create_module_v2(
  117342. sqlite3 *db, /* Database in which module is registered */
  117343. const char *zName, /* Name assigned to this module */
  117344. const sqlite3_module *pModule, /* The definition of the module */
  117345. void *pAux, /* Context pointer for xCreate/xConnect */
  117346. void (*xDestroy)(void *) /* Module destructor function */
  117347. ){
  117348. #ifdef SQLITE_ENABLE_API_ARMOR
  117349. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  117350. #endif
  117351. return createModule(db, zName, pModule, pAux, xDestroy);
  117352. }
  117353. /*
  117354. ** Lock the virtual table so that it cannot be disconnected.
  117355. ** Locks nest. Every lock should have a corresponding unlock.
  117356. ** If an unlock is omitted, resources leaks will occur.
  117357. **
  117358. ** If a disconnect is attempted while a virtual table is locked,
  117359. ** the disconnect is deferred until all locks have been removed.
  117360. */
  117361. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  117362. pVTab->nRef++;
  117363. }
  117364. /*
  117365. ** pTab is a pointer to a Table structure representing a virtual-table.
  117366. ** Return a pointer to the VTable object used by connection db to access
  117367. ** this virtual-table, if one has been created, or NULL otherwise.
  117368. */
  117369. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  117370. VTable *pVtab;
  117371. assert( IsVirtual(pTab) );
  117372. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  117373. return pVtab;
  117374. }
  117375. /*
  117376. ** Decrement the ref-count on a virtual table object. When the ref-count
  117377. ** reaches zero, call the xDisconnect() method to delete the object.
  117378. */
  117379. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  117380. sqlite3 *db = pVTab->db;
  117381. assert( db );
  117382. assert( pVTab->nRef>0 );
  117383. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  117384. pVTab->nRef--;
  117385. if( pVTab->nRef==0 ){
  117386. sqlite3_vtab *p = pVTab->pVtab;
  117387. if( p ){
  117388. p->pModule->xDisconnect(p);
  117389. }
  117390. sqlite3DbFree(db, pVTab);
  117391. }
  117392. }
  117393. /*
  117394. ** Table p is a virtual table. This function moves all elements in the
  117395. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  117396. ** database connections to be disconnected at the next opportunity.
  117397. ** Except, if argument db is not NULL, then the entry associated with
  117398. ** connection db is left in the p->pVTable list.
  117399. */
  117400. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  117401. VTable *pRet = 0;
  117402. VTable *pVTable = p->pVTable;
  117403. p->pVTable = 0;
  117404. /* Assert that the mutex (if any) associated with the BtShared database
  117405. ** that contains table p is held by the caller. See header comments
  117406. ** above function sqlite3VtabUnlockList() for an explanation of why
  117407. ** this makes it safe to access the sqlite3.pDisconnect list of any
  117408. ** database connection that may have an entry in the p->pVTable list.
  117409. */
  117410. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  117411. while( pVTable ){
  117412. sqlite3 *db2 = pVTable->db;
  117413. VTable *pNext = pVTable->pNext;
  117414. assert( db2 );
  117415. if( db2==db ){
  117416. pRet = pVTable;
  117417. p->pVTable = pRet;
  117418. pRet->pNext = 0;
  117419. }else{
  117420. pVTable->pNext = db2->pDisconnect;
  117421. db2->pDisconnect = pVTable;
  117422. }
  117423. pVTable = pNext;
  117424. }
  117425. assert( !db || pRet );
  117426. return pRet;
  117427. }
  117428. /*
  117429. ** Table *p is a virtual table. This function removes the VTable object
  117430. ** for table *p associated with database connection db from the linked
  117431. ** list in p->pVTab. It also decrements the VTable ref count. This is
  117432. ** used when closing database connection db to free all of its VTable
  117433. ** objects without disturbing the rest of the Schema object (which may
  117434. ** be being used by other shared-cache connections).
  117435. */
  117436. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  117437. VTable **ppVTab;
  117438. assert( IsVirtual(p) );
  117439. assert( sqlite3BtreeHoldsAllMutexes(db) );
  117440. assert( sqlite3_mutex_held(db->mutex) );
  117441. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  117442. if( (*ppVTab)->db==db ){
  117443. VTable *pVTab = *ppVTab;
  117444. *ppVTab = pVTab->pNext;
  117445. sqlite3VtabUnlock(pVTab);
  117446. break;
  117447. }
  117448. }
  117449. }
  117450. /*
  117451. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  117452. **
  117453. ** This function may only be called when the mutexes associated with all
  117454. ** shared b-tree databases opened using connection db are held by the
  117455. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  117456. ** sqlite3.pDisconnect list is accessed only as follows:
  117457. **
  117458. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  117459. ** associated with the database handle itself must be held.
  117460. **
  117461. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  117462. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  117463. ** associated with the database the virtual table is stored in is held
  117464. ** or, if the virtual table is stored in a non-sharable database, then
  117465. ** the database handle mutex is held.
  117466. **
  117467. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  117468. ** by multiple threads. It is thread-safe.
  117469. */
  117470. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  117471. VTable *p = db->pDisconnect;
  117472. db->pDisconnect = 0;
  117473. assert( sqlite3BtreeHoldsAllMutexes(db) );
  117474. assert( sqlite3_mutex_held(db->mutex) );
  117475. if( p ){
  117476. sqlite3ExpirePreparedStatements(db);
  117477. do {
  117478. VTable *pNext = p->pNext;
  117479. sqlite3VtabUnlock(p);
  117480. p = pNext;
  117481. }while( p );
  117482. }
  117483. }
  117484. /*
  117485. ** Clear any and all virtual-table information from the Table record.
  117486. ** This routine is called, for example, just before deleting the Table
  117487. ** record.
  117488. **
  117489. ** Since it is a virtual-table, the Table structure contains a pointer
  117490. ** to the head of a linked list of VTable structures. Each VTable
  117491. ** structure is associated with a single sqlite3* user of the schema.
  117492. ** The reference count of the VTable structure associated with database
  117493. ** connection db is decremented immediately (which may lead to the
  117494. ** structure being xDisconnected and free). Any other VTable structures
  117495. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  117496. ** database connection.
  117497. */
  117498. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  117499. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  117500. if( p->azModuleArg ){
  117501. int i;
  117502. for(i=0; i<p->nModuleArg; i++){
  117503. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  117504. }
  117505. sqlite3DbFree(db, p->azModuleArg);
  117506. }
  117507. }
  117508. /*
  117509. ** Add a new module argument to pTable->azModuleArg[].
  117510. ** The string is not copied - the pointer is stored. The
  117511. ** string will be freed automatically when the table is
  117512. ** deleted.
  117513. */
  117514. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  117515. int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
  117516. char **azModuleArg;
  117517. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  117518. if( azModuleArg==0 ){
  117519. sqlite3DbFree(db, zArg);
  117520. }else{
  117521. int i = pTable->nModuleArg++;
  117522. azModuleArg[i] = zArg;
  117523. azModuleArg[i+1] = 0;
  117524. pTable->azModuleArg = azModuleArg;
  117525. }
  117526. }
  117527. /*
  117528. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  117529. ** statement. The module name has been parsed, but the optional list
  117530. ** of parameters that follow the module name are still pending.
  117531. */
  117532. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  117533. Parse *pParse, /* Parsing context */
  117534. Token *pName1, /* Name of new table, or database name */
  117535. Token *pName2, /* Name of new table or NULL */
  117536. Token *pModuleName, /* Name of the module for the virtual table */
  117537. int ifNotExists /* No error if the table already exists */
  117538. ){
  117539. int iDb; /* The database the table is being created in */
  117540. Table *pTable; /* The new virtual table */
  117541. sqlite3 *db; /* Database connection */
  117542. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  117543. pTable = pParse->pNewTable;
  117544. if( pTable==0 ) return;
  117545. assert( 0==pTable->pIndex );
  117546. db = pParse->db;
  117547. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  117548. assert( iDb>=0 );
  117549. assert( pTable->nModuleArg==0 );
  117550. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  117551. addModuleArgument(db, pTable, 0);
  117552. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  117553. assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
  117554. || (pParse->sNameToken.z==pName1->z && pName2->z==0)
  117555. );
  117556. pParse->sNameToken.n = (int)(
  117557. &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
  117558. );
  117559. #ifndef SQLITE_OMIT_AUTHORIZATION
  117560. /* Creating a virtual table invokes the authorization callback twice.
  117561. ** The first invocation, to obtain permission to INSERT a row into the
  117562. ** sqlite_master table, has already been made by sqlite3StartTable().
  117563. ** The second call, to obtain permission to create the table, is made now.
  117564. */
  117565. if( pTable->azModuleArg ){
  117566. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  117567. pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
  117568. }
  117569. #endif
  117570. }
  117571. /*
  117572. ** This routine takes the module argument that has been accumulating
  117573. ** in pParse->zArg[] and appends it to the list of arguments on the
  117574. ** virtual table currently under construction in pParse->pTable.
  117575. */
  117576. static void addArgumentToVtab(Parse *pParse){
  117577. if( pParse->sArg.z && pParse->pNewTable ){
  117578. const char *z = (const char*)pParse->sArg.z;
  117579. int n = pParse->sArg.n;
  117580. sqlite3 *db = pParse->db;
  117581. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  117582. }
  117583. }
  117584. /*
  117585. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  117586. ** has been completely parsed.
  117587. */
  117588. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  117589. Table *pTab = pParse->pNewTable; /* The table being constructed */
  117590. sqlite3 *db = pParse->db; /* The database connection */
  117591. if( pTab==0 ) return;
  117592. addArgumentToVtab(pParse);
  117593. pParse->sArg.z = 0;
  117594. if( pTab->nModuleArg<1 ) return;
  117595. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  117596. ** first time (in other words if the virtual table is actually being
  117597. ** created now instead of just being read out of sqlite_master) then
  117598. ** do additional initialization work and store the statement text
  117599. ** in the sqlite_master table.
  117600. */
  117601. if( !db->init.busy ){
  117602. char *zStmt;
  117603. char *zWhere;
  117604. int iDb;
  117605. int iReg;
  117606. Vdbe *v;
  117607. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  117608. if( pEnd ){
  117609. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  117610. }
  117611. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  117612. /* A slot for the record has already been allocated in the
  117613. ** SQLITE_MASTER table. We just need to update that slot with all
  117614. ** the information we've collected.
  117615. **
  117616. ** The VM register number pParse->regRowid holds the rowid of an
  117617. ** entry in the sqlite_master table tht was created for this vtab
  117618. ** by sqlite3StartTable().
  117619. */
  117620. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  117621. sqlite3NestedParse(pParse,
  117622. "UPDATE %Q.%s "
  117623. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  117624. "WHERE rowid=#%d",
  117625. db->aDb[iDb].zDbSName, MASTER_NAME,
  117626. pTab->zName,
  117627. pTab->zName,
  117628. zStmt,
  117629. pParse->regRowid
  117630. );
  117631. sqlite3DbFree(db, zStmt);
  117632. v = sqlite3GetVdbe(pParse);
  117633. sqlite3ChangeCookie(pParse, iDb);
  117634. sqlite3VdbeAddOp0(v, OP_Expire);
  117635. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  117636. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  117637. iReg = ++pParse->nMem;
  117638. sqlite3VdbeLoadString(v, iReg, pTab->zName);
  117639. sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
  117640. }
  117641. /* If we are rereading the sqlite_master table create the in-memory
  117642. ** record of the table. The xConnect() method is not called until
  117643. ** the first time the virtual table is used in an SQL statement. This
  117644. ** allows a schema that contains virtual tables to be loaded before
  117645. ** the required virtual table implementations are registered. */
  117646. else {
  117647. Table *pOld;
  117648. Schema *pSchema = pTab->pSchema;
  117649. const char *zName = pTab->zName;
  117650. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  117651. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
  117652. if( pOld ){
  117653. sqlite3OomFault(db);
  117654. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  117655. return;
  117656. }
  117657. pParse->pNewTable = 0;
  117658. }
  117659. }
  117660. /*
  117661. ** The parser calls this routine when it sees the first token
  117662. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  117663. */
  117664. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  117665. addArgumentToVtab(pParse);
  117666. pParse->sArg.z = 0;
  117667. pParse->sArg.n = 0;
  117668. }
  117669. /*
  117670. ** The parser calls this routine for each token after the first token
  117671. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  117672. */
  117673. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  117674. Token *pArg = &pParse->sArg;
  117675. if( pArg->z==0 ){
  117676. pArg->z = p->z;
  117677. pArg->n = p->n;
  117678. }else{
  117679. assert(pArg->z <= p->z);
  117680. pArg->n = (int)(&p->z[p->n] - pArg->z);
  117681. }
  117682. }
  117683. /*
  117684. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  117685. ** pointer to the function to invoke is passed as the fourth parameter
  117686. ** to this procedure.
  117687. */
  117688. static int vtabCallConstructor(
  117689. sqlite3 *db,
  117690. Table *pTab,
  117691. Module *pMod,
  117692. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  117693. char **pzErr
  117694. ){
  117695. VtabCtx sCtx;
  117696. VTable *pVTable;
  117697. int rc;
  117698. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  117699. int nArg = pTab->nModuleArg;
  117700. char *zErr = 0;
  117701. char *zModuleName;
  117702. int iDb;
  117703. VtabCtx *pCtx;
  117704. /* Check that the virtual-table is not already being initialized */
  117705. for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
  117706. if( pCtx->pTab==pTab ){
  117707. *pzErr = sqlite3MPrintf(db,
  117708. "vtable constructor called recursively: %s", pTab->zName
  117709. );
  117710. return SQLITE_LOCKED;
  117711. }
  117712. }
  117713. zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  117714. if( !zModuleName ){
  117715. return SQLITE_NOMEM_BKPT;
  117716. }
  117717. pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  117718. if( !pVTable ){
  117719. sqlite3DbFree(db, zModuleName);
  117720. return SQLITE_NOMEM_BKPT;
  117721. }
  117722. pVTable->db = db;
  117723. pVTable->pMod = pMod;
  117724. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  117725. pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
  117726. /* Invoke the virtual table constructor */
  117727. assert( &db->pVtabCtx );
  117728. assert( xConstruct );
  117729. sCtx.pTab = pTab;
  117730. sCtx.pVTable = pVTable;
  117731. sCtx.pPrior = db->pVtabCtx;
  117732. sCtx.bDeclared = 0;
  117733. db->pVtabCtx = &sCtx;
  117734. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  117735. db->pVtabCtx = sCtx.pPrior;
  117736. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  117737. assert( sCtx.pTab==pTab );
  117738. if( SQLITE_OK!=rc ){
  117739. if( zErr==0 ){
  117740. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  117741. }else {
  117742. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  117743. sqlite3_free(zErr);
  117744. }
  117745. sqlite3DbFree(db, pVTable);
  117746. }else if( ALWAYS(pVTable->pVtab) ){
  117747. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  117748. ** the sqlite3_vtab object if successful. */
  117749. memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
  117750. pVTable->pVtab->pModule = pMod->pModule;
  117751. pVTable->nRef = 1;
  117752. if( sCtx.bDeclared==0 ){
  117753. const char *zFormat = "vtable constructor did not declare schema: %s";
  117754. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  117755. sqlite3VtabUnlock(pVTable);
  117756. rc = SQLITE_ERROR;
  117757. }else{
  117758. int iCol;
  117759. u8 oooHidden = 0;
  117760. /* If everything went according to plan, link the new VTable structure
  117761. ** into the linked list headed by pTab->pVTable. Then loop through the
  117762. ** columns of the table to see if any of them contain the token "hidden".
  117763. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  117764. ** the type string. */
  117765. pVTable->pNext = pTab->pVTable;
  117766. pTab->pVTable = pVTable;
  117767. for(iCol=0; iCol<pTab->nCol; iCol++){
  117768. char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
  117769. int nType;
  117770. int i = 0;
  117771. nType = sqlite3Strlen30(zType);
  117772. for(i=0; i<nType; i++){
  117773. if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
  117774. && (i==0 || zType[i-1]==' ')
  117775. && (zType[i+6]=='\0' || zType[i+6]==' ')
  117776. ){
  117777. break;
  117778. }
  117779. }
  117780. if( i<nType ){
  117781. int j;
  117782. int nDel = 6 + (zType[i+6] ? 1 : 0);
  117783. for(j=i; (j+nDel)<=nType; j++){
  117784. zType[j] = zType[j+nDel];
  117785. }
  117786. if( zType[i]=='\0' && i>0 ){
  117787. assert(zType[i-1]==' ');
  117788. zType[i-1] = '\0';
  117789. }
  117790. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  117791. oooHidden = TF_OOOHidden;
  117792. }else{
  117793. pTab->tabFlags |= oooHidden;
  117794. }
  117795. }
  117796. }
  117797. }
  117798. sqlite3DbFree(db, zModuleName);
  117799. return rc;
  117800. }
  117801. /*
  117802. ** This function is invoked by the parser to call the xConnect() method
  117803. ** of the virtual table pTab. If an error occurs, an error code is returned
  117804. ** and an error left in pParse.
  117805. **
  117806. ** This call is a no-op if table pTab is not a virtual table.
  117807. */
  117808. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  117809. sqlite3 *db = pParse->db;
  117810. const char *zMod;
  117811. Module *pMod;
  117812. int rc;
  117813. assert( pTab );
  117814. if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){
  117815. return SQLITE_OK;
  117816. }
  117817. /* Locate the required virtual table module */
  117818. zMod = pTab->azModuleArg[0];
  117819. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  117820. if( !pMod ){
  117821. const char *zModule = pTab->azModuleArg[0];
  117822. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  117823. rc = SQLITE_ERROR;
  117824. }else{
  117825. char *zErr = 0;
  117826. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  117827. if( rc!=SQLITE_OK ){
  117828. sqlite3ErrorMsg(pParse, "%s", zErr);
  117829. }
  117830. sqlite3DbFree(db, zErr);
  117831. }
  117832. return rc;
  117833. }
  117834. /*
  117835. ** Grow the db->aVTrans[] array so that there is room for at least one
  117836. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  117837. */
  117838. static int growVTrans(sqlite3 *db){
  117839. const int ARRAY_INCR = 5;
  117840. /* Grow the sqlite3.aVTrans array if required */
  117841. if( (db->nVTrans%ARRAY_INCR)==0 ){
  117842. VTable **aVTrans;
  117843. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  117844. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  117845. if( !aVTrans ){
  117846. return SQLITE_NOMEM_BKPT;
  117847. }
  117848. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  117849. db->aVTrans = aVTrans;
  117850. }
  117851. return SQLITE_OK;
  117852. }
  117853. /*
  117854. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  117855. ** have already been reserved using growVTrans().
  117856. */
  117857. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  117858. /* Add pVtab to the end of sqlite3.aVTrans */
  117859. db->aVTrans[db->nVTrans++] = pVTab;
  117860. sqlite3VtabLock(pVTab);
  117861. }
  117862. /*
  117863. ** This function is invoked by the vdbe to call the xCreate method
  117864. ** of the virtual table named zTab in database iDb.
  117865. **
  117866. ** If an error occurs, *pzErr is set to point to an English language
  117867. ** description of the error and an SQLITE_XXX error code is returned.
  117868. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  117869. */
  117870. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  117871. int rc = SQLITE_OK;
  117872. Table *pTab;
  117873. Module *pMod;
  117874. const char *zMod;
  117875. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
  117876. assert( pTab && IsVirtual(pTab) && !pTab->pVTable );
  117877. /* Locate the required virtual table module */
  117878. zMod = pTab->azModuleArg[0];
  117879. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  117880. /* If the module has been registered and includes a Create method,
  117881. ** invoke it now. If the module has not been registered, return an
  117882. ** error. Otherwise, do nothing.
  117883. */
  117884. if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
  117885. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  117886. rc = SQLITE_ERROR;
  117887. }else{
  117888. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  117889. }
  117890. /* Justification of ALWAYS(): The xConstructor method is required to
  117891. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  117892. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  117893. rc = growVTrans(db);
  117894. if( rc==SQLITE_OK ){
  117895. addToVTrans(db, sqlite3GetVTable(db, pTab));
  117896. }
  117897. }
  117898. return rc;
  117899. }
  117900. /*
  117901. ** This function is used to set the schema of a virtual table. It is only
  117902. ** valid to call this function from within the xCreate() or xConnect() of a
  117903. ** virtual table module.
  117904. */
  117905. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  117906. VtabCtx *pCtx;
  117907. Parse *pParse;
  117908. int rc = SQLITE_OK;
  117909. Table *pTab;
  117910. char *zErr = 0;
  117911. #ifdef SQLITE_ENABLE_API_ARMOR
  117912. if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
  117913. return SQLITE_MISUSE_BKPT;
  117914. }
  117915. #endif
  117916. sqlite3_mutex_enter(db->mutex);
  117917. pCtx = db->pVtabCtx;
  117918. if( !pCtx || pCtx->bDeclared ){
  117919. sqlite3Error(db, SQLITE_MISUSE);
  117920. sqlite3_mutex_leave(db->mutex);
  117921. return SQLITE_MISUSE_BKPT;
  117922. }
  117923. pTab = pCtx->pTab;
  117924. assert( IsVirtual(pTab) );
  117925. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  117926. if( pParse==0 ){
  117927. rc = SQLITE_NOMEM_BKPT;
  117928. }else{
  117929. pParse->declareVtab = 1;
  117930. pParse->db = db;
  117931. pParse->nQueryLoop = 1;
  117932. if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
  117933. && pParse->pNewTable
  117934. && !db->mallocFailed
  117935. && !pParse->pNewTable->pSelect
  117936. && !IsVirtual(pParse->pNewTable)
  117937. ){
  117938. if( !pTab->aCol ){
  117939. Table *pNew = pParse->pNewTable;
  117940. Index *pIdx;
  117941. pTab->aCol = pNew->aCol;
  117942. pTab->nCol = pNew->nCol;
  117943. pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
  117944. pNew->nCol = 0;
  117945. pNew->aCol = 0;
  117946. assert( pTab->pIndex==0 );
  117947. if( !HasRowid(pNew) && pCtx->pVTable->pMod->pModule->xUpdate!=0 ){
  117948. rc = SQLITE_ERROR;
  117949. }
  117950. pIdx = pNew->pIndex;
  117951. if( pIdx ){
  117952. assert( pIdx->pNext==0 );
  117953. pTab->pIndex = pIdx;
  117954. pNew->pIndex = 0;
  117955. pIdx->pTable = pTab;
  117956. }
  117957. }
  117958. pCtx->bDeclared = 1;
  117959. }else{
  117960. sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  117961. sqlite3DbFree(db, zErr);
  117962. rc = SQLITE_ERROR;
  117963. }
  117964. pParse->declareVtab = 0;
  117965. if( pParse->pVdbe ){
  117966. sqlite3VdbeFinalize(pParse->pVdbe);
  117967. }
  117968. sqlite3DeleteTable(db, pParse->pNewTable);
  117969. sqlite3ParserReset(pParse);
  117970. sqlite3StackFree(db, pParse);
  117971. }
  117972. assert( (rc&0xff)==rc );
  117973. rc = sqlite3ApiExit(db, rc);
  117974. sqlite3_mutex_leave(db->mutex);
  117975. return rc;
  117976. }
  117977. /*
  117978. ** This function is invoked by the vdbe to call the xDestroy method
  117979. ** of the virtual table named zTab in database iDb. This occurs
  117980. ** when a DROP TABLE is mentioned.
  117981. **
  117982. ** This call is a no-op if zTab is not a virtual table.
  117983. */
  117984. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  117985. int rc = SQLITE_OK;
  117986. Table *pTab;
  117987. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
  117988. if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
  117989. VTable *p;
  117990. int (*xDestroy)(sqlite3_vtab *);
  117991. for(p=pTab->pVTable; p; p=p->pNext){
  117992. assert( p->pVtab );
  117993. if( p->pVtab->nRef>0 ){
  117994. return SQLITE_LOCKED;
  117995. }
  117996. }
  117997. p = vtabDisconnectAll(db, pTab);
  117998. xDestroy = p->pMod->pModule->xDestroy;
  117999. assert( xDestroy!=0 ); /* Checked before the virtual table is created */
  118000. rc = xDestroy(p->pVtab);
  118001. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  118002. if( rc==SQLITE_OK ){
  118003. assert( pTab->pVTable==p && p->pNext==0 );
  118004. p->pVtab = 0;
  118005. pTab->pVTable = 0;
  118006. sqlite3VtabUnlock(p);
  118007. }
  118008. }
  118009. return rc;
  118010. }
  118011. /*
  118012. ** This function invokes either the xRollback or xCommit method
  118013. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  118014. ** called is identified by the second argument, "offset", which is
  118015. ** the offset of the method to call in the sqlite3_module structure.
  118016. **
  118017. ** The array is cleared after invoking the callbacks.
  118018. */
  118019. static void callFinaliser(sqlite3 *db, int offset){
  118020. int i;
  118021. if( db->aVTrans ){
  118022. VTable **aVTrans = db->aVTrans;
  118023. db->aVTrans = 0;
  118024. for(i=0; i<db->nVTrans; i++){
  118025. VTable *pVTab = aVTrans[i];
  118026. sqlite3_vtab *p = pVTab->pVtab;
  118027. if( p ){
  118028. int (*x)(sqlite3_vtab *);
  118029. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  118030. if( x ) x(p);
  118031. }
  118032. pVTab->iSavepoint = 0;
  118033. sqlite3VtabUnlock(pVTab);
  118034. }
  118035. sqlite3DbFree(db, aVTrans);
  118036. db->nVTrans = 0;
  118037. }
  118038. }
  118039. /*
  118040. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  118041. ** array. Return the error code for the first error that occurs, or
  118042. ** SQLITE_OK if all xSync operations are successful.
  118043. **
  118044. ** If an error message is available, leave it in p->zErrMsg.
  118045. */
  118046. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  118047. int i;
  118048. int rc = SQLITE_OK;
  118049. VTable **aVTrans = db->aVTrans;
  118050. db->aVTrans = 0;
  118051. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  118052. int (*x)(sqlite3_vtab *);
  118053. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  118054. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  118055. rc = x(pVtab);
  118056. sqlite3VtabImportErrmsg(p, pVtab);
  118057. }
  118058. }
  118059. db->aVTrans = aVTrans;
  118060. return rc;
  118061. }
  118062. /*
  118063. ** Invoke the xRollback method of all virtual tables in the
  118064. ** sqlite3.aVTrans array. Then clear the array itself.
  118065. */
  118066. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  118067. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  118068. return SQLITE_OK;
  118069. }
  118070. /*
  118071. ** Invoke the xCommit method of all virtual tables in the
  118072. ** sqlite3.aVTrans array. Then clear the array itself.
  118073. */
  118074. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  118075. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  118076. return SQLITE_OK;
  118077. }
  118078. /*
  118079. ** If the virtual table pVtab supports the transaction interface
  118080. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  118081. ** not currently open, invoke the xBegin method now.
  118082. **
  118083. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  118084. ** in the sqlite3.aVTrans array.
  118085. */
  118086. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  118087. int rc = SQLITE_OK;
  118088. const sqlite3_module *pModule;
  118089. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  118090. ** than zero, then this function is being called from within a
  118091. ** virtual module xSync() callback. It is illegal to write to
  118092. ** virtual module tables in this case, so return SQLITE_LOCKED.
  118093. */
  118094. if( sqlite3VtabInSync(db) ){
  118095. return SQLITE_LOCKED;
  118096. }
  118097. if( !pVTab ){
  118098. return SQLITE_OK;
  118099. }
  118100. pModule = pVTab->pVtab->pModule;
  118101. if( pModule->xBegin ){
  118102. int i;
  118103. /* If pVtab is already in the aVTrans array, return early */
  118104. for(i=0; i<db->nVTrans; i++){
  118105. if( db->aVTrans[i]==pVTab ){
  118106. return SQLITE_OK;
  118107. }
  118108. }
  118109. /* Invoke the xBegin method. If successful, add the vtab to the
  118110. ** sqlite3.aVTrans[] array. */
  118111. rc = growVTrans(db);
  118112. if( rc==SQLITE_OK ){
  118113. rc = pModule->xBegin(pVTab->pVtab);
  118114. if( rc==SQLITE_OK ){
  118115. int iSvpt = db->nStatement + db->nSavepoint;
  118116. addToVTrans(db, pVTab);
  118117. if( iSvpt && pModule->xSavepoint ){
  118118. pVTab->iSavepoint = iSvpt;
  118119. rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
  118120. }
  118121. }
  118122. }
  118123. }
  118124. return rc;
  118125. }
  118126. /*
  118127. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  118128. ** virtual tables that currently have an open transaction. Pass iSavepoint
  118129. ** as the second argument to the virtual table method invoked.
  118130. **
  118131. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  118132. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  118133. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  118134. ** an open transaction is invoked.
  118135. **
  118136. ** If any virtual table method returns an error code other than SQLITE_OK,
  118137. ** processing is abandoned and the error returned to the caller of this
  118138. ** function immediately. If all calls to virtual table methods are successful,
  118139. ** SQLITE_OK is returned.
  118140. */
  118141. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  118142. int rc = SQLITE_OK;
  118143. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  118144. assert( iSavepoint>=-1 );
  118145. if( db->aVTrans ){
  118146. int i;
  118147. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  118148. VTable *pVTab = db->aVTrans[i];
  118149. const sqlite3_module *pMod = pVTab->pMod->pModule;
  118150. if( pVTab->pVtab && pMod->iVersion>=2 ){
  118151. int (*xMethod)(sqlite3_vtab *, int);
  118152. switch( op ){
  118153. case SAVEPOINT_BEGIN:
  118154. xMethod = pMod->xSavepoint;
  118155. pVTab->iSavepoint = iSavepoint+1;
  118156. break;
  118157. case SAVEPOINT_ROLLBACK:
  118158. xMethod = pMod->xRollbackTo;
  118159. break;
  118160. default:
  118161. xMethod = pMod->xRelease;
  118162. break;
  118163. }
  118164. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  118165. rc = xMethod(pVTab->pVtab, iSavepoint);
  118166. }
  118167. }
  118168. }
  118169. }
  118170. return rc;
  118171. }
  118172. /*
  118173. ** The first parameter (pDef) is a function implementation. The
  118174. ** second parameter (pExpr) is the first argument to this function.
  118175. ** If pExpr is a column in a virtual table, then let the virtual
  118176. ** table implementation have an opportunity to overload the function.
  118177. **
  118178. ** This routine is used to allow virtual table implementations to
  118179. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  118180. **
  118181. ** Return either the pDef argument (indicating no change) or a
  118182. ** new FuncDef structure that is marked as ephemeral using the
  118183. ** SQLITE_FUNC_EPHEM flag.
  118184. */
  118185. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  118186. sqlite3 *db, /* Database connection for reporting malloc problems */
  118187. FuncDef *pDef, /* Function to possibly overload */
  118188. int nArg, /* Number of arguments to the function */
  118189. Expr *pExpr /* First argument to the function */
  118190. ){
  118191. Table *pTab;
  118192. sqlite3_vtab *pVtab;
  118193. sqlite3_module *pMod;
  118194. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  118195. void *pArg = 0;
  118196. FuncDef *pNew;
  118197. int rc = 0;
  118198. char *zLowerName;
  118199. unsigned char *z;
  118200. /* Check to see the left operand is a column in a virtual table */
  118201. if( NEVER(pExpr==0) ) return pDef;
  118202. if( pExpr->op!=TK_COLUMN ) return pDef;
  118203. pTab = pExpr->pTab;
  118204. if( pTab==0 ) return pDef;
  118205. if( !IsVirtual(pTab) ) return pDef;
  118206. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  118207. assert( pVtab!=0 );
  118208. assert( pVtab->pModule!=0 );
  118209. pMod = (sqlite3_module *)pVtab->pModule;
  118210. if( pMod->xFindFunction==0 ) return pDef;
  118211. /* Call the xFindFunction method on the virtual table implementation
  118212. ** to see if the implementation wants to overload this function
  118213. */
  118214. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  118215. if( zLowerName ){
  118216. for(z=(unsigned char*)zLowerName; *z; z++){
  118217. *z = sqlite3UpperToLower[*z];
  118218. }
  118219. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg);
  118220. sqlite3DbFree(db, zLowerName);
  118221. }
  118222. if( rc==0 ){
  118223. return pDef;
  118224. }
  118225. /* Create a new ephemeral function definition for the overloaded
  118226. ** function */
  118227. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  118228. + sqlite3Strlen30(pDef->zName) + 1);
  118229. if( pNew==0 ){
  118230. return pDef;
  118231. }
  118232. *pNew = *pDef;
  118233. pNew->zName = (const char*)&pNew[1];
  118234. memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  118235. pNew->xSFunc = xSFunc;
  118236. pNew->pUserData = pArg;
  118237. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  118238. return pNew;
  118239. }
  118240. /*
  118241. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  118242. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  118243. ** array if it is missing. If pTab is already in the array, this routine
  118244. ** is a no-op.
  118245. */
  118246. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  118247. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  118248. int i, n;
  118249. Table **apVtabLock;
  118250. assert( IsVirtual(pTab) );
  118251. for(i=0; i<pToplevel->nVtabLock; i++){
  118252. if( pTab==pToplevel->apVtabLock[i] ) return;
  118253. }
  118254. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  118255. apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
  118256. if( apVtabLock ){
  118257. pToplevel->apVtabLock = apVtabLock;
  118258. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  118259. }else{
  118260. sqlite3OomFault(pToplevel->db);
  118261. }
  118262. }
  118263. /*
  118264. ** Check to see if virtual table module pMod can be have an eponymous
  118265. ** virtual table instance. If it can, create one if one does not already
  118266. ** exist. Return non-zero if the eponymous virtual table instance exists
  118267. ** when this routine returns, and return zero if it does not exist.
  118268. **
  118269. ** An eponymous virtual table instance is one that is named after its
  118270. ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
  118271. ** statement in order to come into existance. Eponymous virtual table
  118272. ** instances always exist. They cannot be DROP-ed.
  118273. **
  118274. ** Any virtual table module for which xConnect and xCreate are the same
  118275. ** method can have an eponymous virtual table instance.
  118276. */
  118277. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
  118278. const sqlite3_module *pModule = pMod->pModule;
  118279. Table *pTab;
  118280. char *zErr = 0;
  118281. int rc;
  118282. sqlite3 *db = pParse->db;
  118283. if( pMod->pEpoTab ) return 1;
  118284. if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
  118285. pTab = sqlite3DbMallocZero(db, sizeof(Table));
  118286. if( pTab==0 ) return 0;
  118287. pTab->zName = sqlite3DbStrDup(db, pMod->zName);
  118288. if( pTab->zName==0 ){
  118289. sqlite3DbFree(db, pTab);
  118290. return 0;
  118291. }
  118292. pMod->pEpoTab = pTab;
  118293. pTab->nTabRef = 1;
  118294. pTab->pSchema = db->aDb[0].pSchema;
  118295. assert( pTab->nModuleArg==0 );
  118296. pTab->iPKey = -1;
  118297. addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
  118298. addModuleArgument(db, pTab, 0);
  118299. addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
  118300. rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
  118301. if( rc ){
  118302. sqlite3ErrorMsg(pParse, "%s", zErr);
  118303. sqlite3DbFree(db, zErr);
  118304. sqlite3VtabEponymousTableClear(db, pMod);
  118305. return 0;
  118306. }
  118307. return 1;
  118308. }
  118309. /*
  118310. ** Erase the eponymous virtual table instance associated with
  118311. ** virtual table module pMod, if it exists.
  118312. */
  118313. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
  118314. Table *pTab = pMod->pEpoTab;
  118315. if( pTab!=0 ){
  118316. /* Mark the table as Ephemeral prior to deleting it, so that the
  118317. ** sqlite3DeleteTable() routine will know that it is not stored in
  118318. ** the schema. */
  118319. pTab->tabFlags |= TF_Ephemeral;
  118320. sqlite3DeleteTable(db, pTab);
  118321. pMod->pEpoTab = 0;
  118322. }
  118323. }
  118324. /*
  118325. ** Return the ON CONFLICT resolution mode in effect for the virtual
  118326. ** table update operation currently in progress.
  118327. **
  118328. ** The results of this routine are undefined unless it is called from
  118329. ** within an xUpdate method.
  118330. */
  118331. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
  118332. static const unsigned char aMap[] = {
  118333. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  118334. };
  118335. #ifdef SQLITE_ENABLE_API_ARMOR
  118336. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  118337. #endif
  118338. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  118339. assert( OE_Ignore==4 && OE_Replace==5 );
  118340. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  118341. return (int)aMap[db->vtabOnConflict-1];
  118342. }
  118343. /*
  118344. ** Call from within the xCreate() or xConnect() methods to provide
  118345. ** the SQLite core with additional information about the behavior
  118346. ** of the virtual table being implemented.
  118347. */
  118348. SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
  118349. va_list ap;
  118350. int rc = SQLITE_OK;
  118351. #ifdef SQLITE_ENABLE_API_ARMOR
  118352. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  118353. #endif
  118354. sqlite3_mutex_enter(db->mutex);
  118355. va_start(ap, op);
  118356. switch( op ){
  118357. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  118358. VtabCtx *p = db->pVtabCtx;
  118359. if( !p ){
  118360. rc = SQLITE_MISUSE_BKPT;
  118361. }else{
  118362. assert( p->pTab==0 || IsVirtual(p->pTab) );
  118363. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  118364. }
  118365. break;
  118366. }
  118367. default:
  118368. rc = SQLITE_MISUSE_BKPT;
  118369. break;
  118370. }
  118371. va_end(ap);
  118372. if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
  118373. sqlite3_mutex_leave(db->mutex);
  118374. return rc;
  118375. }
  118376. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  118377. /************** End of vtab.c ************************************************/
  118378. /************** Begin file wherecode.c ***************************************/
  118379. /*
  118380. ** 2015-06-06
  118381. **
  118382. ** The author disclaims copyright to this source code. In place of
  118383. ** a legal notice, here is a blessing:
  118384. **
  118385. ** May you do good and not evil.
  118386. ** May you find forgiveness for yourself and forgive others.
  118387. ** May you share freely, never taking more than you give.
  118388. **
  118389. *************************************************************************
  118390. ** This module contains C code that generates VDBE code used to process
  118391. ** the WHERE clause of SQL statements.
  118392. **
  118393. ** This file was split off from where.c on 2015-06-06 in order to reduce the
  118394. ** size of where.c and make it easier to edit. This file contains the routines
  118395. ** that actually generate the bulk of the WHERE loop code. The original where.c
  118396. ** file retains the code that does query planning and analysis.
  118397. */
  118398. /* #include "sqliteInt.h" */
  118399. /************** Include whereInt.h in the middle of wherecode.c **************/
  118400. /************** Begin file whereInt.h ****************************************/
  118401. /*
  118402. ** 2013-11-12
  118403. **
  118404. ** The author disclaims copyright to this source code. In place of
  118405. ** a legal notice, here is a blessing:
  118406. **
  118407. ** May you do good and not evil.
  118408. ** May you find forgiveness for yourself and forgive others.
  118409. ** May you share freely, never taking more than you give.
  118410. **
  118411. *************************************************************************
  118412. **
  118413. ** This file contains structure and macro definitions for the query
  118414. ** planner logic in "where.c". These definitions are broken out into
  118415. ** a separate source file for easier editing.
  118416. */
  118417. /*
  118418. ** Trace output macros
  118419. */
  118420. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  118421. /***/ int sqlite3WhereTrace;
  118422. #endif
  118423. #if defined(SQLITE_DEBUG) \
  118424. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  118425. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  118426. # define WHERETRACE_ENABLED 1
  118427. #else
  118428. # define WHERETRACE(K,X)
  118429. #endif
  118430. /* Forward references
  118431. */
  118432. typedef struct WhereClause WhereClause;
  118433. typedef struct WhereMaskSet WhereMaskSet;
  118434. typedef struct WhereOrInfo WhereOrInfo;
  118435. typedef struct WhereAndInfo WhereAndInfo;
  118436. typedef struct WhereLevel WhereLevel;
  118437. typedef struct WhereLoop WhereLoop;
  118438. typedef struct WherePath WherePath;
  118439. typedef struct WhereTerm WhereTerm;
  118440. typedef struct WhereLoopBuilder WhereLoopBuilder;
  118441. typedef struct WhereScan WhereScan;
  118442. typedef struct WhereOrCost WhereOrCost;
  118443. typedef struct WhereOrSet WhereOrSet;
  118444. /*
  118445. ** This object contains information needed to implement a single nested
  118446. ** loop in WHERE clause.
  118447. **
  118448. ** Contrast this object with WhereLoop. This object describes the
  118449. ** implementation of the loop. WhereLoop describes the algorithm.
  118450. ** This object contains a pointer to the WhereLoop algorithm as one of
  118451. ** its elements.
  118452. **
  118453. ** The WhereInfo object contains a single instance of this object for
  118454. ** each term in the FROM clause (which is to say, for each of the
  118455. ** nested loops as implemented). The order of WhereLevel objects determines
  118456. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  118457. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  118458. */
  118459. struct WhereLevel {
  118460. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  118461. int iTabCur; /* The VDBE cursor used to access the table */
  118462. int iIdxCur; /* The VDBE cursor used to access pIdx */
  118463. int addrBrk; /* Jump here to break out of the loop */
  118464. int addrNxt; /* Jump here to start the next IN combination */
  118465. int addrSkip; /* Jump here for next iteration of skip-scan */
  118466. int addrCont; /* Jump here to continue with the next loop cycle */
  118467. int addrFirst; /* First instruction of interior of the loop */
  118468. int addrBody; /* Beginning of the body of this loop */
  118469. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  118470. u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */
  118471. int addrLikeRep; /* LIKE range processing address */
  118472. #endif
  118473. u8 iFrom; /* Which entry in the FROM clause */
  118474. u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
  118475. int p1, p2; /* Operands of the opcode used to ends the loop */
  118476. union { /* Information that depends on pWLoop->wsFlags */
  118477. struct {
  118478. int nIn; /* Number of entries in aInLoop[] */
  118479. struct InLoop {
  118480. int iCur; /* The VDBE cursor used by this IN operator */
  118481. int addrInTop; /* Top of the IN loop */
  118482. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  118483. } *aInLoop; /* Information about each nested IN operator */
  118484. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  118485. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  118486. } u;
  118487. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  118488. Bitmask notReady; /* FROM entries not usable at this level */
  118489. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  118490. int addrVisit; /* Address at which row is visited */
  118491. #endif
  118492. };
  118493. /*
  118494. ** Each instance of this object represents an algorithm for evaluating one
  118495. ** term of a join. Every term of the FROM clause will have at least
  118496. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  118497. ** prevent a query solution - which is an error) and many terms of the
  118498. ** FROM clause will have multiple WhereLoop objects, each describing a
  118499. ** potential way of implementing that FROM-clause term, together with
  118500. ** dependencies and cost estimates for using the chosen algorithm.
  118501. **
  118502. ** Query planning consists of building up a collection of these WhereLoop
  118503. ** objects, then computing a particular sequence of WhereLoop objects, with
  118504. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  118505. ** and that minimize the overall cost.
  118506. */
  118507. struct WhereLoop {
  118508. Bitmask prereq; /* Bitmask of other loops that must run first */
  118509. Bitmask maskSelf; /* Bitmask identifying table iTab */
  118510. #ifdef SQLITE_DEBUG
  118511. char cId; /* Symbolic ID of this loop for debugging use */
  118512. #endif
  118513. u8 iTab; /* Position in FROM clause of table for this loop */
  118514. u8 iSortIdx; /* Sorting index number. 0==None */
  118515. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  118516. LogEst rRun; /* Cost of running each loop */
  118517. LogEst nOut; /* Estimated number of output rows */
  118518. union {
  118519. struct { /* Information for internal btree tables */
  118520. u16 nEq; /* Number of equality constraints */
  118521. u16 nBtm; /* Size of BTM vector */
  118522. u16 nTop; /* Size of TOP vector */
  118523. u16 nIdxCol; /* Index column used for ORDER BY */
  118524. Index *pIndex; /* Index used, or NULL */
  118525. } btree;
  118526. struct { /* Information for virtual tables */
  118527. int idxNum; /* Index number */
  118528. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  118529. i8 isOrdered; /* True if satisfies ORDER BY */
  118530. u16 omitMask; /* Terms that may be omitted */
  118531. char *idxStr; /* Index identifier string */
  118532. } vtab;
  118533. } u;
  118534. u32 wsFlags; /* WHERE_* flags describing the plan */
  118535. u16 nLTerm; /* Number of entries in aLTerm[] */
  118536. u16 nSkip; /* Number of NULL aLTerm[] entries */
  118537. /**** whereLoopXfer() copies fields above ***********************/
  118538. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  118539. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  118540. WhereTerm **aLTerm; /* WhereTerms used */
  118541. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  118542. WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
  118543. };
  118544. /* This object holds the prerequisites and the cost of running a
  118545. ** subquery on one operand of an OR operator in the WHERE clause.
  118546. ** See WhereOrSet for additional information
  118547. */
  118548. struct WhereOrCost {
  118549. Bitmask prereq; /* Prerequisites */
  118550. LogEst rRun; /* Cost of running this subquery */
  118551. LogEst nOut; /* Number of outputs for this subquery */
  118552. };
  118553. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  118554. ** correspond to the subquery(s) of OR-clause processing. Only the
  118555. ** best N_OR_COST elements are retained.
  118556. */
  118557. #define N_OR_COST 3
  118558. struct WhereOrSet {
  118559. u16 n; /* Number of valid a[] entries */
  118560. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  118561. };
  118562. /*
  118563. ** Each instance of this object holds a sequence of WhereLoop objects
  118564. ** that implement some or all of a query plan.
  118565. **
  118566. ** Think of each WhereLoop object as a node in a graph with arcs
  118567. ** showing dependencies and costs for travelling between nodes. (That is
  118568. ** not a completely accurate description because WhereLoop costs are a
  118569. ** vector, not a scalar, and because dependencies are many-to-one, not
  118570. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  118571. ** Then a WherePath object is a path through the graph that visits some
  118572. ** or all of the WhereLoop objects once.
  118573. **
  118574. ** The "solver" works by creating the N best WherePath objects of length
  118575. ** 1. Then using those as a basis to compute the N best WherePath objects
  118576. ** of length 2. And so forth until the length of WherePaths equals the
  118577. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  118578. ** at the end is the chosen query plan.
  118579. */
  118580. struct WherePath {
  118581. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  118582. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  118583. LogEst nRow; /* Estimated number of rows generated by this path */
  118584. LogEst rCost; /* Total cost of this path */
  118585. LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
  118586. i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
  118587. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  118588. };
  118589. /*
  118590. ** The query generator uses an array of instances of this structure to
  118591. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  118592. ** clause subexpression is separated from the others by AND operators,
  118593. ** usually, or sometimes subexpressions separated by OR.
  118594. **
  118595. ** All WhereTerms are collected into a single WhereClause structure.
  118596. ** The following identity holds:
  118597. **
  118598. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  118599. **
  118600. ** When a term is of the form:
  118601. **
  118602. ** X <op> <expr>
  118603. **
  118604. ** where X is a column name and <op> is one of certain operators,
  118605. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  118606. ** cursor number and column number for X. WhereTerm.eOperator records
  118607. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  118608. ** use of a bitmask encoding for the operator allows us to search
  118609. ** quickly for terms that match any of several different operators.
  118610. **
  118611. ** A WhereTerm might also be two or more subterms connected by OR:
  118612. **
  118613. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  118614. **
  118615. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  118616. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  118617. ** is collected about the OR clause.
  118618. **
  118619. ** If a term in the WHERE clause does not match either of the two previous
  118620. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  118621. ** to the original subexpression content and wtFlags is set up appropriately
  118622. ** but no other fields in the WhereTerm object are meaningful.
  118623. **
  118624. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  118625. ** but they do so indirectly. A single WhereMaskSet structure translates
  118626. ** cursor number into bits and the translated bit is stored in the prereq
  118627. ** fields. The translation is used in order to maximize the number of
  118628. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  118629. ** spread out over the non-negative integers. For example, the cursor
  118630. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  118631. ** translates these sparse cursor numbers into consecutive integers
  118632. ** beginning with 0 in order to make the best possible use of the available
  118633. ** bits in the Bitmask. So, in the example above, the cursor numbers
  118634. ** would be mapped into integers 0 through 7.
  118635. **
  118636. ** The number of terms in a join is limited by the number of bits
  118637. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  118638. ** is only able to process joins with 64 or fewer tables.
  118639. */
  118640. struct WhereTerm {
  118641. Expr *pExpr; /* Pointer to the subexpression that is this term */
  118642. WhereClause *pWC; /* The clause this term is part of */
  118643. LogEst truthProb; /* Probability of truth for this expression */
  118644. u16 wtFlags; /* TERM_xxx bit flags. See below */
  118645. u16 eOperator; /* A WO_xx value describing <op> */
  118646. u8 nChild; /* Number of children that must disable us */
  118647. u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
  118648. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  118649. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  118650. int iField; /* Field in (?,?,?) IN (SELECT...) vector */
  118651. union {
  118652. int leftColumn; /* Column number of X in "X <op> <expr>" */
  118653. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  118654. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  118655. } u;
  118656. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  118657. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  118658. };
  118659. /*
  118660. ** Allowed values of WhereTerm.wtFlags
  118661. */
  118662. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  118663. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  118664. #define TERM_CODED 0x04 /* This term is already coded */
  118665. #define TERM_COPIED 0x08 /* Has a child */
  118666. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  118667. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  118668. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  118669. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  118670. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  118671. #else
  118672. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  118673. #endif
  118674. #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */
  118675. #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */
  118676. #define TERM_LIKE 0x400 /* The original LIKE operator */
  118677. #define TERM_IS 0x800 /* Term.pExpr is an IS operator */
  118678. /*
  118679. ** An instance of the WhereScan object is used as an iterator for locating
  118680. ** terms in the WHERE clause that are useful to the query planner.
  118681. */
  118682. struct WhereScan {
  118683. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  118684. WhereClause *pWC; /* WhereClause currently being scanned */
  118685. const char *zCollName; /* Required collating sequence, if not NULL */
  118686. Expr *pIdxExpr; /* Search for this index expression */
  118687. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  118688. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  118689. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  118690. u32 opMask; /* Acceptable operators */
  118691. int k; /* Resume scanning at this->pWC->a[this->k] */
  118692. int aiCur[11]; /* Cursors in the equivalence class */
  118693. i16 aiColumn[11]; /* Corresponding column number in the eq-class */
  118694. };
  118695. /*
  118696. ** An instance of the following structure holds all information about a
  118697. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  118698. **
  118699. ** Explanation of pOuter: For a WHERE clause of the form
  118700. **
  118701. ** a AND ((b AND c) OR (d AND e)) AND f
  118702. **
  118703. ** There are separate WhereClause objects for the whole clause and for
  118704. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  118705. ** subclauses points to the WhereClause object for the whole clause.
  118706. */
  118707. struct WhereClause {
  118708. WhereInfo *pWInfo; /* WHERE clause processing context */
  118709. WhereClause *pOuter; /* Outer conjunction */
  118710. u8 op; /* Split operator. TK_AND or TK_OR */
  118711. int nTerm; /* Number of terms */
  118712. int nSlot; /* Number of entries in a[] */
  118713. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  118714. #if defined(SQLITE_SMALL_STACK)
  118715. WhereTerm aStatic[1]; /* Initial static space for a[] */
  118716. #else
  118717. WhereTerm aStatic[8]; /* Initial static space for a[] */
  118718. #endif
  118719. };
  118720. /*
  118721. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  118722. ** a dynamically allocated instance of the following structure.
  118723. */
  118724. struct WhereOrInfo {
  118725. WhereClause wc; /* Decomposition into subterms */
  118726. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  118727. };
  118728. /*
  118729. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  118730. ** a dynamically allocated instance of the following structure.
  118731. */
  118732. struct WhereAndInfo {
  118733. WhereClause wc; /* The subexpression broken out */
  118734. };
  118735. /*
  118736. ** An instance of the following structure keeps track of a mapping
  118737. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  118738. **
  118739. ** The VDBE cursor numbers are small integers contained in
  118740. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  118741. ** clause, the cursor numbers might not begin with 0 and they might
  118742. ** contain gaps in the numbering sequence. But we want to make maximum
  118743. ** use of the bits in our bitmasks. This structure provides a mapping
  118744. ** from the sparse cursor numbers into consecutive integers beginning
  118745. ** with 0.
  118746. **
  118747. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  118748. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  118749. **
  118750. ** For example, if the WHERE clause expression used these VDBE
  118751. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  118752. ** would map those cursor numbers into bits 0 through 5.
  118753. **
  118754. ** Note that the mapping is not necessarily ordered. In the example
  118755. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  118756. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  118757. ** does not really matter. What is important is that sparse cursor
  118758. ** numbers all get mapped into bit numbers that begin with 0 and contain
  118759. ** no gaps.
  118760. */
  118761. struct WhereMaskSet {
  118762. int n; /* Number of assigned cursor values */
  118763. int ix[BMS]; /* Cursor assigned to each bit */
  118764. };
  118765. /*
  118766. ** Initialize a WhereMaskSet object
  118767. */
  118768. #define initMaskSet(P) (P)->n=0
  118769. /*
  118770. ** This object is a convenience wrapper holding all information needed
  118771. ** to construct WhereLoop objects for a particular query.
  118772. */
  118773. struct WhereLoopBuilder {
  118774. WhereInfo *pWInfo; /* Information about this WHERE */
  118775. WhereClause *pWC; /* WHERE clause terms */
  118776. ExprList *pOrderBy; /* ORDER BY clause */
  118777. WhereLoop *pNew; /* Template WhereLoop */
  118778. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  118779. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  118780. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  118781. int nRecValid; /* Number of valid fields currently in pRec */
  118782. #endif
  118783. unsigned int bldFlags; /* SQLITE_BLDF_* flags */
  118784. };
  118785. /* Allowed values for WhereLoopBuider.bldFlags */
  118786. #define SQLITE_BLDF_INDEXED 0x0001 /* An index is used */
  118787. #define SQLITE_BLDF_UNIQUE 0x0002 /* All keys of a UNIQUE index used */
  118788. /*
  118789. ** The WHERE clause processing routine has two halves. The
  118790. ** first part does the start of the WHERE loop and the second
  118791. ** half does the tail of the WHERE loop. An instance of
  118792. ** this structure is returned by the first half and passed
  118793. ** into the second half to give some continuity.
  118794. **
  118795. ** An instance of this object holds the complete state of the query
  118796. ** planner.
  118797. */
  118798. struct WhereInfo {
  118799. Parse *pParse; /* Parsing and code generating context */
  118800. SrcList *pTabList; /* List of tables in the join */
  118801. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  118802. ExprList *pResultSet; /* Result set of the query */
  118803. Expr *pWhere; /* The complete WHERE clause */
  118804. LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
  118805. int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
  118806. int iContinue; /* Jump here to continue with next record */
  118807. int iBreak; /* Jump here to break out of the loop */
  118808. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  118809. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  118810. u8 nLevel; /* Number of nested loop */
  118811. i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
  118812. u8 sorted; /* True if really sorted (not just grouped) */
  118813. u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */
  118814. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  118815. u8 eDistinct; /* One of the WHERE_DISTINCT_* values */
  118816. u8 bOrderedInnerLoop; /* True if only the inner-most loop is ordered */
  118817. int iTop; /* The very beginning of the WHERE loop */
  118818. WhereLoop *pLoops; /* List of all WhereLoop objects */
  118819. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  118820. LogEst nRowOut; /* Estimated number of output rows */
  118821. WhereClause sWC; /* Decomposition of the WHERE clause */
  118822. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  118823. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  118824. };
  118825. /*
  118826. ** Private interfaces - callable only by other where.c routines.
  118827. **
  118828. ** where.c:
  118829. */
  118830. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
  118831. #ifdef WHERETRACE_ENABLED
  118832. SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
  118833. #endif
  118834. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  118835. WhereClause *pWC, /* The WHERE clause to be searched */
  118836. int iCur, /* Cursor number of LHS */
  118837. int iColumn, /* Column number of LHS */
  118838. Bitmask notReady, /* RHS must not overlap with this mask */
  118839. u32 op, /* Mask of WO_xx values describing operator */
  118840. Index *pIdx /* Must be compatible with this index, if not NULL */
  118841. );
  118842. /* wherecode.c: */
  118843. #ifndef SQLITE_OMIT_EXPLAIN
  118844. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  118845. Parse *pParse, /* Parse context */
  118846. SrcList *pTabList, /* Table list this loop refers to */
  118847. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  118848. int iLevel, /* Value for "level" column of output */
  118849. int iFrom, /* Value for "from" column of output */
  118850. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  118851. );
  118852. #else
  118853. # define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
  118854. #endif /* SQLITE_OMIT_EXPLAIN */
  118855. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  118856. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  118857. Vdbe *v, /* Vdbe to add scanstatus entry to */
  118858. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  118859. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  118860. int addrExplain /* Address of OP_Explain (or 0) */
  118861. );
  118862. #else
  118863. # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
  118864. #endif
  118865. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  118866. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  118867. int iLevel, /* Which level of pWInfo->a[] should be coded */
  118868. Bitmask notReady /* Which tables are currently available */
  118869. );
  118870. /* whereexpr.c: */
  118871. SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
  118872. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
  118873. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
  118874. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
  118875. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
  118876. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
  118877. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
  118878. /*
  118879. ** Bitmasks for the operators on WhereTerm objects. These are all
  118880. ** operators that are of interest to the query planner. An
  118881. ** OR-ed combination of these values can be used when searching for
  118882. ** particular WhereTerms within a WhereClause.
  118883. **
  118884. ** Value constraints:
  118885. ** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ
  118886. ** WO_LT == SQLITE_INDEX_CONSTRAINT_LT
  118887. ** WO_LE == SQLITE_INDEX_CONSTRAINT_LE
  118888. ** WO_GT == SQLITE_INDEX_CONSTRAINT_GT
  118889. ** WO_GE == SQLITE_INDEX_CONSTRAINT_GE
  118890. ** WO_MATCH == SQLITE_INDEX_CONSTRAINT_MATCH
  118891. */
  118892. #define WO_IN 0x0001
  118893. #define WO_EQ 0x0002
  118894. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  118895. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  118896. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  118897. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  118898. #define WO_MATCH 0x0040
  118899. #define WO_IS 0x0080
  118900. #define WO_ISNULL 0x0100
  118901. #define WO_OR 0x0200 /* Two or more OR-connected terms */
  118902. #define WO_AND 0x0400 /* Two or more AND-connected terms */
  118903. #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
  118904. #define WO_NOOP 0x1000 /* This term does not restrict search space */
  118905. #define WO_ALL 0x1fff /* Mask of all possible WO_* values */
  118906. #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
  118907. /*
  118908. ** These are definitions of bits in the WhereLoop.wsFlags field.
  118909. ** The particular combination of bits in each WhereLoop help to
  118910. ** determine the algorithm that WhereLoop represents.
  118911. */
  118912. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  118913. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  118914. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  118915. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  118916. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  118917. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  118918. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  118919. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  118920. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  118921. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  118922. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  118923. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  118924. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  118925. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  118926. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  118927. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  118928. #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
  118929. #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
  118930. #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
  118931. /************** End of whereInt.h ********************************************/
  118932. /************** Continuing where we left off in wherecode.c ******************/
  118933. #ifndef SQLITE_OMIT_EXPLAIN
  118934. /*
  118935. ** Return the name of the i-th column of the pIdx index.
  118936. */
  118937. static const char *explainIndexColumnName(Index *pIdx, int i){
  118938. i = pIdx->aiColumn[i];
  118939. if( i==XN_EXPR ) return "<expr>";
  118940. if( i==XN_ROWID ) return "rowid";
  118941. return pIdx->pTable->aCol[i].zName;
  118942. }
  118943. /*
  118944. ** This routine is a helper for explainIndexRange() below
  118945. **
  118946. ** pStr holds the text of an expression that we are building up one term
  118947. ** at a time. This routine adds a new term to the end of the expression.
  118948. ** Terms are separated by AND so add the "AND" text for second and subsequent
  118949. ** terms only.
  118950. */
  118951. static void explainAppendTerm(
  118952. StrAccum *pStr, /* The text expression being built */
  118953. Index *pIdx, /* Index to read column names from */
  118954. int nTerm, /* Number of terms */
  118955. int iTerm, /* Zero-based index of first term. */
  118956. int bAnd, /* Non-zero to append " AND " */
  118957. const char *zOp /* Name of the operator */
  118958. ){
  118959. int i;
  118960. assert( nTerm>=1 );
  118961. if( bAnd ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  118962. if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
  118963. for(i=0; i<nTerm; i++){
  118964. if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
  118965. sqlite3StrAccumAppendAll(pStr, explainIndexColumnName(pIdx, iTerm+i));
  118966. }
  118967. if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
  118968. sqlite3StrAccumAppend(pStr, zOp, 1);
  118969. if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
  118970. for(i=0; i<nTerm; i++){
  118971. if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
  118972. sqlite3StrAccumAppend(pStr, "?", 1);
  118973. }
  118974. if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
  118975. }
  118976. /*
  118977. ** Argument pLevel describes a strategy for scanning table pTab. This
  118978. ** function appends text to pStr that describes the subset of table
  118979. ** rows scanned by the strategy in the form of an SQL expression.
  118980. **
  118981. ** For example, if the query:
  118982. **
  118983. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  118984. **
  118985. ** is run and there is an index on (a, b), then this function returns a
  118986. ** string similar to:
  118987. **
  118988. ** "a=? AND b>?"
  118989. */
  118990. static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
  118991. Index *pIndex = pLoop->u.btree.pIndex;
  118992. u16 nEq = pLoop->u.btree.nEq;
  118993. u16 nSkip = pLoop->nSkip;
  118994. int i, j;
  118995. if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
  118996. sqlite3StrAccumAppend(pStr, " (", 2);
  118997. for(i=0; i<nEq; i++){
  118998. const char *z = explainIndexColumnName(pIndex, i);
  118999. if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  119000. sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
  119001. }
  119002. j = i;
  119003. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  119004. explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
  119005. i = 1;
  119006. }
  119007. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  119008. explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
  119009. }
  119010. sqlite3StrAccumAppend(pStr, ")", 1);
  119011. }
  119012. /*
  119013. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  119014. ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
  119015. ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
  119016. ** is added to the output to describe the table scan strategy in pLevel.
  119017. **
  119018. ** If an OP_Explain opcode is added to the VM, its address is returned.
  119019. ** Otherwise, if no OP_Explain is coded, zero is returned.
  119020. */
  119021. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  119022. Parse *pParse, /* Parse context */
  119023. SrcList *pTabList, /* Table list this loop refers to */
  119024. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  119025. int iLevel, /* Value for "level" column of output */
  119026. int iFrom, /* Value for "from" column of output */
  119027. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  119028. ){
  119029. int ret = 0;
  119030. #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  119031. if( pParse->explain==2 )
  119032. #endif
  119033. {
  119034. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  119035. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  119036. sqlite3 *db = pParse->db; /* Database handle */
  119037. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  119038. int isSearch; /* True for a SEARCH. False for SCAN. */
  119039. WhereLoop *pLoop; /* The controlling WhereLoop object */
  119040. u32 flags; /* Flags that describe this loop */
  119041. char *zMsg; /* Text to add to EQP output */
  119042. StrAccum str; /* EQP output string */
  119043. char zBuf[100]; /* Initial space for EQP output string */
  119044. pLoop = pLevel->pWLoop;
  119045. flags = pLoop->wsFlags;
  119046. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
  119047. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  119048. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  119049. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  119050. sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
  119051. sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
  119052. if( pItem->pSelect ){
  119053. sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId);
  119054. }else{
  119055. sqlite3XPrintf(&str, " TABLE %s", pItem->zName);
  119056. }
  119057. if( pItem->zAlias ){
  119058. sqlite3XPrintf(&str, " AS %s", pItem->zAlias);
  119059. }
  119060. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
  119061. const char *zFmt = 0;
  119062. Index *pIdx;
  119063. assert( pLoop->u.btree.pIndex!=0 );
  119064. pIdx = pLoop->u.btree.pIndex;
  119065. assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
  119066. if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
  119067. if( isSearch ){
  119068. zFmt = "PRIMARY KEY";
  119069. }
  119070. }else if( flags & WHERE_PARTIALIDX ){
  119071. zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
  119072. }else if( flags & WHERE_AUTO_INDEX ){
  119073. zFmt = "AUTOMATIC COVERING INDEX";
  119074. }else if( flags & WHERE_IDX_ONLY ){
  119075. zFmt = "COVERING INDEX %s";
  119076. }else{
  119077. zFmt = "INDEX %s";
  119078. }
  119079. if( zFmt ){
  119080. sqlite3StrAccumAppend(&str, " USING ", 7);
  119081. sqlite3XPrintf(&str, zFmt, pIdx->zName);
  119082. explainIndexRange(&str, pLoop);
  119083. }
  119084. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  119085. const char *zRangeOp;
  119086. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  119087. zRangeOp = "=";
  119088. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  119089. zRangeOp = ">? AND rowid<";
  119090. }else if( flags&WHERE_BTM_LIMIT ){
  119091. zRangeOp = ">";
  119092. }else{
  119093. assert( flags&WHERE_TOP_LIMIT);
  119094. zRangeOp = "<";
  119095. }
  119096. sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
  119097. }
  119098. #ifndef SQLITE_OMIT_VIRTUALTABLE
  119099. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  119100. sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s",
  119101. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  119102. }
  119103. #endif
  119104. #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
  119105. if( pLoop->nOut>=10 ){
  119106. sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
  119107. }else{
  119108. sqlite3StrAccumAppend(&str, " (~1 row)", 9);
  119109. }
  119110. #endif
  119111. zMsg = sqlite3StrAccumFinish(&str);
  119112. ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
  119113. }
  119114. return ret;
  119115. }
  119116. #endif /* SQLITE_OMIT_EXPLAIN */
  119117. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  119118. /*
  119119. ** Configure the VM passed as the first argument with an
  119120. ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
  119121. ** implement level pLvl. Argument pSrclist is a pointer to the FROM
  119122. ** clause that the scan reads data from.
  119123. **
  119124. ** If argument addrExplain is not 0, it must be the address of an
  119125. ** OP_Explain instruction that describes the same loop.
  119126. */
  119127. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  119128. Vdbe *v, /* Vdbe to add scanstatus entry to */
  119129. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  119130. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  119131. int addrExplain /* Address of OP_Explain (or 0) */
  119132. ){
  119133. const char *zObj = 0;
  119134. WhereLoop *pLoop = pLvl->pWLoop;
  119135. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
  119136. zObj = pLoop->u.btree.pIndex->zName;
  119137. }else{
  119138. zObj = pSrclist->a[pLvl->iFrom].zName;
  119139. }
  119140. sqlite3VdbeScanStatus(
  119141. v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
  119142. );
  119143. }
  119144. #endif
  119145. /*
  119146. ** Disable a term in the WHERE clause. Except, do not disable the term
  119147. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  119148. ** or USING clause of that join.
  119149. **
  119150. ** Consider the term t2.z='ok' in the following queries:
  119151. **
  119152. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  119153. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  119154. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  119155. **
  119156. ** The t2.z='ok' is disabled in the in (2) because it originates
  119157. ** in the ON clause. The term is disabled in (3) because it is not part
  119158. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  119159. **
  119160. ** Disabling a term causes that term to not be tested in the inner loop
  119161. ** of the join. Disabling is an optimization. When terms are satisfied
  119162. ** by indices, we disable them to prevent redundant tests in the inner
  119163. ** loop. We would get the correct results if nothing were ever disabled,
  119164. ** but joins might run a little slower. The trick is to disable as much
  119165. ** as we can without disabling too much. If we disabled in (1), we'd get
  119166. ** the wrong answer. See ticket #813.
  119167. **
  119168. ** If all the children of a term are disabled, then that term is also
  119169. ** automatically disabled. In this way, terms get disabled if derived
  119170. ** virtual terms are tested first. For example:
  119171. **
  119172. ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
  119173. ** \___________/ \______/ \_____/
  119174. ** parent child1 child2
  119175. **
  119176. ** Only the parent term was in the original WHERE clause. The child1
  119177. ** and child2 terms were added by the LIKE optimization. If both of
  119178. ** the virtual child terms are valid, then testing of the parent can be
  119179. ** skipped.
  119180. **
  119181. ** Usually the parent term is marked as TERM_CODED. But if the parent
  119182. ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
  119183. ** The TERM_LIKECOND marking indicates that the term should be coded inside
  119184. ** a conditional such that is only evaluated on the second pass of a
  119185. ** LIKE-optimization loop, when scanning BLOBs instead of strings.
  119186. */
  119187. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  119188. int nLoop = 0;
  119189. while( ALWAYS(pTerm!=0)
  119190. && (pTerm->wtFlags & TERM_CODED)==0
  119191. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  119192. && (pLevel->notReady & pTerm->prereqAll)==0
  119193. ){
  119194. if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
  119195. pTerm->wtFlags |= TERM_LIKECOND;
  119196. }else{
  119197. pTerm->wtFlags |= TERM_CODED;
  119198. }
  119199. if( pTerm->iParent<0 ) break;
  119200. pTerm = &pTerm->pWC->a[pTerm->iParent];
  119201. pTerm->nChild--;
  119202. if( pTerm->nChild!=0 ) break;
  119203. nLoop++;
  119204. }
  119205. }
  119206. /*
  119207. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  119208. ** to the n registers starting at base.
  119209. **
  119210. ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
  119211. ** beginning and end of zAff are ignored. If all entries in zAff are
  119212. ** SQLITE_AFF_BLOB, then no code gets generated.
  119213. **
  119214. ** This routine makes its own copy of zAff so that the caller is free
  119215. ** to modify zAff after this routine returns.
  119216. */
  119217. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  119218. Vdbe *v = pParse->pVdbe;
  119219. if( zAff==0 ){
  119220. assert( pParse->db->mallocFailed );
  119221. return;
  119222. }
  119223. assert( v!=0 );
  119224. /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
  119225. ** and end of the affinity string.
  119226. */
  119227. while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
  119228. n--;
  119229. base++;
  119230. zAff++;
  119231. }
  119232. while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
  119233. n--;
  119234. }
  119235. /* Code the OP_Affinity opcode if there is anything left to do. */
  119236. if( n>0 ){
  119237. sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
  119238. sqlite3ExprCacheAffinityChange(pParse, base, n);
  119239. }
  119240. }
  119241. /*
  119242. ** Expression pRight, which is the RHS of a comparison operation, is
  119243. ** either a vector of n elements or, if n==1, a scalar expression.
  119244. ** Before the comparison operation, affinity zAff is to be applied
  119245. ** to the pRight values. This function modifies characters within the
  119246. ** affinity string to SQLITE_AFF_BLOB if either:
  119247. **
  119248. ** * the comparison will be performed with no affinity, or
  119249. ** * the affinity change in zAff is guaranteed not to change the value.
  119250. */
  119251. static void updateRangeAffinityStr(
  119252. Expr *pRight, /* RHS of comparison */
  119253. int n, /* Number of vector elements in comparison */
  119254. char *zAff /* Affinity string to modify */
  119255. ){
  119256. int i;
  119257. for(i=0; i<n; i++){
  119258. Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
  119259. if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
  119260. || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
  119261. ){
  119262. zAff[i] = SQLITE_AFF_BLOB;
  119263. }
  119264. }
  119265. }
  119266. /*
  119267. ** Generate code for a single equality term of the WHERE clause. An equality
  119268. ** term can be either X=expr or X IN (...). pTerm is the term to be
  119269. ** coded.
  119270. **
  119271. ** The current value for the constraint is left in a register, the index
  119272. ** of which is returned. An attempt is made store the result in iTarget but
  119273. ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the
  119274. ** constraint is a TK_EQ or TK_IS, then the current value might be left in
  119275. ** some other register and it is the caller's responsibility to compensate.
  119276. **
  119277. ** For a constraint of the form X=expr, the expression is evaluated in
  119278. ** straight-line code. For constraints of the form X IN (...)
  119279. ** this routine sets up a loop that will iterate over all values of X.
  119280. */
  119281. static int codeEqualityTerm(
  119282. Parse *pParse, /* The parsing context */
  119283. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  119284. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  119285. int iEq, /* Index of the equality term within this level */
  119286. int bRev, /* True for reverse-order IN operations */
  119287. int iTarget /* Attempt to leave results in this register */
  119288. ){
  119289. Expr *pX = pTerm->pExpr;
  119290. Vdbe *v = pParse->pVdbe;
  119291. int iReg; /* Register holding results */
  119292. assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
  119293. assert( iTarget>0 );
  119294. if( pX->op==TK_EQ || pX->op==TK_IS ){
  119295. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  119296. }else if( pX->op==TK_ISNULL ){
  119297. iReg = iTarget;
  119298. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  119299. #ifndef SQLITE_OMIT_SUBQUERY
  119300. }else{
  119301. int eType = IN_INDEX_NOOP;
  119302. int iTab;
  119303. struct InLoop *pIn;
  119304. WhereLoop *pLoop = pLevel->pWLoop;
  119305. int i;
  119306. int nEq = 0;
  119307. int *aiMap = 0;
  119308. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  119309. && pLoop->u.btree.pIndex!=0
  119310. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  119311. ){
  119312. testcase( iEq==0 );
  119313. testcase( bRev );
  119314. bRev = !bRev;
  119315. }
  119316. assert( pX->op==TK_IN );
  119317. iReg = iTarget;
  119318. for(i=0; i<iEq; i++){
  119319. if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
  119320. disableTerm(pLevel, pTerm);
  119321. return iTarget;
  119322. }
  119323. }
  119324. for(i=iEq;i<pLoop->nLTerm; i++){
  119325. if( ALWAYS(pLoop->aLTerm[i]) && pLoop->aLTerm[i]->pExpr==pX ) nEq++;
  119326. }
  119327. if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
  119328. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0);
  119329. }else{
  119330. Select *pSelect = pX->x.pSelect;
  119331. sqlite3 *db = pParse->db;
  119332. u16 savedDbOptFlags = db->dbOptFlags;
  119333. ExprList *pOrigRhs = pSelect->pEList;
  119334. ExprList *pOrigLhs = pX->pLeft->x.pList;
  119335. ExprList *pRhs = 0; /* New Select.pEList for RHS */
  119336. ExprList *pLhs = 0; /* New pX->pLeft vector */
  119337. for(i=iEq;i<pLoop->nLTerm; i++){
  119338. if( pLoop->aLTerm[i]->pExpr==pX ){
  119339. int iField = pLoop->aLTerm[i]->iField - 1;
  119340. Expr *pNewRhs = sqlite3ExprDup(db, pOrigRhs->a[iField].pExpr, 0);
  119341. Expr *pNewLhs = sqlite3ExprDup(db, pOrigLhs->a[iField].pExpr, 0);
  119342. pRhs = sqlite3ExprListAppend(pParse, pRhs, pNewRhs);
  119343. pLhs = sqlite3ExprListAppend(pParse, pLhs, pNewLhs);
  119344. }
  119345. }
  119346. if( !db->mallocFailed ){
  119347. Expr *pLeft = pX->pLeft;
  119348. if( pSelect->pOrderBy ){
  119349. /* If the SELECT statement has an ORDER BY clause, zero the
  119350. ** iOrderByCol variables. These are set to non-zero when an
  119351. ** ORDER BY term exactly matches one of the terms of the
  119352. ** result-set. Since the result-set of the SELECT statement may
  119353. ** have been modified or reordered, these variables are no longer
  119354. ** set correctly. Since setting them is just an optimization,
  119355. ** it's easiest just to zero them here. */
  119356. ExprList *pOrderBy = pSelect->pOrderBy;
  119357. for(i=0; i<pOrderBy->nExpr; i++){
  119358. pOrderBy->a[i].u.x.iOrderByCol = 0;
  119359. }
  119360. }
  119361. /* Take care here not to generate a TK_VECTOR containing only a
  119362. ** single value. Since the parser never creates such a vector, some
  119363. ** of the subroutines do not handle this case. */
  119364. if( pLhs->nExpr==1 ){
  119365. pX->pLeft = pLhs->a[0].pExpr;
  119366. }else{
  119367. pLeft->x.pList = pLhs;
  119368. aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int) * nEq);
  119369. testcase( aiMap==0 );
  119370. }
  119371. pSelect->pEList = pRhs;
  119372. db->dbOptFlags |= SQLITE_QueryFlattener;
  119373. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap);
  119374. db->dbOptFlags = savedDbOptFlags;
  119375. testcase( aiMap!=0 && aiMap[0]!=0 );
  119376. pSelect->pEList = pOrigRhs;
  119377. pLeft->x.pList = pOrigLhs;
  119378. pX->pLeft = pLeft;
  119379. }
  119380. sqlite3ExprListDelete(pParse->db, pLhs);
  119381. sqlite3ExprListDelete(pParse->db, pRhs);
  119382. }
  119383. if( eType==IN_INDEX_INDEX_DESC ){
  119384. testcase( bRev );
  119385. bRev = !bRev;
  119386. }
  119387. iTab = pX->iTable;
  119388. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  119389. VdbeCoverageIf(v, bRev);
  119390. VdbeCoverageIf(v, !bRev);
  119391. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  119392. pLoop->wsFlags |= WHERE_IN_ABLE;
  119393. if( pLevel->u.in.nIn==0 ){
  119394. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  119395. }
  119396. i = pLevel->u.in.nIn;
  119397. pLevel->u.in.nIn += nEq;
  119398. pLevel->u.in.aInLoop =
  119399. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  119400. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  119401. pIn = pLevel->u.in.aInLoop;
  119402. if( pIn ){
  119403. int iMap = 0; /* Index in aiMap[] */
  119404. pIn += i;
  119405. for(i=iEq;i<pLoop->nLTerm; i++){
  119406. if( pLoop->aLTerm[i]->pExpr==pX ){
  119407. int iOut = iReg + i - iEq;
  119408. if( eType==IN_INDEX_ROWID ){
  119409. testcase( nEq>1 ); /* Happens with a UNIQUE index on ROWID */
  119410. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
  119411. }else{
  119412. int iCol = aiMap ? aiMap[iMap++] : 0;
  119413. pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
  119414. }
  119415. sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
  119416. if( i==iEq ){
  119417. pIn->iCur = iTab;
  119418. pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
  119419. }else{
  119420. pIn->eEndLoopOp = OP_Noop;
  119421. }
  119422. pIn++;
  119423. }
  119424. }
  119425. }else{
  119426. pLevel->u.in.nIn = 0;
  119427. }
  119428. sqlite3DbFree(pParse->db, aiMap);
  119429. #endif
  119430. }
  119431. disableTerm(pLevel, pTerm);
  119432. return iReg;
  119433. }
  119434. /*
  119435. ** Generate code that will evaluate all == and IN constraints for an
  119436. ** index scan.
  119437. **
  119438. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  119439. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  119440. ** The index has as many as three equality constraints, but in this
  119441. ** example, the third "c" value is an inequality. So only two
  119442. ** constraints are coded. This routine will generate code to evaluate
  119443. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  119444. ** in consecutive registers and the index of the first register is returned.
  119445. **
  119446. ** In the example above nEq==2. But this subroutine works for any value
  119447. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  119448. ** The only thing it does is allocate the pLevel->iMem memory cell and
  119449. ** compute the affinity string.
  119450. **
  119451. ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
  119452. ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
  119453. ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
  119454. ** occurs after the nEq quality constraints.
  119455. **
  119456. ** This routine allocates a range of nEq+nExtraReg memory cells and returns
  119457. ** the index of the first memory cell in that range. The code that
  119458. ** calls this routine will use that memory range to store keys for
  119459. ** start and termination conditions of the loop.
  119460. ** key value of the loop. If one or more IN operators appear, then
  119461. ** this routine allocates an additional nEq memory cells for internal
  119462. ** use.
  119463. **
  119464. ** Before returning, *pzAff is set to point to a buffer containing a
  119465. ** copy of the column affinity string of the index allocated using
  119466. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  119467. ** with equality constraints that use BLOB or NONE affinity are set to
  119468. ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
  119469. **
  119470. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  119471. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  119472. **
  119473. ** In the example above, the index on t1(a) has TEXT affinity. But since
  119474. ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
  119475. ** no conversion should be attempted before using a t2.b value as part of
  119476. ** a key to search the index. Hence the first byte in the returned affinity
  119477. ** string in this example would be set to SQLITE_AFF_BLOB.
  119478. */
  119479. static int codeAllEqualityTerms(
  119480. Parse *pParse, /* Parsing context */
  119481. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  119482. int bRev, /* Reverse the order of IN operators */
  119483. int nExtraReg, /* Number of extra registers to allocate */
  119484. char **pzAff /* OUT: Set to point to affinity string */
  119485. ){
  119486. u16 nEq; /* The number of == or IN constraints to code */
  119487. u16 nSkip; /* Number of left-most columns to skip */
  119488. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  119489. Index *pIdx; /* The index being used for this loop */
  119490. WhereTerm *pTerm; /* A single constraint term */
  119491. WhereLoop *pLoop; /* The WhereLoop object */
  119492. int j; /* Loop counter */
  119493. int regBase; /* Base register */
  119494. int nReg; /* Number of registers to allocate */
  119495. char *zAff; /* Affinity string to return */
  119496. /* This module is only called on query plans that use an index. */
  119497. pLoop = pLevel->pWLoop;
  119498. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  119499. nEq = pLoop->u.btree.nEq;
  119500. nSkip = pLoop->nSkip;
  119501. pIdx = pLoop->u.btree.pIndex;
  119502. assert( pIdx!=0 );
  119503. /* Figure out how many memory cells we will need then allocate them.
  119504. */
  119505. regBase = pParse->nMem + 1;
  119506. nReg = pLoop->u.btree.nEq + nExtraReg;
  119507. pParse->nMem += nReg;
  119508. zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
  119509. assert( zAff!=0 || pParse->db->mallocFailed );
  119510. if( nSkip ){
  119511. int iIdxCur = pLevel->iIdxCur;
  119512. sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
  119513. VdbeCoverageIf(v, bRev==0);
  119514. VdbeCoverageIf(v, bRev!=0);
  119515. VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
  119516. j = sqlite3VdbeAddOp0(v, OP_Goto);
  119517. pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
  119518. iIdxCur, 0, regBase, nSkip);
  119519. VdbeCoverageIf(v, bRev==0);
  119520. VdbeCoverageIf(v, bRev!=0);
  119521. sqlite3VdbeJumpHere(v, j);
  119522. for(j=0; j<nSkip; j++){
  119523. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
  119524. testcase( pIdx->aiColumn[j]==XN_EXPR );
  119525. VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
  119526. }
  119527. }
  119528. /* Evaluate the equality constraints
  119529. */
  119530. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  119531. for(j=nSkip; j<nEq; j++){
  119532. int r1;
  119533. pTerm = pLoop->aLTerm[j];
  119534. assert( pTerm!=0 );
  119535. /* The following testcase is true for indices with redundant columns.
  119536. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  119537. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  119538. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  119539. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  119540. if( r1!=regBase+j ){
  119541. if( nReg==1 ){
  119542. sqlite3ReleaseTempReg(pParse, regBase);
  119543. regBase = r1;
  119544. }else{
  119545. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  119546. }
  119547. }
  119548. if( pTerm->eOperator & WO_IN ){
  119549. if( pTerm->pExpr->flags & EP_xIsSelect ){
  119550. /* No affinity ever needs to be (or should be) applied to a value
  119551. ** from the RHS of an "? IN (SELECT ...)" expression. The
  119552. ** sqlite3FindInIndex() routine has already ensured that the
  119553. ** affinity of the comparison has been applied to the value. */
  119554. if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
  119555. }
  119556. }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
  119557. Expr *pRight = pTerm->pExpr->pRight;
  119558. if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
  119559. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
  119560. VdbeCoverage(v);
  119561. }
  119562. if( zAff ){
  119563. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
  119564. zAff[j] = SQLITE_AFF_BLOB;
  119565. }
  119566. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  119567. zAff[j] = SQLITE_AFF_BLOB;
  119568. }
  119569. }
  119570. }
  119571. }
  119572. *pzAff = zAff;
  119573. return regBase;
  119574. }
  119575. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  119576. /*
  119577. ** If the most recently coded instruction is a constant range constraint
  119578. ** (a string literal) that originated from the LIKE optimization, then
  119579. ** set P3 and P5 on the OP_String opcode so that the string will be cast
  119580. ** to a BLOB at appropriate times.
  119581. **
  119582. ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
  119583. ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
  119584. ** scan loop run twice, once for strings and a second time for BLOBs.
  119585. ** The OP_String opcodes on the second pass convert the upper and lower
  119586. ** bound string constants to blobs. This routine makes the necessary changes
  119587. ** to the OP_String opcodes for that to happen.
  119588. **
  119589. ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
  119590. ** only the one pass through the string space is required, so this routine
  119591. ** becomes a no-op.
  119592. */
  119593. static void whereLikeOptimizationStringFixup(
  119594. Vdbe *v, /* prepared statement under construction */
  119595. WhereLevel *pLevel, /* The loop that contains the LIKE operator */
  119596. WhereTerm *pTerm /* The upper or lower bound just coded */
  119597. ){
  119598. if( pTerm->wtFlags & TERM_LIKEOPT ){
  119599. VdbeOp *pOp;
  119600. assert( pLevel->iLikeRepCntr>0 );
  119601. pOp = sqlite3VdbeGetOp(v, -1);
  119602. assert( pOp!=0 );
  119603. assert( pOp->opcode==OP_String8
  119604. || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
  119605. pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
  119606. pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
  119607. }
  119608. }
  119609. #else
  119610. # define whereLikeOptimizationStringFixup(A,B,C)
  119611. #endif
  119612. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  119613. /*
  119614. ** Information is passed from codeCursorHint() down to individual nodes of
  119615. ** the expression tree (by sqlite3WalkExpr()) using an instance of this
  119616. ** structure.
  119617. */
  119618. struct CCurHint {
  119619. int iTabCur; /* Cursor for the main table */
  119620. int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
  119621. Index *pIdx; /* The index used to access the table */
  119622. };
  119623. /*
  119624. ** This function is called for every node of an expression that is a candidate
  119625. ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
  119626. ** the table CCurHint.iTabCur, verify that the same column can be
  119627. ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
  119628. */
  119629. static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
  119630. struct CCurHint *pHint = pWalker->u.pCCurHint;
  119631. assert( pHint->pIdx!=0 );
  119632. if( pExpr->op==TK_COLUMN
  119633. && pExpr->iTable==pHint->iTabCur
  119634. && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
  119635. ){
  119636. pWalker->eCode = 1;
  119637. }
  119638. return WRC_Continue;
  119639. }
  119640. /*
  119641. ** Test whether or not expression pExpr, which was part of a WHERE clause,
  119642. ** should be included in the cursor-hint for a table that is on the rhs
  119643. ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
  119644. ** expression is not suitable.
  119645. **
  119646. ** An expression is unsuitable if it might evaluate to non NULL even if
  119647. ** a TK_COLUMN node that does affect the value of the expression is set
  119648. ** to NULL. For example:
  119649. **
  119650. ** col IS NULL
  119651. ** col IS NOT NULL
  119652. ** coalesce(col, 1)
  119653. ** CASE WHEN col THEN 0 ELSE 1 END
  119654. */
  119655. static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
  119656. if( pExpr->op==TK_IS
  119657. || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
  119658. || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
  119659. ){
  119660. pWalker->eCode = 1;
  119661. }else if( pExpr->op==TK_FUNCTION ){
  119662. int d1;
  119663. char d2[3];
  119664. if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
  119665. pWalker->eCode = 1;
  119666. }
  119667. }
  119668. return WRC_Continue;
  119669. }
  119670. /*
  119671. ** This function is called on every node of an expression tree used as an
  119672. ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
  119673. ** that accesses any table other than the one identified by
  119674. ** CCurHint.iTabCur, then do the following:
  119675. **
  119676. ** 1) allocate a register and code an OP_Column instruction to read
  119677. ** the specified column into the new register, and
  119678. **
  119679. ** 2) transform the expression node to a TK_REGISTER node that reads
  119680. ** from the newly populated register.
  119681. **
  119682. ** Also, if the node is a TK_COLUMN that does access the table idenified
  119683. ** by pCCurHint.iTabCur, and an index is being used (which we will
  119684. ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
  119685. ** an access of the index rather than the original table.
  119686. */
  119687. static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
  119688. int rc = WRC_Continue;
  119689. struct CCurHint *pHint = pWalker->u.pCCurHint;
  119690. if( pExpr->op==TK_COLUMN ){
  119691. if( pExpr->iTable!=pHint->iTabCur ){
  119692. Vdbe *v = pWalker->pParse->pVdbe;
  119693. int reg = ++pWalker->pParse->nMem; /* Register for column value */
  119694. sqlite3ExprCodeGetColumnOfTable(
  119695. v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
  119696. );
  119697. pExpr->op = TK_REGISTER;
  119698. pExpr->iTable = reg;
  119699. }else if( pHint->pIdx!=0 ){
  119700. pExpr->iTable = pHint->iIdxCur;
  119701. pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
  119702. assert( pExpr->iColumn>=0 );
  119703. }
  119704. }else if( pExpr->op==TK_AGG_FUNCTION ){
  119705. /* An aggregate function in the WHERE clause of a query means this must
  119706. ** be a correlated sub-query, and expression pExpr is an aggregate from
  119707. ** the parent context. Do not walk the function arguments in this case.
  119708. **
  119709. ** todo: It should be possible to replace this node with a TK_REGISTER
  119710. ** expression, as the result of the expression must be stored in a
  119711. ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
  119712. rc = WRC_Prune;
  119713. }
  119714. return rc;
  119715. }
  119716. /*
  119717. ** Insert an OP_CursorHint instruction if it is appropriate to do so.
  119718. */
  119719. static void codeCursorHint(
  119720. struct SrcList_item *pTabItem, /* FROM clause item */
  119721. WhereInfo *pWInfo, /* The where clause */
  119722. WhereLevel *pLevel, /* Which loop to provide hints for */
  119723. WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
  119724. ){
  119725. Parse *pParse = pWInfo->pParse;
  119726. sqlite3 *db = pParse->db;
  119727. Vdbe *v = pParse->pVdbe;
  119728. Expr *pExpr = 0;
  119729. WhereLoop *pLoop = pLevel->pWLoop;
  119730. int iCur;
  119731. WhereClause *pWC;
  119732. WhereTerm *pTerm;
  119733. int i, j;
  119734. struct CCurHint sHint;
  119735. Walker sWalker;
  119736. if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
  119737. iCur = pLevel->iTabCur;
  119738. assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
  119739. sHint.iTabCur = iCur;
  119740. sHint.iIdxCur = pLevel->iIdxCur;
  119741. sHint.pIdx = pLoop->u.btree.pIndex;
  119742. memset(&sWalker, 0, sizeof(sWalker));
  119743. sWalker.pParse = pParse;
  119744. sWalker.u.pCCurHint = &sHint;
  119745. pWC = &pWInfo->sWC;
  119746. for(i=0; i<pWC->nTerm; i++){
  119747. pTerm = &pWC->a[i];
  119748. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  119749. if( pTerm->prereqAll & pLevel->notReady ) continue;
  119750. /* Any terms specified as part of the ON(...) clause for any LEFT
  119751. ** JOIN for which the current table is not the rhs are omitted
  119752. ** from the cursor-hint.
  119753. **
  119754. ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
  119755. ** that were specified as part of the WHERE clause must be excluded.
  119756. ** This is to address the following:
  119757. **
  119758. ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
  119759. **
  119760. ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
  119761. ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
  119762. ** pushed down to the cursor, this row is filtered out, causing
  119763. ** SQLite to synthesize a row of NULL values. Which does match the
  119764. ** WHERE clause, and so the query returns a row. Which is incorrect.
  119765. **
  119766. ** For the same reason, WHERE terms such as:
  119767. **
  119768. ** WHERE 1 = (t2.c IS NULL)
  119769. **
  119770. ** are also excluded. See codeCursorHintIsOrFunction() for details.
  119771. */
  119772. if( pTabItem->fg.jointype & JT_LEFT ){
  119773. Expr *pExpr = pTerm->pExpr;
  119774. if( !ExprHasProperty(pExpr, EP_FromJoin)
  119775. || pExpr->iRightJoinTable!=pTabItem->iCursor
  119776. ){
  119777. sWalker.eCode = 0;
  119778. sWalker.xExprCallback = codeCursorHintIsOrFunction;
  119779. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  119780. if( sWalker.eCode ) continue;
  119781. }
  119782. }else{
  119783. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
  119784. }
  119785. /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
  119786. ** the cursor. These terms are not needed as hints for a pure range
  119787. ** scan (that has no == terms) so omit them. */
  119788. if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
  119789. for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
  119790. if( j<pLoop->nLTerm ) continue;
  119791. }
  119792. /* No subqueries or non-deterministic functions allowed */
  119793. if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
  119794. /* For an index scan, make sure referenced columns are actually in
  119795. ** the index. */
  119796. if( sHint.pIdx!=0 ){
  119797. sWalker.eCode = 0;
  119798. sWalker.xExprCallback = codeCursorHintCheckExpr;
  119799. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  119800. if( sWalker.eCode ) continue;
  119801. }
  119802. /* If we survive all prior tests, that means this term is worth hinting */
  119803. pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
  119804. }
  119805. if( pExpr!=0 ){
  119806. sWalker.xExprCallback = codeCursorHintFixExpr;
  119807. sqlite3WalkExpr(&sWalker, pExpr);
  119808. sqlite3VdbeAddOp4(v, OP_CursorHint,
  119809. (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
  119810. (const char*)pExpr, P4_EXPR);
  119811. }
  119812. }
  119813. #else
  119814. # define codeCursorHint(A,B,C,D) /* No-op */
  119815. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  119816. /*
  119817. ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
  119818. ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
  119819. ** function generates code to do a deferred seek of cursor iCur to the
  119820. ** rowid stored in register iRowid.
  119821. **
  119822. ** Normally, this is just:
  119823. **
  119824. ** OP_Seek $iCur $iRowid
  119825. **
  119826. ** However, if the scan currently being coded is a branch of an OR-loop and
  119827. ** the statement currently being coded is a SELECT, then P3 of the OP_Seek
  119828. ** is set to iIdxCur and P4 is set to point to an array of integers
  119829. ** containing one entry for each column of the table cursor iCur is open
  119830. ** on. For each table column, if the column is the i'th column of the
  119831. ** index, then the corresponding array entry is set to (i+1). If the column
  119832. ** does not appear in the index at all, the array entry is set to 0.
  119833. */
  119834. static void codeDeferredSeek(
  119835. WhereInfo *pWInfo, /* Where clause context */
  119836. Index *pIdx, /* Index scan is using */
  119837. int iCur, /* Cursor for IPK b-tree */
  119838. int iIdxCur /* Index cursor */
  119839. ){
  119840. Parse *pParse = pWInfo->pParse; /* Parse context */
  119841. Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
  119842. assert( iIdxCur>0 );
  119843. assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
  119844. sqlite3VdbeAddOp3(v, OP_Seek, iIdxCur, 0, iCur);
  119845. if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
  119846. && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
  119847. ){
  119848. int i;
  119849. Table *pTab = pIdx->pTable;
  119850. int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
  119851. if( ai ){
  119852. ai[0] = pTab->nCol;
  119853. for(i=0; i<pIdx->nColumn-1; i++){
  119854. assert( pIdx->aiColumn[i]<pTab->nCol );
  119855. if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
  119856. }
  119857. sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
  119858. }
  119859. }
  119860. }
  119861. /*
  119862. ** If the expression passed as the second argument is a vector, generate
  119863. ** code to write the first nReg elements of the vector into an array
  119864. ** of registers starting with iReg.
  119865. **
  119866. ** If the expression is not a vector, then nReg must be passed 1. In
  119867. ** this case, generate code to evaluate the expression and leave the
  119868. ** result in register iReg.
  119869. */
  119870. static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
  119871. assert( nReg>0 );
  119872. if( sqlite3ExprIsVector(p) ){
  119873. #ifndef SQLITE_OMIT_SUBQUERY
  119874. if( (p->flags & EP_xIsSelect) ){
  119875. Vdbe *v = pParse->pVdbe;
  119876. int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0);
  119877. sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
  119878. }else
  119879. #endif
  119880. {
  119881. int i;
  119882. ExprList *pList = p->x.pList;
  119883. assert( nReg<=pList->nExpr );
  119884. for(i=0; i<nReg; i++){
  119885. sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
  119886. }
  119887. }
  119888. }else{
  119889. assert( nReg==1 );
  119890. sqlite3ExprCode(pParse, p, iReg);
  119891. }
  119892. }
  119893. /* An instance of the IdxExprTrans object carries information about a
  119894. ** mapping from an expression on table columns into a column in an index
  119895. ** down through the Walker.
  119896. */
  119897. typedef struct IdxExprTrans {
  119898. Expr *pIdxExpr; /* The index expression */
  119899. int iTabCur; /* The cursor of the corresponding table */
  119900. int iIdxCur; /* The cursor for the index */
  119901. int iIdxCol; /* The column for the index */
  119902. } IdxExprTrans;
  119903. /* The walker node callback used to transform matching expressions into
  119904. ** a reference to an index column for an index on an expression.
  119905. **
  119906. ** If pExpr matches, then transform it into a reference to the index column
  119907. ** that contains the value of pExpr.
  119908. */
  119909. static int whereIndexExprTransNode(Walker *p, Expr *pExpr){
  119910. IdxExprTrans *pX = p->u.pIdxTrans;
  119911. if( sqlite3ExprCompare(pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){
  119912. pExpr->op = TK_COLUMN;
  119913. pExpr->iTable = pX->iIdxCur;
  119914. pExpr->iColumn = pX->iIdxCol;
  119915. pExpr->pTab = 0;
  119916. return WRC_Prune;
  119917. }else{
  119918. return WRC_Continue;
  119919. }
  119920. }
  119921. /*
  119922. ** For an indexes on expression X, locate every instance of expression X in pExpr
  119923. ** and change that subexpression into a reference to the appropriate column of
  119924. ** the index.
  119925. */
  119926. static void whereIndexExprTrans(
  119927. Index *pIdx, /* The Index */
  119928. int iTabCur, /* Cursor of the table that is being indexed */
  119929. int iIdxCur, /* Cursor of the index itself */
  119930. WhereInfo *pWInfo /* Transform expressions in this WHERE clause */
  119931. ){
  119932. int iIdxCol; /* Column number of the index */
  119933. ExprList *aColExpr; /* Expressions that are indexed */
  119934. Walker w;
  119935. IdxExprTrans x;
  119936. aColExpr = pIdx->aColExpr;
  119937. if( aColExpr==0 ) return; /* Not an index on expressions */
  119938. memset(&w, 0, sizeof(w));
  119939. w.xExprCallback = whereIndexExprTransNode;
  119940. w.u.pIdxTrans = &x;
  119941. x.iTabCur = iTabCur;
  119942. x.iIdxCur = iIdxCur;
  119943. for(iIdxCol=0; iIdxCol<aColExpr->nExpr; iIdxCol++){
  119944. if( pIdx->aiColumn[iIdxCol]!=XN_EXPR ) continue;
  119945. assert( aColExpr->a[iIdxCol].pExpr!=0 );
  119946. x.iIdxCol = iIdxCol;
  119947. x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;
  119948. sqlite3WalkExpr(&w, pWInfo->pWhere);
  119949. sqlite3WalkExprList(&w, pWInfo->pOrderBy);
  119950. sqlite3WalkExprList(&w, pWInfo->pResultSet);
  119951. }
  119952. }
  119953. /*
  119954. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  119955. ** implementation described by pWInfo.
  119956. */
  119957. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  119958. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  119959. int iLevel, /* Which level of pWInfo->a[] should be coded */
  119960. Bitmask notReady /* Which tables are currently available */
  119961. ){
  119962. int j, k; /* Loop counters */
  119963. int iCur; /* The VDBE cursor for the table */
  119964. int addrNxt; /* Where to jump to continue with the next IN case */
  119965. int omitTable; /* True if we use the index only */
  119966. int bRev; /* True if we need to scan in reverse order */
  119967. WhereLevel *pLevel; /* The where level to be coded */
  119968. WhereLoop *pLoop; /* The WhereLoop object being coded */
  119969. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  119970. WhereTerm *pTerm; /* A WHERE clause term */
  119971. Parse *pParse; /* Parsing context */
  119972. sqlite3 *db; /* Database connection */
  119973. Vdbe *v; /* The prepared stmt under constructions */
  119974. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  119975. int addrBrk; /* Jump here to break out of the loop */
  119976. int addrHalt; /* addrBrk for the outermost loop */
  119977. int addrCont; /* Jump here to continue with next cycle */
  119978. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  119979. int iReleaseReg = 0; /* Temp register to free before returning */
  119980. Index *pIdx = 0; /* Index used by loop (if any) */
  119981. int loopAgain; /* True if constraint generator loop should repeat */
  119982. pParse = pWInfo->pParse;
  119983. v = pParse->pVdbe;
  119984. pWC = &pWInfo->sWC;
  119985. db = pParse->db;
  119986. pLevel = &pWInfo->a[iLevel];
  119987. pLoop = pLevel->pWLoop;
  119988. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  119989. iCur = pTabItem->iCursor;
  119990. pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
  119991. bRev = (pWInfo->revMask>>iLevel)&1;
  119992. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  119993. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
  119994. VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
  119995. /* Create labels for the "break" and "continue" instructions
  119996. ** for the current loop. Jump to addrBrk to break out of a loop.
  119997. ** Jump to cont to go immediately to the next iteration of the
  119998. ** loop.
  119999. **
  120000. ** When there is an IN operator, we also have a "addrNxt" label that
  120001. ** means to continue with the next IN value combination. When
  120002. ** there are no IN operators in the constraints, the "addrNxt" label
  120003. ** is the same as "addrBrk".
  120004. */
  120005. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  120006. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  120007. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  120008. ** initialize a memory cell that records if this table matches any
  120009. ** row of the left table of the join.
  120010. */
  120011. if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
  120012. pLevel->iLeftJoin = ++pParse->nMem;
  120013. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  120014. VdbeComment((v, "init LEFT JOIN no-match flag"));
  120015. }
  120016. /* Compute a safe address to jump to if we discover that the table for
  120017. ** this loop is empty and can never contribute content. */
  120018. for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){}
  120019. addrHalt = pWInfo->a[j].addrBrk;
  120020. /* Special case of a FROM clause subquery implemented as a co-routine */
  120021. if( pTabItem->fg.viaCoroutine ){
  120022. int regYield = pTabItem->regReturn;
  120023. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  120024. pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
  120025. VdbeCoverage(v);
  120026. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  120027. pLevel->op = OP_Goto;
  120028. }else
  120029. #ifndef SQLITE_OMIT_VIRTUALTABLE
  120030. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  120031. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  120032. ** to access the data.
  120033. */
  120034. int iReg; /* P3 Value for OP_VFilter */
  120035. int addrNotFound;
  120036. int nConstraint = pLoop->nLTerm;
  120037. int iIn; /* Counter for IN constraints */
  120038. sqlite3ExprCachePush(pParse);
  120039. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  120040. addrNotFound = pLevel->addrBrk;
  120041. for(j=0; j<nConstraint; j++){
  120042. int iTarget = iReg+j+2;
  120043. pTerm = pLoop->aLTerm[j];
  120044. if( NEVER(pTerm==0) ) continue;
  120045. if( pTerm->eOperator & WO_IN ){
  120046. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  120047. addrNotFound = pLevel->addrNxt;
  120048. }else{
  120049. Expr *pRight = pTerm->pExpr->pRight;
  120050. codeExprOrVector(pParse, pRight, iTarget, 1);
  120051. }
  120052. }
  120053. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  120054. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  120055. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  120056. pLoop->u.vtab.idxStr,
  120057. pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
  120058. VdbeCoverage(v);
  120059. pLoop->u.vtab.needFree = 0;
  120060. pLevel->p1 = iCur;
  120061. pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
  120062. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  120063. iIn = pLevel->u.in.nIn;
  120064. for(j=nConstraint-1; j>=0; j--){
  120065. pTerm = pLoop->aLTerm[j];
  120066. if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
  120067. disableTerm(pLevel, pTerm);
  120068. }else if( (pTerm->eOperator & WO_IN)!=0 ){
  120069. Expr *pCompare; /* The comparison operator */
  120070. Expr *pRight; /* RHS of the comparison */
  120071. VdbeOp *pOp; /* Opcode to access the value of the IN constraint */
  120072. /* Reload the constraint value into reg[iReg+j+2]. The same value
  120073. ** was loaded into the same register prior to the OP_VFilter, but
  120074. ** the xFilter implementation might have changed the datatype or
  120075. ** encoding of the value in the register, so it *must* be reloaded. */
  120076. assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
  120077. if( !db->mallocFailed ){
  120078. assert( iIn>0 );
  120079. pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
  120080. assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
  120081. assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
  120082. assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
  120083. testcase( pOp->opcode==OP_Rowid );
  120084. sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
  120085. }
  120086. /* Generate code that will continue to the next row if
  120087. ** the IN constraint is not satisfied */
  120088. pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
  120089. assert( pCompare!=0 || db->mallocFailed );
  120090. if( pCompare ){
  120091. pCompare->pLeft = pTerm->pExpr->pLeft;
  120092. pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
  120093. if( pRight ){
  120094. pRight->iTable = iReg+j+2;
  120095. sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
  120096. }
  120097. pCompare->pLeft = 0;
  120098. sqlite3ExprDelete(db, pCompare);
  120099. }
  120100. }
  120101. }
  120102. /* These registers need to be preserved in case there is an IN operator
  120103. ** loop. So we could deallocate the registers here (and potentially
  120104. ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
  120105. ** simpler and safer to simply not reuse the registers.
  120106. **
  120107. ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  120108. */
  120109. sqlite3ExprCachePop(pParse);
  120110. }else
  120111. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  120112. if( (pLoop->wsFlags & WHERE_IPK)!=0
  120113. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  120114. ){
  120115. /* Case 2: We can directly reference a single row using an
  120116. ** equality comparison against the ROWID field. Or
  120117. ** we reference multiple rows using a "rowid IN (...)"
  120118. ** construct.
  120119. */
  120120. assert( pLoop->u.btree.nEq==1 );
  120121. pTerm = pLoop->aLTerm[0];
  120122. assert( pTerm!=0 );
  120123. assert( pTerm->pExpr!=0 );
  120124. assert( omitTable==0 );
  120125. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  120126. iReleaseReg = ++pParse->nMem;
  120127. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  120128. if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
  120129. addrNxt = pLevel->addrNxt;
  120130. sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
  120131. VdbeCoverage(v);
  120132. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  120133. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  120134. VdbeComment((v, "pk"));
  120135. pLevel->op = OP_Noop;
  120136. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  120137. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  120138. ){
  120139. /* Case 3: We have an inequality comparison against the ROWID field.
  120140. */
  120141. int testOp = OP_Noop;
  120142. int start;
  120143. int memEndValue = 0;
  120144. WhereTerm *pStart, *pEnd;
  120145. assert( omitTable==0 );
  120146. j = 0;
  120147. pStart = pEnd = 0;
  120148. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  120149. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  120150. assert( pStart!=0 || pEnd!=0 );
  120151. if( bRev ){
  120152. pTerm = pStart;
  120153. pStart = pEnd;
  120154. pEnd = pTerm;
  120155. }
  120156. codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
  120157. if( pStart ){
  120158. Expr *pX; /* The expression that defines the start bound */
  120159. int r1, rTemp; /* Registers for holding the start boundary */
  120160. int op; /* Cursor seek operation */
  120161. /* The following constant maps TK_xx codes into corresponding
  120162. ** seek opcodes. It depends on a particular ordering of TK_xx
  120163. */
  120164. const u8 aMoveOp[] = {
  120165. /* TK_GT */ OP_SeekGT,
  120166. /* TK_LE */ OP_SeekLE,
  120167. /* TK_LT */ OP_SeekLT,
  120168. /* TK_GE */ OP_SeekGE
  120169. };
  120170. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  120171. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  120172. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  120173. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  120174. testcase( pStart->wtFlags & TERM_VIRTUAL );
  120175. pX = pStart->pExpr;
  120176. assert( pX!=0 );
  120177. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  120178. if( sqlite3ExprIsVector(pX->pRight) ){
  120179. r1 = rTemp = sqlite3GetTempReg(pParse);
  120180. codeExprOrVector(pParse, pX->pRight, r1, 1);
  120181. op = aMoveOp[(pX->op - TK_GT) | 0x0001];
  120182. }else{
  120183. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  120184. disableTerm(pLevel, pStart);
  120185. op = aMoveOp[(pX->op - TK_GT)];
  120186. }
  120187. sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
  120188. VdbeComment((v, "pk"));
  120189. VdbeCoverageIf(v, pX->op==TK_GT);
  120190. VdbeCoverageIf(v, pX->op==TK_LE);
  120191. VdbeCoverageIf(v, pX->op==TK_LT);
  120192. VdbeCoverageIf(v, pX->op==TK_GE);
  120193. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  120194. sqlite3ReleaseTempReg(pParse, rTemp);
  120195. }else{
  120196. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);
  120197. VdbeCoverageIf(v, bRev==0);
  120198. VdbeCoverageIf(v, bRev!=0);
  120199. }
  120200. if( pEnd ){
  120201. Expr *pX;
  120202. pX = pEnd->pExpr;
  120203. assert( pX!=0 );
  120204. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  120205. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  120206. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  120207. memEndValue = ++pParse->nMem;
  120208. codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
  120209. if( 0==sqlite3ExprIsVector(pX->pRight)
  120210. && (pX->op==TK_LT || pX->op==TK_GT)
  120211. ){
  120212. testOp = bRev ? OP_Le : OP_Ge;
  120213. }else{
  120214. testOp = bRev ? OP_Lt : OP_Gt;
  120215. }
  120216. if( 0==sqlite3ExprIsVector(pX->pRight) ){
  120217. disableTerm(pLevel, pEnd);
  120218. }
  120219. }
  120220. start = sqlite3VdbeCurrentAddr(v);
  120221. pLevel->op = bRev ? OP_Prev : OP_Next;
  120222. pLevel->p1 = iCur;
  120223. pLevel->p2 = start;
  120224. assert( pLevel->p5==0 );
  120225. if( testOp!=OP_Noop ){
  120226. iRowidReg = ++pParse->nMem;
  120227. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  120228. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  120229. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  120230. VdbeCoverageIf(v, testOp==OP_Le);
  120231. VdbeCoverageIf(v, testOp==OP_Lt);
  120232. VdbeCoverageIf(v, testOp==OP_Ge);
  120233. VdbeCoverageIf(v, testOp==OP_Gt);
  120234. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  120235. }
  120236. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  120237. /* Case 4: A scan using an index.
  120238. **
  120239. ** The WHERE clause may contain zero or more equality
  120240. ** terms ("==" or "IN" operators) that refer to the N
  120241. ** left-most columns of the index. It may also contain
  120242. ** inequality constraints (>, <, >= or <=) on the indexed
  120243. ** column that immediately follows the N equalities. Only
  120244. ** the right-most column can be an inequality - the rest must
  120245. ** use the "==" and "IN" operators. For example, if the
  120246. ** index is on (x,y,z), then the following clauses are all
  120247. ** optimized:
  120248. **
  120249. ** x=5
  120250. ** x=5 AND y=10
  120251. ** x=5 AND y<10
  120252. ** x=5 AND y>5 AND y<10
  120253. ** x=5 AND y=5 AND z<=10
  120254. **
  120255. ** The z<10 term of the following cannot be used, only
  120256. ** the x=5 term:
  120257. **
  120258. ** x=5 AND z<10
  120259. **
  120260. ** N may be zero if there are inequality constraints.
  120261. ** If there are no inequality constraints, then N is at
  120262. ** least one.
  120263. **
  120264. ** This case is also used when there are no WHERE clause
  120265. ** constraints but an index is selected anyway, in order
  120266. ** to force the output order to conform to an ORDER BY.
  120267. */
  120268. static const u8 aStartOp[] = {
  120269. 0,
  120270. 0,
  120271. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  120272. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  120273. OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
  120274. OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
  120275. OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
  120276. OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
  120277. };
  120278. static const u8 aEndOp[] = {
  120279. OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
  120280. OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
  120281. OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
  120282. OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
  120283. };
  120284. u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  120285. u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */
  120286. u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */
  120287. int regBase; /* Base register holding constraint values */
  120288. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  120289. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  120290. int startEq; /* True if range start uses ==, >= or <= */
  120291. int endEq; /* True if range end uses ==, >= or <= */
  120292. int start_constraints; /* Start of range is constrained */
  120293. int nConstraint; /* Number of constraint terms */
  120294. int iIdxCur; /* The VDBE cursor for the index */
  120295. int nExtraReg = 0; /* Number of extra registers needed */
  120296. int op; /* Instruction opcode */
  120297. char *zStartAff; /* Affinity for start of range constraint */
  120298. char *zEndAff = 0; /* Affinity for end of range constraint */
  120299. u8 bSeekPastNull = 0; /* True to seek past initial nulls */
  120300. u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
  120301. pIdx = pLoop->u.btree.pIndex;
  120302. iIdxCur = pLevel->iIdxCur;
  120303. assert( nEq>=pLoop->nSkip );
  120304. /* If this loop satisfies a sort order (pOrderBy) request that
  120305. ** was passed to this function to implement a "SELECT min(x) ..."
  120306. ** query, then the caller will only allow the loop to run for
  120307. ** a single iteration. This means that the first row returned
  120308. ** should not have a NULL value stored in 'x'. If column 'x' is
  120309. ** the first one after the nEq equality constraints in the index,
  120310. ** this requires some special handling.
  120311. */
  120312. assert( pWInfo->pOrderBy==0
  120313. || pWInfo->pOrderBy->nExpr==1
  120314. || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
  120315. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  120316. && pWInfo->nOBSat>0
  120317. && (pIdx->nKeyCol>nEq)
  120318. ){
  120319. assert( pLoop->nSkip==0 );
  120320. bSeekPastNull = 1;
  120321. nExtraReg = 1;
  120322. }
  120323. /* Find any inequality constraint terms for the start and end
  120324. ** of the range.
  120325. */
  120326. j = nEq;
  120327. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  120328. pRangeStart = pLoop->aLTerm[j++];
  120329. nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
  120330. /* Like optimization range constraints always occur in pairs */
  120331. assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
  120332. (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
  120333. }
  120334. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  120335. pRangeEnd = pLoop->aLTerm[j++];
  120336. nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
  120337. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  120338. if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
  120339. assert( pRangeStart!=0 ); /* LIKE opt constraints */
  120340. assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
  120341. pLevel->iLikeRepCntr = (u32)++pParse->nMem;
  120342. sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
  120343. VdbeComment((v, "LIKE loop counter"));
  120344. pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
  120345. /* iLikeRepCntr actually stores 2x the counter register number. The
  120346. ** bottom bit indicates whether the search order is ASC or DESC. */
  120347. testcase( bRev );
  120348. testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
  120349. assert( (bRev & ~1)==0 );
  120350. pLevel->iLikeRepCntr <<=1;
  120351. pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
  120352. }
  120353. #endif
  120354. if( pRangeStart==0 ){
  120355. j = pIdx->aiColumn[nEq];
  120356. if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
  120357. bSeekPastNull = 1;
  120358. }
  120359. }
  120360. }
  120361. assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
  120362. /* If we are doing a reverse order scan on an ascending index, or
  120363. ** a forward order scan on a descending index, interchange the
  120364. ** start and end terms (pRangeStart and pRangeEnd).
  120365. */
  120366. if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  120367. || (bRev && pIdx->nKeyCol==nEq)
  120368. ){
  120369. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  120370. SWAP(u8, bSeekPastNull, bStopAtNull);
  120371. SWAP(u8, nBtm, nTop);
  120372. }
  120373. /* Generate code to evaluate all constraint terms using == or IN
  120374. ** and store the values of those terms in an array of registers
  120375. ** starting at regBase.
  120376. */
  120377. codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
  120378. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  120379. assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
  120380. if( zStartAff && nTop ){
  120381. zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
  120382. }
  120383. addrNxt = pLevel->addrNxt;
  120384. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  120385. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  120386. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  120387. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  120388. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  120389. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  120390. start_constraints = pRangeStart || nEq>0;
  120391. /* Seek the index cursor to the start of the range. */
  120392. nConstraint = nEq;
  120393. if( pRangeStart ){
  120394. Expr *pRight = pRangeStart->pExpr->pRight;
  120395. codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
  120396. whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
  120397. if( (pRangeStart->wtFlags & TERM_VNULL)==0
  120398. && sqlite3ExprCanBeNull(pRight)
  120399. ){
  120400. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  120401. VdbeCoverage(v);
  120402. }
  120403. if( zStartAff ){
  120404. updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
  120405. }
  120406. nConstraint += nBtm;
  120407. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  120408. if( sqlite3ExprIsVector(pRight)==0 ){
  120409. disableTerm(pLevel, pRangeStart);
  120410. }else{
  120411. startEq = 1;
  120412. }
  120413. bSeekPastNull = 0;
  120414. }else if( bSeekPastNull ){
  120415. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  120416. nConstraint++;
  120417. startEq = 0;
  120418. start_constraints = 1;
  120419. }
  120420. codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
  120421. if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
  120422. /* The skip-scan logic inside the call to codeAllEqualityConstraints()
  120423. ** above has already left the cursor sitting on the correct row,
  120424. ** so no further seeking is needed */
  120425. }else{
  120426. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  120427. assert( op!=0 );
  120428. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  120429. VdbeCoverage(v);
  120430. VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
  120431. VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
  120432. VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
  120433. VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
  120434. VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
  120435. VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
  120436. }
  120437. /* Load the value for the inequality constraint at the end of the
  120438. ** range (if any).
  120439. */
  120440. nConstraint = nEq;
  120441. if( pRangeEnd ){
  120442. Expr *pRight = pRangeEnd->pExpr->pRight;
  120443. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  120444. codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
  120445. whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
  120446. if( (pRangeEnd->wtFlags & TERM_VNULL)==0
  120447. && sqlite3ExprCanBeNull(pRight)
  120448. ){
  120449. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  120450. VdbeCoverage(v);
  120451. }
  120452. if( zEndAff ){
  120453. updateRangeAffinityStr(pRight, nTop, zEndAff);
  120454. codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
  120455. }else{
  120456. assert( pParse->db->mallocFailed );
  120457. }
  120458. nConstraint += nTop;
  120459. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  120460. if( sqlite3ExprIsVector(pRight)==0 ){
  120461. disableTerm(pLevel, pRangeEnd);
  120462. }else{
  120463. endEq = 1;
  120464. }
  120465. }else if( bStopAtNull ){
  120466. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  120467. endEq = 0;
  120468. nConstraint++;
  120469. }
  120470. sqlite3DbFree(db, zStartAff);
  120471. sqlite3DbFree(db, zEndAff);
  120472. /* Top of the loop body */
  120473. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  120474. /* Check if the index cursor is past the end of the range. */
  120475. if( nConstraint ){
  120476. op = aEndOp[bRev*2 + endEq];
  120477. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  120478. testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
  120479. testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
  120480. testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
  120481. testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
  120482. }
  120483. /* Seek the table cursor, if required */
  120484. if( omitTable ){
  120485. /* pIdx is a covering index. No need to access the main table. */
  120486. }else if( HasRowid(pIdx->pTable) ){
  120487. if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || (
  120488. (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE)
  120489. && (pWInfo->eOnePass==ONEPASS_SINGLE)
  120490. )){
  120491. iRowidReg = ++pParse->nMem;
  120492. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  120493. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  120494. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
  120495. VdbeCoverage(v);
  120496. }else{
  120497. codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
  120498. }
  120499. }else if( iCur!=iIdxCur ){
  120500. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  120501. iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  120502. for(j=0; j<pPk->nKeyCol; j++){
  120503. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  120504. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
  120505. }
  120506. sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
  120507. iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
  120508. }
  120509. /* If pIdx is an index on one or more expressions, then look through
  120510. ** all the expressions in pWInfo and try to transform matching expressions
  120511. ** into reference to index columns.
  120512. */
  120513. whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo);
  120514. /* Record the instruction used to terminate the loop. */
  120515. if( pLoop->wsFlags & WHERE_ONEROW ){
  120516. pLevel->op = OP_Noop;
  120517. }else if( bRev ){
  120518. pLevel->op = OP_Prev;
  120519. }else{
  120520. pLevel->op = OP_Next;
  120521. }
  120522. pLevel->p1 = iIdxCur;
  120523. pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
  120524. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  120525. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  120526. }else{
  120527. assert( pLevel->p5==0 );
  120528. }
  120529. if( omitTable ) pIdx = 0;
  120530. }else
  120531. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  120532. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  120533. /* Case 5: Two or more separately indexed terms connected by OR
  120534. **
  120535. ** Example:
  120536. **
  120537. ** CREATE TABLE t1(a,b,c,d);
  120538. ** CREATE INDEX i1 ON t1(a);
  120539. ** CREATE INDEX i2 ON t1(b);
  120540. ** CREATE INDEX i3 ON t1(c);
  120541. **
  120542. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  120543. **
  120544. ** In the example, there are three indexed terms connected by OR.
  120545. ** The top of the loop looks like this:
  120546. **
  120547. ** Null 1 # Zero the rowset in reg 1
  120548. **
  120549. ** Then, for each indexed term, the following. The arguments to
  120550. ** RowSetTest are such that the rowid of the current row is inserted
  120551. ** into the RowSet. If it is already present, control skips the
  120552. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  120553. **
  120554. ** sqlite3WhereBegin(<term>)
  120555. ** RowSetTest # Insert rowid into rowset
  120556. ** Gosub 2 A
  120557. ** sqlite3WhereEnd()
  120558. **
  120559. ** Following the above, code to terminate the loop. Label A, the target
  120560. ** of the Gosub above, jumps to the instruction right after the Goto.
  120561. **
  120562. ** Null 1 # Zero the rowset in reg 1
  120563. ** Goto B # The loop is finished.
  120564. **
  120565. ** A: <loop body> # Return data, whatever.
  120566. **
  120567. ** Return 2 # Jump back to the Gosub
  120568. **
  120569. ** B: <after the loop>
  120570. **
  120571. ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
  120572. ** use an ephemeral index instead of a RowSet to record the primary
  120573. ** keys of the rows we have already seen.
  120574. **
  120575. */
  120576. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  120577. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  120578. Index *pCov = 0; /* Potential covering index (or NULL) */
  120579. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  120580. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  120581. int regRowset = 0; /* Register for RowSet object */
  120582. int regRowid = 0; /* Register holding rowid */
  120583. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  120584. int iRetInit; /* Address of regReturn init */
  120585. int untestedTerms = 0; /* Some terms not completely tested */
  120586. int ii; /* Loop counter */
  120587. u16 wctrlFlags; /* Flags for sub-WHERE clause */
  120588. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  120589. Table *pTab = pTabItem->pTab;
  120590. pTerm = pLoop->aLTerm[0];
  120591. assert( pTerm!=0 );
  120592. assert( pTerm->eOperator & WO_OR );
  120593. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  120594. pOrWc = &pTerm->u.pOrInfo->wc;
  120595. pLevel->op = OP_Return;
  120596. pLevel->p1 = regReturn;
  120597. /* Set up a new SrcList in pOrTab containing the table being scanned
  120598. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  120599. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  120600. */
  120601. if( pWInfo->nLevel>1 ){
  120602. int nNotReady; /* The number of notReady tables */
  120603. struct SrcList_item *origSrc; /* Original list of tables */
  120604. nNotReady = pWInfo->nLevel - iLevel - 1;
  120605. pOrTab = sqlite3StackAllocRaw(db,
  120606. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  120607. if( pOrTab==0 ) return notReady;
  120608. pOrTab->nAlloc = (u8)(nNotReady + 1);
  120609. pOrTab->nSrc = pOrTab->nAlloc;
  120610. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  120611. origSrc = pWInfo->pTabList->a;
  120612. for(k=1; k<=nNotReady; k++){
  120613. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  120614. }
  120615. }else{
  120616. pOrTab = pWInfo->pTabList;
  120617. }
  120618. /* Initialize the rowset register to contain NULL. An SQL NULL is
  120619. ** equivalent to an empty rowset. Or, create an ephemeral index
  120620. ** capable of holding primary keys in the case of a WITHOUT ROWID.
  120621. **
  120622. ** Also initialize regReturn to contain the address of the instruction
  120623. ** immediately following the OP_Return at the bottom of the loop. This
  120624. ** is required in a few obscure LEFT JOIN cases where control jumps
  120625. ** over the top of the loop into the body of it. In this case the
  120626. ** correct response for the end-of-loop code (the OP_Return) is to
  120627. ** fall through to the next instruction, just as an OP_Next does if
  120628. ** called on an uninitialized cursor.
  120629. */
  120630. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  120631. if( HasRowid(pTab) ){
  120632. regRowset = ++pParse->nMem;
  120633. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  120634. }else{
  120635. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  120636. regRowset = pParse->nTab++;
  120637. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
  120638. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  120639. }
  120640. regRowid = ++pParse->nMem;
  120641. }
  120642. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  120643. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  120644. ** Then for every term xN, evaluate as the subexpression: xN AND z
  120645. ** That way, terms in y that are factored into the disjunction will
  120646. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  120647. **
  120648. ** Actually, each subexpression is converted to "xN AND w" where w is
  120649. ** the "interesting" terms of z - terms that did not originate in the
  120650. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  120651. ** indices.
  120652. **
  120653. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  120654. ** is not contained in the ON clause of a LEFT JOIN.
  120655. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  120656. */
  120657. if( pWC->nTerm>1 ){
  120658. int iTerm;
  120659. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  120660. Expr *pExpr = pWC->a[iTerm].pExpr;
  120661. if( &pWC->a[iTerm] == pTerm ) continue;
  120662. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  120663. testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
  120664. testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
  120665. if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
  120666. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  120667. testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
  120668. pExpr = sqlite3ExprDup(db, pExpr, 0);
  120669. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  120670. }
  120671. if( pAndExpr ){
  120672. pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr);
  120673. }
  120674. }
  120675. /* Run a separate WHERE clause for each term of the OR clause. After
  120676. ** eliminating duplicates from other WHERE clauses, the action for each
  120677. ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
  120678. */
  120679. wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
  120680. for(ii=0; ii<pOrWc->nTerm; ii++){
  120681. WhereTerm *pOrTerm = &pOrWc->a[ii];
  120682. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  120683. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  120684. Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
  120685. int jmp1 = 0; /* Address of jump operation */
  120686. if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
  120687. pAndExpr->pLeft = pOrExpr;
  120688. pOrExpr = pAndExpr;
  120689. }
  120690. /* Loop through table entries that match term pOrTerm. */
  120691. WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
  120692. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  120693. wctrlFlags, iCovCur);
  120694. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  120695. if( pSubWInfo ){
  120696. WhereLoop *pSubLoop;
  120697. int addrExplain = sqlite3WhereExplainOneScan(
  120698. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  120699. );
  120700. sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
  120701. /* This is the sub-WHERE clause body. First skip over
  120702. ** duplicate rows from prior sub-WHERE clauses, and record the
  120703. ** rowid (or PRIMARY KEY) for the current row so that the same
  120704. ** row will be skipped in subsequent sub-WHERE clauses.
  120705. */
  120706. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  120707. int r;
  120708. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  120709. if( HasRowid(pTab) ){
  120710. r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
  120711. jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
  120712. r,iSet);
  120713. VdbeCoverage(v);
  120714. }else{
  120715. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  120716. int nPk = pPk->nKeyCol;
  120717. int iPk;
  120718. /* Read the PK into an array of temp registers. */
  120719. r = sqlite3GetTempRange(pParse, nPk);
  120720. for(iPk=0; iPk<nPk; iPk++){
  120721. int iCol = pPk->aiColumn[iPk];
  120722. sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
  120723. }
  120724. /* Check if the temp table already contains this key. If so,
  120725. ** the row has already been included in the result set and
  120726. ** can be ignored (by jumping past the Gosub below). Otherwise,
  120727. ** insert the key into the temp table and proceed with processing
  120728. ** the row.
  120729. **
  120730. ** Use some of the same optimizations as OP_RowSetTest: If iSet
  120731. ** is zero, assume that the key cannot already be present in
  120732. ** the temp table. And if iSet is -1, assume that there is no
  120733. ** need to insert the key into the temp table, as it will never
  120734. ** be tested for. */
  120735. if( iSet ){
  120736. jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
  120737. VdbeCoverage(v);
  120738. }
  120739. if( iSet>=0 ){
  120740. sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
  120741. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
  120742. r, nPk);
  120743. if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  120744. }
  120745. /* Release the array of temp registers */
  120746. sqlite3ReleaseTempRange(pParse, r, nPk);
  120747. }
  120748. }
  120749. /* Invoke the main loop body as a subroutine */
  120750. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  120751. /* Jump here (skipping the main loop body subroutine) if the
  120752. ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
  120753. if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
  120754. /* The pSubWInfo->untestedTerms flag means that this OR term
  120755. ** contained one or more AND term from a notReady table. The
  120756. ** terms from the notReady table could not be tested and will
  120757. ** need to be tested later.
  120758. */
  120759. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  120760. /* If all of the OR-connected terms are optimized using the same
  120761. ** index, and the index is opened using the same cursor number
  120762. ** by each call to sqlite3WhereBegin() made by this loop, it may
  120763. ** be possible to use that index as a covering index.
  120764. **
  120765. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  120766. ** uses an index, and this is either the first OR-connected term
  120767. ** processed or the index is the same as that used by all previous
  120768. ** terms, set pCov to the candidate covering index. Otherwise, set
  120769. ** pCov to NULL to indicate that no candidate covering index will
  120770. ** be available.
  120771. */
  120772. pSubLoop = pSubWInfo->a[0].pWLoop;
  120773. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  120774. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  120775. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  120776. && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
  120777. ){
  120778. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  120779. pCov = pSubLoop->u.btree.pIndex;
  120780. }else{
  120781. pCov = 0;
  120782. }
  120783. /* Finish the loop through table entries that match term pOrTerm. */
  120784. sqlite3WhereEnd(pSubWInfo);
  120785. }
  120786. }
  120787. }
  120788. pLevel->u.pCovidx = pCov;
  120789. if( pCov ) pLevel->iIdxCur = iCovCur;
  120790. if( pAndExpr ){
  120791. pAndExpr->pLeft = 0;
  120792. sqlite3ExprDelete(db, pAndExpr);
  120793. }
  120794. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  120795. sqlite3VdbeGoto(v, pLevel->addrBrk);
  120796. sqlite3VdbeResolveLabel(v, iLoopBody);
  120797. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  120798. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  120799. }else
  120800. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  120801. {
  120802. /* Case 6: There is no usable index. We must do a complete
  120803. ** scan of the entire table.
  120804. */
  120805. static const u8 aStep[] = { OP_Next, OP_Prev };
  120806. static const u8 aStart[] = { OP_Rewind, OP_Last };
  120807. assert( bRev==0 || bRev==1 );
  120808. if( pTabItem->fg.isRecursive ){
  120809. /* Tables marked isRecursive have only a single row that is stored in
  120810. ** a pseudo-cursor. No need to Rewind or Next such cursors. */
  120811. pLevel->op = OP_Noop;
  120812. }else{
  120813. codeCursorHint(pTabItem, pWInfo, pLevel, 0);
  120814. pLevel->op = aStep[bRev];
  120815. pLevel->p1 = iCur;
  120816. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
  120817. VdbeCoverageIf(v, bRev==0);
  120818. VdbeCoverageIf(v, bRev!=0);
  120819. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  120820. }
  120821. }
  120822. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  120823. pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
  120824. #endif
  120825. /* Insert code to test every subexpression that can be completely
  120826. ** computed using the current set of tables.
  120827. **
  120828. ** This loop may run either once (pIdx==0) or twice (pIdx!=0). If
  120829. ** it is run twice, then the first iteration codes those sub-expressions
  120830. ** that can be computed using columns from pIdx only (without seeking
  120831. ** the main table cursor).
  120832. */
  120833. do{
  120834. loopAgain = 0;
  120835. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  120836. Expr *pE;
  120837. int skipLikeAddr = 0;
  120838. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  120839. testcase( pTerm->wtFlags & TERM_CODED );
  120840. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  120841. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  120842. testcase( pWInfo->untestedTerms==0
  120843. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
  120844. pWInfo->untestedTerms = 1;
  120845. continue;
  120846. }
  120847. pE = pTerm->pExpr;
  120848. assert( pE!=0 );
  120849. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  120850. continue;
  120851. }
  120852. if( pIdx && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
  120853. loopAgain = 1;
  120854. continue;
  120855. }
  120856. if( pTerm->wtFlags & TERM_LIKECOND ){
  120857. /* If the TERM_LIKECOND flag is set, that means that the range search
  120858. ** is sufficient to guarantee that the LIKE operator is true, so we
  120859. ** can skip the call to the like(A,B) function. But this only works
  120860. ** for strings. So do not skip the call to the function on the pass
  120861. ** that compares BLOBs. */
  120862. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  120863. continue;
  120864. #else
  120865. u32 x = pLevel->iLikeRepCntr;
  120866. assert( x>0 );
  120867. skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If, (int)(x>>1));
  120868. VdbeCoverage(v);
  120869. #endif
  120870. }
  120871. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  120872. if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
  120873. pTerm->wtFlags |= TERM_CODED;
  120874. }
  120875. pIdx = 0;
  120876. }while( loopAgain );
  120877. /* Insert code to test for implied constraints based on transitivity
  120878. ** of the "==" operator.
  120879. **
  120880. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  120881. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  120882. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  120883. ** the implied "t1.a=123" constraint.
  120884. */
  120885. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  120886. Expr *pE, sEAlt;
  120887. WhereTerm *pAlt;
  120888. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  120889. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
  120890. if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
  120891. if( pTerm->leftCursor!=iCur ) continue;
  120892. if( pLevel->iLeftJoin ) continue;
  120893. pE = pTerm->pExpr;
  120894. assert( !ExprHasProperty(pE, EP_FromJoin) );
  120895. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  120896. pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
  120897. WO_EQ|WO_IN|WO_IS, 0);
  120898. if( pAlt==0 ) continue;
  120899. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  120900. testcase( pAlt->eOperator & WO_EQ );
  120901. testcase( pAlt->eOperator & WO_IS );
  120902. testcase( pAlt->eOperator & WO_IN );
  120903. VdbeModuleComment((v, "begin transitive constraint"));
  120904. sEAlt = *pAlt->pExpr;
  120905. sEAlt.pLeft = pE->pLeft;
  120906. sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
  120907. }
  120908. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  120909. ** at least one row of the right table has matched the left table.
  120910. */
  120911. if( pLevel->iLeftJoin ){
  120912. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  120913. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  120914. VdbeComment((v, "record LEFT JOIN hit"));
  120915. sqlite3ExprCacheClear(pParse);
  120916. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  120917. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  120918. testcase( pTerm->wtFlags & TERM_CODED );
  120919. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  120920. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  120921. assert( pWInfo->untestedTerms );
  120922. continue;
  120923. }
  120924. assert( pTerm->pExpr );
  120925. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  120926. pTerm->wtFlags |= TERM_CODED;
  120927. }
  120928. }
  120929. return pLevel->notReady;
  120930. }
  120931. /************** End of wherecode.c *******************************************/
  120932. /************** Begin file whereexpr.c ***************************************/
  120933. /*
  120934. ** 2015-06-08
  120935. **
  120936. ** The author disclaims copyright to this source code. In place of
  120937. ** a legal notice, here is a blessing:
  120938. **
  120939. ** May you do good and not evil.
  120940. ** May you find forgiveness for yourself and forgive others.
  120941. ** May you share freely, never taking more than you give.
  120942. **
  120943. *************************************************************************
  120944. ** This module contains C code that generates VDBE code used to process
  120945. ** the WHERE clause of SQL statements.
  120946. **
  120947. ** This file was originally part of where.c but was split out to improve
  120948. ** readability and editabiliity. This file contains utility routines for
  120949. ** analyzing Expr objects in the WHERE clause.
  120950. */
  120951. /* #include "sqliteInt.h" */
  120952. /* #include "whereInt.h" */
  120953. /* Forward declarations */
  120954. static void exprAnalyze(SrcList*, WhereClause*, int);
  120955. /*
  120956. ** Deallocate all memory associated with a WhereOrInfo object.
  120957. */
  120958. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  120959. sqlite3WhereClauseClear(&p->wc);
  120960. sqlite3DbFree(db, p);
  120961. }
  120962. /*
  120963. ** Deallocate all memory associated with a WhereAndInfo object.
  120964. */
  120965. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  120966. sqlite3WhereClauseClear(&p->wc);
  120967. sqlite3DbFree(db, p);
  120968. }
  120969. /*
  120970. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  120971. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  120972. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  120973. ** 0 is returned if the new WhereTerm could not be added due to a memory
  120974. ** allocation error. The memory allocation failure will be recorded in
  120975. ** the db->mallocFailed flag so that higher-level functions can detect it.
  120976. **
  120977. ** This routine will increase the size of the pWC->a[] array as necessary.
  120978. **
  120979. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  120980. ** for freeing the expression p is assumed by the WhereClause object pWC.
  120981. ** This is true even if this routine fails to allocate a new WhereTerm.
  120982. **
  120983. ** WARNING: This routine might reallocate the space used to store
  120984. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  120985. ** calling this routine. Such pointers may be reinitialized by referencing
  120986. ** the pWC->a[] array.
  120987. */
  120988. static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
  120989. WhereTerm *pTerm;
  120990. int idx;
  120991. testcase( wtFlags & TERM_VIRTUAL );
  120992. if( pWC->nTerm>=pWC->nSlot ){
  120993. WhereTerm *pOld = pWC->a;
  120994. sqlite3 *db = pWC->pWInfo->pParse->db;
  120995. pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  120996. if( pWC->a==0 ){
  120997. if( wtFlags & TERM_DYNAMIC ){
  120998. sqlite3ExprDelete(db, p);
  120999. }
  121000. pWC->a = pOld;
  121001. return 0;
  121002. }
  121003. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  121004. if( pOld!=pWC->aStatic ){
  121005. sqlite3DbFree(db, pOld);
  121006. }
  121007. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  121008. }
  121009. pTerm = &pWC->a[idx = pWC->nTerm++];
  121010. if( p && ExprHasProperty(p, EP_Unlikely) ){
  121011. pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
  121012. }else{
  121013. pTerm->truthProb = 1;
  121014. }
  121015. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  121016. pTerm->wtFlags = wtFlags;
  121017. pTerm->pWC = pWC;
  121018. pTerm->iParent = -1;
  121019. memset(&pTerm->eOperator, 0,
  121020. sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
  121021. return idx;
  121022. }
  121023. /*
  121024. ** Return TRUE if the given operator is one of the operators that is
  121025. ** allowed for an indexable WHERE clause term. The allowed operators are
  121026. ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
  121027. */
  121028. static int allowedOp(int op){
  121029. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  121030. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  121031. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  121032. assert( TK_GE==TK_EQ+4 );
  121033. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
  121034. }
  121035. /*
  121036. ** Commute a comparison operator. Expressions of the form "X op Y"
  121037. ** are converted into "Y op X".
  121038. **
  121039. ** If left/right precedence rules come into play when determining the
  121040. ** collating sequence, then COLLATE operators are adjusted to ensure
  121041. ** that the collating sequence does not change. For example:
  121042. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  121043. ** the left hand side of a comparison overrides any collation sequence
  121044. ** attached to the right. For the same reason the EP_Collate flag
  121045. ** is not commuted.
  121046. */
  121047. static void exprCommute(Parse *pParse, Expr *pExpr){
  121048. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  121049. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  121050. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  121051. if( expRight==expLeft ){
  121052. /* Either X and Y both have COLLATE operator or neither do */
  121053. if( expRight ){
  121054. /* Both X and Y have COLLATE operators. Make sure X is always
  121055. ** used by clearing the EP_Collate flag from Y. */
  121056. pExpr->pRight->flags &= ~EP_Collate;
  121057. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  121058. /* Neither X nor Y have COLLATE operators, but X has a non-default
  121059. ** collating sequence. So add the EP_Collate marker on X to cause
  121060. ** it to be searched first. */
  121061. pExpr->pLeft->flags |= EP_Collate;
  121062. }
  121063. }
  121064. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  121065. if( pExpr->op>=TK_GT ){
  121066. assert( TK_LT==TK_GT+2 );
  121067. assert( TK_GE==TK_LE+2 );
  121068. assert( TK_GT>TK_EQ );
  121069. assert( TK_GT<TK_LE );
  121070. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  121071. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  121072. }
  121073. }
  121074. /*
  121075. ** Translate from TK_xx operator to WO_xx bitmask.
  121076. */
  121077. static u16 operatorMask(int op){
  121078. u16 c;
  121079. assert( allowedOp(op) );
  121080. if( op==TK_IN ){
  121081. c = WO_IN;
  121082. }else if( op==TK_ISNULL ){
  121083. c = WO_ISNULL;
  121084. }else if( op==TK_IS ){
  121085. c = WO_IS;
  121086. }else{
  121087. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  121088. c = (u16)(WO_EQ<<(op-TK_EQ));
  121089. }
  121090. assert( op!=TK_ISNULL || c==WO_ISNULL );
  121091. assert( op!=TK_IN || c==WO_IN );
  121092. assert( op!=TK_EQ || c==WO_EQ );
  121093. assert( op!=TK_LT || c==WO_LT );
  121094. assert( op!=TK_LE || c==WO_LE );
  121095. assert( op!=TK_GT || c==WO_GT );
  121096. assert( op!=TK_GE || c==WO_GE );
  121097. assert( op!=TK_IS || c==WO_IS );
  121098. return c;
  121099. }
  121100. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  121101. /*
  121102. ** Check to see if the given expression is a LIKE or GLOB operator that
  121103. ** can be optimized using inequality constraints. Return TRUE if it is
  121104. ** so and false if not.
  121105. **
  121106. ** In order for the operator to be optimizible, the RHS must be a string
  121107. ** literal that does not begin with a wildcard. The LHS must be a column
  121108. ** that may only be NULL, a string, or a BLOB, never a number. (This means
  121109. ** that virtual tables cannot participate in the LIKE optimization.) The
  121110. ** collating sequence for the column on the LHS must be appropriate for
  121111. ** the operator.
  121112. */
  121113. static int isLikeOrGlob(
  121114. Parse *pParse, /* Parsing and code generating context */
  121115. Expr *pExpr, /* Test this expression */
  121116. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  121117. int *pisComplete, /* True if the only wildcard is % in the last character */
  121118. int *pnoCase /* True if uppercase is equivalent to lowercase */
  121119. ){
  121120. const char *z = 0; /* String on RHS of LIKE operator */
  121121. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  121122. ExprList *pList; /* List of operands to the LIKE operator */
  121123. int c; /* One character in z[] */
  121124. int cnt; /* Number of non-wildcard prefix characters */
  121125. char wc[3]; /* Wildcard characters */
  121126. sqlite3 *db = pParse->db; /* Database connection */
  121127. sqlite3_value *pVal = 0;
  121128. int op; /* Opcode of pRight */
  121129. int rc; /* Result code to return */
  121130. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  121131. return 0;
  121132. }
  121133. #ifdef SQLITE_EBCDIC
  121134. if( *pnoCase ) return 0;
  121135. #endif
  121136. pList = pExpr->x.pList;
  121137. pLeft = pList->a[1].pExpr;
  121138. pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  121139. op = pRight->op;
  121140. if( op==TK_VARIABLE ){
  121141. Vdbe *pReprepare = pParse->pReprepare;
  121142. int iCol = pRight->iColumn;
  121143. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
  121144. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  121145. z = (char *)sqlite3_value_text(pVal);
  121146. }
  121147. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  121148. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  121149. }else if( op==TK_STRING ){
  121150. z = pRight->u.zToken;
  121151. }
  121152. if( z ){
  121153. /* If the RHS begins with a digit or a minus sign, then the LHS must
  121154. ** be an ordinary column (not a virtual table column) with TEXT affinity.
  121155. ** Otherwise the LHS might be numeric and "lhs >= rhs" would be false
  121156. ** even though "lhs LIKE rhs" is true. But if the RHS does not start
  121157. ** with a digit or '-', then "lhs LIKE rhs" will always be false if
  121158. ** the LHS is numeric and so the optimization still works.
  121159. */
  121160. if( sqlite3Isdigit(z[0]) || z[0]=='-' ){
  121161. if( pLeft->op!=TK_COLUMN
  121162. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  121163. || IsVirtual(pLeft->pTab) /* Value might be numeric */
  121164. ){
  121165. sqlite3ValueFree(pVal);
  121166. return 0;
  121167. }
  121168. }
  121169. cnt = 0;
  121170. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  121171. cnt++;
  121172. }
  121173. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  121174. Expr *pPrefix;
  121175. *pisComplete = c==wc[0] && z[cnt+1]==0;
  121176. pPrefix = sqlite3Expr(db, TK_STRING, z);
  121177. if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
  121178. *ppPrefix = pPrefix;
  121179. if( op==TK_VARIABLE ){
  121180. Vdbe *v = pParse->pVdbe;
  121181. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  121182. if( *pisComplete && pRight->u.zToken[1] ){
  121183. /* If the rhs of the LIKE expression is a variable, and the current
  121184. ** value of the variable means there is no need to invoke the LIKE
  121185. ** function, then no OP_Variable will be added to the program.
  121186. ** This causes problems for the sqlite3_bind_parameter_name()
  121187. ** API. To work around them, add a dummy OP_Variable here.
  121188. */
  121189. int r1 = sqlite3GetTempReg(pParse);
  121190. sqlite3ExprCodeTarget(pParse, pRight, r1);
  121191. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  121192. sqlite3ReleaseTempReg(pParse, r1);
  121193. }
  121194. }
  121195. }else{
  121196. z = 0;
  121197. }
  121198. }
  121199. rc = (z!=0);
  121200. sqlite3ValueFree(pVal);
  121201. return rc;
  121202. }
  121203. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  121204. #ifndef SQLITE_OMIT_VIRTUALTABLE
  121205. /*
  121206. ** Check to see if the given expression is of the form
  121207. **
  121208. ** column OP expr
  121209. **
  121210. ** where OP is one of MATCH, GLOB, LIKE or REGEXP and "column" is a
  121211. ** column of a virtual table.
  121212. **
  121213. ** If it is then return TRUE. If not, return FALSE.
  121214. */
  121215. static int isMatchOfColumn(
  121216. Expr *pExpr, /* Test this expression */
  121217. unsigned char *peOp2 /* OUT: 0 for MATCH, or else an op2 value */
  121218. ){
  121219. static const struct Op2 {
  121220. const char *zOp;
  121221. unsigned char eOp2;
  121222. } aOp[] = {
  121223. { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
  121224. { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
  121225. { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
  121226. { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
  121227. };
  121228. ExprList *pList;
  121229. Expr *pCol; /* Column reference */
  121230. int i;
  121231. if( pExpr->op!=TK_FUNCTION ){
  121232. return 0;
  121233. }
  121234. pList = pExpr->x.pList;
  121235. if( pList==0 || pList->nExpr!=2 ){
  121236. return 0;
  121237. }
  121238. pCol = pList->a[1].pExpr;
  121239. if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
  121240. return 0;
  121241. }
  121242. for(i=0; i<ArraySize(aOp); i++){
  121243. if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
  121244. *peOp2 = aOp[i].eOp2;
  121245. return 1;
  121246. }
  121247. }
  121248. return 0;
  121249. }
  121250. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  121251. /*
  121252. ** If the pBase expression originated in the ON or USING clause of
  121253. ** a join, then transfer the appropriate markings over to derived.
  121254. */
  121255. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  121256. if( pDerived ){
  121257. pDerived->flags |= pBase->flags & EP_FromJoin;
  121258. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  121259. }
  121260. }
  121261. /*
  121262. ** Mark term iChild as being a child of term iParent
  121263. */
  121264. static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
  121265. pWC->a[iChild].iParent = iParent;
  121266. pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
  121267. pWC->a[iParent].nChild++;
  121268. }
  121269. /*
  121270. ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
  121271. ** a conjunction, then return just pTerm when N==0. If N is exceeds
  121272. ** the number of available subterms, return NULL.
  121273. */
  121274. static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
  121275. if( pTerm->eOperator!=WO_AND ){
  121276. return N==0 ? pTerm : 0;
  121277. }
  121278. if( N<pTerm->u.pAndInfo->wc.nTerm ){
  121279. return &pTerm->u.pAndInfo->wc.a[N];
  121280. }
  121281. return 0;
  121282. }
  121283. /*
  121284. ** Subterms pOne and pTwo are contained within WHERE clause pWC. The
  121285. ** two subterms are in disjunction - they are OR-ed together.
  121286. **
  121287. ** If these two terms are both of the form: "A op B" with the same
  121288. ** A and B values but different operators and if the operators are
  121289. ** compatible (if one is = and the other is <, for example) then
  121290. ** add a new virtual AND term to pWC that is the combination of the
  121291. ** two.
  121292. **
  121293. ** Some examples:
  121294. **
  121295. ** x<y OR x=y --> x<=y
  121296. ** x=y OR x=y --> x=y
  121297. ** x<=y OR x<y --> x<=y
  121298. **
  121299. ** The following is NOT generated:
  121300. **
  121301. ** x<y OR x>y --> x!=y
  121302. */
  121303. static void whereCombineDisjuncts(
  121304. SrcList *pSrc, /* the FROM clause */
  121305. WhereClause *pWC, /* The complete WHERE clause */
  121306. WhereTerm *pOne, /* First disjunct */
  121307. WhereTerm *pTwo /* Second disjunct */
  121308. ){
  121309. u16 eOp = pOne->eOperator | pTwo->eOperator;
  121310. sqlite3 *db; /* Database connection (for malloc) */
  121311. Expr *pNew; /* New virtual expression */
  121312. int op; /* Operator for the combined expression */
  121313. int idxNew; /* Index in pWC of the next virtual term */
  121314. if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  121315. if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  121316. if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
  121317. && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
  121318. assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
  121319. assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
  121320. if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
  121321. if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
  121322. /* If we reach this point, it means the two subterms can be combined */
  121323. if( (eOp & (eOp-1))!=0 ){
  121324. if( eOp & (WO_LT|WO_LE) ){
  121325. eOp = WO_LE;
  121326. }else{
  121327. assert( eOp & (WO_GT|WO_GE) );
  121328. eOp = WO_GE;
  121329. }
  121330. }
  121331. db = pWC->pWInfo->pParse->db;
  121332. pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
  121333. if( pNew==0 ) return;
  121334. for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
  121335. pNew->op = op;
  121336. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  121337. exprAnalyze(pSrc, pWC, idxNew);
  121338. }
  121339. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  121340. /*
  121341. ** Analyze a term that consists of two or more OR-connected
  121342. ** subterms. So in:
  121343. **
  121344. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  121345. ** ^^^^^^^^^^^^^^^^^^^^
  121346. **
  121347. ** This routine analyzes terms such as the middle term in the above example.
  121348. ** A WhereOrTerm object is computed and attached to the term under
  121349. ** analysis, regardless of the outcome of the analysis. Hence:
  121350. **
  121351. ** WhereTerm.wtFlags |= TERM_ORINFO
  121352. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  121353. **
  121354. ** The term being analyzed must have two or more of OR-connected subterms.
  121355. ** A single subterm might be a set of AND-connected sub-subterms.
  121356. ** Examples of terms under analysis:
  121357. **
  121358. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  121359. ** (B) x=expr1 OR expr2=x OR x=expr3
  121360. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  121361. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  121362. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  121363. ** (F) x>A OR (x=A AND y>=B)
  121364. **
  121365. ** CASE 1:
  121366. **
  121367. ** If all subterms are of the form T.C=expr for some single column of C and
  121368. ** a single table T (as shown in example B above) then create a new virtual
  121369. ** term that is an equivalent IN expression. In other words, if the term
  121370. ** being analyzed is:
  121371. **
  121372. ** x = expr1 OR expr2 = x OR x = expr3
  121373. **
  121374. ** then create a new virtual term like this:
  121375. **
  121376. ** x IN (expr1,expr2,expr3)
  121377. **
  121378. ** CASE 2:
  121379. **
  121380. ** If there are exactly two disjuncts and one side has x>A and the other side
  121381. ** has x=A (for the same x and A) then add a new virtual conjunct term to the
  121382. ** WHERE clause of the form "x>=A". Example:
  121383. **
  121384. ** x>A OR (x=A AND y>B) adds: x>=A
  121385. **
  121386. ** The added conjunct can sometimes be helpful in query planning.
  121387. **
  121388. ** CASE 3:
  121389. **
  121390. ** If all subterms are indexable by a single table T, then set
  121391. **
  121392. ** WhereTerm.eOperator = WO_OR
  121393. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  121394. **
  121395. ** A subterm is "indexable" if it is of the form
  121396. ** "T.C <op> <expr>" where C is any column of table T and
  121397. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  121398. ** A subterm is also indexable if it is an AND of two or more
  121399. ** subsubterms at least one of which is indexable. Indexable AND
  121400. ** subterms have their eOperator set to WO_AND and they have
  121401. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  121402. **
  121403. ** From another point of view, "indexable" means that the subterm could
  121404. ** potentially be used with an index if an appropriate index exists.
  121405. ** This analysis does not consider whether or not the index exists; that
  121406. ** is decided elsewhere. This analysis only looks at whether subterms
  121407. ** appropriate for indexing exist.
  121408. **
  121409. ** All examples A through E above satisfy case 3. But if a term
  121410. ** also satisfies case 1 (such as B) we know that the optimizer will
  121411. ** always prefer case 1, so in that case we pretend that case 3 is not
  121412. ** satisfied.
  121413. **
  121414. ** It might be the case that multiple tables are indexable. For example,
  121415. ** (E) above is indexable on tables P, Q, and R.
  121416. **
  121417. ** Terms that satisfy case 3 are candidates for lookup by using
  121418. ** separate indices to find rowids for each subterm and composing
  121419. ** the union of all rowids using a RowSet object. This is similar
  121420. ** to "bitmap indices" in other database engines.
  121421. **
  121422. ** OTHERWISE:
  121423. **
  121424. ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
  121425. ** zero. This term is not useful for search.
  121426. */
  121427. static void exprAnalyzeOrTerm(
  121428. SrcList *pSrc, /* the FROM clause */
  121429. WhereClause *pWC, /* the complete WHERE clause */
  121430. int idxTerm /* Index of the OR-term to be analyzed */
  121431. ){
  121432. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  121433. Parse *pParse = pWInfo->pParse; /* Parser context */
  121434. sqlite3 *db = pParse->db; /* Database connection */
  121435. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  121436. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  121437. int i; /* Loop counters */
  121438. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  121439. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  121440. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  121441. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  121442. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  121443. /*
  121444. ** Break the OR clause into its separate subterms. The subterms are
  121445. ** stored in a WhereClause structure containing within the WhereOrInfo
  121446. ** object that is attached to the original OR clause term.
  121447. */
  121448. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  121449. assert( pExpr->op==TK_OR );
  121450. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  121451. if( pOrInfo==0 ) return;
  121452. pTerm->wtFlags |= TERM_ORINFO;
  121453. pOrWc = &pOrInfo->wc;
  121454. memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
  121455. sqlite3WhereClauseInit(pOrWc, pWInfo);
  121456. sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
  121457. sqlite3WhereExprAnalyze(pSrc, pOrWc);
  121458. if( db->mallocFailed ) return;
  121459. assert( pOrWc->nTerm>=2 );
  121460. /*
  121461. ** Compute the set of tables that might satisfy cases 1 or 3.
  121462. */
  121463. indexable = ~(Bitmask)0;
  121464. chngToIN = ~(Bitmask)0;
  121465. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  121466. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  121467. WhereAndInfo *pAndInfo;
  121468. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  121469. chngToIN = 0;
  121470. pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
  121471. if( pAndInfo ){
  121472. WhereClause *pAndWC;
  121473. WhereTerm *pAndTerm;
  121474. int j;
  121475. Bitmask b = 0;
  121476. pOrTerm->u.pAndInfo = pAndInfo;
  121477. pOrTerm->wtFlags |= TERM_ANDINFO;
  121478. pOrTerm->eOperator = WO_AND;
  121479. pAndWC = &pAndInfo->wc;
  121480. memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
  121481. sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
  121482. sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  121483. sqlite3WhereExprAnalyze(pSrc, pAndWC);
  121484. pAndWC->pOuter = pWC;
  121485. if( !db->mallocFailed ){
  121486. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  121487. assert( pAndTerm->pExpr );
  121488. if( allowedOp(pAndTerm->pExpr->op)
  121489. || pAndTerm->eOperator==WO_MATCH
  121490. ){
  121491. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  121492. }
  121493. }
  121494. }
  121495. indexable &= b;
  121496. }
  121497. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  121498. /* Skip this term for now. We revisit it when we process the
  121499. ** corresponding TERM_VIRTUAL term */
  121500. }else{
  121501. Bitmask b;
  121502. b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  121503. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  121504. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  121505. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
  121506. }
  121507. indexable &= b;
  121508. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  121509. chngToIN = 0;
  121510. }else{
  121511. chngToIN &= b;
  121512. }
  121513. }
  121514. }
  121515. /*
  121516. ** Record the set of tables that satisfy case 3. The set might be
  121517. ** empty.
  121518. */
  121519. pOrInfo->indexable = indexable;
  121520. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  121521. /* For a two-way OR, attempt to implementation case 2.
  121522. */
  121523. if( indexable && pOrWc->nTerm==2 ){
  121524. int iOne = 0;
  121525. WhereTerm *pOne;
  121526. while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
  121527. int iTwo = 0;
  121528. WhereTerm *pTwo;
  121529. while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
  121530. whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
  121531. }
  121532. }
  121533. }
  121534. /*
  121535. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  121536. ** we have to do some additional checking to see if case 1 really
  121537. ** is satisfied.
  121538. **
  121539. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  121540. ** that there is no possibility of transforming the OR clause into an
  121541. ** IN operator because one or more terms in the OR clause contain
  121542. ** something other than == on a column in the single table. The 1-bit
  121543. ** case means that every term of the OR clause is of the form
  121544. ** "table.column=expr" for some single table. The one bit that is set
  121545. ** will correspond to the common table. We still need to check to make
  121546. ** sure the same column is used on all terms. The 2-bit case is when
  121547. ** the all terms are of the form "table1.column=table2.column". It
  121548. ** might be possible to form an IN operator with either table1.column
  121549. ** or table2.column as the LHS if either is common to every term of
  121550. ** the OR clause.
  121551. **
  121552. ** Note that terms of the form "table.column1=table.column2" (the
  121553. ** same table on both sizes of the ==) cannot be optimized.
  121554. */
  121555. if( chngToIN ){
  121556. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  121557. int iColumn = -1; /* Column index on lhs of IN operator */
  121558. int iCursor = -1; /* Table cursor common to all terms */
  121559. int j = 0; /* Loop counter */
  121560. /* Search for a table and column that appears on one side or the
  121561. ** other of the == operator in every subterm. That table and column
  121562. ** will be recorded in iCursor and iColumn. There might not be any
  121563. ** such table and column. Set okToChngToIN if an appropriate table
  121564. ** and column is found but leave okToChngToIN false if not found.
  121565. */
  121566. for(j=0; j<2 && !okToChngToIN; j++){
  121567. pOrTerm = pOrWc->a;
  121568. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  121569. assert( pOrTerm->eOperator & WO_EQ );
  121570. pOrTerm->wtFlags &= ~TERM_OR_OK;
  121571. if( pOrTerm->leftCursor==iCursor ){
  121572. /* This is the 2-bit case and we are on the second iteration and
  121573. ** current term is from the first iteration. So skip this term. */
  121574. assert( j==1 );
  121575. continue;
  121576. }
  121577. if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
  121578. pOrTerm->leftCursor))==0 ){
  121579. /* This term must be of the form t1.a==t2.b where t2 is in the
  121580. ** chngToIN set but t1 is not. This term will be either preceded
  121581. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  121582. ** and use its inversion. */
  121583. testcase( pOrTerm->wtFlags & TERM_COPIED );
  121584. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  121585. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  121586. continue;
  121587. }
  121588. iColumn = pOrTerm->u.leftColumn;
  121589. iCursor = pOrTerm->leftCursor;
  121590. break;
  121591. }
  121592. if( i<0 ){
  121593. /* No candidate table+column was found. This can only occur
  121594. ** on the second iteration */
  121595. assert( j==1 );
  121596. assert( IsPowerOfTwo(chngToIN) );
  121597. assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
  121598. break;
  121599. }
  121600. testcase( j==1 );
  121601. /* We have found a candidate table and column. Check to see if that
  121602. ** table and column is common to every term in the OR clause */
  121603. okToChngToIN = 1;
  121604. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  121605. assert( pOrTerm->eOperator & WO_EQ );
  121606. if( pOrTerm->leftCursor!=iCursor ){
  121607. pOrTerm->wtFlags &= ~TERM_OR_OK;
  121608. }else if( pOrTerm->u.leftColumn!=iColumn ){
  121609. okToChngToIN = 0;
  121610. }else{
  121611. int affLeft, affRight;
  121612. /* If the right-hand side is also a column, then the affinities
  121613. ** of both right and left sides must be such that no type
  121614. ** conversions are required on the right. (Ticket #2249)
  121615. */
  121616. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  121617. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  121618. if( affRight!=0 && affRight!=affLeft ){
  121619. okToChngToIN = 0;
  121620. }else{
  121621. pOrTerm->wtFlags |= TERM_OR_OK;
  121622. }
  121623. }
  121624. }
  121625. }
  121626. /* At this point, okToChngToIN is true if original pTerm satisfies
  121627. ** case 1. In that case, construct a new virtual term that is
  121628. ** pTerm converted into an IN operator.
  121629. */
  121630. if( okToChngToIN ){
  121631. Expr *pDup; /* A transient duplicate expression */
  121632. ExprList *pList = 0; /* The RHS of the IN operator */
  121633. Expr *pLeft = 0; /* The LHS of the IN operator */
  121634. Expr *pNew; /* The complete IN operator */
  121635. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  121636. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  121637. assert( pOrTerm->eOperator & WO_EQ );
  121638. assert( pOrTerm->leftCursor==iCursor );
  121639. assert( pOrTerm->u.leftColumn==iColumn );
  121640. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  121641. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  121642. pLeft = pOrTerm->pExpr->pLeft;
  121643. }
  121644. assert( pLeft!=0 );
  121645. pDup = sqlite3ExprDup(db, pLeft, 0);
  121646. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
  121647. if( pNew ){
  121648. int idxNew;
  121649. transferJoinMarkings(pNew, pExpr);
  121650. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  121651. pNew->x.pList = pList;
  121652. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  121653. testcase( idxNew==0 );
  121654. exprAnalyze(pSrc, pWC, idxNew);
  121655. pTerm = &pWC->a[idxTerm];
  121656. markTermAsChild(pWC, idxNew, idxTerm);
  121657. }else{
  121658. sqlite3ExprListDelete(db, pList);
  121659. }
  121660. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
  121661. }
  121662. }
  121663. }
  121664. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  121665. /*
  121666. ** We already know that pExpr is a binary operator where both operands are
  121667. ** column references. This routine checks to see if pExpr is an equivalence
  121668. ** relation:
  121669. ** 1. The SQLITE_Transitive optimization must be enabled
  121670. ** 2. Must be either an == or an IS operator
  121671. ** 3. Not originating in the ON clause of an OUTER JOIN
  121672. ** 4. The affinities of A and B must be compatible
  121673. ** 5a. Both operands use the same collating sequence OR
  121674. ** 5b. The overall collating sequence is BINARY
  121675. ** If this routine returns TRUE, that means that the RHS can be substituted
  121676. ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
  121677. ** This is an optimization. No harm comes from returning 0. But if 1 is
  121678. ** returned when it should not be, then incorrect answers might result.
  121679. */
  121680. static int termIsEquivalence(Parse *pParse, Expr *pExpr){
  121681. char aff1, aff2;
  121682. CollSeq *pColl;
  121683. const char *zColl1, *zColl2;
  121684. if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
  121685. if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
  121686. if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
  121687. aff1 = sqlite3ExprAffinity(pExpr->pLeft);
  121688. aff2 = sqlite3ExprAffinity(pExpr->pRight);
  121689. if( aff1!=aff2
  121690. && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
  121691. ){
  121692. return 0;
  121693. }
  121694. pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
  121695. if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
  121696. pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  121697. zColl1 = pColl ? pColl->zName : 0;
  121698. pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
  121699. zColl2 = pColl ? pColl->zName : 0;
  121700. return sqlite3_stricmp(zColl1, zColl2)==0;
  121701. }
  121702. /*
  121703. ** Recursively walk the expressions of a SELECT statement and generate
  121704. ** a bitmask indicating which tables are used in that expression
  121705. ** tree.
  121706. */
  121707. static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
  121708. Bitmask mask = 0;
  121709. while( pS ){
  121710. SrcList *pSrc = pS->pSrc;
  121711. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
  121712. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
  121713. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
  121714. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
  121715. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
  121716. if( ALWAYS(pSrc!=0) ){
  121717. int i;
  121718. for(i=0; i<pSrc->nSrc; i++){
  121719. mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
  121720. mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
  121721. }
  121722. }
  121723. pS = pS->pPrior;
  121724. }
  121725. return mask;
  121726. }
  121727. /*
  121728. ** Expression pExpr is one operand of a comparison operator that might
  121729. ** be useful for indexing. This routine checks to see if pExpr appears
  121730. ** in any index. Return TRUE (1) if pExpr is an indexed term and return
  121731. ** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor
  121732. ** number of the table that is indexed and aiCurCol[1] to the column number
  121733. ** of the column that is indexed, or XN_EXPR (-2) if an expression is being
  121734. ** indexed.
  121735. **
  121736. ** If pExpr is a TK_COLUMN column reference, then this routine always returns
  121737. ** true even if that particular column is not indexed, because the column
  121738. ** might be added to an automatic index later.
  121739. */
  121740. static SQLITE_NOINLINE int exprMightBeIndexed2(
  121741. SrcList *pFrom, /* The FROM clause */
  121742. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  121743. int *aiCurCol, /* Write the referenced table cursor and column here */
  121744. Expr *pExpr /* An operand of a comparison operator */
  121745. ){
  121746. Index *pIdx;
  121747. int i;
  121748. int iCur;
  121749. for(i=0; mPrereq>1; i++, mPrereq>>=1){}
  121750. iCur = pFrom->a[i].iCursor;
  121751. for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  121752. if( pIdx->aColExpr==0 ) continue;
  121753. for(i=0; i<pIdx->nKeyCol; i++){
  121754. if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
  121755. if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
  121756. aiCurCol[0] = iCur;
  121757. aiCurCol[1] = XN_EXPR;
  121758. return 1;
  121759. }
  121760. }
  121761. }
  121762. return 0;
  121763. }
  121764. static int exprMightBeIndexed(
  121765. SrcList *pFrom, /* The FROM clause */
  121766. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  121767. int *aiCurCol, /* Write the referenced table cursor & column here */
  121768. Expr *pExpr, /* An operand of a comparison operator */
  121769. int op /* The specific comparison operator */
  121770. ){
  121771. /* If this expression is a vector to the left or right of a
  121772. ** inequality constraint (>, <, >= or <=), perform the processing
  121773. ** on the first element of the vector. */
  121774. assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
  121775. assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
  121776. assert( op<=TK_GE );
  121777. if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
  121778. pExpr = pExpr->x.pList->a[0].pExpr;
  121779. }
  121780. if( pExpr->op==TK_COLUMN ){
  121781. aiCurCol[0] = pExpr->iTable;
  121782. aiCurCol[1] = pExpr->iColumn;
  121783. return 1;
  121784. }
  121785. if( mPrereq==0 ) return 0; /* No table references */
  121786. if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
  121787. return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
  121788. }
  121789. /*
  121790. ** The input to this routine is an WhereTerm structure with only the
  121791. ** "pExpr" field filled in. The job of this routine is to analyze the
  121792. ** subexpression and populate all the other fields of the WhereTerm
  121793. ** structure.
  121794. **
  121795. ** If the expression is of the form "<expr> <op> X" it gets commuted
  121796. ** to the standard form of "X <op> <expr>".
  121797. **
  121798. ** If the expression is of the form "X <op> Y" where both X and Y are
  121799. ** columns, then the original expression is unchanged and a new virtual
  121800. ** term of the form "Y <op> X" is added to the WHERE clause and
  121801. ** analyzed separately. The original term is marked with TERM_COPIED
  121802. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  121803. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  121804. ** is a commuted copy of a prior term.) The original term has nChild=1
  121805. ** and the copy has idxParent set to the index of the original term.
  121806. */
  121807. static void exprAnalyze(
  121808. SrcList *pSrc, /* the FROM clause */
  121809. WhereClause *pWC, /* the WHERE clause */
  121810. int idxTerm /* Index of the term to be analyzed */
  121811. ){
  121812. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  121813. WhereTerm *pTerm; /* The term to be analyzed */
  121814. WhereMaskSet *pMaskSet; /* Set of table index masks */
  121815. Expr *pExpr; /* The expression to be analyzed */
  121816. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  121817. Bitmask prereqAll; /* Prerequesites of pExpr */
  121818. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  121819. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  121820. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  121821. int noCase = 0; /* uppercase equivalent to lowercase */
  121822. int op; /* Top-level operator. pExpr->op */
  121823. Parse *pParse = pWInfo->pParse; /* Parsing context */
  121824. sqlite3 *db = pParse->db; /* Database connection */
  121825. unsigned char eOp2; /* op2 value for LIKE/REGEXP/GLOB */
  121826. int nLeft; /* Number of elements on left side vector */
  121827. if( db->mallocFailed ){
  121828. return;
  121829. }
  121830. pTerm = &pWC->a[idxTerm];
  121831. pMaskSet = &pWInfo->sMaskSet;
  121832. pExpr = pTerm->pExpr;
  121833. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  121834. prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
  121835. op = pExpr->op;
  121836. if( op==TK_IN ){
  121837. assert( pExpr->pRight==0 );
  121838. if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
  121839. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  121840. pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
  121841. }else{
  121842. pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
  121843. }
  121844. }else if( op==TK_ISNULL ){
  121845. pTerm->prereqRight = 0;
  121846. }else{
  121847. pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
  121848. }
  121849. prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
  121850. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  121851. Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
  121852. prereqAll |= x;
  121853. extraRight = x-1; /* ON clause terms may not be used with an index
  121854. ** on left table of a LEFT JOIN. Ticket #3015 */
  121855. if( (prereqAll>>1)>=x ){
  121856. sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
  121857. return;
  121858. }
  121859. }
  121860. pTerm->prereqAll = prereqAll;
  121861. pTerm->leftCursor = -1;
  121862. pTerm->iParent = -1;
  121863. pTerm->eOperator = 0;
  121864. if( allowedOp(op) ){
  121865. int aiCurCol[2];
  121866. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  121867. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  121868. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  121869. if( pTerm->iField>0 ){
  121870. assert( op==TK_IN );
  121871. assert( pLeft->op==TK_VECTOR );
  121872. pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
  121873. }
  121874. if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
  121875. pTerm->leftCursor = aiCurCol[0];
  121876. pTerm->u.leftColumn = aiCurCol[1];
  121877. pTerm->eOperator = operatorMask(op) & opMask;
  121878. }
  121879. if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
  121880. if( pRight
  121881. && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
  121882. ){
  121883. WhereTerm *pNew;
  121884. Expr *pDup;
  121885. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  121886. assert( pTerm->iField==0 );
  121887. if( pTerm->leftCursor>=0 ){
  121888. int idxNew;
  121889. pDup = sqlite3ExprDup(db, pExpr, 0);
  121890. if( db->mallocFailed ){
  121891. sqlite3ExprDelete(db, pDup);
  121892. return;
  121893. }
  121894. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  121895. if( idxNew==0 ) return;
  121896. pNew = &pWC->a[idxNew];
  121897. markTermAsChild(pWC, idxNew, idxTerm);
  121898. if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
  121899. pTerm = &pWC->a[idxTerm];
  121900. pTerm->wtFlags |= TERM_COPIED;
  121901. if( termIsEquivalence(pParse, pDup) ){
  121902. pTerm->eOperator |= WO_EQUIV;
  121903. eExtraOp = WO_EQUIV;
  121904. }
  121905. }else{
  121906. pDup = pExpr;
  121907. pNew = pTerm;
  121908. }
  121909. exprCommute(pParse, pDup);
  121910. pNew->leftCursor = aiCurCol[0];
  121911. pNew->u.leftColumn = aiCurCol[1];
  121912. testcase( (prereqLeft | extraRight) != prereqLeft );
  121913. pNew->prereqRight = prereqLeft | extraRight;
  121914. pNew->prereqAll = prereqAll;
  121915. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  121916. }
  121917. }
  121918. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  121919. /* If a term is the BETWEEN operator, create two new virtual terms
  121920. ** that define the range that the BETWEEN implements. For example:
  121921. **
  121922. ** a BETWEEN b AND c
  121923. **
  121924. ** is converted into:
  121925. **
  121926. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  121927. **
  121928. ** The two new terms are added onto the end of the WhereClause object.
  121929. ** The new terms are "dynamic" and are children of the original BETWEEN
  121930. ** term. That means that if the BETWEEN term is coded, the children are
  121931. ** skipped. Or, if the children are satisfied by an index, the original
  121932. ** BETWEEN term is skipped.
  121933. */
  121934. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  121935. ExprList *pList = pExpr->x.pList;
  121936. int i;
  121937. static const u8 ops[] = {TK_GE, TK_LE};
  121938. assert( pList!=0 );
  121939. assert( pList->nExpr==2 );
  121940. for(i=0; i<2; i++){
  121941. Expr *pNewExpr;
  121942. int idxNew;
  121943. pNewExpr = sqlite3PExpr(pParse, ops[i],
  121944. sqlite3ExprDup(db, pExpr->pLeft, 0),
  121945. sqlite3ExprDup(db, pList->a[i].pExpr, 0));
  121946. transferJoinMarkings(pNewExpr, pExpr);
  121947. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  121948. testcase( idxNew==0 );
  121949. exprAnalyze(pSrc, pWC, idxNew);
  121950. pTerm = &pWC->a[idxTerm];
  121951. markTermAsChild(pWC, idxNew, idxTerm);
  121952. }
  121953. }
  121954. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  121955. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  121956. /* Analyze a term that is composed of two or more subterms connected by
  121957. ** an OR operator.
  121958. */
  121959. else if( pExpr->op==TK_OR ){
  121960. assert( pWC->op==TK_AND );
  121961. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  121962. pTerm = &pWC->a[idxTerm];
  121963. }
  121964. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  121965. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  121966. /* Add constraints to reduce the search space on a LIKE or GLOB
  121967. ** operator.
  121968. **
  121969. ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
  121970. **
  121971. ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
  121972. **
  121973. ** The last character of the prefix "abc" is incremented to form the
  121974. ** termination condition "abd". If case is not significant (the default
  121975. ** for LIKE) then the lower-bound is made all uppercase and the upper-
  121976. ** bound is made all lowercase so that the bounds also work when comparing
  121977. ** BLOBs.
  121978. */
  121979. if( pWC->op==TK_AND
  121980. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  121981. ){
  121982. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  121983. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  121984. Expr *pNewExpr1;
  121985. Expr *pNewExpr2;
  121986. int idxNew1;
  121987. int idxNew2;
  121988. const char *zCollSeqName; /* Name of collating sequence */
  121989. const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
  121990. pLeft = pExpr->x.pList->a[1].pExpr;
  121991. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  121992. /* Convert the lower bound to upper-case and the upper bound to
  121993. ** lower-case (upper-case is less than lower-case in ASCII) so that
  121994. ** the range constraints also work for BLOBs
  121995. */
  121996. if( noCase && !pParse->db->mallocFailed ){
  121997. int i;
  121998. char c;
  121999. pTerm->wtFlags |= TERM_LIKE;
  122000. for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
  122001. pStr1->u.zToken[i] = sqlite3Toupper(c);
  122002. pStr2->u.zToken[i] = sqlite3Tolower(c);
  122003. }
  122004. }
  122005. if( !db->mallocFailed ){
  122006. u8 c, *pC; /* Last character before the first wildcard */
  122007. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  122008. c = *pC;
  122009. if( noCase ){
  122010. /* The point is to increment the last character before the first
  122011. ** wildcard. But if we increment '@', that will push it into the
  122012. ** alphabetic range where case conversions will mess up the
  122013. ** inequality. To avoid this, make sure to also run the full
  122014. ** LIKE on all candidate expressions by clearing the isComplete flag
  122015. */
  122016. if( c=='A'-1 ) isComplete = 0;
  122017. c = sqlite3UpperToLower[c];
  122018. }
  122019. *pC = c + 1;
  122020. }
  122021. zCollSeqName = noCase ? "NOCASE" : "BINARY";
  122022. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  122023. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  122024. sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
  122025. pStr1);
  122026. transferJoinMarkings(pNewExpr1, pExpr);
  122027. idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
  122028. testcase( idxNew1==0 );
  122029. exprAnalyze(pSrc, pWC, idxNew1);
  122030. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  122031. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  122032. sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
  122033. pStr2);
  122034. transferJoinMarkings(pNewExpr2, pExpr);
  122035. idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
  122036. testcase( idxNew2==0 );
  122037. exprAnalyze(pSrc, pWC, idxNew2);
  122038. pTerm = &pWC->a[idxTerm];
  122039. if( isComplete ){
  122040. markTermAsChild(pWC, idxNew1, idxTerm);
  122041. markTermAsChild(pWC, idxNew2, idxTerm);
  122042. }
  122043. }
  122044. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  122045. #ifndef SQLITE_OMIT_VIRTUALTABLE
  122046. /* Add a WO_MATCH auxiliary term to the constraint set if the
  122047. ** current expression is of the form: column MATCH expr.
  122048. ** This information is used by the xBestIndex methods of
  122049. ** virtual tables. The native query optimizer does not attempt
  122050. ** to do anything with MATCH functions.
  122051. */
  122052. if( pWC->op==TK_AND && isMatchOfColumn(pExpr, &eOp2) ){
  122053. int idxNew;
  122054. Expr *pRight, *pLeft;
  122055. WhereTerm *pNewTerm;
  122056. Bitmask prereqColumn, prereqExpr;
  122057. pRight = pExpr->x.pList->a[0].pExpr;
  122058. pLeft = pExpr->x.pList->a[1].pExpr;
  122059. prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
  122060. prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
  122061. if( (prereqExpr & prereqColumn)==0 ){
  122062. Expr *pNewExpr;
  122063. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  122064. 0, sqlite3ExprDup(db, pRight, 0));
  122065. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  122066. testcase( idxNew==0 );
  122067. pNewTerm = &pWC->a[idxNew];
  122068. pNewTerm->prereqRight = prereqExpr;
  122069. pNewTerm->leftCursor = pLeft->iTable;
  122070. pNewTerm->u.leftColumn = pLeft->iColumn;
  122071. pNewTerm->eOperator = WO_MATCH;
  122072. pNewTerm->eMatchOp = eOp2;
  122073. markTermAsChild(pWC, idxNew, idxTerm);
  122074. pTerm = &pWC->a[idxTerm];
  122075. pTerm->wtFlags |= TERM_COPIED;
  122076. pNewTerm->prereqAll = pTerm->prereqAll;
  122077. }
  122078. }
  122079. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  122080. /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
  122081. ** new terms for each component comparison - "a = ?" and "b = ?". The
  122082. ** new terms completely replace the original vector comparison, which is
  122083. ** no longer used.
  122084. **
  122085. ** This is only required if at least one side of the comparison operation
  122086. ** is not a sub-select. */
  122087. if( pWC->op==TK_AND
  122088. && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
  122089. && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
  122090. && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
  122091. && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
  122092. || (pExpr->pRight->flags & EP_xIsSelect)==0)
  122093. ){
  122094. int i;
  122095. for(i=0; i<nLeft; i++){
  122096. int idxNew;
  122097. Expr *pNew;
  122098. Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
  122099. Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
  122100. pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
  122101. transferJoinMarkings(pNew, pExpr);
  122102. idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
  122103. exprAnalyze(pSrc, pWC, idxNew);
  122104. }
  122105. pTerm = &pWC->a[idxTerm];
  122106. pTerm->wtFlags = TERM_CODED|TERM_VIRTUAL; /* Disable the original */
  122107. pTerm->eOperator = 0;
  122108. }
  122109. /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
  122110. ** a virtual term for each vector component. The expression object
  122111. ** used by each such virtual term is pExpr (the full vector IN(...)
  122112. ** expression). The WhereTerm.iField variable identifies the index within
  122113. ** the vector on the LHS that the virtual term represents.
  122114. **
  122115. ** This only works if the RHS is a simple SELECT, not a compound
  122116. */
  122117. if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
  122118. && pExpr->pLeft->op==TK_VECTOR
  122119. && pExpr->x.pSelect->pPrior==0
  122120. ){
  122121. int i;
  122122. for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
  122123. int idxNew;
  122124. idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
  122125. pWC->a[idxNew].iField = i+1;
  122126. exprAnalyze(pSrc, pWC, idxNew);
  122127. markTermAsChild(pWC, idxNew, idxTerm);
  122128. }
  122129. }
  122130. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  122131. /* When sqlite_stat3 histogram data is available an operator of the
  122132. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  122133. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  122134. ** virtual term of that form.
  122135. **
  122136. ** Note that the virtual term must be tagged with TERM_VNULL.
  122137. */
  122138. if( pExpr->op==TK_NOTNULL
  122139. && pExpr->pLeft->op==TK_COLUMN
  122140. && pExpr->pLeft->iColumn>=0
  122141. && OptimizationEnabled(db, SQLITE_Stat34)
  122142. ){
  122143. Expr *pNewExpr;
  122144. Expr *pLeft = pExpr->pLeft;
  122145. int idxNew;
  122146. WhereTerm *pNewTerm;
  122147. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  122148. sqlite3ExprDup(db, pLeft, 0),
  122149. sqlite3ExprAlloc(db, TK_NULL, 0, 0));
  122150. idxNew = whereClauseInsert(pWC, pNewExpr,
  122151. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  122152. if( idxNew ){
  122153. pNewTerm = &pWC->a[idxNew];
  122154. pNewTerm->prereqRight = 0;
  122155. pNewTerm->leftCursor = pLeft->iTable;
  122156. pNewTerm->u.leftColumn = pLeft->iColumn;
  122157. pNewTerm->eOperator = WO_GT;
  122158. markTermAsChild(pWC, idxNew, idxTerm);
  122159. pTerm = &pWC->a[idxTerm];
  122160. pTerm->wtFlags |= TERM_COPIED;
  122161. pNewTerm->prereqAll = pTerm->prereqAll;
  122162. }
  122163. }
  122164. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  122165. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  122166. ** an index for tables to the left of the join.
  122167. */
  122168. testcase( pTerm!=&pWC->a[idxTerm] );
  122169. pTerm = &pWC->a[idxTerm];
  122170. pTerm->prereqRight |= extraRight;
  122171. }
  122172. /***************************************************************************
  122173. ** Routines with file scope above. Interface to the rest of the where.c
  122174. ** subsystem follows.
  122175. ***************************************************************************/
  122176. /*
  122177. ** This routine identifies subexpressions in the WHERE clause where
  122178. ** each subexpression is separated by the AND operator or some other
  122179. ** operator specified in the op parameter. The WhereClause structure
  122180. ** is filled with pointers to subexpressions. For example:
  122181. **
  122182. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  122183. ** \________/ \_______________/ \________________/
  122184. ** slot[0] slot[1] slot[2]
  122185. **
  122186. ** The original WHERE clause in pExpr is unaltered. All this routine
  122187. ** does is make slot[] entries point to substructure within pExpr.
  122188. **
  122189. ** In the previous sentence and in the diagram, "slot[]" refers to
  122190. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  122191. ** all terms of the WHERE clause.
  122192. */
  122193. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  122194. Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
  122195. pWC->op = op;
  122196. if( pE2==0 ) return;
  122197. if( pE2->op!=op ){
  122198. whereClauseInsert(pWC, pExpr, 0);
  122199. }else{
  122200. sqlite3WhereSplit(pWC, pE2->pLeft, op);
  122201. sqlite3WhereSplit(pWC, pE2->pRight, op);
  122202. }
  122203. }
  122204. /*
  122205. ** Initialize a preallocated WhereClause structure.
  122206. */
  122207. SQLITE_PRIVATE void sqlite3WhereClauseInit(
  122208. WhereClause *pWC, /* The WhereClause to be initialized */
  122209. WhereInfo *pWInfo /* The WHERE processing context */
  122210. ){
  122211. pWC->pWInfo = pWInfo;
  122212. pWC->pOuter = 0;
  122213. pWC->nTerm = 0;
  122214. pWC->nSlot = ArraySize(pWC->aStatic);
  122215. pWC->a = pWC->aStatic;
  122216. }
  122217. /*
  122218. ** Deallocate a WhereClause structure. The WhereClause structure
  122219. ** itself is not freed. This routine is the inverse of
  122220. ** sqlite3WhereClauseInit().
  122221. */
  122222. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
  122223. int i;
  122224. WhereTerm *a;
  122225. sqlite3 *db = pWC->pWInfo->pParse->db;
  122226. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  122227. if( a->wtFlags & TERM_DYNAMIC ){
  122228. sqlite3ExprDelete(db, a->pExpr);
  122229. }
  122230. if( a->wtFlags & TERM_ORINFO ){
  122231. whereOrInfoDelete(db, a->u.pOrInfo);
  122232. }else if( a->wtFlags & TERM_ANDINFO ){
  122233. whereAndInfoDelete(db, a->u.pAndInfo);
  122234. }
  122235. }
  122236. if( pWC->a!=pWC->aStatic ){
  122237. sqlite3DbFree(db, pWC->a);
  122238. }
  122239. }
  122240. /*
  122241. ** These routines walk (recursively) an expression tree and generate
  122242. ** a bitmask indicating which tables are used in that expression
  122243. ** tree.
  122244. */
  122245. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
  122246. Bitmask mask;
  122247. if( p==0 ) return 0;
  122248. if( p->op==TK_COLUMN ){
  122249. return sqlite3WhereGetMask(pMaskSet, p->iTable);
  122250. }
  122251. mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
  122252. assert( !ExprHasProperty(p, EP_TokenOnly) );
  122253. if( p->pRight ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pRight);
  122254. if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
  122255. if( ExprHasProperty(p, EP_xIsSelect) ){
  122256. mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
  122257. }else if( p->x.pList ){
  122258. mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
  122259. }
  122260. return mask;
  122261. }
  122262. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  122263. int i;
  122264. Bitmask mask = 0;
  122265. if( pList ){
  122266. for(i=0; i<pList->nExpr; i++){
  122267. mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
  122268. }
  122269. }
  122270. return mask;
  122271. }
  122272. /*
  122273. ** Call exprAnalyze on all terms in a WHERE clause.
  122274. **
  122275. ** Note that exprAnalyze() might add new virtual terms onto the
  122276. ** end of the WHERE clause. We do not want to analyze these new
  122277. ** virtual terms, so start analyzing at the end and work forward
  122278. ** so that the added virtual terms are never processed.
  122279. */
  122280. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
  122281. SrcList *pTabList, /* the FROM clause */
  122282. WhereClause *pWC /* the WHERE clause to be analyzed */
  122283. ){
  122284. int i;
  122285. for(i=pWC->nTerm-1; i>=0; i--){
  122286. exprAnalyze(pTabList, pWC, i);
  122287. }
  122288. }
  122289. /*
  122290. ** For table-valued-functions, transform the function arguments into
  122291. ** new WHERE clause terms.
  122292. **
  122293. ** Each function argument translates into an equality constraint against
  122294. ** a HIDDEN column in the table.
  122295. */
  122296. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
  122297. Parse *pParse, /* Parsing context */
  122298. struct SrcList_item *pItem, /* The FROM clause term to process */
  122299. WhereClause *pWC /* Xfer function arguments to here */
  122300. ){
  122301. Table *pTab;
  122302. int j, k;
  122303. ExprList *pArgs;
  122304. Expr *pColRef;
  122305. Expr *pTerm;
  122306. if( pItem->fg.isTabFunc==0 ) return;
  122307. pTab = pItem->pTab;
  122308. assert( pTab!=0 );
  122309. pArgs = pItem->u1.pFuncArg;
  122310. if( pArgs==0 ) return;
  122311. for(j=k=0; j<pArgs->nExpr; j++){
  122312. while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
  122313. if( k>=pTab->nCol ){
  122314. sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
  122315. pTab->zName, j);
  122316. return;
  122317. }
  122318. pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
  122319. if( pColRef==0 ) return;
  122320. pColRef->iTable = pItem->iCursor;
  122321. pColRef->iColumn = k++;
  122322. pColRef->pTab = pTab;
  122323. pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
  122324. sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0));
  122325. whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
  122326. }
  122327. }
  122328. /************** End of whereexpr.c *******************************************/
  122329. /************** Begin file where.c *******************************************/
  122330. /*
  122331. ** 2001 September 15
  122332. **
  122333. ** The author disclaims copyright to this source code. In place of
  122334. ** a legal notice, here is a blessing:
  122335. **
  122336. ** May you do good and not evil.
  122337. ** May you find forgiveness for yourself and forgive others.
  122338. ** May you share freely, never taking more than you give.
  122339. **
  122340. *************************************************************************
  122341. ** This module contains C code that generates VDBE code used to process
  122342. ** the WHERE clause of SQL statements. This module is responsible for
  122343. ** generating the code that loops through a table looking for applicable
  122344. ** rows. Indices are selected and used to speed the search when doing
  122345. ** so is applicable. Because this module is responsible for selecting
  122346. ** indices, you might also think of this module as the "query optimizer".
  122347. */
  122348. /* #include "sqliteInt.h" */
  122349. /* #include "whereInt.h" */
  122350. /* Forward declaration of methods */
  122351. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  122352. /* Test variable that can be set to enable WHERE tracing */
  122353. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  122354. /***/ int sqlite3WhereTrace = 0;
  122355. #endif
  122356. /*
  122357. ** Return the estimated number of output rows from a WHERE clause
  122358. */
  122359. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  122360. return pWInfo->nRowOut;
  122361. }
  122362. /*
  122363. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  122364. ** WHERE clause returns outputs for DISTINCT processing.
  122365. */
  122366. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  122367. return pWInfo->eDistinct;
  122368. }
  122369. /*
  122370. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  122371. ** Return FALSE if the output needs to be sorted.
  122372. */
  122373. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  122374. return pWInfo->nOBSat;
  122375. }
  122376. /*
  122377. ** Return TRUE if the innermost loop of the WHERE clause implementation
  122378. ** returns rows in ORDER BY order for complete run of the inner loop.
  122379. **
  122380. ** Across multiple iterations of outer loops, the output rows need not be
  122381. ** sorted. As long as rows are sorted for just the innermost loop, this
  122382. ** routine can return TRUE.
  122383. */
  122384. SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){
  122385. return pWInfo->bOrderedInnerLoop;
  122386. }
  122387. /*
  122388. ** Return the VDBE address or label to jump to in order to continue
  122389. ** immediately with the next row of a WHERE clause.
  122390. */
  122391. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  122392. assert( pWInfo->iContinue!=0 );
  122393. return pWInfo->iContinue;
  122394. }
  122395. /*
  122396. ** Return the VDBE address or label to jump to in order to break
  122397. ** out of a WHERE loop.
  122398. */
  122399. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  122400. return pWInfo->iBreak;
  122401. }
  122402. /*
  122403. ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
  122404. ** operate directly on the rowis returned by a WHERE clause. Return
  122405. ** ONEPASS_SINGLE (1) if the statement can operation directly because only
  122406. ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
  122407. ** optimization can be used on multiple
  122408. **
  122409. ** If the ONEPASS optimization is used (if this routine returns true)
  122410. ** then also write the indices of open cursors used by ONEPASS
  122411. ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
  122412. ** table and iaCur[1] gets the cursor used by an auxiliary index.
  122413. ** Either value may be -1, indicating that cursor is not used.
  122414. ** Any cursors returned will have been opened for writing.
  122415. **
  122416. ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
  122417. ** unable to use the ONEPASS optimization.
  122418. */
  122419. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
  122420. memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
  122421. #ifdef WHERETRACE_ENABLED
  122422. if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
  122423. sqlite3DebugPrintf("%s cursors: %d %d\n",
  122424. pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
  122425. aiCur[0], aiCur[1]);
  122426. }
  122427. #endif
  122428. return pWInfo->eOnePass;
  122429. }
  122430. /*
  122431. ** Move the content of pSrc into pDest
  122432. */
  122433. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  122434. pDest->n = pSrc->n;
  122435. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  122436. }
  122437. /*
  122438. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  122439. **
  122440. ** The new entry might overwrite an existing entry, or it might be
  122441. ** appended, or it might be discarded. Do whatever is the right thing
  122442. ** so that pSet keeps the N_OR_COST best entries seen so far.
  122443. */
  122444. static int whereOrInsert(
  122445. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  122446. Bitmask prereq, /* Prerequisites of the new entry */
  122447. LogEst rRun, /* Run-cost of the new entry */
  122448. LogEst nOut /* Number of outputs for the new entry */
  122449. ){
  122450. u16 i;
  122451. WhereOrCost *p;
  122452. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  122453. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  122454. goto whereOrInsert_done;
  122455. }
  122456. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  122457. return 0;
  122458. }
  122459. }
  122460. if( pSet->n<N_OR_COST ){
  122461. p = &pSet->a[pSet->n++];
  122462. p->nOut = nOut;
  122463. }else{
  122464. p = pSet->a;
  122465. for(i=1; i<pSet->n; i++){
  122466. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  122467. }
  122468. if( p->rRun<=rRun ) return 0;
  122469. }
  122470. whereOrInsert_done:
  122471. p->prereq = prereq;
  122472. p->rRun = rRun;
  122473. if( p->nOut>nOut ) p->nOut = nOut;
  122474. return 1;
  122475. }
  122476. /*
  122477. ** Return the bitmask for the given cursor number. Return 0 if
  122478. ** iCursor is not in the set.
  122479. */
  122480. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
  122481. int i;
  122482. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  122483. for(i=0; i<pMaskSet->n; i++){
  122484. if( pMaskSet->ix[i]==iCursor ){
  122485. return MASKBIT(i);
  122486. }
  122487. }
  122488. return 0;
  122489. }
  122490. /*
  122491. ** Create a new mask for cursor iCursor.
  122492. **
  122493. ** There is one cursor per table in the FROM clause. The number of
  122494. ** tables in the FROM clause is limited by a test early in the
  122495. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  122496. ** array will never overflow.
  122497. */
  122498. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  122499. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  122500. pMaskSet->ix[pMaskSet->n++] = iCursor;
  122501. }
  122502. /*
  122503. ** Advance to the next WhereTerm that matches according to the criteria
  122504. ** established when the pScan object was initialized by whereScanInit().
  122505. ** Return NULL if there are no more matching WhereTerms.
  122506. */
  122507. static WhereTerm *whereScanNext(WhereScan *pScan){
  122508. int iCur; /* The cursor on the LHS of the term */
  122509. i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
  122510. Expr *pX; /* An expression being tested */
  122511. WhereClause *pWC; /* Shorthand for pScan->pWC */
  122512. WhereTerm *pTerm; /* The term being tested */
  122513. int k = pScan->k; /* Where to start scanning */
  122514. assert( pScan->iEquiv<=pScan->nEquiv );
  122515. pWC = pScan->pWC;
  122516. while(1){
  122517. iColumn = pScan->aiColumn[pScan->iEquiv-1];
  122518. iCur = pScan->aiCur[pScan->iEquiv-1];
  122519. assert( pWC!=0 );
  122520. do{
  122521. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  122522. if( pTerm->leftCursor==iCur
  122523. && pTerm->u.leftColumn==iColumn
  122524. && (iColumn!=XN_EXPR
  122525. || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
  122526. pScan->pIdxExpr,iCur)==0)
  122527. && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  122528. ){
  122529. if( (pTerm->eOperator & WO_EQUIV)!=0
  122530. && pScan->nEquiv<ArraySize(pScan->aiCur)
  122531. && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
  122532. ){
  122533. int j;
  122534. for(j=0; j<pScan->nEquiv; j++){
  122535. if( pScan->aiCur[j]==pX->iTable
  122536. && pScan->aiColumn[j]==pX->iColumn ){
  122537. break;
  122538. }
  122539. }
  122540. if( j==pScan->nEquiv ){
  122541. pScan->aiCur[j] = pX->iTable;
  122542. pScan->aiColumn[j] = pX->iColumn;
  122543. pScan->nEquiv++;
  122544. }
  122545. }
  122546. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  122547. /* Verify the affinity and collating sequence match */
  122548. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  122549. CollSeq *pColl;
  122550. Parse *pParse = pWC->pWInfo->pParse;
  122551. pX = pTerm->pExpr;
  122552. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  122553. continue;
  122554. }
  122555. assert(pX->pLeft);
  122556. pColl = sqlite3BinaryCompareCollSeq(pParse,
  122557. pX->pLeft, pX->pRight);
  122558. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  122559. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  122560. continue;
  122561. }
  122562. }
  122563. if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
  122564. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  122565. && pX->iTable==pScan->aiCur[0]
  122566. && pX->iColumn==pScan->aiColumn[0]
  122567. ){
  122568. testcase( pTerm->eOperator & WO_IS );
  122569. continue;
  122570. }
  122571. pScan->pWC = pWC;
  122572. pScan->k = k+1;
  122573. return pTerm;
  122574. }
  122575. }
  122576. }
  122577. pWC = pWC->pOuter;
  122578. k = 0;
  122579. }while( pWC!=0 );
  122580. if( pScan->iEquiv>=pScan->nEquiv ) break;
  122581. pWC = pScan->pOrigWC;
  122582. k = 0;
  122583. pScan->iEquiv++;
  122584. }
  122585. return 0;
  122586. }
  122587. /*
  122588. ** Initialize a WHERE clause scanner object. Return a pointer to the
  122589. ** first match. Return NULL if there are no matches.
  122590. **
  122591. ** The scanner will be searching the WHERE clause pWC. It will look
  122592. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  122593. ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
  122594. ** must be one of the indexes of table iCur.
  122595. **
  122596. ** The <op> must be one of the operators described by opMask.
  122597. **
  122598. ** If the search is for X and the WHERE clause contains terms of the
  122599. ** form X=Y then this routine might also return terms of the form
  122600. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  122601. ** but is enough to handle most commonly occurring SQL statements.
  122602. **
  122603. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  122604. ** index pIdx.
  122605. */
  122606. static WhereTerm *whereScanInit(
  122607. WhereScan *pScan, /* The WhereScan object being initialized */
  122608. WhereClause *pWC, /* The WHERE clause to be scanned */
  122609. int iCur, /* Cursor to scan for */
  122610. int iColumn, /* Column to scan for */
  122611. u32 opMask, /* Operator(s) to scan for */
  122612. Index *pIdx /* Must be compatible with this index */
  122613. ){
  122614. pScan->pOrigWC = pWC;
  122615. pScan->pWC = pWC;
  122616. pScan->pIdxExpr = 0;
  122617. pScan->idxaff = 0;
  122618. pScan->zCollName = 0;
  122619. if( pIdx ){
  122620. int j = iColumn;
  122621. iColumn = pIdx->aiColumn[j];
  122622. if( iColumn==XN_EXPR ){
  122623. pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
  122624. pScan->zCollName = pIdx->azColl[j];
  122625. }else if( iColumn==pIdx->pTable->iPKey ){
  122626. iColumn = XN_ROWID;
  122627. }else if( iColumn>=0 ){
  122628. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  122629. pScan->zCollName = pIdx->azColl[j];
  122630. }
  122631. }else if( iColumn==XN_EXPR ){
  122632. return 0;
  122633. }
  122634. pScan->opMask = opMask;
  122635. pScan->k = 0;
  122636. pScan->aiCur[0] = iCur;
  122637. pScan->aiColumn[0] = iColumn;
  122638. pScan->nEquiv = 1;
  122639. pScan->iEquiv = 1;
  122640. return whereScanNext(pScan);
  122641. }
  122642. /*
  122643. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  122644. ** where X is a reference to the iColumn of table iCur or of index pIdx
  122645. ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
  122646. ** the op parameter. Return a pointer to the term. Return 0 if not found.
  122647. **
  122648. ** If pIdx!=0 then it must be one of the indexes of table iCur.
  122649. ** Search for terms matching the iColumn-th column of pIdx
  122650. ** rather than the iColumn-th column of table iCur.
  122651. **
  122652. ** The term returned might by Y=<expr> if there is another constraint in
  122653. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  122654. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  122655. ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
  122656. ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
  122657. ** other equivalent values. Hence a search for X will return <expr> if X=A1
  122658. ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
  122659. **
  122660. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  122661. ** then try for the one with no dependencies on <expr> - in other words where
  122662. ** <expr> is a constant expression of some kind. Only return entries of
  122663. ** the form "X <op> Y" where Y is a column in another table if no terms of
  122664. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  122665. ** exist, try to return a term that does not use WO_EQUIV.
  122666. */
  122667. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  122668. WhereClause *pWC, /* The WHERE clause to be searched */
  122669. int iCur, /* Cursor number of LHS */
  122670. int iColumn, /* Column number of LHS */
  122671. Bitmask notReady, /* RHS must not overlap with this mask */
  122672. u32 op, /* Mask of WO_xx values describing operator */
  122673. Index *pIdx /* Must be compatible with this index, if not NULL */
  122674. ){
  122675. WhereTerm *pResult = 0;
  122676. WhereTerm *p;
  122677. WhereScan scan;
  122678. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  122679. op &= WO_EQ|WO_IS;
  122680. while( p ){
  122681. if( (p->prereqRight & notReady)==0 ){
  122682. if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
  122683. testcase( p->eOperator & WO_IS );
  122684. return p;
  122685. }
  122686. if( pResult==0 ) pResult = p;
  122687. }
  122688. p = whereScanNext(&scan);
  122689. }
  122690. return pResult;
  122691. }
  122692. /*
  122693. ** This function searches pList for an entry that matches the iCol-th column
  122694. ** of index pIdx.
  122695. **
  122696. ** If such an expression is found, its index in pList->a[] is returned. If
  122697. ** no expression is found, -1 is returned.
  122698. */
  122699. static int findIndexCol(
  122700. Parse *pParse, /* Parse context */
  122701. ExprList *pList, /* Expression list to search */
  122702. int iBase, /* Cursor for table associated with pIdx */
  122703. Index *pIdx, /* Index to match column of */
  122704. int iCol /* Column of index to match */
  122705. ){
  122706. int i;
  122707. const char *zColl = pIdx->azColl[iCol];
  122708. for(i=0; i<pList->nExpr; i++){
  122709. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  122710. if( p->op==TK_COLUMN
  122711. && p->iColumn==pIdx->aiColumn[iCol]
  122712. && p->iTable==iBase
  122713. ){
  122714. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
  122715. if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
  122716. return i;
  122717. }
  122718. }
  122719. }
  122720. return -1;
  122721. }
  122722. /*
  122723. ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
  122724. */
  122725. static int indexColumnNotNull(Index *pIdx, int iCol){
  122726. int j;
  122727. assert( pIdx!=0 );
  122728. assert( iCol>=0 && iCol<pIdx->nColumn );
  122729. j = pIdx->aiColumn[iCol];
  122730. if( j>=0 ){
  122731. return pIdx->pTable->aCol[j].notNull;
  122732. }else if( j==(-1) ){
  122733. return 1;
  122734. }else{
  122735. assert( j==(-2) );
  122736. return 0; /* Assume an indexed expression can always yield a NULL */
  122737. }
  122738. }
  122739. /*
  122740. ** Return true if the DISTINCT expression-list passed as the third argument
  122741. ** is redundant.
  122742. **
  122743. ** A DISTINCT list is redundant if any subset of the columns in the
  122744. ** DISTINCT list are collectively unique and individually non-null.
  122745. */
  122746. static int isDistinctRedundant(
  122747. Parse *pParse, /* Parsing context */
  122748. SrcList *pTabList, /* The FROM clause */
  122749. WhereClause *pWC, /* The WHERE clause */
  122750. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  122751. ){
  122752. Table *pTab;
  122753. Index *pIdx;
  122754. int i;
  122755. int iBase;
  122756. /* If there is more than one table or sub-select in the FROM clause of
  122757. ** this query, then it will not be possible to show that the DISTINCT
  122758. ** clause is redundant. */
  122759. if( pTabList->nSrc!=1 ) return 0;
  122760. iBase = pTabList->a[0].iCursor;
  122761. pTab = pTabList->a[0].pTab;
  122762. /* If any of the expressions is an IPK column on table iBase, then return
  122763. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  122764. ** current SELECT is a correlated sub-query.
  122765. */
  122766. for(i=0; i<pDistinct->nExpr; i++){
  122767. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  122768. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  122769. }
  122770. /* Loop through all indices on the table, checking each to see if it makes
  122771. ** the DISTINCT qualifier redundant. It does so if:
  122772. **
  122773. ** 1. The index is itself UNIQUE, and
  122774. **
  122775. ** 2. All of the columns in the index are either part of the pDistinct
  122776. ** list, or else the WHERE clause contains a term of the form "col=X",
  122777. ** where X is a constant value. The collation sequences of the
  122778. ** comparison and select-list expressions must match those of the index.
  122779. **
  122780. ** 3. All of those index columns for which the WHERE clause does not
  122781. ** contain a "col=X" term are subject to a NOT NULL constraint.
  122782. */
  122783. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  122784. if( !IsUniqueIndex(pIdx) ) continue;
  122785. for(i=0; i<pIdx->nKeyCol; i++){
  122786. if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
  122787. if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
  122788. if( indexColumnNotNull(pIdx, i)==0 ) break;
  122789. }
  122790. }
  122791. if( i==pIdx->nKeyCol ){
  122792. /* This index implies that the DISTINCT qualifier is redundant. */
  122793. return 1;
  122794. }
  122795. }
  122796. return 0;
  122797. }
  122798. /*
  122799. ** Estimate the logarithm of the input value to base 2.
  122800. */
  122801. static LogEst estLog(LogEst N){
  122802. return N<=10 ? 0 : sqlite3LogEst(N) - 33;
  122803. }
  122804. /*
  122805. ** Convert OP_Column opcodes to OP_Copy in previously generated code.
  122806. **
  122807. ** This routine runs over generated VDBE code and translates OP_Column
  122808. ** opcodes into OP_Copy when the table is being accessed via co-routine
  122809. ** instead of via table lookup.
  122810. **
  122811. ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
  122812. ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
  122813. ** then each OP_Rowid is transformed into an instruction to increment the
  122814. ** value stored in its output register.
  122815. */
  122816. static void translateColumnToCopy(
  122817. Parse *pParse, /* Parsing context */
  122818. int iStart, /* Translate from this opcode to the end */
  122819. int iTabCur, /* OP_Column/OP_Rowid references to this table */
  122820. int iRegister, /* The first column is in this register */
  122821. int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */
  122822. ){
  122823. Vdbe *v = pParse->pVdbe;
  122824. VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
  122825. int iEnd = sqlite3VdbeCurrentAddr(v);
  122826. if( pParse->db->mallocFailed ) return;
  122827. for(; iStart<iEnd; iStart++, pOp++){
  122828. if( pOp->p1!=iTabCur ) continue;
  122829. if( pOp->opcode==OP_Column ){
  122830. pOp->opcode = OP_Copy;
  122831. pOp->p1 = pOp->p2 + iRegister;
  122832. pOp->p2 = pOp->p3;
  122833. pOp->p3 = 0;
  122834. }else if( pOp->opcode==OP_Rowid ){
  122835. if( bIncrRowid ){
  122836. /* Increment the value stored in the P2 operand of the OP_Rowid. */
  122837. pOp->opcode = OP_AddImm;
  122838. pOp->p1 = pOp->p2;
  122839. pOp->p2 = 1;
  122840. }else{
  122841. pOp->opcode = OP_Null;
  122842. pOp->p1 = 0;
  122843. pOp->p3 = 0;
  122844. }
  122845. }
  122846. }
  122847. }
  122848. /*
  122849. ** Two routines for printing the content of an sqlite3_index_info
  122850. ** structure. Used for testing and debugging only. If neither
  122851. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  122852. ** are no-ops.
  122853. */
  122854. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  122855. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  122856. int i;
  122857. if( !sqlite3WhereTrace ) return;
  122858. for(i=0; i<p->nConstraint; i++){
  122859. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  122860. i,
  122861. p->aConstraint[i].iColumn,
  122862. p->aConstraint[i].iTermOffset,
  122863. p->aConstraint[i].op,
  122864. p->aConstraint[i].usable);
  122865. }
  122866. for(i=0; i<p->nOrderBy; i++){
  122867. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  122868. i,
  122869. p->aOrderBy[i].iColumn,
  122870. p->aOrderBy[i].desc);
  122871. }
  122872. }
  122873. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  122874. int i;
  122875. if( !sqlite3WhereTrace ) return;
  122876. for(i=0; i<p->nConstraint; i++){
  122877. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  122878. i,
  122879. p->aConstraintUsage[i].argvIndex,
  122880. p->aConstraintUsage[i].omit);
  122881. }
  122882. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  122883. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  122884. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  122885. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  122886. sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
  122887. }
  122888. #else
  122889. #define TRACE_IDX_INPUTS(A)
  122890. #define TRACE_IDX_OUTPUTS(A)
  122891. #endif
  122892. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  122893. /*
  122894. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  122895. ** could be used with an index to access pSrc, assuming an appropriate
  122896. ** index existed.
  122897. */
  122898. static int termCanDriveIndex(
  122899. WhereTerm *pTerm, /* WHERE clause term to check */
  122900. struct SrcList_item *pSrc, /* Table we are trying to access */
  122901. Bitmask notReady /* Tables in outer loops of the join */
  122902. ){
  122903. char aff;
  122904. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  122905. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
  122906. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  122907. if( pTerm->u.leftColumn<0 ) return 0;
  122908. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  122909. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  122910. testcase( pTerm->pExpr->op==TK_IS );
  122911. return 1;
  122912. }
  122913. #endif
  122914. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  122915. /*
  122916. ** Generate code to construct the Index object for an automatic index
  122917. ** and to set up the WhereLevel object pLevel so that the code generator
  122918. ** makes use of the automatic index.
  122919. */
  122920. static void constructAutomaticIndex(
  122921. Parse *pParse, /* The parsing context */
  122922. WhereClause *pWC, /* The WHERE clause */
  122923. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  122924. Bitmask notReady, /* Mask of cursors that are not available */
  122925. WhereLevel *pLevel /* Write new index here */
  122926. ){
  122927. int nKeyCol; /* Number of columns in the constructed index */
  122928. WhereTerm *pTerm; /* A single term of the WHERE clause */
  122929. WhereTerm *pWCEnd; /* End of pWC->a[] */
  122930. Index *pIdx; /* Object describing the transient index */
  122931. Vdbe *v; /* Prepared statement under construction */
  122932. int addrInit; /* Address of the initialization bypass jump */
  122933. Table *pTable; /* The table being indexed */
  122934. int addrTop; /* Top of the index fill loop */
  122935. int regRecord; /* Register holding an index record */
  122936. int n; /* Column counter */
  122937. int i; /* Loop counter */
  122938. int mxBitCol; /* Maximum column in pSrc->colUsed */
  122939. CollSeq *pColl; /* Collating sequence to on a column */
  122940. WhereLoop *pLoop; /* The Loop object */
  122941. char *zNotUsed; /* Extra space on the end of pIdx */
  122942. Bitmask idxCols; /* Bitmap of columns used for indexing */
  122943. Bitmask extraCols; /* Bitmap of additional columns */
  122944. u8 sentWarning = 0; /* True if a warnning has been issued */
  122945. Expr *pPartial = 0; /* Partial Index Expression */
  122946. int iContinue = 0; /* Jump here to skip excluded rows */
  122947. struct SrcList_item *pTabItem; /* FROM clause term being indexed */
  122948. int addrCounter = 0; /* Address where integer counter is initialized */
  122949. int regBase; /* Array of registers where record is assembled */
  122950. /* Generate code to skip over the creation and initialization of the
  122951. ** transient index on 2nd and subsequent iterations of the loop. */
  122952. v = pParse->pVdbe;
  122953. assert( v!=0 );
  122954. addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  122955. /* Count the number of columns that will be added to the index
  122956. ** and used to match WHERE clause constraints */
  122957. nKeyCol = 0;
  122958. pTable = pSrc->pTab;
  122959. pWCEnd = &pWC->a[pWC->nTerm];
  122960. pLoop = pLevel->pWLoop;
  122961. idxCols = 0;
  122962. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  122963. Expr *pExpr = pTerm->pExpr;
  122964. assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
  122965. || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
  122966. || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
  122967. if( pLoop->prereq==0
  122968. && (pTerm->wtFlags & TERM_VIRTUAL)==0
  122969. && !ExprHasProperty(pExpr, EP_FromJoin)
  122970. && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
  122971. pPartial = sqlite3ExprAnd(pParse->db, pPartial,
  122972. sqlite3ExprDup(pParse->db, pExpr, 0));
  122973. }
  122974. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  122975. int iCol = pTerm->u.leftColumn;
  122976. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  122977. testcase( iCol==BMS );
  122978. testcase( iCol==BMS-1 );
  122979. if( !sentWarning ){
  122980. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  122981. "automatic index on %s(%s)", pTable->zName,
  122982. pTable->aCol[iCol].zName);
  122983. sentWarning = 1;
  122984. }
  122985. if( (idxCols & cMask)==0 ){
  122986. if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
  122987. goto end_auto_index_create;
  122988. }
  122989. pLoop->aLTerm[nKeyCol++] = pTerm;
  122990. idxCols |= cMask;
  122991. }
  122992. }
  122993. }
  122994. assert( nKeyCol>0 );
  122995. pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
  122996. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  122997. | WHERE_AUTO_INDEX;
  122998. /* Count the number of additional columns needed to create a
  122999. ** covering index. A "covering index" is an index that contains all
  123000. ** columns that are needed by the query. With a covering index, the
  123001. ** original table never needs to be accessed. Automatic indices must
  123002. ** be a covering index because the index will not be updated if the
  123003. ** original table changes and the index and table cannot both be used
  123004. ** if they go out of sync.
  123005. */
  123006. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  123007. mxBitCol = MIN(BMS-1,pTable->nCol);
  123008. testcase( pTable->nCol==BMS-1 );
  123009. testcase( pTable->nCol==BMS-2 );
  123010. for(i=0; i<mxBitCol; i++){
  123011. if( extraCols & MASKBIT(i) ) nKeyCol++;
  123012. }
  123013. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  123014. nKeyCol += pTable->nCol - BMS + 1;
  123015. }
  123016. /* Construct the Index object to describe this index */
  123017. pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
  123018. if( pIdx==0 ) goto end_auto_index_create;
  123019. pLoop->u.btree.pIndex = pIdx;
  123020. pIdx->zName = "auto-index";
  123021. pIdx->pTable = pTable;
  123022. n = 0;
  123023. idxCols = 0;
  123024. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  123025. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  123026. int iCol = pTerm->u.leftColumn;
  123027. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  123028. testcase( iCol==BMS-1 );
  123029. testcase( iCol==BMS );
  123030. if( (idxCols & cMask)==0 ){
  123031. Expr *pX = pTerm->pExpr;
  123032. idxCols |= cMask;
  123033. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  123034. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  123035. pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
  123036. n++;
  123037. }
  123038. }
  123039. }
  123040. assert( (u32)n==pLoop->u.btree.nEq );
  123041. /* Add additional columns needed to make the automatic index into
  123042. ** a covering index */
  123043. for(i=0; i<mxBitCol; i++){
  123044. if( extraCols & MASKBIT(i) ){
  123045. pIdx->aiColumn[n] = i;
  123046. pIdx->azColl[n] = sqlite3StrBINARY;
  123047. n++;
  123048. }
  123049. }
  123050. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  123051. for(i=BMS-1; i<pTable->nCol; i++){
  123052. pIdx->aiColumn[n] = i;
  123053. pIdx->azColl[n] = sqlite3StrBINARY;
  123054. n++;
  123055. }
  123056. }
  123057. assert( n==nKeyCol );
  123058. pIdx->aiColumn[n] = XN_ROWID;
  123059. pIdx->azColl[n] = sqlite3StrBINARY;
  123060. /* Create the automatic index */
  123061. assert( pLevel->iIdxCur>=0 );
  123062. pLevel->iIdxCur = pParse->nTab++;
  123063. sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  123064. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  123065. VdbeComment((v, "for %s", pTable->zName));
  123066. /* Fill the automatic index with content */
  123067. sqlite3ExprCachePush(pParse);
  123068. pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
  123069. if( pTabItem->fg.viaCoroutine ){
  123070. int regYield = pTabItem->regReturn;
  123071. addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
  123072. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  123073. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  123074. VdbeCoverage(v);
  123075. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  123076. }else{
  123077. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  123078. }
  123079. if( pPartial ){
  123080. iContinue = sqlite3VdbeMakeLabel(v);
  123081. sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
  123082. pLoop->wsFlags |= WHERE_PARTIALIDX;
  123083. }
  123084. regRecord = sqlite3GetTempReg(pParse);
  123085. regBase = sqlite3GenerateIndexKey(
  123086. pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
  123087. );
  123088. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  123089. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  123090. if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
  123091. if( pTabItem->fg.viaCoroutine ){
  123092. sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
  123093. testcase( pParse->db->mallocFailed );
  123094. translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
  123095. pTabItem->regResult, 1);
  123096. sqlite3VdbeGoto(v, addrTop);
  123097. pTabItem->fg.viaCoroutine = 0;
  123098. }else{
  123099. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
  123100. }
  123101. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  123102. sqlite3VdbeJumpHere(v, addrTop);
  123103. sqlite3ReleaseTempReg(pParse, regRecord);
  123104. sqlite3ExprCachePop(pParse);
  123105. /* Jump here when skipping the initialization */
  123106. sqlite3VdbeJumpHere(v, addrInit);
  123107. end_auto_index_create:
  123108. sqlite3ExprDelete(pParse->db, pPartial);
  123109. }
  123110. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  123111. #ifndef SQLITE_OMIT_VIRTUALTABLE
  123112. /*
  123113. ** Allocate and populate an sqlite3_index_info structure. It is the
  123114. ** responsibility of the caller to eventually release the structure
  123115. ** by passing the pointer returned by this function to sqlite3_free().
  123116. */
  123117. static sqlite3_index_info *allocateIndexInfo(
  123118. Parse *pParse,
  123119. WhereClause *pWC,
  123120. Bitmask mUnusable, /* Ignore terms with these prereqs */
  123121. struct SrcList_item *pSrc,
  123122. ExprList *pOrderBy,
  123123. u16 *pmNoOmit /* Mask of terms not to omit */
  123124. ){
  123125. int i, j;
  123126. int nTerm;
  123127. struct sqlite3_index_constraint *pIdxCons;
  123128. struct sqlite3_index_orderby *pIdxOrderBy;
  123129. struct sqlite3_index_constraint_usage *pUsage;
  123130. WhereTerm *pTerm;
  123131. int nOrderBy;
  123132. sqlite3_index_info *pIdxInfo;
  123133. u16 mNoOmit = 0;
  123134. /* Count the number of possible WHERE clause constraints referring
  123135. ** to this virtual table */
  123136. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  123137. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  123138. if( pTerm->prereqRight & mUnusable ) continue;
  123139. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  123140. testcase( pTerm->eOperator & WO_IN );
  123141. testcase( pTerm->eOperator & WO_ISNULL );
  123142. testcase( pTerm->eOperator & WO_IS );
  123143. testcase( pTerm->eOperator & WO_ALL );
  123144. if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
  123145. if( pTerm->wtFlags & TERM_VNULL ) continue;
  123146. assert( pTerm->u.leftColumn>=(-1) );
  123147. nTerm++;
  123148. }
  123149. /* If the ORDER BY clause contains only columns in the current
  123150. ** virtual table then allocate space for the aOrderBy part of
  123151. ** the sqlite3_index_info structure.
  123152. */
  123153. nOrderBy = 0;
  123154. if( pOrderBy ){
  123155. int n = pOrderBy->nExpr;
  123156. for(i=0; i<n; i++){
  123157. Expr *pExpr = pOrderBy->a[i].pExpr;
  123158. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  123159. }
  123160. if( i==n){
  123161. nOrderBy = n;
  123162. }
  123163. }
  123164. /* Allocate the sqlite3_index_info structure
  123165. */
  123166. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  123167. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  123168. + sizeof(*pIdxOrderBy)*nOrderBy );
  123169. if( pIdxInfo==0 ){
  123170. sqlite3ErrorMsg(pParse, "out of memory");
  123171. return 0;
  123172. }
  123173. /* Initialize the structure. The sqlite3_index_info structure contains
  123174. ** many fields that are declared "const" to prevent xBestIndex from
  123175. ** changing them. We have to do some funky casting in order to
  123176. ** initialize those fields.
  123177. */
  123178. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  123179. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  123180. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  123181. *(int*)&pIdxInfo->nConstraint = nTerm;
  123182. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  123183. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  123184. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  123185. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  123186. pUsage;
  123187. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  123188. u8 op;
  123189. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  123190. if( pTerm->prereqRight & mUnusable ) continue;
  123191. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  123192. testcase( pTerm->eOperator & WO_IN );
  123193. testcase( pTerm->eOperator & WO_IS );
  123194. testcase( pTerm->eOperator & WO_ISNULL );
  123195. testcase( pTerm->eOperator & WO_ALL );
  123196. if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
  123197. if( pTerm->wtFlags & TERM_VNULL ) continue;
  123198. assert( pTerm->u.leftColumn>=(-1) );
  123199. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  123200. pIdxCons[j].iTermOffset = i;
  123201. op = (u8)pTerm->eOperator & WO_ALL;
  123202. if( op==WO_IN ) op = WO_EQ;
  123203. if( op==WO_MATCH ){
  123204. op = pTerm->eMatchOp;
  123205. }
  123206. pIdxCons[j].op = op;
  123207. /* The direct assignment in the previous line is possible only because
  123208. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  123209. ** following asserts verify this fact. */
  123210. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  123211. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  123212. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  123213. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  123214. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  123215. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  123216. assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  123217. if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
  123218. && sqlite3ExprIsVector(pTerm->pExpr->pRight)
  123219. ){
  123220. if( i<16 ) mNoOmit |= (1 << i);
  123221. if( op==WO_LT ) pIdxCons[j].op = WO_LE;
  123222. if( op==WO_GT ) pIdxCons[j].op = WO_GE;
  123223. }
  123224. j++;
  123225. }
  123226. for(i=0; i<nOrderBy; i++){
  123227. Expr *pExpr = pOrderBy->a[i].pExpr;
  123228. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  123229. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  123230. }
  123231. *pmNoOmit = mNoOmit;
  123232. return pIdxInfo;
  123233. }
  123234. /*
  123235. ** The table object reference passed as the second argument to this function
  123236. ** must represent a virtual table. This function invokes the xBestIndex()
  123237. ** method of the virtual table with the sqlite3_index_info object that
  123238. ** comes in as the 3rd argument to this function.
  123239. **
  123240. ** If an error occurs, pParse is populated with an error message and a
  123241. ** non-zero value is returned. Otherwise, 0 is returned and the output
  123242. ** part of the sqlite3_index_info structure is left populated.
  123243. **
  123244. ** Whether or not an error is returned, it is the responsibility of the
  123245. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  123246. ** that this is required.
  123247. */
  123248. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  123249. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  123250. int rc;
  123251. TRACE_IDX_INPUTS(p);
  123252. rc = pVtab->pModule->xBestIndex(pVtab, p);
  123253. TRACE_IDX_OUTPUTS(p);
  123254. if( rc!=SQLITE_OK ){
  123255. if( rc==SQLITE_NOMEM ){
  123256. sqlite3OomFault(pParse->db);
  123257. }else if( !pVtab->zErrMsg ){
  123258. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  123259. }else{
  123260. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  123261. }
  123262. }
  123263. sqlite3_free(pVtab->zErrMsg);
  123264. pVtab->zErrMsg = 0;
  123265. #if 0
  123266. /* This error is now caught by the caller.
  123267. ** Search for "xBestIndex malfunction" below */
  123268. for(i=0; i<p->nConstraint; i++){
  123269. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  123270. sqlite3ErrorMsg(pParse,
  123271. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  123272. }
  123273. }
  123274. #endif
  123275. return pParse->nErr;
  123276. }
  123277. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  123278. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  123279. /*
  123280. ** Estimate the location of a particular key among all keys in an
  123281. ** index. Store the results in aStat as follows:
  123282. **
  123283. ** aStat[0] Est. number of rows less than pRec
  123284. ** aStat[1] Est. number of rows equal to pRec
  123285. **
  123286. ** Return the index of the sample that is the smallest sample that
  123287. ** is greater than or equal to pRec. Note that this index is not an index
  123288. ** into the aSample[] array - it is an index into a virtual set of samples
  123289. ** based on the contents of aSample[] and the number of fields in record
  123290. ** pRec.
  123291. */
  123292. static int whereKeyStats(
  123293. Parse *pParse, /* Database connection */
  123294. Index *pIdx, /* Index to consider domain of */
  123295. UnpackedRecord *pRec, /* Vector of values to consider */
  123296. int roundUp, /* Round up if true. Round down if false */
  123297. tRowcnt *aStat /* OUT: stats written here */
  123298. ){
  123299. IndexSample *aSample = pIdx->aSample;
  123300. int iCol; /* Index of required stats in anEq[] etc. */
  123301. int i; /* Index of first sample >= pRec */
  123302. int iSample; /* Smallest sample larger than or equal to pRec */
  123303. int iMin = 0; /* Smallest sample not yet tested */
  123304. int iTest; /* Next sample to test */
  123305. int res; /* Result of comparison operation */
  123306. int nField; /* Number of fields in pRec */
  123307. tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
  123308. #ifndef SQLITE_DEBUG
  123309. UNUSED_PARAMETER( pParse );
  123310. #endif
  123311. assert( pRec!=0 );
  123312. assert( pIdx->nSample>0 );
  123313. assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
  123314. /* Do a binary search to find the first sample greater than or equal
  123315. ** to pRec. If pRec contains a single field, the set of samples to search
  123316. ** is simply the aSample[] array. If the samples in aSample[] contain more
  123317. ** than one fields, all fields following the first are ignored.
  123318. **
  123319. ** If pRec contains N fields, where N is more than one, then as well as the
  123320. ** samples in aSample[] (truncated to N fields), the search also has to
  123321. ** consider prefixes of those samples. For example, if the set of samples
  123322. ** in aSample is:
  123323. **
  123324. ** aSample[0] = (a, 5)
  123325. ** aSample[1] = (a, 10)
  123326. ** aSample[2] = (b, 5)
  123327. ** aSample[3] = (c, 100)
  123328. ** aSample[4] = (c, 105)
  123329. **
  123330. ** Then the search space should ideally be the samples above and the
  123331. ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
  123332. ** the code actually searches this set:
  123333. **
  123334. ** 0: (a)
  123335. ** 1: (a, 5)
  123336. ** 2: (a, 10)
  123337. ** 3: (a, 10)
  123338. ** 4: (b)
  123339. ** 5: (b, 5)
  123340. ** 6: (c)
  123341. ** 7: (c, 100)
  123342. ** 8: (c, 105)
  123343. ** 9: (c, 105)
  123344. **
  123345. ** For each sample in the aSample[] array, N samples are present in the
  123346. ** effective sample array. In the above, samples 0 and 1 are based on
  123347. ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
  123348. **
  123349. ** Often, sample i of each block of N effective samples has (i+1) fields.
  123350. ** Except, each sample may be extended to ensure that it is greater than or
  123351. ** equal to the previous sample in the array. For example, in the above,
  123352. ** sample 2 is the first sample of a block of N samples, so at first it
  123353. ** appears that it should be 1 field in size. However, that would make it
  123354. ** smaller than sample 1, so the binary search would not work. As a result,
  123355. ** it is extended to two fields. The duplicates that this creates do not
  123356. ** cause any problems.
  123357. */
  123358. nField = pRec->nField;
  123359. iCol = 0;
  123360. iSample = pIdx->nSample * nField;
  123361. do{
  123362. int iSamp; /* Index in aSample[] of test sample */
  123363. int n; /* Number of fields in test sample */
  123364. iTest = (iMin+iSample)/2;
  123365. iSamp = iTest / nField;
  123366. if( iSamp>0 ){
  123367. /* The proposed effective sample is a prefix of sample aSample[iSamp].
  123368. ** Specifically, the shortest prefix of at least (1 + iTest%nField)
  123369. ** fields that is greater than the previous effective sample. */
  123370. for(n=(iTest % nField) + 1; n<nField; n++){
  123371. if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
  123372. }
  123373. }else{
  123374. n = iTest + 1;
  123375. }
  123376. pRec->nField = n;
  123377. res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
  123378. if( res<0 ){
  123379. iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
  123380. iMin = iTest+1;
  123381. }else if( res==0 && n<nField ){
  123382. iLower = aSample[iSamp].anLt[n-1];
  123383. iMin = iTest+1;
  123384. res = -1;
  123385. }else{
  123386. iSample = iTest;
  123387. iCol = n-1;
  123388. }
  123389. }while( res && iMin<iSample );
  123390. i = iSample / nField;
  123391. #ifdef SQLITE_DEBUG
  123392. /* The following assert statements check that the binary search code
  123393. ** above found the right answer. This block serves no purpose other
  123394. ** than to invoke the asserts. */
  123395. if( pParse->db->mallocFailed==0 ){
  123396. if( res==0 ){
  123397. /* If (res==0) is true, then pRec must be equal to sample i. */
  123398. assert( i<pIdx->nSample );
  123399. assert( iCol==nField-1 );
  123400. pRec->nField = nField;
  123401. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  123402. || pParse->db->mallocFailed
  123403. );
  123404. }else{
  123405. /* Unless i==pIdx->nSample, indicating that pRec is larger than
  123406. ** all samples in the aSample[] array, pRec must be smaller than the
  123407. ** (iCol+1) field prefix of sample i. */
  123408. assert( i<=pIdx->nSample && i>=0 );
  123409. pRec->nField = iCol+1;
  123410. assert( i==pIdx->nSample
  123411. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  123412. || pParse->db->mallocFailed );
  123413. /* if i==0 and iCol==0, then record pRec is smaller than all samples
  123414. ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
  123415. ** be greater than or equal to the (iCol) field prefix of sample i.
  123416. ** If (i>0), then pRec must also be greater than sample (i-1). */
  123417. if( iCol>0 ){
  123418. pRec->nField = iCol;
  123419. assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
  123420. || pParse->db->mallocFailed );
  123421. }
  123422. if( i>0 ){
  123423. pRec->nField = nField;
  123424. assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  123425. || pParse->db->mallocFailed );
  123426. }
  123427. }
  123428. }
  123429. #endif /* ifdef SQLITE_DEBUG */
  123430. if( res==0 ){
  123431. /* Record pRec is equal to sample i */
  123432. assert( iCol==nField-1 );
  123433. aStat[0] = aSample[i].anLt[iCol];
  123434. aStat[1] = aSample[i].anEq[iCol];
  123435. }else{
  123436. /* At this point, the (iCol+1) field prefix of aSample[i] is the first
  123437. ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
  123438. ** is larger than all samples in the array. */
  123439. tRowcnt iUpper, iGap;
  123440. if( i>=pIdx->nSample ){
  123441. iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
  123442. }else{
  123443. iUpper = aSample[i].anLt[iCol];
  123444. }
  123445. if( iLower>=iUpper ){
  123446. iGap = 0;
  123447. }else{
  123448. iGap = iUpper - iLower;
  123449. }
  123450. if( roundUp ){
  123451. iGap = (iGap*2)/3;
  123452. }else{
  123453. iGap = iGap/3;
  123454. }
  123455. aStat[0] = iLower + iGap;
  123456. aStat[1] = pIdx->aAvgEq[iCol];
  123457. }
  123458. /* Restore the pRec->nField value before returning. */
  123459. pRec->nField = nField;
  123460. return i;
  123461. }
  123462. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  123463. /*
  123464. ** If it is not NULL, pTerm is a term that provides an upper or lower
  123465. ** bound on a range scan. Without considering pTerm, it is estimated
  123466. ** that the scan will visit nNew rows. This function returns the number
  123467. ** estimated to be visited after taking pTerm into account.
  123468. **
  123469. ** If the user explicitly specified a likelihood() value for this term,
  123470. ** then the return value is the likelihood multiplied by the number of
  123471. ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
  123472. ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
  123473. */
  123474. static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
  123475. LogEst nRet = nNew;
  123476. if( pTerm ){
  123477. if( pTerm->truthProb<=0 ){
  123478. nRet += pTerm->truthProb;
  123479. }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
  123480. nRet -= 20; assert( 20==sqlite3LogEst(4) );
  123481. }
  123482. }
  123483. return nRet;
  123484. }
  123485. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  123486. /*
  123487. ** Return the affinity for a single column of an index.
  123488. */
  123489. SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
  123490. assert( iCol>=0 && iCol<pIdx->nColumn );
  123491. if( !pIdx->zColAff ){
  123492. if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
  123493. }
  123494. return pIdx->zColAff[iCol];
  123495. }
  123496. #endif
  123497. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  123498. /*
  123499. ** This function is called to estimate the number of rows visited by a
  123500. ** range-scan on a skip-scan index. For example:
  123501. **
  123502. ** CREATE INDEX i1 ON t1(a, b, c);
  123503. ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
  123504. **
  123505. ** Value pLoop->nOut is currently set to the estimated number of rows
  123506. ** visited for scanning (a=? AND b=?). This function reduces that estimate
  123507. ** by some factor to account for the (c BETWEEN ? AND ?) expression based
  123508. ** on the stat4 data for the index. this scan will be peformed multiple
  123509. ** times (once for each (a,b) combination that matches a=?) is dealt with
  123510. ** by the caller.
  123511. **
  123512. ** It does this by scanning through all stat4 samples, comparing values
  123513. ** extracted from pLower and pUpper with the corresponding column in each
  123514. ** sample. If L and U are the number of samples found to be less than or
  123515. ** equal to the values extracted from pLower and pUpper respectively, and
  123516. ** N is the total number of samples, the pLoop->nOut value is adjusted
  123517. ** as follows:
  123518. **
  123519. ** nOut = nOut * ( min(U - L, 1) / N )
  123520. **
  123521. ** If pLower is NULL, or a value cannot be extracted from the term, L is
  123522. ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
  123523. ** U is set to N.
  123524. **
  123525. ** Normally, this function sets *pbDone to 1 before returning. However,
  123526. ** if no value can be extracted from either pLower or pUpper (and so the
  123527. ** estimate of the number of rows delivered remains unchanged), *pbDone
  123528. ** is left as is.
  123529. **
  123530. ** If an error occurs, an SQLite error code is returned. Otherwise,
  123531. ** SQLITE_OK.
  123532. */
  123533. static int whereRangeSkipScanEst(
  123534. Parse *pParse, /* Parsing & code generating context */
  123535. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  123536. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  123537. WhereLoop *pLoop, /* Update the .nOut value of this loop */
  123538. int *pbDone /* Set to true if at least one expr. value extracted */
  123539. ){
  123540. Index *p = pLoop->u.btree.pIndex;
  123541. int nEq = pLoop->u.btree.nEq;
  123542. sqlite3 *db = pParse->db;
  123543. int nLower = -1;
  123544. int nUpper = p->nSample+1;
  123545. int rc = SQLITE_OK;
  123546. u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
  123547. CollSeq *pColl;
  123548. sqlite3_value *p1 = 0; /* Value extracted from pLower */
  123549. sqlite3_value *p2 = 0; /* Value extracted from pUpper */
  123550. sqlite3_value *pVal = 0; /* Value extracted from record */
  123551. pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
  123552. if( pLower ){
  123553. rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
  123554. nLower = 0;
  123555. }
  123556. if( pUpper && rc==SQLITE_OK ){
  123557. rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
  123558. nUpper = p2 ? 0 : p->nSample;
  123559. }
  123560. if( p1 || p2 ){
  123561. int i;
  123562. int nDiff;
  123563. for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
  123564. rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
  123565. if( rc==SQLITE_OK && p1 ){
  123566. int res = sqlite3MemCompare(p1, pVal, pColl);
  123567. if( res>=0 ) nLower++;
  123568. }
  123569. if( rc==SQLITE_OK && p2 ){
  123570. int res = sqlite3MemCompare(p2, pVal, pColl);
  123571. if( res>=0 ) nUpper++;
  123572. }
  123573. }
  123574. nDiff = (nUpper - nLower);
  123575. if( nDiff<=0 ) nDiff = 1;
  123576. /* If there is both an upper and lower bound specified, and the
  123577. ** comparisons indicate that they are close together, use the fallback
  123578. ** method (assume that the scan visits 1/64 of the rows) for estimating
  123579. ** the number of rows visited. Otherwise, estimate the number of rows
  123580. ** using the method described in the header comment for this function. */
  123581. if( nDiff!=1 || pUpper==0 || pLower==0 ){
  123582. int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
  123583. pLoop->nOut -= nAdjust;
  123584. *pbDone = 1;
  123585. WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
  123586. nLower, nUpper, nAdjust*-1, pLoop->nOut));
  123587. }
  123588. }else{
  123589. assert( *pbDone==0 );
  123590. }
  123591. sqlite3ValueFree(p1);
  123592. sqlite3ValueFree(p2);
  123593. sqlite3ValueFree(pVal);
  123594. return rc;
  123595. }
  123596. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  123597. /*
  123598. ** This function is used to estimate the number of rows that will be visited
  123599. ** by scanning an index for a range of values. The range may have an upper
  123600. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  123601. ** and lower bounds are represented by pLower and pUpper respectively. For
  123602. ** example, assuming that index p is on t1(a):
  123603. **
  123604. ** ... FROM t1 WHERE a > ? AND a < ? ...
  123605. ** |_____| |_____|
  123606. ** | |
  123607. ** pLower pUpper
  123608. **
  123609. ** If either of the upper or lower bound is not present, then NULL is passed in
  123610. ** place of the corresponding WhereTerm.
  123611. **
  123612. ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
  123613. ** column subject to the range constraint. Or, equivalently, the number of
  123614. ** equality constraints optimized by the proposed index scan. For example,
  123615. ** assuming index p is on t1(a, b), and the SQL query is:
  123616. **
  123617. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  123618. **
  123619. ** then nEq is set to 1 (as the range restricted column, b, is the second
  123620. ** left-most column of the index). Or, if the query is:
  123621. **
  123622. ** ... FROM t1 WHERE a > ? AND a < ? ...
  123623. **
  123624. ** then nEq is set to 0.
  123625. **
  123626. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  123627. ** number of rows that the index scan is expected to visit without
  123628. ** considering the range constraints. If nEq is 0, then *pnOut is the number of
  123629. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  123630. ** to account for the range constraints pLower and pUpper.
  123631. **
  123632. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  123633. ** used, a single range inequality reduces the search space by a factor of 4.
  123634. ** and a pair of constraints (x>? AND x<?) reduces the expected number of
  123635. ** rows visited by a factor of 64.
  123636. */
  123637. static int whereRangeScanEst(
  123638. Parse *pParse, /* Parsing & code generating context */
  123639. WhereLoopBuilder *pBuilder,
  123640. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  123641. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  123642. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  123643. ){
  123644. int rc = SQLITE_OK;
  123645. int nOut = pLoop->nOut;
  123646. LogEst nNew;
  123647. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  123648. Index *p = pLoop->u.btree.pIndex;
  123649. int nEq = pLoop->u.btree.nEq;
  123650. if( p->nSample>0 && nEq<p->nSampleCol ){
  123651. if( nEq==pBuilder->nRecValid ){
  123652. UnpackedRecord *pRec = pBuilder->pRec;
  123653. tRowcnt a[2];
  123654. int nBtm = pLoop->u.btree.nBtm;
  123655. int nTop = pLoop->u.btree.nTop;
  123656. /* Variable iLower will be set to the estimate of the number of rows in
  123657. ** the index that are less than the lower bound of the range query. The
  123658. ** lower bound being the concatenation of $P and $L, where $P is the
  123659. ** key-prefix formed by the nEq values matched against the nEq left-most
  123660. ** columns of the index, and $L is the value in pLower.
  123661. **
  123662. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  123663. ** is not a simple variable or literal value), the lower bound of the
  123664. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  123665. ** if $L is available, whereKeyStats() is called for both ($P) and
  123666. ** ($P:$L) and the larger of the two returned values is used.
  123667. **
  123668. ** Similarly, iUpper is to be set to the estimate of the number of rows
  123669. ** less than the upper bound of the range query. Where the upper bound
  123670. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  123671. ** of iUpper are requested of whereKeyStats() and the smaller used.
  123672. **
  123673. ** The number of rows between the two bounds is then just iUpper-iLower.
  123674. */
  123675. tRowcnt iLower; /* Rows less than the lower bound */
  123676. tRowcnt iUpper; /* Rows less than the upper bound */
  123677. int iLwrIdx = -2; /* aSample[] for the lower bound */
  123678. int iUprIdx = -1; /* aSample[] for the upper bound */
  123679. if( pRec ){
  123680. testcase( pRec->nField!=pBuilder->nRecValid );
  123681. pRec->nField = pBuilder->nRecValid;
  123682. }
  123683. /* Determine iLower and iUpper using ($P) only. */
  123684. if( nEq==0 ){
  123685. iLower = 0;
  123686. iUpper = p->nRowEst0;
  123687. }else{
  123688. /* Note: this call could be optimized away - since the same values must
  123689. ** have been requested when testing key $P in whereEqualScanEst(). */
  123690. whereKeyStats(pParse, p, pRec, 0, a);
  123691. iLower = a[0];
  123692. iUpper = a[0] + a[1];
  123693. }
  123694. assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  123695. assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  123696. assert( p->aSortOrder!=0 );
  123697. if( p->aSortOrder[nEq] ){
  123698. /* The roles of pLower and pUpper are swapped for a DESC index */
  123699. SWAP(WhereTerm*, pLower, pUpper);
  123700. SWAP(int, nBtm, nTop);
  123701. }
  123702. /* If possible, improve on the iLower estimate using ($P:$L). */
  123703. if( pLower ){
  123704. int n; /* Values extracted from pExpr */
  123705. Expr *pExpr = pLower->pExpr->pRight;
  123706. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
  123707. if( rc==SQLITE_OK && n ){
  123708. tRowcnt iNew;
  123709. u16 mask = WO_GT|WO_LE;
  123710. if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
  123711. iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
  123712. iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
  123713. if( iNew>iLower ) iLower = iNew;
  123714. nOut--;
  123715. pLower = 0;
  123716. }
  123717. }
  123718. /* If possible, improve on the iUpper estimate using ($P:$U). */
  123719. if( pUpper ){
  123720. int n; /* Values extracted from pExpr */
  123721. Expr *pExpr = pUpper->pExpr->pRight;
  123722. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
  123723. if( rc==SQLITE_OK && n ){
  123724. tRowcnt iNew;
  123725. u16 mask = WO_GT|WO_LE;
  123726. if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
  123727. iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
  123728. iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
  123729. if( iNew<iUpper ) iUpper = iNew;
  123730. nOut--;
  123731. pUpper = 0;
  123732. }
  123733. }
  123734. pBuilder->pRec = pRec;
  123735. if( rc==SQLITE_OK ){
  123736. if( iUpper>iLower ){
  123737. nNew = sqlite3LogEst(iUpper - iLower);
  123738. /* TUNING: If both iUpper and iLower are derived from the same
  123739. ** sample, then assume they are 4x more selective. This brings
  123740. ** the estimated selectivity more in line with what it would be
  123741. ** if estimated without the use of STAT3/4 tables. */
  123742. if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
  123743. }else{
  123744. nNew = 10; assert( 10==sqlite3LogEst(2) );
  123745. }
  123746. if( nNew<nOut ){
  123747. nOut = nNew;
  123748. }
  123749. WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
  123750. (u32)iLower, (u32)iUpper, nOut));
  123751. }
  123752. }else{
  123753. int bDone = 0;
  123754. rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
  123755. if( bDone ) return rc;
  123756. }
  123757. }
  123758. #else
  123759. UNUSED_PARAMETER(pParse);
  123760. UNUSED_PARAMETER(pBuilder);
  123761. assert( pLower || pUpper );
  123762. #endif
  123763. assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
  123764. nNew = whereRangeAdjust(pLower, nOut);
  123765. nNew = whereRangeAdjust(pUpper, nNew);
  123766. /* TUNING: If there is both an upper and lower limit and neither limit
  123767. ** has an application-defined likelihood(), assume the range is
  123768. ** reduced by an additional 75%. This means that, by default, an open-ended
  123769. ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
  123770. ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
  123771. ** match 1/64 of the index. */
  123772. if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
  123773. nNew -= 20;
  123774. }
  123775. nOut -= (pLower!=0) + (pUpper!=0);
  123776. if( nNew<10 ) nNew = 10;
  123777. if( nNew<nOut ) nOut = nNew;
  123778. #if defined(WHERETRACE_ENABLED)
  123779. if( pLoop->nOut>nOut ){
  123780. WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
  123781. pLoop->nOut, nOut));
  123782. }
  123783. #endif
  123784. pLoop->nOut = (LogEst)nOut;
  123785. return rc;
  123786. }
  123787. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  123788. /*
  123789. ** Estimate the number of rows that will be returned based on
  123790. ** an equality constraint x=VALUE and where that VALUE occurs in
  123791. ** the histogram data. This only works when x is the left-most
  123792. ** column of an index and sqlite_stat3 histogram data is available
  123793. ** for that index. When pExpr==NULL that means the constraint is
  123794. ** "x IS NULL" instead of "x=VALUE".
  123795. **
  123796. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  123797. ** If unable to make an estimate, leave *pnRow unchanged and return
  123798. ** non-zero.
  123799. **
  123800. ** This routine can fail if it is unable to load a collating sequence
  123801. ** required for string comparison, or if unable to allocate memory
  123802. ** for a UTF conversion required for comparison. The error is stored
  123803. ** in the pParse structure.
  123804. */
  123805. static int whereEqualScanEst(
  123806. Parse *pParse, /* Parsing & code generating context */
  123807. WhereLoopBuilder *pBuilder,
  123808. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  123809. tRowcnt *pnRow /* Write the revised row estimate here */
  123810. ){
  123811. Index *p = pBuilder->pNew->u.btree.pIndex;
  123812. int nEq = pBuilder->pNew->u.btree.nEq;
  123813. UnpackedRecord *pRec = pBuilder->pRec;
  123814. int rc; /* Subfunction return code */
  123815. tRowcnt a[2]; /* Statistics */
  123816. int bOk;
  123817. assert( nEq>=1 );
  123818. assert( nEq<=p->nColumn );
  123819. assert( p->aSample!=0 );
  123820. assert( p->nSample>0 );
  123821. assert( pBuilder->nRecValid<nEq );
  123822. /* If values are not available for all fields of the index to the left
  123823. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  123824. if( pBuilder->nRecValid<(nEq-1) ){
  123825. return SQLITE_NOTFOUND;
  123826. }
  123827. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  123828. ** below would return the same value. */
  123829. if( nEq>=p->nColumn ){
  123830. *pnRow = 1;
  123831. return SQLITE_OK;
  123832. }
  123833. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
  123834. pBuilder->pRec = pRec;
  123835. if( rc!=SQLITE_OK ) return rc;
  123836. if( bOk==0 ) return SQLITE_NOTFOUND;
  123837. pBuilder->nRecValid = nEq;
  123838. whereKeyStats(pParse, p, pRec, 0, a);
  123839. WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
  123840. p->zName, nEq-1, (int)a[1]));
  123841. *pnRow = a[1];
  123842. return rc;
  123843. }
  123844. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  123845. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  123846. /*
  123847. ** Estimate the number of rows that will be returned based on
  123848. ** an IN constraint where the right-hand side of the IN operator
  123849. ** is a list of values. Example:
  123850. **
  123851. ** WHERE x IN (1,2,3,4)
  123852. **
  123853. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  123854. ** If unable to make an estimate, leave *pnRow unchanged and return
  123855. ** non-zero.
  123856. **
  123857. ** This routine can fail if it is unable to load a collating sequence
  123858. ** required for string comparison, or if unable to allocate memory
  123859. ** for a UTF conversion required for comparison. The error is stored
  123860. ** in the pParse structure.
  123861. */
  123862. static int whereInScanEst(
  123863. Parse *pParse, /* Parsing & code generating context */
  123864. WhereLoopBuilder *pBuilder,
  123865. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  123866. tRowcnt *pnRow /* Write the revised row estimate here */
  123867. ){
  123868. Index *p = pBuilder->pNew->u.btree.pIndex;
  123869. i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
  123870. int nRecValid = pBuilder->nRecValid;
  123871. int rc = SQLITE_OK; /* Subfunction return code */
  123872. tRowcnt nEst; /* Number of rows for a single term */
  123873. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  123874. int i; /* Loop counter */
  123875. assert( p->aSample!=0 );
  123876. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  123877. nEst = nRow0;
  123878. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  123879. nRowEst += nEst;
  123880. pBuilder->nRecValid = nRecValid;
  123881. }
  123882. if( rc==SQLITE_OK ){
  123883. if( nRowEst > nRow0 ) nRowEst = nRow0;
  123884. *pnRow = nRowEst;
  123885. WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
  123886. }
  123887. assert( pBuilder->nRecValid==nRecValid );
  123888. return rc;
  123889. }
  123890. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  123891. #ifdef WHERETRACE_ENABLED
  123892. /*
  123893. ** Print the content of a WhereTerm object
  123894. */
  123895. static void whereTermPrint(WhereTerm *pTerm, int iTerm){
  123896. if( pTerm==0 ){
  123897. sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
  123898. }else{
  123899. char zType[4];
  123900. char zLeft[50];
  123901. memcpy(zType, "...", 4);
  123902. if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
  123903. if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
  123904. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
  123905. if( pTerm->eOperator & WO_SINGLE ){
  123906. sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
  123907. pTerm->leftCursor, pTerm->u.leftColumn);
  123908. }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
  123909. sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld",
  123910. pTerm->u.pOrInfo->indexable);
  123911. }else{
  123912. sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
  123913. }
  123914. sqlite3DebugPrintf(
  123915. "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x",
  123916. iTerm, pTerm, zType, zLeft, pTerm->truthProb,
  123917. pTerm->eOperator, pTerm->wtFlags);
  123918. if( pTerm->iField ){
  123919. sqlite3DebugPrintf(" iField=%d\n", pTerm->iField);
  123920. }else{
  123921. sqlite3DebugPrintf("\n");
  123922. }
  123923. sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
  123924. }
  123925. }
  123926. #endif
  123927. #ifdef WHERETRACE_ENABLED
  123928. /*
  123929. ** Show the complete content of a WhereClause
  123930. */
  123931. SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
  123932. int i;
  123933. for(i=0; i<pWC->nTerm; i++){
  123934. whereTermPrint(&pWC->a[i], i);
  123935. }
  123936. }
  123937. #endif
  123938. #ifdef WHERETRACE_ENABLED
  123939. /*
  123940. ** Print a WhereLoop object for debugging purposes
  123941. */
  123942. static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
  123943. WhereInfo *pWInfo = pWC->pWInfo;
  123944. int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
  123945. struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
  123946. Table *pTab = pItem->pTab;
  123947. Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
  123948. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  123949. p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
  123950. sqlite3DebugPrintf(" %12s",
  123951. pItem->zAlias ? pItem->zAlias : pTab->zName);
  123952. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  123953. const char *zName;
  123954. if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
  123955. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  123956. int i = sqlite3Strlen30(zName) - 1;
  123957. while( zName[i]!='_' ) i--;
  123958. zName += i;
  123959. }
  123960. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  123961. }else{
  123962. sqlite3DebugPrintf("%20s","");
  123963. }
  123964. }else{
  123965. char *z;
  123966. if( p->u.vtab.idxStr ){
  123967. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  123968. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  123969. }else{
  123970. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  123971. }
  123972. sqlite3DebugPrintf(" %-19s", z);
  123973. sqlite3_free(z);
  123974. }
  123975. if( p->wsFlags & WHERE_SKIPSCAN ){
  123976. sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
  123977. }else{
  123978. sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
  123979. }
  123980. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  123981. if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
  123982. int i;
  123983. for(i=0; i<p->nLTerm; i++){
  123984. whereTermPrint(p->aLTerm[i], i);
  123985. }
  123986. }
  123987. }
  123988. #endif
  123989. /*
  123990. ** Convert bulk memory into a valid WhereLoop that can be passed
  123991. ** to whereLoopClear harmlessly.
  123992. */
  123993. static void whereLoopInit(WhereLoop *p){
  123994. p->aLTerm = p->aLTermSpace;
  123995. p->nLTerm = 0;
  123996. p->nLSlot = ArraySize(p->aLTermSpace);
  123997. p->wsFlags = 0;
  123998. }
  123999. /*
  124000. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  124001. */
  124002. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  124003. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  124004. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  124005. sqlite3_free(p->u.vtab.idxStr);
  124006. p->u.vtab.needFree = 0;
  124007. p->u.vtab.idxStr = 0;
  124008. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  124009. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  124010. sqlite3DbFreeNN(db, p->u.btree.pIndex);
  124011. p->u.btree.pIndex = 0;
  124012. }
  124013. }
  124014. }
  124015. /*
  124016. ** Deallocate internal memory used by a WhereLoop object
  124017. */
  124018. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  124019. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
  124020. whereLoopClearUnion(db, p);
  124021. whereLoopInit(p);
  124022. }
  124023. /*
  124024. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  124025. */
  124026. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  124027. WhereTerm **paNew;
  124028. if( p->nLSlot>=n ) return SQLITE_OK;
  124029. n = (n+7)&~7;
  124030. paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
  124031. if( paNew==0 ) return SQLITE_NOMEM_BKPT;
  124032. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  124033. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
  124034. p->aLTerm = paNew;
  124035. p->nLSlot = n;
  124036. return SQLITE_OK;
  124037. }
  124038. /*
  124039. ** Transfer content from the second pLoop into the first.
  124040. */
  124041. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  124042. whereLoopClearUnion(db, pTo);
  124043. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  124044. memset(&pTo->u, 0, sizeof(pTo->u));
  124045. return SQLITE_NOMEM_BKPT;
  124046. }
  124047. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  124048. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  124049. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  124050. pFrom->u.vtab.needFree = 0;
  124051. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  124052. pFrom->u.btree.pIndex = 0;
  124053. }
  124054. return SQLITE_OK;
  124055. }
  124056. /*
  124057. ** Delete a WhereLoop object
  124058. */
  124059. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  124060. whereLoopClear(db, p);
  124061. sqlite3DbFreeNN(db, p);
  124062. }
  124063. /*
  124064. ** Free a WhereInfo structure
  124065. */
  124066. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  124067. if( ALWAYS(pWInfo) ){
  124068. int i;
  124069. for(i=0; i<pWInfo->nLevel; i++){
  124070. WhereLevel *pLevel = &pWInfo->a[i];
  124071. if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
  124072. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  124073. }
  124074. }
  124075. sqlite3WhereClauseClear(&pWInfo->sWC);
  124076. while( pWInfo->pLoops ){
  124077. WhereLoop *p = pWInfo->pLoops;
  124078. pWInfo->pLoops = p->pNextLoop;
  124079. whereLoopDelete(db, p);
  124080. }
  124081. sqlite3DbFreeNN(db, pWInfo);
  124082. }
  124083. }
  124084. /*
  124085. ** Return TRUE if all of the following are true:
  124086. **
  124087. ** (1) X has the same or lower cost that Y
  124088. ** (2) X is a proper subset of Y
  124089. ** (3) X skips at least as many columns as Y
  124090. **
  124091. ** By "proper subset" we mean that X uses fewer WHERE clause terms
  124092. ** than Y and that every WHERE clause term used by X is also used
  124093. ** by Y.
  124094. **
  124095. ** If X is a proper subset of Y then Y is a better choice and ought
  124096. ** to have a lower cost. This routine returns TRUE when that cost
  124097. ** relationship is inverted and needs to be adjusted. The third rule
  124098. ** was added because if X uses skip-scan less than Y it still might
  124099. ** deserve a lower cost even if it is a proper subset of Y.
  124100. */
  124101. static int whereLoopCheaperProperSubset(
  124102. const WhereLoop *pX, /* First WhereLoop to compare */
  124103. const WhereLoop *pY /* Compare against this WhereLoop */
  124104. ){
  124105. int i, j;
  124106. if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
  124107. return 0; /* X is not a subset of Y */
  124108. }
  124109. if( pY->nSkip > pX->nSkip ) return 0;
  124110. if( pX->rRun >= pY->rRun ){
  124111. if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
  124112. if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
  124113. }
  124114. for(i=pX->nLTerm-1; i>=0; i--){
  124115. if( pX->aLTerm[i]==0 ) continue;
  124116. for(j=pY->nLTerm-1; j>=0; j--){
  124117. if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
  124118. }
  124119. if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
  124120. }
  124121. return 1; /* All conditions meet */
  124122. }
  124123. /*
  124124. ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
  124125. ** that:
  124126. **
  124127. ** (1) pTemplate costs less than any other WhereLoops that are a proper
  124128. ** subset of pTemplate
  124129. **
  124130. ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
  124131. ** is a proper subset.
  124132. **
  124133. ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
  124134. ** WHERE clause terms than Y and that every WHERE clause term used by X is
  124135. ** also used by Y.
  124136. */
  124137. static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
  124138. if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
  124139. for(; p; p=p->pNextLoop){
  124140. if( p->iTab!=pTemplate->iTab ) continue;
  124141. if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
  124142. if( whereLoopCheaperProperSubset(p, pTemplate) ){
  124143. /* Adjust pTemplate cost downward so that it is cheaper than its
  124144. ** subset p. */
  124145. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  124146. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
  124147. pTemplate->rRun = p->rRun;
  124148. pTemplate->nOut = p->nOut - 1;
  124149. }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
  124150. /* Adjust pTemplate cost upward so that it is costlier than p since
  124151. ** pTemplate is a proper subset of p */
  124152. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  124153. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
  124154. pTemplate->rRun = p->rRun;
  124155. pTemplate->nOut = p->nOut + 1;
  124156. }
  124157. }
  124158. }
  124159. /*
  124160. ** Search the list of WhereLoops in *ppPrev looking for one that can be
  124161. ** supplanted by pTemplate.
  124162. **
  124163. ** Return NULL if the WhereLoop list contains an entry that can supplant
  124164. ** pTemplate, in other words if pTemplate does not belong on the list.
  124165. **
  124166. ** If pX is a WhereLoop that pTemplate can supplant, then return the
  124167. ** link that points to pX.
  124168. **
  124169. ** If pTemplate cannot supplant any existing element of the list but needs
  124170. ** to be added to the list, then return a pointer to the tail of the list.
  124171. */
  124172. static WhereLoop **whereLoopFindLesser(
  124173. WhereLoop **ppPrev,
  124174. const WhereLoop *pTemplate
  124175. ){
  124176. WhereLoop *p;
  124177. for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
  124178. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  124179. /* If either the iTab or iSortIdx values for two WhereLoop are different
  124180. ** then those WhereLoops need to be considered separately. Neither is
  124181. ** a candidate to replace the other. */
  124182. continue;
  124183. }
  124184. /* In the current implementation, the rSetup value is either zero
  124185. ** or the cost of building an automatic index (NlogN) and the NlogN
  124186. ** is the same for compatible WhereLoops. */
  124187. assert( p->rSetup==0 || pTemplate->rSetup==0
  124188. || p->rSetup==pTemplate->rSetup );
  124189. /* whereLoopAddBtree() always generates and inserts the automatic index
  124190. ** case first. Hence compatible candidate WhereLoops never have a larger
  124191. ** rSetup. Call this SETUP-INVARIANT */
  124192. assert( p->rSetup>=pTemplate->rSetup );
  124193. /* Any loop using an appliation-defined index (or PRIMARY KEY or
  124194. ** UNIQUE constraint) with one or more == constraints is better
  124195. ** than an automatic index. Unless it is a skip-scan. */
  124196. if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
  124197. && (pTemplate->nSkip)==0
  124198. && (pTemplate->wsFlags & WHERE_INDEXED)!=0
  124199. && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
  124200. && (p->prereq & pTemplate->prereq)==pTemplate->prereq
  124201. ){
  124202. break;
  124203. }
  124204. /* If existing WhereLoop p is better than pTemplate, pTemplate can be
  124205. ** discarded. WhereLoop p is better if:
  124206. ** (1) p has no more dependencies than pTemplate, and
  124207. ** (2) p has an equal or lower cost than pTemplate
  124208. */
  124209. if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
  124210. && p->rSetup<=pTemplate->rSetup /* (2a) */
  124211. && p->rRun<=pTemplate->rRun /* (2b) */
  124212. && p->nOut<=pTemplate->nOut /* (2c) */
  124213. ){
  124214. return 0; /* Discard pTemplate */
  124215. }
  124216. /* If pTemplate is always better than p, then cause p to be overwritten
  124217. ** with pTemplate. pTemplate is better than p if:
  124218. ** (1) pTemplate has no more dependences than p, and
  124219. ** (2) pTemplate has an equal or lower cost than p.
  124220. */
  124221. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
  124222. && p->rRun>=pTemplate->rRun /* (2a) */
  124223. && p->nOut>=pTemplate->nOut /* (2b) */
  124224. ){
  124225. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  124226. break; /* Cause p to be overwritten by pTemplate */
  124227. }
  124228. }
  124229. return ppPrev;
  124230. }
  124231. /*
  124232. ** Insert or replace a WhereLoop entry using the template supplied.
  124233. **
  124234. ** An existing WhereLoop entry might be overwritten if the new template
  124235. ** is better and has fewer dependencies. Or the template will be ignored
  124236. ** and no insert will occur if an existing WhereLoop is faster and has
  124237. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  124238. ** added based on the template.
  124239. **
  124240. ** If pBuilder->pOrSet is not NULL then we care about only the
  124241. ** prerequisites and rRun and nOut costs of the N best loops. That
  124242. ** information is gathered in the pBuilder->pOrSet object. This special
  124243. ** processing mode is used only for OR clause processing.
  124244. **
  124245. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  124246. ** still might overwrite similar loops with the new template if the
  124247. ** new template is better. Loops may be overwritten if the following
  124248. ** conditions are met:
  124249. **
  124250. ** (1) They have the same iTab.
  124251. ** (2) They have the same iSortIdx.
  124252. ** (3) The template has same or fewer dependencies than the current loop
  124253. ** (4) The template has the same or lower cost than the current loop
  124254. */
  124255. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  124256. WhereLoop **ppPrev, *p;
  124257. WhereInfo *pWInfo = pBuilder->pWInfo;
  124258. sqlite3 *db = pWInfo->pParse->db;
  124259. int rc;
  124260. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  124261. ** and prereqs.
  124262. */
  124263. if( pBuilder->pOrSet!=0 ){
  124264. if( pTemplate->nLTerm ){
  124265. #if WHERETRACE_ENABLED
  124266. u16 n = pBuilder->pOrSet->n;
  124267. int x =
  124268. #endif
  124269. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  124270. pTemplate->nOut);
  124271. #if WHERETRACE_ENABLED /* 0x8 */
  124272. if( sqlite3WhereTrace & 0x8 ){
  124273. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  124274. whereLoopPrint(pTemplate, pBuilder->pWC);
  124275. }
  124276. #endif
  124277. }
  124278. return SQLITE_OK;
  124279. }
  124280. /* Look for an existing WhereLoop to replace with pTemplate
  124281. */
  124282. whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
  124283. ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
  124284. if( ppPrev==0 ){
  124285. /* There already exists a WhereLoop on the list that is better
  124286. ** than pTemplate, so just ignore pTemplate */
  124287. #if WHERETRACE_ENABLED /* 0x8 */
  124288. if( sqlite3WhereTrace & 0x8 ){
  124289. sqlite3DebugPrintf(" skip: ");
  124290. whereLoopPrint(pTemplate, pBuilder->pWC);
  124291. }
  124292. #endif
  124293. return SQLITE_OK;
  124294. }else{
  124295. p = *ppPrev;
  124296. }
  124297. /* If we reach this point it means that either p[] should be overwritten
  124298. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  124299. ** WhereLoop and insert it.
  124300. */
  124301. #if WHERETRACE_ENABLED /* 0x8 */
  124302. if( sqlite3WhereTrace & 0x8 ){
  124303. if( p!=0 ){
  124304. sqlite3DebugPrintf("replace: ");
  124305. whereLoopPrint(p, pBuilder->pWC);
  124306. }
  124307. sqlite3DebugPrintf(" add: ");
  124308. whereLoopPrint(pTemplate, pBuilder->pWC);
  124309. }
  124310. #endif
  124311. if( p==0 ){
  124312. /* Allocate a new WhereLoop to add to the end of the list */
  124313. *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
  124314. if( p==0 ) return SQLITE_NOMEM_BKPT;
  124315. whereLoopInit(p);
  124316. p->pNextLoop = 0;
  124317. }else{
  124318. /* We will be overwriting WhereLoop p[]. But before we do, first
  124319. ** go through the rest of the list and delete any other entries besides
  124320. ** p[] that are also supplated by pTemplate */
  124321. WhereLoop **ppTail = &p->pNextLoop;
  124322. WhereLoop *pToDel;
  124323. while( *ppTail ){
  124324. ppTail = whereLoopFindLesser(ppTail, pTemplate);
  124325. if( ppTail==0 ) break;
  124326. pToDel = *ppTail;
  124327. if( pToDel==0 ) break;
  124328. *ppTail = pToDel->pNextLoop;
  124329. #if WHERETRACE_ENABLED /* 0x8 */
  124330. if( sqlite3WhereTrace & 0x8 ){
  124331. sqlite3DebugPrintf(" delete: ");
  124332. whereLoopPrint(pToDel, pBuilder->pWC);
  124333. }
  124334. #endif
  124335. whereLoopDelete(db, pToDel);
  124336. }
  124337. }
  124338. rc = whereLoopXfer(db, p, pTemplate);
  124339. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  124340. Index *pIndex = p->u.btree.pIndex;
  124341. if( pIndex && pIndex->tnum==0 ){
  124342. p->u.btree.pIndex = 0;
  124343. }
  124344. }
  124345. return rc;
  124346. }
  124347. /*
  124348. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  124349. ** WHERE clause that reference the loop but which are not used by an
  124350. ** index.
  124351. *
  124352. ** For every WHERE clause term that is not used by the index
  124353. ** and which has a truth probability assigned by one of the likelihood(),
  124354. ** likely(), or unlikely() SQL functions, reduce the estimated number
  124355. ** of output rows by the probability specified.
  124356. **
  124357. ** TUNING: For every WHERE clause term that is not used by the index
  124358. ** and which does not have an assigned truth probability, heuristics
  124359. ** described below are used to try to estimate the truth probability.
  124360. ** TODO --> Perhaps this is something that could be improved by better
  124361. ** table statistics.
  124362. **
  124363. ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
  124364. ** value corresponds to -1 in LogEst notation, so this means decrement
  124365. ** the WhereLoop.nOut field for every such WHERE clause term.
  124366. **
  124367. ** Heuristic 2: If there exists one or more WHERE clause terms of the
  124368. ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
  124369. ** final output row estimate is no greater than 1/4 of the total number
  124370. ** of rows in the table. In other words, assume that x==EXPR will filter
  124371. ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
  124372. ** "x" column is boolean or else -1 or 0 or 1 is a common default value
  124373. ** on the "x" column and so in that case only cap the output row estimate
  124374. ** at 1/2 instead of 1/4.
  124375. */
  124376. static void whereLoopOutputAdjust(
  124377. WhereClause *pWC, /* The WHERE clause */
  124378. WhereLoop *pLoop, /* The loop to adjust downward */
  124379. LogEst nRow /* Number of rows in the entire table */
  124380. ){
  124381. WhereTerm *pTerm, *pX;
  124382. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  124383. int i, j, k;
  124384. LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
  124385. assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  124386. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  124387. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  124388. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  124389. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  124390. for(j=pLoop->nLTerm-1; j>=0; j--){
  124391. pX = pLoop->aLTerm[j];
  124392. if( pX==0 ) continue;
  124393. if( pX==pTerm ) break;
  124394. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  124395. }
  124396. if( j<0 ){
  124397. if( pTerm->truthProb<=0 ){
  124398. /* If a truth probability is specified using the likelihood() hints,
  124399. ** then use the probability provided by the application. */
  124400. pLoop->nOut += pTerm->truthProb;
  124401. }else{
  124402. /* In the absence of explicit truth probabilities, use heuristics to
  124403. ** guess a reasonable truth probability. */
  124404. pLoop->nOut--;
  124405. if( pTerm->eOperator&(WO_EQ|WO_IS) ){
  124406. Expr *pRight = pTerm->pExpr->pRight;
  124407. testcase( pTerm->pExpr->op==TK_IS );
  124408. if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
  124409. k = 10;
  124410. }else{
  124411. k = 20;
  124412. }
  124413. if( iReduce<k ) iReduce = k;
  124414. }
  124415. }
  124416. }
  124417. }
  124418. if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
  124419. }
  124420. /*
  124421. ** Term pTerm is a vector range comparison operation. The first comparison
  124422. ** in the vector can be optimized using column nEq of the index. This
  124423. ** function returns the total number of vector elements that can be used
  124424. ** as part of the range comparison.
  124425. **
  124426. ** For example, if the query is:
  124427. **
  124428. ** WHERE a = ? AND (b, c, d) > (?, ?, ?)
  124429. **
  124430. ** and the index:
  124431. **
  124432. ** CREATE INDEX ... ON (a, b, c, d, e)
  124433. **
  124434. ** then this function would be invoked with nEq=1. The value returned in
  124435. ** this case is 3.
  124436. */
  124437. static int whereRangeVectorLen(
  124438. Parse *pParse, /* Parsing context */
  124439. int iCur, /* Cursor open on pIdx */
  124440. Index *pIdx, /* The index to be used for a inequality constraint */
  124441. int nEq, /* Number of prior equality constraints on same index */
  124442. WhereTerm *pTerm /* The vector inequality constraint */
  124443. ){
  124444. int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
  124445. int i;
  124446. nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
  124447. for(i=1; i<nCmp; i++){
  124448. /* Test if comparison i of pTerm is compatible with column (i+nEq)
  124449. ** of the index. If not, exit the loop. */
  124450. char aff; /* Comparison affinity */
  124451. char idxaff = 0; /* Indexed columns affinity */
  124452. CollSeq *pColl; /* Comparison collation sequence */
  124453. Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
  124454. Expr *pRhs = pTerm->pExpr->pRight;
  124455. if( pRhs->flags & EP_xIsSelect ){
  124456. pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
  124457. }else{
  124458. pRhs = pRhs->x.pList->a[i].pExpr;
  124459. }
  124460. /* Check that the LHS of the comparison is a column reference to
  124461. ** the right column of the right source table. And that the sort
  124462. ** order of the index column is the same as the sort order of the
  124463. ** leftmost index column. */
  124464. if( pLhs->op!=TK_COLUMN
  124465. || pLhs->iTable!=iCur
  124466. || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
  124467. || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
  124468. ){
  124469. break;
  124470. }
  124471. testcase( pLhs->iColumn==XN_ROWID );
  124472. aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
  124473. idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
  124474. if( aff!=idxaff ) break;
  124475. pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
  124476. if( pColl==0 ) break;
  124477. if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
  124478. }
  124479. return i;
  124480. }
  124481. /*
  124482. ** Adjust the cost C by the costMult facter T. This only occurs if
  124483. ** compiled with -DSQLITE_ENABLE_COSTMULT
  124484. */
  124485. #ifdef SQLITE_ENABLE_COSTMULT
  124486. # define ApplyCostMultiplier(C,T) C += T
  124487. #else
  124488. # define ApplyCostMultiplier(C,T)
  124489. #endif
  124490. /*
  124491. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
  124492. ** index pIndex. Try to match one more.
  124493. **
  124494. ** When this function is called, pBuilder->pNew->nOut contains the
  124495. ** number of rows expected to be visited by filtering using the nEq
  124496. ** terms only. If it is modified, this value is restored before this
  124497. ** function returns.
  124498. **
  124499. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  124500. ** INTEGER PRIMARY KEY.
  124501. */
  124502. static int whereLoopAddBtreeIndex(
  124503. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  124504. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  124505. Index *pProbe, /* An index on pSrc */
  124506. LogEst nInMul /* log(Number of iterations due to IN) */
  124507. ){
  124508. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  124509. Parse *pParse = pWInfo->pParse; /* Parsing context */
  124510. sqlite3 *db = pParse->db; /* Database connection malloc context */
  124511. WhereLoop *pNew; /* Template WhereLoop under construction */
  124512. WhereTerm *pTerm; /* A WhereTerm under consideration */
  124513. int opMask; /* Valid operators for constraints */
  124514. WhereScan scan; /* Iterator for WHERE terms */
  124515. Bitmask saved_prereq; /* Original value of pNew->prereq */
  124516. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  124517. u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
  124518. u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */
  124519. u16 saved_nTop; /* Original value of pNew->u.btree.nTop */
  124520. u16 saved_nSkip; /* Original value of pNew->nSkip */
  124521. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  124522. LogEst saved_nOut; /* Original value of pNew->nOut */
  124523. int rc = SQLITE_OK; /* Return code */
  124524. LogEst rSize; /* Number of rows in the table */
  124525. LogEst rLogSize; /* Logarithm of table size */
  124526. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  124527. pNew = pBuilder->pNew;
  124528. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  124529. WHERETRACE(0x800, ("BEGIN addBtreeIdx(%s), nEq=%d\n",
  124530. pProbe->zName, pNew->u.btree.nEq));
  124531. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  124532. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  124533. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  124534. opMask = WO_LT|WO_LE;
  124535. }else{
  124536. assert( pNew->u.btree.nBtm==0 );
  124537. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
  124538. }
  124539. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  124540. assert( pNew->u.btree.nEq<pProbe->nColumn );
  124541. saved_nEq = pNew->u.btree.nEq;
  124542. saved_nBtm = pNew->u.btree.nBtm;
  124543. saved_nTop = pNew->u.btree.nTop;
  124544. saved_nSkip = pNew->nSkip;
  124545. saved_nLTerm = pNew->nLTerm;
  124546. saved_wsFlags = pNew->wsFlags;
  124547. saved_prereq = pNew->prereq;
  124548. saved_nOut = pNew->nOut;
  124549. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
  124550. opMask, pProbe);
  124551. pNew->rSetup = 0;
  124552. rSize = pProbe->aiRowLogEst[0];
  124553. rLogSize = estLog(rSize);
  124554. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  124555. u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
  124556. LogEst rCostIdx;
  124557. LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
  124558. int nIn = 0;
  124559. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  124560. int nRecValid = pBuilder->nRecValid;
  124561. #endif
  124562. if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  124563. && indexColumnNotNull(pProbe, saved_nEq)
  124564. ){
  124565. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  124566. }
  124567. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  124568. /* Do not allow the upper bound of a LIKE optimization range constraint
  124569. ** to mix with a lower range bound from some other source */
  124570. if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
  124571. /* Do not allow IS constraints from the WHERE clause to be used by the
  124572. ** right table of a LEFT JOIN. Only constraints in the ON clause are
  124573. ** allowed */
  124574. if( (pSrc->fg.jointype & JT_LEFT)!=0
  124575. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  124576. && (eOp & (WO_IS|WO_ISNULL))!=0
  124577. ){
  124578. testcase( eOp & WO_IS );
  124579. testcase( eOp & WO_ISNULL );
  124580. continue;
  124581. }
  124582. if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
  124583. pBuilder->bldFlags |= SQLITE_BLDF_UNIQUE;
  124584. }else{
  124585. pBuilder->bldFlags |= SQLITE_BLDF_INDEXED;
  124586. }
  124587. pNew->wsFlags = saved_wsFlags;
  124588. pNew->u.btree.nEq = saved_nEq;
  124589. pNew->u.btree.nBtm = saved_nBtm;
  124590. pNew->u.btree.nTop = saved_nTop;
  124591. pNew->nLTerm = saved_nLTerm;
  124592. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  124593. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  124594. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  124595. assert( nInMul==0
  124596. || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
  124597. || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
  124598. || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
  124599. );
  124600. if( eOp & WO_IN ){
  124601. Expr *pExpr = pTerm->pExpr;
  124602. pNew->wsFlags |= WHERE_COLUMN_IN;
  124603. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  124604. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  124605. int i;
  124606. nIn = 46; assert( 46==sqlite3LogEst(25) );
  124607. /* The expression may actually be of the form (x, y) IN (SELECT...).
  124608. ** In this case there is a separate term for each of (x) and (y).
  124609. ** However, the nIn multiplier should only be applied once, not once
  124610. ** for each such term. The following loop checks that pTerm is the
  124611. ** first such term in use, and sets nIn back to 0 if it is not. */
  124612. for(i=0; i<pNew->nLTerm-1; i++){
  124613. if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
  124614. }
  124615. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  124616. /* "x IN (value, value, ...)" */
  124617. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  124618. assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
  124619. ** changes "x IN (?)" into "x=?". */
  124620. }
  124621. }else if( eOp & (WO_EQ|WO_IS) ){
  124622. int iCol = pProbe->aiColumn[saved_nEq];
  124623. pNew->wsFlags |= WHERE_COLUMN_EQ;
  124624. assert( saved_nEq==pNew->u.btree.nEq );
  124625. if( iCol==XN_ROWID
  124626. || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
  124627. ){
  124628. if( iCol>=0 && pProbe->uniqNotNull==0 ){
  124629. pNew->wsFlags |= WHERE_UNQ_WANTED;
  124630. }else{
  124631. pNew->wsFlags |= WHERE_ONEROW;
  124632. }
  124633. }
  124634. }else if( eOp & WO_ISNULL ){
  124635. pNew->wsFlags |= WHERE_COLUMN_NULL;
  124636. }else if( eOp & (WO_GT|WO_GE) ){
  124637. testcase( eOp & WO_GT );
  124638. testcase( eOp & WO_GE );
  124639. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  124640. pNew->u.btree.nBtm = whereRangeVectorLen(
  124641. pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
  124642. );
  124643. pBtm = pTerm;
  124644. pTop = 0;
  124645. if( pTerm->wtFlags & TERM_LIKEOPT ){
  124646. /* Range contraints that come from the LIKE optimization are
  124647. ** always used in pairs. */
  124648. pTop = &pTerm[1];
  124649. assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
  124650. assert( pTop->wtFlags & TERM_LIKEOPT );
  124651. assert( pTop->eOperator==WO_LT );
  124652. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  124653. pNew->aLTerm[pNew->nLTerm++] = pTop;
  124654. pNew->wsFlags |= WHERE_TOP_LIMIT;
  124655. pNew->u.btree.nTop = 1;
  124656. }
  124657. }else{
  124658. assert( eOp & (WO_LT|WO_LE) );
  124659. testcase( eOp & WO_LT );
  124660. testcase( eOp & WO_LE );
  124661. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  124662. pNew->u.btree.nTop = whereRangeVectorLen(
  124663. pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
  124664. );
  124665. pTop = pTerm;
  124666. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  124667. pNew->aLTerm[pNew->nLTerm-2] : 0;
  124668. }
  124669. /* At this point pNew->nOut is set to the number of rows expected to
  124670. ** be visited by the index scan before considering term pTerm, or the
  124671. ** values of nIn and nInMul. In other words, assuming that all
  124672. ** "x IN(...)" terms are replaced with "x = ?". This block updates
  124673. ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
  124674. assert( pNew->nOut==saved_nOut );
  124675. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  124676. /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
  124677. ** data, using some other estimate. */
  124678. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  124679. }else{
  124680. int nEq = ++pNew->u.btree.nEq;
  124681. assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
  124682. assert( pNew->nOut==saved_nOut );
  124683. if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
  124684. assert( (eOp & WO_IN) || nIn==0 );
  124685. testcase( eOp & WO_IN );
  124686. pNew->nOut += pTerm->truthProb;
  124687. pNew->nOut -= nIn;
  124688. }else{
  124689. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  124690. tRowcnt nOut = 0;
  124691. if( nInMul==0
  124692. && pProbe->nSample
  124693. && pNew->u.btree.nEq<=pProbe->nSampleCol
  124694. && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
  124695. ){
  124696. Expr *pExpr = pTerm->pExpr;
  124697. if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
  124698. testcase( eOp & WO_EQ );
  124699. testcase( eOp & WO_IS );
  124700. testcase( eOp & WO_ISNULL );
  124701. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  124702. }else{
  124703. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  124704. }
  124705. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  124706. if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
  124707. if( nOut ){
  124708. pNew->nOut = sqlite3LogEst(nOut);
  124709. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  124710. pNew->nOut -= nIn;
  124711. }
  124712. }
  124713. if( nOut==0 )
  124714. #endif
  124715. {
  124716. pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
  124717. if( eOp & WO_ISNULL ){
  124718. /* TUNING: If there is no likelihood() value, assume that a
  124719. ** "col IS NULL" expression matches twice as many rows
  124720. ** as (col=?). */
  124721. pNew->nOut += 10;
  124722. }
  124723. }
  124724. }
  124725. }
  124726. /* Set rCostIdx to the cost of visiting selected rows in index. Add
  124727. ** it to pNew->rRun, which is currently set to the cost of the index
  124728. ** seek only. Then, if this is a non-covering index, add the cost of
  124729. ** visiting the rows in the main table. */
  124730. rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
  124731. pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
  124732. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  124733. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
  124734. }
  124735. ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
  124736. nOutUnadjusted = pNew->nOut;
  124737. pNew->rRun += nInMul + nIn;
  124738. pNew->nOut += nInMul + nIn;
  124739. whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
  124740. rc = whereLoopInsert(pBuilder, pNew);
  124741. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  124742. pNew->nOut = saved_nOut;
  124743. }else{
  124744. pNew->nOut = nOutUnadjusted;
  124745. }
  124746. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  124747. && pNew->u.btree.nEq<pProbe->nColumn
  124748. ){
  124749. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  124750. }
  124751. pNew->nOut = saved_nOut;
  124752. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  124753. pBuilder->nRecValid = nRecValid;
  124754. #endif
  124755. }
  124756. pNew->prereq = saved_prereq;
  124757. pNew->u.btree.nEq = saved_nEq;
  124758. pNew->u.btree.nBtm = saved_nBtm;
  124759. pNew->u.btree.nTop = saved_nTop;
  124760. pNew->nSkip = saved_nSkip;
  124761. pNew->wsFlags = saved_wsFlags;
  124762. pNew->nOut = saved_nOut;
  124763. pNew->nLTerm = saved_nLTerm;
  124764. /* Consider using a skip-scan if there are no WHERE clause constraints
  124765. ** available for the left-most terms of the index, and if the average
  124766. ** number of repeats in the left-most terms is at least 18.
  124767. **
  124768. ** The magic number 18 is selected on the basis that scanning 17 rows
  124769. ** is almost always quicker than an index seek (even though if the index
  124770. ** contains fewer than 2^17 rows we assume otherwise in other parts of
  124771. ** the code). And, even if it is not, it should not be too much slower.
  124772. ** On the other hand, the extra seeks could end up being significantly
  124773. ** more expensive. */
  124774. assert( 42==sqlite3LogEst(18) );
  124775. if( saved_nEq==saved_nSkip
  124776. && saved_nEq+1<pProbe->nKeyCol
  124777. && pProbe->noSkipScan==0
  124778. && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
  124779. && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
  124780. ){
  124781. LogEst nIter;
  124782. pNew->u.btree.nEq++;
  124783. pNew->nSkip++;
  124784. pNew->aLTerm[pNew->nLTerm++] = 0;
  124785. pNew->wsFlags |= WHERE_SKIPSCAN;
  124786. nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
  124787. pNew->nOut -= nIter;
  124788. /* TUNING: Because uncertainties in the estimates for skip-scan queries,
  124789. ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
  124790. nIter += 5;
  124791. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
  124792. pNew->nOut = saved_nOut;
  124793. pNew->u.btree.nEq = saved_nEq;
  124794. pNew->nSkip = saved_nSkip;
  124795. pNew->wsFlags = saved_wsFlags;
  124796. }
  124797. WHERETRACE(0x800, ("END addBtreeIdx(%s), nEq=%d, rc=%d\n",
  124798. pProbe->zName, saved_nEq, rc));
  124799. return rc;
  124800. }
  124801. /*
  124802. ** Return True if it is possible that pIndex might be useful in
  124803. ** implementing the ORDER BY clause in pBuilder.
  124804. **
  124805. ** Return False if pBuilder does not contain an ORDER BY clause or
  124806. ** if there is no way for pIndex to be useful in implementing that
  124807. ** ORDER BY clause.
  124808. */
  124809. static int indexMightHelpWithOrderBy(
  124810. WhereLoopBuilder *pBuilder,
  124811. Index *pIndex,
  124812. int iCursor
  124813. ){
  124814. ExprList *pOB;
  124815. ExprList *aColExpr;
  124816. int ii, jj;
  124817. if( pIndex->bUnordered ) return 0;
  124818. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  124819. for(ii=0; ii<pOB->nExpr; ii++){
  124820. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  124821. if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
  124822. if( pExpr->iColumn<0 ) return 1;
  124823. for(jj=0; jj<pIndex->nKeyCol; jj++){
  124824. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  124825. }
  124826. }else if( (aColExpr = pIndex->aColExpr)!=0 ){
  124827. for(jj=0; jj<pIndex->nKeyCol; jj++){
  124828. if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
  124829. if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
  124830. return 1;
  124831. }
  124832. }
  124833. }
  124834. }
  124835. return 0;
  124836. }
  124837. /*
  124838. ** Return a bitmask where 1s indicate that the corresponding column of
  124839. ** the table is used by an index. Only the first 63 columns are considered.
  124840. */
  124841. static Bitmask columnsInIndex(Index *pIdx){
  124842. Bitmask m = 0;
  124843. int j;
  124844. for(j=pIdx->nColumn-1; j>=0; j--){
  124845. int x = pIdx->aiColumn[j];
  124846. if( x>=0 ){
  124847. testcase( x==BMS-1 );
  124848. testcase( x==BMS-2 );
  124849. if( x<BMS-1 ) m |= MASKBIT(x);
  124850. }
  124851. }
  124852. return m;
  124853. }
  124854. /* Check to see if a partial index with pPartIndexWhere can be used
  124855. ** in the current query. Return true if it can be and false if not.
  124856. */
  124857. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  124858. int i;
  124859. WhereTerm *pTerm;
  124860. while( pWhere->op==TK_AND ){
  124861. if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
  124862. pWhere = pWhere->pRight;
  124863. }
  124864. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  124865. Expr *pExpr = pTerm->pExpr;
  124866. if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
  124867. && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
  124868. ){
  124869. return 1;
  124870. }
  124871. }
  124872. return 0;
  124873. }
  124874. /*
  124875. ** Add all WhereLoop objects for a single table of the join where the table
  124876. ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be
  124877. ** a b-tree table, not a virtual table.
  124878. **
  124879. ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
  124880. ** are calculated as follows:
  124881. **
  124882. ** For a full scan, assuming the table (or index) contains nRow rows:
  124883. **
  124884. ** cost = nRow * 3.0 // full-table scan
  124885. ** cost = nRow * K // scan of covering index
  124886. ** cost = nRow * (K+3.0) // scan of non-covering index
  124887. **
  124888. ** where K is a value between 1.1 and 3.0 set based on the relative
  124889. ** estimated average size of the index and table records.
  124890. **
  124891. ** For an index scan, where nVisit is the number of index rows visited
  124892. ** by the scan, and nSeek is the number of seek operations required on
  124893. ** the index b-tree:
  124894. **
  124895. ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
  124896. ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
  124897. **
  124898. ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
  124899. ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
  124900. ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
  124901. **
  124902. ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
  124903. ** of uncertainty. For this reason, scoring is designed to pick plans that
  124904. ** "do the least harm" if the estimates are inaccurate. For example, a
  124905. ** log(nRow) factor is omitted from a non-covering index scan in order to
  124906. ** bias the scoring in favor of using an index, since the worst-case
  124907. ** performance of using an index is far better than the worst-case performance
  124908. ** of a full table scan.
  124909. */
  124910. static int whereLoopAddBtree(
  124911. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  124912. Bitmask mPrereq /* Extra prerequesites for using this table */
  124913. ){
  124914. WhereInfo *pWInfo; /* WHERE analysis context */
  124915. Index *pProbe; /* An index we are evaluating */
  124916. Index sPk; /* A fake index object for the primary key */
  124917. LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
  124918. i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  124919. SrcList *pTabList; /* The FROM clause */
  124920. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  124921. WhereLoop *pNew; /* Template WhereLoop object */
  124922. int rc = SQLITE_OK; /* Return code */
  124923. int iSortIdx = 1; /* Index number */
  124924. int b; /* A boolean value */
  124925. LogEst rSize; /* number of rows in the table */
  124926. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  124927. WhereClause *pWC; /* The parsed WHERE clause */
  124928. Table *pTab; /* Table being queried */
  124929. pNew = pBuilder->pNew;
  124930. pWInfo = pBuilder->pWInfo;
  124931. pTabList = pWInfo->pTabList;
  124932. pSrc = pTabList->a + pNew->iTab;
  124933. pTab = pSrc->pTab;
  124934. pWC = pBuilder->pWC;
  124935. assert( !IsVirtual(pSrc->pTab) );
  124936. if( pSrc->pIBIndex ){
  124937. /* An INDEXED BY clause specifies a particular index to use */
  124938. pProbe = pSrc->pIBIndex;
  124939. }else if( !HasRowid(pTab) ){
  124940. pProbe = pTab->pIndex;
  124941. }else{
  124942. /* There is no INDEXED BY clause. Create a fake Index object in local
  124943. ** variable sPk to represent the rowid primary key index. Make this
  124944. ** fake index the first in a chain of Index objects with all of the real
  124945. ** indices to follow */
  124946. Index *pFirst; /* First of real indices on the table */
  124947. memset(&sPk, 0, sizeof(Index));
  124948. sPk.nKeyCol = 1;
  124949. sPk.nColumn = 1;
  124950. sPk.aiColumn = &aiColumnPk;
  124951. sPk.aiRowLogEst = aiRowEstPk;
  124952. sPk.onError = OE_Replace;
  124953. sPk.pTable = pTab;
  124954. sPk.szIdxRow = pTab->szTabRow;
  124955. aiRowEstPk[0] = pTab->nRowLogEst;
  124956. aiRowEstPk[1] = 0;
  124957. pFirst = pSrc->pTab->pIndex;
  124958. if( pSrc->fg.notIndexed==0 ){
  124959. /* The real indices of the table are only considered if the
  124960. ** NOT INDEXED qualifier is omitted from the FROM clause */
  124961. sPk.pNext = pFirst;
  124962. }
  124963. pProbe = &sPk;
  124964. }
  124965. rSize = pTab->nRowLogEst;
  124966. rLogSize = estLog(rSize);
  124967. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  124968. /* Automatic indexes */
  124969. if( !pBuilder->pOrSet /* Not part of an OR optimization */
  124970. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  124971. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  124972. && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
  124973. && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
  124974. && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
  124975. && !pSrc->fg.isCorrelated /* Not a correlated subquery */
  124976. && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
  124977. ){
  124978. /* Generate auto-index WhereLoops */
  124979. WhereTerm *pTerm;
  124980. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  124981. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  124982. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  124983. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  124984. pNew->u.btree.nEq = 1;
  124985. pNew->nSkip = 0;
  124986. pNew->u.btree.pIndex = 0;
  124987. pNew->nLTerm = 1;
  124988. pNew->aLTerm[0] = pTerm;
  124989. /* TUNING: One-time cost for computing the automatic index is
  124990. ** estimated to be X*N*log2(N) where N is the number of rows in
  124991. ** the table being indexed and where X is 7 (LogEst=28) for normal
  124992. ** tables or 1.375 (LogEst=4) for views and subqueries. The value
  124993. ** of X is smaller for views and subqueries so that the query planner
  124994. ** will be more aggressive about generating automatic indexes for
  124995. ** those objects, since there is no opportunity to add schema
  124996. ** indexes on subqueries and views. */
  124997. pNew->rSetup = rLogSize + rSize + 4;
  124998. if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
  124999. pNew->rSetup += 24;
  125000. }
  125001. ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
  125002. if( pNew->rSetup<0 ) pNew->rSetup = 0;
  125003. /* TUNING: Each index lookup yields 20 rows in the table. This
  125004. ** is more than the usual guess of 10 rows, since we have no way
  125005. ** of knowing how selective the index will ultimately be. It would
  125006. ** not be unreasonable to make this value much larger. */
  125007. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  125008. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  125009. pNew->wsFlags = WHERE_AUTO_INDEX;
  125010. pNew->prereq = mPrereq | pTerm->prereqRight;
  125011. rc = whereLoopInsert(pBuilder, pNew);
  125012. }
  125013. }
  125014. }
  125015. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  125016. /* Loop over all indices
  125017. */
  125018. for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
  125019. if( pProbe->pPartIdxWhere!=0
  125020. && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
  125021. testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
  125022. continue; /* Partial index inappropriate for this query */
  125023. }
  125024. rSize = pProbe->aiRowLogEst[0];
  125025. pNew->u.btree.nEq = 0;
  125026. pNew->u.btree.nBtm = 0;
  125027. pNew->u.btree.nTop = 0;
  125028. pNew->nSkip = 0;
  125029. pNew->nLTerm = 0;
  125030. pNew->iSortIdx = 0;
  125031. pNew->rSetup = 0;
  125032. pNew->prereq = mPrereq;
  125033. pNew->nOut = rSize;
  125034. pNew->u.btree.pIndex = pProbe;
  125035. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  125036. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  125037. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  125038. if( pProbe->tnum<=0 ){
  125039. /* Integer primary key index */
  125040. pNew->wsFlags = WHERE_IPK;
  125041. /* Full table scan */
  125042. pNew->iSortIdx = b ? iSortIdx : 0;
  125043. /* TUNING: Cost of full table scan is (N*3.0). */
  125044. pNew->rRun = rSize + 16;
  125045. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  125046. whereLoopOutputAdjust(pWC, pNew, rSize);
  125047. rc = whereLoopInsert(pBuilder, pNew);
  125048. pNew->nOut = rSize;
  125049. if( rc ) break;
  125050. }else{
  125051. Bitmask m;
  125052. if( pProbe->isCovering ){
  125053. pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
  125054. m = 0;
  125055. }else{
  125056. m = pSrc->colUsed & ~columnsInIndex(pProbe);
  125057. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  125058. }
  125059. /* Full scan via index */
  125060. if( b
  125061. || !HasRowid(pTab)
  125062. || pProbe->pPartIdxWhere!=0
  125063. || ( m==0
  125064. && pProbe->bUnordered==0
  125065. && (pProbe->szIdxRow<pTab->szTabRow)
  125066. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  125067. && sqlite3GlobalConfig.bUseCis
  125068. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  125069. )
  125070. ){
  125071. pNew->iSortIdx = b ? iSortIdx : 0;
  125072. /* The cost of visiting the index rows is N*K, where K is
  125073. ** between 1.1 and 3.0, depending on the relative sizes of the
  125074. ** index and table rows. */
  125075. pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
  125076. if( m!=0 ){
  125077. /* If this is a non-covering index scan, add in the cost of
  125078. ** doing table lookups. The cost will be 3x the number of
  125079. ** lookups. Take into account WHERE clause terms that can be
  125080. ** satisfied using just the index, and that do not require a
  125081. ** table lookup. */
  125082. LogEst nLookup = rSize + 16; /* Base cost: N*3 */
  125083. int ii;
  125084. int iCur = pSrc->iCursor;
  125085. WhereClause *pWC2 = &pWInfo->sWC;
  125086. for(ii=0; ii<pWC2->nTerm; ii++){
  125087. WhereTerm *pTerm = &pWC2->a[ii];
  125088. if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
  125089. break;
  125090. }
  125091. /* pTerm can be evaluated using just the index. So reduce
  125092. ** the expected number of table lookups accordingly */
  125093. if( pTerm->truthProb<=0 ){
  125094. nLookup += pTerm->truthProb;
  125095. }else{
  125096. nLookup--;
  125097. if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
  125098. }
  125099. }
  125100. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
  125101. }
  125102. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  125103. whereLoopOutputAdjust(pWC, pNew, rSize);
  125104. rc = whereLoopInsert(pBuilder, pNew);
  125105. pNew->nOut = rSize;
  125106. if( rc ) break;
  125107. }
  125108. }
  125109. pBuilder->bldFlags = 0;
  125110. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  125111. if( pBuilder->bldFlags==SQLITE_BLDF_INDEXED ){
  125112. /* If a non-unique index is used, or if a prefix of the key for
  125113. ** unique index is used (making the index functionally non-unique)
  125114. ** then the sqlite_stat1 data becomes important for scoring the
  125115. ** plan */
  125116. pTab->tabFlags |= TF_StatsUsed;
  125117. }
  125118. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  125119. sqlite3Stat4ProbeFree(pBuilder->pRec);
  125120. pBuilder->nRecValid = 0;
  125121. pBuilder->pRec = 0;
  125122. #endif
  125123. /* If there was an INDEXED BY clause, then only that one index is
  125124. ** considered. */
  125125. if( pSrc->pIBIndex ) break;
  125126. }
  125127. return rc;
  125128. }
  125129. #ifndef SQLITE_OMIT_VIRTUALTABLE
  125130. /*
  125131. ** Argument pIdxInfo is already populated with all constraints that may
  125132. ** be used by the virtual table identified by pBuilder->pNew->iTab. This
  125133. ** function marks a subset of those constraints usable, invokes the
  125134. ** xBestIndex method and adds the returned plan to pBuilder.
  125135. **
  125136. ** A constraint is marked usable if:
  125137. **
  125138. ** * Argument mUsable indicates that its prerequisites are available, and
  125139. **
  125140. ** * It is not one of the operators specified in the mExclude mask passed
  125141. ** as the fourth argument (which in practice is either WO_IN or 0).
  125142. **
  125143. ** Argument mPrereq is a mask of tables that must be scanned before the
  125144. ** virtual table in question. These are added to the plans prerequisites
  125145. ** before it is added to pBuilder.
  125146. **
  125147. ** Output parameter *pbIn is set to true if the plan added to pBuilder
  125148. ** uses one or more WO_IN terms, or false otherwise.
  125149. */
  125150. static int whereLoopAddVirtualOne(
  125151. WhereLoopBuilder *pBuilder,
  125152. Bitmask mPrereq, /* Mask of tables that must be used. */
  125153. Bitmask mUsable, /* Mask of usable tables */
  125154. u16 mExclude, /* Exclude terms using these operators */
  125155. sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
  125156. u16 mNoOmit, /* Do not omit these constraints */
  125157. int *pbIn /* OUT: True if plan uses an IN(...) op */
  125158. ){
  125159. WhereClause *pWC = pBuilder->pWC;
  125160. struct sqlite3_index_constraint *pIdxCons;
  125161. struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
  125162. int i;
  125163. int mxTerm;
  125164. int rc = SQLITE_OK;
  125165. WhereLoop *pNew = pBuilder->pNew;
  125166. Parse *pParse = pBuilder->pWInfo->pParse;
  125167. struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
  125168. int nConstraint = pIdxInfo->nConstraint;
  125169. assert( (mUsable & mPrereq)==mPrereq );
  125170. *pbIn = 0;
  125171. pNew->prereq = mPrereq;
  125172. /* Set the usable flag on the subset of constraints identified by
  125173. ** arguments mUsable and mExclude. */
  125174. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  125175. for(i=0; i<nConstraint; i++, pIdxCons++){
  125176. WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
  125177. pIdxCons->usable = 0;
  125178. if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
  125179. && (pTerm->eOperator & mExclude)==0
  125180. ){
  125181. pIdxCons->usable = 1;
  125182. }
  125183. }
  125184. /* Initialize the output fields of the sqlite3_index_info structure */
  125185. memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
  125186. assert( pIdxInfo->needToFreeIdxStr==0 );
  125187. pIdxInfo->idxStr = 0;
  125188. pIdxInfo->idxNum = 0;
  125189. pIdxInfo->orderByConsumed = 0;
  125190. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  125191. pIdxInfo->estimatedRows = 25;
  125192. pIdxInfo->idxFlags = 0;
  125193. pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
  125194. /* Invoke the virtual table xBestIndex() method */
  125195. rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
  125196. if( rc ) return rc;
  125197. mxTerm = -1;
  125198. assert( pNew->nLSlot>=nConstraint );
  125199. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  125200. pNew->u.vtab.omitMask = 0;
  125201. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  125202. for(i=0; i<nConstraint; i++, pIdxCons++){
  125203. int iTerm;
  125204. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  125205. WhereTerm *pTerm;
  125206. int j = pIdxCons->iTermOffset;
  125207. if( iTerm>=nConstraint
  125208. || j<0
  125209. || j>=pWC->nTerm
  125210. || pNew->aLTerm[iTerm]!=0
  125211. || pIdxCons->usable==0
  125212. ){
  125213. rc = SQLITE_ERROR;
  125214. sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
  125215. return rc;
  125216. }
  125217. testcase( iTerm==nConstraint-1 );
  125218. testcase( j==0 );
  125219. testcase( j==pWC->nTerm-1 );
  125220. pTerm = &pWC->a[j];
  125221. pNew->prereq |= pTerm->prereqRight;
  125222. assert( iTerm<pNew->nLSlot );
  125223. pNew->aLTerm[iTerm] = pTerm;
  125224. if( iTerm>mxTerm ) mxTerm = iTerm;
  125225. testcase( iTerm==15 );
  125226. testcase( iTerm==16 );
  125227. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  125228. if( (pTerm->eOperator & WO_IN)!=0 ){
  125229. /* A virtual table that is constrained by an IN clause may not
  125230. ** consume the ORDER BY clause because (1) the order of IN terms
  125231. ** is not necessarily related to the order of output terms and
  125232. ** (2) Multiple outputs from a single IN value will not merge
  125233. ** together. */
  125234. pIdxInfo->orderByConsumed = 0;
  125235. pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
  125236. *pbIn = 1; assert( (mExclude & WO_IN)==0 );
  125237. }
  125238. }
  125239. }
  125240. pNew->u.vtab.omitMask &= ~mNoOmit;
  125241. pNew->nLTerm = mxTerm+1;
  125242. assert( pNew->nLTerm<=pNew->nLSlot );
  125243. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  125244. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  125245. pIdxInfo->needToFreeIdxStr = 0;
  125246. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  125247. pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
  125248. pIdxInfo->nOrderBy : 0);
  125249. pNew->rSetup = 0;
  125250. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  125251. pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
  125252. /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
  125253. ** that the scan will visit at most one row. Clear it otherwise. */
  125254. if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
  125255. pNew->wsFlags |= WHERE_ONEROW;
  125256. }else{
  125257. pNew->wsFlags &= ~WHERE_ONEROW;
  125258. }
  125259. rc = whereLoopInsert(pBuilder, pNew);
  125260. if( pNew->u.vtab.needFree ){
  125261. sqlite3_free(pNew->u.vtab.idxStr);
  125262. pNew->u.vtab.needFree = 0;
  125263. }
  125264. WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
  125265. *pbIn, (sqlite3_uint64)mPrereq,
  125266. (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
  125267. return rc;
  125268. }
  125269. /*
  125270. ** Add all WhereLoop objects for a table of the join identified by
  125271. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  125272. **
  125273. ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
  125274. ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
  125275. ** entries that occur before the virtual table in the FROM clause and are
  125276. ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
  125277. ** mUnusable mask contains all FROM clause entries that occur after the
  125278. ** virtual table and are separated from it by at least one LEFT or
  125279. ** CROSS JOIN.
  125280. **
  125281. ** For example, if the query were:
  125282. **
  125283. ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
  125284. **
  125285. ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
  125286. **
  125287. ** All the tables in mPrereq must be scanned before the current virtual
  125288. ** table. So any terms for which all prerequisites are satisfied by
  125289. ** mPrereq may be specified as "usable" in all calls to xBestIndex.
  125290. ** Conversely, all tables in mUnusable must be scanned after the current
  125291. ** virtual table, so any terms for which the prerequisites overlap with
  125292. ** mUnusable should always be configured as "not-usable" for xBestIndex.
  125293. */
  125294. static int whereLoopAddVirtual(
  125295. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  125296. Bitmask mPrereq, /* Tables that must be scanned before this one */
  125297. Bitmask mUnusable /* Tables that must be scanned after this one */
  125298. ){
  125299. int rc = SQLITE_OK; /* Return code */
  125300. WhereInfo *pWInfo; /* WHERE analysis context */
  125301. Parse *pParse; /* The parsing context */
  125302. WhereClause *pWC; /* The WHERE clause */
  125303. struct SrcList_item *pSrc; /* The FROM clause term to search */
  125304. sqlite3_index_info *p; /* Object to pass to xBestIndex() */
  125305. int nConstraint; /* Number of constraints in p */
  125306. int bIn; /* True if plan uses IN(...) operator */
  125307. WhereLoop *pNew;
  125308. Bitmask mBest; /* Tables used by best possible plan */
  125309. u16 mNoOmit;
  125310. assert( (mPrereq & mUnusable)==0 );
  125311. pWInfo = pBuilder->pWInfo;
  125312. pParse = pWInfo->pParse;
  125313. pWC = pBuilder->pWC;
  125314. pNew = pBuilder->pNew;
  125315. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  125316. assert( IsVirtual(pSrc->pTab) );
  125317. p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy,
  125318. &mNoOmit);
  125319. if( p==0 ) return SQLITE_NOMEM_BKPT;
  125320. pNew->rSetup = 0;
  125321. pNew->wsFlags = WHERE_VIRTUALTABLE;
  125322. pNew->nLTerm = 0;
  125323. pNew->u.vtab.needFree = 0;
  125324. nConstraint = p->nConstraint;
  125325. if( whereLoopResize(pParse->db, pNew, nConstraint) ){
  125326. sqlite3DbFree(pParse->db, p);
  125327. return SQLITE_NOMEM_BKPT;
  125328. }
  125329. /* First call xBestIndex() with all constraints usable. */
  125330. WHERETRACE(0x40, (" VirtualOne: all usable\n"));
  125331. rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
  125332. /* If the call to xBestIndex() with all terms enabled produced a plan
  125333. ** that does not require any source tables (IOW: a plan with mBest==0),
  125334. ** then there is no point in making any further calls to xBestIndex()
  125335. ** since they will all return the same result (if the xBestIndex()
  125336. ** implementation is sane). */
  125337. if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
  125338. int seenZero = 0; /* True if a plan with no prereqs seen */
  125339. int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
  125340. Bitmask mPrev = 0;
  125341. Bitmask mBestNoIn = 0;
  125342. /* If the plan produced by the earlier call uses an IN(...) term, call
  125343. ** xBestIndex again, this time with IN(...) terms disabled. */
  125344. if( bIn ){
  125345. WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n"));
  125346. rc = whereLoopAddVirtualOne(
  125347. pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
  125348. assert( bIn==0 );
  125349. mBestNoIn = pNew->prereq & ~mPrereq;
  125350. if( mBestNoIn==0 ){
  125351. seenZero = 1;
  125352. seenZeroNoIN = 1;
  125353. }
  125354. }
  125355. /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
  125356. ** in the set of terms that apply to the current virtual table. */
  125357. while( rc==SQLITE_OK ){
  125358. int i;
  125359. Bitmask mNext = ALLBITS;
  125360. assert( mNext>0 );
  125361. for(i=0; i<nConstraint; i++){
  125362. Bitmask mThis = (
  125363. pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
  125364. );
  125365. if( mThis>mPrev && mThis<mNext ) mNext = mThis;
  125366. }
  125367. mPrev = mNext;
  125368. if( mNext==ALLBITS ) break;
  125369. if( mNext==mBest || mNext==mBestNoIn ) continue;
  125370. WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
  125371. (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
  125372. rc = whereLoopAddVirtualOne(
  125373. pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
  125374. if( pNew->prereq==mPrereq ){
  125375. seenZero = 1;
  125376. if( bIn==0 ) seenZeroNoIN = 1;
  125377. }
  125378. }
  125379. /* If the calls to xBestIndex() in the above loop did not find a plan
  125380. ** that requires no source tables at all (i.e. one guaranteed to be
  125381. ** usable), make a call here with all source tables disabled */
  125382. if( rc==SQLITE_OK && seenZero==0 ){
  125383. WHERETRACE(0x40, (" VirtualOne: all disabled\n"));
  125384. rc = whereLoopAddVirtualOne(
  125385. pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
  125386. if( bIn==0 ) seenZeroNoIN = 1;
  125387. }
  125388. /* If the calls to xBestIndex() have so far failed to find a plan
  125389. ** that requires no source tables at all and does not use an IN(...)
  125390. ** operator, make a final call to obtain one here. */
  125391. if( rc==SQLITE_OK && seenZeroNoIN==0 ){
  125392. WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n"));
  125393. rc = whereLoopAddVirtualOne(
  125394. pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
  125395. }
  125396. }
  125397. if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
  125398. sqlite3DbFreeNN(pParse->db, p);
  125399. return rc;
  125400. }
  125401. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  125402. /*
  125403. ** Add WhereLoop entries to handle OR terms. This works for either
  125404. ** btrees or virtual tables.
  125405. */
  125406. static int whereLoopAddOr(
  125407. WhereLoopBuilder *pBuilder,
  125408. Bitmask mPrereq,
  125409. Bitmask mUnusable
  125410. ){
  125411. WhereInfo *pWInfo = pBuilder->pWInfo;
  125412. WhereClause *pWC;
  125413. WhereLoop *pNew;
  125414. WhereTerm *pTerm, *pWCEnd;
  125415. int rc = SQLITE_OK;
  125416. int iCur;
  125417. WhereClause tempWC;
  125418. WhereLoopBuilder sSubBuild;
  125419. WhereOrSet sSum, sCur;
  125420. struct SrcList_item *pItem;
  125421. pWC = pBuilder->pWC;
  125422. pWCEnd = pWC->a + pWC->nTerm;
  125423. pNew = pBuilder->pNew;
  125424. memset(&sSum, 0, sizeof(sSum));
  125425. pItem = pWInfo->pTabList->a + pNew->iTab;
  125426. iCur = pItem->iCursor;
  125427. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  125428. if( (pTerm->eOperator & WO_OR)!=0
  125429. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  125430. ){
  125431. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  125432. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  125433. WhereTerm *pOrTerm;
  125434. int once = 1;
  125435. int i, j;
  125436. sSubBuild = *pBuilder;
  125437. sSubBuild.pOrderBy = 0;
  125438. sSubBuild.pOrSet = &sCur;
  125439. WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
  125440. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  125441. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  125442. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  125443. }else if( pOrTerm->leftCursor==iCur ){
  125444. tempWC.pWInfo = pWC->pWInfo;
  125445. tempWC.pOuter = pWC;
  125446. tempWC.op = TK_AND;
  125447. tempWC.nTerm = 1;
  125448. tempWC.a = pOrTerm;
  125449. sSubBuild.pWC = &tempWC;
  125450. }else{
  125451. continue;
  125452. }
  125453. sCur.n = 0;
  125454. #ifdef WHERETRACE_ENABLED
  125455. WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
  125456. (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
  125457. if( sqlite3WhereTrace & 0x400 ){
  125458. sqlite3WhereClausePrint(sSubBuild.pWC);
  125459. }
  125460. #endif
  125461. #ifndef SQLITE_OMIT_VIRTUALTABLE
  125462. if( IsVirtual(pItem->pTab) ){
  125463. rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
  125464. }else
  125465. #endif
  125466. {
  125467. rc = whereLoopAddBtree(&sSubBuild, mPrereq);
  125468. }
  125469. if( rc==SQLITE_OK ){
  125470. rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
  125471. }
  125472. assert( rc==SQLITE_OK || sCur.n==0 );
  125473. if( sCur.n==0 ){
  125474. sSum.n = 0;
  125475. break;
  125476. }else if( once ){
  125477. whereOrMove(&sSum, &sCur);
  125478. once = 0;
  125479. }else{
  125480. WhereOrSet sPrev;
  125481. whereOrMove(&sPrev, &sSum);
  125482. sSum.n = 0;
  125483. for(i=0; i<sPrev.n; i++){
  125484. for(j=0; j<sCur.n; j++){
  125485. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  125486. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  125487. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  125488. }
  125489. }
  125490. }
  125491. }
  125492. pNew->nLTerm = 1;
  125493. pNew->aLTerm[0] = pTerm;
  125494. pNew->wsFlags = WHERE_MULTI_OR;
  125495. pNew->rSetup = 0;
  125496. pNew->iSortIdx = 0;
  125497. memset(&pNew->u, 0, sizeof(pNew->u));
  125498. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  125499. /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
  125500. ** of all sub-scans required by the OR-scan. However, due to rounding
  125501. ** errors, it may be that the cost of the OR-scan is equal to its
  125502. ** most expensive sub-scan. Add the smallest possible penalty
  125503. ** (equivalent to multiplying the cost by 1.07) to ensure that
  125504. ** this does not happen. Otherwise, for WHERE clauses such as the
  125505. ** following where there is an index on "y":
  125506. **
  125507. ** WHERE likelihood(x=?, 0.99) OR y=?
  125508. **
  125509. ** the planner may elect to "OR" together a full-table scan and an
  125510. ** index lookup. And other similarly odd results. */
  125511. pNew->rRun = sSum.a[i].rRun + 1;
  125512. pNew->nOut = sSum.a[i].nOut;
  125513. pNew->prereq = sSum.a[i].prereq;
  125514. rc = whereLoopInsert(pBuilder, pNew);
  125515. }
  125516. WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
  125517. }
  125518. }
  125519. return rc;
  125520. }
  125521. /*
  125522. ** Add all WhereLoop objects for all tables
  125523. */
  125524. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  125525. WhereInfo *pWInfo = pBuilder->pWInfo;
  125526. Bitmask mPrereq = 0;
  125527. Bitmask mPrior = 0;
  125528. int iTab;
  125529. SrcList *pTabList = pWInfo->pTabList;
  125530. struct SrcList_item *pItem;
  125531. struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
  125532. sqlite3 *db = pWInfo->pParse->db;
  125533. int rc = SQLITE_OK;
  125534. WhereLoop *pNew;
  125535. u8 priorJointype = 0;
  125536. /* Loop over the tables in the join, from left to right */
  125537. pNew = pBuilder->pNew;
  125538. whereLoopInit(pNew);
  125539. for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
  125540. Bitmask mUnusable = 0;
  125541. pNew->iTab = iTab;
  125542. pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
  125543. if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
  125544. /* This condition is true when pItem is the FROM clause term on the
  125545. ** right-hand-side of a LEFT or CROSS JOIN. */
  125546. mPrereq = mPrior;
  125547. }
  125548. priorJointype = pItem->fg.jointype;
  125549. #ifndef SQLITE_OMIT_VIRTUALTABLE
  125550. if( IsVirtual(pItem->pTab) ){
  125551. struct SrcList_item *p;
  125552. for(p=&pItem[1]; p<pEnd; p++){
  125553. if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
  125554. mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
  125555. }
  125556. }
  125557. rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
  125558. }else
  125559. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  125560. {
  125561. rc = whereLoopAddBtree(pBuilder, mPrereq);
  125562. }
  125563. if( rc==SQLITE_OK ){
  125564. rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
  125565. }
  125566. mPrior |= pNew->maskSelf;
  125567. if( rc || db->mallocFailed ) break;
  125568. }
  125569. whereLoopClear(db, pNew);
  125570. return rc;
  125571. }
  125572. /*
  125573. ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
  125574. ** parameters) to see if it outputs rows in the requested ORDER BY
  125575. ** (or GROUP BY) without requiring a separate sort operation. Return N:
  125576. **
  125577. ** N>0: N terms of the ORDER BY clause are satisfied
  125578. ** N==0: No terms of the ORDER BY clause are satisfied
  125579. ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
  125580. **
  125581. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  125582. ** strict. With GROUP BY and DISTINCT the only requirement is that
  125583. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  125584. ** and DISTINCT do not require rows to appear in any particular order as long
  125585. ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
  125586. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  125587. ** pOrderBy terms must be matched in strict left-to-right order.
  125588. */
  125589. static i8 wherePathSatisfiesOrderBy(
  125590. WhereInfo *pWInfo, /* The WHERE clause */
  125591. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  125592. WherePath *pPath, /* The WherePath to check */
  125593. u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
  125594. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  125595. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  125596. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  125597. ){
  125598. u8 revSet; /* True if rev is known */
  125599. u8 rev; /* Composite sort order */
  125600. u8 revIdx; /* Index sort order */
  125601. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  125602. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  125603. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  125604. u16 eqOpMask; /* Allowed equality operators */
  125605. u16 nKeyCol; /* Number of key columns in pIndex */
  125606. u16 nColumn; /* Total number of ordered columns in the index */
  125607. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  125608. int iLoop; /* Index of WhereLoop in pPath being processed */
  125609. int i, j; /* Loop counters */
  125610. int iCur; /* Cursor number for current WhereLoop */
  125611. int iColumn; /* A column number within table iCur */
  125612. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  125613. WhereTerm *pTerm; /* A single term of the WHERE clause */
  125614. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  125615. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  125616. Index *pIndex; /* The index associated with pLoop */
  125617. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  125618. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  125619. Bitmask obDone; /* Mask of all ORDER BY terms */
  125620. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  125621. Bitmask ready; /* Mask of inner loops */
  125622. /*
  125623. ** We say the WhereLoop is "one-row" if it generates no more than one
  125624. ** row of output. A WhereLoop is one-row if all of the following are true:
  125625. ** (a) All index columns match with WHERE_COLUMN_EQ.
  125626. ** (b) The index is unique
  125627. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  125628. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  125629. **
  125630. ** We say the WhereLoop is "order-distinct" if the set of columns from
  125631. ** that WhereLoop that are in the ORDER BY clause are different for every
  125632. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  125633. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  125634. ** is not order-distinct. To be order-distinct is not quite the same as being
  125635. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  125636. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  125637. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  125638. **
  125639. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  125640. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  125641. ** automatically order-distinct.
  125642. */
  125643. assert( pOrderBy!=0 );
  125644. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  125645. nOrderBy = pOrderBy->nExpr;
  125646. testcase( nOrderBy==BMS-1 );
  125647. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  125648. isOrderDistinct = 1;
  125649. obDone = MASKBIT(nOrderBy)-1;
  125650. orderDistinctMask = 0;
  125651. ready = 0;
  125652. eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
  125653. if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
  125654. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  125655. if( iLoop>0 ) ready |= pLoop->maskSelf;
  125656. if( iLoop<nLoop ){
  125657. pLoop = pPath->aLoop[iLoop];
  125658. if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
  125659. }else{
  125660. pLoop = pLast;
  125661. }
  125662. if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
  125663. if( pLoop->u.vtab.isOrdered ) obSat = obDone;
  125664. break;
  125665. }else{
  125666. pLoop->u.btree.nIdxCol = 0;
  125667. }
  125668. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  125669. /* Mark off any ORDER BY term X that is a column in the table of
  125670. ** the current loop for which there is term in the WHERE
  125671. ** clause of the form X IS NULL or X=? that reference only outer
  125672. ** loops.
  125673. */
  125674. for(i=0; i<nOrderBy; i++){
  125675. if( MASKBIT(i) & obSat ) continue;
  125676. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  125677. if( pOBExpr->op!=TK_COLUMN ) continue;
  125678. if( pOBExpr->iTable!=iCur ) continue;
  125679. pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  125680. ~ready, eqOpMask, 0);
  125681. if( pTerm==0 ) continue;
  125682. if( pTerm->eOperator==WO_IN ){
  125683. /* IN terms are only valid for sorting in the ORDER BY LIMIT
  125684. ** optimization, and then only if they are actually used
  125685. ** by the query plan */
  125686. assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
  125687. for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
  125688. if( j>=pLoop->nLTerm ) continue;
  125689. }
  125690. if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
  125691. const char *z1, *z2;
  125692. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  125693. if( !pColl ) pColl = db->pDfltColl;
  125694. z1 = pColl->zName;
  125695. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
  125696. if( !pColl ) pColl = db->pDfltColl;
  125697. z2 = pColl->zName;
  125698. if( sqlite3StrICmp(z1, z2)!=0 ) continue;
  125699. testcase( pTerm->pExpr->op==TK_IS );
  125700. }
  125701. obSat |= MASKBIT(i);
  125702. }
  125703. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  125704. if( pLoop->wsFlags & WHERE_IPK ){
  125705. pIndex = 0;
  125706. nKeyCol = 0;
  125707. nColumn = 1;
  125708. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  125709. return 0;
  125710. }else{
  125711. nKeyCol = pIndex->nKeyCol;
  125712. nColumn = pIndex->nColumn;
  125713. assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
  125714. assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
  125715. || !HasRowid(pIndex->pTable));
  125716. isOrderDistinct = IsUniqueIndex(pIndex);
  125717. }
  125718. /* Loop through all columns of the index and deal with the ones
  125719. ** that are not constrained by == or IN.
  125720. */
  125721. rev = revSet = 0;
  125722. distinctColumns = 0;
  125723. for(j=0; j<nColumn; j++){
  125724. u8 bOnce = 1; /* True to run the ORDER BY search loop */
  125725. assert( j>=pLoop->u.btree.nEq
  125726. || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
  125727. );
  125728. if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
  125729. u16 eOp = pLoop->aLTerm[j]->eOperator;
  125730. /* Skip over == and IS and ISNULL terms. (Also skip IN terms when
  125731. ** doing WHERE_ORDERBY_LIMIT processing).
  125732. **
  125733. ** If the current term is a column of an ((?,?) IN (SELECT...))
  125734. ** expression for which the SELECT returns more than one column,
  125735. ** check that it is the only column used by this loop. Otherwise,
  125736. ** if it is one of two or more, none of the columns can be
  125737. ** considered to match an ORDER BY term. */
  125738. if( (eOp & eqOpMask)!=0 ){
  125739. if( eOp & WO_ISNULL ){
  125740. testcase( isOrderDistinct );
  125741. isOrderDistinct = 0;
  125742. }
  125743. continue;
  125744. }else if( ALWAYS(eOp & WO_IN) ){
  125745. /* ALWAYS() justification: eOp is an equality operator due to the
  125746. ** j<pLoop->u.btree.nEq constraint above. Any equality other
  125747. ** than WO_IN is captured by the previous "if". So this one
  125748. ** always has to be WO_IN. */
  125749. Expr *pX = pLoop->aLTerm[j]->pExpr;
  125750. for(i=j+1; i<pLoop->u.btree.nEq; i++){
  125751. if( pLoop->aLTerm[i]->pExpr==pX ){
  125752. assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
  125753. bOnce = 0;
  125754. break;
  125755. }
  125756. }
  125757. }
  125758. }
  125759. /* Get the column number in the table (iColumn) and sort order
  125760. ** (revIdx) for the j-th column of the index.
  125761. */
  125762. if( pIndex ){
  125763. iColumn = pIndex->aiColumn[j];
  125764. revIdx = pIndex->aSortOrder[j];
  125765. if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
  125766. }else{
  125767. iColumn = XN_ROWID;
  125768. revIdx = 0;
  125769. }
  125770. /* An unconstrained column that might be NULL means that this
  125771. ** WhereLoop is not well-ordered
  125772. */
  125773. if( isOrderDistinct
  125774. && iColumn>=0
  125775. && j>=pLoop->u.btree.nEq
  125776. && pIndex->pTable->aCol[iColumn].notNull==0
  125777. ){
  125778. isOrderDistinct = 0;
  125779. }
  125780. /* Find the ORDER BY term that corresponds to the j-th column
  125781. ** of the index and mark that ORDER BY term off
  125782. */
  125783. isMatch = 0;
  125784. for(i=0; bOnce && i<nOrderBy; i++){
  125785. if( MASKBIT(i) & obSat ) continue;
  125786. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  125787. testcase( wctrlFlags & WHERE_GROUPBY );
  125788. testcase( wctrlFlags & WHERE_DISTINCTBY );
  125789. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  125790. if( iColumn>=(-1) ){
  125791. if( pOBExpr->op!=TK_COLUMN ) continue;
  125792. if( pOBExpr->iTable!=iCur ) continue;
  125793. if( pOBExpr->iColumn!=iColumn ) continue;
  125794. }else{
  125795. if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){
  125796. continue;
  125797. }
  125798. }
  125799. if( iColumn>=0 ){
  125800. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  125801. if( !pColl ) pColl = db->pDfltColl;
  125802. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  125803. }
  125804. pLoop->u.btree.nIdxCol = j+1;
  125805. isMatch = 1;
  125806. break;
  125807. }
  125808. if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
  125809. /* Make sure the sort order is compatible in an ORDER BY clause.
  125810. ** Sort order is irrelevant for a GROUP BY clause. */
  125811. if( revSet ){
  125812. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
  125813. }else{
  125814. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  125815. if( rev ) *pRevMask |= MASKBIT(iLoop);
  125816. revSet = 1;
  125817. }
  125818. }
  125819. if( isMatch ){
  125820. if( iColumn==XN_ROWID ){
  125821. testcase( distinctColumns==0 );
  125822. distinctColumns = 1;
  125823. }
  125824. obSat |= MASKBIT(i);
  125825. }else{
  125826. /* No match found */
  125827. if( j==0 || j<nKeyCol ){
  125828. testcase( isOrderDistinct!=0 );
  125829. isOrderDistinct = 0;
  125830. }
  125831. break;
  125832. }
  125833. } /* end Loop over all index columns */
  125834. if( distinctColumns ){
  125835. testcase( isOrderDistinct==0 );
  125836. isOrderDistinct = 1;
  125837. }
  125838. } /* end-if not one-row */
  125839. /* Mark off any other ORDER BY terms that reference pLoop */
  125840. if( isOrderDistinct ){
  125841. orderDistinctMask |= pLoop->maskSelf;
  125842. for(i=0; i<nOrderBy; i++){
  125843. Expr *p;
  125844. Bitmask mTerm;
  125845. if( MASKBIT(i) & obSat ) continue;
  125846. p = pOrderBy->a[i].pExpr;
  125847. mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
  125848. if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
  125849. if( (mTerm&~orderDistinctMask)==0 ){
  125850. obSat |= MASKBIT(i);
  125851. }
  125852. }
  125853. }
  125854. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  125855. if( obSat==obDone ) return (i8)nOrderBy;
  125856. if( !isOrderDistinct ){
  125857. for(i=nOrderBy-1; i>0; i--){
  125858. Bitmask m = MASKBIT(i) - 1;
  125859. if( (obSat&m)==m ) return i;
  125860. }
  125861. return 0;
  125862. }
  125863. return -1;
  125864. }
  125865. /*
  125866. ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
  125867. ** the planner assumes that the specified pOrderBy list is actually a GROUP
  125868. ** BY clause - and so any order that groups rows as required satisfies the
  125869. ** request.
  125870. **
  125871. ** Normally, in this case it is not possible for the caller to determine
  125872. ** whether or not the rows are really being delivered in sorted order, or
  125873. ** just in some other order that provides the required grouping. However,
  125874. ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
  125875. ** this function may be called on the returned WhereInfo object. It returns
  125876. ** true if the rows really will be sorted in the specified order, or false
  125877. ** otherwise.
  125878. **
  125879. ** For example, assuming:
  125880. **
  125881. ** CREATE INDEX i1 ON t1(x, Y);
  125882. **
  125883. ** then
  125884. **
  125885. ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
  125886. ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
  125887. */
  125888. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
  125889. assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
  125890. assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
  125891. return pWInfo->sorted;
  125892. }
  125893. #ifdef WHERETRACE_ENABLED
  125894. /* For debugging use only: */
  125895. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  125896. static char zName[65];
  125897. int i;
  125898. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  125899. if( pLast ) zName[i++] = pLast->cId;
  125900. zName[i] = 0;
  125901. return zName;
  125902. }
  125903. #endif
  125904. /*
  125905. ** Return the cost of sorting nRow rows, assuming that the keys have
  125906. ** nOrderby columns and that the first nSorted columns are already in
  125907. ** order.
  125908. */
  125909. static LogEst whereSortingCost(
  125910. WhereInfo *pWInfo,
  125911. LogEst nRow,
  125912. int nOrderBy,
  125913. int nSorted
  125914. ){
  125915. /* TUNING: Estimated cost of a full external sort, where N is
  125916. ** the number of rows to sort is:
  125917. **
  125918. ** cost = (3.0 * N * log(N)).
  125919. **
  125920. ** Or, if the order-by clause has X terms but only the last Y
  125921. ** terms are out of order, then block-sorting will reduce the
  125922. ** sorting cost to:
  125923. **
  125924. ** cost = (3.0 * N * log(N)) * (Y/X)
  125925. **
  125926. ** The (Y/X) term is implemented using stack variable rScale
  125927. ** below. */
  125928. LogEst rScale, rSortCost;
  125929. assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
  125930. rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
  125931. rSortCost = nRow + rScale + 16;
  125932. /* Multiple by log(M) where M is the number of output rows.
  125933. ** Use the LIMIT for M if it is smaller */
  125934. if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
  125935. nRow = pWInfo->iLimit;
  125936. }
  125937. rSortCost += estLog(nRow);
  125938. return rSortCost;
  125939. }
  125940. /*
  125941. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  125942. ** attempts to find the lowest cost path that visits each WhereLoop
  125943. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  125944. **
  125945. ** Assume that the total number of output rows that will need to be sorted
  125946. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  125947. ** costs if nRowEst==0.
  125948. **
  125949. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  125950. ** error occurs.
  125951. */
  125952. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  125953. int mxChoice; /* Maximum number of simultaneous paths tracked */
  125954. int nLoop; /* Number of terms in the join */
  125955. Parse *pParse; /* Parsing context */
  125956. sqlite3 *db; /* The database connection */
  125957. int iLoop; /* Loop counter over the terms of the join */
  125958. int ii, jj; /* Loop counters */
  125959. int mxI = 0; /* Index of next entry to replace */
  125960. int nOrderBy; /* Number of ORDER BY clause terms */
  125961. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  125962. LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
  125963. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  125964. WherePath *aFrom; /* All nFrom paths at the previous level */
  125965. WherePath *aTo; /* The nTo best paths at the current level */
  125966. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  125967. WherePath *pTo; /* An element of aTo[] that we are working on */
  125968. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  125969. WhereLoop **pX; /* Used to divy up the pSpace memory */
  125970. LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
  125971. char *pSpace; /* Temporary memory used by this routine */
  125972. int nSpace; /* Bytes of space allocated at pSpace */
  125973. pParse = pWInfo->pParse;
  125974. db = pParse->db;
  125975. nLoop = pWInfo->nLevel;
  125976. /* TUNING: For simple queries, only the best path is tracked.
  125977. ** For 2-way joins, the 5 best paths are followed.
  125978. ** For joins of 3 or more tables, track the 10 best paths */
  125979. mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
  125980. assert( nLoop<=pWInfo->pTabList->nSrc );
  125981. WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
  125982. /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
  125983. ** case the purpose of this call is to estimate the number of rows returned
  125984. ** by the overall query. Once this estimate has been obtained, the caller
  125985. ** will invoke this function a second time, passing the estimate as the
  125986. ** nRowEst parameter. */
  125987. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  125988. nOrderBy = 0;
  125989. }else{
  125990. nOrderBy = pWInfo->pOrderBy->nExpr;
  125991. }
  125992. /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
  125993. nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  125994. nSpace += sizeof(LogEst) * nOrderBy;
  125995. pSpace = sqlite3DbMallocRawNN(db, nSpace);
  125996. if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
  125997. aTo = (WherePath*)pSpace;
  125998. aFrom = aTo+mxChoice;
  125999. memset(aFrom, 0, sizeof(aFrom[0]));
  126000. pX = (WhereLoop**)(aFrom+mxChoice);
  126001. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  126002. pFrom->aLoop = pX;
  126003. }
  126004. if( nOrderBy ){
  126005. /* If there is an ORDER BY clause and it is not being ignored, set up
  126006. ** space for the aSortCost[] array. Each element of the aSortCost array
  126007. ** is either zero - meaning it has not yet been initialized - or the
  126008. ** cost of sorting nRowEst rows of data where the first X terms of
  126009. ** the ORDER BY clause are already in order, where X is the array
  126010. ** index. */
  126011. aSortCost = (LogEst*)pX;
  126012. memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
  126013. }
  126014. assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
  126015. assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
  126016. /* Seed the search with a single WherePath containing zero WhereLoops.
  126017. **
  126018. ** TUNING: Do not let the number of iterations go above 28. If the cost
  126019. ** of computing an automatic index is not paid back within the first 28
  126020. ** rows, then do not use the automatic index. */
  126021. aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
  126022. nFrom = 1;
  126023. assert( aFrom[0].isOrdered==0 );
  126024. if( nOrderBy ){
  126025. /* If nLoop is zero, then there are no FROM terms in the query. Since
  126026. ** in this case the query may return a maximum of one row, the results
  126027. ** are already in the requested order. Set isOrdered to nOrderBy to
  126028. ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
  126029. ** -1, indicating that the result set may or may not be ordered,
  126030. ** depending on the loops added to the current plan. */
  126031. aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
  126032. }
  126033. /* Compute successively longer WherePaths using the previous generation
  126034. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  126035. ** best paths at each generation */
  126036. for(iLoop=0; iLoop<nLoop; iLoop++){
  126037. nTo = 0;
  126038. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  126039. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  126040. LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
  126041. LogEst rCost; /* Cost of path (pFrom+pWLoop) */
  126042. LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
  126043. i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
  126044. Bitmask maskNew; /* Mask of src visited by (..) */
  126045. Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
  126046. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  126047. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  126048. if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){
  126049. /* Do not use an automatic index if the this loop is expected
  126050. ** to run less than 2 times. */
  126051. assert( 10==sqlite3LogEst(2) );
  126052. continue;
  126053. }
  126054. /* At this point, pWLoop is a candidate to be the next loop.
  126055. ** Compute its cost */
  126056. rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  126057. rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
  126058. nOut = pFrom->nRow + pWLoop->nOut;
  126059. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  126060. if( isOrdered<0 ){
  126061. isOrdered = wherePathSatisfiesOrderBy(pWInfo,
  126062. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  126063. iLoop, pWLoop, &revMask);
  126064. }else{
  126065. revMask = pFrom->revLoop;
  126066. }
  126067. if( isOrdered>=0 && isOrdered<nOrderBy ){
  126068. if( aSortCost[isOrdered]==0 ){
  126069. aSortCost[isOrdered] = whereSortingCost(
  126070. pWInfo, nRowEst, nOrderBy, isOrdered
  126071. );
  126072. }
  126073. rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
  126074. WHERETRACE(0x002,
  126075. ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
  126076. aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
  126077. rUnsorted, rCost));
  126078. }else{
  126079. rCost = rUnsorted;
  126080. }
  126081. /* Check to see if pWLoop should be added to the set of
  126082. ** mxChoice best-so-far paths.
  126083. **
  126084. ** First look for an existing path among best-so-far paths
  126085. ** that covers the same set of loops and has the same isOrdered
  126086. ** setting as the current path candidate.
  126087. **
  126088. ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
  126089. ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
  126090. ** of legal values for isOrdered, -1..64.
  126091. */
  126092. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  126093. if( pTo->maskLoop==maskNew
  126094. && ((pTo->isOrdered^isOrdered)&0x80)==0
  126095. ){
  126096. testcase( jj==nTo-1 );
  126097. break;
  126098. }
  126099. }
  126100. if( jj>=nTo ){
  126101. /* None of the existing best-so-far paths match the candidate. */
  126102. if( nTo>=mxChoice
  126103. && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
  126104. ){
  126105. /* The current candidate is no better than any of the mxChoice
  126106. ** paths currently in the best-so-far buffer. So discard
  126107. ** this candidate as not viable. */
  126108. #ifdef WHERETRACE_ENABLED /* 0x4 */
  126109. if( sqlite3WhereTrace&0x4 ){
  126110. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
  126111. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  126112. isOrdered>=0 ? isOrdered+'0' : '?');
  126113. }
  126114. #endif
  126115. continue;
  126116. }
  126117. /* If we reach this points it means that the new candidate path
  126118. ** needs to be added to the set of best-so-far paths. */
  126119. if( nTo<mxChoice ){
  126120. /* Increase the size of the aTo set by one */
  126121. jj = nTo++;
  126122. }else{
  126123. /* New path replaces the prior worst to keep count below mxChoice */
  126124. jj = mxI;
  126125. }
  126126. pTo = &aTo[jj];
  126127. #ifdef WHERETRACE_ENABLED /* 0x4 */
  126128. if( sqlite3WhereTrace&0x4 ){
  126129. sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
  126130. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  126131. isOrdered>=0 ? isOrdered+'0' : '?');
  126132. }
  126133. #endif
  126134. }else{
  126135. /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
  126136. ** same set of loops and has the sam isOrdered setting as the
  126137. ** candidate path. Check to see if the candidate should replace
  126138. ** pTo or if the candidate should be skipped */
  126139. if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
  126140. #ifdef WHERETRACE_ENABLED /* 0x4 */
  126141. if( sqlite3WhereTrace&0x4 ){
  126142. sqlite3DebugPrintf(
  126143. "Skip %s cost=%-3d,%3d order=%c",
  126144. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  126145. isOrdered>=0 ? isOrdered+'0' : '?');
  126146. sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
  126147. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  126148. pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  126149. }
  126150. #endif
  126151. /* Discard the candidate path from further consideration */
  126152. testcase( pTo->rCost==rCost );
  126153. continue;
  126154. }
  126155. testcase( pTo->rCost==rCost+1 );
  126156. /* Control reaches here if the candidate path is better than the
  126157. ** pTo path. Replace pTo with the candidate. */
  126158. #ifdef WHERETRACE_ENABLED /* 0x4 */
  126159. if( sqlite3WhereTrace&0x4 ){
  126160. sqlite3DebugPrintf(
  126161. "Update %s cost=%-3d,%3d order=%c",
  126162. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  126163. isOrdered>=0 ? isOrdered+'0' : '?');
  126164. sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
  126165. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  126166. pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  126167. }
  126168. #endif
  126169. }
  126170. /* pWLoop is a winner. Add it to the set of best so far */
  126171. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  126172. pTo->revLoop = revMask;
  126173. pTo->nRow = nOut;
  126174. pTo->rCost = rCost;
  126175. pTo->rUnsorted = rUnsorted;
  126176. pTo->isOrdered = isOrdered;
  126177. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  126178. pTo->aLoop[iLoop] = pWLoop;
  126179. if( nTo>=mxChoice ){
  126180. mxI = 0;
  126181. mxCost = aTo[0].rCost;
  126182. mxUnsorted = aTo[0].nRow;
  126183. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  126184. if( pTo->rCost>mxCost
  126185. || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
  126186. ){
  126187. mxCost = pTo->rCost;
  126188. mxUnsorted = pTo->rUnsorted;
  126189. mxI = jj;
  126190. }
  126191. }
  126192. }
  126193. }
  126194. }
  126195. #ifdef WHERETRACE_ENABLED /* >=2 */
  126196. if( sqlite3WhereTrace & 0x02 ){
  126197. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  126198. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  126199. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  126200. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  126201. pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
  126202. if( pTo->isOrdered>0 ){
  126203. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  126204. }else{
  126205. sqlite3DebugPrintf("\n");
  126206. }
  126207. }
  126208. }
  126209. #endif
  126210. /* Swap the roles of aFrom and aTo for the next generation */
  126211. pFrom = aTo;
  126212. aTo = aFrom;
  126213. aFrom = pFrom;
  126214. nFrom = nTo;
  126215. }
  126216. if( nFrom==0 ){
  126217. sqlite3ErrorMsg(pParse, "no query solution");
  126218. sqlite3DbFreeNN(db, pSpace);
  126219. return SQLITE_ERROR;
  126220. }
  126221. /* Find the lowest cost path. pFrom will be left pointing to that path */
  126222. pFrom = aFrom;
  126223. for(ii=1; ii<nFrom; ii++){
  126224. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  126225. }
  126226. assert( pWInfo->nLevel==nLoop );
  126227. /* Load the lowest cost path into pWInfo */
  126228. for(iLoop=0; iLoop<nLoop; iLoop++){
  126229. WhereLevel *pLevel = pWInfo->a + iLoop;
  126230. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  126231. pLevel->iFrom = pWLoop->iTab;
  126232. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  126233. }
  126234. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  126235. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  126236. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  126237. && nRowEst
  126238. ){
  126239. Bitmask notUsed;
  126240. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  126241. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  126242. if( rc==pWInfo->pResultSet->nExpr ){
  126243. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  126244. }
  126245. }
  126246. if( pWInfo->pOrderBy ){
  126247. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  126248. if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
  126249. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  126250. }
  126251. }else{
  126252. pWInfo->nOBSat = pFrom->isOrdered;
  126253. pWInfo->revMask = pFrom->revLoop;
  126254. if( pWInfo->nOBSat<=0 ){
  126255. pWInfo->nOBSat = 0;
  126256. if( nLoop>0 ){
  126257. u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
  126258. if( (wsFlags & WHERE_ONEROW)==0
  126259. && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
  126260. ){
  126261. Bitmask m = 0;
  126262. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
  126263. WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
  126264. testcase( wsFlags & WHERE_IPK );
  126265. testcase( wsFlags & WHERE_COLUMN_IN );
  126266. if( rc==pWInfo->pOrderBy->nExpr ){
  126267. pWInfo->bOrderedInnerLoop = 1;
  126268. pWInfo->revMask = m;
  126269. }
  126270. }
  126271. }
  126272. }
  126273. }
  126274. if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
  126275. && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
  126276. ){
  126277. Bitmask revMask = 0;
  126278. int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
  126279. pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
  126280. );
  126281. assert( pWInfo->sorted==0 );
  126282. if( nOrder==pWInfo->pOrderBy->nExpr ){
  126283. pWInfo->sorted = 1;
  126284. pWInfo->revMask = revMask;
  126285. }
  126286. }
  126287. }
  126288. pWInfo->nRowOut = pFrom->nRow;
  126289. /* Free temporary memory and return success */
  126290. sqlite3DbFreeNN(db, pSpace);
  126291. return SQLITE_OK;
  126292. }
  126293. /*
  126294. ** Most queries use only a single table (they are not joins) and have
  126295. ** simple == constraints against indexed fields. This routine attempts
  126296. ** to plan those simple cases using much less ceremony than the
  126297. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  126298. ** times for the common case.
  126299. **
  126300. ** Return non-zero on success, if this query can be handled by this
  126301. ** no-frills query planner. Return zero if this query needs the
  126302. ** general-purpose query planner.
  126303. */
  126304. static int whereShortCut(WhereLoopBuilder *pBuilder){
  126305. WhereInfo *pWInfo;
  126306. struct SrcList_item *pItem;
  126307. WhereClause *pWC;
  126308. WhereTerm *pTerm;
  126309. WhereLoop *pLoop;
  126310. int iCur;
  126311. int j;
  126312. Table *pTab;
  126313. Index *pIdx;
  126314. pWInfo = pBuilder->pWInfo;
  126315. if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
  126316. assert( pWInfo->pTabList->nSrc>=1 );
  126317. pItem = pWInfo->pTabList->a;
  126318. pTab = pItem->pTab;
  126319. if( IsVirtual(pTab) ) return 0;
  126320. if( pItem->fg.isIndexedBy ) return 0;
  126321. iCur = pItem->iCursor;
  126322. pWC = &pWInfo->sWC;
  126323. pLoop = pBuilder->pNew;
  126324. pLoop->wsFlags = 0;
  126325. pLoop->nSkip = 0;
  126326. pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
  126327. if( pTerm ){
  126328. testcase( pTerm->eOperator & WO_IS );
  126329. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  126330. pLoop->aLTerm[0] = pTerm;
  126331. pLoop->nLTerm = 1;
  126332. pLoop->u.btree.nEq = 1;
  126333. /* TUNING: Cost of a rowid lookup is 10 */
  126334. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  126335. }else{
  126336. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  126337. int opMask;
  126338. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  126339. if( !IsUniqueIndex(pIdx)
  126340. || pIdx->pPartIdxWhere!=0
  126341. || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
  126342. ) continue;
  126343. opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
  126344. for(j=0; j<pIdx->nKeyCol; j++){
  126345. pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
  126346. if( pTerm==0 ) break;
  126347. testcase( pTerm->eOperator & WO_IS );
  126348. pLoop->aLTerm[j] = pTerm;
  126349. }
  126350. if( j!=pIdx->nKeyCol ) continue;
  126351. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  126352. if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
  126353. pLoop->wsFlags |= WHERE_IDX_ONLY;
  126354. }
  126355. pLoop->nLTerm = j;
  126356. pLoop->u.btree.nEq = j;
  126357. pLoop->u.btree.pIndex = pIdx;
  126358. /* TUNING: Cost of a unique index lookup is 15 */
  126359. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  126360. break;
  126361. }
  126362. }
  126363. if( pLoop->wsFlags ){
  126364. pLoop->nOut = (LogEst)1;
  126365. pWInfo->a[0].pWLoop = pLoop;
  126366. assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
  126367. pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
  126368. pWInfo->a[0].iTabCur = iCur;
  126369. pWInfo->nRowOut = 1;
  126370. if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
  126371. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  126372. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  126373. }
  126374. #ifdef SQLITE_DEBUG
  126375. pLoop->cId = '0';
  126376. #endif
  126377. return 1;
  126378. }
  126379. return 0;
  126380. }
  126381. /*
  126382. ** Generate the beginning of the loop used for WHERE clause processing.
  126383. ** The return value is a pointer to an opaque structure that contains
  126384. ** information needed to terminate the loop. Later, the calling routine
  126385. ** should invoke sqlite3WhereEnd() with the return value of this function
  126386. ** in order to complete the WHERE clause processing.
  126387. **
  126388. ** If an error occurs, this routine returns NULL.
  126389. **
  126390. ** The basic idea is to do a nested loop, one loop for each table in
  126391. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  126392. ** same as a SELECT with only a single table in the FROM clause.) For
  126393. ** example, if the SQL is this:
  126394. **
  126395. ** SELECT * FROM t1, t2, t3 WHERE ...;
  126396. **
  126397. ** Then the code generated is conceptually like the following:
  126398. **
  126399. ** foreach row1 in t1 do \ Code generated
  126400. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  126401. ** foreach row3 in t3 do /
  126402. ** ...
  126403. ** end \ Code generated
  126404. ** end |-- by sqlite3WhereEnd()
  126405. ** end /
  126406. **
  126407. ** Note that the loops might not be nested in the order in which they
  126408. ** appear in the FROM clause if a different order is better able to make
  126409. ** use of indices. Note also that when the IN operator appears in
  126410. ** the WHERE clause, it might result in additional nested loops for
  126411. ** scanning through all values on the right-hand side of the IN.
  126412. **
  126413. ** There are Btree cursors associated with each table. t1 uses cursor
  126414. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  126415. ** And so forth. This routine generates code to open those VDBE cursors
  126416. ** and sqlite3WhereEnd() generates the code to close them.
  126417. **
  126418. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  126419. ** in pTabList pointing at their appropriate entries. The [...] code
  126420. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  126421. ** data from the various tables of the loop.
  126422. **
  126423. ** If the WHERE clause is empty, the foreach loops must each scan their
  126424. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  126425. ** the tables have indices and there are terms in the WHERE clause that
  126426. ** refer to those indices, a complete table scan can be avoided and the
  126427. ** code will run much faster. Most of the work of this routine is checking
  126428. ** to see if there are indices that can be used to speed up the loop.
  126429. **
  126430. ** Terms of the WHERE clause are also used to limit which rows actually
  126431. ** make it to the "..." in the middle of the loop. After each "foreach",
  126432. ** terms of the WHERE clause that use only terms in that loop and outer
  126433. ** loops are evaluated and if false a jump is made around all subsequent
  126434. ** inner loops (or around the "..." if the test occurs within the inner-
  126435. ** most loop)
  126436. **
  126437. ** OUTER JOINS
  126438. **
  126439. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  126440. **
  126441. ** foreach row1 in t1 do
  126442. ** flag = 0
  126443. ** foreach row2 in t2 do
  126444. ** start:
  126445. ** ...
  126446. ** flag = 1
  126447. ** end
  126448. ** if flag==0 then
  126449. ** move the row2 cursor to a null row
  126450. ** goto start
  126451. ** fi
  126452. ** end
  126453. **
  126454. ** ORDER BY CLAUSE PROCESSING
  126455. **
  126456. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  126457. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  126458. ** if there is one. If there is no ORDER BY clause or if this routine
  126459. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  126460. **
  126461. ** The iIdxCur parameter is the cursor number of an index. If
  126462. ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
  126463. ** to use for OR clause processing. The WHERE clause should use this
  126464. ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
  126465. ** the first cursor in an array of cursors for all indices. iIdxCur should
  126466. ** be used to compute the appropriate cursor depending on which index is
  126467. ** used.
  126468. */
  126469. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  126470. Parse *pParse, /* The parser context */
  126471. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  126472. Expr *pWhere, /* The WHERE clause */
  126473. ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
  126474. ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */
  126475. u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
  126476. int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number
  126477. ** If WHERE_USE_LIMIT, then the limit amount */
  126478. ){
  126479. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  126480. int nTabList; /* Number of elements in pTabList */
  126481. WhereInfo *pWInfo; /* Will become the return value of this function */
  126482. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  126483. Bitmask notReady; /* Cursors that are not yet positioned */
  126484. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  126485. WhereMaskSet *pMaskSet; /* The expression mask set */
  126486. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  126487. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  126488. int ii; /* Loop counter */
  126489. sqlite3 *db; /* Database connection */
  126490. int rc; /* Return code */
  126491. u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
  126492. assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
  126493. (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  126494. && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  126495. ));
  126496. /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
  126497. assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  126498. || (wctrlFlags & WHERE_USE_LIMIT)==0 );
  126499. /* Variable initialization */
  126500. db = pParse->db;
  126501. memset(&sWLB, 0, sizeof(sWLB));
  126502. /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
  126503. testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
  126504. if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
  126505. sWLB.pOrderBy = pOrderBy;
  126506. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  126507. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  126508. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  126509. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  126510. }
  126511. /* The number of tables in the FROM clause is limited by the number of
  126512. ** bits in a Bitmask
  126513. */
  126514. testcase( pTabList->nSrc==BMS );
  126515. if( pTabList->nSrc>BMS ){
  126516. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  126517. return 0;
  126518. }
  126519. /* This function normally generates a nested loop for all tables in
  126520. ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should
  126521. ** only generate code for the first table in pTabList and assume that
  126522. ** any cursors associated with subsequent tables are uninitialized.
  126523. */
  126524. nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
  126525. /* Allocate and initialize the WhereInfo structure that will become the
  126526. ** return value. A single allocation is used to store the WhereInfo
  126527. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  126528. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  126529. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  126530. ** some architectures. Hence the ROUND8() below.
  126531. */
  126532. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  126533. pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
  126534. if( db->mallocFailed ){
  126535. sqlite3DbFree(db, pWInfo);
  126536. pWInfo = 0;
  126537. goto whereBeginError;
  126538. }
  126539. pWInfo->pParse = pParse;
  126540. pWInfo->pTabList = pTabList;
  126541. pWInfo->pOrderBy = pOrderBy;
  126542. pWInfo->pWhere = pWhere;
  126543. pWInfo->pResultSet = pResultSet;
  126544. pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
  126545. pWInfo->nLevel = nTabList;
  126546. pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
  126547. pWInfo->wctrlFlags = wctrlFlags;
  126548. pWInfo->iLimit = iAuxArg;
  126549. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  126550. memset(&pWInfo->nOBSat, 0,
  126551. offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
  126552. memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
  126553. assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
  126554. pMaskSet = &pWInfo->sMaskSet;
  126555. sWLB.pWInfo = pWInfo;
  126556. sWLB.pWC = &pWInfo->sWC;
  126557. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  126558. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  126559. whereLoopInit(sWLB.pNew);
  126560. #ifdef SQLITE_DEBUG
  126561. sWLB.pNew->cId = '*';
  126562. #endif
  126563. /* Split the WHERE clause into separate subexpressions where each
  126564. ** subexpression is separated by an AND operator.
  126565. */
  126566. initMaskSet(pMaskSet);
  126567. sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
  126568. sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
  126569. /* Special case: a WHERE clause that is constant. Evaluate the
  126570. ** expression and either jump over all of the code or fall thru.
  126571. */
  126572. for(ii=0; ii<sWLB.pWC->nTerm; ii++){
  126573. if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
  126574. sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
  126575. SQLITE_JUMPIFNULL);
  126576. sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
  126577. }
  126578. }
  126579. /* Special case: No FROM clause
  126580. */
  126581. if( nTabList==0 ){
  126582. if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
  126583. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  126584. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  126585. }
  126586. }
  126587. /* Assign a bit from the bitmask to every term in the FROM clause.
  126588. **
  126589. ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
  126590. **
  126591. ** The rule of the previous sentence ensures thta if X is the bitmask for
  126592. ** a table T, then X-1 is the bitmask for all other tables to the left of T.
  126593. ** Knowing the bitmask for all tables to the left of a left join is
  126594. ** important. Ticket #3015.
  126595. **
  126596. ** Note that bitmasks are created for all pTabList->nSrc tables in
  126597. ** pTabList, not just the first nTabList tables. nTabList is normally
  126598. ** equal to pTabList->nSrc but might be shortened to 1 if the
  126599. ** WHERE_OR_SUBCLAUSE flag is set.
  126600. */
  126601. for(ii=0; ii<pTabList->nSrc; ii++){
  126602. createMask(pMaskSet, pTabList->a[ii].iCursor);
  126603. sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
  126604. }
  126605. #ifdef SQLITE_DEBUG
  126606. for(ii=0; ii<pTabList->nSrc; ii++){
  126607. Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
  126608. assert( m==MASKBIT(ii) );
  126609. }
  126610. #endif
  126611. /* Analyze all of the subexpressions. */
  126612. sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
  126613. if( db->mallocFailed ) goto whereBeginError;
  126614. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  126615. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  126616. /* The DISTINCT marking is pointless. Ignore it. */
  126617. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  126618. }else if( pOrderBy==0 ){
  126619. /* Try to ORDER BY the result set to make distinct processing easier */
  126620. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  126621. pWInfo->pOrderBy = pResultSet;
  126622. }
  126623. }
  126624. /* Construct the WhereLoop objects */
  126625. #if defined(WHERETRACE_ENABLED)
  126626. if( sqlite3WhereTrace & 0xffff ){
  126627. sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
  126628. if( wctrlFlags & WHERE_USE_LIMIT ){
  126629. sqlite3DebugPrintf(", limit: %d", iAuxArg);
  126630. }
  126631. sqlite3DebugPrintf(")\n");
  126632. }
  126633. if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
  126634. sqlite3WhereClausePrint(sWLB.pWC);
  126635. }
  126636. #endif
  126637. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  126638. rc = whereLoopAddAll(&sWLB);
  126639. if( rc ) goto whereBeginError;
  126640. #ifdef WHERETRACE_ENABLED
  126641. if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
  126642. WhereLoop *p;
  126643. int i;
  126644. static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  126645. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  126646. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  126647. p->cId = zLabel[i%sizeof(zLabel)];
  126648. whereLoopPrint(p, sWLB.pWC);
  126649. }
  126650. }
  126651. #endif
  126652. wherePathSolver(pWInfo, 0);
  126653. if( db->mallocFailed ) goto whereBeginError;
  126654. if( pWInfo->pOrderBy ){
  126655. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  126656. if( db->mallocFailed ) goto whereBeginError;
  126657. }
  126658. }
  126659. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  126660. pWInfo->revMask = ALLBITS;
  126661. }
  126662. if( pParse->nErr || NEVER(db->mallocFailed) ){
  126663. goto whereBeginError;
  126664. }
  126665. #ifdef WHERETRACE_ENABLED
  126666. if( sqlite3WhereTrace ){
  126667. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  126668. if( pWInfo->nOBSat>0 ){
  126669. sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
  126670. }
  126671. switch( pWInfo->eDistinct ){
  126672. case WHERE_DISTINCT_UNIQUE: {
  126673. sqlite3DebugPrintf(" DISTINCT=unique");
  126674. break;
  126675. }
  126676. case WHERE_DISTINCT_ORDERED: {
  126677. sqlite3DebugPrintf(" DISTINCT=ordered");
  126678. break;
  126679. }
  126680. case WHERE_DISTINCT_UNORDERED: {
  126681. sqlite3DebugPrintf(" DISTINCT=unordered");
  126682. break;
  126683. }
  126684. }
  126685. sqlite3DebugPrintf("\n");
  126686. for(ii=0; ii<pWInfo->nLevel; ii++){
  126687. whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
  126688. }
  126689. }
  126690. #endif
  126691. /* Attempt to omit tables from the join that do not effect the result */
  126692. if( pWInfo->nLevel>=2
  126693. && pResultSet!=0
  126694. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  126695. ){
  126696. Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
  126697. if( sWLB.pOrderBy ){
  126698. tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
  126699. }
  126700. while( pWInfo->nLevel>=2 ){
  126701. WhereTerm *pTerm, *pEnd;
  126702. pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
  126703. if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
  126704. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  126705. && (pLoop->wsFlags & WHERE_ONEROW)==0
  126706. ){
  126707. break;
  126708. }
  126709. if( (tabUsed & pLoop->maskSelf)!=0 ) break;
  126710. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  126711. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  126712. if( (pTerm->prereqAll & pLoop->maskSelf)!=0
  126713. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  126714. ){
  126715. break;
  126716. }
  126717. }
  126718. if( pTerm<pEnd ) break;
  126719. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  126720. pWInfo->nLevel--;
  126721. nTabList--;
  126722. }
  126723. }
  126724. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  126725. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  126726. /* If the caller is an UPDATE or DELETE statement that is requesting
  126727. ** to use a one-pass algorithm, determine if this is appropriate.
  126728. */
  126729. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  126730. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
  126731. int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
  126732. int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
  126733. if( bOnerow
  126734. || ((wctrlFlags & WHERE_ONEPASS_MULTIROW)!=0
  126735. && 0==(wsFlags & WHERE_VIRTUALTABLE))
  126736. ){
  126737. pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
  126738. if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
  126739. if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
  126740. bFordelete = OPFLAG_FORDELETE;
  126741. }
  126742. pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
  126743. }
  126744. }
  126745. }
  126746. /* Open all tables in the pTabList and any indices selected for
  126747. ** searching those tables.
  126748. */
  126749. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  126750. Table *pTab; /* Table to open */
  126751. int iDb; /* Index of database containing table/index */
  126752. struct SrcList_item *pTabItem;
  126753. pTabItem = &pTabList->a[pLevel->iFrom];
  126754. pTab = pTabItem->pTab;
  126755. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  126756. pLoop = pLevel->pWLoop;
  126757. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  126758. /* Do nothing */
  126759. }else
  126760. #ifndef SQLITE_OMIT_VIRTUALTABLE
  126761. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  126762. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  126763. int iCur = pTabItem->iCursor;
  126764. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  126765. }else if( IsVirtual(pTab) ){
  126766. /* noop */
  126767. }else
  126768. #endif
  126769. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  126770. && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
  126771. int op = OP_OpenRead;
  126772. if( pWInfo->eOnePass!=ONEPASS_OFF ){
  126773. op = OP_OpenWrite;
  126774. pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
  126775. };
  126776. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  126777. assert( pTabItem->iCursor==pLevel->iTabCur );
  126778. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
  126779. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
  126780. if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
  126781. Bitmask b = pTabItem->colUsed;
  126782. int n = 0;
  126783. for(; b; b=b>>1, n++){}
  126784. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
  126785. assert( n<=pTab->nCol );
  126786. }
  126787. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  126788. if( pLoop->u.btree.pIndex!=0 ){
  126789. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
  126790. }else
  126791. #endif
  126792. {
  126793. sqlite3VdbeChangeP5(v, bFordelete);
  126794. }
  126795. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  126796. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
  126797. (const u8*)&pTabItem->colUsed, P4_INT64);
  126798. #endif
  126799. }else{
  126800. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  126801. }
  126802. if( pLoop->wsFlags & WHERE_INDEXED ){
  126803. Index *pIx = pLoop->u.btree.pIndex;
  126804. int iIndexCur;
  126805. int op = OP_OpenRead;
  126806. /* iAuxArg is always set if to a positive value if ONEPASS is possible */
  126807. assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
  126808. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
  126809. && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
  126810. ){
  126811. /* This is one term of an OR-optimization using the PRIMARY KEY of a
  126812. ** WITHOUT ROWID table. No need for a separate index */
  126813. iIndexCur = pLevel->iTabCur;
  126814. op = 0;
  126815. }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
  126816. Index *pJ = pTabItem->pTab->pIndex;
  126817. iIndexCur = iAuxArg;
  126818. assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
  126819. while( ALWAYS(pJ) && pJ!=pIx ){
  126820. iIndexCur++;
  126821. pJ = pJ->pNext;
  126822. }
  126823. op = OP_OpenWrite;
  126824. pWInfo->aiCurOnePass[1] = iIndexCur;
  126825. }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
  126826. iIndexCur = iAuxArg;
  126827. op = OP_ReopenIdx;
  126828. }else{
  126829. iIndexCur = pParse->nTab++;
  126830. }
  126831. pLevel->iIdxCur = iIndexCur;
  126832. assert( pIx->pSchema==pTab->pSchema );
  126833. assert( iIndexCur>=0 );
  126834. if( op ){
  126835. sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
  126836. sqlite3VdbeSetP4KeyInfo(pParse, pIx);
  126837. if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
  126838. && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
  126839. && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
  126840. && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
  126841. ){
  126842. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
  126843. }
  126844. VdbeComment((v, "%s", pIx->zName));
  126845. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  126846. {
  126847. u64 colUsed = 0;
  126848. int ii, jj;
  126849. for(ii=0; ii<pIx->nColumn; ii++){
  126850. jj = pIx->aiColumn[ii];
  126851. if( jj<0 ) continue;
  126852. if( jj>63 ) jj = 63;
  126853. if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
  126854. colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
  126855. }
  126856. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
  126857. (u8*)&colUsed, P4_INT64);
  126858. }
  126859. #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
  126860. }
  126861. }
  126862. if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
  126863. }
  126864. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  126865. if( db->mallocFailed ) goto whereBeginError;
  126866. /* Generate the code to do the search. Each iteration of the for
  126867. ** loop below generates code for a single nested loop of the VM
  126868. ** program.
  126869. */
  126870. notReady = ~(Bitmask)0;
  126871. for(ii=0; ii<nTabList; ii++){
  126872. int addrExplain;
  126873. int wsFlags;
  126874. pLevel = &pWInfo->a[ii];
  126875. wsFlags = pLevel->pWLoop->wsFlags;
  126876. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  126877. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  126878. constructAutomaticIndex(pParse, &pWInfo->sWC,
  126879. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  126880. if( db->mallocFailed ) goto whereBeginError;
  126881. }
  126882. #endif
  126883. addrExplain = sqlite3WhereExplainOneScan(
  126884. pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
  126885. );
  126886. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  126887. notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
  126888. pWInfo->iContinue = pLevel->addrCont;
  126889. if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
  126890. sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
  126891. }
  126892. }
  126893. /* Done. */
  126894. VdbeModuleComment((v, "Begin WHERE-core"));
  126895. return pWInfo;
  126896. /* Jump here if malloc fails */
  126897. whereBeginError:
  126898. if( pWInfo ){
  126899. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  126900. whereInfoFree(db, pWInfo);
  126901. }
  126902. return 0;
  126903. }
  126904. /*
  126905. ** Generate the end of the WHERE loop. See comments on
  126906. ** sqlite3WhereBegin() for additional information.
  126907. */
  126908. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  126909. Parse *pParse = pWInfo->pParse;
  126910. Vdbe *v = pParse->pVdbe;
  126911. int i;
  126912. WhereLevel *pLevel;
  126913. WhereLoop *pLoop;
  126914. SrcList *pTabList = pWInfo->pTabList;
  126915. sqlite3 *db = pParse->db;
  126916. /* Generate loop termination code.
  126917. */
  126918. VdbeModuleComment((v, "End WHERE-core"));
  126919. sqlite3ExprCacheClear(pParse);
  126920. for(i=pWInfo->nLevel-1; i>=0; i--){
  126921. int addr;
  126922. pLevel = &pWInfo->a[i];
  126923. pLoop = pLevel->pWLoop;
  126924. if( pLevel->op!=OP_Noop ){
  126925. #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  126926. int addrSeek = 0;
  126927. Index *pIdx;
  126928. int n;
  126929. if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
  126930. && (pLoop->wsFlags & WHERE_INDEXED)!=0
  126931. && (pIdx = pLoop->u.btree.pIndex)->hasStat1
  126932. && (n = pLoop->u.btree.nIdxCol)>0
  126933. && pIdx->aiRowLogEst[n]>=36
  126934. ){
  126935. int r1 = pParse->nMem+1;
  126936. int j, op;
  126937. for(j=0; j<n; j++){
  126938. sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
  126939. }
  126940. pParse->nMem += n+1;
  126941. op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
  126942. addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
  126943. VdbeCoverageIf(v, op==OP_SeekLT);
  126944. VdbeCoverageIf(v, op==OP_SeekGT);
  126945. sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
  126946. }
  126947. #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
  126948. /* The common case: Advance to the next row */
  126949. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  126950. sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
  126951. sqlite3VdbeChangeP5(v, pLevel->p5);
  126952. VdbeCoverage(v);
  126953. VdbeCoverageIf(v, pLevel->op==OP_Next);
  126954. VdbeCoverageIf(v, pLevel->op==OP_Prev);
  126955. VdbeCoverageIf(v, pLevel->op==OP_VNext);
  126956. #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  126957. if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
  126958. #endif
  126959. }else{
  126960. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  126961. }
  126962. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  126963. struct InLoop *pIn;
  126964. int j;
  126965. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  126966. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  126967. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  126968. if( pIn->eEndLoopOp!=OP_Noop ){
  126969. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  126970. VdbeCoverage(v);
  126971. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
  126972. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
  126973. }
  126974. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  126975. }
  126976. }
  126977. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  126978. if( pLevel->addrSkip ){
  126979. sqlite3VdbeGoto(v, pLevel->addrSkip);
  126980. VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
  126981. sqlite3VdbeJumpHere(v, pLevel->addrSkip);
  126982. sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
  126983. }
  126984. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  126985. if( pLevel->addrLikeRep ){
  126986. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
  126987. pLevel->addrLikeRep);
  126988. VdbeCoverage(v);
  126989. }
  126990. #endif
  126991. if( pLevel->iLeftJoin ){
  126992. int ws = pLoop->wsFlags;
  126993. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
  126994. assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
  126995. if( (ws & WHERE_IDX_ONLY)==0 ){
  126996. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  126997. }
  126998. if( (ws & WHERE_INDEXED)
  126999. || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx)
  127000. ){
  127001. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  127002. }
  127003. if( pLevel->op==OP_Return ){
  127004. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  127005. }else{
  127006. sqlite3VdbeGoto(v, pLevel->addrFirst);
  127007. }
  127008. sqlite3VdbeJumpHere(v, addr);
  127009. }
  127010. VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
  127011. pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
  127012. }
  127013. /* The "break" point is here, just past the end of the outer loop.
  127014. ** Set it.
  127015. */
  127016. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  127017. assert( pWInfo->nLevel<=pTabList->nSrc );
  127018. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  127019. int k, last;
  127020. VdbeOp *pOp;
  127021. Index *pIdx = 0;
  127022. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  127023. Table *pTab = pTabItem->pTab;
  127024. assert( pTab!=0 );
  127025. pLoop = pLevel->pWLoop;
  127026. /* For a co-routine, change all OP_Column references to the table of
  127027. ** the co-routine into OP_Copy of result contained in a register.
  127028. ** OP_Rowid becomes OP_Null.
  127029. */
  127030. if( pTabItem->fg.viaCoroutine ){
  127031. testcase( pParse->db->mallocFailed );
  127032. translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
  127033. pTabItem->regResult, 0);
  127034. continue;
  127035. }
  127036. /* If this scan uses an index, make VDBE code substitutions to read data
  127037. ** from the index instead of from the table where possible. In some cases
  127038. ** this optimization prevents the table from ever being read, which can
  127039. ** yield a significant performance boost.
  127040. **
  127041. ** Calls to the code generator in between sqlite3WhereBegin and
  127042. ** sqlite3WhereEnd will have created code that references the table
  127043. ** directly. This loop scans all that code looking for opcodes
  127044. ** that reference the table and converts them into opcodes that
  127045. ** reference the index.
  127046. */
  127047. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  127048. pIdx = pLoop->u.btree.pIndex;
  127049. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  127050. pIdx = pLevel->u.pCovidx;
  127051. }
  127052. if( pIdx
  127053. && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
  127054. && !db->mallocFailed
  127055. ){
  127056. last = sqlite3VdbeCurrentAddr(v);
  127057. k = pLevel->addrBody;
  127058. pOp = sqlite3VdbeGetOp(v, k);
  127059. for(; k<last; k++, pOp++){
  127060. if( pOp->p1!=pLevel->iTabCur ) continue;
  127061. if( pOp->opcode==OP_Column ){
  127062. int x = pOp->p2;
  127063. assert( pIdx->pTable==pTab );
  127064. if( !HasRowid(pTab) ){
  127065. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  127066. x = pPk->aiColumn[x];
  127067. assert( x>=0 );
  127068. }
  127069. x = sqlite3ColumnOfIndex(pIdx, x);
  127070. if( x>=0 ){
  127071. pOp->p2 = x;
  127072. pOp->p1 = pLevel->iIdxCur;
  127073. }
  127074. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0
  127075. || pWInfo->eOnePass );
  127076. }else if( pOp->opcode==OP_Rowid ){
  127077. pOp->p1 = pLevel->iIdxCur;
  127078. pOp->opcode = OP_IdxRowid;
  127079. }else if( pOp->opcode==OP_IfNullRow ){
  127080. pOp->p1 = pLevel->iIdxCur;
  127081. }
  127082. }
  127083. }
  127084. }
  127085. /* Final cleanup
  127086. */
  127087. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  127088. whereInfoFree(db, pWInfo);
  127089. return;
  127090. }
  127091. /************** End of where.c ***********************************************/
  127092. /************** Begin file parse.c *******************************************/
  127093. /*
  127094. ** 2000-05-29
  127095. **
  127096. ** The author disclaims copyright to this source code. In place of
  127097. ** a legal notice, here is a blessing:
  127098. **
  127099. ** May you do good and not evil.
  127100. ** May you find forgiveness for yourself and forgive others.
  127101. ** May you share freely, never taking more than you give.
  127102. **
  127103. *************************************************************************
  127104. ** Driver template for the LEMON parser generator.
  127105. **
  127106. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  127107. ** this template to construct a parser. The "lemon" program inserts text
  127108. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  127109. ** interstitial "-" characters) contained in this template is changed into
  127110. ** the value of the %name directive from the grammar. Otherwise, the content
  127111. ** of this template is copied straight through into the generate parser
  127112. ** source file.
  127113. **
  127114. ** The following is the concatenation of all %include directives from the
  127115. ** input grammar file:
  127116. */
  127117. /* #include <stdio.h> */
  127118. /************ Begin %include sections from the grammar ************************/
  127119. /* #include "sqliteInt.h" */
  127120. /*
  127121. ** Disable all error recovery processing in the parser push-down
  127122. ** automaton.
  127123. */
  127124. #define YYNOERRORRECOVERY 1
  127125. /*
  127126. ** Make yytestcase() the same as testcase()
  127127. */
  127128. #define yytestcase(X) testcase(X)
  127129. /*
  127130. ** Indicate that sqlite3ParserFree() will never be called with a null
  127131. ** pointer.
  127132. */
  127133. #define YYPARSEFREENEVERNULL 1
  127134. /*
  127135. ** In the amalgamation, the parse.c file generated by lemon and the
  127136. ** tokenize.c file are concatenated. In that case, sqlite3RunParser()
  127137. ** has access to the the size of the yyParser object and so the parser
  127138. ** engine can be allocated from stack. In that case, only the
  127139. ** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
  127140. ** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
  127141. ** omitted.
  127142. */
  127143. #ifdef SQLITE_AMALGAMATION
  127144. # define sqlite3Parser_ENGINEALWAYSONSTACK 1
  127145. #endif
  127146. /*
  127147. ** Alternative datatype for the argument to the malloc() routine passed
  127148. ** into sqlite3ParserAlloc(). The default is size_t.
  127149. */
  127150. #define YYMALLOCARGTYPE u64
  127151. /*
  127152. ** An instance of this structure holds information about the
  127153. ** LIMIT clause of a SELECT statement.
  127154. */
  127155. struct LimitVal {
  127156. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  127157. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  127158. };
  127159. /*
  127160. ** An instance of the following structure describes the event of a
  127161. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  127162. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  127163. **
  127164. ** UPDATE ON (a,b,c)
  127165. **
  127166. ** Then the "b" IdList records the list "a,b,c".
  127167. */
  127168. struct TrigEvent { int a; IdList * b; };
  127169. /*
  127170. ** Disable lookaside memory allocation for objects that might be
  127171. ** shared across database connections.
  127172. */
  127173. static void disableLookaside(Parse *pParse){
  127174. pParse->disableLookaside++;
  127175. pParse->db->lookaside.bDisable++;
  127176. }
  127177. /*
  127178. ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
  127179. ** all elements in the list. And make sure list length does not exceed
  127180. ** SQLITE_LIMIT_COMPOUND_SELECT.
  127181. */
  127182. static void parserDoubleLinkSelect(Parse *pParse, Select *p){
  127183. if( p->pPrior ){
  127184. Select *pNext = 0, *pLoop;
  127185. int mxSelect, cnt = 0;
  127186. for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
  127187. pLoop->pNext = pNext;
  127188. pLoop->selFlags |= SF_Compound;
  127189. }
  127190. if( (p->selFlags & SF_MultiValue)==0 &&
  127191. (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
  127192. cnt>mxSelect
  127193. ){
  127194. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  127195. }
  127196. }
  127197. }
  127198. /* This is a utility routine used to set the ExprSpan.zStart and
  127199. ** ExprSpan.zEnd values of pOut so that the span covers the complete
  127200. ** range of text beginning with pStart and going to the end of pEnd.
  127201. */
  127202. static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
  127203. pOut->zStart = pStart->z;
  127204. pOut->zEnd = &pEnd->z[pEnd->n];
  127205. }
  127206. /* Construct a new Expr object from a single identifier. Use the
  127207. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  127208. ** that created the expression.
  127209. */
  127210. static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){
  127211. Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
  127212. if( p ){
  127213. memset(p, 0, sizeof(Expr));
  127214. p->op = (u8)op;
  127215. p->flags = EP_Leaf;
  127216. p->iAgg = -1;
  127217. p->u.zToken = (char*)&p[1];
  127218. memcpy(p->u.zToken, t.z, t.n);
  127219. p->u.zToken[t.n] = 0;
  127220. if( sqlite3Isquote(p->u.zToken[0]) ){
  127221. if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted;
  127222. sqlite3Dequote(p->u.zToken);
  127223. }
  127224. #if SQLITE_MAX_EXPR_DEPTH>0
  127225. p->nHeight = 1;
  127226. #endif
  127227. }
  127228. pOut->pExpr = p;
  127229. pOut->zStart = t.z;
  127230. pOut->zEnd = &t.z[t.n];
  127231. }
  127232. /* This routine constructs a binary expression node out of two ExprSpan
  127233. ** objects and uses the result to populate a new ExprSpan object.
  127234. */
  127235. static void spanBinaryExpr(
  127236. Parse *pParse, /* The parsing context. Errors accumulate here */
  127237. int op, /* The binary operation */
  127238. ExprSpan *pLeft, /* The left operand, and output */
  127239. ExprSpan *pRight /* The right operand */
  127240. ){
  127241. pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr);
  127242. pLeft->zEnd = pRight->zEnd;
  127243. }
  127244. /* If doNot is true, then add a TK_NOT Expr-node wrapper around the
  127245. ** outside of *ppExpr.
  127246. */
  127247. static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){
  127248. if( doNot ){
  127249. pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0);
  127250. }
  127251. }
  127252. /* Construct an expression node for a unary postfix operator
  127253. */
  127254. static void spanUnaryPostfix(
  127255. Parse *pParse, /* Parsing context to record errors */
  127256. int op, /* The operator */
  127257. ExprSpan *pOperand, /* The operand, and output */
  127258. Token *pPostOp /* The operand token for setting the span */
  127259. ){
  127260. pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0);
  127261. pOperand->zEnd = &pPostOp->z[pPostOp->n];
  127262. }
  127263. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  127264. ** unary TK_ISNULL or TK_NOTNULL expression. */
  127265. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  127266. sqlite3 *db = pParse->db;
  127267. if( pA && pY && pY->op==TK_NULL ){
  127268. pA->op = (u8)op;
  127269. sqlite3ExprDelete(db, pA->pRight);
  127270. pA->pRight = 0;
  127271. }
  127272. }
  127273. /* Construct an expression node for a unary prefix operator
  127274. */
  127275. static void spanUnaryPrefix(
  127276. ExprSpan *pOut, /* Write the new expression node here */
  127277. Parse *pParse, /* Parsing context to record errors */
  127278. int op, /* The operator */
  127279. ExprSpan *pOperand, /* The operand */
  127280. Token *pPreOp /* The operand token for setting the span */
  127281. ){
  127282. pOut->zStart = pPreOp->z;
  127283. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0);
  127284. pOut->zEnd = pOperand->zEnd;
  127285. }
  127286. /* Add a single new term to an ExprList that is used to store a
  127287. ** list of identifiers. Report an error if the ID list contains
  127288. ** a COLLATE clause or an ASC or DESC keyword, except ignore the
  127289. ** error while parsing a legacy schema.
  127290. */
  127291. static ExprList *parserAddExprIdListTerm(
  127292. Parse *pParse,
  127293. ExprList *pPrior,
  127294. Token *pIdToken,
  127295. int hasCollate,
  127296. int sortOrder
  127297. ){
  127298. ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
  127299. if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
  127300. && pParse->db->init.busy==0
  127301. ){
  127302. sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
  127303. pIdToken->n, pIdToken->z);
  127304. }
  127305. sqlite3ExprListSetName(pParse, p, pIdToken, 1);
  127306. return p;
  127307. }
  127308. /**************** End of %include directives **********************************/
  127309. /* These constants specify the various numeric values for terminal symbols
  127310. ** in a format understandable to "makeheaders". This section is blank unless
  127311. ** "lemon" is run with the "-m" command-line option.
  127312. ***************** Begin makeheaders token definitions *************************/
  127313. /**************** End makeheaders token definitions ***************************/
  127314. /* The next sections is a series of control #defines.
  127315. ** various aspects of the generated parser.
  127316. ** YYCODETYPE is the data type used to store the integer codes
  127317. ** that represent terminal and non-terminal symbols.
  127318. ** "unsigned char" is used if there are fewer than
  127319. ** 256 symbols. Larger types otherwise.
  127320. ** YYNOCODE is a number of type YYCODETYPE that is not used for
  127321. ** any terminal or nonterminal symbol.
  127322. ** YYFALLBACK If defined, this indicates that one or more tokens
  127323. ** (also known as: "terminal symbols") have fall-back
  127324. ** values which should be used if the original symbol
  127325. ** would not parse. This permits keywords to sometimes
  127326. ** be used as identifiers, for example.
  127327. ** YYACTIONTYPE is the data type used for "action codes" - numbers
  127328. ** that indicate what to do in response to the next
  127329. ** token.
  127330. ** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal
  127331. ** symbols. Background: A "minor type" is a semantic
  127332. ** value associated with a terminal or non-terminal
  127333. ** symbols. For example, for an "ID" terminal symbol,
  127334. ** the minor type might be the name of the identifier.
  127335. ** Each non-terminal can have a different minor type.
  127336. ** Terminal symbols all have the same minor type, though.
  127337. ** This macros defines the minor type for terminal
  127338. ** symbols.
  127339. ** YYMINORTYPE is the data type used for all minor types.
  127340. ** This is typically a union of many types, one of
  127341. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  127342. ** for terminal symbols is called "yy0".
  127343. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  127344. ** zero the stack is dynamically sized using realloc()
  127345. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  127346. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  127347. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  127348. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  127349. ** YYERRORSYMBOL is the code number of the error symbol. If not
  127350. ** defined, then do no error processing.
  127351. ** YYNSTATE the combined number of states.
  127352. ** YYNRULE the number of rules in the grammar
  127353. ** YY_MAX_SHIFT Maximum value for shift actions
  127354. ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  127355. ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  127356. ** YY_MIN_REDUCE Maximum value for reduce actions
  127357. ** YY_ERROR_ACTION The yy_action[] code for syntax error
  127358. ** YY_ACCEPT_ACTION The yy_action[] code for accept
  127359. ** YY_NO_ACTION The yy_action[] code for no-op
  127360. */
  127361. #ifndef INTERFACE
  127362. # define INTERFACE 1
  127363. #endif
  127364. /************* Begin control #defines *****************************************/
  127365. #define YYCODETYPE unsigned char
  127366. #define YYNOCODE 252
  127367. #define YYACTIONTYPE unsigned short int
  127368. #define YYWILDCARD 69
  127369. #define sqlite3ParserTOKENTYPE Token
  127370. typedef union {
  127371. int yyinit;
  127372. sqlite3ParserTOKENTYPE yy0;
  127373. Expr* yy72;
  127374. TriggerStep* yy145;
  127375. ExprList* yy148;
  127376. SrcList* yy185;
  127377. ExprSpan yy190;
  127378. int yy194;
  127379. Select* yy243;
  127380. IdList* yy254;
  127381. With* yy285;
  127382. struct TrigEvent yy332;
  127383. struct LimitVal yy354;
  127384. struct {int value; int mask;} yy497;
  127385. } YYMINORTYPE;
  127386. #ifndef YYSTACKDEPTH
  127387. #define YYSTACKDEPTH 100
  127388. #endif
  127389. #define sqlite3ParserARG_SDECL Parse *pParse;
  127390. #define sqlite3ParserARG_PDECL ,Parse *pParse
  127391. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  127392. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  127393. #define YYFALLBACK 1
  127394. #define YYNSTATE 456
  127395. #define YYNRULE 332
  127396. #define YY_MAX_SHIFT 455
  127397. #define YY_MIN_SHIFTREDUCE 668
  127398. #define YY_MAX_SHIFTREDUCE 999
  127399. #define YY_MIN_REDUCE 1000
  127400. #define YY_MAX_REDUCE 1331
  127401. #define YY_ERROR_ACTION 1332
  127402. #define YY_ACCEPT_ACTION 1333
  127403. #define YY_NO_ACTION 1334
  127404. /************* End control #defines *******************************************/
  127405. /* Define the yytestcase() macro to be a no-op if is not already defined
  127406. ** otherwise.
  127407. **
  127408. ** Applications can choose to define yytestcase() in the %include section
  127409. ** to a macro that can assist in verifying code coverage. For production
  127410. ** code the yytestcase() macro should be turned off. But it is useful
  127411. ** for testing.
  127412. */
  127413. #ifndef yytestcase
  127414. # define yytestcase(X)
  127415. #endif
  127416. /* Next are the tables used to determine what action to take based on the
  127417. ** current state and lookahead token. These tables are used to implement
  127418. ** functions that take a state number and lookahead value and return an
  127419. ** action integer.
  127420. **
  127421. ** Suppose the action integer is N. Then the action is determined as
  127422. ** follows
  127423. **
  127424. ** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead
  127425. ** token onto the stack and goto state N.
  127426. **
  127427. ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  127428. ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
  127429. **
  127430. ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
  127431. ** and YY_MAX_REDUCE
  127432. **
  127433. ** N == YY_ERROR_ACTION A syntax error has occurred.
  127434. **
  127435. ** N == YY_ACCEPT_ACTION The parser accepts its input.
  127436. **
  127437. ** N == YY_NO_ACTION No such action. Denotes unused
  127438. ** slots in the yy_action[] table.
  127439. **
  127440. ** The action table is constructed as a single large table named yy_action[].
  127441. ** Given state S and lookahead X, the action is computed as either:
  127442. **
  127443. ** (A) N = yy_action[ yy_shift_ofst[S] + X ]
  127444. ** (B) N = yy_default[S]
  127445. **
  127446. ** The (A) formula is preferred. The B formula is used instead if:
  127447. ** (1) The yy_shift_ofst[S]+X value is out of range, or
  127448. ** (2) yy_lookahead[yy_shift_ofst[S]+X] is not equal to X, or
  127449. ** (3) yy_shift_ofst[S] equal YY_SHIFT_USE_DFLT.
  127450. ** (Implementation note: YY_SHIFT_USE_DFLT is chosen so that
  127451. ** YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
  127452. ** Hence only tests (1) and (2) need to be evaluated.)
  127453. **
  127454. ** The formulas above are for computing the action when the lookahead is
  127455. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  127456. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  127457. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  127458. ** YY_SHIFT_USE_DFLT.
  127459. **
  127460. ** The following are the tables generated in this section:
  127461. **
  127462. ** yy_action[] A single table containing all actions.
  127463. ** yy_lookahead[] A table containing the lookahead for each entry in
  127464. ** yy_action. Used to detect hash collisions.
  127465. ** yy_shift_ofst[] For each state, the offset into yy_action for
  127466. ** shifting terminals.
  127467. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  127468. ** shifting non-terminals after a reduce.
  127469. ** yy_default[] Default action for each state.
  127470. **
  127471. *********** Begin parsing tables **********************************************/
  127472. #define YY_ACTTAB_COUNT (1566)
  127473. static const YYACTIONTYPE yy_action[] = {
  127474. /* 0 */ 325, 411, 343, 752, 752, 203, 946, 354, 976, 98,
  127475. /* 10 */ 98, 98, 98, 91, 96, 96, 96, 96, 95, 95,
  127476. /* 20 */ 94, 94, 94, 93, 351, 1333, 155, 155, 2, 813,
  127477. /* 30 */ 978, 978, 98, 98, 98, 98, 20, 96, 96, 96,
  127478. /* 40 */ 96, 95, 95, 94, 94, 94, 93, 351, 92, 89,
  127479. /* 50 */ 178, 99, 100, 90, 853, 856, 845, 845, 97, 97,
  127480. /* 60 */ 98, 98, 98, 98, 351, 96, 96, 96, 96, 95,
  127481. /* 70 */ 95, 94, 94, 94, 93, 351, 325, 340, 976, 262,
  127482. /* 80 */ 365, 251, 212, 169, 287, 405, 282, 404, 199, 791,
  127483. /* 90 */ 242, 412, 21, 957, 379, 280, 93, 351, 792, 95,
  127484. /* 100 */ 95, 94, 94, 94, 93, 351, 978, 978, 96, 96,
  127485. /* 110 */ 96, 96, 95, 95, 94, 94, 94, 93, 351, 813,
  127486. /* 120 */ 329, 242, 412, 913, 832, 913, 132, 99, 100, 90,
  127487. /* 130 */ 853, 856, 845, 845, 97, 97, 98, 98, 98, 98,
  127488. /* 140 */ 450, 96, 96, 96, 96, 95, 95, 94, 94, 94,
  127489. /* 150 */ 93, 351, 325, 825, 349, 348, 120, 819, 120, 75,
  127490. /* 160 */ 52, 52, 957, 958, 959, 760, 984, 146, 361, 262,
  127491. /* 170 */ 370, 261, 957, 982, 961, 983, 92, 89, 178, 371,
  127492. /* 180 */ 230, 371, 978, 978, 817, 361, 360, 101, 824, 824,
  127493. /* 190 */ 826, 384, 24, 964, 381, 428, 413, 369, 985, 380,
  127494. /* 200 */ 985, 708, 325, 99, 100, 90, 853, 856, 845, 845,
  127495. /* 210 */ 97, 97, 98, 98, 98, 98, 373, 96, 96, 96,
  127496. /* 220 */ 96, 95, 95, 94, 94, 94, 93, 351, 957, 132,
  127497. /* 230 */ 897, 450, 978, 978, 896, 60, 94, 94, 94, 93,
  127498. /* 240 */ 351, 957, 958, 959, 961, 103, 361, 957, 385, 334,
  127499. /* 250 */ 702, 52, 52, 99, 100, 90, 853, 856, 845, 845,
  127500. /* 260 */ 97, 97, 98, 98, 98, 98, 698, 96, 96, 96,
  127501. /* 270 */ 96, 95, 95, 94, 94, 94, 93, 351, 325, 455,
  127502. /* 280 */ 670, 450, 227, 61, 157, 243, 344, 114, 701, 888,
  127503. /* 290 */ 147, 832, 957, 373, 747, 957, 320, 957, 958, 959,
  127504. /* 300 */ 194, 10, 10, 402, 399, 398, 888, 890, 978, 978,
  127505. /* 310 */ 762, 171, 170, 157, 397, 337, 957, 958, 959, 702,
  127506. /* 320 */ 825, 310, 153, 957, 819, 321, 82, 23, 80, 99,
  127507. /* 330 */ 100, 90, 853, 856, 845, 845, 97, 97, 98, 98,
  127508. /* 340 */ 98, 98, 894, 96, 96, 96, 96, 95, 95, 94,
  127509. /* 350 */ 94, 94, 93, 351, 325, 824, 824, 826, 277, 231,
  127510. /* 360 */ 300, 957, 958, 959, 957, 958, 959, 888, 194, 25,
  127511. /* 370 */ 450, 402, 399, 398, 957, 355, 300, 450, 957, 74,
  127512. /* 380 */ 450, 1, 397, 132, 978, 978, 957, 224, 224, 813,
  127513. /* 390 */ 10, 10, 957, 958, 959, 968, 132, 52, 52, 415,
  127514. /* 400 */ 52, 52, 739, 739, 339, 99, 100, 90, 853, 856,
  127515. /* 410 */ 845, 845, 97, 97, 98, 98, 98, 98, 790, 96,
  127516. /* 420 */ 96, 96, 96, 95, 95, 94, 94, 94, 93, 351,
  127517. /* 430 */ 325, 789, 428, 418, 706, 428, 427, 1270, 1270, 262,
  127518. /* 440 */ 370, 261, 957, 957, 958, 959, 757, 957, 958, 959,
  127519. /* 450 */ 450, 756, 450, 734, 713, 957, 958, 959, 443, 711,
  127520. /* 460 */ 978, 978, 734, 394, 92, 89, 178, 447, 447, 447,
  127521. /* 470 */ 51, 51, 52, 52, 439, 778, 700, 92, 89, 178,
  127522. /* 480 */ 172, 99, 100, 90, 853, 856, 845, 845, 97, 97,
  127523. /* 490 */ 98, 98, 98, 98, 198, 96, 96, 96, 96, 95,
  127524. /* 500 */ 95, 94, 94, 94, 93, 351, 325, 428, 408, 916,
  127525. /* 510 */ 699, 957, 958, 959, 92, 89, 178, 224, 224, 157,
  127526. /* 520 */ 241, 221, 419, 299, 776, 917, 416, 375, 450, 415,
  127527. /* 530 */ 58, 324, 737, 737, 920, 379, 978, 978, 379, 777,
  127528. /* 540 */ 449, 918, 363, 740, 296, 686, 9, 9, 52, 52,
  127529. /* 550 */ 234, 330, 234, 256, 417, 741, 280, 99, 100, 90,
  127530. /* 560 */ 853, 856, 845, 845, 97, 97, 98, 98, 98, 98,
  127531. /* 570 */ 450, 96, 96, 96, 96, 95, 95, 94, 94, 94,
  127532. /* 580 */ 93, 351, 325, 423, 72, 450, 833, 120, 368, 450,
  127533. /* 590 */ 10, 10, 5, 301, 203, 450, 177, 976, 253, 420,
  127534. /* 600 */ 255, 776, 200, 175, 233, 10, 10, 842, 842, 36,
  127535. /* 610 */ 36, 1299, 978, 978, 729, 37, 37, 349, 348, 425,
  127536. /* 620 */ 203, 260, 776, 976, 232, 937, 1326, 876, 338, 1326,
  127537. /* 630 */ 422, 854, 857, 99, 100, 90, 853, 856, 845, 845,
  127538. /* 640 */ 97, 97, 98, 98, 98, 98, 268, 96, 96, 96,
  127539. /* 650 */ 96, 95, 95, 94, 94, 94, 93, 351, 325, 846,
  127540. /* 660 */ 450, 985, 818, 985, 1209, 450, 916, 976, 720, 350,
  127541. /* 670 */ 350, 350, 935, 177, 450, 937, 1327, 254, 198, 1327,
  127542. /* 680 */ 12, 12, 917, 403, 450, 27, 27, 250, 978, 978,
  127543. /* 690 */ 118, 721, 162, 976, 38, 38, 268, 176, 918, 776,
  127544. /* 700 */ 433, 1275, 946, 354, 39, 39, 317, 998, 325, 99,
  127545. /* 710 */ 100, 90, 853, 856, 845, 845, 97, 97, 98, 98,
  127546. /* 720 */ 98, 98, 935, 96, 96, 96, 96, 95, 95, 94,
  127547. /* 730 */ 94, 94, 93, 351, 450, 330, 450, 358, 978, 978,
  127548. /* 740 */ 717, 317, 936, 341, 900, 900, 387, 673, 674, 675,
  127549. /* 750 */ 275, 996, 318, 999, 40, 40, 41, 41, 268, 99,
  127550. /* 760 */ 100, 90, 853, 856, 845, 845, 97, 97, 98, 98,
  127551. /* 770 */ 98, 98, 450, 96, 96, 96, 96, 95, 95, 94,
  127552. /* 780 */ 94, 94, 93, 351, 325, 450, 356, 450, 999, 450,
  127553. /* 790 */ 692, 331, 42, 42, 791, 270, 450, 273, 450, 228,
  127554. /* 800 */ 450, 298, 450, 792, 450, 28, 28, 29, 29, 31,
  127555. /* 810 */ 31, 450, 817, 450, 978, 978, 43, 43, 44, 44,
  127556. /* 820 */ 45, 45, 11, 11, 46, 46, 893, 78, 893, 268,
  127557. /* 830 */ 268, 105, 105, 47, 47, 99, 100, 90, 853, 856,
  127558. /* 840 */ 845, 845, 97, 97, 98, 98, 98, 98, 450, 96,
  127559. /* 850 */ 96, 96, 96, 95, 95, 94, 94, 94, 93, 351,
  127560. /* 860 */ 325, 450, 117, 450, 749, 158, 450, 696, 48, 48,
  127561. /* 870 */ 229, 919, 450, 928, 450, 415, 450, 335, 450, 245,
  127562. /* 880 */ 450, 33, 33, 49, 49, 450, 50, 50, 246, 817,
  127563. /* 890 */ 978, 978, 34, 34, 122, 122, 123, 123, 124, 124,
  127564. /* 900 */ 56, 56, 268, 81, 249, 35, 35, 197, 196, 195,
  127565. /* 910 */ 325, 99, 100, 90, 853, 856, 845, 845, 97, 97,
  127566. /* 920 */ 98, 98, 98, 98, 450, 96, 96, 96, 96, 95,
  127567. /* 930 */ 95, 94, 94, 94, 93, 351, 450, 696, 450, 817,
  127568. /* 940 */ 978, 978, 975, 884, 106, 106, 268, 886, 268, 944,
  127569. /* 950 */ 2, 892, 268, 892, 336, 716, 53, 53, 107, 107,
  127570. /* 960 */ 325, 99, 100, 90, 853, 856, 845, 845, 97, 97,
  127571. /* 970 */ 98, 98, 98, 98, 450, 96, 96, 96, 96, 95,
  127572. /* 980 */ 95, 94, 94, 94, 93, 351, 450, 746, 450, 742,
  127573. /* 990 */ 978, 978, 715, 267, 108, 108, 446, 331, 332, 133,
  127574. /* 1000 */ 223, 175, 301, 225, 386, 933, 104, 104, 121, 121,
  127575. /* 1010 */ 325, 99, 88, 90, 853, 856, 845, 845, 97, 97,
  127576. /* 1020 */ 98, 98, 98, 98, 817, 96, 96, 96, 96, 95,
  127577. /* 1030 */ 95, 94, 94, 94, 93, 351, 450, 347, 450, 167,
  127578. /* 1040 */ 978, 978, 932, 815, 372, 319, 202, 202, 374, 263,
  127579. /* 1050 */ 395, 202, 74, 208, 726, 727, 119, 119, 112, 112,
  127580. /* 1060 */ 325, 407, 100, 90, 853, 856, 845, 845, 97, 97,
  127581. /* 1070 */ 98, 98, 98, 98, 450, 96, 96, 96, 96, 95,
  127582. /* 1080 */ 95, 94, 94, 94, 93, 351, 450, 757, 450, 345,
  127583. /* 1090 */ 978, 978, 756, 278, 111, 111, 74, 719, 718, 709,
  127584. /* 1100 */ 286, 883, 754, 1289, 257, 77, 109, 109, 110, 110,
  127585. /* 1110 */ 908, 285, 810, 90, 853, 856, 845, 845, 97, 97,
  127586. /* 1120 */ 98, 98, 98, 98, 911, 96, 96, 96, 96, 95,
  127587. /* 1130 */ 95, 94, 94, 94, 93, 351, 86, 445, 450, 3,
  127588. /* 1140 */ 1202, 450, 745, 132, 352, 120, 689, 86, 445, 785,
  127589. /* 1150 */ 3, 767, 202, 377, 448, 352, 907, 120, 55, 55,
  127590. /* 1160 */ 450, 57, 57, 828, 879, 448, 450, 208, 450, 709,
  127591. /* 1170 */ 450, 883, 237, 434, 436, 120, 440, 429, 362, 120,
  127592. /* 1180 */ 54, 54, 132, 450, 434, 832, 52, 52, 26, 26,
  127593. /* 1190 */ 30, 30, 382, 132, 409, 444, 832, 694, 264, 390,
  127594. /* 1200 */ 116, 269, 272, 32, 32, 83, 84, 120, 274, 120,
  127595. /* 1210 */ 120, 276, 85, 352, 452, 451, 83, 84, 819, 730,
  127596. /* 1220 */ 714, 428, 430, 85, 352, 452, 451, 120, 120, 819,
  127597. /* 1230 */ 378, 218, 281, 828, 783, 816, 86, 445, 410, 3,
  127598. /* 1240 */ 763, 774, 431, 432, 352, 302, 303, 823, 697, 824,
  127599. /* 1250 */ 824, 826, 827, 19, 448, 691, 680, 679, 681, 951,
  127600. /* 1260 */ 824, 824, 826, 827, 19, 289, 159, 291, 293, 7,
  127601. /* 1270 */ 316, 173, 259, 434, 805, 364, 252, 910, 376, 713,
  127602. /* 1280 */ 295, 435, 168, 993, 400, 832, 284, 881, 880, 205,
  127603. /* 1290 */ 954, 308, 927, 86, 445, 990, 3, 925, 333, 144,
  127604. /* 1300 */ 130, 352, 72, 135, 59, 83, 84, 761, 137, 366,
  127605. /* 1310 */ 802, 448, 85, 352, 452, 451, 139, 226, 819, 140,
  127606. /* 1320 */ 156, 62, 315, 314, 313, 215, 311, 367, 393, 683,
  127607. /* 1330 */ 434, 185, 141, 912, 142, 160, 148, 812, 875, 383,
  127608. /* 1340 */ 189, 67, 832, 180, 389, 248, 895, 775, 219, 824,
  127609. /* 1350 */ 824, 826, 827, 19, 247, 190, 266, 154, 391, 271,
  127610. /* 1360 */ 191, 192, 83, 84, 682, 406, 733, 182, 322, 85,
  127611. /* 1370 */ 352, 452, 451, 732, 183, 819, 342, 132, 181, 711,
  127612. /* 1380 */ 731, 421, 76, 445, 705, 3, 323, 704, 283, 724,
  127613. /* 1390 */ 352, 771, 703, 966, 723, 71, 204, 6, 288, 290,
  127614. /* 1400 */ 448, 772, 770, 769, 79, 292, 824, 824, 826, 827,
  127615. /* 1410 */ 19, 294, 297, 438, 346, 442, 102, 861, 753, 434,
  127616. /* 1420 */ 238, 426, 73, 305, 239, 304, 326, 240, 424, 306,
  127617. /* 1430 */ 307, 832, 213, 688, 22, 952, 453, 214, 216, 217,
  127618. /* 1440 */ 454, 677, 115, 676, 671, 125, 126, 235, 127, 669,
  127619. /* 1450 */ 327, 83, 84, 359, 353, 244, 166, 328, 85, 352,
  127620. /* 1460 */ 452, 451, 134, 179, 819, 357, 113, 891, 811, 889,
  127621. /* 1470 */ 136, 128, 138, 743, 258, 184, 906, 143, 145, 63,
  127622. /* 1480 */ 64, 65, 66, 129, 909, 905, 187, 186, 8, 13,
  127623. /* 1490 */ 188, 265, 898, 149, 202, 824, 824, 826, 827, 19,
  127624. /* 1500 */ 388, 987, 150, 161, 285, 685, 392, 396, 151, 722,
  127625. /* 1510 */ 193, 68, 14, 401, 279, 15, 69, 236, 831, 830,
  127626. /* 1520 */ 131, 859, 751, 70, 16, 414, 755, 4, 784, 220,
  127627. /* 1530 */ 222, 174, 152, 437, 779, 201, 17, 77, 74, 18,
  127628. /* 1540 */ 874, 860, 858, 915, 863, 914, 207, 206, 941, 163,
  127629. /* 1550 */ 210, 942, 209, 164, 441, 862, 165, 211, 829, 695,
  127630. /* 1560 */ 87, 312, 309, 947, 1291, 1290,
  127631. };
  127632. static const YYCODETYPE yy_lookahead[] = {
  127633. /* 0 */ 19, 115, 19, 117, 118, 24, 1, 2, 27, 79,
  127634. /* 10 */ 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
  127635. /* 20 */ 90, 91, 92, 93, 94, 144, 145, 146, 147, 58,
  127636. /* 30 */ 49, 50, 79, 80, 81, 82, 22, 84, 85, 86,
  127637. /* 40 */ 87, 88, 89, 90, 91, 92, 93, 94, 221, 222,
  127638. /* 50 */ 223, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  127639. /* 60 */ 79, 80, 81, 82, 94, 84, 85, 86, 87, 88,
  127640. /* 70 */ 89, 90, 91, 92, 93, 94, 19, 94, 97, 108,
  127641. /* 80 */ 109, 110, 99, 100, 101, 102, 103, 104, 105, 32,
  127642. /* 90 */ 119, 120, 78, 27, 152, 112, 93, 94, 41, 88,
  127643. /* 100 */ 89, 90, 91, 92, 93, 94, 49, 50, 84, 85,
  127644. /* 110 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 58,
  127645. /* 120 */ 157, 119, 120, 163, 68, 163, 65, 70, 71, 72,
  127646. /* 130 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  127647. /* 140 */ 152, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  127648. /* 150 */ 93, 94, 19, 97, 88, 89, 196, 101, 196, 26,
  127649. /* 160 */ 172, 173, 96, 97, 98, 210, 100, 22, 152, 108,
  127650. /* 170 */ 109, 110, 27, 107, 27, 109, 221, 222, 223, 219,
  127651. /* 180 */ 238, 219, 49, 50, 152, 169, 170, 54, 132, 133,
  127652. /* 190 */ 134, 228, 232, 171, 231, 207, 208, 237, 132, 237,
  127653. /* 200 */ 134, 179, 19, 70, 71, 72, 73, 74, 75, 76,
  127654. /* 210 */ 77, 78, 79, 80, 81, 82, 152, 84, 85, 86,
  127655. /* 220 */ 87, 88, 89, 90, 91, 92, 93, 94, 27, 65,
  127656. /* 230 */ 30, 152, 49, 50, 34, 52, 90, 91, 92, 93,
  127657. /* 240 */ 94, 96, 97, 98, 97, 22, 230, 27, 48, 217,
  127658. /* 250 */ 27, 172, 173, 70, 71, 72, 73, 74, 75, 76,
  127659. /* 260 */ 77, 78, 79, 80, 81, 82, 172, 84, 85, 86,
  127660. /* 270 */ 87, 88, 89, 90, 91, 92, 93, 94, 19, 148,
  127661. /* 280 */ 149, 152, 218, 24, 152, 154, 207, 156, 172, 152,
  127662. /* 290 */ 22, 68, 27, 152, 163, 27, 164, 96, 97, 98,
  127663. /* 300 */ 99, 172, 173, 102, 103, 104, 169, 170, 49, 50,
  127664. /* 310 */ 90, 88, 89, 152, 113, 186, 96, 97, 98, 96,
  127665. /* 320 */ 97, 160, 57, 27, 101, 164, 137, 196, 139, 70,
  127666. /* 330 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  127667. /* 340 */ 81, 82, 11, 84, 85, 86, 87, 88, 89, 90,
  127668. /* 350 */ 91, 92, 93, 94, 19, 132, 133, 134, 23, 218,
  127669. /* 360 */ 152, 96, 97, 98, 96, 97, 98, 230, 99, 22,
  127670. /* 370 */ 152, 102, 103, 104, 27, 244, 152, 152, 27, 26,
  127671. /* 380 */ 152, 22, 113, 65, 49, 50, 27, 194, 195, 58,
  127672. /* 390 */ 172, 173, 96, 97, 98, 185, 65, 172, 173, 206,
  127673. /* 400 */ 172, 173, 190, 191, 186, 70, 71, 72, 73, 74,
  127674. /* 410 */ 75, 76, 77, 78, 79, 80, 81, 82, 175, 84,
  127675. /* 420 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
  127676. /* 430 */ 19, 175, 207, 208, 23, 207, 208, 119, 120, 108,
  127677. /* 440 */ 109, 110, 27, 96, 97, 98, 116, 96, 97, 98,
  127678. /* 450 */ 152, 121, 152, 179, 180, 96, 97, 98, 250, 106,
  127679. /* 460 */ 49, 50, 188, 19, 221, 222, 223, 168, 169, 170,
  127680. /* 470 */ 172, 173, 172, 173, 250, 124, 172, 221, 222, 223,
  127681. /* 480 */ 26, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  127682. /* 490 */ 79, 80, 81, 82, 50, 84, 85, 86, 87, 88,
  127683. /* 500 */ 89, 90, 91, 92, 93, 94, 19, 207, 208, 12,
  127684. /* 510 */ 23, 96, 97, 98, 221, 222, 223, 194, 195, 152,
  127685. /* 520 */ 199, 23, 19, 225, 26, 28, 152, 152, 152, 206,
  127686. /* 530 */ 209, 164, 190, 191, 241, 152, 49, 50, 152, 124,
  127687. /* 540 */ 152, 44, 219, 46, 152, 21, 172, 173, 172, 173,
  127688. /* 550 */ 183, 107, 185, 16, 163, 58, 112, 70, 71, 72,
  127689. /* 560 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  127690. /* 570 */ 152, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  127691. /* 580 */ 93, 94, 19, 207, 130, 152, 23, 196, 64, 152,
  127692. /* 590 */ 172, 173, 22, 152, 24, 152, 98, 27, 61, 96,
  127693. /* 600 */ 63, 26, 211, 212, 186, 172, 173, 49, 50, 172,
  127694. /* 610 */ 173, 23, 49, 50, 26, 172, 173, 88, 89, 186,
  127695. /* 620 */ 24, 238, 124, 27, 238, 22, 23, 103, 187, 26,
  127696. /* 630 */ 152, 73, 74, 70, 71, 72, 73, 74, 75, 76,
  127697. /* 640 */ 77, 78, 79, 80, 81, 82, 152, 84, 85, 86,
  127698. /* 650 */ 87, 88, 89, 90, 91, 92, 93, 94, 19, 101,
  127699. /* 660 */ 152, 132, 23, 134, 140, 152, 12, 97, 36, 168,
  127700. /* 670 */ 169, 170, 69, 98, 152, 22, 23, 140, 50, 26,
  127701. /* 680 */ 172, 173, 28, 51, 152, 172, 173, 193, 49, 50,
  127702. /* 690 */ 22, 59, 24, 97, 172, 173, 152, 152, 44, 124,
  127703. /* 700 */ 46, 0, 1, 2, 172, 173, 22, 23, 19, 70,
  127704. /* 710 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  127705. /* 720 */ 81, 82, 69, 84, 85, 86, 87, 88, 89, 90,
  127706. /* 730 */ 91, 92, 93, 94, 152, 107, 152, 193, 49, 50,
  127707. /* 740 */ 181, 22, 23, 111, 108, 109, 110, 7, 8, 9,
  127708. /* 750 */ 16, 247, 248, 69, 172, 173, 172, 173, 152, 70,
  127709. /* 760 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  127710. /* 770 */ 81, 82, 152, 84, 85, 86, 87, 88, 89, 90,
  127711. /* 780 */ 91, 92, 93, 94, 19, 152, 242, 152, 69, 152,
  127712. /* 790 */ 166, 167, 172, 173, 32, 61, 152, 63, 152, 193,
  127713. /* 800 */ 152, 152, 152, 41, 152, 172, 173, 172, 173, 172,
  127714. /* 810 */ 173, 152, 152, 152, 49, 50, 172, 173, 172, 173,
  127715. /* 820 */ 172, 173, 172, 173, 172, 173, 132, 138, 134, 152,
  127716. /* 830 */ 152, 172, 173, 172, 173, 70, 71, 72, 73, 74,
  127717. /* 840 */ 75, 76, 77, 78, 79, 80, 81, 82, 152, 84,
  127718. /* 850 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
  127719. /* 860 */ 19, 152, 22, 152, 195, 24, 152, 27, 172, 173,
  127720. /* 870 */ 193, 193, 152, 152, 152, 206, 152, 217, 152, 152,
  127721. /* 880 */ 152, 172, 173, 172, 173, 152, 172, 173, 152, 152,
  127722. /* 890 */ 49, 50, 172, 173, 172, 173, 172, 173, 172, 173,
  127723. /* 900 */ 172, 173, 152, 138, 152, 172, 173, 108, 109, 110,
  127724. /* 910 */ 19, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  127725. /* 920 */ 79, 80, 81, 82, 152, 84, 85, 86, 87, 88,
  127726. /* 930 */ 89, 90, 91, 92, 93, 94, 152, 97, 152, 152,
  127727. /* 940 */ 49, 50, 26, 193, 172, 173, 152, 152, 152, 146,
  127728. /* 950 */ 147, 132, 152, 134, 217, 181, 172, 173, 172, 173,
  127729. /* 960 */ 19, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  127730. /* 970 */ 79, 80, 81, 82, 152, 84, 85, 86, 87, 88,
  127731. /* 980 */ 89, 90, 91, 92, 93, 94, 152, 193, 152, 193,
  127732. /* 990 */ 49, 50, 181, 193, 172, 173, 166, 167, 245, 246,
  127733. /* 1000 */ 211, 212, 152, 22, 217, 152, 172, 173, 172, 173,
  127734. /* 1010 */ 19, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  127735. /* 1020 */ 79, 80, 81, 82, 152, 84, 85, 86, 87, 88,
  127736. /* 1030 */ 89, 90, 91, 92, 93, 94, 152, 187, 152, 123,
  127737. /* 1040 */ 49, 50, 23, 23, 23, 26, 26, 26, 23, 23,
  127738. /* 1050 */ 23, 26, 26, 26, 7, 8, 172, 173, 172, 173,
  127739. /* 1060 */ 19, 90, 71, 72, 73, 74, 75, 76, 77, 78,
  127740. /* 1070 */ 79, 80, 81, 82, 152, 84, 85, 86, 87, 88,
  127741. /* 1080 */ 89, 90, 91, 92, 93, 94, 152, 116, 152, 217,
  127742. /* 1090 */ 49, 50, 121, 23, 172, 173, 26, 100, 101, 27,
  127743. /* 1100 */ 101, 27, 23, 122, 152, 26, 172, 173, 172, 173,
  127744. /* 1110 */ 152, 112, 163, 72, 73, 74, 75, 76, 77, 78,
  127745. /* 1120 */ 79, 80, 81, 82, 163, 84, 85, 86, 87, 88,
  127746. /* 1130 */ 89, 90, 91, 92, 93, 94, 19, 20, 152, 22,
  127747. /* 1140 */ 23, 152, 163, 65, 27, 196, 163, 19, 20, 23,
  127748. /* 1150 */ 22, 213, 26, 19, 37, 27, 152, 196, 172, 173,
  127749. /* 1160 */ 152, 172, 173, 27, 23, 37, 152, 26, 152, 97,
  127750. /* 1170 */ 152, 97, 210, 56, 163, 196, 163, 163, 100, 196,
  127751. /* 1180 */ 172, 173, 65, 152, 56, 68, 172, 173, 172, 173,
  127752. /* 1190 */ 172, 173, 152, 65, 163, 163, 68, 23, 152, 234,
  127753. /* 1200 */ 26, 152, 152, 172, 173, 88, 89, 196, 152, 196,
  127754. /* 1210 */ 196, 152, 95, 96, 97, 98, 88, 89, 101, 152,
  127755. /* 1220 */ 152, 207, 208, 95, 96, 97, 98, 196, 196, 101,
  127756. /* 1230 */ 96, 233, 152, 97, 152, 152, 19, 20, 207, 22,
  127757. /* 1240 */ 152, 152, 152, 191, 27, 152, 152, 152, 152, 132,
  127758. /* 1250 */ 133, 134, 135, 136, 37, 152, 152, 152, 152, 152,
  127759. /* 1260 */ 132, 133, 134, 135, 136, 210, 197, 210, 210, 198,
  127760. /* 1270 */ 150, 184, 239, 56, 201, 214, 214, 201, 239, 180,
  127761. /* 1280 */ 214, 227, 198, 38, 176, 68, 175, 175, 175, 122,
  127762. /* 1290 */ 155, 200, 159, 19, 20, 40, 22, 159, 159, 22,
  127763. /* 1300 */ 70, 27, 130, 243, 240, 88, 89, 90, 189, 18,
  127764. /* 1310 */ 201, 37, 95, 96, 97, 98, 192, 5, 101, 192,
  127765. /* 1320 */ 220, 240, 10, 11, 12, 13, 14, 159, 18, 17,
  127766. /* 1330 */ 56, 158, 192, 201, 192, 220, 189, 189, 201, 159,
  127767. /* 1340 */ 158, 137, 68, 31, 45, 33, 236, 159, 159, 132,
  127768. /* 1350 */ 133, 134, 135, 136, 42, 158, 235, 22, 177, 159,
  127769. /* 1360 */ 158, 158, 88, 89, 159, 107, 174, 55, 177, 95,
  127770. /* 1370 */ 96, 97, 98, 174, 62, 101, 47, 65, 66, 106,
  127771. /* 1380 */ 174, 125, 19, 20, 174, 22, 177, 176, 174, 182,
  127772. /* 1390 */ 27, 216, 174, 174, 182, 107, 159, 22, 215, 215,
  127773. /* 1400 */ 37, 216, 216, 216, 137, 215, 132, 133, 134, 135,
  127774. /* 1410 */ 136, 215, 159, 177, 94, 177, 129, 224, 205, 56,
  127775. /* 1420 */ 226, 126, 128, 203, 229, 204, 114, 229, 127, 202,
  127776. /* 1430 */ 201, 68, 25, 162, 26, 13, 161, 153, 153, 6,
  127777. /* 1440 */ 151, 151, 178, 151, 151, 165, 165, 178, 165, 4,
  127778. /* 1450 */ 249, 88, 89, 141, 3, 142, 22, 249, 95, 96,
  127779. /* 1460 */ 97, 98, 246, 15, 101, 67, 16, 23, 120, 23,
  127780. /* 1470 */ 131, 111, 123, 20, 16, 125, 1, 123, 131, 78,
  127781. /* 1480 */ 78, 78, 78, 111, 96, 1, 122, 35, 5, 22,
  127782. /* 1490 */ 107, 140, 53, 53, 26, 132, 133, 134, 135, 136,
  127783. /* 1500 */ 43, 60, 107, 24, 112, 20, 19, 52, 22, 29,
  127784. /* 1510 */ 105, 22, 22, 52, 23, 22, 22, 52, 23, 23,
  127785. /* 1520 */ 39, 23, 116, 26, 22, 26, 23, 22, 96, 23,
  127786. /* 1530 */ 23, 122, 22, 24, 124, 35, 35, 26, 26, 35,
  127787. /* 1540 */ 23, 23, 23, 23, 11, 23, 22, 26, 23, 22,
  127788. /* 1550 */ 122, 23, 26, 22, 24, 23, 22, 122, 23, 23,
  127789. /* 1560 */ 22, 15, 23, 1, 122, 122,
  127790. };
  127791. #define YY_SHIFT_USE_DFLT (1566)
  127792. #define YY_SHIFT_COUNT (455)
  127793. #define YY_SHIFT_MIN (-114)
  127794. #define YY_SHIFT_MAX (1562)
  127795. static const short yy_shift_ofst[] = {
  127796. /* 0 */ 5, 1117, 1312, 1128, 1274, 1274, 1274, 1274, 61, -19,
  127797. /* 10 */ 57, 57, 183, 1274, 1274, 1274, 1274, 1274, 1274, 1274,
  127798. /* 20 */ 66, 66, 201, -29, 331, 318, 133, 259, 335, 411,
  127799. /* 30 */ 487, 563, 639, 689, 765, 841, 891, 891, 891, 891,
  127800. /* 40 */ 891, 891, 891, 891, 891, 891, 891, 891, 891, 891,
  127801. /* 50 */ 891, 891, 891, 941, 891, 991, 1041, 1041, 1217, 1274,
  127802. /* 60 */ 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274,
  127803. /* 70 */ 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274,
  127804. /* 80 */ 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274,
  127805. /* 90 */ 1363, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274, 1274,
  127806. /* 100 */ 1274, 1274, 1274, 1274, -70, -47, -47, -47, -47, -47,
  127807. /* 110 */ 24, 11, 146, 296, 524, 444, 529, 529, 296, 3,
  127808. /* 120 */ 2, -30, 1566, 1566, 1566, -17, -17, -17, 145, 145,
  127809. /* 130 */ 497, 497, 265, 603, 653, 296, 296, 296, 296, 296,
  127810. /* 140 */ 296, 296, 296, 296, 296, 296, 296, 296, 296, 296,
  127811. /* 150 */ 296, 296, 296, 296, 296, 701, 1078, 147, 147, 2,
  127812. /* 160 */ 164, 164, 164, 164, 164, 164, 1566, 1566, 1566, 223,
  127813. /* 170 */ 56, 56, 268, 269, 220, 347, 351, 415, 359, 296,
  127814. /* 180 */ 296, 296, 296, 296, 296, 296, 296, 296, 296, 296,
  127815. /* 190 */ 296, 296, 296, 296, 296, 632, 632, 632, 296, 296,
  127816. /* 200 */ 498, 296, 296, 296, 570, 296, 296, 654, 296, 296,
  127817. /* 210 */ 296, 296, 296, 296, 296, 296, 296, 296, 636, 200,
  127818. /* 220 */ 596, 596, 596, 575, -114, 971, 740, 454, 503, 503,
  127819. /* 230 */ 1134, 454, 1134, 353, 588, 628, 762, 503, 189, 762,
  127820. /* 240 */ 762, 916, 330, 668, 1245, 1167, 1167, 1255, 1255, 1167,
  127821. /* 250 */ 1277, 1230, 1172, 1291, 1291, 1291, 1291, 1167, 1310, 1172,
  127822. /* 260 */ 1277, 1230, 1230, 1172, 1167, 1310, 1204, 1299, 1167, 1167,
  127823. /* 270 */ 1310, 1335, 1167, 1310, 1167, 1310, 1335, 1258, 1258, 1258,
  127824. /* 280 */ 1329, 1335, 1258, 1273, 1258, 1329, 1258, 1258, 1256, 1288,
  127825. /* 290 */ 1256, 1288, 1256, 1288, 1256, 1288, 1167, 1375, 1167, 1267,
  127826. /* 300 */ 1335, 1320, 1320, 1335, 1287, 1295, 1294, 1301, 1172, 1407,
  127827. /* 310 */ 1408, 1422, 1422, 1433, 1433, 1433, 1433, 1566, 1566, 1566,
  127828. /* 320 */ 1566, 1566, 1566, 1566, 1566, 558, 537, 684, 719, 734,
  127829. /* 330 */ 799, 840, 1019, 14, 1020, 1021, 1025, 1026, 1027, 1070,
  127830. /* 340 */ 1072, 997, 1047, 999, 1079, 1126, 1074, 1141, 694, 819,
  127831. /* 350 */ 1174, 1136, 981, 1445, 1451, 1434, 1313, 1448, 1398, 1450,
  127832. /* 360 */ 1444, 1446, 1348, 1339, 1360, 1349, 1453, 1350, 1458, 1475,
  127833. /* 370 */ 1354, 1347, 1401, 1402, 1403, 1404, 1372, 1388, 1452, 1364,
  127834. /* 380 */ 1484, 1483, 1467, 1383, 1351, 1439, 1468, 1440, 1441, 1457,
  127835. /* 390 */ 1395, 1479, 1485, 1487, 1392, 1405, 1486, 1455, 1489, 1490,
  127836. /* 400 */ 1491, 1493, 1461, 1480, 1494, 1465, 1481, 1495, 1496, 1498,
  127837. /* 410 */ 1497, 1406, 1502, 1503, 1505, 1499, 1409, 1506, 1507, 1432,
  127838. /* 420 */ 1500, 1510, 1410, 1511, 1501, 1512, 1504, 1517, 1511, 1518,
  127839. /* 430 */ 1519, 1520, 1521, 1522, 1524, 1533, 1525, 1527, 1509, 1526,
  127840. /* 440 */ 1528, 1531, 1530, 1526, 1532, 1534, 1535, 1536, 1538, 1428,
  127841. /* 450 */ 1435, 1442, 1443, 1539, 1546, 1562,
  127842. };
  127843. #define YY_REDUCE_USE_DFLT (-174)
  127844. #define YY_REDUCE_COUNT (324)
  127845. #define YY_REDUCE_MIN (-173)
  127846. #define YY_REDUCE_MAX (1293)
  127847. static const short yy_reduce_ofst[] = {
  127848. /* 0 */ -119, 1014, 131, 1031, -12, 225, 228, 300, -40, -45,
  127849. /* 10 */ 243, 256, 293, 129, 218, 418, 79, 376, 433, 298,
  127850. /* 20 */ 16, 137, 367, 323, -38, 391, -173, -173, -173, -173,
  127851. /* 30 */ -173, -173, -173, -173, -173, -173, -173, -173, -173, -173,
  127852. /* 40 */ -173, -173, -173, -173, -173, -173, -173, -173, -173, -173,
  127853. /* 50 */ -173, -173, -173, -173, -173, -173, -173, -173, 374, 437,
  127854. /* 60 */ 443, 508, 513, 522, 532, 582, 584, 620, 633, 635,
  127855. /* 70 */ 637, 644, 646, 648, 650, 652, 659, 661, 696, 709,
  127856. /* 80 */ 711, 714, 720, 722, 724, 726, 728, 733, 772, 784,
  127857. /* 90 */ 786, 822, 834, 836, 884, 886, 922, 934, 936, 986,
  127858. /* 100 */ 989, 1008, 1016, 1018, -173, -173, -173, -173, -173, -173,
  127859. /* 110 */ -173, -173, -173, 544, -37, 274, 299, 501, 161, -173,
  127860. /* 120 */ 193, -173, -173, -173, -173, 22, 22, 22, 64, 141,
  127861. /* 130 */ 212, 342, 208, 504, 504, 132, 494, 606, 677, 678,
  127862. /* 140 */ 750, 794, 796, -58, 32, 383, 660, 737, 386, 787,
  127863. /* 150 */ 800, 441, 872, 224, 850, 803, 949, 624, 830, 669,
  127864. /* 160 */ 961, 979, 983, 1011, 1013, 1032, 753, 789, 321, 94,
  127865. /* 170 */ 116, 304, 375, 210, 388, 392, 478, 545, 649, 721,
  127866. /* 180 */ 727, 736, 752, 795, 853, 952, 958, 1004, 1040, 1046,
  127867. /* 190 */ 1049, 1050, 1056, 1059, 1067, 559, 774, 811, 1068, 1080,
  127868. /* 200 */ 938, 1082, 1083, 1088, 962, 1089, 1090, 1052, 1093, 1094,
  127869. /* 210 */ 1095, 388, 1096, 1103, 1104, 1105, 1106, 1107, 965, 998,
  127870. /* 220 */ 1055, 1057, 1058, 938, 1069, 1071, 1120, 1073, 1061, 1062,
  127871. /* 230 */ 1033, 1076, 1039, 1108, 1087, 1099, 1111, 1066, 1054, 1112,
  127872. /* 240 */ 1113, 1091, 1084, 1135, 1060, 1133, 1138, 1064, 1081, 1139,
  127873. /* 250 */ 1100, 1119, 1109, 1124, 1127, 1140, 1142, 1168, 1173, 1132,
  127874. /* 260 */ 1115, 1147, 1148, 1137, 1180, 1182, 1110, 1121, 1188, 1189,
  127875. /* 270 */ 1197, 1181, 1200, 1202, 1205, 1203, 1191, 1192, 1199, 1206,
  127876. /* 280 */ 1207, 1209, 1210, 1211, 1214, 1212, 1218, 1219, 1175, 1183,
  127877. /* 290 */ 1185, 1184, 1186, 1190, 1187, 1196, 1237, 1193, 1253, 1194,
  127878. /* 300 */ 1236, 1195, 1198, 1238, 1213, 1221, 1220, 1227, 1229, 1271,
  127879. /* 310 */ 1275, 1284, 1285, 1289, 1290, 1292, 1293, 1201, 1208, 1216,
  127880. /* 320 */ 1280, 1281, 1264, 1269, 1283,
  127881. };
  127882. static const YYACTIONTYPE yy_default[] = {
  127883. /* 0 */ 1280, 1270, 1270, 1270, 1202, 1202, 1202, 1202, 1270, 1096,
  127884. /* 10 */ 1125, 1125, 1254, 1332, 1332, 1332, 1332, 1332, 1332, 1201,
  127885. /* 20 */ 1332, 1332, 1332, 1332, 1270, 1100, 1131, 1332, 1332, 1332,
  127886. /* 30 */ 1332, 1203, 1204, 1332, 1332, 1332, 1253, 1255, 1141, 1140,
  127887. /* 40 */ 1139, 1138, 1236, 1112, 1136, 1129, 1133, 1203, 1197, 1198,
  127888. /* 50 */ 1196, 1200, 1204, 1332, 1132, 1167, 1181, 1166, 1332, 1332,
  127889. /* 60 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127890. /* 70 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127891. /* 80 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127892. /* 90 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127893. /* 100 */ 1332, 1332, 1332, 1332, 1175, 1180, 1187, 1179, 1176, 1169,
  127894. /* 110 */ 1168, 1170, 1171, 1332, 1019, 1067, 1332, 1332, 1332, 1172,
  127895. /* 120 */ 1332, 1173, 1184, 1183, 1182, 1261, 1288, 1287, 1332, 1332,
  127896. /* 130 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127897. /* 140 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127898. /* 150 */ 1332, 1332, 1332, 1332, 1332, 1280, 1270, 1025, 1025, 1332,
  127899. /* 160 */ 1270, 1270, 1270, 1270, 1270, 1270, 1266, 1100, 1091, 1332,
  127900. /* 170 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127901. /* 180 */ 1258, 1256, 1332, 1217, 1332, 1332, 1332, 1332, 1332, 1332,
  127902. /* 190 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127903. /* 200 */ 1332, 1332, 1332, 1332, 1096, 1332, 1332, 1332, 1332, 1332,
  127904. /* 210 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1282, 1332, 1231,
  127905. /* 220 */ 1096, 1096, 1096, 1098, 1080, 1090, 1004, 1135, 1114, 1114,
  127906. /* 230 */ 1321, 1135, 1321, 1042, 1302, 1039, 1125, 1114, 1199, 1125,
  127907. /* 240 */ 1125, 1097, 1090, 1332, 1324, 1105, 1105, 1323, 1323, 1105,
  127908. /* 250 */ 1146, 1070, 1135, 1076, 1076, 1076, 1076, 1105, 1016, 1135,
  127909. /* 260 */ 1146, 1070, 1070, 1135, 1105, 1016, 1235, 1318, 1105, 1105,
  127910. /* 270 */ 1016, 1210, 1105, 1016, 1105, 1016, 1210, 1068, 1068, 1068,
  127911. /* 280 */ 1057, 1210, 1068, 1042, 1068, 1057, 1068, 1068, 1118, 1113,
  127912. /* 290 */ 1118, 1113, 1118, 1113, 1118, 1113, 1105, 1205, 1105, 1332,
  127913. /* 300 */ 1210, 1214, 1214, 1210, 1130, 1119, 1128, 1126, 1135, 1022,
  127914. /* 310 */ 1060, 1285, 1285, 1281, 1281, 1281, 1281, 1329, 1329, 1266,
  127915. /* 320 */ 1297, 1297, 1044, 1044, 1297, 1332, 1332, 1332, 1332, 1332,
  127916. /* 330 */ 1332, 1292, 1332, 1219, 1332, 1332, 1332, 1332, 1332, 1332,
  127917. /* 340 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127918. /* 350 */ 1332, 1332, 1152, 1332, 1000, 1263, 1332, 1332, 1262, 1332,
  127919. /* 360 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127920. /* 370 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1320,
  127921. /* 380 */ 1332, 1332, 1332, 1332, 1332, 1332, 1234, 1233, 1332, 1332,
  127922. /* 390 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127923. /* 400 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332,
  127924. /* 410 */ 1332, 1082, 1332, 1332, 1332, 1306, 1332, 1332, 1332, 1332,
  127925. /* 420 */ 1332, 1332, 1332, 1127, 1332, 1120, 1332, 1332, 1311, 1332,
  127926. /* 430 */ 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1332, 1272,
  127927. /* 440 */ 1332, 1332, 1332, 1271, 1332, 1332, 1332, 1332, 1332, 1154,
  127928. /* 450 */ 1332, 1153, 1157, 1332, 1010, 1332,
  127929. };
  127930. /********** End of lemon-generated parsing tables *****************************/
  127931. /* The next table maps tokens (terminal symbols) into fallback tokens.
  127932. ** If a construct like the following:
  127933. **
  127934. ** %fallback ID X Y Z.
  127935. **
  127936. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  127937. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  127938. ** but it does not parse, the type of the token is changed to ID and
  127939. ** the parse is retried before an error is thrown.
  127940. **
  127941. ** This feature can be used, for example, to cause some keywords in a language
  127942. ** to revert to identifiers if they keyword does not apply in the context where
  127943. ** it appears.
  127944. */
  127945. #ifdef YYFALLBACK
  127946. static const YYCODETYPE yyFallback[] = {
  127947. 0, /* $ => nothing */
  127948. 0, /* SEMI => nothing */
  127949. 27, /* EXPLAIN => ID */
  127950. 27, /* QUERY => ID */
  127951. 27, /* PLAN => ID */
  127952. 27, /* BEGIN => ID */
  127953. 0, /* TRANSACTION => nothing */
  127954. 27, /* DEFERRED => ID */
  127955. 27, /* IMMEDIATE => ID */
  127956. 27, /* EXCLUSIVE => ID */
  127957. 0, /* COMMIT => nothing */
  127958. 27, /* END => ID */
  127959. 27, /* ROLLBACK => ID */
  127960. 27, /* SAVEPOINT => ID */
  127961. 27, /* RELEASE => ID */
  127962. 0, /* TO => nothing */
  127963. 0, /* TABLE => nothing */
  127964. 0, /* CREATE => nothing */
  127965. 27, /* IF => ID */
  127966. 0, /* NOT => nothing */
  127967. 0, /* EXISTS => nothing */
  127968. 27, /* TEMP => ID */
  127969. 0, /* LP => nothing */
  127970. 0, /* RP => nothing */
  127971. 0, /* AS => nothing */
  127972. 27, /* WITHOUT => ID */
  127973. 0, /* COMMA => nothing */
  127974. 0, /* ID => nothing */
  127975. 27, /* ABORT => ID */
  127976. 27, /* ACTION => ID */
  127977. 27, /* AFTER => ID */
  127978. 27, /* ANALYZE => ID */
  127979. 27, /* ASC => ID */
  127980. 27, /* ATTACH => ID */
  127981. 27, /* BEFORE => ID */
  127982. 27, /* BY => ID */
  127983. 27, /* CASCADE => ID */
  127984. 27, /* CAST => ID */
  127985. 27, /* COLUMNKW => ID */
  127986. 27, /* CONFLICT => ID */
  127987. 27, /* DATABASE => ID */
  127988. 27, /* DESC => ID */
  127989. 27, /* DETACH => ID */
  127990. 27, /* EACH => ID */
  127991. 27, /* FAIL => ID */
  127992. 27, /* FOR => ID */
  127993. 27, /* IGNORE => ID */
  127994. 27, /* INITIALLY => ID */
  127995. 27, /* INSTEAD => ID */
  127996. 27, /* LIKE_KW => ID */
  127997. 27, /* MATCH => ID */
  127998. 27, /* NO => ID */
  127999. 27, /* KEY => ID */
  128000. 27, /* OF => ID */
  128001. 27, /* OFFSET => ID */
  128002. 27, /* PRAGMA => ID */
  128003. 27, /* RAISE => ID */
  128004. 27, /* RECURSIVE => ID */
  128005. 27, /* REPLACE => ID */
  128006. 27, /* RESTRICT => ID */
  128007. 27, /* ROW => ID */
  128008. 27, /* TRIGGER => ID */
  128009. 27, /* VACUUM => ID */
  128010. 27, /* VIEW => ID */
  128011. 27, /* VIRTUAL => ID */
  128012. 27, /* WITH => ID */
  128013. 27, /* REINDEX => ID */
  128014. 27, /* RENAME => ID */
  128015. 27, /* CTIME_KW => ID */
  128016. };
  128017. #endif /* YYFALLBACK */
  128018. /* The following structure represents a single element of the
  128019. ** parser's stack. Information stored includes:
  128020. **
  128021. ** + The state number for the parser at this level of the stack.
  128022. **
  128023. ** + The value of the token stored at this level of the stack.
  128024. ** (In other words, the "major" token.)
  128025. **
  128026. ** + The semantic value stored at this level of the stack. This is
  128027. ** the information used by the action routines in the grammar.
  128028. ** It is sometimes called the "minor" token.
  128029. **
  128030. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  128031. ** actually contains the reduce action for the second half of the
  128032. ** SHIFTREDUCE.
  128033. */
  128034. struct yyStackEntry {
  128035. YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  128036. YYCODETYPE major; /* The major token value. This is the code
  128037. ** number for the token at this stack level */
  128038. YYMINORTYPE minor; /* The user-supplied minor token value. This
  128039. ** is the value of the token */
  128040. };
  128041. typedef struct yyStackEntry yyStackEntry;
  128042. /* The state of the parser is completely contained in an instance of
  128043. ** the following structure */
  128044. struct yyParser {
  128045. yyStackEntry *yytos; /* Pointer to top element of the stack */
  128046. #ifdef YYTRACKMAXSTACKDEPTH
  128047. int yyhwm; /* High-water mark of the stack */
  128048. #endif
  128049. #ifndef YYNOERRORRECOVERY
  128050. int yyerrcnt; /* Shifts left before out of the error */
  128051. #endif
  128052. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  128053. #if YYSTACKDEPTH<=0
  128054. int yystksz; /* Current side of the stack */
  128055. yyStackEntry *yystack; /* The parser's stack */
  128056. yyStackEntry yystk0; /* First stack entry */
  128057. #else
  128058. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  128059. #endif
  128060. };
  128061. typedef struct yyParser yyParser;
  128062. #ifndef NDEBUG
  128063. /* #include <stdio.h> */
  128064. static FILE *yyTraceFILE = 0;
  128065. static char *yyTracePrompt = 0;
  128066. #endif /* NDEBUG */
  128067. #ifndef NDEBUG
  128068. /*
  128069. ** Turn parser tracing on by giving a stream to which to write the trace
  128070. ** and a prompt to preface each trace message. Tracing is turned off
  128071. ** by making either argument NULL
  128072. **
  128073. ** Inputs:
  128074. ** <ul>
  128075. ** <li> A FILE* to which trace output should be written.
  128076. ** If NULL, then tracing is turned off.
  128077. ** <li> A prefix string written at the beginning of every
  128078. ** line of trace output. If NULL, then tracing is
  128079. ** turned off.
  128080. ** </ul>
  128081. **
  128082. ** Outputs:
  128083. ** None.
  128084. */
  128085. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  128086. yyTraceFILE = TraceFILE;
  128087. yyTracePrompt = zTracePrompt;
  128088. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  128089. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  128090. }
  128091. #endif /* NDEBUG */
  128092. #ifndef NDEBUG
  128093. /* For tracing shifts, the names of all terminals and nonterminals
  128094. ** are required. The following table supplies these names */
  128095. static const char *const yyTokenName[] = {
  128096. "$", "SEMI", "EXPLAIN", "QUERY",
  128097. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  128098. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  128099. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  128100. "TABLE", "CREATE", "IF", "NOT",
  128101. "EXISTS", "TEMP", "LP", "RP",
  128102. "AS", "WITHOUT", "COMMA", "ID",
  128103. "ABORT", "ACTION", "AFTER", "ANALYZE",
  128104. "ASC", "ATTACH", "BEFORE", "BY",
  128105. "CASCADE", "CAST", "COLUMNKW", "CONFLICT",
  128106. "DATABASE", "DESC", "DETACH", "EACH",
  128107. "FAIL", "FOR", "IGNORE", "INITIALLY",
  128108. "INSTEAD", "LIKE_KW", "MATCH", "NO",
  128109. "KEY", "OF", "OFFSET", "PRAGMA",
  128110. "RAISE", "RECURSIVE", "REPLACE", "RESTRICT",
  128111. "ROW", "TRIGGER", "VACUUM", "VIEW",
  128112. "VIRTUAL", "WITH", "REINDEX", "RENAME",
  128113. "CTIME_KW", "ANY", "OR", "AND",
  128114. "IS", "BETWEEN", "IN", "ISNULL",
  128115. "NOTNULL", "NE", "EQ", "GT",
  128116. "LE", "LT", "GE", "ESCAPE",
  128117. "BITAND", "BITOR", "LSHIFT", "RSHIFT",
  128118. "PLUS", "MINUS", "STAR", "SLASH",
  128119. "REM", "CONCAT", "COLLATE", "BITNOT",
  128120. "INDEXED", "STRING", "JOIN_KW", "CONSTRAINT",
  128121. "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
  128122. "CHECK", "REFERENCES", "AUTOINCR", "ON",
  128123. "INSERT", "DELETE", "UPDATE", "SET",
  128124. "DEFERRABLE", "FOREIGN", "DROP", "UNION",
  128125. "ALL", "EXCEPT", "INTERSECT", "SELECT",
  128126. "VALUES", "DISTINCT", "DOT", "FROM",
  128127. "JOIN", "USING", "ORDER", "GROUP",
  128128. "HAVING", "LIMIT", "WHERE", "INTO",
  128129. "FLOAT", "BLOB", "INTEGER", "VARIABLE",
  128130. "CASE", "WHEN", "THEN", "ELSE",
  128131. "INDEX", "ALTER", "ADD", "error",
  128132. "input", "cmdlist", "ecmd", "explain",
  128133. "cmdx", "cmd", "transtype", "trans_opt",
  128134. "nm", "savepoint_opt", "create_table", "create_table_args",
  128135. "createkw", "temp", "ifnotexists", "dbnm",
  128136. "columnlist", "conslist_opt", "table_options", "select",
  128137. "columnname", "carglist", "typetoken", "typename",
  128138. "signed", "plus_num", "minus_num", "ccons",
  128139. "term", "expr", "onconf", "sortorder",
  128140. "autoinc", "eidlist_opt", "refargs", "defer_subclause",
  128141. "refarg", "refact", "init_deferred_pred_opt", "conslist",
  128142. "tconscomma", "tcons", "sortlist", "eidlist",
  128143. "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
  128144. "ifexists", "fullname", "selectnowith", "oneselect",
  128145. "with", "multiselect_op", "distinct", "selcollist",
  128146. "from", "where_opt", "groupby_opt", "having_opt",
  128147. "orderby_opt", "limit_opt", "values", "nexprlist",
  128148. "exprlist", "sclp", "as", "seltablist",
  128149. "stl_prefix", "joinop", "indexed_opt", "on_opt",
  128150. "using_opt", "idlist", "setlist", "insert_cmd",
  128151. "idlist_opt", "likeop", "between_op", "in_op",
  128152. "paren_exprlist", "case_operand", "case_exprlist", "case_else",
  128153. "uniqueflag", "collate", "nmnum", "trigger_decl",
  128154. "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause",
  128155. "when_clause", "trigger_cmd", "trnm", "tridxby",
  128156. "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt",
  128157. "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken",
  128158. "lp", "anylist", "wqlist",
  128159. };
  128160. #endif /* NDEBUG */
  128161. #ifndef NDEBUG
  128162. /* For tracing reduce actions, the names of all rules are required.
  128163. */
  128164. static const char *const yyRuleName[] = {
  128165. /* 0 */ "explain ::= EXPLAIN",
  128166. /* 1 */ "explain ::= EXPLAIN QUERY PLAN",
  128167. /* 2 */ "cmdx ::= cmd",
  128168. /* 3 */ "cmd ::= BEGIN transtype trans_opt",
  128169. /* 4 */ "transtype ::=",
  128170. /* 5 */ "transtype ::= DEFERRED",
  128171. /* 6 */ "transtype ::= IMMEDIATE",
  128172. /* 7 */ "transtype ::= EXCLUSIVE",
  128173. /* 8 */ "cmd ::= COMMIT trans_opt",
  128174. /* 9 */ "cmd ::= END trans_opt",
  128175. /* 10 */ "cmd ::= ROLLBACK trans_opt",
  128176. /* 11 */ "cmd ::= SAVEPOINT nm",
  128177. /* 12 */ "cmd ::= RELEASE savepoint_opt nm",
  128178. /* 13 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  128179. /* 14 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  128180. /* 15 */ "createkw ::= CREATE",
  128181. /* 16 */ "ifnotexists ::=",
  128182. /* 17 */ "ifnotexists ::= IF NOT EXISTS",
  128183. /* 18 */ "temp ::= TEMP",
  128184. /* 19 */ "temp ::=",
  128185. /* 20 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
  128186. /* 21 */ "create_table_args ::= AS select",
  128187. /* 22 */ "table_options ::=",
  128188. /* 23 */ "table_options ::= WITHOUT nm",
  128189. /* 24 */ "columnname ::= nm typetoken",
  128190. /* 25 */ "typetoken ::=",
  128191. /* 26 */ "typetoken ::= typename LP signed RP",
  128192. /* 27 */ "typetoken ::= typename LP signed COMMA signed RP",
  128193. /* 28 */ "typename ::= typename ID|STRING",
  128194. /* 29 */ "ccons ::= CONSTRAINT nm",
  128195. /* 30 */ "ccons ::= DEFAULT term",
  128196. /* 31 */ "ccons ::= DEFAULT LP expr RP",
  128197. /* 32 */ "ccons ::= DEFAULT PLUS term",
  128198. /* 33 */ "ccons ::= DEFAULT MINUS term",
  128199. /* 34 */ "ccons ::= DEFAULT ID|INDEXED",
  128200. /* 35 */ "ccons ::= NOT NULL onconf",
  128201. /* 36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  128202. /* 37 */ "ccons ::= UNIQUE onconf",
  128203. /* 38 */ "ccons ::= CHECK LP expr RP",
  128204. /* 39 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
  128205. /* 40 */ "ccons ::= defer_subclause",
  128206. /* 41 */ "ccons ::= COLLATE ID|STRING",
  128207. /* 42 */ "autoinc ::=",
  128208. /* 43 */ "autoinc ::= AUTOINCR",
  128209. /* 44 */ "refargs ::=",
  128210. /* 45 */ "refargs ::= refargs refarg",
  128211. /* 46 */ "refarg ::= MATCH nm",
  128212. /* 47 */ "refarg ::= ON INSERT refact",
  128213. /* 48 */ "refarg ::= ON DELETE refact",
  128214. /* 49 */ "refarg ::= ON UPDATE refact",
  128215. /* 50 */ "refact ::= SET NULL",
  128216. /* 51 */ "refact ::= SET DEFAULT",
  128217. /* 52 */ "refact ::= CASCADE",
  128218. /* 53 */ "refact ::= RESTRICT",
  128219. /* 54 */ "refact ::= NO ACTION",
  128220. /* 55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  128221. /* 56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  128222. /* 57 */ "init_deferred_pred_opt ::=",
  128223. /* 58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  128224. /* 59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  128225. /* 60 */ "conslist_opt ::=",
  128226. /* 61 */ "tconscomma ::= COMMA",
  128227. /* 62 */ "tcons ::= CONSTRAINT nm",
  128228. /* 63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
  128229. /* 64 */ "tcons ::= UNIQUE LP sortlist RP onconf",
  128230. /* 65 */ "tcons ::= CHECK LP expr RP onconf",
  128231. /* 66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
  128232. /* 67 */ "defer_subclause_opt ::=",
  128233. /* 68 */ "onconf ::=",
  128234. /* 69 */ "onconf ::= ON CONFLICT resolvetype",
  128235. /* 70 */ "orconf ::=",
  128236. /* 71 */ "orconf ::= OR resolvetype",
  128237. /* 72 */ "resolvetype ::= IGNORE",
  128238. /* 73 */ "resolvetype ::= REPLACE",
  128239. /* 74 */ "cmd ::= DROP TABLE ifexists fullname",
  128240. /* 75 */ "ifexists ::= IF EXISTS",
  128241. /* 76 */ "ifexists ::=",
  128242. /* 77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
  128243. /* 78 */ "cmd ::= DROP VIEW ifexists fullname",
  128244. /* 79 */ "cmd ::= select",
  128245. /* 80 */ "select ::= with selectnowith",
  128246. /* 81 */ "selectnowith ::= selectnowith multiselect_op oneselect",
  128247. /* 82 */ "multiselect_op ::= UNION",
  128248. /* 83 */ "multiselect_op ::= UNION ALL",
  128249. /* 84 */ "multiselect_op ::= EXCEPT|INTERSECT",
  128250. /* 85 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  128251. /* 86 */ "values ::= VALUES LP nexprlist RP",
  128252. /* 87 */ "values ::= values COMMA LP exprlist RP",
  128253. /* 88 */ "distinct ::= DISTINCT",
  128254. /* 89 */ "distinct ::= ALL",
  128255. /* 90 */ "distinct ::=",
  128256. /* 91 */ "sclp ::=",
  128257. /* 92 */ "selcollist ::= sclp expr as",
  128258. /* 93 */ "selcollist ::= sclp STAR",
  128259. /* 94 */ "selcollist ::= sclp nm DOT STAR",
  128260. /* 95 */ "as ::= AS nm",
  128261. /* 96 */ "as ::=",
  128262. /* 97 */ "from ::=",
  128263. /* 98 */ "from ::= FROM seltablist",
  128264. /* 99 */ "stl_prefix ::= seltablist joinop",
  128265. /* 100 */ "stl_prefix ::=",
  128266. /* 101 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  128267. /* 102 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
  128268. /* 103 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  128269. /* 104 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  128270. /* 105 */ "dbnm ::=",
  128271. /* 106 */ "dbnm ::= DOT nm",
  128272. /* 107 */ "fullname ::= nm dbnm",
  128273. /* 108 */ "joinop ::= COMMA|JOIN",
  128274. /* 109 */ "joinop ::= JOIN_KW JOIN",
  128275. /* 110 */ "joinop ::= JOIN_KW nm JOIN",
  128276. /* 111 */ "joinop ::= JOIN_KW nm nm JOIN",
  128277. /* 112 */ "on_opt ::= ON expr",
  128278. /* 113 */ "on_opt ::=",
  128279. /* 114 */ "indexed_opt ::=",
  128280. /* 115 */ "indexed_opt ::= INDEXED BY nm",
  128281. /* 116 */ "indexed_opt ::= NOT INDEXED",
  128282. /* 117 */ "using_opt ::= USING LP idlist RP",
  128283. /* 118 */ "using_opt ::=",
  128284. /* 119 */ "orderby_opt ::=",
  128285. /* 120 */ "orderby_opt ::= ORDER BY sortlist",
  128286. /* 121 */ "sortlist ::= sortlist COMMA expr sortorder",
  128287. /* 122 */ "sortlist ::= expr sortorder",
  128288. /* 123 */ "sortorder ::= ASC",
  128289. /* 124 */ "sortorder ::= DESC",
  128290. /* 125 */ "sortorder ::=",
  128291. /* 126 */ "groupby_opt ::=",
  128292. /* 127 */ "groupby_opt ::= GROUP BY nexprlist",
  128293. /* 128 */ "having_opt ::=",
  128294. /* 129 */ "having_opt ::= HAVING expr",
  128295. /* 130 */ "limit_opt ::=",
  128296. /* 131 */ "limit_opt ::= LIMIT expr",
  128297. /* 132 */ "limit_opt ::= LIMIT expr OFFSET expr",
  128298. /* 133 */ "limit_opt ::= LIMIT expr COMMA expr",
  128299. /* 134 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
  128300. /* 135 */ "where_opt ::=",
  128301. /* 136 */ "where_opt ::= WHERE expr",
  128302. /* 137 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
  128303. /* 138 */ "setlist ::= setlist COMMA nm EQ expr",
  128304. /* 139 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
  128305. /* 140 */ "setlist ::= nm EQ expr",
  128306. /* 141 */ "setlist ::= LP idlist RP EQ expr",
  128307. /* 142 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
  128308. /* 143 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
  128309. /* 144 */ "insert_cmd ::= INSERT orconf",
  128310. /* 145 */ "insert_cmd ::= REPLACE",
  128311. /* 146 */ "idlist_opt ::=",
  128312. /* 147 */ "idlist_opt ::= LP idlist RP",
  128313. /* 148 */ "idlist ::= idlist COMMA nm",
  128314. /* 149 */ "idlist ::= nm",
  128315. /* 150 */ "expr ::= LP expr RP",
  128316. /* 151 */ "term ::= NULL",
  128317. /* 152 */ "expr ::= ID|INDEXED",
  128318. /* 153 */ "expr ::= JOIN_KW",
  128319. /* 154 */ "expr ::= nm DOT nm",
  128320. /* 155 */ "expr ::= nm DOT nm DOT nm",
  128321. /* 156 */ "term ::= FLOAT|BLOB",
  128322. /* 157 */ "term ::= STRING",
  128323. /* 158 */ "term ::= INTEGER",
  128324. /* 159 */ "expr ::= VARIABLE",
  128325. /* 160 */ "expr ::= expr COLLATE ID|STRING",
  128326. /* 161 */ "expr ::= CAST LP expr AS typetoken RP",
  128327. /* 162 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
  128328. /* 163 */ "expr ::= ID|INDEXED LP STAR RP",
  128329. /* 164 */ "term ::= CTIME_KW",
  128330. /* 165 */ "expr ::= LP nexprlist COMMA expr RP",
  128331. /* 166 */ "expr ::= expr AND expr",
  128332. /* 167 */ "expr ::= expr OR expr",
  128333. /* 168 */ "expr ::= expr LT|GT|GE|LE expr",
  128334. /* 169 */ "expr ::= expr EQ|NE expr",
  128335. /* 170 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  128336. /* 171 */ "expr ::= expr PLUS|MINUS expr",
  128337. /* 172 */ "expr ::= expr STAR|SLASH|REM expr",
  128338. /* 173 */ "expr ::= expr CONCAT expr",
  128339. /* 174 */ "likeop ::= NOT LIKE_KW|MATCH",
  128340. /* 175 */ "expr ::= expr likeop expr",
  128341. /* 176 */ "expr ::= expr likeop expr ESCAPE expr",
  128342. /* 177 */ "expr ::= expr ISNULL|NOTNULL",
  128343. /* 178 */ "expr ::= expr NOT NULL",
  128344. /* 179 */ "expr ::= expr IS expr",
  128345. /* 180 */ "expr ::= expr IS NOT expr",
  128346. /* 181 */ "expr ::= NOT expr",
  128347. /* 182 */ "expr ::= BITNOT expr",
  128348. /* 183 */ "expr ::= MINUS expr",
  128349. /* 184 */ "expr ::= PLUS expr",
  128350. /* 185 */ "between_op ::= BETWEEN",
  128351. /* 186 */ "between_op ::= NOT BETWEEN",
  128352. /* 187 */ "expr ::= expr between_op expr AND expr",
  128353. /* 188 */ "in_op ::= IN",
  128354. /* 189 */ "in_op ::= NOT IN",
  128355. /* 190 */ "expr ::= expr in_op LP exprlist RP",
  128356. /* 191 */ "expr ::= LP select RP",
  128357. /* 192 */ "expr ::= expr in_op LP select RP",
  128358. /* 193 */ "expr ::= expr in_op nm dbnm paren_exprlist",
  128359. /* 194 */ "expr ::= EXISTS LP select RP",
  128360. /* 195 */ "expr ::= CASE case_operand case_exprlist case_else END",
  128361. /* 196 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  128362. /* 197 */ "case_exprlist ::= WHEN expr THEN expr",
  128363. /* 198 */ "case_else ::= ELSE expr",
  128364. /* 199 */ "case_else ::=",
  128365. /* 200 */ "case_operand ::= expr",
  128366. /* 201 */ "case_operand ::=",
  128367. /* 202 */ "exprlist ::=",
  128368. /* 203 */ "nexprlist ::= nexprlist COMMA expr",
  128369. /* 204 */ "nexprlist ::= expr",
  128370. /* 205 */ "paren_exprlist ::=",
  128371. /* 206 */ "paren_exprlist ::= LP exprlist RP",
  128372. /* 207 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
  128373. /* 208 */ "uniqueflag ::= UNIQUE",
  128374. /* 209 */ "uniqueflag ::=",
  128375. /* 210 */ "eidlist_opt ::=",
  128376. /* 211 */ "eidlist_opt ::= LP eidlist RP",
  128377. /* 212 */ "eidlist ::= eidlist COMMA nm collate sortorder",
  128378. /* 213 */ "eidlist ::= nm collate sortorder",
  128379. /* 214 */ "collate ::=",
  128380. /* 215 */ "collate ::= COLLATE ID|STRING",
  128381. /* 216 */ "cmd ::= DROP INDEX ifexists fullname",
  128382. /* 217 */ "cmd ::= VACUUM",
  128383. /* 218 */ "cmd ::= VACUUM nm",
  128384. /* 219 */ "cmd ::= PRAGMA nm dbnm",
  128385. /* 220 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  128386. /* 221 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  128387. /* 222 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  128388. /* 223 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  128389. /* 224 */ "plus_num ::= PLUS INTEGER|FLOAT",
  128390. /* 225 */ "minus_num ::= MINUS INTEGER|FLOAT",
  128391. /* 226 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  128392. /* 227 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  128393. /* 228 */ "trigger_time ::= BEFORE",
  128394. /* 229 */ "trigger_time ::= AFTER",
  128395. /* 230 */ "trigger_time ::= INSTEAD OF",
  128396. /* 231 */ "trigger_time ::=",
  128397. /* 232 */ "trigger_event ::= DELETE|INSERT",
  128398. /* 233 */ "trigger_event ::= UPDATE",
  128399. /* 234 */ "trigger_event ::= UPDATE OF idlist",
  128400. /* 235 */ "when_clause ::=",
  128401. /* 236 */ "when_clause ::= WHEN expr",
  128402. /* 237 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  128403. /* 238 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  128404. /* 239 */ "trnm ::= nm DOT nm",
  128405. /* 240 */ "tridxby ::= INDEXED BY nm",
  128406. /* 241 */ "tridxby ::= NOT INDEXED",
  128407. /* 242 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
  128408. /* 243 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
  128409. /* 244 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
  128410. /* 245 */ "trigger_cmd ::= select",
  128411. /* 246 */ "expr ::= RAISE LP IGNORE RP",
  128412. /* 247 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  128413. /* 248 */ "raisetype ::= ROLLBACK",
  128414. /* 249 */ "raisetype ::= ABORT",
  128415. /* 250 */ "raisetype ::= FAIL",
  128416. /* 251 */ "cmd ::= DROP TRIGGER ifexists fullname",
  128417. /* 252 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  128418. /* 253 */ "cmd ::= DETACH database_kw_opt expr",
  128419. /* 254 */ "key_opt ::=",
  128420. /* 255 */ "key_opt ::= KEY expr",
  128421. /* 256 */ "cmd ::= REINDEX",
  128422. /* 257 */ "cmd ::= REINDEX nm dbnm",
  128423. /* 258 */ "cmd ::= ANALYZE",
  128424. /* 259 */ "cmd ::= ANALYZE nm dbnm",
  128425. /* 260 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  128426. /* 261 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
  128427. /* 262 */ "add_column_fullname ::= fullname",
  128428. /* 263 */ "cmd ::= create_vtab",
  128429. /* 264 */ "cmd ::= create_vtab LP vtabarglist RP",
  128430. /* 265 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  128431. /* 266 */ "vtabarg ::=",
  128432. /* 267 */ "vtabargtoken ::= ANY",
  128433. /* 268 */ "vtabargtoken ::= lp anylist RP",
  128434. /* 269 */ "lp ::= LP",
  128435. /* 270 */ "with ::=",
  128436. /* 271 */ "with ::= WITH wqlist",
  128437. /* 272 */ "with ::= WITH RECURSIVE wqlist",
  128438. /* 273 */ "wqlist ::= nm eidlist_opt AS LP select RP",
  128439. /* 274 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
  128440. /* 275 */ "input ::= cmdlist",
  128441. /* 276 */ "cmdlist ::= cmdlist ecmd",
  128442. /* 277 */ "cmdlist ::= ecmd",
  128443. /* 278 */ "ecmd ::= SEMI",
  128444. /* 279 */ "ecmd ::= explain cmdx SEMI",
  128445. /* 280 */ "explain ::=",
  128446. /* 281 */ "trans_opt ::=",
  128447. /* 282 */ "trans_opt ::= TRANSACTION",
  128448. /* 283 */ "trans_opt ::= TRANSACTION nm",
  128449. /* 284 */ "savepoint_opt ::= SAVEPOINT",
  128450. /* 285 */ "savepoint_opt ::=",
  128451. /* 286 */ "cmd ::= create_table create_table_args",
  128452. /* 287 */ "columnlist ::= columnlist COMMA columnname carglist",
  128453. /* 288 */ "columnlist ::= columnname carglist",
  128454. /* 289 */ "nm ::= ID|INDEXED",
  128455. /* 290 */ "nm ::= STRING",
  128456. /* 291 */ "nm ::= JOIN_KW",
  128457. /* 292 */ "typetoken ::= typename",
  128458. /* 293 */ "typename ::= ID|STRING",
  128459. /* 294 */ "signed ::= plus_num",
  128460. /* 295 */ "signed ::= minus_num",
  128461. /* 296 */ "carglist ::= carglist ccons",
  128462. /* 297 */ "carglist ::=",
  128463. /* 298 */ "ccons ::= NULL onconf",
  128464. /* 299 */ "conslist_opt ::= COMMA conslist",
  128465. /* 300 */ "conslist ::= conslist tconscomma tcons",
  128466. /* 301 */ "conslist ::= tcons",
  128467. /* 302 */ "tconscomma ::=",
  128468. /* 303 */ "defer_subclause_opt ::= defer_subclause",
  128469. /* 304 */ "resolvetype ::= raisetype",
  128470. /* 305 */ "selectnowith ::= oneselect",
  128471. /* 306 */ "oneselect ::= values",
  128472. /* 307 */ "sclp ::= selcollist COMMA",
  128473. /* 308 */ "as ::= ID|STRING",
  128474. /* 309 */ "expr ::= term",
  128475. /* 310 */ "likeop ::= LIKE_KW|MATCH",
  128476. /* 311 */ "exprlist ::= nexprlist",
  128477. /* 312 */ "nmnum ::= plus_num",
  128478. /* 313 */ "nmnum ::= nm",
  128479. /* 314 */ "nmnum ::= ON",
  128480. /* 315 */ "nmnum ::= DELETE",
  128481. /* 316 */ "nmnum ::= DEFAULT",
  128482. /* 317 */ "plus_num ::= INTEGER|FLOAT",
  128483. /* 318 */ "foreach_clause ::=",
  128484. /* 319 */ "foreach_clause ::= FOR EACH ROW",
  128485. /* 320 */ "trnm ::= nm",
  128486. /* 321 */ "tridxby ::=",
  128487. /* 322 */ "database_kw_opt ::= DATABASE",
  128488. /* 323 */ "database_kw_opt ::=",
  128489. /* 324 */ "kwcolumn_opt ::=",
  128490. /* 325 */ "kwcolumn_opt ::= COLUMNKW",
  128491. /* 326 */ "vtabarglist ::= vtabarg",
  128492. /* 327 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  128493. /* 328 */ "vtabarg ::= vtabarg vtabargtoken",
  128494. /* 329 */ "anylist ::=",
  128495. /* 330 */ "anylist ::= anylist LP anylist RP",
  128496. /* 331 */ "anylist ::= anylist ANY",
  128497. };
  128498. #endif /* NDEBUG */
  128499. #if YYSTACKDEPTH<=0
  128500. /*
  128501. ** Try to increase the size of the parser stack. Return the number
  128502. ** of errors. Return 0 on success.
  128503. */
  128504. static int yyGrowStack(yyParser *p){
  128505. int newSize;
  128506. int idx;
  128507. yyStackEntry *pNew;
  128508. newSize = p->yystksz*2 + 100;
  128509. idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
  128510. if( p->yystack==&p->yystk0 ){
  128511. pNew = malloc(newSize*sizeof(pNew[0]));
  128512. if( pNew ) pNew[0] = p->yystk0;
  128513. }else{
  128514. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  128515. }
  128516. if( pNew ){
  128517. p->yystack = pNew;
  128518. p->yytos = &p->yystack[idx];
  128519. #ifndef NDEBUG
  128520. if( yyTraceFILE ){
  128521. fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
  128522. yyTracePrompt, p->yystksz, newSize);
  128523. }
  128524. #endif
  128525. p->yystksz = newSize;
  128526. }
  128527. return pNew==0;
  128528. }
  128529. #endif
  128530. /* Datatype of the argument to the memory allocated passed as the
  128531. ** second argument to sqlite3ParserAlloc() below. This can be changed by
  128532. ** putting an appropriate #define in the %include section of the input
  128533. ** grammar.
  128534. */
  128535. #ifndef YYMALLOCARGTYPE
  128536. # define YYMALLOCARGTYPE size_t
  128537. #endif
  128538. /* Initialize a new parser that has already been allocated.
  128539. */
  128540. SQLITE_PRIVATE void sqlite3ParserInit(void *yypParser){
  128541. yyParser *pParser = (yyParser*)yypParser;
  128542. #ifdef YYTRACKMAXSTACKDEPTH
  128543. pParser->yyhwm = 0;
  128544. #endif
  128545. #if YYSTACKDEPTH<=0
  128546. pParser->yytos = NULL;
  128547. pParser->yystack = NULL;
  128548. pParser->yystksz = 0;
  128549. if( yyGrowStack(pParser) ){
  128550. pParser->yystack = &pParser->yystk0;
  128551. pParser->yystksz = 1;
  128552. }
  128553. #endif
  128554. #ifndef YYNOERRORRECOVERY
  128555. pParser->yyerrcnt = -1;
  128556. #endif
  128557. pParser->yytos = pParser->yystack;
  128558. pParser->yystack[0].stateno = 0;
  128559. pParser->yystack[0].major = 0;
  128560. }
  128561. #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
  128562. /*
  128563. ** This function allocates a new parser.
  128564. ** The only argument is a pointer to a function which works like
  128565. ** malloc.
  128566. **
  128567. ** Inputs:
  128568. ** A pointer to the function used to allocate memory.
  128569. **
  128570. ** Outputs:
  128571. ** A pointer to a parser. This pointer is used in subsequent calls
  128572. ** to sqlite3Parser and sqlite3ParserFree.
  128573. */
  128574. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){
  128575. yyParser *pParser;
  128576. pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
  128577. if( pParser ) sqlite3ParserInit(pParser);
  128578. return pParser;
  128579. }
  128580. #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
  128581. /* The following function deletes the "minor type" or semantic value
  128582. ** associated with a symbol. The symbol can be either a terminal
  128583. ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
  128584. ** a pointer to the value to be deleted. The code used to do the
  128585. ** deletions is derived from the %destructor and/or %token_destructor
  128586. ** directives of the input grammar.
  128587. */
  128588. static void yy_destructor(
  128589. yyParser *yypParser, /* The parser */
  128590. YYCODETYPE yymajor, /* Type code for object to destroy */
  128591. YYMINORTYPE *yypminor /* The object to be destroyed */
  128592. ){
  128593. sqlite3ParserARG_FETCH;
  128594. switch( yymajor ){
  128595. /* Here is inserted the actions which take place when a
  128596. ** terminal or non-terminal is destroyed. This can happen
  128597. ** when the symbol is popped from the stack during a
  128598. ** reduce or during error processing or when a parser is
  128599. ** being destroyed before it is finished parsing.
  128600. **
  128601. ** Note: during a reduce, the only symbols destroyed are those
  128602. ** which appear on the RHS of the rule, but which are *not* used
  128603. ** inside the C code.
  128604. */
  128605. /********* Begin destructor definitions ***************************************/
  128606. case 163: /* select */
  128607. case 194: /* selectnowith */
  128608. case 195: /* oneselect */
  128609. case 206: /* values */
  128610. {
  128611. sqlite3SelectDelete(pParse->db, (yypminor->yy243));
  128612. }
  128613. break;
  128614. case 172: /* term */
  128615. case 173: /* expr */
  128616. {
  128617. sqlite3ExprDelete(pParse->db, (yypminor->yy190).pExpr);
  128618. }
  128619. break;
  128620. case 177: /* eidlist_opt */
  128621. case 186: /* sortlist */
  128622. case 187: /* eidlist */
  128623. case 199: /* selcollist */
  128624. case 202: /* groupby_opt */
  128625. case 204: /* orderby_opt */
  128626. case 207: /* nexprlist */
  128627. case 208: /* exprlist */
  128628. case 209: /* sclp */
  128629. case 218: /* setlist */
  128630. case 224: /* paren_exprlist */
  128631. case 226: /* case_exprlist */
  128632. {
  128633. sqlite3ExprListDelete(pParse->db, (yypminor->yy148));
  128634. }
  128635. break;
  128636. case 193: /* fullname */
  128637. case 200: /* from */
  128638. case 211: /* seltablist */
  128639. case 212: /* stl_prefix */
  128640. {
  128641. sqlite3SrcListDelete(pParse->db, (yypminor->yy185));
  128642. }
  128643. break;
  128644. case 196: /* with */
  128645. case 250: /* wqlist */
  128646. {
  128647. sqlite3WithDelete(pParse->db, (yypminor->yy285));
  128648. }
  128649. break;
  128650. case 201: /* where_opt */
  128651. case 203: /* having_opt */
  128652. case 215: /* on_opt */
  128653. case 225: /* case_operand */
  128654. case 227: /* case_else */
  128655. case 236: /* when_clause */
  128656. case 241: /* key_opt */
  128657. {
  128658. sqlite3ExprDelete(pParse->db, (yypminor->yy72));
  128659. }
  128660. break;
  128661. case 216: /* using_opt */
  128662. case 217: /* idlist */
  128663. case 220: /* idlist_opt */
  128664. {
  128665. sqlite3IdListDelete(pParse->db, (yypminor->yy254));
  128666. }
  128667. break;
  128668. case 232: /* trigger_cmd_list */
  128669. case 237: /* trigger_cmd */
  128670. {
  128671. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy145));
  128672. }
  128673. break;
  128674. case 234: /* trigger_event */
  128675. {
  128676. sqlite3IdListDelete(pParse->db, (yypminor->yy332).b);
  128677. }
  128678. break;
  128679. /********* End destructor definitions *****************************************/
  128680. default: break; /* If no destructor action specified: do nothing */
  128681. }
  128682. }
  128683. /*
  128684. ** Pop the parser's stack once.
  128685. **
  128686. ** If there is a destructor routine associated with the token which
  128687. ** is popped from the stack, then call it.
  128688. */
  128689. static void yy_pop_parser_stack(yyParser *pParser){
  128690. yyStackEntry *yytos;
  128691. assert( pParser->yytos!=0 );
  128692. assert( pParser->yytos > pParser->yystack );
  128693. yytos = pParser->yytos--;
  128694. #ifndef NDEBUG
  128695. if( yyTraceFILE ){
  128696. fprintf(yyTraceFILE,"%sPopping %s\n",
  128697. yyTracePrompt,
  128698. yyTokenName[yytos->major]);
  128699. }
  128700. #endif
  128701. yy_destructor(pParser, yytos->major, &yytos->minor);
  128702. }
  128703. /*
  128704. ** Clear all secondary memory allocations from the parser
  128705. */
  128706. SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){
  128707. yyParser *pParser = (yyParser*)p;
  128708. while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
  128709. #if YYSTACKDEPTH<=0
  128710. if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
  128711. #endif
  128712. }
  128713. #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
  128714. /*
  128715. ** Deallocate and destroy a parser. Destructors are called for
  128716. ** all stack elements before shutting the parser down.
  128717. **
  128718. ** If the YYPARSEFREENEVERNULL macro exists (for example because it
  128719. ** is defined in a %include section of the input grammar) then it is
  128720. ** assumed that the input pointer is never NULL.
  128721. */
  128722. SQLITE_PRIVATE void sqlite3ParserFree(
  128723. void *p, /* The parser to be deleted */
  128724. void (*freeProc)(void*) /* Function used to reclaim memory */
  128725. ){
  128726. #ifndef YYPARSEFREENEVERNULL
  128727. if( p==0 ) return;
  128728. #endif
  128729. sqlite3ParserFinalize(p);
  128730. (*freeProc)(p);
  128731. }
  128732. #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
  128733. /*
  128734. ** Return the peak depth of the stack for a parser.
  128735. */
  128736. #ifdef YYTRACKMAXSTACKDEPTH
  128737. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  128738. yyParser *pParser = (yyParser*)p;
  128739. return pParser->yyhwm;
  128740. }
  128741. #endif
  128742. /*
  128743. ** Find the appropriate action for a parser given the terminal
  128744. ** look-ahead token iLookAhead.
  128745. */
  128746. static unsigned int yy_find_shift_action(
  128747. yyParser *pParser, /* The parser */
  128748. YYCODETYPE iLookAhead /* The look-ahead token */
  128749. ){
  128750. int i;
  128751. int stateno = pParser->yytos->stateno;
  128752. if( stateno>=YY_MIN_REDUCE ) return stateno;
  128753. assert( stateno <= YY_SHIFT_COUNT );
  128754. do{
  128755. i = yy_shift_ofst[stateno];
  128756. assert( iLookAhead!=YYNOCODE );
  128757. i += iLookAhead;
  128758. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  128759. #ifdef YYFALLBACK
  128760. YYCODETYPE iFallback; /* Fallback token */
  128761. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  128762. && (iFallback = yyFallback[iLookAhead])!=0 ){
  128763. #ifndef NDEBUG
  128764. if( yyTraceFILE ){
  128765. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  128766. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  128767. }
  128768. #endif
  128769. assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  128770. iLookAhead = iFallback;
  128771. continue;
  128772. }
  128773. #endif
  128774. #ifdef YYWILDCARD
  128775. {
  128776. int j = i - iLookAhead + YYWILDCARD;
  128777. if(
  128778. #if YY_SHIFT_MIN+YYWILDCARD<0
  128779. j>=0 &&
  128780. #endif
  128781. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  128782. j<YY_ACTTAB_COUNT &&
  128783. #endif
  128784. yy_lookahead[j]==YYWILDCARD && iLookAhead>0
  128785. ){
  128786. #ifndef NDEBUG
  128787. if( yyTraceFILE ){
  128788. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  128789. yyTracePrompt, yyTokenName[iLookAhead],
  128790. yyTokenName[YYWILDCARD]);
  128791. }
  128792. #endif /* NDEBUG */
  128793. return yy_action[j];
  128794. }
  128795. }
  128796. #endif /* YYWILDCARD */
  128797. return yy_default[stateno];
  128798. }else{
  128799. return yy_action[i];
  128800. }
  128801. }while(1);
  128802. }
  128803. /*
  128804. ** Find the appropriate action for a parser given the non-terminal
  128805. ** look-ahead token iLookAhead.
  128806. */
  128807. static int yy_find_reduce_action(
  128808. int stateno, /* Current state number */
  128809. YYCODETYPE iLookAhead /* The look-ahead token */
  128810. ){
  128811. int i;
  128812. #ifdef YYERRORSYMBOL
  128813. if( stateno>YY_REDUCE_COUNT ){
  128814. return yy_default[stateno];
  128815. }
  128816. #else
  128817. assert( stateno<=YY_REDUCE_COUNT );
  128818. #endif
  128819. i = yy_reduce_ofst[stateno];
  128820. assert( i!=YY_REDUCE_USE_DFLT );
  128821. assert( iLookAhead!=YYNOCODE );
  128822. i += iLookAhead;
  128823. #ifdef YYERRORSYMBOL
  128824. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  128825. return yy_default[stateno];
  128826. }
  128827. #else
  128828. assert( i>=0 && i<YY_ACTTAB_COUNT );
  128829. assert( yy_lookahead[i]==iLookAhead );
  128830. #endif
  128831. return yy_action[i];
  128832. }
  128833. /*
  128834. ** The following routine is called if the stack overflows.
  128835. */
  128836. static void yyStackOverflow(yyParser *yypParser){
  128837. sqlite3ParserARG_FETCH;
  128838. #ifndef NDEBUG
  128839. if( yyTraceFILE ){
  128840. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  128841. }
  128842. #endif
  128843. while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
  128844. /* Here code is inserted which will execute if the parser
  128845. ** stack every overflows */
  128846. /******** Begin %stack_overflow code ******************************************/
  128847. sqlite3ErrorMsg(pParse, "parser stack overflow");
  128848. /******** End %stack_overflow code ********************************************/
  128849. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  128850. }
  128851. /*
  128852. ** Print tracing information for a SHIFT action
  128853. */
  128854. #ifndef NDEBUG
  128855. static void yyTraceShift(yyParser *yypParser, int yyNewState){
  128856. if( yyTraceFILE ){
  128857. if( yyNewState<YYNSTATE ){
  128858. fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n",
  128859. yyTracePrompt,yyTokenName[yypParser->yytos->major],
  128860. yyNewState);
  128861. }else{
  128862. fprintf(yyTraceFILE,"%sShift '%s'\n",
  128863. yyTracePrompt,yyTokenName[yypParser->yytos->major]);
  128864. }
  128865. }
  128866. }
  128867. #else
  128868. # define yyTraceShift(X,Y)
  128869. #endif
  128870. /*
  128871. ** Perform a shift action.
  128872. */
  128873. static void yy_shift(
  128874. yyParser *yypParser, /* The parser to be shifted */
  128875. int yyNewState, /* The new state to shift in */
  128876. int yyMajor, /* The major token to shift in */
  128877. sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */
  128878. ){
  128879. yyStackEntry *yytos;
  128880. yypParser->yytos++;
  128881. #ifdef YYTRACKMAXSTACKDEPTH
  128882. if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
  128883. yypParser->yyhwm++;
  128884. assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
  128885. }
  128886. #endif
  128887. #if YYSTACKDEPTH>0
  128888. if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH] ){
  128889. yypParser->yytos--;
  128890. yyStackOverflow(yypParser);
  128891. return;
  128892. }
  128893. #else
  128894. if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
  128895. if( yyGrowStack(yypParser) ){
  128896. yypParser->yytos--;
  128897. yyStackOverflow(yypParser);
  128898. return;
  128899. }
  128900. }
  128901. #endif
  128902. if( yyNewState > YY_MAX_SHIFT ){
  128903. yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
  128904. }
  128905. yytos = yypParser->yytos;
  128906. yytos->stateno = (YYACTIONTYPE)yyNewState;
  128907. yytos->major = (YYCODETYPE)yyMajor;
  128908. yytos->minor.yy0 = yyMinor;
  128909. yyTraceShift(yypParser, yyNewState);
  128910. }
  128911. /* The following table contains information about every rule that
  128912. ** is used during the reduce.
  128913. */
  128914. static const struct {
  128915. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  128916. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  128917. } yyRuleInfo[] = {
  128918. { 147, 1 },
  128919. { 147, 3 },
  128920. { 148, 1 },
  128921. { 149, 3 },
  128922. { 150, 0 },
  128923. { 150, 1 },
  128924. { 150, 1 },
  128925. { 150, 1 },
  128926. { 149, 2 },
  128927. { 149, 2 },
  128928. { 149, 2 },
  128929. { 149, 2 },
  128930. { 149, 3 },
  128931. { 149, 5 },
  128932. { 154, 6 },
  128933. { 156, 1 },
  128934. { 158, 0 },
  128935. { 158, 3 },
  128936. { 157, 1 },
  128937. { 157, 0 },
  128938. { 155, 5 },
  128939. { 155, 2 },
  128940. { 162, 0 },
  128941. { 162, 2 },
  128942. { 164, 2 },
  128943. { 166, 0 },
  128944. { 166, 4 },
  128945. { 166, 6 },
  128946. { 167, 2 },
  128947. { 171, 2 },
  128948. { 171, 2 },
  128949. { 171, 4 },
  128950. { 171, 3 },
  128951. { 171, 3 },
  128952. { 171, 2 },
  128953. { 171, 3 },
  128954. { 171, 5 },
  128955. { 171, 2 },
  128956. { 171, 4 },
  128957. { 171, 4 },
  128958. { 171, 1 },
  128959. { 171, 2 },
  128960. { 176, 0 },
  128961. { 176, 1 },
  128962. { 178, 0 },
  128963. { 178, 2 },
  128964. { 180, 2 },
  128965. { 180, 3 },
  128966. { 180, 3 },
  128967. { 180, 3 },
  128968. { 181, 2 },
  128969. { 181, 2 },
  128970. { 181, 1 },
  128971. { 181, 1 },
  128972. { 181, 2 },
  128973. { 179, 3 },
  128974. { 179, 2 },
  128975. { 182, 0 },
  128976. { 182, 2 },
  128977. { 182, 2 },
  128978. { 161, 0 },
  128979. { 184, 1 },
  128980. { 185, 2 },
  128981. { 185, 7 },
  128982. { 185, 5 },
  128983. { 185, 5 },
  128984. { 185, 10 },
  128985. { 188, 0 },
  128986. { 174, 0 },
  128987. { 174, 3 },
  128988. { 189, 0 },
  128989. { 189, 2 },
  128990. { 190, 1 },
  128991. { 190, 1 },
  128992. { 149, 4 },
  128993. { 192, 2 },
  128994. { 192, 0 },
  128995. { 149, 9 },
  128996. { 149, 4 },
  128997. { 149, 1 },
  128998. { 163, 2 },
  128999. { 194, 3 },
  129000. { 197, 1 },
  129001. { 197, 2 },
  129002. { 197, 1 },
  129003. { 195, 9 },
  129004. { 206, 4 },
  129005. { 206, 5 },
  129006. { 198, 1 },
  129007. { 198, 1 },
  129008. { 198, 0 },
  129009. { 209, 0 },
  129010. { 199, 3 },
  129011. { 199, 2 },
  129012. { 199, 4 },
  129013. { 210, 2 },
  129014. { 210, 0 },
  129015. { 200, 0 },
  129016. { 200, 2 },
  129017. { 212, 2 },
  129018. { 212, 0 },
  129019. { 211, 7 },
  129020. { 211, 9 },
  129021. { 211, 7 },
  129022. { 211, 7 },
  129023. { 159, 0 },
  129024. { 159, 2 },
  129025. { 193, 2 },
  129026. { 213, 1 },
  129027. { 213, 2 },
  129028. { 213, 3 },
  129029. { 213, 4 },
  129030. { 215, 2 },
  129031. { 215, 0 },
  129032. { 214, 0 },
  129033. { 214, 3 },
  129034. { 214, 2 },
  129035. { 216, 4 },
  129036. { 216, 0 },
  129037. { 204, 0 },
  129038. { 204, 3 },
  129039. { 186, 4 },
  129040. { 186, 2 },
  129041. { 175, 1 },
  129042. { 175, 1 },
  129043. { 175, 0 },
  129044. { 202, 0 },
  129045. { 202, 3 },
  129046. { 203, 0 },
  129047. { 203, 2 },
  129048. { 205, 0 },
  129049. { 205, 2 },
  129050. { 205, 4 },
  129051. { 205, 4 },
  129052. { 149, 6 },
  129053. { 201, 0 },
  129054. { 201, 2 },
  129055. { 149, 8 },
  129056. { 218, 5 },
  129057. { 218, 7 },
  129058. { 218, 3 },
  129059. { 218, 5 },
  129060. { 149, 6 },
  129061. { 149, 7 },
  129062. { 219, 2 },
  129063. { 219, 1 },
  129064. { 220, 0 },
  129065. { 220, 3 },
  129066. { 217, 3 },
  129067. { 217, 1 },
  129068. { 173, 3 },
  129069. { 172, 1 },
  129070. { 173, 1 },
  129071. { 173, 1 },
  129072. { 173, 3 },
  129073. { 173, 5 },
  129074. { 172, 1 },
  129075. { 172, 1 },
  129076. { 172, 1 },
  129077. { 173, 1 },
  129078. { 173, 3 },
  129079. { 173, 6 },
  129080. { 173, 5 },
  129081. { 173, 4 },
  129082. { 172, 1 },
  129083. { 173, 5 },
  129084. { 173, 3 },
  129085. { 173, 3 },
  129086. { 173, 3 },
  129087. { 173, 3 },
  129088. { 173, 3 },
  129089. { 173, 3 },
  129090. { 173, 3 },
  129091. { 173, 3 },
  129092. { 221, 2 },
  129093. { 173, 3 },
  129094. { 173, 5 },
  129095. { 173, 2 },
  129096. { 173, 3 },
  129097. { 173, 3 },
  129098. { 173, 4 },
  129099. { 173, 2 },
  129100. { 173, 2 },
  129101. { 173, 2 },
  129102. { 173, 2 },
  129103. { 222, 1 },
  129104. { 222, 2 },
  129105. { 173, 5 },
  129106. { 223, 1 },
  129107. { 223, 2 },
  129108. { 173, 5 },
  129109. { 173, 3 },
  129110. { 173, 5 },
  129111. { 173, 5 },
  129112. { 173, 4 },
  129113. { 173, 5 },
  129114. { 226, 5 },
  129115. { 226, 4 },
  129116. { 227, 2 },
  129117. { 227, 0 },
  129118. { 225, 1 },
  129119. { 225, 0 },
  129120. { 208, 0 },
  129121. { 207, 3 },
  129122. { 207, 1 },
  129123. { 224, 0 },
  129124. { 224, 3 },
  129125. { 149, 12 },
  129126. { 228, 1 },
  129127. { 228, 0 },
  129128. { 177, 0 },
  129129. { 177, 3 },
  129130. { 187, 5 },
  129131. { 187, 3 },
  129132. { 229, 0 },
  129133. { 229, 2 },
  129134. { 149, 4 },
  129135. { 149, 1 },
  129136. { 149, 2 },
  129137. { 149, 3 },
  129138. { 149, 5 },
  129139. { 149, 6 },
  129140. { 149, 5 },
  129141. { 149, 6 },
  129142. { 169, 2 },
  129143. { 170, 2 },
  129144. { 149, 5 },
  129145. { 231, 11 },
  129146. { 233, 1 },
  129147. { 233, 1 },
  129148. { 233, 2 },
  129149. { 233, 0 },
  129150. { 234, 1 },
  129151. { 234, 1 },
  129152. { 234, 3 },
  129153. { 236, 0 },
  129154. { 236, 2 },
  129155. { 232, 3 },
  129156. { 232, 2 },
  129157. { 238, 3 },
  129158. { 239, 3 },
  129159. { 239, 2 },
  129160. { 237, 7 },
  129161. { 237, 5 },
  129162. { 237, 5 },
  129163. { 237, 1 },
  129164. { 173, 4 },
  129165. { 173, 6 },
  129166. { 191, 1 },
  129167. { 191, 1 },
  129168. { 191, 1 },
  129169. { 149, 4 },
  129170. { 149, 6 },
  129171. { 149, 3 },
  129172. { 241, 0 },
  129173. { 241, 2 },
  129174. { 149, 1 },
  129175. { 149, 3 },
  129176. { 149, 1 },
  129177. { 149, 3 },
  129178. { 149, 6 },
  129179. { 149, 7 },
  129180. { 242, 1 },
  129181. { 149, 1 },
  129182. { 149, 4 },
  129183. { 244, 8 },
  129184. { 246, 0 },
  129185. { 247, 1 },
  129186. { 247, 3 },
  129187. { 248, 1 },
  129188. { 196, 0 },
  129189. { 196, 2 },
  129190. { 196, 3 },
  129191. { 250, 6 },
  129192. { 250, 8 },
  129193. { 144, 1 },
  129194. { 145, 2 },
  129195. { 145, 1 },
  129196. { 146, 1 },
  129197. { 146, 3 },
  129198. { 147, 0 },
  129199. { 151, 0 },
  129200. { 151, 1 },
  129201. { 151, 2 },
  129202. { 153, 1 },
  129203. { 153, 0 },
  129204. { 149, 2 },
  129205. { 160, 4 },
  129206. { 160, 2 },
  129207. { 152, 1 },
  129208. { 152, 1 },
  129209. { 152, 1 },
  129210. { 166, 1 },
  129211. { 167, 1 },
  129212. { 168, 1 },
  129213. { 168, 1 },
  129214. { 165, 2 },
  129215. { 165, 0 },
  129216. { 171, 2 },
  129217. { 161, 2 },
  129218. { 183, 3 },
  129219. { 183, 1 },
  129220. { 184, 0 },
  129221. { 188, 1 },
  129222. { 190, 1 },
  129223. { 194, 1 },
  129224. { 195, 1 },
  129225. { 209, 2 },
  129226. { 210, 1 },
  129227. { 173, 1 },
  129228. { 221, 1 },
  129229. { 208, 1 },
  129230. { 230, 1 },
  129231. { 230, 1 },
  129232. { 230, 1 },
  129233. { 230, 1 },
  129234. { 230, 1 },
  129235. { 169, 1 },
  129236. { 235, 0 },
  129237. { 235, 3 },
  129238. { 238, 1 },
  129239. { 239, 0 },
  129240. { 240, 1 },
  129241. { 240, 0 },
  129242. { 243, 0 },
  129243. { 243, 1 },
  129244. { 245, 1 },
  129245. { 245, 3 },
  129246. { 246, 2 },
  129247. { 249, 0 },
  129248. { 249, 4 },
  129249. { 249, 2 },
  129250. };
  129251. static void yy_accept(yyParser*); /* Forward Declaration */
  129252. /*
  129253. ** Perform a reduce action and the shift that must immediately
  129254. ** follow the reduce.
  129255. */
  129256. static void yy_reduce(
  129257. yyParser *yypParser, /* The parser */
  129258. unsigned int yyruleno /* Number of the rule by which to reduce */
  129259. ){
  129260. int yygoto; /* The next state */
  129261. int yyact; /* The next action */
  129262. yyStackEntry *yymsp; /* The top of the parser's stack */
  129263. int yysize; /* Amount to pop the stack */
  129264. sqlite3ParserARG_FETCH;
  129265. yymsp = yypParser->yytos;
  129266. #ifndef NDEBUG
  129267. if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  129268. yysize = yyRuleInfo[yyruleno].nrhs;
  129269. fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt,
  129270. yyRuleName[yyruleno], yymsp[-yysize].stateno);
  129271. }
  129272. #endif /* NDEBUG */
  129273. /* Check that the stack is large enough to grow by a single entry
  129274. ** if the RHS of the rule is empty. This ensures that there is room
  129275. ** enough on the stack to push the LHS value */
  129276. if( yyRuleInfo[yyruleno].nrhs==0 ){
  129277. #ifdef YYTRACKMAXSTACKDEPTH
  129278. if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
  129279. yypParser->yyhwm++;
  129280. assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
  129281. }
  129282. #endif
  129283. #if YYSTACKDEPTH>0
  129284. if( yypParser->yytos>=&yypParser->yystack[YYSTACKDEPTH-1] ){
  129285. yyStackOverflow(yypParser);
  129286. return;
  129287. }
  129288. #else
  129289. if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
  129290. if( yyGrowStack(yypParser) ){
  129291. yyStackOverflow(yypParser);
  129292. return;
  129293. }
  129294. yymsp = yypParser->yytos;
  129295. }
  129296. #endif
  129297. }
  129298. switch( yyruleno ){
  129299. /* Beginning here are the reduction cases. A typical example
  129300. ** follows:
  129301. ** case 0:
  129302. ** #line <lineno> <grammarfile>
  129303. ** { ... } // User supplied code
  129304. ** #line <lineno> <thisfile>
  129305. ** break;
  129306. */
  129307. /********** Begin reduce actions **********************************************/
  129308. YYMINORTYPE yylhsminor;
  129309. case 0: /* explain ::= EXPLAIN */
  129310. { pParse->explain = 1; }
  129311. break;
  129312. case 1: /* explain ::= EXPLAIN QUERY PLAN */
  129313. { pParse->explain = 2; }
  129314. break;
  129315. case 2: /* cmdx ::= cmd */
  129316. { sqlite3FinishCoding(pParse); }
  129317. break;
  129318. case 3: /* cmd ::= BEGIN transtype trans_opt */
  129319. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy194);}
  129320. break;
  129321. case 4: /* transtype ::= */
  129322. {yymsp[1].minor.yy194 = TK_DEFERRED;}
  129323. break;
  129324. case 5: /* transtype ::= DEFERRED */
  129325. case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
  129326. case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
  129327. {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-X*/}
  129328. break;
  129329. case 8: /* cmd ::= COMMIT trans_opt */
  129330. case 9: /* cmd ::= END trans_opt */ yytestcase(yyruleno==9);
  129331. {sqlite3CommitTransaction(pParse);}
  129332. break;
  129333. case 10: /* cmd ::= ROLLBACK trans_opt */
  129334. {sqlite3RollbackTransaction(pParse);}
  129335. break;
  129336. case 11: /* cmd ::= SAVEPOINT nm */
  129337. {
  129338. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  129339. }
  129340. break;
  129341. case 12: /* cmd ::= RELEASE savepoint_opt nm */
  129342. {
  129343. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  129344. }
  129345. break;
  129346. case 13: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  129347. {
  129348. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  129349. }
  129350. break;
  129351. case 14: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  129352. {
  129353. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy194,0,0,yymsp[-2].minor.yy194);
  129354. }
  129355. break;
  129356. case 15: /* createkw ::= CREATE */
  129357. {disableLookaside(pParse);}
  129358. break;
  129359. case 16: /* ifnotexists ::= */
  129360. case 19: /* temp ::= */ yytestcase(yyruleno==19);
  129361. case 22: /* table_options ::= */ yytestcase(yyruleno==22);
  129362. case 42: /* autoinc ::= */ yytestcase(yyruleno==42);
  129363. case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57);
  129364. case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67);
  129365. case 76: /* ifexists ::= */ yytestcase(yyruleno==76);
  129366. case 90: /* distinct ::= */ yytestcase(yyruleno==90);
  129367. case 214: /* collate ::= */ yytestcase(yyruleno==214);
  129368. {yymsp[1].minor.yy194 = 0;}
  129369. break;
  129370. case 17: /* ifnotexists ::= IF NOT EXISTS */
  129371. {yymsp[-2].minor.yy194 = 1;}
  129372. break;
  129373. case 18: /* temp ::= TEMP */
  129374. case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43);
  129375. {yymsp[0].minor.yy194 = 1;}
  129376. break;
  129377. case 20: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
  129378. {
  129379. sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy194,0);
  129380. }
  129381. break;
  129382. case 21: /* create_table_args ::= AS select */
  129383. {
  129384. sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy243);
  129385. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
  129386. }
  129387. break;
  129388. case 23: /* table_options ::= WITHOUT nm */
  129389. {
  129390. if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
  129391. yymsp[-1].minor.yy194 = TF_WithoutRowid | TF_NoVisibleRowid;
  129392. }else{
  129393. yymsp[-1].minor.yy194 = 0;
  129394. sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
  129395. }
  129396. }
  129397. break;
  129398. case 24: /* columnname ::= nm typetoken */
  129399. {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  129400. break;
  129401. case 25: /* typetoken ::= */
  129402. case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60);
  129403. case 96: /* as ::= */ yytestcase(yyruleno==96);
  129404. {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
  129405. break;
  129406. case 26: /* typetoken ::= typename LP signed RP */
  129407. {
  129408. yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  129409. }
  129410. break;
  129411. case 27: /* typetoken ::= typename LP signed COMMA signed RP */
  129412. {
  129413. yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  129414. }
  129415. break;
  129416. case 28: /* typename ::= typename ID|STRING */
  129417. {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
  129418. break;
  129419. case 29: /* ccons ::= CONSTRAINT nm */
  129420. case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62);
  129421. {pParse->constraintName = yymsp[0].minor.yy0;}
  129422. break;
  129423. case 30: /* ccons ::= DEFAULT term */
  129424. case 32: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==32);
  129425. {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy190);}
  129426. break;
  129427. case 31: /* ccons ::= DEFAULT LP expr RP */
  129428. {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy190);}
  129429. break;
  129430. case 33: /* ccons ::= DEFAULT MINUS term */
  129431. {
  129432. ExprSpan v;
  129433. v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy190.pExpr, 0);
  129434. v.zStart = yymsp[-1].minor.yy0.z;
  129435. v.zEnd = yymsp[0].minor.yy190.zEnd;
  129436. sqlite3AddDefaultValue(pParse,&v);
  129437. }
  129438. break;
  129439. case 34: /* ccons ::= DEFAULT ID|INDEXED */
  129440. {
  129441. ExprSpan v;
  129442. spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0);
  129443. sqlite3AddDefaultValue(pParse,&v);
  129444. }
  129445. break;
  129446. case 35: /* ccons ::= NOT NULL onconf */
  129447. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy194);}
  129448. break;
  129449. case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  129450. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy194,yymsp[0].minor.yy194,yymsp[-2].minor.yy194);}
  129451. break;
  129452. case 37: /* ccons ::= UNIQUE onconf */
  129453. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy194,0,0,0,0,
  129454. SQLITE_IDXTYPE_UNIQUE);}
  129455. break;
  129456. case 38: /* ccons ::= CHECK LP expr RP */
  129457. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy190.pExpr);}
  129458. break;
  129459. case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */
  129460. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy148,yymsp[0].minor.yy194);}
  129461. break;
  129462. case 40: /* ccons ::= defer_subclause */
  129463. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy194);}
  129464. break;
  129465. case 41: /* ccons ::= COLLATE ID|STRING */
  129466. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  129467. break;
  129468. case 44: /* refargs ::= */
  129469. { yymsp[1].minor.yy194 = OE_None*0x0101; /* EV: R-19803-45884 */}
  129470. break;
  129471. case 45: /* refargs ::= refargs refarg */
  129472. { yymsp[-1].minor.yy194 = (yymsp[-1].minor.yy194 & ~yymsp[0].minor.yy497.mask) | yymsp[0].minor.yy497.value; }
  129473. break;
  129474. case 46: /* refarg ::= MATCH nm */
  129475. { yymsp[-1].minor.yy497.value = 0; yymsp[-1].minor.yy497.mask = 0x000000; }
  129476. break;
  129477. case 47: /* refarg ::= ON INSERT refact */
  129478. { yymsp[-2].minor.yy497.value = 0; yymsp[-2].minor.yy497.mask = 0x000000; }
  129479. break;
  129480. case 48: /* refarg ::= ON DELETE refact */
  129481. { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194; yymsp[-2].minor.yy497.mask = 0x0000ff; }
  129482. break;
  129483. case 49: /* refarg ::= ON UPDATE refact */
  129484. { yymsp[-2].minor.yy497.value = yymsp[0].minor.yy194<<8; yymsp[-2].minor.yy497.mask = 0x00ff00; }
  129485. break;
  129486. case 50: /* refact ::= SET NULL */
  129487. { yymsp[-1].minor.yy194 = OE_SetNull; /* EV: R-33326-45252 */}
  129488. break;
  129489. case 51: /* refact ::= SET DEFAULT */
  129490. { yymsp[-1].minor.yy194 = OE_SetDflt; /* EV: R-33326-45252 */}
  129491. break;
  129492. case 52: /* refact ::= CASCADE */
  129493. { yymsp[0].minor.yy194 = OE_Cascade; /* EV: R-33326-45252 */}
  129494. break;
  129495. case 53: /* refact ::= RESTRICT */
  129496. { yymsp[0].minor.yy194 = OE_Restrict; /* EV: R-33326-45252 */}
  129497. break;
  129498. case 54: /* refact ::= NO ACTION */
  129499. { yymsp[-1].minor.yy194 = OE_None; /* EV: R-33326-45252 */}
  129500. break;
  129501. case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  129502. {yymsp[-2].minor.yy194 = 0;}
  129503. break;
  129504. case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  129505. case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71);
  129506. case 144: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==144);
  129507. {yymsp[-1].minor.yy194 = yymsp[0].minor.yy194;}
  129508. break;
  129509. case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
  129510. case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75);
  129511. case 186: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==186);
  129512. case 189: /* in_op ::= NOT IN */ yytestcase(yyruleno==189);
  129513. case 215: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==215);
  129514. {yymsp[-1].minor.yy194 = 1;}
  129515. break;
  129516. case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  129517. {yymsp[-1].minor.yy194 = 0;}
  129518. break;
  129519. case 61: /* tconscomma ::= COMMA */
  129520. {pParse->constraintName.n = 0;}
  129521. break;
  129522. case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  129523. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy148,yymsp[0].minor.yy194,yymsp[-2].minor.yy194,0);}
  129524. break;
  129525. case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */
  129526. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy148,yymsp[0].minor.yy194,0,0,0,0,
  129527. SQLITE_IDXTYPE_UNIQUE);}
  129528. break;
  129529. case 65: /* tcons ::= CHECK LP expr RP onconf */
  129530. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy190.pExpr);}
  129531. break;
  129532. case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  129533. {
  129534. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy148, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[-1].minor.yy194);
  129535. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy194);
  129536. }
  129537. break;
  129538. case 68: /* onconf ::= */
  129539. case 70: /* orconf ::= */ yytestcase(yyruleno==70);
  129540. {yymsp[1].minor.yy194 = OE_Default;}
  129541. break;
  129542. case 69: /* onconf ::= ON CONFLICT resolvetype */
  129543. {yymsp[-2].minor.yy194 = yymsp[0].minor.yy194;}
  129544. break;
  129545. case 72: /* resolvetype ::= IGNORE */
  129546. {yymsp[0].minor.yy194 = OE_Ignore;}
  129547. break;
  129548. case 73: /* resolvetype ::= REPLACE */
  129549. case 145: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==145);
  129550. {yymsp[0].minor.yy194 = OE_Replace;}
  129551. break;
  129552. case 74: /* cmd ::= DROP TABLE ifexists fullname */
  129553. {
  129554. sqlite3DropTable(pParse, yymsp[0].minor.yy185, 0, yymsp[-1].minor.yy194);
  129555. }
  129556. break;
  129557. case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  129558. {
  129559. sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy148, yymsp[0].minor.yy243, yymsp[-7].minor.yy194, yymsp[-5].minor.yy194);
  129560. }
  129561. break;
  129562. case 78: /* cmd ::= DROP VIEW ifexists fullname */
  129563. {
  129564. sqlite3DropTable(pParse, yymsp[0].minor.yy185, 1, yymsp[-1].minor.yy194);
  129565. }
  129566. break;
  129567. case 79: /* cmd ::= select */
  129568. {
  129569. SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
  129570. sqlite3Select(pParse, yymsp[0].minor.yy243, &dest);
  129571. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy243);
  129572. }
  129573. break;
  129574. case 80: /* select ::= with selectnowith */
  129575. {
  129576. Select *p = yymsp[0].minor.yy243;
  129577. if( p ){
  129578. p->pWith = yymsp[-1].minor.yy285;
  129579. parserDoubleLinkSelect(pParse, p);
  129580. }else{
  129581. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy285);
  129582. }
  129583. yymsp[-1].minor.yy243 = p; /*A-overwrites-W*/
  129584. }
  129585. break;
  129586. case 81: /* selectnowith ::= selectnowith multiselect_op oneselect */
  129587. {
  129588. Select *pRhs = yymsp[0].minor.yy243;
  129589. Select *pLhs = yymsp[-2].minor.yy243;
  129590. if( pRhs && pRhs->pPrior ){
  129591. SrcList *pFrom;
  129592. Token x;
  129593. x.n = 0;
  129594. parserDoubleLinkSelect(pParse, pRhs);
  129595. pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
  129596. pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
  129597. }
  129598. if( pRhs ){
  129599. pRhs->op = (u8)yymsp[-1].minor.yy194;
  129600. pRhs->pPrior = pLhs;
  129601. if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
  129602. pRhs->selFlags &= ~SF_MultiValue;
  129603. if( yymsp[-1].minor.yy194!=TK_ALL ) pParse->hasCompound = 1;
  129604. }else{
  129605. sqlite3SelectDelete(pParse->db, pLhs);
  129606. }
  129607. yymsp[-2].minor.yy243 = pRhs;
  129608. }
  129609. break;
  129610. case 82: /* multiselect_op ::= UNION */
  129611. case 84: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==84);
  129612. {yymsp[0].minor.yy194 = yymsp[0].major; /*A-overwrites-OP*/}
  129613. break;
  129614. case 83: /* multiselect_op ::= UNION ALL */
  129615. {yymsp[-1].minor.yy194 = TK_ALL;}
  129616. break;
  129617. case 85: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  129618. {
  129619. #if SELECTTRACE_ENABLED
  129620. Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/
  129621. #endif
  129622. yymsp[-8].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy148,yymsp[-5].minor.yy185,yymsp[-4].minor.yy72,yymsp[-3].minor.yy148,yymsp[-2].minor.yy72,yymsp[-1].minor.yy148,yymsp[-7].minor.yy194,yymsp[0].minor.yy354.pLimit,yymsp[0].minor.yy354.pOffset);
  129623. #if SELECTTRACE_ENABLED
  129624. /* Populate the Select.zSelName[] string that is used to help with
  129625. ** query planner debugging, to differentiate between multiple Select
  129626. ** objects in a complex query.
  129627. **
  129628. ** If the SELECT keyword is immediately followed by a C-style comment
  129629. ** then extract the first few alphanumeric characters from within that
  129630. ** comment to be the zSelName value. Otherwise, the label is #N where
  129631. ** is an integer that is incremented with each SELECT statement seen.
  129632. */
  129633. if( yymsp[-8].minor.yy243!=0 ){
  129634. const char *z = s.z+6;
  129635. int i;
  129636. sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "#%d",
  129637. ++pParse->nSelect);
  129638. while( z[0]==' ' ) z++;
  129639. if( z[0]=='/' && z[1]=='*' ){
  129640. z += 2;
  129641. while( z[0]==' ' ) z++;
  129642. for(i=0; sqlite3Isalnum(z[i]); i++){}
  129643. sqlite3_snprintf(sizeof(yymsp[-8].minor.yy243->zSelName), yymsp[-8].minor.yy243->zSelName, "%.*s", i, z);
  129644. }
  129645. }
  129646. #endif /* SELECTRACE_ENABLED */
  129647. }
  129648. break;
  129649. case 86: /* values ::= VALUES LP nexprlist RP */
  129650. {
  129651. yymsp[-3].minor.yy243 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values,0,0);
  129652. }
  129653. break;
  129654. case 87: /* values ::= values COMMA LP exprlist RP */
  129655. {
  129656. Select *pRight, *pLeft = yymsp[-4].minor.yy243;
  129657. pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy148,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
  129658. if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
  129659. if( pRight ){
  129660. pRight->op = TK_ALL;
  129661. pRight->pPrior = pLeft;
  129662. yymsp[-4].minor.yy243 = pRight;
  129663. }else{
  129664. yymsp[-4].minor.yy243 = pLeft;
  129665. }
  129666. }
  129667. break;
  129668. case 88: /* distinct ::= DISTINCT */
  129669. {yymsp[0].minor.yy194 = SF_Distinct;}
  129670. break;
  129671. case 89: /* distinct ::= ALL */
  129672. {yymsp[0].minor.yy194 = SF_All;}
  129673. break;
  129674. case 91: /* sclp ::= */
  129675. case 119: /* orderby_opt ::= */ yytestcase(yyruleno==119);
  129676. case 126: /* groupby_opt ::= */ yytestcase(yyruleno==126);
  129677. case 202: /* exprlist ::= */ yytestcase(yyruleno==202);
  129678. case 205: /* paren_exprlist ::= */ yytestcase(yyruleno==205);
  129679. case 210: /* eidlist_opt ::= */ yytestcase(yyruleno==210);
  129680. {yymsp[1].minor.yy148 = 0;}
  129681. break;
  129682. case 92: /* selcollist ::= sclp expr as */
  129683. {
  129684. yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy148, yymsp[-1].minor.yy190.pExpr);
  129685. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy148, &yymsp[0].minor.yy0, 1);
  129686. sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy148,&yymsp[-1].minor.yy190);
  129687. }
  129688. break;
  129689. case 93: /* selcollist ::= sclp STAR */
  129690. {
  129691. Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
  129692. yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy148, p);
  129693. }
  129694. break;
  129695. case 94: /* selcollist ::= sclp nm DOT STAR */
  129696. {
  129697. Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
  129698. Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  129699. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  129700. yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, pDot);
  129701. }
  129702. break;
  129703. case 95: /* as ::= AS nm */
  129704. case 106: /* dbnm ::= DOT nm */ yytestcase(yyruleno==106);
  129705. case 224: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==224);
  129706. case 225: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==225);
  129707. {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
  129708. break;
  129709. case 97: /* from ::= */
  129710. {yymsp[1].minor.yy185 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy185));}
  129711. break;
  129712. case 98: /* from ::= FROM seltablist */
  129713. {
  129714. yymsp[-1].minor.yy185 = yymsp[0].minor.yy185;
  129715. sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy185);
  129716. }
  129717. break;
  129718. case 99: /* stl_prefix ::= seltablist joinop */
  129719. {
  129720. if( ALWAYS(yymsp[-1].minor.yy185 && yymsp[-1].minor.yy185->nSrc>0) ) yymsp[-1].minor.yy185->a[yymsp[-1].minor.yy185->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy194;
  129721. }
  129722. break;
  129723. case 100: /* stl_prefix ::= */
  129724. {yymsp[1].minor.yy185 = 0;}
  129725. break;
  129726. case 101: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  129727. {
  129728. yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
  129729. sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy185, &yymsp[-2].minor.yy0);
  129730. }
  129731. break;
  129732. case 102: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  129733. {
  129734. yymsp[-8].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy185,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
  129735. sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy185, yymsp[-4].minor.yy148);
  129736. }
  129737. break;
  129738. case 103: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  129739. {
  129740. yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy243,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
  129741. }
  129742. break;
  129743. case 104: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  129744. {
  129745. if( yymsp[-6].minor.yy185==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy72==0 && yymsp[0].minor.yy254==0 ){
  129746. yymsp[-6].minor.yy185 = yymsp[-4].minor.yy185;
  129747. }else if( yymsp[-4].minor.yy185->nSrc==1 ){
  129748. yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
  129749. if( yymsp[-6].minor.yy185 ){
  129750. struct SrcList_item *pNew = &yymsp[-6].minor.yy185->a[yymsp[-6].minor.yy185->nSrc-1];
  129751. struct SrcList_item *pOld = yymsp[-4].minor.yy185->a;
  129752. pNew->zName = pOld->zName;
  129753. pNew->zDatabase = pOld->zDatabase;
  129754. pNew->pSelect = pOld->pSelect;
  129755. pOld->zName = pOld->zDatabase = 0;
  129756. pOld->pSelect = 0;
  129757. }
  129758. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy185);
  129759. }else{
  129760. Select *pSubquery;
  129761. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy185);
  129762. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy185,0,0,0,0,SF_NestedFrom,0,0);
  129763. yymsp[-6].minor.yy185 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy185,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy72,yymsp[0].minor.yy254);
  129764. }
  129765. }
  129766. break;
  129767. case 105: /* dbnm ::= */
  129768. case 114: /* indexed_opt ::= */ yytestcase(yyruleno==114);
  129769. {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
  129770. break;
  129771. case 107: /* fullname ::= nm dbnm */
  129772. {yymsp[-1].minor.yy185 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
  129773. break;
  129774. case 108: /* joinop ::= COMMA|JOIN */
  129775. { yymsp[0].minor.yy194 = JT_INNER; }
  129776. break;
  129777. case 109: /* joinop ::= JOIN_KW JOIN */
  129778. {yymsp[-1].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/}
  129779. break;
  129780. case 110: /* joinop ::= JOIN_KW nm JOIN */
  129781. {yymsp[-2].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
  129782. break;
  129783. case 111: /* joinop ::= JOIN_KW nm nm JOIN */
  129784. {yymsp[-3].minor.yy194 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
  129785. break;
  129786. case 112: /* on_opt ::= ON expr */
  129787. case 129: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==129);
  129788. case 136: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==136);
  129789. case 198: /* case_else ::= ELSE expr */ yytestcase(yyruleno==198);
  129790. {yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr;}
  129791. break;
  129792. case 113: /* on_opt ::= */
  129793. case 128: /* having_opt ::= */ yytestcase(yyruleno==128);
  129794. case 135: /* where_opt ::= */ yytestcase(yyruleno==135);
  129795. case 199: /* case_else ::= */ yytestcase(yyruleno==199);
  129796. case 201: /* case_operand ::= */ yytestcase(yyruleno==201);
  129797. {yymsp[1].minor.yy72 = 0;}
  129798. break;
  129799. case 115: /* indexed_opt ::= INDEXED BY nm */
  129800. {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
  129801. break;
  129802. case 116: /* indexed_opt ::= NOT INDEXED */
  129803. {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
  129804. break;
  129805. case 117: /* using_opt ::= USING LP idlist RP */
  129806. {yymsp[-3].minor.yy254 = yymsp[-1].minor.yy254;}
  129807. break;
  129808. case 118: /* using_opt ::= */
  129809. case 146: /* idlist_opt ::= */ yytestcase(yyruleno==146);
  129810. {yymsp[1].minor.yy254 = 0;}
  129811. break;
  129812. case 120: /* orderby_opt ::= ORDER BY sortlist */
  129813. case 127: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==127);
  129814. {yymsp[-2].minor.yy148 = yymsp[0].minor.yy148;}
  129815. break;
  129816. case 121: /* sortlist ::= sortlist COMMA expr sortorder */
  129817. {
  129818. yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148,yymsp[-1].minor.yy190.pExpr);
  129819. sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy148,yymsp[0].minor.yy194);
  129820. }
  129821. break;
  129822. case 122: /* sortlist ::= expr sortorder */
  129823. {
  129824. yymsp[-1].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy190.pExpr); /*A-overwrites-Y*/
  129825. sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy148,yymsp[0].minor.yy194);
  129826. }
  129827. break;
  129828. case 123: /* sortorder ::= ASC */
  129829. {yymsp[0].minor.yy194 = SQLITE_SO_ASC;}
  129830. break;
  129831. case 124: /* sortorder ::= DESC */
  129832. {yymsp[0].minor.yy194 = SQLITE_SO_DESC;}
  129833. break;
  129834. case 125: /* sortorder ::= */
  129835. {yymsp[1].minor.yy194 = SQLITE_SO_UNDEFINED;}
  129836. break;
  129837. case 130: /* limit_opt ::= */
  129838. {yymsp[1].minor.yy354.pLimit = 0; yymsp[1].minor.yy354.pOffset = 0;}
  129839. break;
  129840. case 131: /* limit_opt ::= LIMIT expr */
  129841. {yymsp[-1].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr; yymsp[-1].minor.yy354.pOffset = 0;}
  129842. break;
  129843. case 132: /* limit_opt ::= LIMIT expr OFFSET expr */
  129844. {yymsp[-3].minor.yy354.pLimit = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pOffset = yymsp[0].minor.yy190.pExpr;}
  129845. break;
  129846. case 133: /* limit_opt ::= LIMIT expr COMMA expr */
  129847. {yymsp[-3].minor.yy354.pOffset = yymsp[-2].minor.yy190.pExpr; yymsp[-3].minor.yy354.pLimit = yymsp[0].minor.yy190.pExpr;}
  129848. break;
  129849. case 134: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
  129850. {
  129851. sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
  129852. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy185, &yymsp[-1].minor.yy0);
  129853. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy185,yymsp[0].minor.yy72);
  129854. }
  129855. break;
  129856. case 137: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
  129857. {
  129858. sqlite3WithPush(pParse, yymsp[-7].minor.yy285, 1);
  129859. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy185, &yymsp[-3].minor.yy0);
  129860. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy148,"set list");
  129861. sqlite3Update(pParse,yymsp[-4].minor.yy185,yymsp[-1].minor.yy148,yymsp[0].minor.yy72,yymsp[-5].minor.yy194);
  129862. }
  129863. break;
  129864. case 138: /* setlist ::= setlist COMMA nm EQ expr */
  129865. {
  129866. yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
  129867. sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, 1);
  129868. }
  129869. break;
  129870. case 139: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
  129871. {
  129872. yymsp[-6].minor.yy148 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy148, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr);
  129873. }
  129874. break;
  129875. case 140: /* setlist ::= nm EQ expr */
  129876. {
  129877. yylhsminor.yy148 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy190.pExpr);
  129878. sqlite3ExprListSetName(pParse, yylhsminor.yy148, &yymsp[-2].minor.yy0, 1);
  129879. }
  129880. yymsp[-2].minor.yy148 = yylhsminor.yy148;
  129881. break;
  129882. case 141: /* setlist ::= LP idlist RP EQ expr */
  129883. {
  129884. yymsp[-4].minor.yy148 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy254, yymsp[0].minor.yy190.pExpr);
  129885. }
  129886. break;
  129887. case 142: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
  129888. {
  129889. sqlite3WithPush(pParse, yymsp[-5].minor.yy285, 1);
  129890. sqlite3Insert(pParse, yymsp[-2].minor.yy185, yymsp[0].minor.yy243, yymsp[-1].minor.yy254, yymsp[-4].minor.yy194);
  129891. }
  129892. break;
  129893. case 143: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
  129894. {
  129895. sqlite3WithPush(pParse, yymsp[-6].minor.yy285, 1);
  129896. sqlite3Insert(pParse, yymsp[-3].minor.yy185, 0, yymsp[-2].minor.yy254, yymsp[-5].minor.yy194);
  129897. }
  129898. break;
  129899. case 147: /* idlist_opt ::= LP idlist RP */
  129900. {yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;}
  129901. break;
  129902. case 148: /* idlist ::= idlist COMMA nm */
  129903. {yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);}
  129904. break;
  129905. case 149: /* idlist ::= nm */
  129906. {yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
  129907. break;
  129908. case 150: /* expr ::= LP expr RP */
  129909. {spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ yymsp[-2].minor.yy190.pExpr = yymsp[-1].minor.yy190.pExpr;}
  129910. break;
  129911. case 151: /* term ::= NULL */
  129912. case 156: /* term ::= FLOAT|BLOB */ yytestcase(yyruleno==156);
  129913. case 157: /* term ::= STRING */ yytestcase(yyruleno==157);
  129914. {spanExpr(&yymsp[0].minor.yy190,pParse,yymsp[0].major,yymsp[0].minor.yy0);/*A-overwrites-X*/}
  129915. break;
  129916. case 152: /* expr ::= ID|INDEXED */
  129917. case 153: /* expr ::= JOIN_KW */ yytestcase(yyruleno==153);
  129918. {spanExpr(&yymsp[0].minor.yy190,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
  129919. break;
  129920. case 154: /* expr ::= nm DOT nm */
  129921. {
  129922. Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  129923. Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
  129924. spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  129925. yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
  129926. }
  129927. break;
  129928. case 155: /* expr ::= nm DOT nm DOT nm */
  129929. {
  129930. Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
  129931. Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  129932. Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
  129933. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
  129934. spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  129935. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
  129936. }
  129937. break;
  129938. case 158: /* term ::= INTEGER */
  129939. {
  129940. yylhsminor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
  129941. yylhsminor.yy190.zStart = yymsp[0].minor.yy0.z;
  129942. yylhsminor.yy190.zEnd = yymsp[0].minor.yy0.z + yymsp[0].minor.yy0.n;
  129943. if( yylhsminor.yy190.pExpr ) yylhsminor.yy190.pExpr->flags |= EP_Leaf|EP_Resolved;
  129944. }
  129945. yymsp[0].minor.yy190 = yylhsminor.yy190;
  129946. break;
  129947. case 159: /* expr ::= VARIABLE */
  129948. {
  129949. if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
  129950. u32 n = yymsp[0].minor.yy0.n;
  129951. spanExpr(&yymsp[0].minor.yy190, pParse, TK_VARIABLE, yymsp[0].minor.yy0);
  129952. sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy190.pExpr, n);
  129953. }else{
  129954. /* When doing a nested parse, one can include terms in an expression
  129955. ** that look like this: #1 #2 ... These terms refer to registers
  129956. ** in the virtual machine. #N is the N-th register. */
  129957. Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
  129958. assert( t.n>=2 );
  129959. spanSet(&yymsp[0].minor.yy190, &t, &t);
  129960. if( pParse->nested==0 ){
  129961. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
  129962. yymsp[0].minor.yy190.pExpr = 0;
  129963. }else{
  129964. yymsp[0].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
  129965. if( yymsp[0].minor.yy190.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy190.pExpr->iTable);
  129966. }
  129967. }
  129968. }
  129969. break;
  129970. case 160: /* expr ::= expr COLLATE ID|STRING */
  129971. {
  129972. yymsp[-2].minor.yy190.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy190.pExpr, &yymsp[0].minor.yy0, 1);
  129973. yymsp[-2].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  129974. }
  129975. break;
  129976. case 161: /* expr ::= CAST LP expr AS typetoken RP */
  129977. {
  129978. spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  129979. yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
  129980. sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, 0);
  129981. }
  129982. break;
  129983. case 162: /* expr ::= ID|INDEXED LP distinct exprlist RP */
  129984. {
  129985. if( yymsp[-1].minor.yy148 && yymsp[-1].minor.yy148->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  129986. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  129987. }
  129988. yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy148, &yymsp[-4].minor.yy0);
  129989. spanSet(&yylhsminor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  129990. if( yymsp[-2].minor.yy194==SF_Distinct && yylhsminor.yy190.pExpr ){
  129991. yylhsminor.yy190.pExpr->flags |= EP_Distinct;
  129992. }
  129993. }
  129994. yymsp[-4].minor.yy190 = yylhsminor.yy190;
  129995. break;
  129996. case 163: /* expr ::= ID|INDEXED LP STAR RP */
  129997. {
  129998. yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  129999. spanSet(&yylhsminor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  130000. }
  130001. yymsp[-3].minor.yy190 = yylhsminor.yy190;
  130002. break;
  130003. case 164: /* term ::= CTIME_KW */
  130004. {
  130005. yylhsminor.yy190.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
  130006. spanSet(&yylhsminor.yy190, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  130007. }
  130008. yymsp[0].minor.yy190 = yylhsminor.yy190;
  130009. break;
  130010. case 165: /* expr ::= LP nexprlist COMMA expr RP */
  130011. {
  130012. ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy148, yymsp[-1].minor.yy190.pExpr);
  130013. yylhsminor.yy190.pExpr = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
  130014. if( yylhsminor.yy190.pExpr ){
  130015. yylhsminor.yy190.pExpr->x.pList = pList;
  130016. spanSet(&yylhsminor.yy190, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
  130017. }else{
  130018. sqlite3ExprListDelete(pParse->db, pList);
  130019. }
  130020. }
  130021. yymsp[-4].minor.yy190 = yylhsminor.yy190;
  130022. break;
  130023. case 166: /* expr ::= expr AND expr */
  130024. case 167: /* expr ::= expr OR expr */ yytestcase(yyruleno==167);
  130025. case 168: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==168);
  130026. case 169: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==169);
  130027. case 170: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==170);
  130028. case 171: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==171);
  130029. case 172: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==172);
  130030. case 173: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==173);
  130031. {spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);}
  130032. break;
  130033. case 174: /* likeop ::= NOT LIKE_KW|MATCH */
  130034. {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
  130035. break;
  130036. case 175: /* expr ::= expr likeop expr */
  130037. {
  130038. ExprList *pList;
  130039. int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
  130040. yymsp[-1].minor.yy0.n &= 0x7fffffff;
  130041. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy190.pExpr);
  130042. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy190.pExpr);
  130043. yymsp[-2].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0);
  130044. exprNot(pParse, bNot, &yymsp[-2].minor.yy190);
  130045. yymsp[-2].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
  130046. if( yymsp[-2].minor.yy190.pExpr ) yymsp[-2].minor.yy190.pExpr->flags |= EP_InfixFunc;
  130047. }
  130048. break;
  130049. case 176: /* expr ::= expr likeop expr ESCAPE expr */
  130050. {
  130051. ExprList *pList;
  130052. int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
  130053. yymsp[-3].minor.yy0.n &= 0x7fffffff;
  130054. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
  130055. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy190.pExpr);
  130056. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
  130057. yymsp[-4].minor.yy190.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0);
  130058. exprNot(pParse, bNot, &yymsp[-4].minor.yy190);
  130059. yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
  130060. if( yymsp[-4].minor.yy190.pExpr ) yymsp[-4].minor.yy190.pExpr->flags |= EP_InfixFunc;
  130061. }
  130062. break;
  130063. case 177: /* expr ::= expr ISNULL|NOTNULL */
  130064. {spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy190,&yymsp[0].minor.yy0);}
  130065. break;
  130066. case 178: /* expr ::= expr NOT NULL */
  130067. {spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy0);}
  130068. break;
  130069. case 179: /* expr ::= expr IS expr */
  130070. {
  130071. spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy190,&yymsp[0].minor.yy190);
  130072. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-2].minor.yy190.pExpr, TK_ISNULL);
  130073. }
  130074. break;
  130075. case 180: /* expr ::= expr IS NOT expr */
  130076. {
  130077. spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy190,&yymsp[0].minor.yy190);
  130078. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy190.pExpr, yymsp[-3].minor.yy190.pExpr, TK_NOTNULL);
  130079. }
  130080. break;
  130081. case 181: /* expr ::= NOT expr */
  130082. case 182: /* expr ::= BITNOT expr */ yytestcase(yyruleno==182);
  130083. {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,yymsp[-1].major,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
  130084. break;
  130085. case 183: /* expr ::= MINUS expr */
  130086. {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UMINUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
  130087. break;
  130088. case 184: /* expr ::= PLUS expr */
  130089. {spanUnaryPrefix(&yymsp[-1].minor.yy190,pParse,TK_UPLUS,&yymsp[0].minor.yy190,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
  130090. break;
  130091. case 185: /* between_op ::= BETWEEN */
  130092. case 188: /* in_op ::= IN */ yytestcase(yyruleno==188);
  130093. {yymsp[0].minor.yy194 = 0;}
  130094. break;
  130095. case 187: /* expr ::= expr between_op expr AND expr */
  130096. {
  130097. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
  130098. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy190.pExpr);
  130099. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy190.pExpr, 0);
  130100. if( yymsp[-4].minor.yy190.pExpr ){
  130101. yymsp[-4].minor.yy190.pExpr->x.pList = pList;
  130102. }else{
  130103. sqlite3ExprListDelete(pParse->db, pList);
  130104. }
  130105. exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
  130106. yymsp[-4].minor.yy190.zEnd = yymsp[0].minor.yy190.zEnd;
  130107. }
  130108. break;
  130109. case 190: /* expr ::= expr in_op LP exprlist RP */
  130110. {
  130111. if( yymsp[-1].minor.yy148==0 ){
  130112. /* Expressions of the form
  130113. **
  130114. ** expr1 IN ()
  130115. ** expr1 NOT IN ()
  130116. **
  130117. ** simplify to constants 0 (false) and 1 (true), respectively,
  130118. ** regardless of the value of expr1.
  130119. */
  130120. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy190.pExpr);
  130121. yymsp[-4].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[yymsp[-3].minor.yy194],1);
  130122. }else if( yymsp[-1].minor.yy148->nExpr==1 ){
  130123. /* Expressions of the form:
  130124. **
  130125. ** expr1 IN (?1)
  130126. ** expr1 NOT IN (?2)
  130127. **
  130128. ** with exactly one value on the RHS can be simplified to something
  130129. ** like this:
  130130. **
  130131. ** expr1 == ?1
  130132. ** expr1 <> ?2
  130133. **
  130134. ** But, the RHS of the == or <> is marked with the EP_Generic flag
  130135. ** so that it may not contribute to the computation of comparison
  130136. ** affinity or the collating sequence to use for comparison. Otherwise,
  130137. ** the semantics would be subtly different from IN or NOT IN.
  130138. */
  130139. Expr *pRHS = yymsp[-1].minor.yy148->a[0].pExpr;
  130140. yymsp[-1].minor.yy148->a[0].pExpr = 0;
  130141. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
  130142. /* pRHS cannot be NULL because a malloc error would have been detected
  130143. ** before now and control would have never reached this point */
  130144. if( ALWAYS(pRHS) ){
  130145. pRHS->flags &= ~EP_Collate;
  130146. pRHS->flags |= EP_Generic;
  130147. }
  130148. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy194 ? TK_NE : TK_EQ, yymsp[-4].minor.yy190.pExpr, pRHS);
  130149. }else{
  130150. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
  130151. if( yymsp[-4].minor.yy190.pExpr ){
  130152. yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy148;
  130153. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
  130154. }else{
  130155. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy148);
  130156. }
  130157. exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
  130158. }
  130159. yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  130160. }
  130161. break;
  130162. case 191: /* expr ::= LP select RP */
  130163. {
  130164. spanSet(&yymsp[-2].minor.yy190,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
  130165. yymsp[-2].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
  130166. sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy190.pExpr, yymsp[-1].minor.yy243);
  130167. }
  130168. break;
  130169. case 192: /* expr ::= expr in_op LP select RP */
  130170. {
  130171. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
  130172. sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, yymsp[-1].minor.yy243);
  130173. exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
  130174. yymsp[-4].minor.yy190.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  130175. }
  130176. break;
  130177. case 193: /* expr ::= expr in_op nm dbnm paren_exprlist */
  130178. {
  130179. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
  130180. Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  130181. if( yymsp[0].minor.yy148 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy148);
  130182. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy190.pExpr, 0);
  130183. sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy190.pExpr, pSelect);
  130184. exprNot(pParse, yymsp[-3].minor.yy194, &yymsp[-4].minor.yy190);
  130185. yymsp[-4].minor.yy190.zEnd = yymsp[-1].minor.yy0.z ? &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n] : &yymsp[-2].minor.yy0.z[yymsp[-2].minor.yy0.n];
  130186. }
  130187. break;
  130188. case 194: /* expr ::= EXISTS LP select RP */
  130189. {
  130190. Expr *p;
  130191. spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
  130192. p = yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
  130193. sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy243);
  130194. }
  130195. break;
  130196. case 195: /* expr ::= CASE case_operand case_exprlist case_else END */
  130197. {
  130198. spanSet(&yymsp[-4].minor.yy190,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-C*/
  130199. yymsp[-4].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy72, 0);
  130200. if( yymsp[-4].minor.yy190.pExpr ){
  130201. yymsp[-4].minor.yy190.pExpr->x.pList = yymsp[-1].minor.yy72 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[-1].minor.yy72) : yymsp[-2].minor.yy148;
  130202. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy190.pExpr);
  130203. }else{
  130204. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy148);
  130205. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy72);
  130206. }
  130207. }
  130208. break;
  130209. case 196: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  130210. {
  130211. yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[-2].minor.yy190.pExpr);
  130212. yymsp[-4].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy148, yymsp[0].minor.yy190.pExpr);
  130213. }
  130214. break;
  130215. case 197: /* case_exprlist ::= WHEN expr THEN expr */
  130216. {
  130217. yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy190.pExpr);
  130218. yymsp[-3].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy148, yymsp[0].minor.yy190.pExpr);
  130219. }
  130220. break;
  130221. case 200: /* case_operand ::= expr */
  130222. {yymsp[0].minor.yy72 = yymsp[0].minor.yy190.pExpr; /*A-overwrites-X*/}
  130223. break;
  130224. case 203: /* nexprlist ::= nexprlist COMMA expr */
  130225. {yymsp[-2].minor.yy148 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy148,yymsp[0].minor.yy190.pExpr);}
  130226. break;
  130227. case 204: /* nexprlist ::= expr */
  130228. {yymsp[0].minor.yy148 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy190.pExpr); /*A-overwrites-Y*/}
  130229. break;
  130230. case 206: /* paren_exprlist ::= LP exprlist RP */
  130231. case 211: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==211);
  130232. {yymsp[-2].minor.yy148 = yymsp[-1].minor.yy148;}
  130233. break;
  130234. case 207: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  130235. {
  130236. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  130237. sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy148, yymsp[-10].minor.yy194,
  130238. &yymsp[-11].minor.yy0, yymsp[0].minor.yy72, SQLITE_SO_ASC, yymsp[-8].minor.yy194, SQLITE_IDXTYPE_APPDEF);
  130239. }
  130240. break;
  130241. case 208: /* uniqueflag ::= UNIQUE */
  130242. case 249: /* raisetype ::= ABORT */ yytestcase(yyruleno==249);
  130243. {yymsp[0].minor.yy194 = OE_Abort;}
  130244. break;
  130245. case 209: /* uniqueflag ::= */
  130246. {yymsp[1].minor.yy194 = OE_None;}
  130247. break;
  130248. case 212: /* eidlist ::= eidlist COMMA nm collate sortorder */
  130249. {
  130250. yymsp[-4].minor.yy148 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy148, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194);
  130251. }
  130252. break;
  130253. case 213: /* eidlist ::= nm collate sortorder */
  130254. {
  130255. yymsp[-2].minor.yy148 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy194, yymsp[0].minor.yy194); /*A-overwrites-Y*/
  130256. }
  130257. break;
  130258. case 216: /* cmd ::= DROP INDEX ifexists fullname */
  130259. {sqlite3DropIndex(pParse, yymsp[0].minor.yy185, yymsp[-1].minor.yy194);}
  130260. break;
  130261. case 217: /* cmd ::= VACUUM */
  130262. {sqlite3Vacuum(pParse,0);}
  130263. break;
  130264. case 218: /* cmd ::= VACUUM nm */
  130265. {sqlite3Vacuum(pParse,&yymsp[0].minor.yy0);}
  130266. break;
  130267. case 219: /* cmd ::= PRAGMA nm dbnm */
  130268. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  130269. break;
  130270. case 220: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  130271. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  130272. break;
  130273. case 221: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  130274. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  130275. break;
  130276. case 222: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  130277. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  130278. break;
  130279. case 223: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  130280. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  130281. break;
  130282. case 226: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  130283. {
  130284. Token all;
  130285. all.z = yymsp[-3].minor.yy0.z;
  130286. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  130287. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy145, &all);
  130288. }
  130289. break;
  130290. case 227: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  130291. {
  130292. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy194, yymsp[-4].minor.yy332.a, yymsp[-4].minor.yy332.b, yymsp[-2].minor.yy185, yymsp[0].minor.yy72, yymsp[-10].minor.yy194, yymsp[-8].minor.yy194);
  130293. yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
  130294. }
  130295. break;
  130296. case 228: /* trigger_time ::= BEFORE */
  130297. { yymsp[0].minor.yy194 = TK_BEFORE; }
  130298. break;
  130299. case 229: /* trigger_time ::= AFTER */
  130300. { yymsp[0].minor.yy194 = TK_AFTER; }
  130301. break;
  130302. case 230: /* trigger_time ::= INSTEAD OF */
  130303. { yymsp[-1].minor.yy194 = TK_INSTEAD;}
  130304. break;
  130305. case 231: /* trigger_time ::= */
  130306. { yymsp[1].minor.yy194 = TK_BEFORE; }
  130307. break;
  130308. case 232: /* trigger_event ::= DELETE|INSERT */
  130309. case 233: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==233);
  130310. {yymsp[0].minor.yy332.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy332.b = 0;}
  130311. break;
  130312. case 234: /* trigger_event ::= UPDATE OF idlist */
  130313. {yymsp[-2].minor.yy332.a = TK_UPDATE; yymsp[-2].minor.yy332.b = yymsp[0].minor.yy254;}
  130314. break;
  130315. case 235: /* when_clause ::= */
  130316. case 254: /* key_opt ::= */ yytestcase(yyruleno==254);
  130317. { yymsp[1].minor.yy72 = 0; }
  130318. break;
  130319. case 236: /* when_clause ::= WHEN expr */
  130320. case 255: /* key_opt ::= KEY expr */ yytestcase(yyruleno==255);
  130321. { yymsp[-1].minor.yy72 = yymsp[0].minor.yy190.pExpr; }
  130322. break;
  130323. case 237: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  130324. {
  130325. assert( yymsp[-2].minor.yy145!=0 );
  130326. yymsp[-2].minor.yy145->pLast->pNext = yymsp[-1].minor.yy145;
  130327. yymsp[-2].minor.yy145->pLast = yymsp[-1].minor.yy145;
  130328. }
  130329. break;
  130330. case 238: /* trigger_cmd_list ::= trigger_cmd SEMI */
  130331. {
  130332. assert( yymsp[-1].minor.yy145!=0 );
  130333. yymsp[-1].minor.yy145->pLast = yymsp[-1].minor.yy145;
  130334. }
  130335. break;
  130336. case 239: /* trnm ::= nm DOT nm */
  130337. {
  130338. yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
  130339. sqlite3ErrorMsg(pParse,
  130340. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  130341. "statements within triggers");
  130342. }
  130343. break;
  130344. case 240: /* tridxby ::= INDEXED BY nm */
  130345. {
  130346. sqlite3ErrorMsg(pParse,
  130347. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  130348. "within triggers");
  130349. }
  130350. break;
  130351. case 241: /* tridxby ::= NOT INDEXED */
  130352. {
  130353. sqlite3ErrorMsg(pParse,
  130354. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  130355. "within triggers");
  130356. }
  130357. break;
  130358. case 242: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
  130359. {yymsp[-6].minor.yy145 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy148, yymsp[0].minor.yy72, yymsp[-5].minor.yy194);}
  130360. break;
  130361. case 243: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
  130362. {yymsp[-4].minor.yy145 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy254, yymsp[0].minor.yy243, yymsp[-4].minor.yy194);/*A-overwrites-R*/}
  130363. break;
  130364. case 244: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
  130365. {yymsp[-4].minor.yy145 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy72);}
  130366. break;
  130367. case 245: /* trigger_cmd ::= select */
  130368. {yymsp[0].minor.yy145 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy243); /*A-overwrites-X*/}
  130369. break;
  130370. case 246: /* expr ::= RAISE LP IGNORE RP */
  130371. {
  130372. spanSet(&yymsp[-3].minor.yy190,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  130373. yymsp[-3].minor.yy190.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
  130374. if( yymsp[-3].minor.yy190.pExpr ){
  130375. yymsp[-3].minor.yy190.pExpr->affinity = OE_Ignore;
  130376. }
  130377. }
  130378. break;
  130379. case 247: /* expr ::= RAISE LP raisetype COMMA nm RP */
  130380. {
  130381. spanSet(&yymsp[-5].minor.yy190,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
  130382. yymsp[-5].minor.yy190.pExpr = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
  130383. if( yymsp[-5].minor.yy190.pExpr ) {
  130384. yymsp[-5].minor.yy190.pExpr->affinity = (char)yymsp[-3].minor.yy194;
  130385. }
  130386. }
  130387. break;
  130388. case 248: /* raisetype ::= ROLLBACK */
  130389. {yymsp[0].minor.yy194 = OE_Rollback;}
  130390. break;
  130391. case 250: /* raisetype ::= FAIL */
  130392. {yymsp[0].minor.yy194 = OE_Fail;}
  130393. break;
  130394. case 251: /* cmd ::= DROP TRIGGER ifexists fullname */
  130395. {
  130396. sqlite3DropTrigger(pParse,yymsp[0].minor.yy185,yymsp[-1].minor.yy194);
  130397. }
  130398. break;
  130399. case 252: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  130400. {
  130401. sqlite3Attach(pParse, yymsp[-3].minor.yy190.pExpr, yymsp[-1].minor.yy190.pExpr, yymsp[0].minor.yy72);
  130402. }
  130403. break;
  130404. case 253: /* cmd ::= DETACH database_kw_opt expr */
  130405. {
  130406. sqlite3Detach(pParse, yymsp[0].minor.yy190.pExpr);
  130407. }
  130408. break;
  130409. case 256: /* cmd ::= REINDEX */
  130410. {sqlite3Reindex(pParse, 0, 0);}
  130411. break;
  130412. case 257: /* cmd ::= REINDEX nm dbnm */
  130413. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  130414. break;
  130415. case 258: /* cmd ::= ANALYZE */
  130416. {sqlite3Analyze(pParse, 0, 0);}
  130417. break;
  130418. case 259: /* cmd ::= ANALYZE nm dbnm */
  130419. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  130420. break;
  130421. case 260: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  130422. {
  130423. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy185,&yymsp[0].minor.yy0);
  130424. }
  130425. break;
  130426. case 261: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  130427. {
  130428. yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
  130429. sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
  130430. }
  130431. break;
  130432. case 262: /* add_column_fullname ::= fullname */
  130433. {
  130434. disableLookaside(pParse);
  130435. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy185);
  130436. }
  130437. break;
  130438. case 263: /* cmd ::= create_vtab */
  130439. {sqlite3VtabFinishParse(pParse,0);}
  130440. break;
  130441. case 264: /* cmd ::= create_vtab LP vtabarglist RP */
  130442. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  130443. break;
  130444. case 265: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  130445. {
  130446. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy194);
  130447. }
  130448. break;
  130449. case 266: /* vtabarg ::= */
  130450. {sqlite3VtabArgInit(pParse);}
  130451. break;
  130452. case 267: /* vtabargtoken ::= ANY */
  130453. case 268: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==268);
  130454. case 269: /* lp ::= LP */ yytestcase(yyruleno==269);
  130455. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  130456. break;
  130457. case 270: /* with ::= */
  130458. {yymsp[1].minor.yy285 = 0;}
  130459. break;
  130460. case 271: /* with ::= WITH wqlist */
  130461. { yymsp[-1].minor.yy285 = yymsp[0].minor.yy285; }
  130462. break;
  130463. case 272: /* with ::= WITH RECURSIVE wqlist */
  130464. { yymsp[-2].minor.yy285 = yymsp[0].minor.yy285; }
  130465. break;
  130466. case 273: /* wqlist ::= nm eidlist_opt AS LP select RP */
  130467. {
  130468. yymsp[-5].minor.yy285 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243); /*A-overwrites-X*/
  130469. }
  130470. break;
  130471. case 274: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  130472. {
  130473. yymsp[-7].minor.yy285 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy285, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy148, yymsp[-1].minor.yy243);
  130474. }
  130475. break;
  130476. default:
  130477. /* (275) input ::= cmdlist */ yytestcase(yyruleno==275);
  130478. /* (276) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==276);
  130479. /* (277) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=277);
  130480. /* (278) ecmd ::= SEMI */ yytestcase(yyruleno==278);
  130481. /* (279) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==279);
  130482. /* (280) explain ::= */ yytestcase(yyruleno==280);
  130483. /* (281) trans_opt ::= */ yytestcase(yyruleno==281);
  130484. /* (282) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==282);
  130485. /* (283) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==283);
  130486. /* (284) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==284);
  130487. /* (285) savepoint_opt ::= */ yytestcase(yyruleno==285);
  130488. /* (286) cmd ::= create_table create_table_args */ yytestcase(yyruleno==286);
  130489. /* (287) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==287);
  130490. /* (288) columnlist ::= columnname carglist */ yytestcase(yyruleno==288);
  130491. /* (289) nm ::= ID|INDEXED */ yytestcase(yyruleno==289);
  130492. /* (290) nm ::= STRING */ yytestcase(yyruleno==290);
  130493. /* (291) nm ::= JOIN_KW */ yytestcase(yyruleno==291);
  130494. /* (292) typetoken ::= typename */ yytestcase(yyruleno==292);
  130495. /* (293) typename ::= ID|STRING */ yytestcase(yyruleno==293);
  130496. /* (294) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=294);
  130497. /* (295) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=295);
  130498. /* (296) carglist ::= carglist ccons */ yytestcase(yyruleno==296);
  130499. /* (297) carglist ::= */ yytestcase(yyruleno==297);
  130500. /* (298) ccons ::= NULL onconf */ yytestcase(yyruleno==298);
  130501. /* (299) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==299);
  130502. /* (300) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==300);
  130503. /* (301) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=301);
  130504. /* (302) tconscomma ::= */ yytestcase(yyruleno==302);
  130505. /* (303) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=303);
  130506. /* (304) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=304);
  130507. /* (305) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=305);
  130508. /* (306) oneselect ::= values */ yytestcase(yyruleno==306);
  130509. /* (307) sclp ::= selcollist COMMA */ yytestcase(yyruleno==307);
  130510. /* (308) as ::= ID|STRING */ yytestcase(yyruleno==308);
  130511. /* (309) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=309);
  130512. /* (310) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==310);
  130513. /* (311) exprlist ::= nexprlist */ yytestcase(yyruleno==311);
  130514. /* (312) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=312);
  130515. /* (313) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=313);
  130516. /* (314) nmnum ::= ON */ yytestcase(yyruleno==314);
  130517. /* (315) nmnum ::= DELETE */ yytestcase(yyruleno==315);
  130518. /* (316) nmnum ::= DEFAULT */ yytestcase(yyruleno==316);
  130519. /* (317) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==317);
  130520. /* (318) foreach_clause ::= */ yytestcase(yyruleno==318);
  130521. /* (319) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==319);
  130522. /* (320) trnm ::= nm */ yytestcase(yyruleno==320);
  130523. /* (321) tridxby ::= */ yytestcase(yyruleno==321);
  130524. /* (322) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==322);
  130525. /* (323) database_kw_opt ::= */ yytestcase(yyruleno==323);
  130526. /* (324) kwcolumn_opt ::= */ yytestcase(yyruleno==324);
  130527. /* (325) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==325);
  130528. /* (326) vtabarglist ::= vtabarg */ yytestcase(yyruleno==326);
  130529. /* (327) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==327);
  130530. /* (328) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==328);
  130531. /* (329) anylist ::= */ yytestcase(yyruleno==329);
  130532. /* (330) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==330);
  130533. /* (331) anylist ::= anylist ANY */ yytestcase(yyruleno==331);
  130534. break;
  130535. /********** End reduce actions ************************************************/
  130536. };
  130537. assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  130538. yygoto = yyRuleInfo[yyruleno].lhs;
  130539. yysize = yyRuleInfo[yyruleno].nrhs;
  130540. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  130541. if( yyact <= YY_MAX_SHIFTREDUCE ){
  130542. if( yyact>YY_MAX_SHIFT ){
  130543. yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
  130544. }
  130545. yymsp -= yysize-1;
  130546. yypParser->yytos = yymsp;
  130547. yymsp->stateno = (YYACTIONTYPE)yyact;
  130548. yymsp->major = (YYCODETYPE)yygoto;
  130549. yyTraceShift(yypParser, yyact);
  130550. }else{
  130551. assert( yyact == YY_ACCEPT_ACTION );
  130552. yypParser->yytos -= yysize;
  130553. yy_accept(yypParser);
  130554. }
  130555. }
  130556. /*
  130557. ** The following code executes when the parse fails
  130558. */
  130559. #ifndef YYNOERRORRECOVERY
  130560. static void yy_parse_failed(
  130561. yyParser *yypParser /* The parser */
  130562. ){
  130563. sqlite3ParserARG_FETCH;
  130564. #ifndef NDEBUG
  130565. if( yyTraceFILE ){
  130566. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  130567. }
  130568. #endif
  130569. while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
  130570. /* Here code is inserted which will be executed whenever the
  130571. ** parser fails */
  130572. /************ Begin %parse_failure code ***************************************/
  130573. /************ End %parse_failure code *****************************************/
  130574. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  130575. }
  130576. #endif /* YYNOERRORRECOVERY */
  130577. /*
  130578. ** The following code executes when a syntax error first occurs.
  130579. */
  130580. static void yy_syntax_error(
  130581. yyParser *yypParser, /* The parser */
  130582. int yymajor, /* The major type of the error token */
  130583. sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */
  130584. ){
  130585. sqlite3ParserARG_FETCH;
  130586. #define TOKEN yyminor
  130587. /************ Begin %syntax_error code ****************************************/
  130588. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  130589. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  130590. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  130591. /************ End %syntax_error code ******************************************/
  130592. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  130593. }
  130594. /*
  130595. ** The following is executed when the parser accepts
  130596. */
  130597. static void yy_accept(
  130598. yyParser *yypParser /* The parser */
  130599. ){
  130600. sqlite3ParserARG_FETCH;
  130601. #ifndef NDEBUG
  130602. if( yyTraceFILE ){
  130603. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  130604. }
  130605. #endif
  130606. #ifndef YYNOERRORRECOVERY
  130607. yypParser->yyerrcnt = -1;
  130608. #endif
  130609. assert( yypParser->yytos==yypParser->yystack );
  130610. /* Here code is inserted which will be executed whenever the
  130611. ** parser accepts */
  130612. /*********** Begin %parse_accept code *****************************************/
  130613. /*********** End %parse_accept code *******************************************/
  130614. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  130615. }
  130616. /* The main parser program.
  130617. ** The first argument is a pointer to a structure obtained from
  130618. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  130619. ** The second argument is the major token number. The third is
  130620. ** the minor token. The fourth optional argument is whatever the
  130621. ** user wants (and specified in the grammar) and is available for
  130622. ** use by the action routines.
  130623. **
  130624. ** Inputs:
  130625. ** <ul>
  130626. ** <li> A pointer to the parser (an opaque structure.)
  130627. ** <li> The major token number.
  130628. ** <li> The minor token number.
  130629. ** <li> An option argument of a grammar-specified type.
  130630. ** </ul>
  130631. **
  130632. ** Outputs:
  130633. ** None.
  130634. */
  130635. SQLITE_PRIVATE void sqlite3Parser(
  130636. void *yyp, /* The parser */
  130637. int yymajor, /* The major token code number */
  130638. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  130639. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  130640. ){
  130641. YYMINORTYPE yyminorunion;
  130642. unsigned int yyact; /* The parser action. */
  130643. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  130644. int yyendofinput; /* True if we are at the end of input */
  130645. #endif
  130646. #ifdef YYERRORSYMBOL
  130647. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  130648. #endif
  130649. yyParser *yypParser; /* The parser */
  130650. yypParser = (yyParser*)yyp;
  130651. assert( yypParser->yytos!=0 );
  130652. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  130653. yyendofinput = (yymajor==0);
  130654. #endif
  130655. sqlite3ParserARG_STORE;
  130656. #ifndef NDEBUG
  130657. if( yyTraceFILE ){
  130658. fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]);
  130659. }
  130660. #endif
  130661. do{
  130662. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  130663. if( yyact <= YY_MAX_SHIFTREDUCE ){
  130664. yy_shift(yypParser,yyact,yymajor,yyminor);
  130665. #ifndef YYNOERRORRECOVERY
  130666. yypParser->yyerrcnt--;
  130667. #endif
  130668. yymajor = YYNOCODE;
  130669. }else if( yyact <= YY_MAX_REDUCE ){
  130670. yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
  130671. }else{
  130672. assert( yyact == YY_ERROR_ACTION );
  130673. yyminorunion.yy0 = yyminor;
  130674. #ifdef YYERRORSYMBOL
  130675. int yymx;
  130676. #endif
  130677. #ifndef NDEBUG
  130678. if( yyTraceFILE ){
  130679. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  130680. }
  130681. #endif
  130682. #ifdef YYERRORSYMBOL
  130683. /* A syntax error has occurred.
  130684. ** The response to an error depends upon whether or not the
  130685. ** grammar defines an error token "ERROR".
  130686. **
  130687. ** This is what we do if the grammar does define ERROR:
  130688. **
  130689. ** * Call the %syntax_error function.
  130690. **
  130691. ** * Begin popping the stack until we enter a state where
  130692. ** it is legal to shift the error symbol, then shift
  130693. ** the error symbol.
  130694. **
  130695. ** * Set the error count to three.
  130696. **
  130697. ** * Begin accepting and shifting new tokens. No new error
  130698. ** processing will occur until three tokens have been
  130699. ** shifted successfully.
  130700. **
  130701. */
  130702. if( yypParser->yyerrcnt<0 ){
  130703. yy_syntax_error(yypParser,yymajor,yyminor);
  130704. }
  130705. yymx = yypParser->yytos->major;
  130706. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  130707. #ifndef NDEBUG
  130708. if( yyTraceFILE ){
  130709. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  130710. yyTracePrompt,yyTokenName[yymajor]);
  130711. }
  130712. #endif
  130713. yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
  130714. yymajor = YYNOCODE;
  130715. }else{
  130716. while( yypParser->yytos >= yypParser->yystack
  130717. && yymx != YYERRORSYMBOL
  130718. && (yyact = yy_find_reduce_action(
  130719. yypParser->yytos->stateno,
  130720. YYERRORSYMBOL)) >= YY_MIN_REDUCE
  130721. ){
  130722. yy_pop_parser_stack(yypParser);
  130723. }
  130724. if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
  130725. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  130726. yy_parse_failed(yypParser);
  130727. #ifndef YYNOERRORRECOVERY
  130728. yypParser->yyerrcnt = -1;
  130729. #endif
  130730. yymajor = YYNOCODE;
  130731. }else if( yymx!=YYERRORSYMBOL ){
  130732. yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
  130733. }
  130734. }
  130735. yypParser->yyerrcnt = 3;
  130736. yyerrorhit = 1;
  130737. #elif defined(YYNOERRORRECOVERY)
  130738. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  130739. ** do any kind of error recovery. Instead, simply invoke the syntax
  130740. ** error routine and continue going as if nothing had happened.
  130741. **
  130742. ** Applications can set this macro (for example inside %include) if
  130743. ** they intend to abandon the parse upon the first syntax error seen.
  130744. */
  130745. yy_syntax_error(yypParser,yymajor, yyminor);
  130746. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  130747. yymajor = YYNOCODE;
  130748. #else /* YYERRORSYMBOL is not defined */
  130749. /* This is what we do if the grammar does not define ERROR:
  130750. **
  130751. ** * Report an error message, and throw away the input token.
  130752. **
  130753. ** * If the input token is $, then fail the parse.
  130754. **
  130755. ** As before, subsequent error messages are suppressed until
  130756. ** three input tokens have been successfully shifted.
  130757. */
  130758. if( yypParser->yyerrcnt<=0 ){
  130759. yy_syntax_error(yypParser,yymajor, yyminor);
  130760. }
  130761. yypParser->yyerrcnt = 3;
  130762. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  130763. if( yyendofinput ){
  130764. yy_parse_failed(yypParser);
  130765. #ifndef YYNOERRORRECOVERY
  130766. yypParser->yyerrcnt = -1;
  130767. #endif
  130768. }
  130769. yymajor = YYNOCODE;
  130770. #endif
  130771. }
  130772. }while( yymajor!=YYNOCODE && yypParser->yytos>yypParser->yystack );
  130773. #ifndef NDEBUG
  130774. if( yyTraceFILE ){
  130775. yyStackEntry *i;
  130776. char cDiv = '[';
  130777. fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
  130778. for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
  130779. fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
  130780. cDiv = ' ';
  130781. }
  130782. fprintf(yyTraceFILE,"]\n");
  130783. }
  130784. #endif
  130785. return;
  130786. }
  130787. /************** End of parse.c ***********************************************/
  130788. /************** Begin file tokenize.c ****************************************/
  130789. /*
  130790. ** 2001 September 15
  130791. **
  130792. ** The author disclaims copyright to this source code. In place of
  130793. ** a legal notice, here is a blessing:
  130794. **
  130795. ** May you do good and not evil.
  130796. ** May you find forgiveness for yourself and forgive others.
  130797. ** May you share freely, never taking more than you give.
  130798. **
  130799. *************************************************************************
  130800. ** An tokenizer for SQL
  130801. **
  130802. ** This file contains C code that splits an SQL input string up into
  130803. ** individual tokens and sends those tokens one-by-one over to the
  130804. ** parser for analysis.
  130805. */
  130806. /* #include "sqliteInt.h" */
  130807. /* #include <stdlib.h> */
  130808. /* Character classes for tokenizing
  130809. **
  130810. ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
  130811. ** using a lookup table, whereas a switch() directly on c uses a binary search.
  130812. ** The lookup table is much faster. To maximize speed, and to ensure that
  130813. ** a lookup table is used, all of the classes need to be small integers and
  130814. ** all of them need to be used within the switch.
  130815. */
  130816. #define CC_X 0 /* The letter 'x', or start of BLOB literal */
  130817. #define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */
  130818. #define CC_ID 2 /* unicode characters usable in IDs */
  130819. #define CC_DIGIT 3 /* Digits */
  130820. #define CC_DOLLAR 4 /* '$' */
  130821. #define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */
  130822. #define CC_VARNUM 6 /* '?'. Numeric SQL variables */
  130823. #define CC_SPACE 7 /* Space characters */
  130824. #define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */
  130825. #define CC_QUOTE2 9 /* '['. [...] style quoted ids */
  130826. #define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */
  130827. #define CC_MINUS 11 /* '-'. Minus or SQL-style comment */
  130828. #define CC_LT 12 /* '<'. Part of < or <= or <> */
  130829. #define CC_GT 13 /* '>'. Part of > or >= */
  130830. #define CC_EQ 14 /* '='. Part of = or == */
  130831. #define CC_BANG 15 /* '!'. Part of != */
  130832. #define CC_SLASH 16 /* '/'. / or c-style comment */
  130833. #define CC_LP 17 /* '(' */
  130834. #define CC_RP 18 /* ')' */
  130835. #define CC_SEMI 19 /* ';' */
  130836. #define CC_PLUS 20 /* '+' */
  130837. #define CC_STAR 21 /* '*' */
  130838. #define CC_PERCENT 22 /* '%' */
  130839. #define CC_COMMA 23 /* ',' */
  130840. #define CC_AND 24 /* '&' */
  130841. #define CC_TILDA 25 /* '~' */
  130842. #define CC_DOT 26 /* '.' */
  130843. #define CC_ILLEGAL 27 /* Illegal character */
  130844. static const unsigned char aiClass[] = {
  130845. #ifdef SQLITE_ASCII
  130846. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  130847. /* 0x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27,
  130848. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  130849. /* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16,
  130850. /* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6,
  130851. /* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  130852. /* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1,
  130853. /* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  130854. /* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27,
  130855. /* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  130856. /* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  130857. /* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  130858. /* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  130859. /* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  130860. /* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  130861. /* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  130862. /* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
  130863. #endif
  130864. #ifdef SQLITE_EBCDIC
  130865. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  130866. /* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27,
  130867. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  130868. /* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  130869. /* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  130870. /* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10,
  130871. /* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27,
  130872. /* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 6,
  130873. /* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8,
  130874. /* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  130875. /* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  130876. /* Ax */ 27, 25, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  130877. /* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27,
  130878. /* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  130879. /* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  130880. /* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  130881. /* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27,
  130882. #endif
  130883. };
  130884. /*
  130885. ** The charMap() macro maps alphabetic characters (only) into their
  130886. ** lower-case ASCII equivalent. On ASCII machines, this is just
  130887. ** an upper-to-lower case map. On EBCDIC machines we also need
  130888. ** to adjust the encoding. The mapping is only valid for alphabetics
  130889. ** which are the only characters for which this feature is used.
  130890. **
  130891. ** Used by keywordhash.h
  130892. */
  130893. #ifdef SQLITE_ASCII
  130894. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  130895. #endif
  130896. #ifdef SQLITE_EBCDIC
  130897. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  130898. const unsigned char ebcdicToAscii[] = {
  130899. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  130900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  130901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  130902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  130903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  130904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  130905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  130906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  130907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  130908. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  130909. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  130910. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  130911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  130912. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  130913. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  130914. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  130915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  130916. };
  130917. #endif
  130918. /*
  130919. ** The sqlite3KeywordCode function looks up an identifier to determine if
  130920. ** it is a keyword. If it is a keyword, the token code of that keyword is
  130921. ** returned. If the input is not a keyword, TK_ID is returned.
  130922. **
  130923. ** The implementation of this routine was generated by a program,
  130924. ** mkkeywordhash.c, located in the tool subdirectory of the distribution.
  130925. ** The output of the mkkeywordhash.c program is written into a file
  130926. ** named keywordhash.h and then included into this source file by
  130927. ** the #include below.
  130928. */
  130929. /************** Include keywordhash.h in the middle of tokenize.c ************/
  130930. /************** Begin file keywordhash.h *************************************/
  130931. /***** This file contains automatically generated code ******
  130932. **
  130933. ** The code in this file has been automatically generated by
  130934. **
  130935. ** sqlite/tool/mkkeywordhash.c
  130936. **
  130937. ** The code in this file implements a function that determines whether
  130938. ** or not a given identifier is really an SQL keyword. The same thing
  130939. ** might be implemented more directly using a hand-written hash table.
  130940. ** But by using this automatically generated code, the size of the code
  130941. ** is substantially reduced. This is important for embedded applications
  130942. ** on platforms with limited memory.
  130943. */
  130944. /* Hash score: 182 */
  130945. static int keywordCode(const char *z, int n, int *pType){
  130946. /* zText[] encodes 834 bytes of keywords in 554 bytes */
  130947. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  130948. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  130949. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  130950. /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
  130951. /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
  130952. /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
  130953. /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
  130954. /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
  130955. /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
  130956. /* VACUUMVIEWINITIALLY */
  130957. static const char zText[553] = {
  130958. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  130959. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  130960. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  130961. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  130962. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  130963. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  130964. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  130965. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  130966. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  130967. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  130968. 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
  130969. 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
  130970. 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
  130971. 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
  130972. 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
  130973. 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
  130974. 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
  130975. 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
  130976. 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
  130977. 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
  130978. 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
  130979. 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
  130980. 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
  130981. 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
  130982. 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
  130983. 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
  130984. 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
  130985. 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
  130986. 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
  130987. 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
  130988. 'V','I','E','W','I','N','I','T','I','A','L','L','Y',
  130989. };
  130990. static const unsigned char aHash[127] = {
  130991. 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
  130992. 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
  130993. 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
  130994. 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
  130995. 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
  130996. 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
  130997. 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
  130998. 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
  130999. 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
  131000. 29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
  131001. };
  131002. static const unsigned char aNext[124] = {
  131003. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  131004. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  131005. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131006. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
  131007. 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
  131008. 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
  131009. 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
  131010. 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
  131011. 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
  131012. 73, 83, 0, 35, 68, 0, 0,
  131013. };
  131014. static const unsigned char aLen[124] = {
  131015. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  131016. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  131017. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  131018. 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
  131019. 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
  131020. 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
  131021. 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
  131022. 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
  131023. 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
  131024. 3, 5, 5, 6, 4, 9, 3,
  131025. };
  131026. static const unsigned short int aOffset[124] = {
  131027. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  131028. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  131029. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  131030. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
  131031. 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
  131032. 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
  131033. 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
  131034. 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
  131035. 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
  131036. 521, 524, 529, 534, 540, 544, 549,
  131037. };
  131038. static const unsigned char aCode[124] = {
  131039. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  131040. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  131041. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  131042. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  131043. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  131044. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  131045. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  131046. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  131047. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  131048. TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
  131049. TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
  131050. TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN,
  131051. TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
  131052. TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE,
  131053. TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN,
  131054. TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
  131055. TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN,
  131056. TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND,
  131057. TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
  131058. TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
  131059. TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS,
  131060. TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW,
  131061. TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT,
  131062. TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
  131063. TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
  131064. };
  131065. int i, j;
  131066. const char *zKW;
  131067. if( n>=2 ){
  131068. i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
  131069. for(i=((int)aHash[i])-1; i>=0; i=((int)aNext[i])-1){
  131070. if( aLen[i]!=n ) continue;
  131071. j = 0;
  131072. zKW = &zText[aOffset[i]];
  131073. #ifdef SQLITE_ASCII
  131074. while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
  131075. #endif
  131076. #ifdef SQLITE_EBCDIC
  131077. while( j<n && toupper(z[j])==zKW[j] ){ j++; }
  131078. #endif
  131079. if( j<n ) continue;
  131080. testcase( i==0 ); /* REINDEX */
  131081. testcase( i==1 ); /* INDEXED */
  131082. testcase( i==2 ); /* INDEX */
  131083. testcase( i==3 ); /* DESC */
  131084. testcase( i==4 ); /* ESCAPE */
  131085. testcase( i==5 ); /* EACH */
  131086. testcase( i==6 ); /* CHECK */
  131087. testcase( i==7 ); /* KEY */
  131088. testcase( i==8 ); /* BEFORE */
  131089. testcase( i==9 ); /* FOREIGN */
  131090. testcase( i==10 ); /* FOR */
  131091. testcase( i==11 ); /* IGNORE */
  131092. testcase( i==12 ); /* REGEXP */
  131093. testcase( i==13 ); /* EXPLAIN */
  131094. testcase( i==14 ); /* INSTEAD */
  131095. testcase( i==15 ); /* ADD */
  131096. testcase( i==16 ); /* DATABASE */
  131097. testcase( i==17 ); /* AS */
  131098. testcase( i==18 ); /* SELECT */
  131099. testcase( i==19 ); /* TABLE */
  131100. testcase( i==20 ); /* LEFT */
  131101. testcase( i==21 ); /* THEN */
  131102. testcase( i==22 ); /* END */
  131103. testcase( i==23 ); /* DEFERRABLE */
  131104. testcase( i==24 ); /* ELSE */
  131105. testcase( i==25 ); /* EXCEPT */
  131106. testcase( i==26 ); /* TRANSACTION */
  131107. testcase( i==27 ); /* ACTION */
  131108. testcase( i==28 ); /* ON */
  131109. testcase( i==29 ); /* NATURAL */
  131110. testcase( i==30 ); /* ALTER */
  131111. testcase( i==31 ); /* RAISE */
  131112. testcase( i==32 ); /* EXCLUSIVE */
  131113. testcase( i==33 ); /* EXISTS */
  131114. testcase( i==34 ); /* SAVEPOINT */
  131115. testcase( i==35 ); /* INTERSECT */
  131116. testcase( i==36 ); /* TRIGGER */
  131117. testcase( i==37 ); /* REFERENCES */
  131118. testcase( i==38 ); /* CONSTRAINT */
  131119. testcase( i==39 ); /* INTO */
  131120. testcase( i==40 ); /* OFFSET */
  131121. testcase( i==41 ); /* OF */
  131122. testcase( i==42 ); /* SET */
  131123. testcase( i==43 ); /* TEMPORARY */
  131124. testcase( i==44 ); /* TEMP */
  131125. testcase( i==45 ); /* OR */
  131126. testcase( i==46 ); /* UNIQUE */
  131127. testcase( i==47 ); /* QUERY */
  131128. testcase( i==48 ); /* WITHOUT */
  131129. testcase( i==49 ); /* WITH */
  131130. testcase( i==50 ); /* OUTER */
  131131. testcase( i==51 ); /* RELEASE */
  131132. testcase( i==52 ); /* ATTACH */
  131133. testcase( i==53 ); /* HAVING */
  131134. testcase( i==54 ); /* GROUP */
  131135. testcase( i==55 ); /* UPDATE */
  131136. testcase( i==56 ); /* BEGIN */
  131137. testcase( i==57 ); /* INNER */
  131138. testcase( i==58 ); /* RECURSIVE */
  131139. testcase( i==59 ); /* BETWEEN */
  131140. testcase( i==60 ); /* NOTNULL */
  131141. testcase( i==61 ); /* NOT */
  131142. testcase( i==62 ); /* NO */
  131143. testcase( i==63 ); /* NULL */
  131144. testcase( i==64 ); /* LIKE */
  131145. testcase( i==65 ); /* CASCADE */
  131146. testcase( i==66 ); /* ASC */
  131147. testcase( i==67 ); /* DELETE */
  131148. testcase( i==68 ); /* CASE */
  131149. testcase( i==69 ); /* COLLATE */
  131150. testcase( i==70 ); /* CREATE */
  131151. testcase( i==71 ); /* CURRENT_DATE */
  131152. testcase( i==72 ); /* DETACH */
  131153. testcase( i==73 ); /* IMMEDIATE */
  131154. testcase( i==74 ); /* JOIN */
  131155. testcase( i==75 ); /* INSERT */
  131156. testcase( i==76 ); /* MATCH */
  131157. testcase( i==77 ); /* PLAN */
  131158. testcase( i==78 ); /* ANALYZE */
  131159. testcase( i==79 ); /* PRAGMA */
  131160. testcase( i==80 ); /* ABORT */
  131161. testcase( i==81 ); /* VALUES */
  131162. testcase( i==82 ); /* VIRTUAL */
  131163. testcase( i==83 ); /* LIMIT */
  131164. testcase( i==84 ); /* WHEN */
  131165. testcase( i==85 ); /* WHERE */
  131166. testcase( i==86 ); /* RENAME */
  131167. testcase( i==87 ); /* AFTER */
  131168. testcase( i==88 ); /* REPLACE */
  131169. testcase( i==89 ); /* AND */
  131170. testcase( i==90 ); /* DEFAULT */
  131171. testcase( i==91 ); /* AUTOINCREMENT */
  131172. testcase( i==92 ); /* TO */
  131173. testcase( i==93 ); /* IN */
  131174. testcase( i==94 ); /* CAST */
  131175. testcase( i==95 ); /* COLUMN */
  131176. testcase( i==96 ); /* COMMIT */
  131177. testcase( i==97 ); /* CONFLICT */
  131178. testcase( i==98 ); /* CROSS */
  131179. testcase( i==99 ); /* CURRENT_TIMESTAMP */
  131180. testcase( i==100 ); /* CURRENT_TIME */
  131181. testcase( i==101 ); /* PRIMARY */
  131182. testcase( i==102 ); /* DEFERRED */
  131183. testcase( i==103 ); /* DISTINCT */
  131184. testcase( i==104 ); /* IS */
  131185. testcase( i==105 ); /* DROP */
  131186. testcase( i==106 ); /* FAIL */
  131187. testcase( i==107 ); /* FROM */
  131188. testcase( i==108 ); /* FULL */
  131189. testcase( i==109 ); /* GLOB */
  131190. testcase( i==110 ); /* BY */
  131191. testcase( i==111 ); /* IF */
  131192. testcase( i==112 ); /* ISNULL */
  131193. testcase( i==113 ); /* ORDER */
  131194. testcase( i==114 ); /* RESTRICT */
  131195. testcase( i==115 ); /* RIGHT */
  131196. testcase( i==116 ); /* ROLLBACK */
  131197. testcase( i==117 ); /* ROW */
  131198. testcase( i==118 ); /* UNION */
  131199. testcase( i==119 ); /* USING */
  131200. testcase( i==120 ); /* VACUUM */
  131201. testcase( i==121 ); /* VIEW */
  131202. testcase( i==122 ); /* INITIALLY */
  131203. testcase( i==123 ); /* ALL */
  131204. *pType = aCode[i];
  131205. break;
  131206. }
  131207. }
  131208. return n;
  131209. }
  131210. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  131211. int id = TK_ID;
  131212. keywordCode((char*)z, n, &id);
  131213. return id;
  131214. }
  131215. #define SQLITE_N_KEYWORD 124
  131216. /************** End of keywordhash.h *****************************************/
  131217. /************** Continuing where we left off in tokenize.c *******************/
  131218. /*
  131219. ** If X is a character that can be used in an identifier then
  131220. ** IdChar(X) will be true. Otherwise it is false.
  131221. **
  131222. ** For ASCII, any character with the high-order bit set is
  131223. ** allowed in an identifier. For 7-bit characters,
  131224. ** sqlite3IsIdChar[X] must be 1.
  131225. **
  131226. ** For EBCDIC, the rules are more complex but have the same
  131227. ** end result.
  131228. **
  131229. ** Ticket #1066. the SQL standard does not allow '$' in the
  131230. ** middle of identifiers. But many SQL implementations do.
  131231. ** SQLite will allow '$' in identifiers for compatibility.
  131232. ** But the feature is undocumented.
  131233. */
  131234. #ifdef SQLITE_ASCII
  131235. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  131236. #endif
  131237. #ifdef SQLITE_EBCDIC
  131238. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  131239. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  131240. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  131241. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  131242. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  131243. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  131244. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  131245. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  131246. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  131247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  131248. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  131249. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  131250. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  131251. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  131252. };
  131253. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  131254. #endif
  131255. /* Make the IdChar function accessible from ctime.c */
  131256. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  131257. SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
  131258. #endif
  131259. /*
  131260. ** Return the length (in bytes) of the token that begins at z[0].
  131261. ** Store the token type in *tokenType before returning.
  131262. */
  131263. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  131264. int i, c;
  131265. switch( aiClass[*z] ){ /* Switch on the character-class of the first byte
  131266. ** of the token. See the comment on the CC_ defines
  131267. ** above. */
  131268. case CC_SPACE: {
  131269. testcase( z[0]==' ' );
  131270. testcase( z[0]=='\t' );
  131271. testcase( z[0]=='\n' );
  131272. testcase( z[0]=='\f' );
  131273. testcase( z[0]=='\r' );
  131274. for(i=1; sqlite3Isspace(z[i]); i++){}
  131275. *tokenType = TK_SPACE;
  131276. return i;
  131277. }
  131278. case CC_MINUS: {
  131279. if( z[1]=='-' ){
  131280. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  131281. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  131282. return i;
  131283. }
  131284. *tokenType = TK_MINUS;
  131285. return 1;
  131286. }
  131287. case CC_LP: {
  131288. *tokenType = TK_LP;
  131289. return 1;
  131290. }
  131291. case CC_RP: {
  131292. *tokenType = TK_RP;
  131293. return 1;
  131294. }
  131295. case CC_SEMI: {
  131296. *tokenType = TK_SEMI;
  131297. return 1;
  131298. }
  131299. case CC_PLUS: {
  131300. *tokenType = TK_PLUS;
  131301. return 1;
  131302. }
  131303. case CC_STAR: {
  131304. *tokenType = TK_STAR;
  131305. return 1;
  131306. }
  131307. case CC_SLASH: {
  131308. if( z[1]!='*' || z[2]==0 ){
  131309. *tokenType = TK_SLASH;
  131310. return 1;
  131311. }
  131312. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  131313. if( c ) i++;
  131314. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  131315. return i;
  131316. }
  131317. case CC_PERCENT: {
  131318. *tokenType = TK_REM;
  131319. return 1;
  131320. }
  131321. case CC_EQ: {
  131322. *tokenType = TK_EQ;
  131323. return 1 + (z[1]=='=');
  131324. }
  131325. case CC_LT: {
  131326. if( (c=z[1])=='=' ){
  131327. *tokenType = TK_LE;
  131328. return 2;
  131329. }else if( c=='>' ){
  131330. *tokenType = TK_NE;
  131331. return 2;
  131332. }else if( c=='<' ){
  131333. *tokenType = TK_LSHIFT;
  131334. return 2;
  131335. }else{
  131336. *tokenType = TK_LT;
  131337. return 1;
  131338. }
  131339. }
  131340. case CC_GT: {
  131341. if( (c=z[1])=='=' ){
  131342. *tokenType = TK_GE;
  131343. return 2;
  131344. }else if( c=='>' ){
  131345. *tokenType = TK_RSHIFT;
  131346. return 2;
  131347. }else{
  131348. *tokenType = TK_GT;
  131349. return 1;
  131350. }
  131351. }
  131352. case CC_BANG: {
  131353. if( z[1]!='=' ){
  131354. *tokenType = TK_ILLEGAL;
  131355. return 1;
  131356. }else{
  131357. *tokenType = TK_NE;
  131358. return 2;
  131359. }
  131360. }
  131361. case CC_PIPE: {
  131362. if( z[1]!='|' ){
  131363. *tokenType = TK_BITOR;
  131364. return 1;
  131365. }else{
  131366. *tokenType = TK_CONCAT;
  131367. return 2;
  131368. }
  131369. }
  131370. case CC_COMMA: {
  131371. *tokenType = TK_COMMA;
  131372. return 1;
  131373. }
  131374. case CC_AND: {
  131375. *tokenType = TK_BITAND;
  131376. return 1;
  131377. }
  131378. case CC_TILDA: {
  131379. *tokenType = TK_BITNOT;
  131380. return 1;
  131381. }
  131382. case CC_QUOTE: {
  131383. int delim = z[0];
  131384. testcase( delim=='`' );
  131385. testcase( delim=='\'' );
  131386. testcase( delim=='"' );
  131387. for(i=1; (c=z[i])!=0; i++){
  131388. if( c==delim ){
  131389. if( z[i+1]==delim ){
  131390. i++;
  131391. }else{
  131392. break;
  131393. }
  131394. }
  131395. }
  131396. if( c=='\'' ){
  131397. *tokenType = TK_STRING;
  131398. return i+1;
  131399. }else if( c!=0 ){
  131400. *tokenType = TK_ID;
  131401. return i+1;
  131402. }else{
  131403. *tokenType = TK_ILLEGAL;
  131404. return i;
  131405. }
  131406. }
  131407. case CC_DOT: {
  131408. #ifndef SQLITE_OMIT_FLOATING_POINT
  131409. if( !sqlite3Isdigit(z[1]) )
  131410. #endif
  131411. {
  131412. *tokenType = TK_DOT;
  131413. return 1;
  131414. }
  131415. /* If the next character is a digit, this is a floating point
  131416. ** number that begins with ".". Fall thru into the next case */
  131417. }
  131418. case CC_DIGIT: {
  131419. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  131420. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  131421. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  131422. testcase( z[0]=='9' );
  131423. *tokenType = TK_INTEGER;
  131424. #ifndef SQLITE_OMIT_HEX_INTEGER
  131425. if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
  131426. for(i=3; sqlite3Isxdigit(z[i]); i++){}
  131427. return i;
  131428. }
  131429. #endif
  131430. for(i=0; sqlite3Isdigit(z[i]); i++){}
  131431. #ifndef SQLITE_OMIT_FLOATING_POINT
  131432. if( z[i]=='.' ){
  131433. i++;
  131434. while( sqlite3Isdigit(z[i]) ){ i++; }
  131435. *tokenType = TK_FLOAT;
  131436. }
  131437. if( (z[i]=='e' || z[i]=='E') &&
  131438. ( sqlite3Isdigit(z[i+1])
  131439. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  131440. )
  131441. ){
  131442. i += 2;
  131443. while( sqlite3Isdigit(z[i]) ){ i++; }
  131444. *tokenType = TK_FLOAT;
  131445. }
  131446. #endif
  131447. while( IdChar(z[i]) ){
  131448. *tokenType = TK_ILLEGAL;
  131449. i++;
  131450. }
  131451. return i;
  131452. }
  131453. case CC_QUOTE2: {
  131454. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  131455. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  131456. return i;
  131457. }
  131458. case CC_VARNUM: {
  131459. *tokenType = TK_VARIABLE;
  131460. for(i=1; sqlite3Isdigit(z[i]); i++){}
  131461. return i;
  131462. }
  131463. case CC_DOLLAR:
  131464. case CC_VARALPHA: {
  131465. int n = 0;
  131466. testcase( z[0]=='$' ); testcase( z[0]=='@' );
  131467. testcase( z[0]==':' ); testcase( z[0]=='#' );
  131468. *tokenType = TK_VARIABLE;
  131469. for(i=1; (c=z[i])!=0; i++){
  131470. if( IdChar(c) ){
  131471. n++;
  131472. #ifndef SQLITE_OMIT_TCL_VARIABLE
  131473. }else if( c=='(' && n>0 ){
  131474. do{
  131475. i++;
  131476. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  131477. if( c==')' ){
  131478. i++;
  131479. }else{
  131480. *tokenType = TK_ILLEGAL;
  131481. }
  131482. break;
  131483. }else if( c==':' && z[i+1]==':' ){
  131484. i++;
  131485. #endif
  131486. }else{
  131487. break;
  131488. }
  131489. }
  131490. if( n==0 ) *tokenType = TK_ILLEGAL;
  131491. return i;
  131492. }
  131493. case CC_KYWD: {
  131494. for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
  131495. if( IdChar(z[i]) ){
  131496. /* This token started out using characters that can appear in keywords,
  131497. ** but z[i] is a character not allowed within keywords, so this must
  131498. ** be an identifier instead */
  131499. i++;
  131500. break;
  131501. }
  131502. *tokenType = TK_ID;
  131503. return keywordCode((char*)z, i, tokenType);
  131504. }
  131505. case CC_X: {
  131506. #ifndef SQLITE_OMIT_BLOB_LITERAL
  131507. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  131508. if( z[1]=='\'' ){
  131509. *tokenType = TK_BLOB;
  131510. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  131511. if( z[i]!='\'' || i%2 ){
  131512. *tokenType = TK_ILLEGAL;
  131513. while( z[i] && z[i]!='\'' ){ i++; }
  131514. }
  131515. if( z[i] ) i++;
  131516. return i;
  131517. }
  131518. #endif
  131519. /* If it is not a BLOB literal, then it must be an ID, since no
  131520. ** SQL keywords start with the letter 'x'. Fall through */
  131521. }
  131522. case CC_ID: {
  131523. i = 1;
  131524. break;
  131525. }
  131526. default: {
  131527. *tokenType = TK_ILLEGAL;
  131528. return 1;
  131529. }
  131530. }
  131531. while( IdChar(z[i]) ){ i++; }
  131532. *tokenType = TK_ID;
  131533. return i;
  131534. }
  131535. /*
  131536. ** Run the parser on the given SQL string. The parser structure is
  131537. ** passed in. An SQLITE_ status code is returned. If an error occurs
  131538. ** then an and attempt is made to write an error message into
  131539. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  131540. ** error message.
  131541. */
  131542. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  131543. int nErr = 0; /* Number of errors encountered */
  131544. void *pEngine; /* The LEMON-generated LALR(1) parser */
  131545. int n = 0; /* Length of the next token token */
  131546. int tokenType; /* type of the next token */
  131547. int lastTokenParsed = -1; /* type of the previous token */
  131548. sqlite3 *db = pParse->db; /* The database connection */
  131549. int mxSqlLen; /* Max length of an SQL string */
  131550. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  131551. yyParser sEngine; /* Space to hold the Lemon-generated Parser object */
  131552. #endif
  131553. assert( zSql!=0 );
  131554. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  131555. if( db->nVdbeActive==0 ){
  131556. db->u1.isInterrupted = 0;
  131557. }
  131558. pParse->rc = SQLITE_OK;
  131559. pParse->zTail = zSql;
  131560. assert( pzErrMsg!=0 );
  131561. /* sqlite3ParserTrace(stdout, "parser: "); */
  131562. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  131563. pEngine = &sEngine;
  131564. sqlite3ParserInit(pEngine);
  131565. #else
  131566. pEngine = sqlite3ParserAlloc(sqlite3Malloc);
  131567. if( pEngine==0 ){
  131568. sqlite3OomFault(db);
  131569. return SQLITE_NOMEM_BKPT;
  131570. }
  131571. #endif
  131572. assert( pParse->pNewTable==0 );
  131573. assert( pParse->pNewTrigger==0 );
  131574. assert( pParse->nVar==0 );
  131575. assert( pParse->pVList==0 );
  131576. while( 1 ){
  131577. if( zSql[0]!=0 ){
  131578. n = sqlite3GetToken((u8*)zSql, &tokenType);
  131579. mxSqlLen -= n;
  131580. if( mxSqlLen<0 ){
  131581. pParse->rc = SQLITE_TOOBIG;
  131582. break;
  131583. }
  131584. }else{
  131585. /* Upon reaching the end of input, call the parser two more times
  131586. ** with tokens TK_SEMI and 0, in that order. */
  131587. if( lastTokenParsed==TK_SEMI ){
  131588. tokenType = 0;
  131589. }else if( lastTokenParsed==0 ){
  131590. break;
  131591. }else{
  131592. tokenType = TK_SEMI;
  131593. }
  131594. zSql -= n;
  131595. }
  131596. if( tokenType>=TK_SPACE ){
  131597. assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
  131598. if( db->u1.isInterrupted ){
  131599. pParse->rc = SQLITE_INTERRUPT;
  131600. break;
  131601. }
  131602. if( tokenType==TK_ILLEGAL ){
  131603. sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql);
  131604. break;
  131605. }
  131606. zSql += n;
  131607. }else{
  131608. pParse->sLastToken.z = zSql;
  131609. pParse->sLastToken.n = n;
  131610. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  131611. lastTokenParsed = tokenType;
  131612. zSql += n;
  131613. if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
  131614. }
  131615. }
  131616. assert( nErr==0 );
  131617. pParse->zTail = zSql;
  131618. #ifdef YYTRACKMAXSTACKDEPTH
  131619. sqlite3_mutex_enter(sqlite3MallocMutex());
  131620. sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
  131621. sqlite3ParserStackPeak(pEngine)
  131622. );
  131623. sqlite3_mutex_leave(sqlite3MallocMutex());
  131624. #endif /* YYDEBUG */
  131625. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  131626. sqlite3ParserFinalize(pEngine);
  131627. #else
  131628. sqlite3ParserFree(pEngine, sqlite3_free);
  131629. #endif
  131630. if( db->mallocFailed ){
  131631. pParse->rc = SQLITE_NOMEM_BKPT;
  131632. }
  131633. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  131634. pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
  131635. }
  131636. assert( pzErrMsg!=0 );
  131637. if( pParse->zErrMsg ){
  131638. *pzErrMsg = pParse->zErrMsg;
  131639. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  131640. pParse->zErrMsg = 0;
  131641. nErr++;
  131642. }
  131643. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  131644. sqlite3VdbeDelete(pParse->pVdbe);
  131645. pParse->pVdbe = 0;
  131646. }
  131647. #ifndef SQLITE_OMIT_SHARED_CACHE
  131648. if( pParse->nested==0 ){
  131649. sqlite3DbFree(db, pParse->aTableLock);
  131650. pParse->aTableLock = 0;
  131651. pParse->nTableLock = 0;
  131652. }
  131653. #endif
  131654. #ifndef SQLITE_OMIT_VIRTUALTABLE
  131655. sqlite3_free(pParse->apVtabLock);
  131656. #endif
  131657. if( !IN_DECLARE_VTAB ){
  131658. /* If the pParse->declareVtab flag is set, do not delete any table
  131659. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  131660. ** will take responsibility for freeing the Table structure.
  131661. */
  131662. sqlite3DeleteTable(db, pParse->pNewTable);
  131663. }
  131664. if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
  131665. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  131666. sqlite3DbFree(db, pParse->pVList);
  131667. while( pParse->pAinc ){
  131668. AutoincInfo *p = pParse->pAinc;
  131669. pParse->pAinc = p->pNext;
  131670. sqlite3DbFreeNN(db, p);
  131671. }
  131672. while( pParse->pZombieTab ){
  131673. Table *p = pParse->pZombieTab;
  131674. pParse->pZombieTab = p->pNextZombie;
  131675. sqlite3DeleteTable(db, p);
  131676. }
  131677. assert( nErr==0 || pParse->rc!=SQLITE_OK );
  131678. return nErr;
  131679. }
  131680. /************** End of tokenize.c ********************************************/
  131681. /************** Begin file complete.c ****************************************/
  131682. /*
  131683. ** 2001 September 15
  131684. **
  131685. ** The author disclaims copyright to this source code. In place of
  131686. ** a legal notice, here is a blessing:
  131687. **
  131688. ** May you do good and not evil.
  131689. ** May you find forgiveness for yourself and forgive others.
  131690. ** May you share freely, never taking more than you give.
  131691. **
  131692. *************************************************************************
  131693. ** An tokenizer for SQL
  131694. **
  131695. ** This file contains C code that implements the sqlite3_complete() API.
  131696. ** This code used to be part of the tokenizer.c source file. But by
  131697. ** separating it out, the code will be automatically omitted from
  131698. ** static links that do not use it.
  131699. */
  131700. /* #include "sqliteInt.h" */
  131701. #ifndef SQLITE_OMIT_COMPLETE
  131702. /*
  131703. ** This is defined in tokenize.c. We just have to import the definition.
  131704. */
  131705. #ifndef SQLITE_AMALGAMATION
  131706. #ifdef SQLITE_ASCII
  131707. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  131708. #endif
  131709. #ifdef SQLITE_EBCDIC
  131710. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  131711. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  131712. #endif
  131713. #endif /* SQLITE_AMALGAMATION */
  131714. /*
  131715. ** Token types used by the sqlite3_complete() routine. See the header
  131716. ** comments on that procedure for additional information.
  131717. */
  131718. #define tkSEMI 0
  131719. #define tkWS 1
  131720. #define tkOTHER 2
  131721. #ifndef SQLITE_OMIT_TRIGGER
  131722. #define tkEXPLAIN 3
  131723. #define tkCREATE 4
  131724. #define tkTEMP 5
  131725. #define tkTRIGGER 6
  131726. #define tkEND 7
  131727. #endif
  131728. /*
  131729. ** Return TRUE if the given SQL string ends in a semicolon.
  131730. **
  131731. ** Special handling is require for CREATE TRIGGER statements.
  131732. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  131733. ** must end with ";END;".
  131734. **
  131735. ** This implementation uses a state machine with 8 states:
  131736. **
  131737. ** (0) INVALID We have not yet seen a non-whitespace character.
  131738. **
  131739. ** (1) START At the beginning or end of an SQL statement. This routine
  131740. ** returns 1 if it ends in the START state and 0 if it ends
  131741. ** in any other state.
  131742. **
  131743. ** (2) NORMAL We are in the middle of statement which ends with a single
  131744. ** semicolon.
  131745. **
  131746. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  131747. ** a statement.
  131748. **
  131749. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  131750. ** statement, possibly preceded by EXPLAIN and/or followed by
  131751. ** TEMP or TEMPORARY
  131752. **
  131753. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  131754. ** ended by a semicolon, the keyword END, and another semicolon.
  131755. **
  131756. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  131757. ** the end of a trigger definition.
  131758. **
  131759. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  131760. ** of a trigger definition.
  131761. **
  131762. ** Transitions between states above are determined by tokens extracted
  131763. ** from the input. The following tokens are significant:
  131764. **
  131765. ** (0) tkSEMI A semicolon.
  131766. ** (1) tkWS Whitespace.
  131767. ** (2) tkOTHER Any other SQL token.
  131768. ** (3) tkEXPLAIN The "explain" keyword.
  131769. ** (4) tkCREATE The "create" keyword.
  131770. ** (5) tkTEMP The "temp" or "temporary" keyword.
  131771. ** (6) tkTRIGGER The "trigger" keyword.
  131772. ** (7) tkEND The "end" keyword.
  131773. **
  131774. ** Whitespace never causes a state transition and is always ignored.
  131775. ** This means that a SQL string of all whitespace is invalid.
  131776. **
  131777. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  131778. ** to recognize the end of a trigger can be omitted. All we have to do
  131779. ** is look for a semicolon that is not part of an string or comment.
  131780. */
  131781. SQLITE_API int sqlite3_complete(const char *zSql){
  131782. u8 state = 0; /* Current state, using numbers defined in header comment */
  131783. u8 token; /* Value of the next token */
  131784. #ifndef SQLITE_OMIT_TRIGGER
  131785. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  131786. ** statement. This is the normal case.
  131787. */
  131788. static const u8 trans[8][8] = {
  131789. /* Token: */
  131790. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  131791. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  131792. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  131793. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  131794. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  131795. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  131796. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  131797. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  131798. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  131799. };
  131800. #else
  131801. /* If triggers are not supported by this compile then the statement machine
  131802. ** used to detect the end of a statement is much simpler
  131803. */
  131804. static const u8 trans[3][3] = {
  131805. /* Token: */
  131806. /* State: ** SEMI WS OTHER */
  131807. /* 0 INVALID: */ { 1, 0, 2, },
  131808. /* 1 START: */ { 1, 1, 2, },
  131809. /* 2 NORMAL: */ { 1, 2, 2, },
  131810. };
  131811. #endif /* SQLITE_OMIT_TRIGGER */
  131812. #ifdef SQLITE_ENABLE_API_ARMOR
  131813. if( zSql==0 ){
  131814. (void)SQLITE_MISUSE_BKPT;
  131815. return 0;
  131816. }
  131817. #endif
  131818. while( *zSql ){
  131819. switch( *zSql ){
  131820. case ';': { /* A semicolon */
  131821. token = tkSEMI;
  131822. break;
  131823. }
  131824. case ' ':
  131825. case '\r':
  131826. case '\t':
  131827. case '\n':
  131828. case '\f': { /* White space is ignored */
  131829. token = tkWS;
  131830. break;
  131831. }
  131832. case '/': { /* C-style comments */
  131833. if( zSql[1]!='*' ){
  131834. token = tkOTHER;
  131835. break;
  131836. }
  131837. zSql += 2;
  131838. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  131839. if( zSql[0]==0 ) return 0;
  131840. zSql++;
  131841. token = tkWS;
  131842. break;
  131843. }
  131844. case '-': { /* SQL-style comments from "--" to end of line */
  131845. if( zSql[1]!='-' ){
  131846. token = tkOTHER;
  131847. break;
  131848. }
  131849. while( *zSql && *zSql!='\n' ){ zSql++; }
  131850. if( *zSql==0 ) return state==1;
  131851. token = tkWS;
  131852. break;
  131853. }
  131854. case '[': { /* Microsoft-style identifiers in [...] */
  131855. zSql++;
  131856. while( *zSql && *zSql!=']' ){ zSql++; }
  131857. if( *zSql==0 ) return 0;
  131858. token = tkOTHER;
  131859. break;
  131860. }
  131861. case '`': /* Grave-accent quoted symbols used by MySQL */
  131862. case '"': /* single- and double-quoted strings */
  131863. case '\'': {
  131864. int c = *zSql;
  131865. zSql++;
  131866. while( *zSql && *zSql!=c ){ zSql++; }
  131867. if( *zSql==0 ) return 0;
  131868. token = tkOTHER;
  131869. break;
  131870. }
  131871. default: {
  131872. #ifdef SQLITE_EBCDIC
  131873. unsigned char c;
  131874. #endif
  131875. if( IdChar((u8)*zSql) ){
  131876. /* Keywords and unquoted identifiers */
  131877. int nId;
  131878. for(nId=1; IdChar(zSql[nId]); nId++){}
  131879. #ifdef SQLITE_OMIT_TRIGGER
  131880. token = tkOTHER;
  131881. #else
  131882. switch( *zSql ){
  131883. case 'c': case 'C': {
  131884. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  131885. token = tkCREATE;
  131886. }else{
  131887. token = tkOTHER;
  131888. }
  131889. break;
  131890. }
  131891. case 't': case 'T': {
  131892. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  131893. token = tkTRIGGER;
  131894. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  131895. token = tkTEMP;
  131896. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  131897. token = tkTEMP;
  131898. }else{
  131899. token = tkOTHER;
  131900. }
  131901. break;
  131902. }
  131903. case 'e': case 'E': {
  131904. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  131905. token = tkEND;
  131906. }else
  131907. #ifndef SQLITE_OMIT_EXPLAIN
  131908. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  131909. token = tkEXPLAIN;
  131910. }else
  131911. #endif
  131912. {
  131913. token = tkOTHER;
  131914. }
  131915. break;
  131916. }
  131917. default: {
  131918. token = tkOTHER;
  131919. break;
  131920. }
  131921. }
  131922. #endif /* SQLITE_OMIT_TRIGGER */
  131923. zSql += nId-1;
  131924. }else{
  131925. /* Operators and special symbols */
  131926. token = tkOTHER;
  131927. }
  131928. break;
  131929. }
  131930. }
  131931. state = trans[state][token];
  131932. zSql++;
  131933. }
  131934. return state==1;
  131935. }
  131936. #ifndef SQLITE_OMIT_UTF16
  131937. /*
  131938. ** This routine is the same as the sqlite3_complete() routine described
  131939. ** above, except that the parameter is required to be UTF-16 encoded, not
  131940. ** UTF-8.
  131941. */
  131942. SQLITE_API int sqlite3_complete16(const void *zSql){
  131943. sqlite3_value *pVal;
  131944. char const *zSql8;
  131945. int rc;
  131946. #ifndef SQLITE_OMIT_AUTOINIT
  131947. rc = sqlite3_initialize();
  131948. if( rc ) return rc;
  131949. #endif
  131950. pVal = sqlite3ValueNew(0);
  131951. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  131952. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  131953. if( zSql8 ){
  131954. rc = sqlite3_complete(zSql8);
  131955. }else{
  131956. rc = SQLITE_NOMEM_BKPT;
  131957. }
  131958. sqlite3ValueFree(pVal);
  131959. return rc & 0xff;
  131960. }
  131961. #endif /* SQLITE_OMIT_UTF16 */
  131962. #endif /* SQLITE_OMIT_COMPLETE */
  131963. /************** End of complete.c ********************************************/
  131964. /************** Begin file main.c ********************************************/
  131965. /*
  131966. ** 2001 September 15
  131967. **
  131968. ** The author disclaims copyright to this source code. In place of
  131969. ** a legal notice, here is a blessing:
  131970. **
  131971. ** May you do good and not evil.
  131972. ** May you find forgiveness for yourself and forgive others.
  131973. ** May you share freely, never taking more than you give.
  131974. **
  131975. *************************************************************************
  131976. ** Main file for the SQLite library. The routines in this file
  131977. ** implement the programmer interface to the library. Routines in
  131978. ** other files are for internal use by SQLite and should not be
  131979. ** accessed by users of the library.
  131980. */
  131981. /* #include "sqliteInt.h" */
  131982. #ifdef SQLITE_ENABLE_FTS3
  131983. /************** Include fts3.h in the middle of main.c ***********************/
  131984. /************** Begin file fts3.h ********************************************/
  131985. /*
  131986. ** 2006 Oct 10
  131987. **
  131988. ** The author disclaims copyright to this source code. In place of
  131989. ** a legal notice, here is a blessing:
  131990. **
  131991. ** May you do good and not evil.
  131992. ** May you find forgiveness for yourself and forgive others.
  131993. ** May you share freely, never taking more than you give.
  131994. **
  131995. ******************************************************************************
  131996. **
  131997. ** This header file is used by programs that want to link against the
  131998. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  131999. */
  132000. /* #include "sqlite3.h" */
  132001. #if 0
  132002. extern "C" {
  132003. #endif /* __cplusplus */
  132004. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  132005. #if 0
  132006. } /* extern "C" */
  132007. #endif /* __cplusplus */
  132008. /************** End of fts3.h ************************************************/
  132009. /************** Continuing where we left off in main.c ***********************/
  132010. #endif
  132011. #ifdef SQLITE_ENABLE_RTREE
  132012. /************** Include rtree.h in the middle of main.c **********************/
  132013. /************** Begin file rtree.h *******************************************/
  132014. /*
  132015. ** 2008 May 26
  132016. **
  132017. ** The author disclaims copyright to this source code. In place of
  132018. ** a legal notice, here is a blessing:
  132019. **
  132020. ** May you do good and not evil.
  132021. ** May you find forgiveness for yourself and forgive others.
  132022. ** May you share freely, never taking more than you give.
  132023. **
  132024. ******************************************************************************
  132025. **
  132026. ** This header file is used by programs that want to link against the
  132027. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  132028. */
  132029. /* #include "sqlite3.h" */
  132030. #if 0
  132031. extern "C" {
  132032. #endif /* __cplusplus */
  132033. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  132034. #if 0
  132035. } /* extern "C" */
  132036. #endif /* __cplusplus */
  132037. /************** End of rtree.h ***********************************************/
  132038. /************** Continuing where we left off in main.c ***********************/
  132039. #endif
  132040. #ifdef SQLITE_ENABLE_ICU
  132041. /************** Include sqliteicu.h in the middle of main.c ******************/
  132042. /************** Begin file sqliteicu.h ***************************************/
  132043. /*
  132044. ** 2008 May 26
  132045. **
  132046. ** The author disclaims copyright to this source code. In place of
  132047. ** a legal notice, here is a blessing:
  132048. **
  132049. ** May you do good and not evil.
  132050. ** May you find forgiveness for yourself and forgive others.
  132051. ** May you share freely, never taking more than you give.
  132052. **
  132053. ******************************************************************************
  132054. **
  132055. ** This header file is used by programs that want to link against the
  132056. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  132057. */
  132058. /* #include "sqlite3.h" */
  132059. #if 0
  132060. extern "C" {
  132061. #endif /* __cplusplus */
  132062. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  132063. #if 0
  132064. } /* extern "C" */
  132065. #endif /* __cplusplus */
  132066. /************** End of sqliteicu.h *******************************************/
  132067. /************** Continuing where we left off in main.c ***********************/
  132068. #endif
  132069. #ifdef SQLITE_ENABLE_JSON1
  132070. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
  132071. #endif
  132072. #ifdef SQLITE_ENABLE_FTS5
  132073. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
  132074. #endif
  132075. #ifndef SQLITE_AMALGAMATION
  132076. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  132077. ** contains the text of SQLITE_VERSION macro.
  132078. */
  132079. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  132080. #endif
  132081. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  132082. ** a pointer to the to the sqlite3_version[] string constant.
  132083. */
  132084. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  132085. /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
  132086. ** pointer to a string constant whose value is the same as the
  132087. ** SQLITE_SOURCE_ID C preprocessor macro.
  132088. */
  132089. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  132090. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  132091. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  132092. */
  132093. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  132094. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  132095. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  132096. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  132097. */
  132098. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  132099. /*
  132100. ** When compiling the test fixture or with debugging enabled (on Win32),
  132101. ** this variable being set to non-zero will cause OSTRACE macros to emit
  132102. ** extra diagnostic information.
  132103. */
  132104. #ifdef SQLITE_HAVE_OS_TRACE
  132105. # ifndef SQLITE_DEBUG_OS_TRACE
  132106. # define SQLITE_DEBUG_OS_TRACE 0
  132107. # endif
  132108. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  132109. #endif
  132110. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  132111. /*
  132112. ** If the following function pointer is not NULL and if
  132113. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  132114. ** I/O active are written using this function. These messages
  132115. ** are intended for debugging activity only.
  132116. */
  132117. SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
  132118. #endif
  132119. /*
  132120. ** If the following global variable points to a string which is the
  132121. ** name of a directory, then that directory will be used to store
  132122. ** temporary files.
  132123. **
  132124. ** See also the "PRAGMA temp_store_directory" SQL command.
  132125. */
  132126. SQLITE_API char *sqlite3_temp_directory = 0;
  132127. /*
  132128. ** If the following global variable points to a string which is the
  132129. ** name of a directory, then that directory will be used to store
  132130. ** all database files specified with a relative pathname.
  132131. **
  132132. ** See also the "PRAGMA data_store_directory" SQL command.
  132133. */
  132134. SQLITE_API char *sqlite3_data_directory = 0;
  132135. /*
  132136. ** Initialize SQLite.
  132137. **
  132138. ** This routine must be called to initialize the memory allocation,
  132139. ** VFS, and mutex subsystems prior to doing any serious work with
  132140. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  132141. ** this routine will be called automatically by key routines such as
  132142. ** sqlite3_open().
  132143. **
  132144. ** This routine is a no-op except on its very first call for the process,
  132145. ** or for the first call after a call to sqlite3_shutdown.
  132146. **
  132147. ** The first thread to call this routine runs the initialization to
  132148. ** completion. If subsequent threads call this routine before the first
  132149. ** thread has finished the initialization process, then the subsequent
  132150. ** threads must block until the first thread finishes with the initialization.
  132151. **
  132152. ** The first thread might call this routine recursively. Recursive
  132153. ** calls to this routine should not block, of course. Otherwise the
  132154. ** initialization process would never complete.
  132155. **
  132156. ** Let X be the first thread to enter this routine. Let Y be some other
  132157. ** thread. Then while the initial invocation of this routine by X is
  132158. ** incomplete, it is required that:
  132159. **
  132160. ** * Calls to this routine from Y must block until the outer-most
  132161. ** call by X completes.
  132162. **
  132163. ** * Recursive calls to this routine from thread X return immediately
  132164. ** without blocking.
  132165. */
  132166. SQLITE_API int sqlite3_initialize(void){
  132167. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  132168. int rc; /* Result code */
  132169. #ifdef SQLITE_EXTRA_INIT
  132170. int bRunExtraInit = 0; /* Extra initialization needed */
  132171. #endif
  132172. #ifdef SQLITE_OMIT_WSD
  132173. rc = sqlite3_wsd_init(4096, 24);
  132174. if( rc!=SQLITE_OK ){
  132175. return rc;
  132176. }
  132177. #endif
  132178. /* If the following assert() fails on some obscure processor/compiler
  132179. ** combination, the work-around is to set the correct pointer
  132180. ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
  132181. assert( SQLITE_PTRSIZE==sizeof(char*) );
  132182. /* If SQLite is already completely initialized, then this call
  132183. ** to sqlite3_initialize() should be a no-op. But the initialization
  132184. ** must be complete. So isInit must not be set until the very end
  132185. ** of this routine.
  132186. */
  132187. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  132188. /* Make sure the mutex subsystem is initialized. If unable to
  132189. ** initialize the mutex subsystem, return early with the error.
  132190. ** If the system is so sick that we are unable to allocate a mutex,
  132191. ** there is not much SQLite is going to be able to do.
  132192. **
  132193. ** The mutex subsystem must take care of serializing its own
  132194. ** initialization.
  132195. */
  132196. rc = sqlite3MutexInit();
  132197. if( rc ) return rc;
  132198. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  132199. ** This operation is protected by the STATIC_MASTER mutex. Note that
  132200. ** MutexAlloc() is called for a static mutex prior to initializing the
  132201. ** malloc subsystem - this implies that the allocation of a static
  132202. ** mutex must not require support from the malloc subsystem.
  132203. */
  132204. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  132205. sqlite3_mutex_enter(pMaster);
  132206. sqlite3GlobalConfig.isMutexInit = 1;
  132207. if( !sqlite3GlobalConfig.isMallocInit ){
  132208. rc = sqlite3MallocInit();
  132209. }
  132210. if( rc==SQLITE_OK ){
  132211. sqlite3GlobalConfig.isMallocInit = 1;
  132212. if( !sqlite3GlobalConfig.pInitMutex ){
  132213. sqlite3GlobalConfig.pInitMutex =
  132214. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  132215. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  132216. rc = SQLITE_NOMEM_BKPT;
  132217. }
  132218. }
  132219. }
  132220. if( rc==SQLITE_OK ){
  132221. sqlite3GlobalConfig.nRefInitMutex++;
  132222. }
  132223. sqlite3_mutex_leave(pMaster);
  132224. /* If rc is not SQLITE_OK at this point, then either the malloc
  132225. ** subsystem could not be initialized or the system failed to allocate
  132226. ** the pInitMutex mutex. Return an error in either case. */
  132227. if( rc!=SQLITE_OK ){
  132228. return rc;
  132229. }
  132230. /* Do the rest of the initialization under the recursive mutex so
  132231. ** that we will be able to handle recursive calls into
  132232. ** sqlite3_initialize(). The recursive calls normally come through
  132233. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  132234. ** recursive calls might also be possible.
  132235. **
  132236. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  132237. ** to the xInit method, so the xInit method need not be threadsafe.
  132238. **
  132239. ** The following mutex is what serializes access to the appdef pcache xInit
  132240. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  132241. ** call to sqlite3PcacheInitialize().
  132242. */
  132243. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  132244. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  132245. sqlite3GlobalConfig.inProgress = 1;
  132246. #ifdef SQLITE_ENABLE_SQLLOG
  132247. {
  132248. extern void sqlite3_init_sqllog(void);
  132249. sqlite3_init_sqllog();
  132250. }
  132251. #endif
  132252. memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
  132253. sqlite3RegisterBuiltinFunctions();
  132254. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  132255. rc = sqlite3PcacheInitialize();
  132256. }
  132257. if( rc==SQLITE_OK ){
  132258. sqlite3GlobalConfig.isPCacheInit = 1;
  132259. rc = sqlite3OsInit();
  132260. }
  132261. if( rc==SQLITE_OK ){
  132262. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  132263. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  132264. sqlite3GlobalConfig.isInit = 1;
  132265. #ifdef SQLITE_EXTRA_INIT
  132266. bRunExtraInit = 1;
  132267. #endif
  132268. }
  132269. sqlite3GlobalConfig.inProgress = 0;
  132270. }
  132271. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  132272. /* Go back under the static mutex and clean up the recursive
  132273. ** mutex to prevent a resource leak.
  132274. */
  132275. sqlite3_mutex_enter(pMaster);
  132276. sqlite3GlobalConfig.nRefInitMutex--;
  132277. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  132278. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  132279. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  132280. sqlite3GlobalConfig.pInitMutex = 0;
  132281. }
  132282. sqlite3_mutex_leave(pMaster);
  132283. /* The following is just a sanity check to make sure SQLite has
  132284. ** been compiled correctly. It is important to run this code, but
  132285. ** we don't want to run it too often and soak up CPU cycles for no
  132286. ** reason. So we run it once during initialization.
  132287. */
  132288. #ifndef NDEBUG
  132289. #ifndef SQLITE_OMIT_FLOATING_POINT
  132290. /* This section of code's only "output" is via assert() statements. */
  132291. if ( rc==SQLITE_OK ){
  132292. u64 x = (((u64)1)<<63)-1;
  132293. double y;
  132294. assert(sizeof(x)==8);
  132295. assert(sizeof(x)==sizeof(y));
  132296. memcpy(&y, &x, 8);
  132297. assert( sqlite3IsNaN(y) );
  132298. }
  132299. #endif
  132300. #endif
  132301. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  132302. ** compile-time option.
  132303. */
  132304. #ifdef SQLITE_EXTRA_INIT
  132305. if( bRunExtraInit ){
  132306. int SQLITE_EXTRA_INIT(const char*);
  132307. rc = SQLITE_EXTRA_INIT(0);
  132308. }
  132309. #endif
  132310. return rc;
  132311. }
  132312. /*
  132313. ** Undo the effects of sqlite3_initialize(). Must not be called while
  132314. ** there are outstanding database connections or memory allocations or
  132315. ** while any part of SQLite is otherwise in use in any thread. This
  132316. ** routine is not threadsafe. But it is safe to invoke this routine
  132317. ** on when SQLite is already shut down. If SQLite is already shut down
  132318. ** when this routine is invoked, then this routine is a harmless no-op.
  132319. */
  132320. SQLITE_API int sqlite3_shutdown(void){
  132321. #ifdef SQLITE_OMIT_WSD
  132322. int rc = sqlite3_wsd_init(4096, 24);
  132323. if( rc!=SQLITE_OK ){
  132324. return rc;
  132325. }
  132326. #endif
  132327. if( sqlite3GlobalConfig.isInit ){
  132328. #ifdef SQLITE_EXTRA_SHUTDOWN
  132329. void SQLITE_EXTRA_SHUTDOWN(void);
  132330. SQLITE_EXTRA_SHUTDOWN();
  132331. #endif
  132332. sqlite3_os_end();
  132333. sqlite3_reset_auto_extension();
  132334. sqlite3GlobalConfig.isInit = 0;
  132335. }
  132336. if( sqlite3GlobalConfig.isPCacheInit ){
  132337. sqlite3PcacheShutdown();
  132338. sqlite3GlobalConfig.isPCacheInit = 0;
  132339. }
  132340. if( sqlite3GlobalConfig.isMallocInit ){
  132341. sqlite3MallocEnd();
  132342. sqlite3GlobalConfig.isMallocInit = 0;
  132343. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  132344. /* The heap subsystem has now been shutdown and these values are supposed
  132345. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  132346. ** which would rely on that heap subsystem; therefore, make sure these
  132347. ** values cannot refer to heap memory that was just invalidated when the
  132348. ** heap subsystem was shutdown. This is only done if the current call to
  132349. ** this function resulted in the heap subsystem actually being shutdown.
  132350. */
  132351. sqlite3_data_directory = 0;
  132352. sqlite3_temp_directory = 0;
  132353. #endif
  132354. }
  132355. if( sqlite3GlobalConfig.isMutexInit ){
  132356. sqlite3MutexEnd();
  132357. sqlite3GlobalConfig.isMutexInit = 0;
  132358. }
  132359. return SQLITE_OK;
  132360. }
  132361. /*
  132362. ** This API allows applications to modify the global configuration of
  132363. ** the SQLite library at run-time.
  132364. **
  132365. ** This routine should only be called when there are no outstanding
  132366. ** database connections or memory allocations. This routine is not
  132367. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  132368. ** behavior.
  132369. */
  132370. SQLITE_API int sqlite3_config(int op, ...){
  132371. va_list ap;
  132372. int rc = SQLITE_OK;
  132373. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  132374. ** the SQLite library is in use. */
  132375. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  132376. va_start(ap, op);
  132377. switch( op ){
  132378. /* Mutex configuration options are only available in a threadsafe
  132379. ** compile.
  132380. */
  132381. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
  132382. case SQLITE_CONFIG_SINGLETHREAD: {
  132383. /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
  132384. ** Single-thread. */
  132385. sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
  132386. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  132387. break;
  132388. }
  132389. #endif
  132390. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
  132391. case SQLITE_CONFIG_MULTITHREAD: {
  132392. /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
  132393. ** Multi-thread. */
  132394. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  132395. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  132396. break;
  132397. }
  132398. #endif
  132399. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
  132400. case SQLITE_CONFIG_SERIALIZED: {
  132401. /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
  132402. ** Serialized. */
  132403. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  132404. sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
  132405. break;
  132406. }
  132407. #endif
  132408. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
  132409. case SQLITE_CONFIG_MUTEX: {
  132410. /* Specify an alternative mutex implementation */
  132411. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  132412. break;
  132413. }
  132414. #endif
  132415. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
  132416. case SQLITE_CONFIG_GETMUTEX: {
  132417. /* Retrieve the current mutex implementation */
  132418. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  132419. break;
  132420. }
  132421. #endif
  132422. case SQLITE_CONFIG_MALLOC: {
  132423. /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
  132424. ** single argument which is a pointer to an instance of the
  132425. ** sqlite3_mem_methods structure. The argument specifies alternative
  132426. ** low-level memory allocation routines to be used in place of the memory
  132427. ** allocation routines built into SQLite. */
  132428. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  132429. break;
  132430. }
  132431. case SQLITE_CONFIG_GETMALLOC: {
  132432. /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
  132433. ** single argument which is a pointer to an instance of the
  132434. ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
  132435. ** filled with the currently defined memory allocation routines. */
  132436. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  132437. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  132438. break;
  132439. }
  132440. case SQLITE_CONFIG_MEMSTATUS: {
  132441. /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
  132442. ** single argument of type int, interpreted as a boolean, which enables
  132443. ** or disables the collection of memory allocation statistics. */
  132444. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  132445. break;
  132446. }
  132447. case SQLITE_CONFIG_SCRATCH: {
  132448. /* EVIDENCE-OF: R-08404-60887 There are three arguments to
  132449. ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
  132450. ** which the scratch allocations will be drawn, the size of each scratch
  132451. ** allocation (sz), and the maximum number of scratch allocations (N). */
  132452. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  132453. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  132454. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  132455. break;
  132456. }
  132457. case SQLITE_CONFIG_PAGECACHE: {
  132458. /* EVIDENCE-OF: R-18761-36601 There are three arguments to
  132459. ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
  132460. ** the size of each page cache line (sz), and the number of cache lines
  132461. ** (N). */
  132462. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  132463. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  132464. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  132465. break;
  132466. }
  132467. case SQLITE_CONFIG_PCACHE_HDRSZ: {
  132468. /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
  132469. ** a single parameter which is a pointer to an integer and writes into
  132470. ** that integer the number of extra bytes per page required for each page
  132471. ** in SQLITE_CONFIG_PAGECACHE. */
  132472. *va_arg(ap, int*) =
  132473. sqlite3HeaderSizeBtree() +
  132474. sqlite3HeaderSizePcache() +
  132475. sqlite3HeaderSizePcache1();
  132476. break;
  132477. }
  132478. case SQLITE_CONFIG_PCACHE: {
  132479. /* no-op */
  132480. break;
  132481. }
  132482. case SQLITE_CONFIG_GETPCACHE: {
  132483. /* now an error */
  132484. rc = SQLITE_ERROR;
  132485. break;
  132486. }
  132487. case SQLITE_CONFIG_PCACHE2: {
  132488. /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
  132489. ** single argument which is a pointer to an sqlite3_pcache_methods2
  132490. ** object. This object specifies the interface to a custom page cache
  132491. ** implementation. */
  132492. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  132493. break;
  132494. }
  132495. case SQLITE_CONFIG_GETPCACHE2: {
  132496. /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
  132497. ** single argument which is a pointer to an sqlite3_pcache_methods2
  132498. ** object. SQLite copies of the current page cache implementation into
  132499. ** that object. */
  132500. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  132501. sqlite3PCacheSetDefault();
  132502. }
  132503. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  132504. break;
  132505. }
  132506. /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
  132507. ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
  132508. ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
  132509. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  132510. case SQLITE_CONFIG_HEAP: {
  132511. /* EVIDENCE-OF: R-19854-42126 There are three arguments to
  132512. ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
  132513. ** number of bytes in the memory buffer, and the minimum allocation size.
  132514. */
  132515. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  132516. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  132517. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  132518. if( sqlite3GlobalConfig.mnReq<1 ){
  132519. sqlite3GlobalConfig.mnReq = 1;
  132520. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  132521. /* cap min request size at 2^12 */
  132522. sqlite3GlobalConfig.mnReq = (1<<12);
  132523. }
  132524. if( sqlite3GlobalConfig.pHeap==0 ){
  132525. /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
  132526. ** is NULL, then SQLite reverts to using its default memory allocator
  132527. ** (the system malloc() implementation), undoing any prior invocation of
  132528. ** SQLITE_CONFIG_MALLOC.
  132529. **
  132530. ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
  132531. ** revert to its default implementation when sqlite3_initialize() is run
  132532. */
  132533. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  132534. }else{
  132535. /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
  132536. ** alternative memory allocator is engaged to handle all of SQLites
  132537. ** memory allocation needs. */
  132538. #ifdef SQLITE_ENABLE_MEMSYS3
  132539. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  132540. #endif
  132541. #ifdef SQLITE_ENABLE_MEMSYS5
  132542. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  132543. #endif
  132544. }
  132545. break;
  132546. }
  132547. #endif
  132548. case SQLITE_CONFIG_LOOKASIDE: {
  132549. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  132550. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  132551. break;
  132552. }
  132553. /* Record a pointer to the logger function and its first argument.
  132554. ** The default is NULL. Logging is disabled if the function pointer is
  132555. ** NULL.
  132556. */
  132557. case SQLITE_CONFIG_LOG: {
  132558. /* MSVC is picky about pulling func ptrs from va lists.
  132559. ** http://support.microsoft.com/kb/47961
  132560. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  132561. */
  132562. typedef void(*LOGFUNC_t)(void*,int,const char*);
  132563. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  132564. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  132565. break;
  132566. }
  132567. /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
  132568. ** can be changed at start-time using the
  132569. ** sqlite3_config(SQLITE_CONFIG_URI,1) or
  132570. ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
  132571. */
  132572. case SQLITE_CONFIG_URI: {
  132573. /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
  132574. ** argument of type int. If non-zero, then URI handling is globally
  132575. ** enabled. If the parameter is zero, then URI handling is globally
  132576. ** disabled. */
  132577. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  132578. break;
  132579. }
  132580. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  132581. /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
  132582. ** option takes a single integer argument which is interpreted as a
  132583. ** boolean in order to enable or disable the use of covering indices for
  132584. ** full table scans in the query optimizer. */
  132585. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  132586. break;
  132587. }
  132588. #ifdef SQLITE_ENABLE_SQLLOG
  132589. case SQLITE_CONFIG_SQLLOG: {
  132590. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  132591. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  132592. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  132593. break;
  132594. }
  132595. #endif
  132596. case SQLITE_CONFIG_MMAP_SIZE: {
  132597. /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
  132598. ** integer (sqlite3_int64) values that are the default mmap size limit
  132599. ** (the default setting for PRAGMA mmap_size) and the maximum allowed
  132600. ** mmap size limit. */
  132601. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  132602. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  132603. /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
  132604. ** negative, then that argument is changed to its compile-time default.
  132605. **
  132606. ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
  132607. ** silently truncated if necessary so that it does not exceed the
  132608. ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
  132609. ** compile-time option.
  132610. */
  132611. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  132612. mxMmap = SQLITE_MAX_MMAP_SIZE;
  132613. }
  132614. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  132615. if( szMmap>mxMmap) szMmap = mxMmap;
  132616. sqlite3GlobalConfig.mxMmap = mxMmap;
  132617. sqlite3GlobalConfig.szMmap = szMmap;
  132618. break;
  132619. }
  132620. #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
  132621. case SQLITE_CONFIG_WIN32_HEAPSIZE: {
  132622. /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
  132623. ** unsigned integer value that specifies the maximum size of the created
  132624. ** heap. */
  132625. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  132626. break;
  132627. }
  132628. #endif
  132629. case SQLITE_CONFIG_PMASZ: {
  132630. sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
  132631. break;
  132632. }
  132633. case SQLITE_CONFIG_STMTJRNL_SPILL: {
  132634. sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
  132635. break;
  132636. }
  132637. default: {
  132638. rc = SQLITE_ERROR;
  132639. break;
  132640. }
  132641. }
  132642. va_end(ap);
  132643. return rc;
  132644. }
  132645. /*
  132646. ** Set up the lookaside buffers for a database connection.
  132647. ** Return SQLITE_OK on success.
  132648. ** If lookaside is already active, return SQLITE_BUSY.
  132649. **
  132650. ** The sz parameter is the number of bytes in each lookaside slot.
  132651. ** The cnt parameter is the number of slots. If pStart is NULL the
  132652. ** space for the lookaside memory is obtained from sqlite3_malloc().
  132653. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  132654. ** the lookaside memory.
  132655. */
  132656. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  132657. #ifndef SQLITE_OMIT_LOOKASIDE
  132658. void *pStart;
  132659. if( db->lookaside.nOut ){
  132660. return SQLITE_BUSY;
  132661. }
  132662. /* Free any existing lookaside buffer for this handle before
  132663. ** allocating a new one so we don't have to have space for
  132664. ** both at the same time.
  132665. */
  132666. if( db->lookaside.bMalloced ){
  132667. sqlite3_free(db->lookaside.pStart);
  132668. }
  132669. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  132670. ** than a pointer to be useful.
  132671. */
  132672. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  132673. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  132674. if( cnt<0 ) cnt = 0;
  132675. if( sz==0 || cnt==0 ){
  132676. sz = 0;
  132677. pStart = 0;
  132678. }else if( pBuf==0 ){
  132679. sqlite3BeginBenignMalloc();
  132680. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  132681. sqlite3EndBenignMalloc();
  132682. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  132683. }else{
  132684. pStart = pBuf;
  132685. }
  132686. db->lookaside.pStart = pStart;
  132687. db->lookaside.pFree = 0;
  132688. db->lookaside.sz = (u16)sz;
  132689. if( pStart ){
  132690. int i;
  132691. LookasideSlot *p;
  132692. assert( sz > (int)sizeof(LookasideSlot*) );
  132693. p = (LookasideSlot*)pStart;
  132694. for(i=cnt-1; i>=0; i--){
  132695. p->pNext = db->lookaside.pFree;
  132696. db->lookaside.pFree = p;
  132697. p = (LookasideSlot*)&((u8*)p)[sz];
  132698. }
  132699. db->lookaside.pEnd = p;
  132700. db->lookaside.bDisable = 0;
  132701. db->lookaside.bMalloced = pBuf==0 ?1:0;
  132702. }else{
  132703. db->lookaside.pStart = db;
  132704. db->lookaside.pEnd = db;
  132705. db->lookaside.bDisable = 1;
  132706. db->lookaside.bMalloced = 0;
  132707. }
  132708. #endif /* SQLITE_OMIT_LOOKASIDE */
  132709. return SQLITE_OK;
  132710. }
  132711. /*
  132712. ** Return the mutex associated with a database connection.
  132713. */
  132714. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  132715. #ifdef SQLITE_ENABLE_API_ARMOR
  132716. if( !sqlite3SafetyCheckOk(db) ){
  132717. (void)SQLITE_MISUSE_BKPT;
  132718. return 0;
  132719. }
  132720. #endif
  132721. return db->mutex;
  132722. }
  132723. /*
  132724. ** Free up as much memory as we can from the given database
  132725. ** connection.
  132726. */
  132727. SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
  132728. int i;
  132729. #ifdef SQLITE_ENABLE_API_ARMOR
  132730. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  132731. #endif
  132732. sqlite3_mutex_enter(db->mutex);
  132733. sqlite3BtreeEnterAll(db);
  132734. for(i=0; i<db->nDb; i++){
  132735. Btree *pBt = db->aDb[i].pBt;
  132736. if( pBt ){
  132737. Pager *pPager = sqlite3BtreePager(pBt);
  132738. sqlite3PagerShrink(pPager);
  132739. }
  132740. }
  132741. sqlite3BtreeLeaveAll(db);
  132742. sqlite3_mutex_leave(db->mutex);
  132743. return SQLITE_OK;
  132744. }
  132745. /*
  132746. ** Flush any dirty pages in the pager-cache for any attached database
  132747. ** to disk.
  132748. */
  132749. SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
  132750. int i;
  132751. int rc = SQLITE_OK;
  132752. int bSeenBusy = 0;
  132753. #ifdef SQLITE_ENABLE_API_ARMOR
  132754. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  132755. #endif
  132756. sqlite3_mutex_enter(db->mutex);
  132757. sqlite3BtreeEnterAll(db);
  132758. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  132759. Btree *pBt = db->aDb[i].pBt;
  132760. if( pBt && sqlite3BtreeIsInTrans(pBt) ){
  132761. Pager *pPager = sqlite3BtreePager(pBt);
  132762. rc = sqlite3PagerFlush(pPager);
  132763. if( rc==SQLITE_BUSY ){
  132764. bSeenBusy = 1;
  132765. rc = SQLITE_OK;
  132766. }
  132767. }
  132768. }
  132769. sqlite3BtreeLeaveAll(db);
  132770. sqlite3_mutex_leave(db->mutex);
  132771. return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
  132772. }
  132773. /*
  132774. ** Configuration settings for an individual database connection
  132775. */
  132776. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  132777. va_list ap;
  132778. int rc;
  132779. va_start(ap, op);
  132780. switch( op ){
  132781. case SQLITE_DBCONFIG_MAINDBNAME: {
  132782. db->aDb[0].zDbSName = va_arg(ap,char*);
  132783. rc = SQLITE_OK;
  132784. break;
  132785. }
  132786. case SQLITE_DBCONFIG_LOOKASIDE: {
  132787. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  132788. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  132789. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  132790. rc = setupLookaside(db, pBuf, sz, cnt);
  132791. break;
  132792. }
  132793. default: {
  132794. static const struct {
  132795. int op; /* The opcode */
  132796. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  132797. } aFlagOp[] = {
  132798. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  132799. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  132800. { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
  132801. { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
  132802. { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose },
  132803. };
  132804. unsigned int i;
  132805. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  132806. for(i=0; i<ArraySize(aFlagOp); i++){
  132807. if( aFlagOp[i].op==op ){
  132808. int onoff = va_arg(ap, int);
  132809. int *pRes = va_arg(ap, int*);
  132810. int oldFlags = db->flags;
  132811. if( onoff>0 ){
  132812. db->flags |= aFlagOp[i].mask;
  132813. }else if( onoff==0 ){
  132814. db->flags &= ~aFlagOp[i].mask;
  132815. }
  132816. if( oldFlags!=db->flags ){
  132817. sqlite3ExpirePreparedStatements(db);
  132818. }
  132819. if( pRes ){
  132820. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  132821. }
  132822. rc = SQLITE_OK;
  132823. break;
  132824. }
  132825. }
  132826. break;
  132827. }
  132828. }
  132829. va_end(ap);
  132830. return rc;
  132831. }
  132832. /*
  132833. ** Return true if the buffer z[0..n-1] contains all spaces.
  132834. */
  132835. static int allSpaces(const char *z, int n){
  132836. while( n>0 && z[n-1]==' ' ){ n--; }
  132837. return n==0;
  132838. }
  132839. /*
  132840. ** This is the default collating function named "BINARY" which is always
  132841. ** available.
  132842. **
  132843. ** If the padFlag argument is not NULL then space padding at the end
  132844. ** of strings is ignored. This implements the RTRIM collation.
  132845. */
  132846. static int binCollFunc(
  132847. void *padFlag,
  132848. int nKey1, const void *pKey1,
  132849. int nKey2, const void *pKey2
  132850. ){
  132851. int rc, n;
  132852. n = nKey1<nKey2 ? nKey1 : nKey2;
  132853. /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
  132854. ** strings byte by byte using the memcmp() function from the standard C
  132855. ** library. */
  132856. rc = memcmp(pKey1, pKey2, n);
  132857. if( rc==0 ){
  132858. if( padFlag
  132859. && allSpaces(((char*)pKey1)+n, nKey1-n)
  132860. && allSpaces(((char*)pKey2)+n, nKey2-n)
  132861. ){
  132862. /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
  132863. ** spaces at the end of either string do not change the result. In other
  132864. ** words, strings will compare equal to one another as long as they
  132865. ** differ only in the number of spaces at the end.
  132866. */
  132867. }else{
  132868. rc = nKey1 - nKey2;
  132869. }
  132870. }
  132871. return rc;
  132872. }
  132873. /*
  132874. ** Another built-in collating sequence: NOCASE.
  132875. **
  132876. ** This collating sequence is intended to be used for "case independent
  132877. ** comparison". SQLite's knowledge of upper and lower case equivalents
  132878. ** extends only to the 26 characters used in the English language.
  132879. **
  132880. ** At the moment there is only a UTF-8 implementation.
  132881. */
  132882. static int nocaseCollatingFunc(
  132883. void *NotUsed,
  132884. int nKey1, const void *pKey1,
  132885. int nKey2, const void *pKey2
  132886. ){
  132887. int r = sqlite3StrNICmp(
  132888. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  132889. UNUSED_PARAMETER(NotUsed);
  132890. if( 0==r ){
  132891. r = nKey1-nKey2;
  132892. }
  132893. return r;
  132894. }
  132895. /*
  132896. ** Return the ROWID of the most recent insert
  132897. */
  132898. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  132899. #ifdef SQLITE_ENABLE_API_ARMOR
  132900. if( !sqlite3SafetyCheckOk(db) ){
  132901. (void)SQLITE_MISUSE_BKPT;
  132902. return 0;
  132903. }
  132904. #endif
  132905. return db->lastRowid;
  132906. }
  132907. /*
  132908. ** Set the value returned by the sqlite3_last_insert_rowid() API function.
  132909. */
  132910. SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
  132911. #ifdef SQLITE_ENABLE_API_ARMOR
  132912. if( !sqlite3SafetyCheckOk(db) ){
  132913. (void)SQLITE_MISUSE_BKPT;
  132914. return;
  132915. }
  132916. #endif
  132917. sqlite3_mutex_enter(db->mutex);
  132918. db->lastRowid = iRowid;
  132919. sqlite3_mutex_leave(db->mutex);
  132920. }
  132921. /*
  132922. ** Return the number of changes in the most recent call to sqlite3_exec().
  132923. */
  132924. SQLITE_API int sqlite3_changes(sqlite3 *db){
  132925. #ifdef SQLITE_ENABLE_API_ARMOR
  132926. if( !sqlite3SafetyCheckOk(db) ){
  132927. (void)SQLITE_MISUSE_BKPT;
  132928. return 0;
  132929. }
  132930. #endif
  132931. return db->nChange;
  132932. }
  132933. /*
  132934. ** Return the number of changes since the database handle was opened.
  132935. */
  132936. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  132937. #ifdef SQLITE_ENABLE_API_ARMOR
  132938. if( !sqlite3SafetyCheckOk(db) ){
  132939. (void)SQLITE_MISUSE_BKPT;
  132940. return 0;
  132941. }
  132942. #endif
  132943. return db->nTotalChange;
  132944. }
  132945. /*
  132946. ** Close all open savepoints. This function only manipulates fields of the
  132947. ** database handle object, it does not close any savepoints that may be open
  132948. ** at the b-tree/pager level.
  132949. */
  132950. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  132951. while( db->pSavepoint ){
  132952. Savepoint *pTmp = db->pSavepoint;
  132953. db->pSavepoint = pTmp->pNext;
  132954. sqlite3DbFree(db, pTmp);
  132955. }
  132956. db->nSavepoint = 0;
  132957. db->nStatement = 0;
  132958. db->isTransactionSavepoint = 0;
  132959. }
  132960. /*
  132961. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  132962. ** if this is not the last copy of the function, do not invoke it. Multiple
  132963. ** copies of a single function are created when create_function() is called
  132964. ** with SQLITE_ANY as the encoding.
  132965. */
  132966. static void functionDestroy(sqlite3 *db, FuncDef *p){
  132967. FuncDestructor *pDestructor = p->u.pDestructor;
  132968. if( pDestructor ){
  132969. pDestructor->nRef--;
  132970. if( pDestructor->nRef==0 ){
  132971. pDestructor->xDestroy(pDestructor->pUserData);
  132972. sqlite3DbFree(db, pDestructor);
  132973. }
  132974. }
  132975. }
  132976. /*
  132977. ** Disconnect all sqlite3_vtab objects that belong to database connection
  132978. ** db. This is called when db is being closed.
  132979. */
  132980. static void disconnectAllVtab(sqlite3 *db){
  132981. #ifndef SQLITE_OMIT_VIRTUALTABLE
  132982. int i;
  132983. HashElem *p;
  132984. sqlite3BtreeEnterAll(db);
  132985. for(i=0; i<db->nDb; i++){
  132986. Schema *pSchema = db->aDb[i].pSchema;
  132987. if( db->aDb[i].pSchema ){
  132988. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  132989. Table *pTab = (Table *)sqliteHashData(p);
  132990. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  132991. }
  132992. }
  132993. }
  132994. for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
  132995. Module *pMod = (Module *)sqliteHashData(p);
  132996. if( pMod->pEpoTab ){
  132997. sqlite3VtabDisconnect(db, pMod->pEpoTab);
  132998. }
  132999. }
  133000. sqlite3VtabUnlockList(db);
  133001. sqlite3BtreeLeaveAll(db);
  133002. #else
  133003. UNUSED_PARAMETER(db);
  133004. #endif
  133005. }
  133006. /*
  133007. ** Return TRUE if database connection db has unfinalized prepared
  133008. ** statements or unfinished sqlite3_backup objects.
  133009. */
  133010. static int connectionIsBusy(sqlite3 *db){
  133011. int j;
  133012. assert( sqlite3_mutex_held(db->mutex) );
  133013. if( db->pVdbe ) return 1;
  133014. for(j=0; j<db->nDb; j++){
  133015. Btree *pBt = db->aDb[j].pBt;
  133016. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  133017. }
  133018. return 0;
  133019. }
  133020. /*
  133021. ** Close an existing SQLite database
  133022. */
  133023. static int sqlite3Close(sqlite3 *db, int forceZombie){
  133024. if( !db ){
  133025. /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
  133026. ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
  133027. return SQLITE_OK;
  133028. }
  133029. if( !sqlite3SafetyCheckSickOrOk(db) ){
  133030. return SQLITE_MISUSE_BKPT;
  133031. }
  133032. sqlite3_mutex_enter(db->mutex);
  133033. if( db->mTrace & SQLITE_TRACE_CLOSE ){
  133034. db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
  133035. }
  133036. /* Force xDisconnect calls on all virtual tables */
  133037. disconnectAllVtab(db);
  133038. /* If a transaction is open, the disconnectAllVtab() call above
  133039. ** will not have called the xDisconnect() method on any virtual
  133040. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  133041. ** call will do so. We need to do this before the check for active
  133042. ** SQL statements below, as the v-table implementation may be storing
  133043. ** some prepared statements internally.
  133044. */
  133045. sqlite3VtabRollback(db);
  133046. /* Legacy behavior (sqlite3_close() behavior) is to return
  133047. ** SQLITE_BUSY if the connection can not be closed immediately.
  133048. */
  133049. if( !forceZombie && connectionIsBusy(db) ){
  133050. sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
  133051. "statements or unfinished backups");
  133052. sqlite3_mutex_leave(db->mutex);
  133053. return SQLITE_BUSY;
  133054. }
  133055. #ifdef SQLITE_ENABLE_SQLLOG
  133056. if( sqlite3GlobalConfig.xSqllog ){
  133057. /* Closing the handle. Fourth parameter is passed the value 2. */
  133058. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  133059. }
  133060. #endif
  133061. /* Convert the connection into a zombie and then close it.
  133062. */
  133063. db->magic = SQLITE_MAGIC_ZOMBIE;
  133064. sqlite3LeaveMutexAndCloseZombie(db);
  133065. return SQLITE_OK;
  133066. }
  133067. /*
  133068. ** Two variations on the public interface for closing a database
  133069. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  133070. ** leaves the connection option if there are unfinalized prepared
  133071. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  133072. ** version forces the connection to become a zombie if there are
  133073. ** unclosed resources, and arranges for deallocation when the last
  133074. ** prepare statement or sqlite3_backup closes.
  133075. */
  133076. SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  133077. SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  133078. /*
  133079. ** Close the mutex on database connection db.
  133080. **
  133081. ** Furthermore, if database connection db is a zombie (meaning that there
  133082. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  133083. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  133084. ** finished, then free all resources.
  133085. */
  133086. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  133087. HashElem *i; /* Hash table iterator */
  133088. int j;
  133089. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  133090. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  133091. ** then just leave the mutex and return.
  133092. */
  133093. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  133094. sqlite3_mutex_leave(db->mutex);
  133095. return;
  133096. }
  133097. /* If we reach this point, it means that the database connection has
  133098. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  133099. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  133100. ** go ahead and free all resources.
  133101. */
  133102. /* If a transaction is open, roll it back. This also ensures that if
  133103. ** any database schemas have been modified by an uncommitted transaction
  133104. ** they are reset. And that the required b-tree mutex is held to make
  133105. ** the pager rollback and schema reset an atomic operation. */
  133106. sqlite3RollbackAll(db, SQLITE_OK);
  133107. /* Free any outstanding Savepoint structures. */
  133108. sqlite3CloseSavepoints(db);
  133109. /* Close all database connections */
  133110. for(j=0; j<db->nDb; j++){
  133111. struct Db *pDb = &db->aDb[j];
  133112. if( pDb->pBt ){
  133113. sqlite3BtreeClose(pDb->pBt);
  133114. pDb->pBt = 0;
  133115. if( j!=1 ){
  133116. pDb->pSchema = 0;
  133117. }
  133118. }
  133119. }
  133120. /* Clear the TEMP schema separately and last */
  133121. if( db->aDb[1].pSchema ){
  133122. sqlite3SchemaClear(db->aDb[1].pSchema);
  133123. }
  133124. sqlite3VtabUnlockList(db);
  133125. /* Free up the array of auxiliary databases */
  133126. sqlite3CollapseDatabaseArray(db);
  133127. assert( db->nDb<=2 );
  133128. assert( db->aDb==db->aDbStatic );
  133129. /* Tell the code in notify.c that the connection no longer holds any
  133130. ** locks and does not require any further unlock-notify callbacks.
  133131. */
  133132. sqlite3ConnectionClosed(db);
  133133. for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
  133134. FuncDef *pNext, *p;
  133135. p = sqliteHashData(i);
  133136. do{
  133137. functionDestroy(db, p);
  133138. pNext = p->pNext;
  133139. sqlite3DbFree(db, p);
  133140. p = pNext;
  133141. }while( p );
  133142. }
  133143. sqlite3HashClear(&db->aFunc);
  133144. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  133145. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  133146. /* Invoke any destructors registered for collation sequence user data. */
  133147. for(j=0; j<3; j++){
  133148. if( pColl[j].xDel ){
  133149. pColl[j].xDel(pColl[j].pUser);
  133150. }
  133151. }
  133152. sqlite3DbFree(db, pColl);
  133153. }
  133154. sqlite3HashClear(&db->aCollSeq);
  133155. #ifndef SQLITE_OMIT_VIRTUALTABLE
  133156. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  133157. Module *pMod = (Module *)sqliteHashData(i);
  133158. if( pMod->xDestroy ){
  133159. pMod->xDestroy(pMod->pAux);
  133160. }
  133161. sqlite3VtabEponymousTableClear(db, pMod);
  133162. sqlite3DbFree(db, pMod);
  133163. }
  133164. sqlite3HashClear(&db->aModule);
  133165. #endif
  133166. sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
  133167. sqlite3ValueFree(db->pErr);
  133168. sqlite3CloseExtensions(db);
  133169. #if SQLITE_USER_AUTHENTICATION
  133170. sqlite3_free(db->auth.zAuthUser);
  133171. sqlite3_free(db->auth.zAuthPW);
  133172. #endif
  133173. db->magic = SQLITE_MAGIC_ERROR;
  133174. /* The temp-database schema is allocated differently from the other schema
  133175. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  133176. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  133177. ** the same sqliteMalloc() as the one that allocates the database
  133178. ** structure?
  133179. */
  133180. sqlite3DbFree(db, db->aDb[1].pSchema);
  133181. sqlite3_mutex_leave(db->mutex);
  133182. db->magic = SQLITE_MAGIC_CLOSED;
  133183. sqlite3_mutex_free(db->mutex);
  133184. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  133185. if( db->lookaside.bMalloced ){
  133186. sqlite3_free(db->lookaside.pStart);
  133187. }
  133188. sqlite3_free(db);
  133189. }
  133190. /*
  133191. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  133192. ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
  133193. ** breaker") and made to return tripCode if there are any further
  133194. ** attempts to use that cursor. Read cursors remain open and valid
  133195. ** but are "saved" in case the table pages are moved around.
  133196. */
  133197. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  133198. int i;
  133199. int inTrans = 0;
  133200. int schemaChange;
  133201. assert( sqlite3_mutex_held(db->mutex) );
  133202. sqlite3BeginBenignMalloc();
  133203. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  133204. ** This is important in case the transaction being rolled back has
  133205. ** modified the database schema. If the b-tree mutexes are not taken
  133206. ** here, then another shared-cache connection might sneak in between
  133207. ** the database rollback and schema reset, which can cause false
  133208. ** corruption reports in some cases. */
  133209. sqlite3BtreeEnterAll(db);
  133210. schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
  133211. for(i=0; i<db->nDb; i++){
  133212. Btree *p = db->aDb[i].pBt;
  133213. if( p ){
  133214. if( sqlite3BtreeIsInTrans(p) ){
  133215. inTrans = 1;
  133216. }
  133217. sqlite3BtreeRollback(p, tripCode, !schemaChange);
  133218. }
  133219. }
  133220. sqlite3VtabRollback(db);
  133221. sqlite3EndBenignMalloc();
  133222. if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
  133223. sqlite3ExpirePreparedStatements(db);
  133224. sqlite3ResetAllSchemasOfConnection(db);
  133225. }
  133226. sqlite3BtreeLeaveAll(db);
  133227. /* Any deferred constraint violations have now been resolved. */
  133228. db->nDeferredCons = 0;
  133229. db->nDeferredImmCons = 0;
  133230. db->flags &= ~SQLITE_DeferFKs;
  133231. /* If one has been configured, invoke the rollback-hook callback */
  133232. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  133233. db->xRollbackCallback(db->pRollbackArg);
  133234. }
  133235. }
  133236. /*
  133237. ** Return a static string containing the name corresponding to the error code
  133238. ** specified in the argument.
  133239. */
  133240. #if defined(SQLITE_NEED_ERR_NAME)
  133241. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  133242. const char *zName = 0;
  133243. int i, origRc = rc;
  133244. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  133245. switch( rc ){
  133246. case SQLITE_OK: zName = "SQLITE_OK"; break;
  133247. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  133248. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  133249. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  133250. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  133251. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  133252. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  133253. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  133254. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  133255. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  133256. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  133257. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  133258. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  133259. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  133260. case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
  133261. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  133262. case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
  133263. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  133264. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  133265. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  133266. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  133267. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  133268. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  133269. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  133270. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  133271. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  133272. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  133273. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  133274. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  133275. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  133276. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  133277. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  133278. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  133279. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  133280. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  133281. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  133282. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  133283. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  133284. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  133285. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  133286. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  133287. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  133288. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  133289. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  133290. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  133291. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  133292. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  133293. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  133294. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  133295. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  133296. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  133297. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  133298. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  133299. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  133300. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  133301. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  133302. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  133303. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  133304. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  133305. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  133306. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  133307. case SQLITE_CONSTRAINT_FOREIGNKEY:
  133308. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  133309. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  133310. case SQLITE_CONSTRAINT_PRIMARYKEY:
  133311. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  133312. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  133313. case SQLITE_CONSTRAINT_COMMITHOOK:
  133314. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  133315. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  133316. case SQLITE_CONSTRAINT_FUNCTION:
  133317. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  133318. case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
  133319. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  133320. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  133321. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  133322. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  133323. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  133324. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  133325. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  133326. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  133327. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  133328. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  133329. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  133330. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  133331. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  133332. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  133333. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  133334. }
  133335. }
  133336. if( zName==0 ){
  133337. static char zBuf[50];
  133338. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  133339. zName = zBuf;
  133340. }
  133341. return zName;
  133342. }
  133343. #endif
  133344. /*
  133345. ** Return a static string that describes the kind of error specified in the
  133346. ** argument.
  133347. */
  133348. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  133349. static const char* const aMsg[] = {
  133350. /* SQLITE_OK */ "not an error",
  133351. /* SQLITE_ERROR */ "SQL logic error or missing database",
  133352. /* SQLITE_INTERNAL */ 0,
  133353. /* SQLITE_PERM */ "access permission denied",
  133354. /* SQLITE_ABORT */ "callback requested query abort",
  133355. /* SQLITE_BUSY */ "database is locked",
  133356. /* SQLITE_LOCKED */ "database table is locked",
  133357. /* SQLITE_NOMEM */ "out of memory",
  133358. /* SQLITE_READONLY */ "attempt to write a readonly database",
  133359. /* SQLITE_INTERRUPT */ "interrupted",
  133360. /* SQLITE_IOERR */ "disk I/O error",
  133361. /* SQLITE_CORRUPT */ "database disk image is malformed",
  133362. /* SQLITE_NOTFOUND */ "unknown operation",
  133363. /* SQLITE_FULL */ "database or disk is full",
  133364. /* SQLITE_CANTOPEN */ "unable to open database file",
  133365. /* SQLITE_PROTOCOL */ "locking protocol",
  133366. /* SQLITE_EMPTY */ "table contains no data",
  133367. /* SQLITE_SCHEMA */ "database schema has changed",
  133368. /* SQLITE_TOOBIG */ "string or blob too big",
  133369. /* SQLITE_CONSTRAINT */ "constraint failed",
  133370. /* SQLITE_MISMATCH */ "datatype mismatch",
  133371. /* SQLITE_MISUSE */ "library routine called out of sequence",
  133372. /* SQLITE_NOLFS */ "large file support is disabled",
  133373. /* SQLITE_AUTH */ "authorization denied",
  133374. /* SQLITE_FORMAT */ "auxiliary database format error",
  133375. /* SQLITE_RANGE */ "bind or column index out of range",
  133376. /* SQLITE_NOTADB */ "file is encrypted or is not a database",
  133377. };
  133378. const char *zErr = "unknown error";
  133379. switch( rc ){
  133380. case SQLITE_ABORT_ROLLBACK: {
  133381. zErr = "abort due to ROLLBACK";
  133382. break;
  133383. }
  133384. default: {
  133385. rc &= 0xff;
  133386. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  133387. zErr = aMsg[rc];
  133388. }
  133389. break;
  133390. }
  133391. }
  133392. return zErr;
  133393. }
  133394. /*
  133395. ** This routine implements a busy callback that sleeps and tries
  133396. ** again until a timeout value is reached. The timeout value is
  133397. ** an integer number of milliseconds passed in as the first
  133398. ** argument.
  133399. */
  133400. static int sqliteDefaultBusyCallback(
  133401. void *ptr, /* Database connection */
  133402. int count /* Number of times table has been busy */
  133403. ){
  133404. #if SQLITE_OS_WIN || HAVE_USLEEP
  133405. static const u8 delays[] =
  133406. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  133407. static const u8 totals[] =
  133408. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  133409. # define NDELAY ArraySize(delays)
  133410. sqlite3 *db = (sqlite3 *)ptr;
  133411. int timeout = db->busyTimeout;
  133412. int delay, prior;
  133413. assert( count>=0 );
  133414. if( count < NDELAY ){
  133415. delay = delays[count];
  133416. prior = totals[count];
  133417. }else{
  133418. delay = delays[NDELAY-1];
  133419. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  133420. }
  133421. if( prior + delay > timeout ){
  133422. delay = timeout - prior;
  133423. if( delay<=0 ) return 0;
  133424. }
  133425. sqlite3OsSleep(db->pVfs, delay*1000);
  133426. return 1;
  133427. #else
  133428. sqlite3 *db = (sqlite3 *)ptr;
  133429. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  133430. if( (count+1)*1000 > timeout ){
  133431. return 0;
  133432. }
  133433. sqlite3OsSleep(db->pVfs, 1000000);
  133434. return 1;
  133435. #endif
  133436. }
  133437. /*
  133438. ** Invoke the given busy handler.
  133439. **
  133440. ** This routine is called when an operation failed with a lock.
  133441. ** If this routine returns non-zero, the lock is retried. If it
  133442. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  133443. */
  133444. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  133445. int rc;
  133446. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  133447. rc = p->xFunc(p->pArg, p->nBusy);
  133448. if( rc==0 ){
  133449. p->nBusy = -1;
  133450. }else{
  133451. p->nBusy++;
  133452. }
  133453. return rc;
  133454. }
  133455. /*
  133456. ** This routine sets the busy callback for an Sqlite database to the
  133457. ** given callback function with the given argument.
  133458. */
  133459. SQLITE_API int sqlite3_busy_handler(
  133460. sqlite3 *db,
  133461. int (*xBusy)(void*,int),
  133462. void *pArg
  133463. ){
  133464. #ifdef SQLITE_ENABLE_API_ARMOR
  133465. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  133466. #endif
  133467. sqlite3_mutex_enter(db->mutex);
  133468. db->busyHandler.xFunc = xBusy;
  133469. db->busyHandler.pArg = pArg;
  133470. db->busyHandler.nBusy = 0;
  133471. db->busyTimeout = 0;
  133472. sqlite3_mutex_leave(db->mutex);
  133473. return SQLITE_OK;
  133474. }
  133475. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  133476. /*
  133477. ** This routine sets the progress callback for an Sqlite database to the
  133478. ** given callback function with the given argument. The progress callback will
  133479. ** be invoked every nOps opcodes.
  133480. */
  133481. SQLITE_API void sqlite3_progress_handler(
  133482. sqlite3 *db,
  133483. int nOps,
  133484. int (*xProgress)(void*),
  133485. void *pArg
  133486. ){
  133487. #ifdef SQLITE_ENABLE_API_ARMOR
  133488. if( !sqlite3SafetyCheckOk(db) ){
  133489. (void)SQLITE_MISUSE_BKPT;
  133490. return;
  133491. }
  133492. #endif
  133493. sqlite3_mutex_enter(db->mutex);
  133494. if( nOps>0 ){
  133495. db->xProgress = xProgress;
  133496. db->nProgressOps = (unsigned)nOps;
  133497. db->pProgressArg = pArg;
  133498. }else{
  133499. db->xProgress = 0;
  133500. db->nProgressOps = 0;
  133501. db->pProgressArg = 0;
  133502. }
  133503. sqlite3_mutex_leave(db->mutex);
  133504. }
  133505. #endif
  133506. /*
  133507. ** This routine installs a default busy handler that waits for the
  133508. ** specified number of milliseconds before returning 0.
  133509. */
  133510. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  133511. #ifdef SQLITE_ENABLE_API_ARMOR
  133512. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  133513. #endif
  133514. if( ms>0 ){
  133515. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  133516. db->busyTimeout = ms;
  133517. }else{
  133518. sqlite3_busy_handler(db, 0, 0);
  133519. }
  133520. return SQLITE_OK;
  133521. }
  133522. /*
  133523. ** Cause any pending operation to stop at its earliest opportunity.
  133524. */
  133525. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  133526. #ifdef SQLITE_ENABLE_API_ARMOR
  133527. if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
  133528. (void)SQLITE_MISUSE_BKPT;
  133529. return;
  133530. }
  133531. #endif
  133532. db->u1.isInterrupted = 1;
  133533. }
  133534. /*
  133535. ** This function is exactly the same as sqlite3_create_function(), except
  133536. ** that it is designed to be called by internal code. The difference is
  133537. ** that if a malloc() fails in sqlite3_create_function(), an error code
  133538. ** is returned and the mallocFailed flag cleared.
  133539. */
  133540. SQLITE_PRIVATE int sqlite3CreateFunc(
  133541. sqlite3 *db,
  133542. const char *zFunctionName,
  133543. int nArg,
  133544. int enc,
  133545. void *pUserData,
  133546. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  133547. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  133548. void (*xFinal)(sqlite3_context*),
  133549. FuncDestructor *pDestructor
  133550. ){
  133551. FuncDef *p;
  133552. int nName;
  133553. int extraFlags;
  133554. assert( sqlite3_mutex_held(db->mutex) );
  133555. if( zFunctionName==0 ||
  133556. (xSFunc && (xFinal || xStep)) ||
  133557. (!xSFunc && (xFinal && !xStep)) ||
  133558. (!xSFunc && (!xFinal && xStep)) ||
  133559. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  133560. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  133561. return SQLITE_MISUSE_BKPT;
  133562. }
  133563. assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
  133564. extraFlags = enc & SQLITE_DETERMINISTIC;
  133565. enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
  133566. #ifndef SQLITE_OMIT_UTF16
  133567. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  133568. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  133569. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  133570. **
  133571. ** If SQLITE_ANY is specified, add three versions of the function
  133572. ** to the hash table.
  133573. */
  133574. if( enc==SQLITE_UTF16 ){
  133575. enc = SQLITE_UTF16NATIVE;
  133576. }else if( enc==SQLITE_ANY ){
  133577. int rc;
  133578. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
  133579. pUserData, xSFunc, xStep, xFinal, pDestructor);
  133580. if( rc==SQLITE_OK ){
  133581. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
  133582. pUserData, xSFunc, xStep, xFinal, pDestructor);
  133583. }
  133584. if( rc!=SQLITE_OK ){
  133585. return rc;
  133586. }
  133587. enc = SQLITE_UTF16BE;
  133588. }
  133589. #else
  133590. enc = SQLITE_UTF8;
  133591. #endif
  133592. /* Check if an existing function is being overridden or deleted. If so,
  133593. ** and there are active VMs, then return SQLITE_BUSY. If a function
  133594. ** is being overridden/deleted but there are no active VMs, allow the
  133595. ** operation to continue but invalidate all precompiled statements.
  133596. */
  133597. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
  133598. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
  133599. if( db->nVdbeActive ){
  133600. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  133601. "unable to delete/modify user-function due to active statements");
  133602. assert( !db->mallocFailed );
  133603. return SQLITE_BUSY;
  133604. }else{
  133605. sqlite3ExpirePreparedStatements(db);
  133606. }
  133607. }
  133608. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
  133609. assert(p || db->mallocFailed);
  133610. if( !p ){
  133611. return SQLITE_NOMEM_BKPT;
  133612. }
  133613. /* If an older version of the function with a configured destructor is
  133614. ** being replaced invoke the destructor function here. */
  133615. functionDestroy(db, p);
  133616. if( pDestructor ){
  133617. pDestructor->nRef++;
  133618. }
  133619. p->u.pDestructor = pDestructor;
  133620. p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
  133621. testcase( p->funcFlags & SQLITE_DETERMINISTIC );
  133622. p->xSFunc = xSFunc ? xSFunc : xStep;
  133623. p->xFinalize = xFinal;
  133624. p->pUserData = pUserData;
  133625. p->nArg = (u16)nArg;
  133626. return SQLITE_OK;
  133627. }
  133628. /*
  133629. ** Create new user functions.
  133630. */
  133631. SQLITE_API int sqlite3_create_function(
  133632. sqlite3 *db,
  133633. const char *zFunc,
  133634. int nArg,
  133635. int enc,
  133636. void *p,
  133637. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  133638. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  133639. void (*xFinal)(sqlite3_context*)
  133640. ){
  133641. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
  133642. xFinal, 0);
  133643. }
  133644. SQLITE_API int sqlite3_create_function_v2(
  133645. sqlite3 *db,
  133646. const char *zFunc,
  133647. int nArg,
  133648. int enc,
  133649. void *p,
  133650. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  133651. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  133652. void (*xFinal)(sqlite3_context*),
  133653. void (*xDestroy)(void *)
  133654. ){
  133655. int rc = SQLITE_ERROR;
  133656. FuncDestructor *pArg = 0;
  133657. #ifdef SQLITE_ENABLE_API_ARMOR
  133658. if( !sqlite3SafetyCheckOk(db) ){
  133659. return SQLITE_MISUSE_BKPT;
  133660. }
  133661. #endif
  133662. sqlite3_mutex_enter(db->mutex);
  133663. if( xDestroy ){
  133664. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  133665. if( !pArg ){
  133666. xDestroy(p);
  133667. goto out;
  133668. }
  133669. pArg->xDestroy = xDestroy;
  133670. pArg->pUserData = p;
  133671. }
  133672. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
  133673. if( pArg && pArg->nRef==0 ){
  133674. assert( rc!=SQLITE_OK );
  133675. xDestroy(p);
  133676. sqlite3DbFree(db, pArg);
  133677. }
  133678. out:
  133679. rc = sqlite3ApiExit(db, rc);
  133680. sqlite3_mutex_leave(db->mutex);
  133681. return rc;
  133682. }
  133683. #ifndef SQLITE_OMIT_UTF16
  133684. SQLITE_API int sqlite3_create_function16(
  133685. sqlite3 *db,
  133686. const void *zFunctionName,
  133687. int nArg,
  133688. int eTextRep,
  133689. void *p,
  133690. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
  133691. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  133692. void (*xFinal)(sqlite3_context*)
  133693. ){
  133694. int rc;
  133695. char *zFunc8;
  133696. #ifdef SQLITE_ENABLE_API_ARMOR
  133697. if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
  133698. #endif
  133699. sqlite3_mutex_enter(db->mutex);
  133700. assert( !db->mallocFailed );
  133701. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  133702. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
  133703. sqlite3DbFree(db, zFunc8);
  133704. rc = sqlite3ApiExit(db, rc);
  133705. sqlite3_mutex_leave(db->mutex);
  133706. return rc;
  133707. }
  133708. #endif
  133709. /*
  133710. ** Declare that a function has been overloaded by a virtual table.
  133711. **
  133712. ** If the function already exists as a regular global function, then
  133713. ** this routine is a no-op. If the function does not exist, then create
  133714. ** a new one that always throws a run-time error.
  133715. **
  133716. ** When virtual tables intend to provide an overloaded function, they
  133717. ** should call this routine to make sure the global function exists.
  133718. ** A global function must exist in order for name resolution to work
  133719. ** properly.
  133720. */
  133721. SQLITE_API int sqlite3_overload_function(
  133722. sqlite3 *db,
  133723. const char *zName,
  133724. int nArg
  133725. ){
  133726. int rc = SQLITE_OK;
  133727. #ifdef SQLITE_ENABLE_API_ARMOR
  133728. if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
  133729. return SQLITE_MISUSE_BKPT;
  133730. }
  133731. #endif
  133732. sqlite3_mutex_enter(db->mutex);
  133733. if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
  133734. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  133735. 0, sqlite3InvalidFunction, 0, 0, 0);
  133736. }
  133737. rc = sqlite3ApiExit(db, rc);
  133738. sqlite3_mutex_leave(db->mutex);
  133739. return rc;
  133740. }
  133741. #ifndef SQLITE_OMIT_TRACE
  133742. /*
  133743. ** Register a trace function. The pArg from the previously registered trace
  133744. ** is returned.
  133745. **
  133746. ** A NULL trace function means that no tracing is executes. A non-NULL
  133747. ** trace is a pointer to a function that is invoked at the start of each
  133748. ** SQL statement.
  133749. */
  133750. #ifndef SQLITE_OMIT_DEPRECATED
  133751. SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
  133752. void *pOld;
  133753. #ifdef SQLITE_ENABLE_API_ARMOR
  133754. if( !sqlite3SafetyCheckOk(db) ){
  133755. (void)SQLITE_MISUSE_BKPT;
  133756. return 0;
  133757. }
  133758. #endif
  133759. sqlite3_mutex_enter(db->mutex);
  133760. pOld = db->pTraceArg;
  133761. db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
  133762. db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
  133763. db->pTraceArg = pArg;
  133764. sqlite3_mutex_leave(db->mutex);
  133765. return pOld;
  133766. }
  133767. #endif /* SQLITE_OMIT_DEPRECATED */
  133768. /* Register a trace callback using the version-2 interface.
  133769. */
  133770. SQLITE_API int sqlite3_trace_v2(
  133771. sqlite3 *db, /* Trace this connection */
  133772. unsigned mTrace, /* Mask of events to be traced */
  133773. int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
  133774. void *pArg /* Context */
  133775. ){
  133776. #ifdef SQLITE_ENABLE_API_ARMOR
  133777. if( !sqlite3SafetyCheckOk(db) ){
  133778. return SQLITE_MISUSE_BKPT;
  133779. }
  133780. #endif
  133781. sqlite3_mutex_enter(db->mutex);
  133782. if( mTrace==0 ) xTrace = 0;
  133783. if( xTrace==0 ) mTrace = 0;
  133784. db->mTrace = mTrace;
  133785. db->xTrace = xTrace;
  133786. db->pTraceArg = pArg;
  133787. sqlite3_mutex_leave(db->mutex);
  133788. return SQLITE_OK;
  133789. }
  133790. #ifndef SQLITE_OMIT_DEPRECATED
  133791. /*
  133792. ** Register a profile function. The pArg from the previously registered
  133793. ** profile function is returned.
  133794. **
  133795. ** A NULL profile function means that no profiling is executes. A non-NULL
  133796. ** profile is a pointer to a function that is invoked at the conclusion of
  133797. ** each SQL statement that is run.
  133798. */
  133799. SQLITE_API void *sqlite3_profile(
  133800. sqlite3 *db,
  133801. void (*xProfile)(void*,const char*,sqlite_uint64),
  133802. void *pArg
  133803. ){
  133804. void *pOld;
  133805. #ifdef SQLITE_ENABLE_API_ARMOR
  133806. if( !sqlite3SafetyCheckOk(db) ){
  133807. (void)SQLITE_MISUSE_BKPT;
  133808. return 0;
  133809. }
  133810. #endif
  133811. sqlite3_mutex_enter(db->mutex);
  133812. pOld = db->pProfileArg;
  133813. db->xProfile = xProfile;
  133814. db->pProfileArg = pArg;
  133815. sqlite3_mutex_leave(db->mutex);
  133816. return pOld;
  133817. }
  133818. #endif /* SQLITE_OMIT_DEPRECATED */
  133819. #endif /* SQLITE_OMIT_TRACE */
  133820. /*
  133821. ** Register a function to be invoked when a transaction commits.
  133822. ** If the invoked function returns non-zero, then the commit becomes a
  133823. ** rollback.
  133824. */
  133825. SQLITE_API void *sqlite3_commit_hook(
  133826. sqlite3 *db, /* Attach the hook to this database */
  133827. int (*xCallback)(void*), /* Function to invoke on each commit */
  133828. void *pArg /* Argument to the function */
  133829. ){
  133830. void *pOld;
  133831. #ifdef SQLITE_ENABLE_API_ARMOR
  133832. if( !sqlite3SafetyCheckOk(db) ){
  133833. (void)SQLITE_MISUSE_BKPT;
  133834. return 0;
  133835. }
  133836. #endif
  133837. sqlite3_mutex_enter(db->mutex);
  133838. pOld = db->pCommitArg;
  133839. db->xCommitCallback = xCallback;
  133840. db->pCommitArg = pArg;
  133841. sqlite3_mutex_leave(db->mutex);
  133842. return pOld;
  133843. }
  133844. /*
  133845. ** Register a callback to be invoked each time a row is updated,
  133846. ** inserted or deleted using this database connection.
  133847. */
  133848. SQLITE_API void *sqlite3_update_hook(
  133849. sqlite3 *db, /* Attach the hook to this database */
  133850. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  133851. void *pArg /* Argument to the function */
  133852. ){
  133853. void *pRet;
  133854. #ifdef SQLITE_ENABLE_API_ARMOR
  133855. if( !sqlite3SafetyCheckOk(db) ){
  133856. (void)SQLITE_MISUSE_BKPT;
  133857. return 0;
  133858. }
  133859. #endif
  133860. sqlite3_mutex_enter(db->mutex);
  133861. pRet = db->pUpdateArg;
  133862. db->xUpdateCallback = xCallback;
  133863. db->pUpdateArg = pArg;
  133864. sqlite3_mutex_leave(db->mutex);
  133865. return pRet;
  133866. }
  133867. /*
  133868. ** Register a callback to be invoked each time a transaction is rolled
  133869. ** back by this database connection.
  133870. */
  133871. SQLITE_API void *sqlite3_rollback_hook(
  133872. sqlite3 *db, /* Attach the hook to this database */
  133873. void (*xCallback)(void*), /* Callback function */
  133874. void *pArg /* Argument to the function */
  133875. ){
  133876. void *pRet;
  133877. #ifdef SQLITE_ENABLE_API_ARMOR
  133878. if( !sqlite3SafetyCheckOk(db) ){
  133879. (void)SQLITE_MISUSE_BKPT;
  133880. return 0;
  133881. }
  133882. #endif
  133883. sqlite3_mutex_enter(db->mutex);
  133884. pRet = db->pRollbackArg;
  133885. db->xRollbackCallback = xCallback;
  133886. db->pRollbackArg = pArg;
  133887. sqlite3_mutex_leave(db->mutex);
  133888. return pRet;
  133889. }
  133890. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  133891. /*
  133892. ** Register a callback to be invoked each time a row is updated,
  133893. ** inserted or deleted using this database connection.
  133894. */
  133895. SQLITE_API void *sqlite3_preupdate_hook(
  133896. sqlite3 *db, /* Attach the hook to this database */
  133897. void(*xCallback)( /* Callback function */
  133898. void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
  133899. void *pArg /* First callback argument */
  133900. ){
  133901. void *pRet;
  133902. sqlite3_mutex_enter(db->mutex);
  133903. pRet = db->pPreUpdateArg;
  133904. db->xPreUpdateCallback = xCallback;
  133905. db->pPreUpdateArg = pArg;
  133906. sqlite3_mutex_leave(db->mutex);
  133907. return pRet;
  133908. }
  133909. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  133910. #ifndef SQLITE_OMIT_WAL
  133911. /*
  133912. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  133913. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  133914. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  133915. ** wal_autocheckpoint()).
  133916. */
  133917. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  133918. void *pClientData, /* Argument */
  133919. sqlite3 *db, /* Connection */
  133920. const char *zDb, /* Database */
  133921. int nFrame /* Size of WAL */
  133922. ){
  133923. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  133924. sqlite3BeginBenignMalloc();
  133925. sqlite3_wal_checkpoint(db, zDb);
  133926. sqlite3EndBenignMalloc();
  133927. }
  133928. return SQLITE_OK;
  133929. }
  133930. #endif /* SQLITE_OMIT_WAL */
  133931. /*
  133932. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  133933. ** a database after committing a transaction if there are nFrame or
  133934. ** more frames in the log file. Passing zero or a negative value as the
  133935. ** nFrame parameter disables automatic checkpoints entirely.
  133936. **
  133937. ** The callback registered by this function replaces any existing callback
  133938. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  133939. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  133940. ** configured by this function.
  133941. */
  133942. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  133943. #ifdef SQLITE_OMIT_WAL
  133944. UNUSED_PARAMETER(db);
  133945. UNUSED_PARAMETER(nFrame);
  133946. #else
  133947. #ifdef SQLITE_ENABLE_API_ARMOR
  133948. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  133949. #endif
  133950. if( nFrame>0 ){
  133951. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  133952. }else{
  133953. sqlite3_wal_hook(db, 0, 0);
  133954. }
  133955. #endif
  133956. return SQLITE_OK;
  133957. }
  133958. /*
  133959. ** Register a callback to be invoked each time a transaction is written
  133960. ** into the write-ahead-log by this database connection.
  133961. */
  133962. SQLITE_API void *sqlite3_wal_hook(
  133963. sqlite3 *db, /* Attach the hook to this db handle */
  133964. int(*xCallback)(void *, sqlite3*, const char*, int),
  133965. void *pArg /* First argument passed to xCallback() */
  133966. ){
  133967. #ifndef SQLITE_OMIT_WAL
  133968. void *pRet;
  133969. #ifdef SQLITE_ENABLE_API_ARMOR
  133970. if( !sqlite3SafetyCheckOk(db) ){
  133971. (void)SQLITE_MISUSE_BKPT;
  133972. return 0;
  133973. }
  133974. #endif
  133975. sqlite3_mutex_enter(db->mutex);
  133976. pRet = db->pWalArg;
  133977. db->xWalCallback = xCallback;
  133978. db->pWalArg = pArg;
  133979. sqlite3_mutex_leave(db->mutex);
  133980. return pRet;
  133981. #else
  133982. return 0;
  133983. #endif
  133984. }
  133985. /*
  133986. ** Checkpoint database zDb.
  133987. */
  133988. SQLITE_API int sqlite3_wal_checkpoint_v2(
  133989. sqlite3 *db, /* Database handle */
  133990. const char *zDb, /* Name of attached database (or NULL) */
  133991. int eMode, /* SQLITE_CHECKPOINT_* value */
  133992. int *pnLog, /* OUT: Size of WAL log in frames */
  133993. int *pnCkpt /* OUT: Total number of frames checkpointed */
  133994. ){
  133995. #ifdef SQLITE_OMIT_WAL
  133996. return SQLITE_OK;
  133997. #else
  133998. int rc; /* Return code */
  133999. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  134000. #ifdef SQLITE_ENABLE_API_ARMOR
  134001. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  134002. #endif
  134003. /* Initialize the output variables to -1 in case an error occurs. */
  134004. if( pnLog ) *pnLog = -1;
  134005. if( pnCkpt ) *pnCkpt = -1;
  134006. assert( SQLITE_CHECKPOINT_PASSIVE==0 );
  134007. assert( SQLITE_CHECKPOINT_FULL==1 );
  134008. assert( SQLITE_CHECKPOINT_RESTART==2 );
  134009. assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
  134010. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
  134011. /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
  134012. ** mode: */
  134013. return SQLITE_MISUSE;
  134014. }
  134015. sqlite3_mutex_enter(db->mutex);
  134016. if( zDb && zDb[0] ){
  134017. iDb = sqlite3FindDbName(db, zDb);
  134018. }
  134019. if( iDb<0 ){
  134020. rc = SQLITE_ERROR;
  134021. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
  134022. }else{
  134023. db->busyHandler.nBusy = 0;
  134024. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  134025. sqlite3Error(db, rc);
  134026. }
  134027. rc = sqlite3ApiExit(db, rc);
  134028. /* If there are no active statements, clear the interrupt flag at this
  134029. ** point. */
  134030. if( db->nVdbeActive==0 ){
  134031. db->u1.isInterrupted = 0;
  134032. }
  134033. sqlite3_mutex_leave(db->mutex);
  134034. return rc;
  134035. #endif
  134036. }
  134037. /*
  134038. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  134039. ** to contains a zero-length string, all attached databases are
  134040. ** checkpointed.
  134041. */
  134042. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  134043. /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
  134044. ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
  134045. return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
  134046. }
  134047. #ifndef SQLITE_OMIT_WAL
  134048. /*
  134049. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  134050. ** not currently open in WAL mode.
  134051. **
  134052. ** If a transaction is open on the database being checkpointed, this
  134053. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  134054. ** an error occurs while running the checkpoint, an SQLite error code is
  134055. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  134056. **
  134057. ** The mutex on database handle db should be held by the caller. The mutex
  134058. ** associated with the specific b-tree being checkpointed is taken by
  134059. ** this function while the checkpoint is running.
  134060. **
  134061. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  134062. ** checkpointed. If an error is encountered it is returned immediately -
  134063. ** no attempt is made to checkpoint any remaining databases.
  134064. **
  134065. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  134066. */
  134067. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  134068. int rc = SQLITE_OK; /* Return code */
  134069. int i; /* Used to iterate through attached dbs */
  134070. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  134071. assert( sqlite3_mutex_held(db->mutex) );
  134072. assert( !pnLog || *pnLog==-1 );
  134073. assert( !pnCkpt || *pnCkpt==-1 );
  134074. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  134075. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  134076. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  134077. pnLog = 0;
  134078. pnCkpt = 0;
  134079. if( rc==SQLITE_BUSY ){
  134080. bBusy = 1;
  134081. rc = SQLITE_OK;
  134082. }
  134083. }
  134084. }
  134085. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  134086. }
  134087. #endif /* SQLITE_OMIT_WAL */
  134088. /*
  134089. ** This function returns true if main-memory should be used instead of
  134090. ** a temporary file for transient pager files and statement journals.
  134091. ** The value returned depends on the value of db->temp_store (runtime
  134092. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  134093. ** following table describes the relationship between these two values
  134094. ** and this functions return value.
  134095. **
  134096. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  134097. ** ----------------- -------------- ------------------------------
  134098. ** 0 any file (return 0)
  134099. ** 1 1 file (return 0)
  134100. ** 1 2 memory (return 1)
  134101. ** 1 0 file (return 0)
  134102. ** 2 1 file (return 0)
  134103. ** 2 2 memory (return 1)
  134104. ** 2 0 memory (return 1)
  134105. ** 3 any memory (return 1)
  134106. */
  134107. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  134108. #if SQLITE_TEMP_STORE==1
  134109. return ( db->temp_store==2 );
  134110. #endif
  134111. #if SQLITE_TEMP_STORE==2
  134112. return ( db->temp_store!=1 );
  134113. #endif
  134114. #if SQLITE_TEMP_STORE==3
  134115. UNUSED_PARAMETER(db);
  134116. return 1;
  134117. #endif
  134118. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  134119. UNUSED_PARAMETER(db);
  134120. return 0;
  134121. #endif
  134122. }
  134123. /*
  134124. ** Return UTF-8 encoded English language explanation of the most recent
  134125. ** error.
  134126. */
  134127. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  134128. const char *z;
  134129. if( !db ){
  134130. return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  134131. }
  134132. if( !sqlite3SafetyCheckSickOrOk(db) ){
  134133. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  134134. }
  134135. sqlite3_mutex_enter(db->mutex);
  134136. if( db->mallocFailed ){
  134137. z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  134138. }else{
  134139. testcase( db->pErr==0 );
  134140. z = (char*)sqlite3_value_text(db->pErr);
  134141. assert( !db->mallocFailed );
  134142. if( z==0 ){
  134143. z = sqlite3ErrStr(db->errCode);
  134144. }
  134145. }
  134146. sqlite3_mutex_leave(db->mutex);
  134147. return z;
  134148. }
  134149. #ifndef SQLITE_OMIT_UTF16
  134150. /*
  134151. ** Return UTF-16 encoded English language explanation of the most recent
  134152. ** error.
  134153. */
  134154. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  134155. static const u16 outOfMem[] = {
  134156. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  134157. };
  134158. static const u16 misuse[] = {
  134159. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  134160. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  134161. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  134162. 'o', 'u', 't', ' ',
  134163. 'o', 'f', ' ',
  134164. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  134165. };
  134166. const void *z;
  134167. if( !db ){
  134168. return (void *)outOfMem;
  134169. }
  134170. if( !sqlite3SafetyCheckSickOrOk(db) ){
  134171. return (void *)misuse;
  134172. }
  134173. sqlite3_mutex_enter(db->mutex);
  134174. if( db->mallocFailed ){
  134175. z = (void *)outOfMem;
  134176. }else{
  134177. z = sqlite3_value_text16(db->pErr);
  134178. if( z==0 ){
  134179. sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
  134180. z = sqlite3_value_text16(db->pErr);
  134181. }
  134182. /* A malloc() may have failed within the call to sqlite3_value_text16()
  134183. ** above. If this is the case, then the db->mallocFailed flag needs to
  134184. ** be cleared before returning. Do this directly, instead of via
  134185. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  134186. */
  134187. sqlite3OomClear(db);
  134188. }
  134189. sqlite3_mutex_leave(db->mutex);
  134190. return z;
  134191. }
  134192. #endif /* SQLITE_OMIT_UTF16 */
  134193. /*
  134194. ** Return the most recent error code generated by an SQLite routine. If NULL is
  134195. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  134196. */
  134197. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  134198. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  134199. return SQLITE_MISUSE_BKPT;
  134200. }
  134201. if( !db || db->mallocFailed ){
  134202. return SQLITE_NOMEM_BKPT;
  134203. }
  134204. return db->errCode & db->errMask;
  134205. }
  134206. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  134207. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  134208. return SQLITE_MISUSE_BKPT;
  134209. }
  134210. if( !db || db->mallocFailed ){
  134211. return SQLITE_NOMEM_BKPT;
  134212. }
  134213. return db->errCode;
  134214. }
  134215. SQLITE_API int sqlite3_system_errno(sqlite3 *db){
  134216. return db ? db->iSysErrno : 0;
  134217. }
  134218. /*
  134219. ** Return a string that describes the kind of error specified in the
  134220. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  134221. ** function.
  134222. */
  134223. SQLITE_API const char *sqlite3_errstr(int rc){
  134224. return sqlite3ErrStr(rc);
  134225. }
  134226. /*
  134227. ** Create a new collating function for database "db". The name is zName
  134228. ** and the encoding is enc.
  134229. */
  134230. static int createCollation(
  134231. sqlite3* db,
  134232. const char *zName,
  134233. u8 enc,
  134234. void* pCtx,
  134235. int(*xCompare)(void*,int,const void*,int,const void*),
  134236. void(*xDel)(void*)
  134237. ){
  134238. CollSeq *pColl;
  134239. int enc2;
  134240. assert( sqlite3_mutex_held(db->mutex) );
  134241. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  134242. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  134243. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  134244. */
  134245. enc2 = enc;
  134246. testcase( enc2==SQLITE_UTF16 );
  134247. testcase( enc2==SQLITE_UTF16_ALIGNED );
  134248. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  134249. enc2 = SQLITE_UTF16NATIVE;
  134250. }
  134251. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  134252. return SQLITE_MISUSE_BKPT;
  134253. }
  134254. /* Check if this call is removing or replacing an existing collation
  134255. ** sequence. If so, and there are active VMs, return busy. If there
  134256. ** are no active VMs, invalidate any pre-compiled statements.
  134257. */
  134258. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  134259. if( pColl && pColl->xCmp ){
  134260. if( db->nVdbeActive ){
  134261. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  134262. "unable to delete/modify collation sequence due to active statements");
  134263. return SQLITE_BUSY;
  134264. }
  134265. sqlite3ExpirePreparedStatements(db);
  134266. /* If collation sequence pColl was created directly by a call to
  134267. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  134268. ** then any copies made by synthCollSeq() need to be invalidated.
  134269. ** Also, collation destructor - CollSeq.xDel() - function may need
  134270. ** to be called.
  134271. */
  134272. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  134273. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
  134274. int j;
  134275. for(j=0; j<3; j++){
  134276. CollSeq *p = &aColl[j];
  134277. if( p->enc==pColl->enc ){
  134278. if( p->xDel ){
  134279. p->xDel(p->pUser);
  134280. }
  134281. p->xCmp = 0;
  134282. }
  134283. }
  134284. }
  134285. }
  134286. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  134287. if( pColl==0 ) return SQLITE_NOMEM_BKPT;
  134288. pColl->xCmp = xCompare;
  134289. pColl->pUser = pCtx;
  134290. pColl->xDel = xDel;
  134291. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  134292. sqlite3Error(db, SQLITE_OK);
  134293. return SQLITE_OK;
  134294. }
  134295. /*
  134296. ** This array defines hard upper bounds on limit values. The
  134297. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  134298. ** #defines in sqlite3.h.
  134299. */
  134300. static const int aHardLimit[] = {
  134301. SQLITE_MAX_LENGTH,
  134302. SQLITE_MAX_SQL_LENGTH,
  134303. SQLITE_MAX_COLUMN,
  134304. SQLITE_MAX_EXPR_DEPTH,
  134305. SQLITE_MAX_COMPOUND_SELECT,
  134306. SQLITE_MAX_VDBE_OP,
  134307. SQLITE_MAX_FUNCTION_ARG,
  134308. SQLITE_MAX_ATTACHED,
  134309. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  134310. SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
  134311. SQLITE_MAX_TRIGGER_DEPTH,
  134312. SQLITE_MAX_WORKER_THREADS,
  134313. };
  134314. /*
  134315. ** Make sure the hard limits are set to reasonable values
  134316. */
  134317. #if SQLITE_MAX_LENGTH<100
  134318. # error SQLITE_MAX_LENGTH must be at least 100
  134319. #endif
  134320. #if SQLITE_MAX_SQL_LENGTH<100
  134321. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  134322. #endif
  134323. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  134324. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  134325. #endif
  134326. #if SQLITE_MAX_COMPOUND_SELECT<2
  134327. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  134328. #endif
  134329. #if SQLITE_MAX_VDBE_OP<40
  134330. # error SQLITE_MAX_VDBE_OP must be at least 40
  134331. #endif
  134332. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
  134333. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
  134334. #endif
  134335. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
  134336. # error SQLITE_MAX_ATTACHED must be between 0 and 125
  134337. #endif
  134338. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  134339. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  134340. #endif
  134341. #if SQLITE_MAX_COLUMN>32767
  134342. # error SQLITE_MAX_COLUMN must not exceed 32767
  134343. #endif
  134344. #if SQLITE_MAX_TRIGGER_DEPTH<1
  134345. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  134346. #endif
  134347. #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
  134348. # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
  134349. #endif
  134350. /*
  134351. ** Change the value of a limit. Report the old value.
  134352. ** If an invalid limit index is supplied, report -1.
  134353. ** Make no changes but still report the old value if the
  134354. ** new limit is negative.
  134355. **
  134356. ** A new lower limit does not shrink existing constructs.
  134357. ** It merely prevents new constructs that exceed the limit
  134358. ** from forming.
  134359. */
  134360. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  134361. int oldLimit;
  134362. #ifdef SQLITE_ENABLE_API_ARMOR
  134363. if( !sqlite3SafetyCheckOk(db) ){
  134364. (void)SQLITE_MISUSE_BKPT;
  134365. return -1;
  134366. }
  134367. #endif
  134368. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  134369. ** there is a hard upper bound set at compile-time by a C preprocessor
  134370. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  134371. ** "_MAX_".)
  134372. */
  134373. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  134374. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  134375. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  134376. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  134377. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  134378. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  134379. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  134380. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  134381. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  134382. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  134383. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  134384. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  134385. assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
  134386. assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
  134387. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  134388. return -1;
  134389. }
  134390. oldLimit = db->aLimit[limitId];
  134391. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  134392. if( newLimit>aHardLimit[limitId] ){
  134393. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  134394. }
  134395. db->aLimit[limitId] = newLimit;
  134396. }
  134397. return oldLimit; /* IMP: R-53341-35419 */
  134398. }
  134399. /*
  134400. ** This function is used to parse both URIs and non-URI filenames passed by the
  134401. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  134402. ** URIs specified as part of ATTACH statements.
  134403. **
  134404. ** The first argument to this function is the name of the VFS to use (or
  134405. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  134406. ** query parameter. The second argument contains the URI (or non-URI filename)
  134407. ** itself. When this function is called the *pFlags variable should contain
  134408. ** the default flags to open the database handle with. The value stored in
  134409. ** *pFlags may be updated before returning if the URI filename contains
  134410. ** "cache=xxx" or "mode=xxx" query parameters.
  134411. **
  134412. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  134413. ** the VFS that should be used to open the database file. *pzFile is set to
  134414. ** point to a buffer containing the name of the file to open. It is the
  134415. ** responsibility of the caller to eventually call sqlite3_free() to release
  134416. ** this buffer.
  134417. **
  134418. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  134419. ** may be set to point to a buffer containing an English language error
  134420. ** message. It is the responsibility of the caller to eventually release
  134421. ** this buffer by calling sqlite3_free().
  134422. */
  134423. SQLITE_PRIVATE int sqlite3ParseUri(
  134424. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  134425. const char *zUri, /* Nul-terminated URI to parse */
  134426. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  134427. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  134428. char **pzFile, /* OUT: Filename component of URI */
  134429. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  134430. ){
  134431. int rc = SQLITE_OK;
  134432. unsigned int flags = *pFlags;
  134433. const char *zVfs = zDefaultVfs;
  134434. char *zFile;
  134435. char c;
  134436. int nUri = sqlite3Strlen30(zUri);
  134437. assert( *pzErrMsg==0 );
  134438. if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
  134439. || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
  134440. && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
  134441. ){
  134442. char *zOpt;
  134443. int eState; /* Parser state when parsing URI */
  134444. int iIn; /* Input character index */
  134445. int iOut = 0; /* Output character index */
  134446. u64 nByte = nUri+2; /* Bytes of space to allocate */
  134447. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  134448. ** method that there may be extra parameters following the file-name. */
  134449. flags |= SQLITE_OPEN_URI;
  134450. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  134451. zFile = sqlite3_malloc64(nByte);
  134452. if( !zFile ) return SQLITE_NOMEM_BKPT;
  134453. iIn = 5;
  134454. #ifdef SQLITE_ALLOW_URI_AUTHORITY
  134455. if( strncmp(zUri+5, "///", 3)==0 ){
  134456. iIn = 7;
  134457. /* The following condition causes URIs with five leading / characters
  134458. ** like file://///host/path to be converted into UNCs like //host/path.
  134459. ** The correct URI for that UNC has only two or four leading / characters
  134460. ** file://host/path or file:////host/path. But 5 leading slashes is a
  134461. ** common error, we are told, so we handle it as a special case. */
  134462. if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
  134463. }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
  134464. iIn = 16;
  134465. }
  134466. #else
  134467. /* Discard the scheme and authority segments of the URI. */
  134468. if( zUri[5]=='/' && zUri[6]=='/' ){
  134469. iIn = 7;
  134470. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  134471. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  134472. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  134473. iIn-7, &zUri[7]);
  134474. rc = SQLITE_ERROR;
  134475. goto parse_uri_out;
  134476. }
  134477. }
  134478. #endif
  134479. /* Copy the filename and any query parameters into the zFile buffer.
  134480. ** Decode %HH escape codes along the way.
  134481. **
  134482. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  134483. ** on the parsing context. As follows:
  134484. **
  134485. ** 0: Parsing file-name.
  134486. ** 1: Parsing name section of a name=value query parameter.
  134487. ** 2: Parsing value section of a name=value query parameter.
  134488. */
  134489. eState = 0;
  134490. while( (c = zUri[iIn])!=0 && c!='#' ){
  134491. iIn++;
  134492. if( c=='%'
  134493. && sqlite3Isxdigit(zUri[iIn])
  134494. && sqlite3Isxdigit(zUri[iIn+1])
  134495. ){
  134496. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  134497. octet += sqlite3HexToInt(zUri[iIn++]);
  134498. assert( octet>=0 && octet<256 );
  134499. if( octet==0 ){
  134500. #ifndef SQLITE_ENABLE_URI_00_ERROR
  134501. /* This branch is taken when "%00" appears within the URI. In this
  134502. ** case we ignore all text in the remainder of the path, name or
  134503. ** value currently being parsed. So ignore the current character
  134504. ** and skip to the next "?", "=" or "&", as appropriate. */
  134505. while( (c = zUri[iIn])!=0 && c!='#'
  134506. && (eState!=0 || c!='?')
  134507. && (eState!=1 || (c!='=' && c!='&'))
  134508. && (eState!=2 || c!='&')
  134509. ){
  134510. iIn++;
  134511. }
  134512. continue;
  134513. #else
  134514. /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
  134515. *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
  134516. rc = SQLITE_ERROR;
  134517. goto parse_uri_out;
  134518. #endif
  134519. }
  134520. c = octet;
  134521. }else if( eState==1 && (c=='&' || c=='=') ){
  134522. if( zFile[iOut-1]==0 ){
  134523. /* An empty option name. Ignore this option altogether. */
  134524. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  134525. continue;
  134526. }
  134527. if( c=='&' ){
  134528. zFile[iOut++] = '\0';
  134529. }else{
  134530. eState = 2;
  134531. }
  134532. c = 0;
  134533. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  134534. c = 0;
  134535. eState = 1;
  134536. }
  134537. zFile[iOut++] = c;
  134538. }
  134539. if( eState==1 ) zFile[iOut++] = '\0';
  134540. zFile[iOut++] = '\0';
  134541. zFile[iOut++] = '\0';
  134542. /* Check if there were any options specified that should be interpreted
  134543. ** here. Options that are interpreted here include "vfs" and those that
  134544. ** correspond to flags that may be passed to the sqlite3_open_v2()
  134545. ** method. */
  134546. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  134547. while( zOpt[0] ){
  134548. int nOpt = sqlite3Strlen30(zOpt);
  134549. char *zVal = &zOpt[nOpt+1];
  134550. int nVal = sqlite3Strlen30(zVal);
  134551. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  134552. zVfs = zVal;
  134553. }else{
  134554. struct OpenMode {
  134555. const char *z;
  134556. int mode;
  134557. } *aMode = 0;
  134558. char *zModeType = 0;
  134559. int mask = 0;
  134560. int limit = 0;
  134561. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  134562. static struct OpenMode aCacheMode[] = {
  134563. { "shared", SQLITE_OPEN_SHAREDCACHE },
  134564. { "private", SQLITE_OPEN_PRIVATECACHE },
  134565. { 0, 0 }
  134566. };
  134567. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  134568. aMode = aCacheMode;
  134569. limit = mask;
  134570. zModeType = "cache";
  134571. }
  134572. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  134573. static struct OpenMode aOpenMode[] = {
  134574. { "ro", SQLITE_OPEN_READONLY },
  134575. { "rw", SQLITE_OPEN_READWRITE },
  134576. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  134577. { "memory", SQLITE_OPEN_MEMORY },
  134578. { 0, 0 }
  134579. };
  134580. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  134581. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  134582. aMode = aOpenMode;
  134583. limit = mask & flags;
  134584. zModeType = "access";
  134585. }
  134586. if( aMode ){
  134587. int i;
  134588. int mode = 0;
  134589. for(i=0; aMode[i].z; i++){
  134590. const char *z = aMode[i].z;
  134591. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  134592. mode = aMode[i].mode;
  134593. break;
  134594. }
  134595. }
  134596. if( mode==0 ){
  134597. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  134598. rc = SQLITE_ERROR;
  134599. goto parse_uri_out;
  134600. }
  134601. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  134602. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  134603. zModeType, zVal);
  134604. rc = SQLITE_PERM;
  134605. goto parse_uri_out;
  134606. }
  134607. flags = (flags & ~mask) | mode;
  134608. }
  134609. }
  134610. zOpt = &zVal[nVal+1];
  134611. }
  134612. }else{
  134613. zFile = sqlite3_malloc64(nUri+2);
  134614. if( !zFile ) return SQLITE_NOMEM_BKPT;
  134615. if( nUri ){
  134616. memcpy(zFile, zUri, nUri);
  134617. }
  134618. zFile[nUri] = '\0';
  134619. zFile[nUri+1] = '\0';
  134620. flags &= ~SQLITE_OPEN_URI;
  134621. }
  134622. *ppVfs = sqlite3_vfs_find(zVfs);
  134623. if( *ppVfs==0 ){
  134624. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  134625. rc = SQLITE_ERROR;
  134626. }
  134627. parse_uri_out:
  134628. if( rc!=SQLITE_OK ){
  134629. sqlite3_free(zFile);
  134630. zFile = 0;
  134631. }
  134632. *pFlags = flags;
  134633. *pzFile = zFile;
  134634. return rc;
  134635. }
  134636. /*
  134637. ** This routine does the work of opening a database on behalf of
  134638. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  134639. ** is UTF-8 encoded.
  134640. */
  134641. static int openDatabase(
  134642. const char *zFilename, /* Database filename UTF-8 encoded */
  134643. sqlite3 **ppDb, /* OUT: Returned database handle */
  134644. unsigned int flags, /* Operational flags */
  134645. const char *zVfs /* Name of the VFS to use */
  134646. ){
  134647. sqlite3 *db; /* Store allocated handle here */
  134648. int rc; /* Return code */
  134649. int isThreadsafe; /* True for threadsafe connections */
  134650. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  134651. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  134652. #ifdef SQLITE_ENABLE_API_ARMOR
  134653. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  134654. #endif
  134655. *ppDb = 0;
  134656. #ifndef SQLITE_OMIT_AUTOINIT
  134657. rc = sqlite3_initialize();
  134658. if( rc ) return rc;
  134659. #endif
  134660. /* Only allow sensible combinations of bits in the flags argument.
  134661. ** Throw an error if any non-sense combination is used. If we
  134662. ** do not block illegal combinations here, it could trigger
  134663. ** assert() statements in deeper layers. Sensible combinations
  134664. ** are:
  134665. **
  134666. ** 1: SQLITE_OPEN_READONLY
  134667. ** 2: SQLITE_OPEN_READWRITE
  134668. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  134669. */
  134670. assert( SQLITE_OPEN_READONLY == 0x01 );
  134671. assert( SQLITE_OPEN_READWRITE == 0x02 );
  134672. assert( SQLITE_OPEN_CREATE == 0x04 );
  134673. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  134674. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  134675. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  134676. if( ((1<<(flags&7)) & 0x46)==0 ){
  134677. return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
  134678. }
  134679. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  134680. isThreadsafe = 0;
  134681. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  134682. isThreadsafe = 0;
  134683. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  134684. isThreadsafe = 1;
  134685. }else{
  134686. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  134687. }
  134688. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  134689. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  134690. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  134691. flags |= SQLITE_OPEN_SHAREDCACHE;
  134692. }
  134693. /* Remove harmful bits from the flags parameter
  134694. **
  134695. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  134696. ** dealt with in the previous code block. Besides these, the only
  134697. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  134698. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  134699. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  134700. ** off all other flags.
  134701. */
  134702. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  134703. SQLITE_OPEN_EXCLUSIVE |
  134704. SQLITE_OPEN_MAIN_DB |
  134705. SQLITE_OPEN_TEMP_DB |
  134706. SQLITE_OPEN_TRANSIENT_DB |
  134707. SQLITE_OPEN_MAIN_JOURNAL |
  134708. SQLITE_OPEN_TEMP_JOURNAL |
  134709. SQLITE_OPEN_SUBJOURNAL |
  134710. SQLITE_OPEN_MASTER_JOURNAL |
  134711. SQLITE_OPEN_NOMUTEX |
  134712. SQLITE_OPEN_FULLMUTEX |
  134713. SQLITE_OPEN_WAL
  134714. );
  134715. /* Allocate the sqlite data structure */
  134716. db = sqlite3MallocZero( sizeof(sqlite3) );
  134717. if( db==0 ) goto opendb_out;
  134718. if( isThreadsafe ){
  134719. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  134720. if( db->mutex==0 ){
  134721. sqlite3_free(db);
  134722. db = 0;
  134723. goto opendb_out;
  134724. }
  134725. }
  134726. sqlite3_mutex_enter(db->mutex);
  134727. db->errMask = 0xff;
  134728. db->nDb = 2;
  134729. db->magic = SQLITE_MAGIC_BUSY;
  134730. db->aDb = db->aDbStatic;
  134731. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  134732. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  134733. db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
  134734. db->autoCommit = 1;
  134735. db->nextAutovac = -1;
  134736. db->szMmap = sqlite3GlobalConfig.szMmap;
  134737. db->nextPagesize = 0;
  134738. db->nMaxSorterMmap = 0x7FFFFFFF;
  134739. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  134740. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  134741. | SQLITE_AutoIndex
  134742. #endif
  134743. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  134744. | SQLITE_CkptFullFSync
  134745. #endif
  134746. #if SQLITE_DEFAULT_FILE_FORMAT<4
  134747. | SQLITE_LegacyFileFmt
  134748. #endif
  134749. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  134750. | SQLITE_LoadExtension
  134751. #endif
  134752. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  134753. | SQLITE_RecTriggers
  134754. #endif
  134755. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  134756. | SQLITE_ForeignKeys
  134757. #endif
  134758. #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
  134759. | SQLITE_ReverseOrder
  134760. #endif
  134761. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  134762. | SQLITE_CellSizeCk
  134763. #endif
  134764. #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
  134765. | SQLITE_Fts3Tokenizer
  134766. #endif
  134767. ;
  134768. sqlite3HashInit(&db->aCollSeq);
  134769. #ifndef SQLITE_OMIT_VIRTUALTABLE
  134770. sqlite3HashInit(&db->aModule);
  134771. #endif
  134772. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  134773. ** and UTF-16, so add a version for each to avoid any unnecessary
  134774. ** conversions. The only error that can occur here is a malloc() failure.
  134775. **
  134776. ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
  134777. ** functions:
  134778. */
  134779. createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
  134780. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
  134781. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
  134782. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  134783. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  134784. if( db->mallocFailed ){
  134785. goto opendb_out;
  134786. }
  134787. /* EVIDENCE-OF: R-08308-17224 The default collating function for all
  134788. ** strings is BINARY.
  134789. */
  134790. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
  134791. assert( db->pDfltColl!=0 );
  134792. /* Parse the filename/URI argument. */
  134793. db->openFlags = flags;
  134794. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  134795. if( rc!=SQLITE_OK ){
  134796. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  134797. sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  134798. sqlite3_free(zErrMsg);
  134799. goto opendb_out;
  134800. }
  134801. /* Open the backend database driver */
  134802. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  134803. flags | SQLITE_OPEN_MAIN_DB);
  134804. if( rc!=SQLITE_OK ){
  134805. if( rc==SQLITE_IOERR_NOMEM ){
  134806. rc = SQLITE_NOMEM_BKPT;
  134807. }
  134808. sqlite3Error(db, rc);
  134809. goto opendb_out;
  134810. }
  134811. sqlite3BtreeEnter(db->aDb[0].pBt);
  134812. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  134813. if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
  134814. sqlite3BtreeLeave(db->aDb[0].pBt);
  134815. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  134816. /* The default safety_level for the main database is FULL; for the temp
  134817. ** database it is OFF. This matches the pager layer defaults.
  134818. */
  134819. db->aDb[0].zDbSName = "main";
  134820. db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  134821. db->aDb[1].zDbSName = "temp";
  134822. db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
  134823. db->magic = SQLITE_MAGIC_OPEN;
  134824. if( db->mallocFailed ){
  134825. goto opendb_out;
  134826. }
  134827. /* Register all built-in functions, but do not attempt to read the
  134828. ** database schema yet. This is delayed until the first time the database
  134829. ** is accessed.
  134830. */
  134831. sqlite3Error(db, SQLITE_OK);
  134832. sqlite3RegisterPerConnectionBuiltinFunctions(db);
  134833. rc = sqlite3_errcode(db);
  134834. #ifdef SQLITE_ENABLE_FTS5
  134835. /* Register any built-in FTS5 module before loading the automatic
  134836. ** extensions. This allows automatic extensions to register FTS5
  134837. ** tokenizers and auxiliary functions. */
  134838. if( !db->mallocFailed && rc==SQLITE_OK ){
  134839. rc = sqlite3Fts5Init(db);
  134840. }
  134841. #endif
  134842. /* Load automatic extensions - extensions that have been registered
  134843. ** using the sqlite3_automatic_extension() API.
  134844. */
  134845. if( rc==SQLITE_OK ){
  134846. sqlite3AutoLoadExtensions(db);
  134847. rc = sqlite3_errcode(db);
  134848. if( rc!=SQLITE_OK ){
  134849. goto opendb_out;
  134850. }
  134851. }
  134852. #ifdef SQLITE_ENABLE_FTS1
  134853. if( !db->mallocFailed ){
  134854. extern int sqlite3Fts1Init(sqlite3*);
  134855. rc = sqlite3Fts1Init(db);
  134856. }
  134857. #endif
  134858. #ifdef SQLITE_ENABLE_FTS2
  134859. if( !db->mallocFailed && rc==SQLITE_OK ){
  134860. extern int sqlite3Fts2Init(sqlite3*);
  134861. rc = sqlite3Fts2Init(db);
  134862. }
  134863. #endif
  134864. #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
  134865. if( !db->mallocFailed && rc==SQLITE_OK ){
  134866. rc = sqlite3Fts3Init(db);
  134867. }
  134868. #endif
  134869. #ifdef SQLITE_ENABLE_ICU
  134870. if( !db->mallocFailed && rc==SQLITE_OK ){
  134871. rc = sqlite3IcuInit(db);
  134872. }
  134873. #endif
  134874. #ifdef SQLITE_ENABLE_RTREE
  134875. if( !db->mallocFailed && rc==SQLITE_OK){
  134876. rc = sqlite3RtreeInit(db);
  134877. }
  134878. #endif
  134879. #ifdef SQLITE_ENABLE_DBSTAT_VTAB
  134880. if( !db->mallocFailed && rc==SQLITE_OK){
  134881. rc = sqlite3DbstatRegister(db);
  134882. }
  134883. #endif
  134884. #ifdef SQLITE_ENABLE_JSON1
  134885. if( !db->mallocFailed && rc==SQLITE_OK){
  134886. rc = sqlite3Json1Init(db);
  134887. }
  134888. #endif
  134889. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  134890. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  134891. ** mode. Doing nothing at all also makes NORMAL the default.
  134892. */
  134893. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  134894. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  134895. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  134896. SQLITE_DEFAULT_LOCKING_MODE);
  134897. #endif
  134898. if( rc ) sqlite3Error(db, rc);
  134899. /* Enable the lookaside-malloc subsystem */
  134900. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  134901. sqlite3GlobalConfig.nLookaside);
  134902. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  134903. opendb_out:
  134904. if( db ){
  134905. assert( db->mutex!=0 || isThreadsafe==0
  134906. || sqlite3GlobalConfig.bFullMutex==0 );
  134907. sqlite3_mutex_leave(db->mutex);
  134908. }
  134909. rc = sqlite3_errcode(db);
  134910. assert( db!=0 || rc==SQLITE_NOMEM );
  134911. if( rc==SQLITE_NOMEM ){
  134912. sqlite3_close(db);
  134913. db = 0;
  134914. }else if( rc!=SQLITE_OK ){
  134915. db->magic = SQLITE_MAGIC_SICK;
  134916. }
  134917. *ppDb = db;
  134918. #ifdef SQLITE_ENABLE_SQLLOG
  134919. if( sqlite3GlobalConfig.xSqllog ){
  134920. /* Opening a db handle. Fourth parameter is passed 0. */
  134921. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  134922. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  134923. }
  134924. #endif
  134925. #if defined(SQLITE_HAS_CODEC)
  134926. if( rc==SQLITE_OK ){
  134927. const char *zKey;
  134928. if( (zKey = sqlite3_uri_parameter(zOpen, "hexkey"))!=0 && zKey[0] ){
  134929. u8 iByte;
  134930. int i;
  134931. char zDecoded[40];
  134932. for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
  134933. iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
  134934. if( (i&1)!=0 ) zDecoded[i/2] = iByte;
  134935. }
  134936. sqlite3_key_v2(db, 0, zDecoded, i/2);
  134937. }else if( (zKey = sqlite3_uri_parameter(zOpen, "key"))!=0 ){
  134938. sqlite3_key_v2(db, 0, zKey, sqlite3Strlen30(zKey));
  134939. }
  134940. }
  134941. #endif
  134942. sqlite3_free(zOpen);
  134943. return rc & 0xff;
  134944. }
  134945. /*
  134946. ** Open a new database handle.
  134947. */
  134948. SQLITE_API int sqlite3_open(
  134949. const char *zFilename,
  134950. sqlite3 **ppDb
  134951. ){
  134952. return openDatabase(zFilename, ppDb,
  134953. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  134954. }
  134955. SQLITE_API int sqlite3_open_v2(
  134956. const char *filename, /* Database filename (UTF-8) */
  134957. sqlite3 **ppDb, /* OUT: SQLite db handle */
  134958. int flags, /* Flags */
  134959. const char *zVfs /* Name of VFS module to use */
  134960. ){
  134961. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  134962. }
  134963. #ifndef SQLITE_OMIT_UTF16
  134964. /*
  134965. ** Open a new database handle.
  134966. */
  134967. SQLITE_API int sqlite3_open16(
  134968. const void *zFilename,
  134969. sqlite3 **ppDb
  134970. ){
  134971. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  134972. sqlite3_value *pVal;
  134973. int rc;
  134974. #ifdef SQLITE_ENABLE_API_ARMOR
  134975. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  134976. #endif
  134977. *ppDb = 0;
  134978. #ifndef SQLITE_OMIT_AUTOINIT
  134979. rc = sqlite3_initialize();
  134980. if( rc ) return rc;
  134981. #endif
  134982. if( zFilename==0 ) zFilename = "\000\000";
  134983. pVal = sqlite3ValueNew(0);
  134984. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  134985. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  134986. if( zFilename8 ){
  134987. rc = openDatabase(zFilename8, ppDb,
  134988. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  134989. assert( *ppDb || rc==SQLITE_NOMEM );
  134990. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  134991. SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
  134992. }
  134993. }else{
  134994. rc = SQLITE_NOMEM_BKPT;
  134995. }
  134996. sqlite3ValueFree(pVal);
  134997. return rc & 0xff;
  134998. }
  134999. #endif /* SQLITE_OMIT_UTF16 */
  135000. /*
  135001. ** Register a new collation sequence with the database handle db.
  135002. */
  135003. SQLITE_API int sqlite3_create_collation(
  135004. sqlite3* db,
  135005. const char *zName,
  135006. int enc,
  135007. void* pCtx,
  135008. int(*xCompare)(void*,int,const void*,int,const void*)
  135009. ){
  135010. return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
  135011. }
  135012. /*
  135013. ** Register a new collation sequence with the database handle db.
  135014. */
  135015. SQLITE_API int sqlite3_create_collation_v2(
  135016. sqlite3* db,
  135017. const char *zName,
  135018. int enc,
  135019. void* pCtx,
  135020. int(*xCompare)(void*,int,const void*,int,const void*),
  135021. void(*xDel)(void*)
  135022. ){
  135023. int rc;
  135024. #ifdef SQLITE_ENABLE_API_ARMOR
  135025. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  135026. #endif
  135027. sqlite3_mutex_enter(db->mutex);
  135028. assert( !db->mallocFailed );
  135029. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  135030. rc = sqlite3ApiExit(db, rc);
  135031. sqlite3_mutex_leave(db->mutex);
  135032. return rc;
  135033. }
  135034. #ifndef SQLITE_OMIT_UTF16
  135035. /*
  135036. ** Register a new collation sequence with the database handle db.
  135037. */
  135038. SQLITE_API int sqlite3_create_collation16(
  135039. sqlite3* db,
  135040. const void *zName,
  135041. int enc,
  135042. void* pCtx,
  135043. int(*xCompare)(void*,int,const void*,int,const void*)
  135044. ){
  135045. int rc = SQLITE_OK;
  135046. char *zName8;
  135047. #ifdef SQLITE_ENABLE_API_ARMOR
  135048. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  135049. #endif
  135050. sqlite3_mutex_enter(db->mutex);
  135051. assert( !db->mallocFailed );
  135052. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  135053. if( zName8 ){
  135054. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  135055. sqlite3DbFree(db, zName8);
  135056. }
  135057. rc = sqlite3ApiExit(db, rc);
  135058. sqlite3_mutex_leave(db->mutex);
  135059. return rc;
  135060. }
  135061. #endif /* SQLITE_OMIT_UTF16 */
  135062. /*
  135063. ** Register a collation sequence factory callback with the database handle
  135064. ** db. Replace any previously installed collation sequence factory.
  135065. */
  135066. SQLITE_API int sqlite3_collation_needed(
  135067. sqlite3 *db,
  135068. void *pCollNeededArg,
  135069. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  135070. ){
  135071. #ifdef SQLITE_ENABLE_API_ARMOR
  135072. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  135073. #endif
  135074. sqlite3_mutex_enter(db->mutex);
  135075. db->xCollNeeded = xCollNeeded;
  135076. db->xCollNeeded16 = 0;
  135077. db->pCollNeededArg = pCollNeededArg;
  135078. sqlite3_mutex_leave(db->mutex);
  135079. return SQLITE_OK;
  135080. }
  135081. #ifndef SQLITE_OMIT_UTF16
  135082. /*
  135083. ** Register a collation sequence factory callback with the database handle
  135084. ** db. Replace any previously installed collation sequence factory.
  135085. */
  135086. SQLITE_API int sqlite3_collation_needed16(
  135087. sqlite3 *db,
  135088. void *pCollNeededArg,
  135089. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  135090. ){
  135091. #ifdef SQLITE_ENABLE_API_ARMOR
  135092. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  135093. #endif
  135094. sqlite3_mutex_enter(db->mutex);
  135095. db->xCollNeeded = 0;
  135096. db->xCollNeeded16 = xCollNeeded16;
  135097. db->pCollNeededArg = pCollNeededArg;
  135098. sqlite3_mutex_leave(db->mutex);
  135099. return SQLITE_OK;
  135100. }
  135101. #endif /* SQLITE_OMIT_UTF16 */
  135102. #ifndef SQLITE_OMIT_DEPRECATED
  135103. /*
  135104. ** This function is now an anachronism. It used to be used to recover from a
  135105. ** malloc() failure, but SQLite now does this automatically.
  135106. */
  135107. SQLITE_API int sqlite3_global_recover(void){
  135108. return SQLITE_OK;
  135109. }
  135110. #endif
  135111. /*
  135112. ** Test to see whether or not the database connection is in autocommit
  135113. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  135114. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  135115. ** by the next COMMIT or ROLLBACK.
  135116. */
  135117. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  135118. #ifdef SQLITE_ENABLE_API_ARMOR
  135119. if( !sqlite3SafetyCheckOk(db) ){
  135120. (void)SQLITE_MISUSE_BKPT;
  135121. return 0;
  135122. }
  135123. #endif
  135124. return db->autoCommit;
  135125. }
  135126. /*
  135127. ** The following routines are substitutes for constants SQLITE_CORRUPT,
  135128. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
  135129. ** constants. They serve two purposes:
  135130. **
  135131. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  135132. ** to detect when version error conditions occurs.
  135133. **
  135134. ** 2. Invoke sqlite3_log() to provide the source code location where
  135135. ** a low-level error is first detected.
  135136. */
  135137. static int reportError(int iErr, int lineno, const char *zType){
  135138. sqlite3_log(iErr, "%s at line %d of [%.10s]",
  135139. zType, lineno, 20+sqlite3_sourceid());
  135140. return iErr;
  135141. }
  135142. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  135143. testcase( sqlite3GlobalConfig.xLog!=0 );
  135144. return reportError(SQLITE_CORRUPT, lineno, "database corruption");
  135145. }
  135146. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  135147. testcase( sqlite3GlobalConfig.xLog!=0 );
  135148. return reportError(SQLITE_MISUSE, lineno, "misuse");
  135149. }
  135150. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  135151. testcase( sqlite3GlobalConfig.xLog!=0 );
  135152. return reportError(SQLITE_CANTOPEN, lineno, "cannot open file");
  135153. }
  135154. #ifdef SQLITE_DEBUG
  135155. SQLITE_PRIVATE int sqlite3NomemError(int lineno){
  135156. testcase( sqlite3GlobalConfig.xLog!=0 );
  135157. return reportError(SQLITE_NOMEM, lineno, "OOM");
  135158. }
  135159. SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
  135160. testcase( sqlite3GlobalConfig.xLog!=0 );
  135161. return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
  135162. }
  135163. #endif
  135164. #ifndef SQLITE_OMIT_DEPRECATED
  135165. /*
  135166. ** This is a convenience routine that makes sure that all thread-specific
  135167. ** data for this thread has been deallocated.
  135168. **
  135169. ** SQLite no longer uses thread-specific data so this routine is now a
  135170. ** no-op. It is retained for historical compatibility.
  135171. */
  135172. SQLITE_API void sqlite3_thread_cleanup(void){
  135173. }
  135174. #endif
  135175. /*
  135176. ** Return meta information about a specific column of a database table.
  135177. ** See comment in sqlite3.h (sqlite.h.in) for details.
  135178. */
  135179. SQLITE_API int sqlite3_table_column_metadata(
  135180. sqlite3 *db, /* Connection handle */
  135181. const char *zDbName, /* Database name or NULL */
  135182. const char *zTableName, /* Table name */
  135183. const char *zColumnName, /* Column name */
  135184. char const **pzDataType, /* OUTPUT: Declared data type */
  135185. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  135186. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  135187. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  135188. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  135189. ){
  135190. int rc;
  135191. char *zErrMsg = 0;
  135192. Table *pTab = 0;
  135193. Column *pCol = 0;
  135194. int iCol = 0;
  135195. char const *zDataType = 0;
  135196. char const *zCollSeq = 0;
  135197. int notnull = 0;
  135198. int primarykey = 0;
  135199. int autoinc = 0;
  135200. #ifdef SQLITE_ENABLE_API_ARMOR
  135201. if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
  135202. return SQLITE_MISUSE_BKPT;
  135203. }
  135204. #endif
  135205. /* Ensure the database schema has been loaded */
  135206. sqlite3_mutex_enter(db->mutex);
  135207. sqlite3BtreeEnterAll(db);
  135208. rc = sqlite3Init(db, &zErrMsg);
  135209. if( SQLITE_OK!=rc ){
  135210. goto error_out;
  135211. }
  135212. /* Locate the table in question */
  135213. pTab = sqlite3FindTable(db, zTableName, zDbName);
  135214. if( !pTab || pTab->pSelect ){
  135215. pTab = 0;
  135216. goto error_out;
  135217. }
  135218. /* Find the column for which info is requested */
  135219. if( zColumnName==0 ){
  135220. /* Query for existance of table only */
  135221. }else{
  135222. for(iCol=0; iCol<pTab->nCol; iCol++){
  135223. pCol = &pTab->aCol[iCol];
  135224. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  135225. break;
  135226. }
  135227. }
  135228. if( iCol==pTab->nCol ){
  135229. if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
  135230. iCol = pTab->iPKey;
  135231. pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
  135232. }else{
  135233. pTab = 0;
  135234. goto error_out;
  135235. }
  135236. }
  135237. }
  135238. /* The following block stores the meta information that will be returned
  135239. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  135240. ** and autoinc. At this point there are two possibilities:
  135241. **
  135242. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  135243. ** and there is no explicitly declared IPK column.
  135244. **
  135245. ** 2. The table is not a view and the column name identified an
  135246. ** explicitly declared column. Copy meta information from *pCol.
  135247. */
  135248. if( pCol ){
  135249. zDataType = sqlite3ColumnType(pCol,0);
  135250. zCollSeq = pCol->zColl;
  135251. notnull = pCol->notNull!=0;
  135252. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  135253. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  135254. }else{
  135255. zDataType = "INTEGER";
  135256. primarykey = 1;
  135257. }
  135258. if( !zCollSeq ){
  135259. zCollSeq = sqlite3StrBINARY;
  135260. }
  135261. error_out:
  135262. sqlite3BtreeLeaveAll(db);
  135263. /* Whether the function call succeeded or failed, set the output parameters
  135264. ** to whatever their local counterparts contain. If an error did occur,
  135265. ** this has the effect of zeroing all output parameters.
  135266. */
  135267. if( pzDataType ) *pzDataType = zDataType;
  135268. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  135269. if( pNotNull ) *pNotNull = notnull;
  135270. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  135271. if( pAutoinc ) *pAutoinc = autoinc;
  135272. if( SQLITE_OK==rc && !pTab ){
  135273. sqlite3DbFree(db, zErrMsg);
  135274. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  135275. zColumnName);
  135276. rc = SQLITE_ERROR;
  135277. }
  135278. sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
  135279. sqlite3DbFree(db, zErrMsg);
  135280. rc = sqlite3ApiExit(db, rc);
  135281. sqlite3_mutex_leave(db->mutex);
  135282. return rc;
  135283. }
  135284. /*
  135285. ** Sleep for a little while. Return the amount of time slept.
  135286. */
  135287. SQLITE_API int sqlite3_sleep(int ms){
  135288. sqlite3_vfs *pVfs;
  135289. int rc;
  135290. pVfs = sqlite3_vfs_find(0);
  135291. if( pVfs==0 ) return 0;
  135292. /* This function works in milliseconds, but the underlying OsSleep()
  135293. ** API uses microseconds. Hence the 1000's.
  135294. */
  135295. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  135296. return rc;
  135297. }
  135298. /*
  135299. ** Enable or disable the extended result codes.
  135300. */
  135301. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  135302. #ifdef SQLITE_ENABLE_API_ARMOR
  135303. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  135304. #endif
  135305. sqlite3_mutex_enter(db->mutex);
  135306. db->errMask = onoff ? 0xffffffff : 0xff;
  135307. sqlite3_mutex_leave(db->mutex);
  135308. return SQLITE_OK;
  135309. }
  135310. /*
  135311. ** Invoke the xFileControl method on a particular database.
  135312. */
  135313. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  135314. int rc = SQLITE_ERROR;
  135315. Btree *pBtree;
  135316. #ifdef SQLITE_ENABLE_API_ARMOR
  135317. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  135318. #endif
  135319. sqlite3_mutex_enter(db->mutex);
  135320. pBtree = sqlite3DbNameToBtree(db, zDbName);
  135321. if( pBtree ){
  135322. Pager *pPager;
  135323. sqlite3_file *fd;
  135324. sqlite3BtreeEnter(pBtree);
  135325. pPager = sqlite3BtreePager(pBtree);
  135326. assert( pPager!=0 );
  135327. fd = sqlite3PagerFile(pPager);
  135328. assert( fd!=0 );
  135329. if( op==SQLITE_FCNTL_FILE_POINTER ){
  135330. *(sqlite3_file**)pArg = fd;
  135331. rc = SQLITE_OK;
  135332. }else if( op==SQLITE_FCNTL_VFS_POINTER ){
  135333. *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
  135334. rc = SQLITE_OK;
  135335. }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
  135336. *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
  135337. rc = SQLITE_OK;
  135338. }else if( fd->pMethods ){
  135339. rc = sqlite3OsFileControl(fd, op, pArg);
  135340. }else{
  135341. rc = SQLITE_NOTFOUND;
  135342. }
  135343. sqlite3BtreeLeave(pBtree);
  135344. }
  135345. sqlite3_mutex_leave(db->mutex);
  135346. return rc;
  135347. }
  135348. /*
  135349. ** Interface to the testing logic.
  135350. */
  135351. SQLITE_API int sqlite3_test_control(int op, ...){
  135352. int rc = 0;
  135353. #ifdef SQLITE_UNTESTABLE
  135354. UNUSED_PARAMETER(op);
  135355. #else
  135356. va_list ap;
  135357. va_start(ap, op);
  135358. switch( op ){
  135359. /*
  135360. ** Save the current state of the PRNG.
  135361. */
  135362. case SQLITE_TESTCTRL_PRNG_SAVE: {
  135363. sqlite3PrngSaveState();
  135364. break;
  135365. }
  135366. /*
  135367. ** Restore the state of the PRNG to the last state saved using
  135368. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  135369. ** this verb acts like PRNG_RESET.
  135370. */
  135371. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  135372. sqlite3PrngRestoreState();
  135373. break;
  135374. }
  135375. /*
  135376. ** Reset the PRNG back to its uninitialized state. The next call
  135377. ** to sqlite3_randomness() will reseed the PRNG using a single call
  135378. ** to the xRandomness method of the default VFS.
  135379. */
  135380. case SQLITE_TESTCTRL_PRNG_RESET: {
  135381. sqlite3_randomness(0,0);
  135382. break;
  135383. }
  135384. /*
  135385. ** sqlite3_test_control(BITVEC_TEST, size, program)
  135386. **
  135387. ** Run a test against a Bitvec object of size. The program argument
  135388. ** is an array of integers that defines the test. Return -1 on a
  135389. ** memory allocation error, 0 on success, or non-zero for an error.
  135390. ** See the sqlite3BitvecBuiltinTest() for additional information.
  135391. */
  135392. case SQLITE_TESTCTRL_BITVEC_TEST: {
  135393. int sz = va_arg(ap, int);
  135394. int *aProg = va_arg(ap, int*);
  135395. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  135396. break;
  135397. }
  135398. /*
  135399. ** sqlite3_test_control(FAULT_INSTALL, xCallback)
  135400. **
  135401. ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
  135402. ** if xCallback is not NULL.
  135403. **
  135404. ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
  135405. ** is called immediately after installing the new callback and the return
  135406. ** value from sqlite3FaultSim(0) becomes the return from
  135407. ** sqlite3_test_control().
  135408. */
  135409. case SQLITE_TESTCTRL_FAULT_INSTALL: {
  135410. /* MSVC is picky about pulling func ptrs from va lists.
  135411. ** http://support.microsoft.com/kb/47961
  135412. ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
  135413. */
  135414. typedef int(*TESTCALLBACKFUNC_t)(int);
  135415. sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
  135416. rc = sqlite3FaultSim(0);
  135417. break;
  135418. }
  135419. /*
  135420. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  135421. **
  135422. ** Register hooks to call to indicate which malloc() failures
  135423. ** are benign.
  135424. */
  135425. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  135426. typedef void (*void_function)(void);
  135427. void_function xBenignBegin;
  135428. void_function xBenignEnd;
  135429. xBenignBegin = va_arg(ap, void_function);
  135430. xBenignEnd = va_arg(ap, void_function);
  135431. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  135432. break;
  135433. }
  135434. /*
  135435. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  135436. **
  135437. ** Set the PENDING byte to the value in the argument, if X>0.
  135438. ** Make no changes if X==0. Return the value of the pending byte
  135439. ** as it existing before this routine was called.
  135440. **
  135441. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  135442. ** an incompatible database file format. Changing the PENDING byte
  135443. ** while any database connection is open results in undefined and
  135444. ** deleterious behavior.
  135445. */
  135446. case SQLITE_TESTCTRL_PENDING_BYTE: {
  135447. rc = PENDING_BYTE;
  135448. #ifndef SQLITE_OMIT_WSD
  135449. {
  135450. unsigned int newVal = va_arg(ap, unsigned int);
  135451. if( newVal ) sqlite3PendingByte = newVal;
  135452. }
  135453. #endif
  135454. break;
  135455. }
  135456. /*
  135457. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  135458. **
  135459. ** This action provides a run-time test to see whether or not
  135460. ** assert() was enabled at compile-time. If X is true and assert()
  135461. ** is enabled, then the return value is true. If X is true and
  135462. ** assert() is disabled, then the return value is zero. If X is
  135463. ** false and assert() is enabled, then the assertion fires and the
  135464. ** process aborts. If X is false and assert() is disabled, then the
  135465. ** return value is zero.
  135466. */
  135467. case SQLITE_TESTCTRL_ASSERT: {
  135468. volatile int x = 0;
  135469. assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
  135470. rc = x;
  135471. break;
  135472. }
  135473. /*
  135474. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  135475. **
  135476. ** This action provides a run-time test to see how the ALWAYS and
  135477. ** NEVER macros were defined at compile-time.
  135478. **
  135479. ** The return value is ALWAYS(X).
  135480. **
  135481. ** The recommended test is X==2. If the return value is 2, that means
  135482. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  135483. ** default setting. If the return value is 1, then ALWAYS() is either
  135484. ** hard-coded to true or else it asserts if its argument is false.
  135485. ** The first behavior (hard-coded to true) is the case if
  135486. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  135487. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  135488. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  135489. **
  135490. ** The run-time test procedure might look something like this:
  135491. **
  135492. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  135493. ** // ALWAYS() and NEVER() are no-op pass-through macros
  135494. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  135495. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  135496. ** }else{
  135497. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  135498. ** }
  135499. */
  135500. case SQLITE_TESTCTRL_ALWAYS: {
  135501. int x = va_arg(ap,int);
  135502. rc = ALWAYS(x);
  135503. break;
  135504. }
  135505. /*
  135506. ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
  135507. **
  135508. ** The integer returned reveals the byte-order of the computer on which
  135509. ** SQLite is running:
  135510. **
  135511. ** 1 big-endian, determined at run-time
  135512. ** 10 little-endian, determined at run-time
  135513. ** 432101 big-endian, determined at compile-time
  135514. ** 123410 little-endian, determined at compile-time
  135515. */
  135516. case SQLITE_TESTCTRL_BYTEORDER: {
  135517. rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
  135518. break;
  135519. }
  135520. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  135521. **
  135522. ** Set the nReserve size to N for the main database on the database
  135523. ** connection db.
  135524. */
  135525. case SQLITE_TESTCTRL_RESERVE: {
  135526. sqlite3 *db = va_arg(ap, sqlite3*);
  135527. int x = va_arg(ap,int);
  135528. sqlite3_mutex_enter(db->mutex);
  135529. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  135530. sqlite3_mutex_leave(db->mutex);
  135531. break;
  135532. }
  135533. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  135534. **
  135535. ** Enable or disable various optimizations for testing purposes. The
  135536. ** argument N is a bitmask of optimizations to be disabled. For normal
  135537. ** operation N should be 0. The idea is that a test program (like the
  135538. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  135539. ** with various optimizations disabled to verify that the same answer
  135540. ** is obtained in every case.
  135541. */
  135542. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  135543. sqlite3 *db = va_arg(ap, sqlite3*);
  135544. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  135545. break;
  135546. }
  135547. #ifdef SQLITE_N_KEYWORD
  135548. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  135549. **
  135550. ** If zWord is a keyword recognized by the parser, then return the
  135551. ** number of keywords. Or if zWord is not a keyword, return 0.
  135552. **
  135553. ** This test feature is only available in the amalgamation since
  135554. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  135555. ** is built using separate source files.
  135556. */
  135557. case SQLITE_TESTCTRL_ISKEYWORD: {
  135558. const char *zWord = va_arg(ap, const char*);
  135559. int n = sqlite3Strlen30(zWord);
  135560. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  135561. break;
  135562. }
  135563. #endif
  135564. /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  135565. **
  135566. ** Pass pFree into sqlite3ScratchFree().
  135567. ** If sz>0 then allocate a scratch buffer into pNew.
  135568. */
  135569. case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  135570. void *pFree, **ppNew;
  135571. int sz;
  135572. sz = va_arg(ap, int);
  135573. ppNew = va_arg(ap, void**);
  135574. pFree = va_arg(ap, void*);
  135575. if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
  135576. sqlite3ScratchFree(pFree);
  135577. break;
  135578. }
  135579. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  135580. **
  135581. ** If parameter onoff is non-zero, configure the wrappers so that all
  135582. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  135583. ** undo this setting.
  135584. */
  135585. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  135586. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  135587. break;
  135588. }
  135589. /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
  135590. **
  135591. ** Set or clear a flag that indicates that the database file is always well-
  135592. ** formed and never corrupt. This flag is clear by default, indicating that
  135593. ** database files might have arbitrary corruption. Setting the flag during
  135594. ** testing causes certain assert() statements in the code to be activated
  135595. ** that demonstrat invariants on well-formed database files.
  135596. */
  135597. case SQLITE_TESTCTRL_NEVER_CORRUPT: {
  135598. sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
  135599. break;
  135600. }
  135601. /* Set the threshold at which OP_Once counters reset back to zero.
  135602. ** By default this is 0x7ffffffe (over 2 billion), but that value is
  135603. ** too big to test in a reasonable amount of time, so this control is
  135604. ** provided to set a small and easily reachable reset value.
  135605. */
  135606. case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
  135607. sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
  135608. break;
  135609. }
  135610. /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
  135611. **
  135612. ** Set the VDBE coverage callback function to xCallback with context
  135613. ** pointer ptr.
  135614. */
  135615. case SQLITE_TESTCTRL_VDBE_COVERAGE: {
  135616. #ifdef SQLITE_VDBE_COVERAGE
  135617. typedef void (*branch_callback)(void*,int,u8,u8);
  135618. sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
  135619. sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
  135620. #endif
  135621. break;
  135622. }
  135623. /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
  135624. case SQLITE_TESTCTRL_SORTER_MMAP: {
  135625. sqlite3 *db = va_arg(ap, sqlite3*);
  135626. db->nMaxSorterMmap = va_arg(ap, int);
  135627. break;
  135628. }
  135629. /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
  135630. **
  135631. ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
  135632. ** not.
  135633. */
  135634. case SQLITE_TESTCTRL_ISINIT: {
  135635. if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
  135636. break;
  135637. }
  135638. /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
  135639. **
  135640. ** This test control is used to create imposter tables. "db" is a pointer
  135641. ** to the database connection. dbName is the database name (ex: "main" or
  135642. ** "temp") which will receive the imposter. "onOff" turns imposter mode on
  135643. ** or off. "tnum" is the root page of the b-tree to which the imposter
  135644. ** table should connect.
  135645. **
  135646. ** Enable imposter mode only when the schema has already been parsed. Then
  135647. ** run a single CREATE TABLE statement to construct the imposter table in
  135648. ** the parsed schema. Then turn imposter mode back off again.
  135649. **
  135650. ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
  135651. ** the schema to be reparsed the next time it is needed. This has the
  135652. ** effect of erasing all imposter tables.
  135653. */
  135654. case SQLITE_TESTCTRL_IMPOSTER: {
  135655. sqlite3 *db = va_arg(ap, sqlite3*);
  135656. sqlite3_mutex_enter(db->mutex);
  135657. db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
  135658. db->init.busy = db->init.imposterTable = va_arg(ap,int);
  135659. db->init.newTnum = va_arg(ap,int);
  135660. if( db->init.busy==0 && db->init.newTnum>0 ){
  135661. sqlite3ResetAllSchemasOfConnection(db);
  135662. }
  135663. sqlite3_mutex_leave(db->mutex);
  135664. break;
  135665. }
  135666. }
  135667. va_end(ap);
  135668. #endif /* SQLITE_UNTESTABLE */
  135669. return rc;
  135670. }
  135671. /*
  135672. ** This is a utility routine, useful to VFS implementations, that checks
  135673. ** to see if a database file was a URI that contained a specific query
  135674. ** parameter, and if so obtains the value of the query parameter.
  135675. **
  135676. ** The zFilename argument is the filename pointer passed into the xOpen()
  135677. ** method of a VFS implementation. The zParam argument is the name of the
  135678. ** query parameter we seek. This routine returns the value of the zParam
  135679. ** parameter if it exists. If the parameter does not exist, this routine
  135680. ** returns a NULL pointer.
  135681. */
  135682. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  135683. if( zFilename==0 || zParam==0 ) return 0;
  135684. zFilename += sqlite3Strlen30(zFilename) + 1;
  135685. while( zFilename[0] ){
  135686. int x = strcmp(zFilename, zParam);
  135687. zFilename += sqlite3Strlen30(zFilename) + 1;
  135688. if( x==0 ) return zFilename;
  135689. zFilename += sqlite3Strlen30(zFilename) + 1;
  135690. }
  135691. return 0;
  135692. }
  135693. /*
  135694. ** Return a boolean value for a query parameter.
  135695. */
  135696. SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  135697. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  135698. bDflt = bDflt!=0;
  135699. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  135700. }
  135701. /*
  135702. ** Return a 64-bit integer value for a query parameter.
  135703. */
  135704. SQLITE_API sqlite3_int64 sqlite3_uri_int64(
  135705. const char *zFilename, /* Filename as passed to xOpen */
  135706. const char *zParam, /* URI parameter sought */
  135707. sqlite3_int64 bDflt /* return if parameter is missing */
  135708. ){
  135709. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  135710. sqlite3_int64 v;
  135711. if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
  135712. bDflt = v;
  135713. }
  135714. return bDflt;
  135715. }
  135716. /*
  135717. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  135718. */
  135719. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  135720. int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
  135721. return iDb<0 ? 0 : db->aDb[iDb].pBt;
  135722. }
  135723. /*
  135724. ** Return the filename of the database associated with a database
  135725. ** connection.
  135726. */
  135727. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  135728. Btree *pBt;
  135729. #ifdef SQLITE_ENABLE_API_ARMOR
  135730. if( !sqlite3SafetyCheckOk(db) ){
  135731. (void)SQLITE_MISUSE_BKPT;
  135732. return 0;
  135733. }
  135734. #endif
  135735. pBt = sqlite3DbNameToBtree(db, zDbName);
  135736. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  135737. }
  135738. /*
  135739. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  135740. ** no such database exists.
  135741. */
  135742. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  135743. Btree *pBt;
  135744. #ifdef SQLITE_ENABLE_API_ARMOR
  135745. if( !sqlite3SafetyCheckOk(db) ){
  135746. (void)SQLITE_MISUSE_BKPT;
  135747. return -1;
  135748. }
  135749. #endif
  135750. pBt = sqlite3DbNameToBtree(db, zDbName);
  135751. return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
  135752. }
  135753. #ifdef SQLITE_ENABLE_SNAPSHOT
  135754. /*
  135755. ** Obtain a snapshot handle for the snapshot of database zDb currently
  135756. ** being read by handle db.
  135757. */
  135758. SQLITE_API int sqlite3_snapshot_get(
  135759. sqlite3 *db,
  135760. const char *zDb,
  135761. sqlite3_snapshot **ppSnapshot
  135762. ){
  135763. int rc = SQLITE_ERROR;
  135764. #ifndef SQLITE_OMIT_WAL
  135765. #ifdef SQLITE_ENABLE_API_ARMOR
  135766. if( !sqlite3SafetyCheckOk(db) ){
  135767. return SQLITE_MISUSE_BKPT;
  135768. }
  135769. #endif
  135770. sqlite3_mutex_enter(db->mutex);
  135771. if( db->autoCommit==0 ){
  135772. int iDb = sqlite3FindDbName(db, zDb);
  135773. if( iDb==0 || iDb>1 ){
  135774. Btree *pBt = db->aDb[iDb].pBt;
  135775. if( 0==sqlite3BtreeIsInTrans(pBt) ){
  135776. rc = sqlite3BtreeBeginTrans(pBt, 0);
  135777. if( rc==SQLITE_OK ){
  135778. rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
  135779. }
  135780. }
  135781. }
  135782. }
  135783. sqlite3_mutex_leave(db->mutex);
  135784. #endif /* SQLITE_OMIT_WAL */
  135785. return rc;
  135786. }
  135787. /*
  135788. ** Open a read-transaction on the snapshot idendified by pSnapshot.
  135789. */
  135790. SQLITE_API int sqlite3_snapshot_open(
  135791. sqlite3 *db,
  135792. const char *zDb,
  135793. sqlite3_snapshot *pSnapshot
  135794. ){
  135795. int rc = SQLITE_ERROR;
  135796. #ifndef SQLITE_OMIT_WAL
  135797. #ifdef SQLITE_ENABLE_API_ARMOR
  135798. if( !sqlite3SafetyCheckOk(db) ){
  135799. return SQLITE_MISUSE_BKPT;
  135800. }
  135801. #endif
  135802. sqlite3_mutex_enter(db->mutex);
  135803. if( db->autoCommit==0 ){
  135804. int iDb;
  135805. iDb = sqlite3FindDbName(db, zDb);
  135806. if( iDb==0 || iDb>1 ){
  135807. Btree *pBt = db->aDb[iDb].pBt;
  135808. if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
  135809. rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
  135810. if( rc==SQLITE_OK ){
  135811. rc = sqlite3BtreeBeginTrans(pBt, 0);
  135812. sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
  135813. }
  135814. }
  135815. }
  135816. }
  135817. sqlite3_mutex_leave(db->mutex);
  135818. #endif /* SQLITE_OMIT_WAL */
  135819. return rc;
  135820. }
  135821. /*
  135822. ** Recover as many snapshots as possible from the wal file associated with
  135823. ** schema zDb of database db.
  135824. */
  135825. SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
  135826. int rc = SQLITE_ERROR;
  135827. int iDb;
  135828. #ifndef SQLITE_OMIT_WAL
  135829. #ifdef SQLITE_ENABLE_API_ARMOR
  135830. if( !sqlite3SafetyCheckOk(db) ){
  135831. return SQLITE_MISUSE_BKPT;
  135832. }
  135833. #endif
  135834. sqlite3_mutex_enter(db->mutex);
  135835. iDb = sqlite3FindDbName(db, zDb);
  135836. if( iDb==0 || iDb>1 ){
  135837. Btree *pBt = db->aDb[iDb].pBt;
  135838. if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
  135839. rc = sqlite3BtreeBeginTrans(pBt, 0);
  135840. if( rc==SQLITE_OK ){
  135841. rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
  135842. sqlite3BtreeCommit(pBt);
  135843. }
  135844. }
  135845. }
  135846. sqlite3_mutex_leave(db->mutex);
  135847. #endif /* SQLITE_OMIT_WAL */
  135848. return rc;
  135849. }
  135850. /*
  135851. ** Free a snapshot handle obtained from sqlite3_snapshot_get().
  135852. */
  135853. SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
  135854. sqlite3_free(pSnapshot);
  135855. }
  135856. #endif /* SQLITE_ENABLE_SNAPSHOT */
  135857. /************** End of main.c ************************************************/
  135858. /************** Begin file notify.c ******************************************/
  135859. /*
  135860. ** 2009 March 3
  135861. **
  135862. ** The author disclaims copyright to this source code. In place of
  135863. ** a legal notice, here is a blessing:
  135864. **
  135865. ** May you do good and not evil.
  135866. ** May you find forgiveness for yourself and forgive others.
  135867. ** May you share freely, never taking more than you give.
  135868. **
  135869. *************************************************************************
  135870. **
  135871. ** This file contains the implementation of the sqlite3_unlock_notify()
  135872. ** API method and its associated functionality.
  135873. */
  135874. /* #include "sqliteInt.h" */
  135875. /* #include "btreeInt.h" */
  135876. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  135877. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  135878. /*
  135879. ** Public interfaces:
  135880. **
  135881. ** sqlite3ConnectionBlocked()
  135882. ** sqlite3ConnectionUnlocked()
  135883. ** sqlite3ConnectionClosed()
  135884. ** sqlite3_unlock_notify()
  135885. */
  135886. #define assertMutexHeld() \
  135887. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  135888. /*
  135889. ** Head of a linked list of all sqlite3 objects created by this process
  135890. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  135891. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  135892. ** mutex is held.
  135893. */
  135894. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  135895. #ifndef NDEBUG
  135896. /*
  135897. ** This function is a complex assert() that verifies the following
  135898. ** properties of the blocked connections list:
  135899. **
  135900. ** 1) Each entry in the list has a non-NULL value for either
  135901. ** pUnlockConnection or pBlockingConnection, or both.
  135902. **
  135903. ** 2) All entries in the list that share a common value for
  135904. ** xUnlockNotify are grouped together.
  135905. **
  135906. ** 3) If the argument db is not NULL, then none of the entries in the
  135907. ** blocked connections list have pUnlockConnection or pBlockingConnection
  135908. ** set to db. This is used when closing connection db.
  135909. */
  135910. static void checkListProperties(sqlite3 *db){
  135911. sqlite3 *p;
  135912. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  135913. int seen = 0;
  135914. sqlite3 *p2;
  135915. /* Verify property (1) */
  135916. assert( p->pUnlockConnection || p->pBlockingConnection );
  135917. /* Verify property (2) */
  135918. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  135919. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  135920. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  135921. assert( db==0 || p->pUnlockConnection!=db );
  135922. assert( db==0 || p->pBlockingConnection!=db );
  135923. }
  135924. }
  135925. }
  135926. #else
  135927. # define checkListProperties(x)
  135928. #endif
  135929. /*
  135930. ** Remove connection db from the blocked connections list. If connection
  135931. ** db is not currently a part of the list, this function is a no-op.
  135932. */
  135933. static void removeFromBlockedList(sqlite3 *db){
  135934. sqlite3 **pp;
  135935. assertMutexHeld();
  135936. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  135937. if( *pp==db ){
  135938. *pp = (*pp)->pNextBlocked;
  135939. break;
  135940. }
  135941. }
  135942. }
  135943. /*
  135944. ** Add connection db to the blocked connections list. It is assumed
  135945. ** that it is not already a part of the list.
  135946. */
  135947. static void addToBlockedList(sqlite3 *db){
  135948. sqlite3 **pp;
  135949. assertMutexHeld();
  135950. for(
  135951. pp=&sqlite3BlockedList;
  135952. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  135953. pp=&(*pp)->pNextBlocked
  135954. );
  135955. db->pNextBlocked = *pp;
  135956. *pp = db;
  135957. }
  135958. /*
  135959. ** Obtain the STATIC_MASTER mutex.
  135960. */
  135961. static void enterMutex(void){
  135962. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  135963. checkListProperties(0);
  135964. }
  135965. /*
  135966. ** Release the STATIC_MASTER mutex.
  135967. */
  135968. static void leaveMutex(void){
  135969. assertMutexHeld();
  135970. checkListProperties(0);
  135971. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  135972. }
  135973. /*
  135974. ** Register an unlock-notify callback.
  135975. **
  135976. ** This is called after connection "db" has attempted some operation
  135977. ** but has received an SQLITE_LOCKED error because another connection
  135978. ** (call it pOther) in the same process was busy using the same shared
  135979. ** cache. pOther is found by looking at db->pBlockingConnection.
  135980. **
  135981. ** If there is no blocking connection, the callback is invoked immediately,
  135982. ** before this routine returns.
  135983. **
  135984. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  135985. ** a deadlock.
  135986. **
  135987. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  135988. ** its locks.
  135989. **
  135990. ** Each call to this routine overrides any prior callbacks registered
  135991. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  135992. ** cancelled.
  135993. */
  135994. SQLITE_API int sqlite3_unlock_notify(
  135995. sqlite3 *db,
  135996. void (*xNotify)(void **, int),
  135997. void *pArg
  135998. ){
  135999. int rc = SQLITE_OK;
  136000. sqlite3_mutex_enter(db->mutex);
  136001. enterMutex();
  136002. if( xNotify==0 ){
  136003. removeFromBlockedList(db);
  136004. db->pBlockingConnection = 0;
  136005. db->pUnlockConnection = 0;
  136006. db->xUnlockNotify = 0;
  136007. db->pUnlockArg = 0;
  136008. }else if( 0==db->pBlockingConnection ){
  136009. /* The blocking transaction has been concluded. Or there never was a
  136010. ** blocking transaction. In either case, invoke the notify callback
  136011. ** immediately.
  136012. */
  136013. xNotify(&pArg, 1);
  136014. }else{
  136015. sqlite3 *p;
  136016. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  136017. if( p ){
  136018. rc = SQLITE_LOCKED; /* Deadlock detected. */
  136019. }else{
  136020. db->pUnlockConnection = db->pBlockingConnection;
  136021. db->xUnlockNotify = xNotify;
  136022. db->pUnlockArg = pArg;
  136023. removeFromBlockedList(db);
  136024. addToBlockedList(db);
  136025. }
  136026. }
  136027. leaveMutex();
  136028. assert( !db->mallocFailed );
  136029. sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
  136030. sqlite3_mutex_leave(db->mutex);
  136031. return rc;
  136032. }
  136033. /*
  136034. ** This function is called while stepping or preparing a statement
  136035. ** associated with connection db. The operation will return SQLITE_LOCKED
  136036. ** to the user because it requires a lock that will not be available
  136037. ** until connection pBlocker concludes its current transaction.
  136038. */
  136039. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  136040. enterMutex();
  136041. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  136042. addToBlockedList(db);
  136043. }
  136044. db->pBlockingConnection = pBlocker;
  136045. leaveMutex();
  136046. }
  136047. /*
  136048. ** This function is called when
  136049. ** the transaction opened by database db has just finished. Locks held
  136050. ** by database connection db have been released.
  136051. **
  136052. ** This function loops through each entry in the blocked connections
  136053. ** list and does the following:
  136054. **
  136055. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  136056. ** set to db, then set pBlockingConnection=0.
  136057. **
  136058. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  136059. ** set to db, then invoke the configured unlock-notify callback and
  136060. ** set pUnlockConnection=0.
  136061. **
  136062. ** 3) If the two steps above mean that pBlockingConnection==0 and
  136063. ** pUnlockConnection==0, remove the entry from the blocked connections
  136064. ** list.
  136065. */
  136066. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  136067. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  136068. int nArg = 0; /* Number of entries in aArg[] */
  136069. sqlite3 **pp; /* Iterator variable */
  136070. void **aArg; /* Arguments to the unlock callback */
  136071. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  136072. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  136073. aArg = aStatic;
  136074. enterMutex(); /* Enter STATIC_MASTER mutex */
  136075. /* This loop runs once for each entry in the blocked-connections list. */
  136076. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  136077. sqlite3 *p = *pp;
  136078. /* Step 1. */
  136079. if( p->pBlockingConnection==db ){
  136080. p->pBlockingConnection = 0;
  136081. }
  136082. /* Step 2. */
  136083. if( p->pUnlockConnection==db ){
  136084. assert( p->xUnlockNotify );
  136085. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  136086. xUnlockNotify(aArg, nArg);
  136087. nArg = 0;
  136088. }
  136089. sqlite3BeginBenignMalloc();
  136090. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  136091. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  136092. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  136093. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  136094. ){
  136095. /* The aArg[] array needs to grow. */
  136096. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  136097. if( pNew ){
  136098. memcpy(pNew, aArg, nArg*sizeof(void *));
  136099. sqlite3_free(aDyn);
  136100. aDyn = aArg = pNew;
  136101. }else{
  136102. /* This occurs when the array of context pointers that need to
  136103. ** be passed to the unlock-notify callback is larger than the
  136104. ** aStatic[] array allocated on the stack and the attempt to
  136105. ** allocate a larger array from the heap has failed.
  136106. **
  136107. ** This is a difficult situation to handle. Returning an error
  136108. ** code to the caller is insufficient, as even if an error code
  136109. ** is returned the transaction on connection db will still be
  136110. ** closed and the unlock-notify callbacks on blocked connections
  136111. ** will go unissued. This might cause the application to wait
  136112. ** indefinitely for an unlock-notify callback that will never
  136113. ** arrive.
  136114. **
  136115. ** Instead, invoke the unlock-notify callback with the context
  136116. ** array already accumulated. We can then clear the array and
  136117. ** begin accumulating any further context pointers without
  136118. ** requiring any dynamic allocation. This is sub-optimal because
  136119. ** it means that instead of one callback with a large array of
  136120. ** context pointers the application will receive two or more
  136121. ** callbacks with smaller arrays of context pointers, which will
  136122. ** reduce the applications ability to prioritize multiple
  136123. ** connections. But it is the best that can be done under the
  136124. ** circumstances.
  136125. */
  136126. xUnlockNotify(aArg, nArg);
  136127. nArg = 0;
  136128. }
  136129. }
  136130. sqlite3EndBenignMalloc();
  136131. aArg[nArg++] = p->pUnlockArg;
  136132. xUnlockNotify = p->xUnlockNotify;
  136133. p->pUnlockConnection = 0;
  136134. p->xUnlockNotify = 0;
  136135. p->pUnlockArg = 0;
  136136. }
  136137. /* Step 3. */
  136138. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  136139. /* Remove connection p from the blocked connections list. */
  136140. *pp = p->pNextBlocked;
  136141. p->pNextBlocked = 0;
  136142. }else{
  136143. pp = &p->pNextBlocked;
  136144. }
  136145. }
  136146. if( nArg!=0 ){
  136147. xUnlockNotify(aArg, nArg);
  136148. }
  136149. sqlite3_free(aDyn);
  136150. leaveMutex(); /* Leave STATIC_MASTER mutex */
  136151. }
  136152. /*
  136153. ** This is called when the database connection passed as an argument is
  136154. ** being closed. The connection is removed from the blocked list.
  136155. */
  136156. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  136157. sqlite3ConnectionUnlocked(db);
  136158. enterMutex();
  136159. removeFromBlockedList(db);
  136160. checkListProperties(db);
  136161. leaveMutex();
  136162. }
  136163. #endif
  136164. /************** End of notify.c **********************************************/
  136165. /************** Begin file fts3.c ********************************************/
  136166. /*
  136167. ** 2006 Oct 10
  136168. **
  136169. ** The author disclaims copyright to this source code. In place of
  136170. ** a legal notice, here is a blessing:
  136171. **
  136172. ** May you do good and not evil.
  136173. ** May you find forgiveness for yourself and forgive others.
  136174. ** May you share freely, never taking more than you give.
  136175. **
  136176. ******************************************************************************
  136177. **
  136178. ** This is an SQLite module implementing full-text search.
  136179. */
  136180. /*
  136181. ** The code in this file is only compiled if:
  136182. **
  136183. ** * The FTS3 module is being built as an extension
  136184. ** (in which case SQLITE_CORE is not defined), or
  136185. **
  136186. ** * The FTS3 module is being built into the core of
  136187. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  136188. */
  136189. /* The full-text index is stored in a series of b+tree (-like)
  136190. ** structures called segments which map terms to doclists. The
  136191. ** structures are like b+trees in layout, but are constructed from the
  136192. ** bottom up in optimal fashion and are not updatable. Since trees
  136193. ** are built from the bottom up, things will be described from the
  136194. ** bottom up.
  136195. **
  136196. **
  136197. **** Varints ****
  136198. ** The basic unit of encoding is a variable-length integer called a
  136199. ** varint. We encode variable-length integers in little-endian order
  136200. ** using seven bits * per byte as follows:
  136201. **
  136202. ** KEY:
  136203. ** A = 0xxxxxxx 7 bits of data and one flag bit
  136204. ** B = 1xxxxxxx 7 bits of data and one flag bit
  136205. **
  136206. ** 7 bits - A
  136207. ** 14 bits - BA
  136208. ** 21 bits - BBA
  136209. ** and so on.
  136210. **
  136211. ** This is similar in concept to how sqlite encodes "varints" but
  136212. ** the encoding is not the same. SQLite varints are big-endian
  136213. ** are are limited to 9 bytes in length whereas FTS3 varints are
  136214. ** little-endian and can be up to 10 bytes in length (in theory).
  136215. **
  136216. ** Example encodings:
  136217. **
  136218. ** 1: 0x01
  136219. ** 127: 0x7f
  136220. ** 128: 0x81 0x00
  136221. **
  136222. **
  136223. **** Document lists ****
  136224. ** A doclist (document list) holds a docid-sorted list of hits for a
  136225. ** given term. Doclists hold docids and associated token positions.
  136226. ** A docid is the unique integer identifier for a single document.
  136227. ** A position is the index of a word within the document. The first
  136228. ** word of the document has a position of 0.
  136229. **
  136230. ** FTS3 used to optionally store character offsets using a compile-time
  136231. ** option. But that functionality is no longer supported.
  136232. **
  136233. ** A doclist is stored like this:
  136234. **
  136235. ** array {
  136236. ** varint docid; (delta from previous doclist)
  136237. ** array { (position list for column 0)
  136238. ** varint position; (2 more than the delta from previous position)
  136239. ** }
  136240. ** array {
  136241. ** varint POS_COLUMN; (marks start of position list for new column)
  136242. ** varint column; (index of new column)
  136243. ** array {
  136244. ** varint position; (2 more than the delta from previous position)
  136245. ** }
  136246. ** }
  136247. ** varint POS_END; (marks end of positions for this document.
  136248. ** }
  136249. **
  136250. ** Here, array { X } means zero or more occurrences of X, adjacent in
  136251. ** memory. A "position" is an index of a token in the token stream
  136252. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  136253. ** in the same logical place as the position element, and act as sentinals
  136254. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  136255. ** The positions numbers are not stored literally but rather as two more
  136256. ** than the difference from the prior position, or the just the position plus
  136257. ** 2 for the first position. Example:
  136258. **
  136259. ** label: A B C D E F G H I J K
  136260. ** value: 123 5 9 1 1 14 35 0 234 72 0
  136261. **
  136262. ** The 123 value is the first docid. For column zero in this document
  136263. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  136264. ** at D signals the start of a new column; the 1 at E indicates that the
  136265. ** new column is column number 1. There are two positions at 12 and 45
  136266. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  136267. ** 234 at I is the delta to next docid (357). It has one position 70
  136268. ** (72-2) and then terminates with the 0 at K.
  136269. **
  136270. ** A "position-list" is the list of positions for multiple columns for
  136271. ** a single docid. A "column-list" is the set of positions for a single
  136272. ** column. Hence, a position-list consists of one or more column-lists,
  136273. ** a document record consists of a docid followed by a position-list and
  136274. ** a doclist consists of one or more document records.
  136275. **
  136276. ** A bare doclist omits the position information, becoming an
  136277. ** array of varint-encoded docids.
  136278. **
  136279. **** Segment leaf nodes ****
  136280. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  136281. ** nodes are written using LeafWriter, and read using LeafReader (to
  136282. ** iterate through a single leaf node's data) and LeavesReader (to
  136283. ** iterate through a segment's entire leaf layer). Leaf nodes have
  136284. ** the format:
  136285. **
  136286. ** varint iHeight; (height from leaf level, always 0)
  136287. ** varint nTerm; (length of first term)
  136288. ** char pTerm[nTerm]; (content of first term)
  136289. ** varint nDoclist; (length of term's associated doclist)
  136290. ** char pDoclist[nDoclist]; (content of doclist)
  136291. ** array {
  136292. ** (further terms are delta-encoded)
  136293. ** varint nPrefix; (length of prefix shared with previous term)
  136294. ** varint nSuffix; (length of unshared suffix)
  136295. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  136296. ** varint nDoclist; (length of term's associated doclist)
  136297. ** char pDoclist[nDoclist]; (content of doclist)
  136298. ** }
  136299. **
  136300. ** Here, array { X } means zero or more occurrences of X, adjacent in
  136301. ** memory.
  136302. **
  136303. ** Leaf nodes are broken into blocks which are stored contiguously in
  136304. ** the %_segments table in sorted order. This means that when the end
  136305. ** of a node is reached, the next term is in the node with the next
  136306. ** greater node id.
  136307. **
  136308. ** New data is spilled to a new leaf node when the current node
  136309. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  136310. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  136311. ** node (a leaf node with a single term and doclist). The goal of
  136312. ** these settings is to pack together groups of small doclists while
  136313. ** making it efficient to directly access large doclists. The
  136314. ** assumption is that large doclists represent terms which are more
  136315. ** likely to be query targets.
  136316. **
  136317. ** TODO(shess) It may be useful for blocking decisions to be more
  136318. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  136319. ** node rather than splitting into 2k and .5k nodes. My intuition is
  136320. ** that this might extend through 2x or 4x the pagesize.
  136321. **
  136322. **
  136323. **** Segment interior nodes ****
  136324. ** Segment interior nodes store blockids for subtree nodes and terms
  136325. ** to describe what data is stored by the each subtree. Interior
  136326. ** nodes are written using InteriorWriter, and read using
  136327. ** InteriorReader. InteriorWriters are created as needed when
  136328. ** SegmentWriter creates new leaf nodes, or when an interior node
  136329. ** itself grows too big and must be split. The format of interior
  136330. ** nodes:
  136331. **
  136332. ** varint iHeight; (height from leaf level, always >0)
  136333. ** varint iBlockid; (block id of node's leftmost subtree)
  136334. ** optional {
  136335. ** varint nTerm; (length of first term)
  136336. ** char pTerm[nTerm]; (content of first term)
  136337. ** array {
  136338. ** (further terms are delta-encoded)
  136339. ** varint nPrefix; (length of shared prefix with previous term)
  136340. ** varint nSuffix; (length of unshared suffix)
  136341. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  136342. ** }
  136343. ** }
  136344. **
  136345. ** Here, optional { X } means an optional element, while array { X }
  136346. ** means zero or more occurrences of X, adjacent in memory.
  136347. **
  136348. ** An interior node encodes n terms separating n+1 subtrees. The
  136349. ** subtree blocks are contiguous, so only the first subtree's blockid
  136350. ** is encoded. The subtree at iBlockid will contain all terms less
  136351. ** than the first term encoded (or all terms if no term is encoded).
  136352. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  136353. ** than pTerm[i+1], the subtree for that term will be rooted at
  136354. ** iBlockid+i. Interior nodes only store enough term data to
  136355. ** distinguish adjacent children (if the rightmost term of the left
  136356. ** child is "something", and the leftmost term of the right child is
  136357. ** "wicked", only "w" is stored).
  136358. **
  136359. ** New data is spilled to a new interior node at the same height when
  136360. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  136361. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  136362. ** interior nodes and making the tree too skinny. The interior nodes
  136363. ** at a given height are naturally tracked by interior nodes at
  136364. ** height+1, and so on.
  136365. **
  136366. **
  136367. **** Segment directory ****
  136368. ** The segment directory in table %_segdir stores meta-information for
  136369. ** merging and deleting segments, and also the root node of the
  136370. ** segment's tree.
  136371. **
  136372. ** The root node is the top node of the segment's tree after encoding
  136373. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  136374. ** This could be either a leaf node or an interior node. If the top
  136375. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  136376. ** and a new root interior node is generated (which should always fit
  136377. ** within ROOT_MAX because it only needs space for 2 varints, the
  136378. ** height and the blockid of the previous root).
  136379. **
  136380. ** The meta-information in the segment directory is:
  136381. ** level - segment level (see below)
  136382. ** idx - index within level
  136383. ** - (level,idx uniquely identify a segment)
  136384. ** start_block - first leaf node
  136385. ** leaves_end_block - last leaf node
  136386. ** end_block - last block (including interior nodes)
  136387. ** root - contents of root node
  136388. **
  136389. ** If the root node is a leaf node, then start_block,
  136390. ** leaves_end_block, and end_block are all 0.
  136391. **
  136392. **
  136393. **** Segment merging ****
  136394. ** To amortize update costs, segments are grouped into levels and
  136395. ** merged in batches. Each increase in level represents exponentially
  136396. ** more documents.
  136397. **
  136398. ** New documents (actually, document updates) are tokenized and
  136399. ** written individually (using LeafWriter) to a level 0 segment, with
  136400. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  136401. ** level 0 segments are merged into a single level 1 segment. Level 1
  136402. ** is populated like level 0, and eventually MERGE_COUNT level 1
  136403. ** segments are merged to a single level 2 segment (representing
  136404. ** MERGE_COUNT^2 updates), and so on.
  136405. **
  136406. ** A segment merge traverses all segments at a given level in
  136407. ** parallel, performing a straightforward sorted merge. Since segment
  136408. ** leaf nodes are written in to the %_segments table in order, this
  136409. ** merge traverses the underlying sqlite disk structures efficiently.
  136410. ** After the merge, all segment blocks from the merged level are
  136411. ** deleted.
  136412. **
  136413. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  136414. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  136415. ** very similar performance numbers to 16 on insertion, though they're
  136416. ** a tiny bit slower (perhaps due to more overhead in merge-time
  136417. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  136418. ** 16, 2 about 66% slower than 16.
  136419. **
  136420. ** At query time, high MERGE_COUNT increases the number of segments
  136421. ** which need to be scanned and merged. For instance, with 100k docs
  136422. ** inserted:
  136423. **
  136424. ** MERGE_COUNT segments
  136425. ** 16 25
  136426. ** 8 12
  136427. ** 4 10
  136428. ** 2 6
  136429. **
  136430. ** This appears to have only a moderate impact on queries for very
  136431. ** frequent terms (which are somewhat dominated by segment merge
  136432. ** costs), and infrequent and non-existent terms still seem to be fast
  136433. ** even with many segments.
  136434. **
  136435. ** TODO(shess) That said, it would be nice to have a better query-side
  136436. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  136437. ** optimizations to things like doclist merging will swing the sweet
  136438. ** spot around.
  136439. **
  136440. **
  136441. **
  136442. **** Handling of deletions and updates ****
  136443. ** Since we're using a segmented structure, with no docid-oriented
  136444. ** index into the term index, we clearly cannot simply update the term
  136445. ** index when a document is deleted or updated. For deletions, we
  136446. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  136447. ** we simply write the new doclist. Segment merges overwrite older
  136448. ** data for a particular docid with newer data, so deletes or updates
  136449. ** will eventually overtake the earlier data and knock it out. The
  136450. ** query logic likewise merges doclists so that newer data knocks out
  136451. ** older data.
  136452. */
  136453. /************** Include fts3Int.h in the middle of fts3.c ********************/
  136454. /************** Begin file fts3Int.h *****************************************/
  136455. /*
  136456. ** 2009 Nov 12
  136457. **
  136458. ** The author disclaims copyright to this source code. In place of
  136459. ** a legal notice, here is a blessing:
  136460. **
  136461. ** May you do good and not evil.
  136462. ** May you find forgiveness for yourself and forgive others.
  136463. ** May you share freely, never taking more than you give.
  136464. **
  136465. ******************************************************************************
  136466. **
  136467. */
  136468. #ifndef _FTSINT_H
  136469. #define _FTSINT_H
  136470. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  136471. # define NDEBUG 1
  136472. #endif
  136473. /* FTS3/FTS4 require virtual tables */
  136474. #ifdef SQLITE_OMIT_VIRTUALTABLE
  136475. # undef SQLITE_ENABLE_FTS3
  136476. # undef SQLITE_ENABLE_FTS4
  136477. #endif
  136478. /*
  136479. ** FTS4 is really an extension for FTS3. It is enabled using the
  136480. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  136481. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  136482. */
  136483. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  136484. # define SQLITE_ENABLE_FTS3
  136485. #endif
  136486. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  136487. /* If not building as part of the core, include sqlite3ext.h. */
  136488. #ifndef SQLITE_CORE
  136489. /* # include "sqlite3ext.h" */
  136490. SQLITE_EXTENSION_INIT3
  136491. #endif
  136492. /* #include "sqlite3.h" */
  136493. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  136494. /************** Begin file fts3_tokenizer.h **********************************/
  136495. /*
  136496. ** 2006 July 10
  136497. **
  136498. ** The author disclaims copyright to this source code.
  136499. **
  136500. *************************************************************************
  136501. ** Defines the interface to tokenizers used by fulltext-search. There
  136502. ** are three basic components:
  136503. **
  136504. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  136505. ** interface functions. This is essentially the class structure for
  136506. ** tokenizers.
  136507. **
  136508. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  136509. ** including customization information defined at creation time.
  136510. **
  136511. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  136512. ** tokens from a particular input.
  136513. */
  136514. #ifndef _FTS3_TOKENIZER_H_
  136515. #define _FTS3_TOKENIZER_H_
  136516. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  136517. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  136518. ** we will need a way to register the API consistently.
  136519. */
  136520. /* #include "sqlite3.h" */
  136521. /*
  136522. ** Structures used by the tokenizer interface. When a new tokenizer
  136523. ** implementation is registered, the caller provides a pointer to
  136524. ** an sqlite3_tokenizer_module containing pointers to the callback
  136525. ** functions that make up an implementation.
  136526. **
  136527. ** When an fts3 table is created, it passes any arguments passed to
  136528. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  136529. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  136530. ** implementation. The xCreate() function in turn returns an
  136531. ** sqlite3_tokenizer structure representing the specific tokenizer to
  136532. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  136533. **
  136534. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  136535. ** method is called. It returns an sqlite3_tokenizer_cursor object
  136536. ** that may be used to tokenize a specific input buffer based on
  136537. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  136538. ** object.
  136539. */
  136540. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  136541. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  136542. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  136543. struct sqlite3_tokenizer_module {
  136544. /*
  136545. ** Structure version. Should always be set to 0 or 1.
  136546. */
  136547. int iVersion;
  136548. /*
  136549. ** Create a new tokenizer. The values in the argv[] array are the
  136550. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  136551. ** TABLE statement that created the fts3 table. For example, if
  136552. ** the following SQL is executed:
  136553. **
  136554. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  136555. **
  136556. ** then argc is set to 2, and the argv[] array contains pointers
  136557. ** to the strings "arg1" and "arg2".
  136558. **
  136559. ** This method should return either SQLITE_OK (0), or an SQLite error
  136560. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  136561. ** to point at the newly created tokenizer structure. The generic
  136562. ** sqlite3_tokenizer.pModule variable should not be initialized by
  136563. ** this callback. The caller will do so.
  136564. */
  136565. int (*xCreate)(
  136566. int argc, /* Size of argv array */
  136567. const char *const*argv, /* Tokenizer argument strings */
  136568. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  136569. );
  136570. /*
  136571. ** Destroy an existing tokenizer. The fts3 module calls this method
  136572. ** exactly once for each successful call to xCreate().
  136573. */
  136574. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  136575. /*
  136576. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  136577. ** is responsible for ensuring that the input buffer remains valid
  136578. ** until the cursor is closed (using the xClose() method).
  136579. */
  136580. int (*xOpen)(
  136581. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  136582. const char *pInput, int nBytes, /* Input buffer */
  136583. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  136584. );
  136585. /*
  136586. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  136587. ** method exactly once for each successful call to xOpen().
  136588. */
  136589. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  136590. /*
  136591. ** Retrieve the next token from the tokenizer cursor pCursor. This
  136592. ** method should either return SQLITE_OK and set the values of the
  136593. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  136594. ** the end of the buffer has been reached, or an SQLite error code.
  136595. **
  136596. ** *ppToken should be set to point at a buffer containing the
  136597. ** normalized version of the token (i.e. after any case-folding and/or
  136598. ** stemming has been performed). *pnBytes should be set to the length
  136599. ** of this buffer in bytes. The input text that generated the token is
  136600. ** identified by the byte offsets returned in *piStartOffset and
  136601. ** *piEndOffset. *piStartOffset should be set to the index of the first
  136602. ** byte of the token in the input buffer. *piEndOffset should be set
  136603. ** to the index of the first byte just past the end of the token in
  136604. ** the input buffer.
  136605. **
  136606. ** The buffer *ppToken is set to point at is managed by the tokenizer
  136607. ** implementation. It is only required to be valid until the next call
  136608. ** to xNext() or xClose().
  136609. */
  136610. /* TODO(shess) current implementation requires pInput to be
  136611. ** nul-terminated. This should either be fixed, or pInput/nBytes
  136612. ** should be converted to zInput.
  136613. */
  136614. int (*xNext)(
  136615. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  136616. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  136617. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  136618. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  136619. int *piPosition /* OUT: Number of tokens returned before this one */
  136620. );
  136621. /***********************************************************************
  136622. ** Methods below this point are only available if iVersion>=1.
  136623. */
  136624. /*
  136625. ** Configure the language id of a tokenizer cursor.
  136626. */
  136627. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  136628. };
  136629. struct sqlite3_tokenizer {
  136630. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  136631. /* Tokenizer implementations will typically add additional fields */
  136632. };
  136633. struct sqlite3_tokenizer_cursor {
  136634. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  136635. /* Tokenizer implementations will typically add additional fields */
  136636. };
  136637. int fts3_global_term_cnt(int iTerm, int iCol);
  136638. int fts3_term_cnt(int iTerm, int iCol);
  136639. #endif /* _FTS3_TOKENIZER_H_ */
  136640. /************** End of fts3_tokenizer.h **************************************/
  136641. /************** Continuing where we left off in fts3Int.h ********************/
  136642. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  136643. /************** Begin file fts3_hash.h ***************************************/
  136644. /*
  136645. ** 2001 September 22
  136646. **
  136647. ** The author disclaims copyright to this source code. In place of
  136648. ** a legal notice, here is a blessing:
  136649. **
  136650. ** May you do good and not evil.
  136651. ** May you find forgiveness for yourself and forgive others.
  136652. ** May you share freely, never taking more than you give.
  136653. **
  136654. *************************************************************************
  136655. ** This is the header file for the generic hash-table implementation
  136656. ** used in SQLite. We've modified it slightly to serve as a standalone
  136657. ** hash table implementation for the full-text indexing module.
  136658. **
  136659. */
  136660. #ifndef _FTS3_HASH_H_
  136661. #define _FTS3_HASH_H_
  136662. /* Forward declarations of structures. */
  136663. typedef struct Fts3Hash Fts3Hash;
  136664. typedef struct Fts3HashElem Fts3HashElem;
  136665. /* A complete hash table is an instance of the following structure.
  136666. ** The internals of this structure are intended to be opaque -- client
  136667. ** code should not attempt to access or modify the fields of this structure
  136668. ** directly. Change this structure only by using the routines below.
  136669. ** However, many of the "procedures" and "functions" for modifying and
  136670. ** accessing this structure are really macros, so we can't really make
  136671. ** this structure opaque.
  136672. */
  136673. struct Fts3Hash {
  136674. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  136675. char copyKey; /* True if copy of key made on insert */
  136676. int count; /* Number of entries in this table */
  136677. Fts3HashElem *first; /* The first element of the array */
  136678. int htsize; /* Number of buckets in the hash table */
  136679. struct _fts3ht { /* the hash table */
  136680. int count; /* Number of entries with this hash */
  136681. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  136682. } *ht;
  136683. };
  136684. /* Each element in the hash table is an instance of the following
  136685. ** structure. All elements are stored on a single doubly-linked list.
  136686. **
  136687. ** Again, this structure is intended to be opaque, but it can't really
  136688. ** be opaque because it is used by macros.
  136689. */
  136690. struct Fts3HashElem {
  136691. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  136692. void *data; /* Data associated with this element */
  136693. void *pKey; int nKey; /* Key associated with this element */
  136694. };
  136695. /*
  136696. ** There are 2 different modes of operation for a hash table:
  136697. **
  136698. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  136699. ** (including the null-terminator, if any). Case
  136700. ** is respected in comparisons.
  136701. **
  136702. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  136703. ** memcmp() is used to compare keys.
  136704. **
  136705. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  136706. */
  136707. #define FTS3_HASH_STRING 1
  136708. #define FTS3_HASH_BINARY 2
  136709. /*
  136710. ** Access routines. To delete, insert a NULL pointer.
  136711. */
  136712. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  136713. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  136714. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  136715. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  136716. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  136717. /*
  136718. ** Shorthand for the functions above
  136719. */
  136720. #define fts3HashInit sqlite3Fts3HashInit
  136721. #define fts3HashInsert sqlite3Fts3HashInsert
  136722. #define fts3HashFind sqlite3Fts3HashFind
  136723. #define fts3HashClear sqlite3Fts3HashClear
  136724. #define fts3HashFindElem sqlite3Fts3HashFindElem
  136725. /*
  136726. ** Macros for looping over all elements of a hash table. The idiom is
  136727. ** like this:
  136728. **
  136729. ** Fts3Hash h;
  136730. ** Fts3HashElem *p;
  136731. ** ...
  136732. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  136733. ** SomeStructure *pData = fts3HashData(p);
  136734. ** // do something with pData
  136735. ** }
  136736. */
  136737. #define fts3HashFirst(H) ((H)->first)
  136738. #define fts3HashNext(E) ((E)->next)
  136739. #define fts3HashData(E) ((E)->data)
  136740. #define fts3HashKey(E) ((E)->pKey)
  136741. #define fts3HashKeysize(E) ((E)->nKey)
  136742. /*
  136743. ** Number of entries in a hash table
  136744. */
  136745. #define fts3HashCount(H) ((H)->count)
  136746. #endif /* _FTS3_HASH_H_ */
  136747. /************** End of fts3_hash.h *******************************************/
  136748. /************** Continuing where we left off in fts3Int.h ********************/
  136749. /*
  136750. ** This constant determines the maximum depth of an FTS expression tree
  136751. ** that the library will create and use. FTS uses recursion to perform
  136752. ** various operations on the query tree, so the disadvantage of a large
  136753. ** limit is that it may allow very large queries to use large amounts
  136754. ** of stack space (perhaps causing a stack overflow).
  136755. */
  136756. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  136757. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  136758. #endif
  136759. /*
  136760. ** This constant controls how often segments are merged. Once there are
  136761. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  136762. ** segment of level N+1.
  136763. */
  136764. #define FTS3_MERGE_COUNT 16
  136765. /*
  136766. ** This is the maximum amount of data (in bytes) to store in the
  136767. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  136768. ** populated as documents are inserted/updated/deleted in a transaction
  136769. ** and used to create a new segment when the transaction is committed.
  136770. ** However if this limit is reached midway through a transaction, a new
  136771. ** segment is created and the hash table cleared immediately.
  136772. */
  136773. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  136774. /*
  136775. ** Macro to return the number of elements in an array. SQLite has a
  136776. ** similar macro called ArraySize(). Use a different name to avoid
  136777. ** a collision when building an amalgamation with built-in FTS3.
  136778. */
  136779. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  136780. #ifndef MIN
  136781. # define MIN(x,y) ((x)<(y)?(x):(y))
  136782. #endif
  136783. #ifndef MAX
  136784. # define MAX(x,y) ((x)>(y)?(x):(y))
  136785. #endif
  136786. /*
  136787. ** Maximum length of a varint encoded integer. The varint format is different
  136788. ** from that used by SQLite, so the maximum length is 10, not 9.
  136789. */
  136790. #define FTS3_VARINT_MAX 10
  136791. /*
  136792. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  136793. ** in the document set and zero or more prefix indexes. All indexes are stored
  136794. ** as one or more b+-trees in the %_segments and %_segdir tables.
  136795. **
  136796. ** It is possible to determine which index a b+-tree belongs to based on the
  136797. ** value stored in the "%_segdir.level" column. Given this value L, the index
  136798. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  136799. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  136800. ** between 1024 and 2047 to index 1, and so on.
  136801. **
  136802. ** It is considered impossible for an index to use more than 1024 levels. In
  136803. ** theory though this may happen, but only after at least
  136804. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  136805. */
  136806. #define FTS3_SEGDIR_MAXLEVEL 1024
  136807. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  136808. /*
  136809. ** The testcase() macro is only used by the amalgamation. If undefined,
  136810. ** make it a no-op.
  136811. */
  136812. #ifndef testcase
  136813. # define testcase(X)
  136814. #endif
  136815. /*
  136816. ** Terminator values for position-lists and column-lists.
  136817. */
  136818. #define POS_COLUMN (1) /* Column-list terminator */
  136819. #define POS_END (0) /* Position-list terminator */
  136820. /*
  136821. ** This section provides definitions to allow the
  136822. ** FTS3 extension to be compiled outside of the
  136823. ** amalgamation.
  136824. */
  136825. #ifndef SQLITE_AMALGAMATION
  136826. /*
  136827. ** Macros indicating that conditional expressions are always true or
  136828. ** false.
  136829. */
  136830. #ifdef SQLITE_COVERAGE_TEST
  136831. # define ALWAYS(x) (1)
  136832. # define NEVER(X) (0)
  136833. #elif defined(SQLITE_DEBUG)
  136834. # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
  136835. # define NEVER(x) sqlite3Fts3Never((x)!=0)
  136836. SQLITE_PRIVATE int sqlite3Fts3Always(int b);
  136837. SQLITE_PRIVATE int sqlite3Fts3Never(int b);
  136838. #else
  136839. # define ALWAYS(x) (x)
  136840. # define NEVER(x) (x)
  136841. #endif
  136842. /*
  136843. ** Internal types used by SQLite.
  136844. */
  136845. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  136846. typedef short int i16; /* 2-byte (or larger) signed integer */
  136847. typedef unsigned int u32; /* 4-byte unsigned integer */
  136848. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  136849. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  136850. /*
  136851. ** Macro used to suppress compiler warnings for unused parameters.
  136852. */
  136853. #define UNUSED_PARAMETER(x) (void)(x)
  136854. /*
  136855. ** Activate assert() only if SQLITE_TEST is enabled.
  136856. */
  136857. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  136858. # define NDEBUG 1
  136859. #endif
  136860. /*
  136861. ** The TESTONLY macro is used to enclose variable declarations or
  136862. ** other bits of code that are needed to support the arguments
  136863. ** within testcase() and assert() macros.
  136864. */
  136865. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  136866. # define TESTONLY(X) X
  136867. #else
  136868. # define TESTONLY(X)
  136869. #endif
  136870. #endif /* SQLITE_AMALGAMATION */
  136871. #ifdef SQLITE_DEBUG
  136872. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  136873. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  136874. #else
  136875. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  136876. #endif
  136877. typedef struct Fts3Table Fts3Table;
  136878. typedef struct Fts3Cursor Fts3Cursor;
  136879. typedef struct Fts3Expr Fts3Expr;
  136880. typedef struct Fts3Phrase Fts3Phrase;
  136881. typedef struct Fts3PhraseToken Fts3PhraseToken;
  136882. typedef struct Fts3Doclist Fts3Doclist;
  136883. typedef struct Fts3SegFilter Fts3SegFilter;
  136884. typedef struct Fts3DeferredToken Fts3DeferredToken;
  136885. typedef struct Fts3SegReader Fts3SegReader;
  136886. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  136887. typedef struct MatchinfoBuffer MatchinfoBuffer;
  136888. /*
  136889. ** A connection to a fulltext index is an instance of the following
  136890. ** structure. The xCreate and xConnect methods create an instance
  136891. ** of this structure and xDestroy and xDisconnect free that instance.
  136892. ** All other methods receive a pointer to the structure as one of their
  136893. ** arguments.
  136894. */
  136895. struct Fts3Table {
  136896. sqlite3_vtab base; /* Base class used by SQLite core */
  136897. sqlite3 *db; /* The database connection */
  136898. const char *zDb; /* logical database name */
  136899. const char *zName; /* virtual table name */
  136900. int nColumn; /* number of named columns in virtual table */
  136901. char **azColumn; /* column names. malloced */
  136902. u8 *abNotindexed; /* True for 'notindexed' columns */
  136903. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  136904. char *zContentTbl; /* content=xxx option, or NULL */
  136905. char *zLanguageid; /* languageid=xxx option, or NULL */
  136906. int nAutoincrmerge; /* Value configured by 'automerge' */
  136907. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  136908. /* Precompiled statements used by the implementation. Each of these
  136909. ** statements is run and reset within a single virtual table API call.
  136910. */
  136911. sqlite3_stmt *aStmt[40];
  136912. sqlite3_stmt *pSeekStmt; /* Cache for fts3CursorSeekStmt() */
  136913. char *zReadExprlist;
  136914. char *zWriteExprlist;
  136915. int nNodeSize; /* Soft limit for node size */
  136916. u8 bFts4; /* True for FTS4, false for FTS3 */
  136917. u8 bHasStat; /* True if %_stat table exists (2==unknown) */
  136918. u8 bHasDocsize; /* True if %_docsize table exists */
  136919. u8 bDescIdx; /* True if doclists are in reverse order */
  136920. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  136921. int nPgsz; /* Page size for host database */
  136922. char *zSegmentsTbl; /* Name of %_segments table */
  136923. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  136924. /*
  136925. ** The following array of hash tables is used to buffer pending index
  136926. ** updates during transactions. All pending updates buffered at any one
  136927. ** time must share a common language-id (see the FTS4 langid= feature).
  136928. ** The current language id is stored in variable iPrevLangid.
  136929. **
  136930. ** A single FTS4 table may have multiple full-text indexes. For each index
  136931. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  136932. ** terms that appear in the document set. Each subsequent index in aIndex[]
  136933. ** is an index of prefixes of a specific length.
  136934. **
  136935. ** Variable nPendingData contains an estimate the memory consumed by the
  136936. ** pending data structures, including hash table overhead, but not including
  136937. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  136938. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  136939. ** recently inserted record.
  136940. */
  136941. int nIndex; /* Size of aIndex[] */
  136942. struct Fts3Index {
  136943. int nPrefix; /* Prefix length (0 for main terms index) */
  136944. Fts3Hash hPending; /* Pending terms table for this index */
  136945. } *aIndex;
  136946. int nMaxPendingData; /* Max pending data before flush to disk */
  136947. int nPendingData; /* Current bytes of pending data */
  136948. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  136949. int iPrevLangid; /* Langid of recently inserted document */
  136950. int bPrevDelete; /* True if last operation was a delete */
  136951. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  136952. /* State variables used for validating that the transaction control
  136953. ** methods of the virtual table are called at appropriate times. These
  136954. ** values do not contribute to FTS functionality; they are used for
  136955. ** verifying the operation of the SQLite core.
  136956. */
  136957. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  136958. int mxSavepoint; /* Largest valid xSavepoint integer */
  136959. #endif
  136960. #ifdef SQLITE_TEST
  136961. /* True to disable the incremental doclist optimization. This is controled
  136962. ** by special insert command 'test-no-incr-doclist'. */
  136963. int bNoIncrDoclist;
  136964. #endif
  136965. };
  136966. /*
  136967. ** When the core wants to read from the virtual table, it creates a
  136968. ** virtual table cursor (an instance of the following structure) using
  136969. ** the xOpen method. Cursors are destroyed using the xClose method.
  136970. */
  136971. struct Fts3Cursor {
  136972. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  136973. i16 eSearch; /* Search strategy (see below) */
  136974. u8 isEof; /* True if at End Of Results */
  136975. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  136976. u8 bSeekStmt; /* True if pStmt is a seek */
  136977. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  136978. Fts3Expr *pExpr; /* Parsed MATCH query string */
  136979. int iLangid; /* Language being queried for */
  136980. int nPhrase; /* Number of matchable phrases in query */
  136981. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  136982. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  136983. char *pNextId; /* Pointer into the body of aDoclist */
  136984. char *aDoclist; /* List of docids for full-text queries */
  136985. int nDoclist; /* Size of buffer at aDoclist */
  136986. u8 bDesc; /* True to sort in descending order */
  136987. int eEvalmode; /* An FTS3_EVAL_XX constant */
  136988. int nRowAvg; /* Average size of database rows, in pages */
  136989. sqlite3_int64 nDoc; /* Documents in table */
  136990. i64 iMinDocid; /* Minimum docid to return */
  136991. i64 iMaxDocid; /* Maximum docid to return */
  136992. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  136993. MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */
  136994. };
  136995. #define FTS3_EVAL_FILTER 0
  136996. #define FTS3_EVAL_NEXT 1
  136997. #define FTS3_EVAL_MATCHINFO 2
  136998. /*
  136999. ** The Fts3Cursor.eSearch member is always set to one of the following.
  137000. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  137001. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  137002. ** of the column to be searched. For example, in
  137003. **
  137004. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  137005. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  137006. **
  137007. ** Because the LHS of the MATCH operator is 2nd column "b",
  137008. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  137009. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  137010. ** indicating that all columns should be searched,
  137011. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  137012. */
  137013. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  137014. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  137015. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  137016. /*
  137017. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  137018. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  137019. ** above. The upper 16-bits contain a combination of the following
  137020. ** bits, used to describe extra constraints on full-text searches.
  137021. */
  137022. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  137023. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  137024. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  137025. struct Fts3Doclist {
  137026. char *aAll; /* Array containing doclist (or NULL) */
  137027. int nAll; /* Size of a[] in bytes */
  137028. char *pNextDocid; /* Pointer to next docid */
  137029. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  137030. int bFreeList; /* True if pList should be sqlite3_free()d */
  137031. char *pList; /* Pointer to position list following iDocid */
  137032. int nList; /* Length of position list */
  137033. };
  137034. /*
  137035. ** A "phrase" is a sequence of one or more tokens that must match in
  137036. ** sequence. A single token is the base case and the most common case.
  137037. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  137038. ** nToken will be the number of tokens in the string.
  137039. */
  137040. struct Fts3PhraseToken {
  137041. char *z; /* Text of the token */
  137042. int n; /* Number of bytes in buffer z */
  137043. int isPrefix; /* True if token ends with a "*" character */
  137044. int bFirst; /* True if token must appear at position 0 */
  137045. /* Variables above this point are populated when the expression is
  137046. ** parsed (by code in fts3_expr.c). Below this point the variables are
  137047. ** used when evaluating the expression. */
  137048. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  137049. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  137050. };
  137051. struct Fts3Phrase {
  137052. /* Cache of doclist for this phrase. */
  137053. Fts3Doclist doclist;
  137054. int bIncr; /* True if doclist is loaded incrementally */
  137055. int iDoclistToken;
  137056. /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
  137057. ** OR condition. */
  137058. char *pOrPoslist;
  137059. i64 iOrDocid;
  137060. /* Variables below this point are populated by fts3_expr.c when parsing
  137061. ** a MATCH expression. Everything above is part of the evaluation phase.
  137062. */
  137063. int nToken; /* Number of tokens in the phrase */
  137064. int iColumn; /* Index of column this phrase must match */
  137065. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  137066. };
  137067. /*
  137068. ** A tree of these objects forms the RHS of a MATCH operator.
  137069. **
  137070. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  137071. ** points to a malloced buffer, size nDoclist bytes, containing the results
  137072. ** of this phrase query in FTS3 doclist format. As usual, the initial
  137073. ** "Length" field found in doclists stored on disk is omitted from this
  137074. ** buffer.
  137075. **
  137076. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  137077. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  137078. ** where nCol is the number of columns in the queried FTS table. The array
  137079. ** is populated as follows:
  137080. **
  137081. ** aMI[iCol*3 + 0] = Undefined
  137082. ** aMI[iCol*3 + 1] = Number of occurrences
  137083. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  137084. **
  137085. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  137086. ** when the expression node is.
  137087. */
  137088. struct Fts3Expr {
  137089. int eType; /* One of the FTSQUERY_XXX values defined below */
  137090. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  137091. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  137092. Fts3Expr *pLeft; /* Left operand */
  137093. Fts3Expr *pRight; /* Right operand */
  137094. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  137095. /* The following are used by the fts3_eval.c module. */
  137096. sqlite3_int64 iDocid; /* Current docid */
  137097. u8 bEof; /* True this expression is at EOF already */
  137098. u8 bStart; /* True if iDocid is valid */
  137099. u8 bDeferred; /* True if this expression is entirely deferred */
  137100. /* The following are used by the fts3_snippet.c module. */
  137101. int iPhrase; /* Index of this phrase in matchinfo() results */
  137102. u32 *aMI; /* See above */
  137103. };
  137104. /*
  137105. ** Candidate values for Fts3Query.eType. Note that the order of the first
  137106. ** four values is in order of precedence when parsing expressions. For
  137107. ** example, the following:
  137108. **
  137109. ** "a OR b AND c NOT d NEAR e"
  137110. **
  137111. ** is equivalent to:
  137112. **
  137113. ** "a OR (b AND (c NOT (d NEAR e)))"
  137114. */
  137115. #define FTSQUERY_NEAR 1
  137116. #define FTSQUERY_NOT 2
  137117. #define FTSQUERY_AND 3
  137118. #define FTSQUERY_OR 4
  137119. #define FTSQUERY_PHRASE 5
  137120. /* fts3_write.c */
  137121. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  137122. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  137123. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  137124. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  137125. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  137126. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  137127. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  137128. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  137129. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  137130. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  137131. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  137132. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  137133. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  137134. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  137135. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  137136. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  137137. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  137138. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  137139. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  137140. #else
  137141. # define sqlite3Fts3FreeDeferredTokens(x)
  137142. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  137143. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  137144. # define sqlite3Fts3FreeDeferredDoclists(x)
  137145. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  137146. #endif
  137147. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  137148. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  137149. /* Special values interpreted by sqlite3SegReaderCursor() */
  137150. #define FTS3_SEGCURSOR_PENDING -1
  137151. #define FTS3_SEGCURSOR_ALL -2
  137152. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  137153. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  137154. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  137155. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  137156. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  137157. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  137158. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  137159. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  137160. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  137161. #define FTS3_SEGMENT_PREFIX 0x00000008
  137162. #define FTS3_SEGMENT_SCAN 0x00000010
  137163. #define FTS3_SEGMENT_FIRST 0x00000020
  137164. /* Type passed as 4th argument to SegmentReaderIterate() */
  137165. struct Fts3SegFilter {
  137166. const char *zTerm;
  137167. int nTerm;
  137168. int iCol;
  137169. int flags;
  137170. };
  137171. struct Fts3MultiSegReader {
  137172. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  137173. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  137174. int nSegment; /* Size of apSegment array */
  137175. int nAdvance; /* How many seg-readers to advance */
  137176. Fts3SegFilter *pFilter; /* Pointer to filter object */
  137177. char *aBuffer; /* Buffer to merge doclists in */
  137178. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  137179. int iColFilter; /* If >=0, filter for this column */
  137180. int bRestart;
  137181. /* Used by fts3.c only. */
  137182. int nCost; /* Cost of running iterator */
  137183. int bLookup; /* True if a lookup of a single entry. */
  137184. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  137185. char *zTerm; /* Pointer to term buffer */
  137186. int nTerm; /* Size of zTerm in bytes */
  137187. char *aDoclist; /* Pointer to doclist buffer */
  137188. int nDoclist; /* Size of aDoclist[] in bytes */
  137189. };
  137190. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  137191. #define fts3GetVarint32(p, piVal) ( \
  137192. (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
  137193. )
  137194. /* fts3.c */
  137195. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
  137196. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  137197. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  137198. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  137199. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  137200. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  137201. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  137202. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  137203. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  137204. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  137205. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
  137206. /* fts3_tokenizer.c */
  137207. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  137208. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  137209. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  137210. sqlite3_tokenizer **, char **
  137211. );
  137212. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  137213. /* fts3_snippet.c */
  137214. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  137215. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  137216. const char *, const char *, int, int
  137217. );
  137218. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  137219. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
  137220. /* fts3_expr.c */
  137221. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  137222. char **, int, int, int, const char *, int, Fts3Expr **, char **
  137223. );
  137224. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  137225. #ifdef SQLITE_TEST
  137226. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  137227. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  137228. #endif
  137229. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  137230. sqlite3_tokenizer_cursor **
  137231. );
  137232. /* fts3_aux.c */
  137233. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  137234. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  137235. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  137236. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  137237. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  137238. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  137239. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  137240. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  137241. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  137242. /* fts3_tokenize_vtab.c */
  137243. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  137244. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  137245. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  137246. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  137247. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  137248. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  137249. #endif
  137250. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  137251. #endif /* _FTSINT_H */
  137252. /************** End of fts3Int.h *********************************************/
  137253. /************** Continuing where we left off in fts3.c ***********************/
  137254. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  137255. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  137256. # define SQLITE_CORE 1
  137257. #endif
  137258. /* #include <assert.h> */
  137259. /* #include <stdlib.h> */
  137260. /* #include <stddef.h> */
  137261. /* #include <stdio.h> */
  137262. /* #include <string.h> */
  137263. /* #include <stdarg.h> */
  137264. /* #include "fts3.h" */
  137265. #ifndef SQLITE_CORE
  137266. /* # include "sqlite3ext.h" */
  137267. SQLITE_EXTENSION_INIT1
  137268. #endif
  137269. static int fts3EvalNext(Fts3Cursor *pCsr);
  137270. static int fts3EvalStart(Fts3Cursor *pCsr);
  137271. static int fts3TermSegReaderCursor(
  137272. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  137273. #ifndef SQLITE_AMALGAMATION
  137274. # if defined(SQLITE_DEBUG)
  137275. SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
  137276. SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
  137277. # endif
  137278. #endif
  137279. /*
  137280. ** Write a 64-bit variable-length integer to memory starting at p[0].
  137281. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  137282. ** The number of bytes written is returned.
  137283. */
  137284. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  137285. unsigned char *q = (unsigned char *) p;
  137286. sqlite_uint64 vu = v;
  137287. do{
  137288. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  137289. vu >>= 7;
  137290. }while( vu!=0 );
  137291. q[-1] &= 0x7f; /* turn off high bit in final byte */
  137292. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  137293. return (int) (q - (unsigned char *)p);
  137294. }
  137295. #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
  137296. v = (v & mask1) | ( (*ptr++) << shift ); \
  137297. if( (v & mask2)==0 ){ var = v; return ret; }
  137298. #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
  137299. v = (*ptr++); \
  137300. if( (v & mask2)==0 ){ var = v; return ret; }
  137301. /*
  137302. ** Read a 64-bit variable-length integer from memory starting at p[0].
  137303. ** Return the number of bytes read, or 0 on error.
  137304. ** The value is stored in *v.
  137305. */
  137306. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
  137307. const unsigned char *p = (const unsigned char*)pBuf;
  137308. const unsigned char *pStart = p;
  137309. u32 a;
  137310. u64 b;
  137311. int shift;
  137312. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
  137313. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
  137314. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
  137315. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
  137316. b = (a & 0x0FFFFFFF );
  137317. for(shift=28; shift<=63; shift+=7){
  137318. u64 c = *p++;
  137319. b += (c&0x7F) << shift;
  137320. if( (c & 0x80)==0 ) break;
  137321. }
  137322. *v = b;
  137323. return (int)(p - pStart);
  137324. }
  137325. /*
  137326. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to
  137327. ** a non-negative 32-bit integer before it is returned.
  137328. */
  137329. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  137330. u32 a;
  137331. #ifndef fts3GetVarint32
  137332. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
  137333. #else
  137334. a = (*p++);
  137335. assert( a & 0x80 );
  137336. #endif
  137337. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
  137338. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
  137339. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
  137340. a = (a & 0x0FFFFFFF );
  137341. *pi = (int)(a | ((u32)(*p & 0x07) << 28));
  137342. assert( 0==(a & 0x80000000) );
  137343. assert( *pi>=0 );
  137344. return 5;
  137345. }
  137346. /*
  137347. ** Return the number of bytes required to encode v as a varint
  137348. */
  137349. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  137350. int i = 0;
  137351. do{
  137352. i++;
  137353. v >>= 7;
  137354. }while( v!=0 );
  137355. return i;
  137356. }
  137357. /*
  137358. ** Convert an SQL-style quoted string into a normal string by removing
  137359. ** the quote characters. The conversion is done in-place. If the
  137360. ** input does not begin with a quote character, then this routine
  137361. ** is a no-op.
  137362. **
  137363. ** Examples:
  137364. **
  137365. ** "abc" becomes abc
  137366. ** 'xyz' becomes xyz
  137367. ** [pqr] becomes pqr
  137368. ** `mno` becomes mno
  137369. **
  137370. */
  137371. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  137372. char quote; /* Quote character (if any ) */
  137373. quote = z[0];
  137374. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  137375. int iIn = 1; /* Index of next byte to read from input */
  137376. int iOut = 0; /* Index of next byte to write to output */
  137377. /* If the first byte was a '[', then the close-quote character is a ']' */
  137378. if( quote=='[' ) quote = ']';
  137379. while( z[iIn] ){
  137380. if( z[iIn]==quote ){
  137381. if( z[iIn+1]!=quote ) break;
  137382. z[iOut++] = quote;
  137383. iIn += 2;
  137384. }else{
  137385. z[iOut++] = z[iIn++];
  137386. }
  137387. }
  137388. z[iOut] = '\0';
  137389. }
  137390. }
  137391. /*
  137392. ** Read a single varint from the doclist at *pp and advance *pp to point
  137393. ** to the first byte past the end of the varint. Add the value of the varint
  137394. ** to *pVal.
  137395. */
  137396. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  137397. sqlite3_int64 iVal;
  137398. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  137399. *pVal += iVal;
  137400. }
  137401. /*
  137402. ** When this function is called, *pp points to the first byte following a
  137403. ** varint that is part of a doclist (or position-list, or any other list
  137404. ** of varints). This function moves *pp to point to the start of that varint,
  137405. ** and sets *pVal by the varint value.
  137406. **
  137407. ** Argument pStart points to the first byte of the doclist that the
  137408. ** varint is part of.
  137409. */
  137410. static void fts3GetReverseVarint(
  137411. char **pp,
  137412. char *pStart,
  137413. sqlite3_int64 *pVal
  137414. ){
  137415. sqlite3_int64 iVal;
  137416. char *p;
  137417. /* Pointer p now points at the first byte past the varint we are
  137418. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  137419. ** clear on character p[-1]. */
  137420. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  137421. p++;
  137422. *pp = p;
  137423. sqlite3Fts3GetVarint(p, &iVal);
  137424. *pVal = iVal;
  137425. }
  137426. /*
  137427. ** The xDisconnect() virtual table method.
  137428. */
  137429. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  137430. Fts3Table *p = (Fts3Table *)pVtab;
  137431. int i;
  137432. assert( p->nPendingData==0 );
  137433. assert( p->pSegments==0 );
  137434. /* Free any prepared statements held */
  137435. sqlite3_finalize(p->pSeekStmt);
  137436. for(i=0; i<SizeofArray(p->aStmt); i++){
  137437. sqlite3_finalize(p->aStmt[i]);
  137438. }
  137439. sqlite3_free(p->zSegmentsTbl);
  137440. sqlite3_free(p->zReadExprlist);
  137441. sqlite3_free(p->zWriteExprlist);
  137442. sqlite3_free(p->zContentTbl);
  137443. sqlite3_free(p->zLanguageid);
  137444. /* Invoke the tokenizer destructor to free the tokenizer. */
  137445. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  137446. sqlite3_free(p);
  137447. return SQLITE_OK;
  137448. }
  137449. /*
  137450. ** Write an error message into *pzErr
  137451. */
  137452. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
  137453. va_list ap;
  137454. sqlite3_free(*pzErr);
  137455. va_start(ap, zFormat);
  137456. *pzErr = sqlite3_vmprintf(zFormat, ap);
  137457. va_end(ap);
  137458. }
  137459. /*
  137460. ** Construct one or more SQL statements from the format string given
  137461. ** and then evaluate those statements. The success code is written
  137462. ** into *pRc.
  137463. **
  137464. ** If *pRc is initially non-zero then this routine is a no-op.
  137465. */
  137466. static void fts3DbExec(
  137467. int *pRc, /* Success code */
  137468. sqlite3 *db, /* Database in which to run SQL */
  137469. const char *zFormat, /* Format string for SQL */
  137470. ... /* Arguments to the format string */
  137471. ){
  137472. va_list ap;
  137473. char *zSql;
  137474. if( *pRc ) return;
  137475. va_start(ap, zFormat);
  137476. zSql = sqlite3_vmprintf(zFormat, ap);
  137477. va_end(ap);
  137478. if( zSql==0 ){
  137479. *pRc = SQLITE_NOMEM;
  137480. }else{
  137481. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  137482. sqlite3_free(zSql);
  137483. }
  137484. }
  137485. /*
  137486. ** The xDestroy() virtual table method.
  137487. */
  137488. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  137489. Fts3Table *p = (Fts3Table *)pVtab;
  137490. int rc = SQLITE_OK; /* Return code */
  137491. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  137492. sqlite3 *db = p->db; /* Database handle */
  137493. /* Drop the shadow tables */
  137494. if( p->zContentTbl==0 ){
  137495. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  137496. }
  137497. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  137498. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  137499. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  137500. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  137501. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  137502. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  137503. ** Otherwise, return an SQLite error code.
  137504. */
  137505. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  137506. }
  137507. /*
  137508. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  137509. ** passed as the first argument. This is done as part of the xConnect()
  137510. ** and xCreate() methods.
  137511. **
  137512. ** If *pRc is non-zero when this function is called, it is a no-op.
  137513. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  137514. ** before returning.
  137515. */
  137516. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  137517. if( *pRc==SQLITE_OK ){
  137518. int i; /* Iterator variable */
  137519. int rc; /* Return code */
  137520. char *zSql; /* SQL statement passed to declare_vtab() */
  137521. char *zCols; /* List of user defined columns */
  137522. const char *zLanguageid;
  137523. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  137524. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  137525. /* Create a list of user columns for the virtual table */
  137526. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  137527. for(i=1; zCols && i<p->nColumn; i++){
  137528. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  137529. }
  137530. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  137531. zSql = sqlite3_mprintf(
  137532. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  137533. zCols, p->zName, zLanguageid
  137534. );
  137535. if( !zCols || !zSql ){
  137536. rc = SQLITE_NOMEM;
  137537. }else{
  137538. rc = sqlite3_declare_vtab(p->db, zSql);
  137539. }
  137540. sqlite3_free(zSql);
  137541. sqlite3_free(zCols);
  137542. *pRc = rc;
  137543. }
  137544. }
  137545. /*
  137546. ** Create the %_stat table if it does not already exist.
  137547. */
  137548. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  137549. fts3DbExec(pRc, p->db,
  137550. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  137551. "(id INTEGER PRIMARY KEY, value BLOB);",
  137552. p->zDb, p->zName
  137553. );
  137554. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  137555. }
  137556. /*
  137557. ** Create the backing store tables (%_content, %_segments and %_segdir)
  137558. ** required by the FTS3 table passed as the only argument. This is done
  137559. ** as part of the vtab xCreate() method.
  137560. **
  137561. ** If the p->bHasDocsize boolean is true (indicating that this is an
  137562. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  137563. ** %_stat tables required by FTS4.
  137564. */
  137565. static int fts3CreateTables(Fts3Table *p){
  137566. int rc = SQLITE_OK; /* Return code */
  137567. int i; /* Iterator variable */
  137568. sqlite3 *db = p->db; /* The database connection */
  137569. if( p->zContentTbl==0 ){
  137570. const char *zLanguageid = p->zLanguageid;
  137571. char *zContentCols; /* Columns of %_content table */
  137572. /* Create a list of user columns for the content table */
  137573. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  137574. for(i=0; zContentCols && i<p->nColumn; i++){
  137575. char *z = p->azColumn[i];
  137576. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  137577. }
  137578. if( zLanguageid && zContentCols ){
  137579. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  137580. }
  137581. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  137582. /* Create the content table */
  137583. fts3DbExec(&rc, db,
  137584. "CREATE TABLE %Q.'%q_content'(%s)",
  137585. p->zDb, p->zName, zContentCols
  137586. );
  137587. sqlite3_free(zContentCols);
  137588. }
  137589. /* Create other tables */
  137590. fts3DbExec(&rc, db,
  137591. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  137592. p->zDb, p->zName
  137593. );
  137594. fts3DbExec(&rc, db,
  137595. "CREATE TABLE %Q.'%q_segdir'("
  137596. "level INTEGER,"
  137597. "idx INTEGER,"
  137598. "start_block INTEGER,"
  137599. "leaves_end_block INTEGER,"
  137600. "end_block INTEGER,"
  137601. "root BLOB,"
  137602. "PRIMARY KEY(level, idx)"
  137603. ");",
  137604. p->zDb, p->zName
  137605. );
  137606. if( p->bHasDocsize ){
  137607. fts3DbExec(&rc, db,
  137608. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  137609. p->zDb, p->zName
  137610. );
  137611. }
  137612. assert( p->bHasStat==p->bFts4 );
  137613. if( p->bHasStat ){
  137614. sqlite3Fts3CreateStatTable(&rc, p);
  137615. }
  137616. return rc;
  137617. }
  137618. /*
  137619. ** Store the current database page-size in bytes in p->nPgsz.
  137620. **
  137621. ** If *pRc is non-zero when this function is called, it is a no-op.
  137622. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  137623. ** before returning.
  137624. */
  137625. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  137626. if( *pRc==SQLITE_OK ){
  137627. int rc; /* Return code */
  137628. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  137629. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  137630. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  137631. if( !zSql ){
  137632. rc = SQLITE_NOMEM;
  137633. }else{
  137634. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  137635. if( rc==SQLITE_OK ){
  137636. sqlite3_step(pStmt);
  137637. p->nPgsz = sqlite3_column_int(pStmt, 0);
  137638. rc = sqlite3_finalize(pStmt);
  137639. }else if( rc==SQLITE_AUTH ){
  137640. p->nPgsz = 1024;
  137641. rc = SQLITE_OK;
  137642. }
  137643. }
  137644. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  137645. sqlite3_free(zSql);
  137646. *pRc = rc;
  137647. }
  137648. }
  137649. /*
  137650. ** "Special" FTS4 arguments are column specifications of the following form:
  137651. **
  137652. ** <key> = <value>
  137653. **
  137654. ** There may not be whitespace surrounding the "=" character. The <value>
  137655. ** term may be quoted, but the <key> may not.
  137656. */
  137657. static int fts3IsSpecialColumn(
  137658. const char *z,
  137659. int *pnKey,
  137660. char **pzValue
  137661. ){
  137662. char *zValue;
  137663. const char *zCsr = z;
  137664. while( *zCsr!='=' ){
  137665. if( *zCsr=='\0' ) return 0;
  137666. zCsr++;
  137667. }
  137668. *pnKey = (int)(zCsr-z);
  137669. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  137670. if( zValue ){
  137671. sqlite3Fts3Dequote(zValue);
  137672. }
  137673. *pzValue = zValue;
  137674. return 1;
  137675. }
  137676. /*
  137677. ** Append the output of a printf() style formatting to an existing string.
  137678. */
  137679. static void fts3Appendf(
  137680. int *pRc, /* IN/OUT: Error code */
  137681. char **pz, /* IN/OUT: Pointer to string buffer */
  137682. const char *zFormat, /* Printf format string to append */
  137683. ... /* Arguments for printf format string */
  137684. ){
  137685. if( *pRc==SQLITE_OK ){
  137686. va_list ap;
  137687. char *z;
  137688. va_start(ap, zFormat);
  137689. z = sqlite3_vmprintf(zFormat, ap);
  137690. va_end(ap);
  137691. if( z && *pz ){
  137692. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  137693. sqlite3_free(z);
  137694. z = z2;
  137695. }
  137696. if( z==0 ) *pRc = SQLITE_NOMEM;
  137697. sqlite3_free(*pz);
  137698. *pz = z;
  137699. }
  137700. }
  137701. /*
  137702. ** Return a copy of input string zInput enclosed in double-quotes (") and
  137703. ** with all double quote characters escaped. For example:
  137704. **
  137705. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  137706. **
  137707. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  137708. ** is the callers responsibility to call sqlite3_free() to release this
  137709. ** memory.
  137710. */
  137711. static char *fts3QuoteId(char const *zInput){
  137712. int nRet;
  137713. char *zRet;
  137714. nRet = 2 + (int)strlen(zInput)*2 + 1;
  137715. zRet = sqlite3_malloc(nRet);
  137716. if( zRet ){
  137717. int i;
  137718. char *z = zRet;
  137719. *(z++) = '"';
  137720. for(i=0; zInput[i]; i++){
  137721. if( zInput[i]=='"' ) *(z++) = '"';
  137722. *(z++) = zInput[i];
  137723. }
  137724. *(z++) = '"';
  137725. *(z++) = '\0';
  137726. }
  137727. return zRet;
  137728. }
  137729. /*
  137730. ** Return a list of comma separated SQL expressions and a FROM clause that
  137731. ** could be used in a SELECT statement such as the following:
  137732. **
  137733. ** SELECT <list of expressions> FROM %_content AS x ...
  137734. **
  137735. ** to return the docid, followed by each column of text data in order
  137736. ** from left to write. If parameter zFunc is not NULL, then instead of
  137737. ** being returned directly each column of text data is passed to an SQL
  137738. ** function named zFunc first. For example, if zFunc is "unzip" and the
  137739. ** table has the three user-defined columns "a", "b", and "c", the following
  137740. ** string is returned:
  137741. **
  137742. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  137743. **
  137744. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  137745. ** is the responsibility of the caller to eventually free it.
  137746. **
  137747. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  137748. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  137749. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  137750. ** no error occurs, *pRc is left unmodified.
  137751. */
  137752. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  137753. char *zRet = 0;
  137754. char *zFree = 0;
  137755. char *zFunction;
  137756. int i;
  137757. if( p->zContentTbl==0 ){
  137758. if( !zFunc ){
  137759. zFunction = "";
  137760. }else{
  137761. zFree = zFunction = fts3QuoteId(zFunc);
  137762. }
  137763. fts3Appendf(pRc, &zRet, "docid");
  137764. for(i=0; i<p->nColumn; i++){
  137765. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  137766. }
  137767. if( p->zLanguageid ){
  137768. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  137769. }
  137770. sqlite3_free(zFree);
  137771. }else{
  137772. fts3Appendf(pRc, &zRet, "rowid");
  137773. for(i=0; i<p->nColumn; i++){
  137774. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  137775. }
  137776. if( p->zLanguageid ){
  137777. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  137778. }
  137779. }
  137780. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  137781. p->zDb,
  137782. (p->zContentTbl ? p->zContentTbl : p->zName),
  137783. (p->zContentTbl ? "" : "_content")
  137784. );
  137785. return zRet;
  137786. }
  137787. /*
  137788. ** Return a list of N comma separated question marks, where N is the number
  137789. ** of columns in the %_content table (one for the docid plus one for each
  137790. ** user-defined text column).
  137791. **
  137792. ** If argument zFunc is not NULL, then all but the first question mark
  137793. ** is preceded by zFunc and an open bracket, and followed by a closed
  137794. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  137795. ** user-defined text columns, the following string is returned:
  137796. **
  137797. ** "?, zip(?), zip(?), zip(?)"
  137798. **
  137799. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  137800. ** is the responsibility of the caller to eventually free it.
  137801. **
  137802. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  137803. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  137804. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  137805. ** no error occurs, *pRc is left unmodified.
  137806. */
  137807. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  137808. char *zRet = 0;
  137809. char *zFree = 0;
  137810. char *zFunction;
  137811. int i;
  137812. if( !zFunc ){
  137813. zFunction = "";
  137814. }else{
  137815. zFree = zFunction = fts3QuoteId(zFunc);
  137816. }
  137817. fts3Appendf(pRc, &zRet, "?");
  137818. for(i=0; i<p->nColumn; i++){
  137819. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  137820. }
  137821. if( p->zLanguageid ){
  137822. fts3Appendf(pRc, &zRet, ", ?");
  137823. }
  137824. sqlite3_free(zFree);
  137825. return zRet;
  137826. }
  137827. /*
  137828. ** This function interprets the string at (*pp) as a non-negative integer
  137829. ** value. It reads the integer and sets *pnOut to the value read, then
  137830. ** sets *pp to point to the byte immediately following the last byte of
  137831. ** the integer value.
  137832. **
  137833. ** Only decimal digits ('0'..'9') may be part of an integer value.
  137834. **
  137835. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  137836. ** the output value undefined. Otherwise SQLITE_OK is returned.
  137837. **
  137838. ** This function is used when parsing the "prefix=" FTS4 parameter.
  137839. */
  137840. static int fts3GobbleInt(const char **pp, int *pnOut){
  137841. const int MAX_NPREFIX = 10000000;
  137842. const char *p; /* Iterator pointer */
  137843. int nInt = 0; /* Output value */
  137844. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  137845. nInt = nInt * 10 + (p[0] - '0');
  137846. if( nInt>MAX_NPREFIX ){
  137847. nInt = 0;
  137848. break;
  137849. }
  137850. }
  137851. if( p==*pp ) return SQLITE_ERROR;
  137852. *pnOut = nInt;
  137853. *pp = p;
  137854. return SQLITE_OK;
  137855. }
  137856. /*
  137857. ** This function is called to allocate an array of Fts3Index structures
  137858. ** representing the indexes maintained by the current FTS table. FTS tables
  137859. ** always maintain the main "terms" index, but may also maintain one or
  137860. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  137861. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  137862. **
  137863. ** Argument zParam is passed the value of the "prefix=" option if one was
  137864. ** specified, or NULL otherwise.
  137865. **
  137866. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  137867. ** the allocated array. *pnIndex is set to the number of elements in the
  137868. ** array. If an error does occur, an SQLite error code is returned.
  137869. **
  137870. ** Regardless of whether or not an error is returned, it is the responsibility
  137871. ** of the caller to call sqlite3_free() on the output array to free it.
  137872. */
  137873. static int fts3PrefixParameter(
  137874. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  137875. int *pnIndex, /* OUT: size of *apIndex[] array */
  137876. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  137877. ){
  137878. struct Fts3Index *aIndex; /* Allocated array */
  137879. int nIndex = 1; /* Number of entries in array */
  137880. if( zParam && zParam[0] ){
  137881. const char *p;
  137882. nIndex++;
  137883. for(p=zParam; *p; p++){
  137884. if( *p==',' ) nIndex++;
  137885. }
  137886. }
  137887. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  137888. *apIndex = aIndex;
  137889. if( !aIndex ){
  137890. return SQLITE_NOMEM;
  137891. }
  137892. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  137893. if( zParam ){
  137894. const char *p = zParam;
  137895. int i;
  137896. for(i=1; i<nIndex; i++){
  137897. int nPrefix = 0;
  137898. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  137899. assert( nPrefix>=0 );
  137900. if( nPrefix==0 ){
  137901. nIndex--;
  137902. i--;
  137903. }else{
  137904. aIndex[i].nPrefix = nPrefix;
  137905. }
  137906. p++;
  137907. }
  137908. }
  137909. *pnIndex = nIndex;
  137910. return SQLITE_OK;
  137911. }
  137912. /*
  137913. ** This function is called when initializing an FTS4 table that uses the
  137914. ** content=xxx option. It determines the number of and names of the columns
  137915. ** of the new FTS4 table.
  137916. **
  137917. ** The third argument passed to this function is the value passed to the
  137918. ** config=xxx option (i.e. "xxx"). This function queries the database for
  137919. ** a table of that name. If found, the output variables are populated
  137920. ** as follows:
  137921. **
  137922. ** *pnCol: Set to the number of columns table xxx has,
  137923. **
  137924. ** *pnStr: Set to the total amount of space required to store a copy
  137925. ** of each columns name, including the nul-terminator.
  137926. **
  137927. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  137928. ** the name of the corresponding column in table xxx. The array
  137929. ** and its contents are allocated using a single allocation. It
  137930. ** is the responsibility of the caller to free this allocation
  137931. ** by eventually passing the *pazCol value to sqlite3_free().
  137932. **
  137933. ** If the table cannot be found, an error code is returned and the output
  137934. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  137935. ** returned (and the output variables are undefined).
  137936. */
  137937. static int fts3ContentColumns(
  137938. sqlite3 *db, /* Database handle */
  137939. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  137940. const char *zTbl, /* Name of content table */
  137941. const char ***pazCol, /* OUT: Malloc'd array of column names */
  137942. int *pnCol, /* OUT: Size of array *pazCol */
  137943. int *pnStr, /* OUT: Bytes of string content */
  137944. char **pzErr /* OUT: error message */
  137945. ){
  137946. int rc = SQLITE_OK; /* Return code */
  137947. char *zSql; /* "SELECT *" statement on zTbl */
  137948. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  137949. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  137950. if( !zSql ){
  137951. rc = SQLITE_NOMEM;
  137952. }else{
  137953. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  137954. if( rc!=SQLITE_OK ){
  137955. sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
  137956. }
  137957. }
  137958. sqlite3_free(zSql);
  137959. if( rc==SQLITE_OK ){
  137960. const char **azCol; /* Output array */
  137961. int nStr = 0; /* Size of all column names (incl. 0x00) */
  137962. int nCol; /* Number of table columns */
  137963. int i; /* Used to iterate through columns */
  137964. /* Loop through the returned columns. Set nStr to the number of bytes of
  137965. ** space required to store a copy of each column name, including the
  137966. ** nul-terminator byte. */
  137967. nCol = sqlite3_column_count(pStmt);
  137968. for(i=0; i<nCol; i++){
  137969. const char *zCol = sqlite3_column_name(pStmt, i);
  137970. nStr += (int)strlen(zCol) + 1;
  137971. }
  137972. /* Allocate and populate the array to return. */
  137973. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  137974. if( azCol==0 ){
  137975. rc = SQLITE_NOMEM;
  137976. }else{
  137977. char *p = (char *)&azCol[nCol];
  137978. for(i=0; i<nCol; i++){
  137979. const char *zCol = sqlite3_column_name(pStmt, i);
  137980. int n = (int)strlen(zCol)+1;
  137981. memcpy(p, zCol, n);
  137982. azCol[i] = p;
  137983. p += n;
  137984. }
  137985. }
  137986. sqlite3_finalize(pStmt);
  137987. /* Set the output variables. */
  137988. *pnCol = nCol;
  137989. *pnStr = nStr;
  137990. *pazCol = azCol;
  137991. }
  137992. return rc;
  137993. }
  137994. /*
  137995. ** This function is the implementation of both the xConnect and xCreate
  137996. ** methods of the FTS3 virtual table.
  137997. **
  137998. ** The argv[] array contains the following:
  137999. **
  138000. ** argv[0] -> module name ("fts3" or "fts4")
  138001. ** argv[1] -> database name
  138002. ** argv[2] -> table name
  138003. ** argv[...] -> "column name" and other module argument fields.
  138004. */
  138005. static int fts3InitVtab(
  138006. int isCreate, /* True for xCreate, false for xConnect */
  138007. sqlite3 *db, /* The SQLite database connection */
  138008. void *pAux, /* Hash table containing tokenizers */
  138009. int argc, /* Number of elements in argv array */
  138010. const char * const *argv, /* xCreate/xConnect argument array */
  138011. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  138012. char **pzErr /* Write any error message here */
  138013. ){
  138014. Fts3Hash *pHash = (Fts3Hash *)pAux;
  138015. Fts3Table *p = 0; /* Pointer to allocated vtab */
  138016. int rc = SQLITE_OK; /* Return code */
  138017. int i; /* Iterator variable */
  138018. int nByte; /* Size of allocation used for *p */
  138019. int iCol; /* Column index */
  138020. int nString = 0; /* Bytes required to hold all column names */
  138021. int nCol = 0; /* Number of columns in the FTS table */
  138022. char *zCsr; /* Space for holding column names */
  138023. int nDb; /* Bytes required to hold database name */
  138024. int nName; /* Bytes required to hold table name */
  138025. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  138026. const char **aCol; /* Array of column names */
  138027. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  138028. int nIndex = 0; /* Size of aIndex[] array */
  138029. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  138030. /* The results of parsing supported FTS4 key=value options: */
  138031. int bNoDocsize = 0; /* True to omit %_docsize table */
  138032. int bDescIdx = 0; /* True to store descending indexes */
  138033. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  138034. char *zCompress = 0; /* compress=? parameter (or NULL) */
  138035. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  138036. char *zContent = 0; /* content=? parameter (or NULL) */
  138037. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  138038. char **azNotindexed = 0; /* The set of notindexed= columns */
  138039. int nNotindexed = 0; /* Size of azNotindexed[] array */
  138040. assert( strlen(argv[0])==4 );
  138041. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  138042. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  138043. );
  138044. nDb = (int)strlen(argv[1]) + 1;
  138045. nName = (int)strlen(argv[2]) + 1;
  138046. nByte = sizeof(const char *) * (argc-2);
  138047. aCol = (const char **)sqlite3_malloc(nByte);
  138048. if( aCol ){
  138049. memset((void*)aCol, 0, nByte);
  138050. azNotindexed = (char **)sqlite3_malloc(nByte);
  138051. }
  138052. if( azNotindexed ){
  138053. memset(azNotindexed, 0, nByte);
  138054. }
  138055. if( !aCol || !azNotindexed ){
  138056. rc = SQLITE_NOMEM;
  138057. goto fts3_init_out;
  138058. }
  138059. /* Loop through all of the arguments passed by the user to the FTS3/4
  138060. ** module (i.e. all the column names and special arguments). This loop
  138061. ** does the following:
  138062. **
  138063. ** + Figures out the number of columns the FTSX table will have, and
  138064. ** the number of bytes of space that must be allocated to store copies
  138065. ** of the column names.
  138066. **
  138067. ** + If there is a tokenizer specification included in the arguments,
  138068. ** initializes the tokenizer pTokenizer.
  138069. */
  138070. for(i=3; rc==SQLITE_OK && i<argc; i++){
  138071. char const *z = argv[i];
  138072. int nKey;
  138073. char *zVal;
  138074. /* Check if this is a tokenizer specification */
  138075. if( !pTokenizer
  138076. && strlen(z)>8
  138077. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  138078. && 0==sqlite3Fts3IsIdChar(z[8])
  138079. ){
  138080. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  138081. }
  138082. /* Check if it is an FTS4 special argument. */
  138083. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  138084. struct Fts4Option {
  138085. const char *zOpt;
  138086. int nOpt;
  138087. } aFts4Opt[] = {
  138088. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  138089. { "prefix", 6 }, /* 1 -> PREFIX */
  138090. { "compress", 8 }, /* 2 -> COMPRESS */
  138091. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  138092. { "order", 5 }, /* 4 -> ORDER */
  138093. { "content", 7 }, /* 5 -> CONTENT */
  138094. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  138095. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  138096. };
  138097. int iOpt;
  138098. if( !zVal ){
  138099. rc = SQLITE_NOMEM;
  138100. }else{
  138101. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  138102. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  138103. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  138104. break;
  138105. }
  138106. }
  138107. switch( iOpt ){
  138108. case 0: /* MATCHINFO */
  138109. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  138110. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
  138111. rc = SQLITE_ERROR;
  138112. }
  138113. bNoDocsize = 1;
  138114. break;
  138115. case 1: /* PREFIX */
  138116. sqlite3_free(zPrefix);
  138117. zPrefix = zVal;
  138118. zVal = 0;
  138119. break;
  138120. case 2: /* COMPRESS */
  138121. sqlite3_free(zCompress);
  138122. zCompress = zVal;
  138123. zVal = 0;
  138124. break;
  138125. case 3: /* UNCOMPRESS */
  138126. sqlite3_free(zUncompress);
  138127. zUncompress = zVal;
  138128. zVal = 0;
  138129. break;
  138130. case 4: /* ORDER */
  138131. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  138132. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  138133. ){
  138134. sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
  138135. rc = SQLITE_ERROR;
  138136. }
  138137. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  138138. break;
  138139. case 5: /* CONTENT */
  138140. sqlite3_free(zContent);
  138141. zContent = zVal;
  138142. zVal = 0;
  138143. break;
  138144. case 6: /* LANGUAGEID */
  138145. assert( iOpt==6 );
  138146. sqlite3_free(zLanguageid);
  138147. zLanguageid = zVal;
  138148. zVal = 0;
  138149. break;
  138150. case 7: /* NOTINDEXED */
  138151. azNotindexed[nNotindexed++] = zVal;
  138152. zVal = 0;
  138153. break;
  138154. default:
  138155. assert( iOpt==SizeofArray(aFts4Opt) );
  138156. sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
  138157. rc = SQLITE_ERROR;
  138158. break;
  138159. }
  138160. sqlite3_free(zVal);
  138161. }
  138162. }
  138163. /* Otherwise, the argument is a column name. */
  138164. else {
  138165. nString += (int)(strlen(z) + 1);
  138166. aCol[nCol++] = z;
  138167. }
  138168. }
  138169. /* If a content=xxx option was specified, the following:
  138170. **
  138171. ** 1. Ignore any compress= and uncompress= options.
  138172. **
  138173. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  138174. ** TABLE statement, use all columns from the content table.
  138175. */
  138176. if( rc==SQLITE_OK && zContent ){
  138177. sqlite3_free(zCompress);
  138178. sqlite3_free(zUncompress);
  138179. zCompress = 0;
  138180. zUncompress = 0;
  138181. if( nCol==0 ){
  138182. sqlite3_free((void*)aCol);
  138183. aCol = 0;
  138184. rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
  138185. /* If a languageid= option was specified, remove the language id
  138186. ** column from the aCol[] array. */
  138187. if( rc==SQLITE_OK && zLanguageid ){
  138188. int j;
  138189. for(j=0; j<nCol; j++){
  138190. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  138191. int k;
  138192. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  138193. nCol--;
  138194. break;
  138195. }
  138196. }
  138197. }
  138198. }
  138199. }
  138200. if( rc!=SQLITE_OK ) goto fts3_init_out;
  138201. if( nCol==0 ){
  138202. assert( nString==0 );
  138203. aCol[0] = "content";
  138204. nString = 8;
  138205. nCol = 1;
  138206. }
  138207. if( pTokenizer==0 ){
  138208. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  138209. if( rc!=SQLITE_OK ) goto fts3_init_out;
  138210. }
  138211. assert( pTokenizer );
  138212. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  138213. if( rc==SQLITE_ERROR ){
  138214. assert( zPrefix );
  138215. sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
  138216. }
  138217. if( rc!=SQLITE_OK ) goto fts3_init_out;
  138218. /* Allocate and populate the Fts3Table structure. */
  138219. nByte = sizeof(Fts3Table) + /* Fts3Table */
  138220. nCol * sizeof(char *) + /* azColumn */
  138221. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  138222. nCol * sizeof(u8) + /* abNotindexed */
  138223. nName + /* zName */
  138224. nDb + /* zDb */
  138225. nString; /* Space for azColumn strings */
  138226. p = (Fts3Table*)sqlite3_malloc(nByte);
  138227. if( p==0 ){
  138228. rc = SQLITE_NOMEM;
  138229. goto fts3_init_out;
  138230. }
  138231. memset(p, 0, nByte);
  138232. p->db = db;
  138233. p->nColumn = nCol;
  138234. p->nPendingData = 0;
  138235. p->azColumn = (char **)&p[1];
  138236. p->pTokenizer = pTokenizer;
  138237. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  138238. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  138239. p->bHasStat = (u8)isFts4;
  138240. p->bFts4 = (u8)isFts4;
  138241. p->bDescIdx = (u8)bDescIdx;
  138242. p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
  138243. p->zContentTbl = zContent;
  138244. p->zLanguageid = zLanguageid;
  138245. zContent = 0;
  138246. zLanguageid = 0;
  138247. TESTONLY( p->inTransaction = -1 );
  138248. TESTONLY( p->mxSavepoint = -1 );
  138249. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  138250. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  138251. p->nIndex = nIndex;
  138252. for(i=0; i<nIndex; i++){
  138253. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  138254. }
  138255. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  138256. /* Fill in the zName and zDb fields of the vtab structure. */
  138257. zCsr = (char *)&p->abNotindexed[nCol];
  138258. p->zName = zCsr;
  138259. memcpy(zCsr, argv[2], nName);
  138260. zCsr += nName;
  138261. p->zDb = zCsr;
  138262. memcpy(zCsr, argv[1], nDb);
  138263. zCsr += nDb;
  138264. /* Fill in the azColumn array */
  138265. for(iCol=0; iCol<nCol; iCol++){
  138266. char *z;
  138267. int n = 0;
  138268. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  138269. if( n>0 ){
  138270. memcpy(zCsr, z, n);
  138271. }
  138272. zCsr[n] = '\0';
  138273. sqlite3Fts3Dequote(zCsr);
  138274. p->azColumn[iCol] = zCsr;
  138275. zCsr += n+1;
  138276. assert( zCsr <= &((char *)p)[nByte] );
  138277. }
  138278. /* Fill in the abNotindexed array */
  138279. for(iCol=0; iCol<nCol; iCol++){
  138280. int n = (int)strlen(p->azColumn[iCol]);
  138281. for(i=0; i<nNotindexed; i++){
  138282. char *zNot = azNotindexed[i];
  138283. if( zNot && n==(int)strlen(zNot)
  138284. && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
  138285. ){
  138286. p->abNotindexed[iCol] = 1;
  138287. sqlite3_free(zNot);
  138288. azNotindexed[i] = 0;
  138289. }
  138290. }
  138291. }
  138292. for(i=0; i<nNotindexed; i++){
  138293. if( azNotindexed[i] ){
  138294. sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
  138295. rc = SQLITE_ERROR;
  138296. }
  138297. }
  138298. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  138299. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  138300. rc = SQLITE_ERROR;
  138301. sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
  138302. }
  138303. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  138304. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  138305. if( rc!=SQLITE_OK ) goto fts3_init_out;
  138306. /* If this is an xCreate call, create the underlying tables in the
  138307. ** database. TODO: For xConnect(), it could verify that said tables exist.
  138308. */
  138309. if( isCreate ){
  138310. rc = fts3CreateTables(p);
  138311. }
  138312. /* Check to see if a legacy fts3 table has been "upgraded" by the
  138313. ** addition of a %_stat table so that it can use incremental merge.
  138314. */
  138315. if( !isFts4 && !isCreate ){
  138316. p->bHasStat = 2;
  138317. }
  138318. /* Figure out the page-size for the database. This is required in order to
  138319. ** estimate the cost of loading large doclists from the database. */
  138320. fts3DatabasePageSize(&rc, p);
  138321. p->nNodeSize = p->nPgsz-35;
  138322. /* Declare the table schema to SQLite. */
  138323. fts3DeclareVtab(&rc, p);
  138324. fts3_init_out:
  138325. sqlite3_free(zPrefix);
  138326. sqlite3_free(aIndex);
  138327. sqlite3_free(zCompress);
  138328. sqlite3_free(zUncompress);
  138329. sqlite3_free(zContent);
  138330. sqlite3_free(zLanguageid);
  138331. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  138332. sqlite3_free((void *)aCol);
  138333. sqlite3_free((void *)azNotindexed);
  138334. if( rc!=SQLITE_OK ){
  138335. if( p ){
  138336. fts3DisconnectMethod((sqlite3_vtab *)p);
  138337. }else if( pTokenizer ){
  138338. pTokenizer->pModule->xDestroy(pTokenizer);
  138339. }
  138340. }else{
  138341. assert( p->pSegments==0 );
  138342. *ppVTab = &p->base;
  138343. }
  138344. return rc;
  138345. }
  138346. /*
  138347. ** The xConnect() and xCreate() methods for the virtual table. All the
  138348. ** work is done in function fts3InitVtab().
  138349. */
  138350. static int fts3ConnectMethod(
  138351. sqlite3 *db, /* Database connection */
  138352. void *pAux, /* Pointer to tokenizer hash table */
  138353. int argc, /* Number of elements in argv array */
  138354. const char * const *argv, /* xCreate/xConnect argument array */
  138355. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  138356. char **pzErr /* OUT: sqlite3_malloc'd error message */
  138357. ){
  138358. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  138359. }
  138360. static int fts3CreateMethod(
  138361. sqlite3 *db, /* Database connection */
  138362. void *pAux, /* Pointer to tokenizer hash table */
  138363. int argc, /* Number of elements in argv array */
  138364. const char * const *argv, /* xCreate/xConnect argument array */
  138365. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  138366. char **pzErr /* OUT: sqlite3_malloc'd error message */
  138367. ){
  138368. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  138369. }
  138370. /*
  138371. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  138372. ** extension is currently being used by a version of SQLite too old to
  138373. ** support estimatedRows. In that case this function is a no-op.
  138374. */
  138375. static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  138376. #if SQLITE_VERSION_NUMBER>=3008002
  138377. if( sqlite3_libversion_number()>=3008002 ){
  138378. pIdxInfo->estimatedRows = nRow;
  138379. }
  138380. #endif
  138381. }
  138382. /*
  138383. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  138384. ** extension is currently being used by a version of SQLite too old to
  138385. ** support index-info flags. In that case this function is a no-op.
  138386. */
  138387. static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  138388. #if SQLITE_VERSION_NUMBER>=3008012
  138389. if( sqlite3_libversion_number()>=3008012 ){
  138390. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  138391. }
  138392. #endif
  138393. }
  138394. /*
  138395. ** Implementation of the xBestIndex method for FTS3 tables. There
  138396. ** are three possible strategies, in order of preference:
  138397. **
  138398. ** 1. Direct lookup by rowid or docid.
  138399. ** 2. Full-text search using a MATCH operator on a non-docid column.
  138400. ** 3. Linear scan of %_content table.
  138401. */
  138402. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  138403. Fts3Table *p = (Fts3Table *)pVTab;
  138404. int i; /* Iterator variable */
  138405. int iCons = -1; /* Index of constraint to use */
  138406. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  138407. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  138408. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  138409. int iIdx;
  138410. /* By default use a full table scan. This is an expensive option,
  138411. ** so search through the constraints to see if a more efficient
  138412. ** strategy is possible.
  138413. */
  138414. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  138415. pInfo->estimatedCost = 5000000;
  138416. for(i=0; i<pInfo->nConstraint; i++){
  138417. int bDocid; /* True if this constraint is on docid */
  138418. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  138419. if( pCons->usable==0 ){
  138420. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  138421. /* There exists an unusable MATCH constraint. This means that if
  138422. ** the planner does elect to use the results of this call as part
  138423. ** of the overall query plan the user will see an "unable to use
  138424. ** function MATCH in the requested context" error. To discourage
  138425. ** this, return a very high cost here. */
  138426. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  138427. pInfo->estimatedCost = 1e50;
  138428. fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
  138429. return SQLITE_OK;
  138430. }
  138431. continue;
  138432. }
  138433. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  138434. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  138435. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  138436. pInfo->idxNum = FTS3_DOCID_SEARCH;
  138437. pInfo->estimatedCost = 1.0;
  138438. iCons = i;
  138439. }
  138440. /* A MATCH constraint. Use a full-text search.
  138441. **
  138442. ** If there is more than one MATCH constraint available, use the first
  138443. ** one encountered. If there is both a MATCH constraint and a direct
  138444. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  138445. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  138446. ** it would lead to an "unable to use function MATCH in the requested
  138447. ** context" error.
  138448. */
  138449. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  138450. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  138451. ){
  138452. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  138453. pInfo->estimatedCost = 2.0;
  138454. iCons = i;
  138455. }
  138456. /* Equality constraint on the langid column */
  138457. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  138458. && pCons->iColumn==p->nColumn + 2
  138459. ){
  138460. iLangidCons = i;
  138461. }
  138462. if( bDocid ){
  138463. switch( pCons->op ){
  138464. case SQLITE_INDEX_CONSTRAINT_GE:
  138465. case SQLITE_INDEX_CONSTRAINT_GT:
  138466. iDocidGe = i;
  138467. break;
  138468. case SQLITE_INDEX_CONSTRAINT_LE:
  138469. case SQLITE_INDEX_CONSTRAINT_LT:
  138470. iDocidLe = i;
  138471. break;
  138472. }
  138473. }
  138474. }
  138475. /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
  138476. if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
  138477. iIdx = 1;
  138478. if( iCons>=0 ){
  138479. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  138480. pInfo->aConstraintUsage[iCons].omit = 1;
  138481. }
  138482. if( iLangidCons>=0 ){
  138483. pInfo->idxNum |= FTS3_HAVE_LANGID;
  138484. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  138485. }
  138486. if( iDocidGe>=0 ){
  138487. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  138488. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  138489. }
  138490. if( iDocidLe>=0 ){
  138491. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  138492. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  138493. }
  138494. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  138495. ** docid) order. Both ascending and descending are possible.
  138496. */
  138497. if( pInfo->nOrderBy==1 ){
  138498. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  138499. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  138500. if( pOrder->desc ){
  138501. pInfo->idxStr = "DESC";
  138502. }else{
  138503. pInfo->idxStr = "ASC";
  138504. }
  138505. pInfo->orderByConsumed = 1;
  138506. }
  138507. }
  138508. assert( p->pSegments==0 );
  138509. return SQLITE_OK;
  138510. }
  138511. /*
  138512. ** Implementation of xOpen method.
  138513. */
  138514. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  138515. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  138516. UNUSED_PARAMETER(pVTab);
  138517. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  138518. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  138519. ** if the allocation fails, return SQLITE_NOMEM.
  138520. */
  138521. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  138522. if( !pCsr ){
  138523. return SQLITE_NOMEM;
  138524. }
  138525. memset(pCsr, 0, sizeof(Fts3Cursor));
  138526. return SQLITE_OK;
  138527. }
  138528. /*
  138529. ** Finalize the statement handle at pCsr->pStmt.
  138530. **
  138531. ** Or, if that statement handle is one created by fts3CursorSeekStmt(),
  138532. ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
  138533. ** pointer there instead of finalizing it.
  138534. */
  138535. static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
  138536. if( pCsr->bSeekStmt ){
  138537. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  138538. if( p->pSeekStmt==0 ){
  138539. p->pSeekStmt = pCsr->pStmt;
  138540. sqlite3_reset(pCsr->pStmt);
  138541. pCsr->pStmt = 0;
  138542. }
  138543. pCsr->bSeekStmt = 0;
  138544. }
  138545. sqlite3_finalize(pCsr->pStmt);
  138546. }
  138547. /*
  138548. ** Close the cursor. For additional information see the documentation
  138549. ** on the xClose method of the virtual table interface.
  138550. */
  138551. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  138552. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  138553. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  138554. fts3CursorFinalizeStmt(pCsr);
  138555. sqlite3Fts3ExprFree(pCsr->pExpr);
  138556. sqlite3Fts3FreeDeferredTokens(pCsr);
  138557. sqlite3_free(pCsr->aDoclist);
  138558. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  138559. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  138560. sqlite3_free(pCsr);
  138561. return SQLITE_OK;
  138562. }
  138563. /*
  138564. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  138565. ** compose and prepare an SQL statement of the form:
  138566. **
  138567. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  138568. **
  138569. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  138570. ** it. If an error occurs, return an SQLite error code.
  138571. */
  138572. static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
  138573. int rc = SQLITE_OK;
  138574. if( pCsr->pStmt==0 ){
  138575. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  138576. char *zSql;
  138577. if( p->pSeekStmt ){
  138578. pCsr->pStmt = p->pSeekStmt;
  138579. p->pSeekStmt = 0;
  138580. }else{
  138581. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  138582. if( !zSql ) return SQLITE_NOMEM;
  138583. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  138584. sqlite3_free(zSql);
  138585. }
  138586. if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
  138587. }
  138588. return rc;
  138589. }
  138590. /*
  138591. ** Position the pCsr->pStmt statement so that it is on the row
  138592. ** of the %_content table that contains the last match. Return
  138593. ** SQLITE_OK on success.
  138594. */
  138595. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  138596. int rc = SQLITE_OK;
  138597. if( pCsr->isRequireSeek ){
  138598. rc = fts3CursorSeekStmt(pCsr);
  138599. if( rc==SQLITE_OK ){
  138600. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  138601. pCsr->isRequireSeek = 0;
  138602. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  138603. return SQLITE_OK;
  138604. }else{
  138605. rc = sqlite3_reset(pCsr->pStmt);
  138606. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  138607. /* If no row was found and no error has occurred, then the %_content
  138608. ** table is missing a row that is present in the full-text index.
  138609. ** The data structures are corrupt. */
  138610. rc = FTS_CORRUPT_VTAB;
  138611. pCsr->isEof = 1;
  138612. }
  138613. }
  138614. }
  138615. }
  138616. if( rc!=SQLITE_OK && pContext ){
  138617. sqlite3_result_error_code(pContext, rc);
  138618. }
  138619. return rc;
  138620. }
  138621. /*
  138622. ** This function is used to process a single interior node when searching
  138623. ** a b-tree for a term or term prefix. The node data is passed to this
  138624. ** function via the zNode/nNode parameters. The term to search for is
  138625. ** passed in zTerm/nTerm.
  138626. **
  138627. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  138628. ** of the child node that heads the sub-tree that may contain the term.
  138629. **
  138630. ** If piLast is not NULL, then *piLast is set to the right-most child node
  138631. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  138632. ** a prefix.
  138633. **
  138634. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  138635. */
  138636. static int fts3ScanInteriorNode(
  138637. const char *zTerm, /* Term to select leaves for */
  138638. int nTerm, /* Size of term zTerm in bytes */
  138639. const char *zNode, /* Buffer containing segment interior node */
  138640. int nNode, /* Size of buffer at zNode */
  138641. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  138642. sqlite3_int64 *piLast /* OUT: Selected child node */
  138643. ){
  138644. int rc = SQLITE_OK; /* Return code */
  138645. const char *zCsr = zNode; /* Cursor to iterate through node */
  138646. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  138647. char *zBuffer = 0; /* Buffer to load terms into */
  138648. int nAlloc = 0; /* Size of allocated buffer */
  138649. int isFirstTerm = 1; /* True when processing first term on page */
  138650. sqlite3_int64 iChild; /* Block id of child node to descend to */
  138651. /* Skip over the 'height' varint that occurs at the start of every
  138652. ** interior node. Then load the blockid of the left-child of the b-tree
  138653. ** node into variable iChild.
  138654. **
  138655. ** Even if the data structure on disk is corrupted, this (reading two
  138656. ** varints from the buffer) does not risk an overread. If zNode is a
  138657. ** root node, then the buffer comes from a SELECT statement. SQLite does
  138658. ** not make this guarantee explicitly, but in practice there are always
  138659. ** either more than 20 bytes of allocated space following the nNode bytes of
  138660. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  138661. ** table, then there are always 20 bytes of zeroed padding following the
  138662. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  138663. */
  138664. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  138665. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  138666. if( zCsr>zEnd ){
  138667. return FTS_CORRUPT_VTAB;
  138668. }
  138669. while( zCsr<zEnd && (piFirst || piLast) ){
  138670. int cmp; /* memcmp() result */
  138671. int nSuffix; /* Size of term suffix */
  138672. int nPrefix = 0; /* Size of term prefix */
  138673. int nBuffer; /* Total term size */
  138674. /* Load the next term on the node into zBuffer. Use realloc() to expand
  138675. ** the size of zBuffer if required. */
  138676. if( !isFirstTerm ){
  138677. zCsr += fts3GetVarint32(zCsr, &nPrefix);
  138678. }
  138679. isFirstTerm = 0;
  138680. zCsr += fts3GetVarint32(zCsr, &nSuffix);
  138681. assert( nPrefix>=0 && nSuffix>=0 );
  138682. if( &zCsr[nSuffix]>zEnd ){
  138683. rc = FTS_CORRUPT_VTAB;
  138684. goto finish_scan;
  138685. }
  138686. if( nPrefix+nSuffix>nAlloc ){
  138687. char *zNew;
  138688. nAlloc = (nPrefix+nSuffix) * 2;
  138689. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  138690. if( !zNew ){
  138691. rc = SQLITE_NOMEM;
  138692. goto finish_scan;
  138693. }
  138694. zBuffer = zNew;
  138695. }
  138696. assert( zBuffer );
  138697. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  138698. nBuffer = nPrefix + nSuffix;
  138699. zCsr += nSuffix;
  138700. /* Compare the term we are searching for with the term just loaded from
  138701. ** the interior node. If the specified term is greater than or equal
  138702. ** to the term from the interior node, then all terms on the sub-tree
  138703. ** headed by node iChild are smaller than zTerm. No need to search
  138704. ** iChild.
  138705. **
  138706. ** If the interior node term is larger than the specified term, then
  138707. ** the tree headed by iChild may contain the specified term.
  138708. */
  138709. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  138710. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  138711. *piFirst = iChild;
  138712. piFirst = 0;
  138713. }
  138714. if( piLast && cmp<0 ){
  138715. *piLast = iChild;
  138716. piLast = 0;
  138717. }
  138718. iChild++;
  138719. };
  138720. if( piFirst ) *piFirst = iChild;
  138721. if( piLast ) *piLast = iChild;
  138722. finish_scan:
  138723. sqlite3_free(zBuffer);
  138724. return rc;
  138725. }
  138726. /*
  138727. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  138728. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  138729. ** contains a term. This function searches the sub-tree headed by the zNode
  138730. ** node for the range of leaf nodes that may contain the specified term
  138731. ** or terms for which the specified term is a prefix.
  138732. **
  138733. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  138734. ** left-most leaf node in the tree that may contain the specified term.
  138735. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  138736. ** right-most leaf node that may contain a term for which the specified
  138737. ** term is a prefix.
  138738. **
  138739. ** It is possible that the range of returned leaf nodes does not contain
  138740. ** the specified term or any terms for which it is a prefix. However, if the
  138741. ** segment does contain any such terms, they are stored within the identified
  138742. ** range. Because this function only inspects interior segment nodes (and
  138743. ** never loads leaf nodes into memory), it is not possible to be sure.
  138744. **
  138745. ** If an error occurs, an error code other than SQLITE_OK is returned.
  138746. */
  138747. static int fts3SelectLeaf(
  138748. Fts3Table *p, /* Virtual table handle */
  138749. const char *zTerm, /* Term to select leaves for */
  138750. int nTerm, /* Size of term zTerm in bytes */
  138751. const char *zNode, /* Buffer containing segment interior node */
  138752. int nNode, /* Size of buffer at zNode */
  138753. sqlite3_int64 *piLeaf, /* Selected leaf node */
  138754. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  138755. ){
  138756. int rc = SQLITE_OK; /* Return code */
  138757. int iHeight; /* Height of this node in tree */
  138758. assert( piLeaf || piLeaf2 );
  138759. fts3GetVarint32(zNode, &iHeight);
  138760. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  138761. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  138762. if( rc==SQLITE_OK && iHeight>1 ){
  138763. char *zBlob = 0; /* Blob read from %_segments table */
  138764. int nBlob = 0; /* Size of zBlob in bytes */
  138765. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  138766. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  138767. if( rc==SQLITE_OK ){
  138768. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  138769. }
  138770. sqlite3_free(zBlob);
  138771. piLeaf = 0;
  138772. zBlob = 0;
  138773. }
  138774. if( rc==SQLITE_OK ){
  138775. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  138776. }
  138777. if( rc==SQLITE_OK ){
  138778. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  138779. }
  138780. sqlite3_free(zBlob);
  138781. }
  138782. return rc;
  138783. }
  138784. /*
  138785. ** This function is used to create delta-encoded serialized lists of FTS3
  138786. ** varints. Each call to this function appends a single varint to a list.
  138787. */
  138788. static void fts3PutDeltaVarint(
  138789. char **pp, /* IN/OUT: Output pointer */
  138790. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  138791. sqlite3_int64 iVal /* Write this value to the list */
  138792. ){
  138793. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  138794. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  138795. *piPrev = iVal;
  138796. }
  138797. /*
  138798. ** When this function is called, *ppPoslist is assumed to point to the
  138799. ** start of a position-list. After it returns, *ppPoslist points to the
  138800. ** first byte after the position-list.
  138801. **
  138802. ** A position list is list of positions (delta encoded) and columns for
  138803. ** a single document record of a doclist. So, in other words, this
  138804. ** routine advances *ppPoslist so that it points to the next docid in
  138805. ** the doclist, or to the first byte past the end of the doclist.
  138806. **
  138807. ** If pp is not NULL, then the contents of the position list are copied
  138808. ** to *pp. *pp is set to point to the first byte past the last byte copied
  138809. ** before this function returns.
  138810. */
  138811. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  138812. char *pEnd = *ppPoslist;
  138813. char c = 0;
  138814. /* The end of a position list is marked by a zero encoded as an FTS3
  138815. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  138816. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  138817. ** of some other, multi-byte, value.
  138818. **
  138819. ** The following while-loop moves pEnd to point to the first byte that is not
  138820. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  138821. ** pEnd once more so that it points to the byte immediately following the
  138822. ** last byte in the position-list.
  138823. */
  138824. while( *pEnd | c ){
  138825. c = *pEnd++ & 0x80;
  138826. testcase( c!=0 && (*pEnd)==0 );
  138827. }
  138828. pEnd++; /* Advance past the POS_END terminator byte */
  138829. if( pp ){
  138830. int n = (int)(pEnd - *ppPoslist);
  138831. char *p = *pp;
  138832. memcpy(p, *ppPoslist, n);
  138833. p += n;
  138834. *pp = p;
  138835. }
  138836. *ppPoslist = pEnd;
  138837. }
  138838. /*
  138839. ** When this function is called, *ppPoslist is assumed to point to the
  138840. ** start of a column-list. After it returns, *ppPoslist points to the
  138841. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  138842. **
  138843. ** A column-list is list of delta-encoded positions for a single column
  138844. ** within a single document within a doclist.
  138845. **
  138846. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  138847. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  138848. ** the POS_COLUMN or POS_END that terminates the column-list.
  138849. **
  138850. ** If pp is not NULL, then the contents of the column-list are copied
  138851. ** to *pp. *pp is set to point to the first byte past the last byte copied
  138852. ** before this function returns. The POS_COLUMN or POS_END terminator
  138853. ** is not copied into *pp.
  138854. */
  138855. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  138856. char *pEnd = *ppPoslist;
  138857. char c = 0;
  138858. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  138859. ** not part of a multi-byte varint.
  138860. */
  138861. while( 0xFE & (*pEnd | c) ){
  138862. c = *pEnd++ & 0x80;
  138863. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  138864. }
  138865. if( pp ){
  138866. int n = (int)(pEnd - *ppPoslist);
  138867. char *p = *pp;
  138868. memcpy(p, *ppPoslist, n);
  138869. p += n;
  138870. *pp = p;
  138871. }
  138872. *ppPoslist = pEnd;
  138873. }
  138874. /*
  138875. ** Value used to signify the end of an position-list. This is safe because
  138876. ** it is not possible to have a document with 2^31 terms.
  138877. */
  138878. #define POSITION_LIST_END 0x7fffffff
  138879. /*
  138880. ** This function is used to help parse position-lists. When this function is
  138881. ** called, *pp may point to the start of the next varint in the position-list
  138882. ** being parsed, or it may point to 1 byte past the end of the position-list
  138883. ** (in which case **pp will be a terminator bytes POS_END (0) or
  138884. ** (1)).
  138885. **
  138886. ** If *pp points past the end of the current position-list, set *pi to
  138887. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  138888. ** increment the current value of *pi by the value read, and set *pp to
  138889. ** point to the next value before returning.
  138890. **
  138891. ** Before calling this routine *pi must be initialized to the value of
  138892. ** the previous position, or zero if we are reading the first position
  138893. ** in the position-list. Because positions are delta-encoded, the value
  138894. ** of the previous position is needed in order to compute the value of
  138895. ** the next position.
  138896. */
  138897. static void fts3ReadNextPos(
  138898. char **pp, /* IN/OUT: Pointer into position-list buffer */
  138899. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  138900. ){
  138901. if( (**pp)&0xFE ){
  138902. fts3GetDeltaVarint(pp, pi);
  138903. *pi -= 2;
  138904. }else{
  138905. *pi = POSITION_LIST_END;
  138906. }
  138907. }
  138908. /*
  138909. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  138910. ** the value of iCol encoded as a varint to *pp. This will start a new
  138911. ** column list.
  138912. **
  138913. ** Set *pp to point to the byte just after the last byte written before
  138914. ** returning (do not modify it if iCol==0). Return the total number of bytes
  138915. ** written (0 if iCol==0).
  138916. */
  138917. static int fts3PutColNumber(char **pp, int iCol){
  138918. int n = 0; /* Number of bytes written */
  138919. if( iCol ){
  138920. char *p = *pp; /* Output pointer */
  138921. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  138922. *p = 0x01;
  138923. *pp = &p[n];
  138924. }
  138925. return n;
  138926. }
  138927. /*
  138928. ** Compute the union of two position lists. The output written
  138929. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  138930. ** order and with any duplicates removed. All pointers are
  138931. ** updated appropriately. The caller is responsible for insuring
  138932. ** that there is enough space in *pp to hold the complete output.
  138933. */
  138934. static void fts3PoslistMerge(
  138935. char **pp, /* Output buffer */
  138936. char **pp1, /* Left input list */
  138937. char **pp2 /* Right input list */
  138938. ){
  138939. char *p = *pp;
  138940. char *p1 = *pp1;
  138941. char *p2 = *pp2;
  138942. while( *p1 || *p2 ){
  138943. int iCol1; /* The current column index in pp1 */
  138944. int iCol2; /* The current column index in pp2 */
  138945. if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
  138946. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  138947. else iCol1 = 0;
  138948. if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
  138949. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  138950. else iCol2 = 0;
  138951. if( iCol1==iCol2 ){
  138952. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  138953. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  138954. sqlite3_int64 iPrev = 0;
  138955. int n = fts3PutColNumber(&p, iCol1);
  138956. p1 += n;
  138957. p2 += n;
  138958. /* At this point, both p1 and p2 point to the start of column-lists
  138959. ** for the same column (the column with index iCol1 and iCol2).
  138960. ** A column-list is a list of non-negative delta-encoded varints, each
  138961. ** incremented by 2 before being stored. Each list is terminated by a
  138962. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  138963. ** and writes the results to buffer p. p is left pointing to the byte
  138964. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  138965. ** written to the output.
  138966. */
  138967. fts3GetDeltaVarint(&p1, &i1);
  138968. fts3GetDeltaVarint(&p2, &i2);
  138969. do {
  138970. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  138971. iPrev -= 2;
  138972. if( i1==i2 ){
  138973. fts3ReadNextPos(&p1, &i1);
  138974. fts3ReadNextPos(&p2, &i2);
  138975. }else if( i1<i2 ){
  138976. fts3ReadNextPos(&p1, &i1);
  138977. }else{
  138978. fts3ReadNextPos(&p2, &i2);
  138979. }
  138980. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  138981. }else if( iCol1<iCol2 ){
  138982. p1 += fts3PutColNumber(&p, iCol1);
  138983. fts3ColumnlistCopy(&p, &p1);
  138984. }else{
  138985. p2 += fts3PutColNumber(&p, iCol2);
  138986. fts3ColumnlistCopy(&p, &p2);
  138987. }
  138988. }
  138989. *p++ = POS_END;
  138990. *pp = p;
  138991. *pp1 = p1 + 1;
  138992. *pp2 = p2 + 1;
  138993. }
  138994. /*
  138995. ** This function is used to merge two position lists into one. When it is
  138996. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  138997. ** the part of a doclist that follows each document id. For example, if a row
  138998. ** contains:
  138999. **
  139000. ** 'a b c'|'x y z'|'a b b a'
  139001. **
  139002. ** Then the position list for this row for token 'b' would consist of:
  139003. **
  139004. ** 0x02 0x01 0x02 0x03 0x03 0x00
  139005. **
  139006. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  139007. ** byte following the 0x00 terminator of their respective position lists.
  139008. **
  139009. ** If isSaveLeft is 0, an entry is added to the output position list for
  139010. ** each position in *pp2 for which there exists one or more positions in
  139011. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  139012. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  139013. ** slots before it.
  139014. **
  139015. ** e.g. nToken==1 searches for adjacent positions.
  139016. */
  139017. static int fts3PoslistPhraseMerge(
  139018. char **pp, /* IN/OUT: Preallocated output buffer */
  139019. int nToken, /* Maximum difference in token positions */
  139020. int isSaveLeft, /* Save the left position */
  139021. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  139022. char **pp1, /* IN/OUT: Left input list */
  139023. char **pp2 /* IN/OUT: Right input list */
  139024. ){
  139025. char *p = *pp;
  139026. char *p1 = *pp1;
  139027. char *p2 = *pp2;
  139028. int iCol1 = 0;
  139029. int iCol2 = 0;
  139030. /* Never set both isSaveLeft and isExact for the same invocation. */
  139031. assert( isSaveLeft==0 || isExact==0 );
  139032. assert( p!=0 && *p1!=0 && *p2!=0 );
  139033. if( *p1==POS_COLUMN ){
  139034. p1++;
  139035. p1 += fts3GetVarint32(p1, &iCol1);
  139036. }
  139037. if( *p2==POS_COLUMN ){
  139038. p2++;
  139039. p2 += fts3GetVarint32(p2, &iCol2);
  139040. }
  139041. while( 1 ){
  139042. if( iCol1==iCol2 ){
  139043. char *pSave = p;
  139044. sqlite3_int64 iPrev = 0;
  139045. sqlite3_int64 iPos1 = 0;
  139046. sqlite3_int64 iPos2 = 0;
  139047. if( iCol1 ){
  139048. *p++ = POS_COLUMN;
  139049. p += sqlite3Fts3PutVarint(p, iCol1);
  139050. }
  139051. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  139052. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  139053. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  139054. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  139055. while( 1 ){
  139056. if( iPos2==iPos1+nToken
  139057. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  139058. ){
  139059. sqlite3_int64 iSave;
  139060. iSave = isSaveLeft ? iPos1 : iPos2;
  139061. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  139062. pSave = 0;
  139063. assert( p );
  139064. }
  139065. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  139066. if( (*p2&0xFE)==0 ) break;
  139067. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  139068. }else{
  139069. if( (*p1&0xFE)==0 ) break;
  139070. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  139071. }
  139072. }
  139073. if( pSave ){
  139074. assert( pp && p );
  139075. p = pSave;
  139076. }
  139077. fts3ColumnlistCopy(0, &p1);
  139078. fts3ColumnlistCopy(0, &p2);
  139079. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  139080. if( 0==*p1 || 0==*p2 ) break;
  139081. p1++;
  139082. p1 += fts3GetVarint32(p1, &iCol1);
  139083. p2++;
  139084. p2 += fts3GetVarint32(p2, &iCol2);
  139085. }
  139086. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  139087. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  139088. ** end of the position list, or the 0x01 that precedes the next
  139089. ** column-number in the position list.
  139090. */
  139091. else if( iCol1<iCol2 ){
  139092. fts3ColumnlistCopy(0, &p1);
  139093. if( 0==*p1 ) break;
  139094. p1++;
  139095. p1 += fts3GetVarint32(p1, &iCol1);
  139096. }else{
  139097. fts3ColumnlistCopy(0, &p2);
  139098. if( 0==*p2 ) break;
  139099. p2++;
  139100. p2 += fts3GetVarint32(p2, &iCol2);
  139101. }
  139102. }
  139103. fts3PoslistCopy(0, &p2);
  139104. fts3PoslistCopy(0, &p1);
  139105. *pp1 = p1;
  139106. *pp2 = p2;
  139107. if( *pp==p ){
  139108. return 0;
  139109. }
  139110. *p++ = 0x00;
  139111. *pp = p;
  139112. return 1;
  139113. }
  139114. /*
  139115. ** Merge two position-lists as required by the NEAR operator. The argument
  139116. ** position lists correspond to the left and right phrases of an expression
  139117. ** like:
  139118. **
  139119. ** "phrase 1" NEAR "phrase number 2"
  139120. **
  139121. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  139122. ** expression and *pp2 to the right. As usual, the indexes in the position
  139123. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  139124. ** in the example above).
  139125. **
  139126. ** The output position list - written to *pp - is a copy of *pp2 with those
  139127. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  139128. */
  139129. static int fts3PoslistNearMerge(
  139130. char **pp, /* Output buffer */
  139131. char *aTmp, /* Temporary buffer space */
  139132. int nRight, /* Maximum difference in token positions */
  139133. int nLeft, /* Maximum difference in token positions */
  139134. char **pp1, /* IN/OUT: Left input list */
  139135. char **pp2 /* IN/OUT: Right input list */
  139136. ){
  139137. char *p1 = *pp1;
  139138. char *p2 = *pp2;
  139139. char *pTmp1 = aTmp;
  139140. char *pTmp2;
  139141. char *aTmp2;
  139142. int res = 1;
  139143. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  139144. aTmp2 = pTmp2 = pTmp1;
  139145. *pp1 = p1;
  139146. *pp2 = p2;
  139147. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  139148. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  139149. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  139150. }else if( pTmp1!=aTmp ){
  139151. fts3PoslistCopy(pp, &aTmp);
  139152. }else if( pTmp2!=aTmp2 ){
  139153. fts3PoslistCopy(pp, &aTmp2);
  139154. }else{
  139155. res = 0;
  139156. }
  139157. return res;
  139158. }
  139159. /*
  139160. ** An instance of this function is used to merge together the (potentially
  139161. ** large number of) doclists for each term that matches a prefix query.
  139162. ** See function fts3TermSelectMerge() for details.
  139163. */
  139164. typedef struct TermSelect TermSelect;
  139165. struct TermSelect {
  139166. char *aaOutput[16]; /* Malloc'd output buffers */
  139167. int anOutput[16]; /* Size each output buffer in bytes */
  139168. };
  139169. /*
  139170. ** This function is used to read a single varint from a buffer. Parameter
  139171. ** pEnd points 1 byte past the end of the buffer. When this function is
  139172. ** called, if *pp points to pEnd or greater, then the end of the buffer
  139173. ** has been reached. In this case *pp is set to 0 and the function returns.
  139174. **
  139175. ** If *pp does not point to or past pEnd, then a single varint is read
  139176. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  139177. **
  139178. ** If bDescIdx is false, the value read is added to *pVal before returning.
  139179. ** If it is true, the value read is subtracted from *pVal before this
  139180. ** function returns.
  139181. */
  139182. static void fts3GetDeltaVarint3(
  139183. char **pp, /* IN/OUT: Point to read varint from */
  139184. char *pEnd, /* End of buffer */
  139185. int bDescIdx, /* True if docids are descending */
  139186. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  139187. ){
  139188. if( *pp>=pEnd ){
  139189. *pp = 0;
  139190. }else{
  139191. sqlite3_int64 iVal;
  139192. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  139193. if( bDescIdx ){
  139194. *pVal -= iVal;
  139195. }else{
  139196. *pVal += iVal;
  139197. }
  139198. }
  139199. }
  139200. /*
  139201. ** This function is used to write a single varint to a buffer. The varint
  139202. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  139203. ** end of the value written.
  139204. **
  139205. ** If *pbFirst is zero when this function is called, the value written to
  139206. ** the buffer is that of parameter iVal.
  139207. **
  139208. ** If *pbFirst is non-zero when this function is called, then the value
  139209. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  139210. ** (if bDescIdx is non-zero).
  139211. **
  139212. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  139213. ** to the value of parameter iVal.
  139214. */
  139215. static void fts3PutDeltaVarint3(
  139216. char **pp, /* IN/OUT: Output pointer */
  139217. int bDescIdx, /* True for descending docids */
  139218. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  139219. int *pbFirst, /* IN/OUT: True after first int written */
  139220. sqlite3_int64 iVal /* Write this value to the list */
  139221. ){
  139222. sqlite3_int64 iWrite;
  139223. if( bDescIdx==0 || *pbFirst==0 ){
  139224. iWrite = iVal - *piPrev;
  139225. }else{
  139226. iWrite = *piPrev - iVal;
  139227. }
  139228. assert( *pbFirst || *piPrev==0 );
  139229. assert( *pbFirst==0 || iWrite>0 );
  139230. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  139231. *piPrev = iVal;
  139232. *pbFirst = 1;
  139233. }
  139234. /*
  139235. ** This macro is used by various functions that merge doclists. The two
  139236. ** arguments are 64-bit docid values. If the value of the stack variable
  139237. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  139238. ** Otherwise, (i2-i1).
  139239. **
  139240. ** Using this makes it easier to write code that can merge doclists that are
  139241. ** sorted in either ascending or descending order.
  139242. */
  139243. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  139244. /*
  139245. ** This function does an "OR" merge of two doclists (output contains all
  139246. ** positions contained in either argument doclist). If the docids in the
  139247. ** input doclists are sorted in ascending order, parameter bDescDoclist
  139248. ** should be false. If they are sorted in ascending order, it should be
  139249. ** passed a non-zero value.
  139250. **
  139251. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  139252. ** containing the output doclist and SQLITE_OK is returned. In this case
  139253. ** *pnOut is set to the number of bytes in the output doclist.
  139254. **
  139255. ** If an error occurs, an SQLite error code is returned. The output values
  139256. ** are undefined in this case.
  139257. */
  139258. static int fts3DoclistOrMerge(
  139259. int bDescDoclist, /* True if arguments are desc */
  139260. char *a1, int n1, /* First doclist */
  139261. char *a2, int n2, /* Second doclist */
  139262. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  139263. ){
  139264. sqlite3_int64 i1 = 0;
  139265. sqlite3_int64 i2 = 0;
  139266. sqlite3_int64 iPrev = 0;
  139267. char *pEnd1 = &a1[n1];
  139268. char *pEnd2 = &a2[n2];
  139269. char *p1 = a1;
  139270. char *p2 = a2;
  139271. char *p;
  139272. char *aOut;
  139273. int bFirstOut = 0;
  139274. *paOut = 0;
  139275. *pnOut = 0;
  139276. /* Allocate space for the output. Both the input and output doclists
  139277. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  139278. ** then the first docid in each list is simply encoded as a varint. For
  139279. ** each subsequent docid, the varint stored is the difference between the
  139280. ** current and previous docid (a positive number - since the list is in
  139281. ** ascending order).
  139282. **
  139283. ** The first docid written to the output is therefore encoded using the
  139284. ** same number of bytes as it is in whichever of the input lists it is
  139285. ** read from. And each subsequent docid read from the same input list
  139286. ** consumes either the same or less bytes as it did in the input (since
  139287. ** the difference between it and the previous value in the output must
  139288. ** be a positive value less than or equal to the delta value read from
  139289. ** the input list). The same argument applies to all but the first docid
  139290. ** read from the 'other' list. And to the contents of all position lists
  139291. ** that will be copied and merged from the input to the output.
  139292. **
  139293. ** However, if the first docid copied to the output is a negative number,
  139294. ** then the encoding of the first docid from the 'other' input list may
  139295. ** be larger in the output than it was in the input (since the delta value
  139296. ** may be a larger positive integer than the actual docid).
  139297. **
  139298. ** The space required to store the output is therefore the sum of the
  139299. ** sizes of the two inputs, plus enough space for exactly one of the input
  139300. ** docids to grow.
  139301. **
  139302. ** A symetric argument may be made if the doclists are in descending
  139303. ** order.
  139304. */
  139305. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  139306. if( !aOut ) return SQLITE_NOMEM;
  139307. p = aOut;
  139308. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  139309. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  139310. while( p1 || p2 ){
  139311. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  139312. if( p2 && p1 && iDiff==0 ){
  139313. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  139314. fts3PoslistMerge(&p, &p1, &p2);
  139315. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  139316. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  139317. }else if( !p2 || (p1 && iDiff<0) ){
  139318. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  139319. fts3PoslistCopy(&p, &p1);
  139320. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  139321. }else{
  139322. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  139323. fts3PoslistCopy(&p, &p2);
  139324. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  139325. }
  139326. }
  139327. *paOut = aOut;
  139328. *pnOut = (int)(p-aOut);
  139329. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  139330. return SQLITE_OK;
  139331. }
  139332. /*
  139333. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  139334. ** the output contains a copy of each position from the right-hand input
  139335. ** doclist for which there is a position in the left-hand input doclist
  139336. ** exactly nDist tokens before it.
  139337. **
  139338. ** If the docids in the input doclists are sorted in ascending order,
  139339. ** parameter bDescDoclist should be false. If they are sorted in ascending
  139340. ** order, it should be passed a non-zero value.
  139341. **
  139342. ** The right-hand input doclist is overwritten by this function.
  139343. */
  139344. static int fts3DoclistPhraseMerge(
  139345. int bDescDoclist, /* True if arguments are desc */
  139346. int nDist, /* Distance from left to right (1=adjacent) */
  139347. char *aLeft, int nLeft, /* Left doclist */
  139348. char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
  139349. ){
  139350. sqlite3_int64 i1 = 0;
  139351. sqlite3_int64 i2 = 0;
  139352. sqlite3_int64 iPrev = 0;
  139353. char *aRight = *paRight;
  139354. char *pEnd1 = &aLeft[nLeft];
  139355. char *pEnd2 = &aRight[*pnRight];
  139356. char *p1 = aLeft;
  139357. char *p2 = aRight;
  139358. char *p;
  139359. int bFirstOut = 0;
  139360. char *aOut;
  139361. assert( nDist>0 );
  139362. if( bDescDoclist ){
  139363. aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
  139364. if( aOut==0 ) return SQLITE_NOMEM;
  139365. }else{
  139366. aOut = aRight;
  139367. }
  139368. p = aOut;
  139369. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  139370. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  139371. while( p1 && p2 ){
  139372. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  139373. if( iDiff==0 ){
  139374. char *pSave = p;
  139375. sqlite3_int64 iPrevSave = iPrev;
  139376. int bFirstOutSave = bFirstOut;
  139377. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  139378. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  139379. p = pSave;
  139380. iPrev = iPrevSave;
  139381. bFirstOut = bFirstOutSave;
  139382. }
  139383. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  139384. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  139385. }else if( iDiff<0 ){
  139386. fts3PoslistCopy(0, &p1);
  139387. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  139388. }else{
  139389. fts3PoslistCopy(0, &p2);
  139390. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  139391. }
  139392. }
  139393. *pnRight = (int)(p - aOut);
  139394. if( bDescDoclist ){
  139395. sqlite3_free(aRight);
  139396. *paRight = aOut;
  139397. }
  139398. return SQLITE_OK;
  139399. }
  139400. /*
  139401. ** Argument pList points to a position list nList bytes in size. This
  139402. ** function checks to see if the position list contains any entries for
  139403. ** a token in position 0 (of any column). If so, it writes argument iDelta
  139404. ** to the output buffer pOut, followed by a position list consisting only
  139405. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  139406. ** The value returned is the number of bytes written to pOut (if any).
  139407. */
  139408. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  139409. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  139410. char *pList, /* Position list (no 0x00 term) */
  139411. int nList, /* Size of pList in bytes */
  139412. char *pOut /* Write output here */
  139413. ){
  139414. int nOut = 0;
  139415. int bWritten = 0; /* True once iDelta has been written */
  139416. char *p = pList;
  139417. char *pEnd = &pList[nList];
  139418. if( *p!=0x01 ){
  139419. if( *p==0x02 ){
  139420. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  139421. pOut[nOut++] = 0x02;
  139422. bWritten = 1;
  139423. }
  139424. fts3ColumnlistCopy(0, &p);
  139425. }
  139426. while( p<pEnd ){
  139427. sqlite3_int64 iCol;
  139428. p++;
  139429. p += sqlite3Fts3GetVarint(p, &iCol);
  139430. if( *p==0x02 ){
  139431. if( bWritten==0 ){
  139432. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  139433. bWritten = 1;
  139434. }
  139435. pOut[nOut++] = 0x01;
  139436. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  139437. pOut[nOut++] = 0x02;
  139438. }
  139439. fts3ColumnlistCopy(0, &p);
  139440. }
  139441. if( bWritten ){
  139442. pOut[nOut++] = 0x00;
  139443. }
  139444. return nOut;
  139445. }
  139446. /*
  139447. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  139448. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  139449. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  139450. **
  139451. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  139452. ** the responsibility of the caller to free any doclists left in the
  139453. ** TermSelect.aaOutput[] array.
  139454. */
  139455. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  139456. char *aOut = 0;
  139457. int nOut = 0;
  139458. int i;
  139459. /* Loop through the doclists in the aaOutput[] array. Merge them all
  139460. ** into a single doclist.
  139461. */
  139462. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  139463. if( pTS->aaOutput[i] ){
  139464. if( !aOut ){
  139465. aOut = pTS->aaOutput[i];
  139466. nOut = pTS->anOutput[i];
  139467. pTS->aaOutput[i] = 0;
  139468. }else{
  139469. int nNew;
  139470. char *aNew;
  139471. int rc = fts3DoclistOrMerge(p->bDescIdx,
  139472. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  139473. );
  139474. if( rc!=SQLITE_OK ){
  139475. sqlite3_free(aOut);
  139476. return rc;
  139477. }
  139478. sqlite3_free(pTS->aaOutput[i]);
  139479. sqlite3_free(aOut);
  139480. pTS->aaOutput[i] = 0;
  139481. aOut = aNew;
  139482. nOut = nNew;
  139483. }
  139484. }
  139485. }
  139486. pTS->aaOutput[0] = aOut;
  139487. pTS->anOutput[0] = nOut;
  139488. return SQLITE_OK;
  139489. }
  139490. /*
  139491. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  139492. ** as the first argument. The merge is an "OR" merge (see function
  139493. ** fts3DoclistOrMerge() for details).
  139494. **
  139495. ** This function is called with the doclist for each term that matches
  139496. ** a queried prefix. It merges all these doclists into one, the doclist
  139497. ** for the specified prefix. Since there can be a very large number of
  139498. ** doclists to merge, the merging is done pair-wise using the TermSelect
  139499. ** object.
  139500. **
  139501. ** This function returns SQLITE_OK if the merge is successful, or an
  139502. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  139503. */
  139504. static int fts3TermSelectMerge(
  139505. Fts3Table *p, /* FTS table handle */
  139506. TermSelect *pTS, /* TermSelect object to merge into */
  139507. char *aDoclist, /* Pointer to doclist */
  139508. int nDoclist /* Size of aDoclist in bytes */
  139509. ){
  139510. if( pTS->aaOutput[0]==0 ){
  139511. /* If this is the first term selected, copy the doclist to the output
  139512. ** buffer using memcpy().
  139513. **
  139514. ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
  139515. ** allocation. This is so as to ensure that the buffer is big enough
  139516. ** to hold the current doclist AND'd with any other doclist. If the
  139517. ** doclists are stored in order=ASC order, this padding would not be
  139518. ** required (since the size of [doclistA AND doclistB] is always less
  139519. ** than or equal to the size of [doclistA] in that case). But this is
  139520. ** not true for order=DESC. For example, a doclist containing (1, -1)
  139521. ** may be smaller than (-1), as in the first example the -1 may be stored
  139522. ** as a single-byte delta, whereas in the second it must be stored as a
  139523. ** FTS3_VARINT_MAX byte varint.
  139524. **
  139525. ** Similar padding is added in the fts3DoclistOrMerge() function.
  139526. */
  139527. pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
  139528. pTS->anOutput[0] = nDoclist;
  139529. if( pTS->aaOutput[0] ){
  139530. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  139531. }else{
  139532. return SQLITE_NOMEM;
  139533. }
  139534. }else{
  139535. char *aMerge = aDoclist;
  139536. int nMerge = nDoclist;
  139537. int iOut;
  139538. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  139539. if( pTS->aaOutput[iOut]==0 ){
  139540. assert( iOut>0 );
  139541. pTS->aaOutput[iOut] = aMerge;
  139542. pTS->anOutput[iOut] = nMerge;
  139543. break;
  139544. }else{
  139545. char *aNew;
  139546. int nNew;
  139547. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  139548. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  139549. );
  139550. if( rc!=SQLITE_OK ){
  139551. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  139552. return rc;
  139553. }
  139554. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  139555. sqlite3_free(pTS->aaOutput[iOut]);
  139556. pTS->aaOutput[iOut] = 0;
  139557. aMerge = aNew;
  139558. nMerge = nNew;
  139559. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  139560. pTS->aaOutput[iOut] = aMerge;
  139561. pTS->anOutput[iOut] = nMerge;
  139562. }
  139563. }
  139564. }
  139565. }
  139566. return SQLITE_OK;
  139567. }
  139568. /*
  139569. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  139570. */
  139571. static int fts3SegReaderCursorAppend(
  139572. Fts3MultiSegReader *pCsr,
  139573. Fts3SegReader *pNew
  139574. ){
  139575. if( (pCsr->nSegment%16)==0 ){
  139576. Fts3SegReader **apNew;
  139577. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  139578. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  139579. if( !apNew ){
  139580. sqlite3Fts3SegReaderFree(pNew);
  139581. return SQLITE_NOMEM;
  139582. }
  139583. pCsr->apSegment = apNew;
  139584. }
  139585. pCsr->apSegment[pCsr->nSegment++] = pNew;
  139586. return SQLITE_OK;
  139587. }
  139588. /*
  139589. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  139590. ** 8th argument.
  139591. **
  139592. ** This function returns SQLITE_OK if successful, or an SQLite error code
  139593. ** otherwise.
  139594. */
  139595. static int fts3SegReaderCursor(
  139596. Fts3Table *p, /* FTS3 table handle */
  139597. int iLangid, /* Language id */
  139598. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  139599. int iLevel, /* Level of segments to scan */
  139600. const char *zTerm, /* Term to query for */
  139601. int nTerm, /* Size of zTerm in bytes */
  139602. int isPrefix, /* True for a prefix search */
  139603. int isScan, /* True to scan from zTerm to EOF */
  139604. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  139605. ){
  139606. int rc = SQLITE_OK; /* Error code */
  139607. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  139608. int rc2; /* Result of sqlite3_reset() */
  139609. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  139610. ** for the pending-terms. If this is a scan, then this call must be being
  139611. ** made by an fts4aux module, not an FTS table. In this case calling
  139612. ** Fts3SegReaderPending might segfault, as the data structures used by
  139613. ** fts4aux are not completely populated. So it's easiest to filter these
  139614. ** calls out here. */
  139615. if( iLevel<0 && p->aIndex ){
  139616. Fts3SegReader *pSeg = 0;
  139617. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
  139618. if( rc==SQLITE_OK && pSeg ){
  139619. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  139620. }
  139621. }
  139622. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  139623. if( rc==SQLITE_OK ){
  139624. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  139625. }
  139626. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  139627. Fts3SegReader *pSeg = 0;
  139628. /* Read the values returned by the SELECT into local variables. */
  139629. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  139630. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  139631. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  139632. int nRoot = sqlite3_column_bytes(pStmt, 4);
  139633. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  139634. /* If zTerm is not NULL, and this segment is not stored entirely on its
  139635. ** root node, the range of leaves scanned can be reduced. Do this. */
  139636. if( iStartBlock && zTerm ){
  139637. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  139638. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  139639. if( rc!=SQLITE_OK ) goto finished;
  139640. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  139641. }
  139642. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  139643. (isPrefix==0 && isScan==0),
  139644. iStartBlock, iLeavesEndBlock,
  139645. iEndBlock, zRoot, nRoot, &pSeg
  139646. );
  139647. if( rc!=SQLITE_OK ) goto finished;
  139648. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  139649. }
  139650. }
  139651. finished:
  139652. rc2 = sqlite3_reset(pStmt);
  139653. if( rc==SQLITE_DONE ) rc = rc2;
  139654. return rc;
  139655. }
  139656. /*
  139657. ** Set up a cursor object for iterating through a full-text index or a
  139658. ** single level therein.
  139659. */
  139660. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  139661. Fts3Table *p, /* FTS3 table handle */
  139662. int iLangid, /* Language-id to search */
  139663. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  139664. int iLevel, /* Level of segments to scan */
  139665. const char *zTerm, /* Term to query for */
  139666. int nTerm, /* Size of zTerm in bytes */
  139667. int isPrefix, /* True for a prefix search */
  139668. int isScan, /* True to scan from zTerm to EOF */
  139669. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  139670. ){
  139671. assert( iIndex>=0 && iIndex<p->nIndex );
  139672. assert( iLevel==FTS3_SEGCURSOR_ALL
  139673. || iLevel==FTS3_SEGCURSOR_PENDING
  139674. || iLevel>=0
  139675. );
  139676. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  139677. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  139678. assert( isPrefix==0 || isScan==0 );
  139679. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  139680. return fts3SegReaderCursor(
  139681. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  139682. );
  139683. }
  139684. /*
  139685. ** In addition to its current configuration, have the Fts3MultiSegReader
  139686. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  139687. **
  139688. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  139689. */
  139690. static int fts3SegReaderCursorAddZero(
  139691. Fts3Table *p, /* FTS virtual table handle */
  139692. int iLangid,
  139693. const char *zTerm, /* Term to scan doclist of */
  139694. int nTerm, /* Number of bytes in zTerm */
  139695. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  139696. ){
  139697. return fts3SegReaderCursor(p,
  139698. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  139699. );
  139700. }
  139701. /*
  139702. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  139703. ** if isPrefix is true, to scan the doclist for all terms for which
  139704. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  139705. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  139706. ** an SQLite error code.
  139707. **
  139708. ** It is the responsibility of the caller to free this object by eventually
  139709. ** passing it to fts3SegReaderCursorFree()
  139710. **
  139711. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  139712. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  139713. */
  139714. static int fts3TermSegReaderCursor(
  139715. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  139716. const char *zTerm, /* Term to query for */
  139717. int nTerm, /* Size of zTerm in bytes */
  139718. int isPrefix, /* True for a prefix search */
  139719. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  139720. ){
  139721. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  139722. int rc = SQLITE_NOMEM; /* Return code */
  139723. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  139724. if( pSegcsr ){
  139725. int i;
  139726. int bFound = 0; /* True once an index has been found */
  139727. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  139728. if( isPrefix ){
  139729. for(i=1; bFound==0 && i<p->nIndex; i++){
  139730. if( p->aIndex[i].nPrefix==nTerm ){
  139731. bFound = 1;
  139732. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  139733. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  139734. );
  139735. pSegcsr->bLookup = 1;
  139736. }
  139737. }
  139738. for(i=1; bFound==0 && i<p->nIndex; i++){
  139739. if( p->aIndex[i].nPrefix==nTerm+1 ){
  139740. bFound = 1;
  139741. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  139742. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  139743. );
  139744. if( rc==SQLITE_OK ){
  139745. rc = fts3SegReaderCursorAddZero(
  139746. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  139747. );
  139748. }
  139749. }
  139750. }
  139751. }
  139752. if( bFound==0 ){
  139753. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  139754. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  139755. );
  139756. pSegcsr->bLookup = !isPrefix;
  139757. }
  139758. }
  139759. *ppSegcsr = pSegcsr;
  139760. return rc;
  139761. }
  139762. /*
  139763. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  139764. */
  139765. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  139766. sqlite3Fts3SegReaderFinish(pSegcsr);
  139767. sqlite3_free(pSegcsr);
  139768. }
  139769. /*
  139770. ** This function retrieves the doclist for the specified term (or term
  139771. ** prefix) from the database.
  139772. */
  139773. static int fts3TermSelect(
  139774. Fts3Table *p, /* Virtual table handle */
  139775. Fts3PhraseToken *pTok, /* Token to query for */
  139776. int iColumn, /* Column to query (or -ve for all columns) */
  139777. int *pnOut, /* OUT: Size of buffer at *ppOut */
  139778. char **ppOut /* OUT: Malloced result buffer */
  139779. ){
  139780. int rc; /* Return code */
  139781. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  139782. TermSelect tsc; /* Object for pair-wise doclist merging */
  139783. Fts3SegFilter filter; /* Segment term filter configuration */
  139784. pSegcsr = pTok->pSegcsr;
  139785. memset(&tsc, 0, sizeof(TermSelect));
  139786. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  139787. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  139788. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  139789. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  139790. filter.iCol = iColumn;
  139791. filter.zTerm = pTok->z;
  139792. filter.nTerm = pTok->n;
  139793. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  139794. while( SQLITE_OK==rc
  139795. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  139796. ){
  139797. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  139798. }
  139799. if( rc==SQLITE_OK ){
  139800. rc = fts3TermSelectFinishMerge(p, &tsc);
  139801. }
  139802. if( rc==SQLITE_OK ){
  139803. *ppOut = tsc.aaOutput[0];
  139804. *pnOut = tsc.anOutput[0];
  139805. }else{
  139806. int i;
  139807. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  139808. sqlite3_free(tsc.aaOutput[i]);
  139809. }
  139810. }
  139811. fts3SegReaderCursorFree(pSegcsr);
  139812. pTok->pSegcsr = 0;
  139813. return rc;
  139814. }
  139815. /*
  139816. ** This function counts the total number of docids in the doclist stored
  139817. ** in buffer aList[], size nList bytes.
  139818. **
  139819. ** If the isPoslist argument is true, then it is assumed that the doclist
  139820. ** contains a position-list following each docid. Otherwise, it is assumed
  139821. ** that the doclist is simply a list of docids stored as delta encoded
  139822. ** varints.
  139823. */
  139824. static int fts3DoclistCountDocids(char *aList, int nList){
  139825. int nDoc = 0; /* Return value */
  139826. if( aList ){
  139827. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  139828. char *p = aList; /* Cursor */
  139829. while( p<aEnd ){
  139830. nDoc++;
  139831. while( (*p++)&0x80 ); /* Skip docid varint */
  139832. fts3PoslistCopy(0, &p); /* Skip over position list */
  139833. }
  139834. }
  139835. return nDoc;
  139836. }
  139837. /*
  139838. ** Advance the cursor to the next row in the %_content table that
  139839. ** matches the search criteria. For a MATCH search, this will be
  139840. ** the next row that matches. For a full-table scan, this will be
  139841. ** simply the next row in the %_content table. For a docid lookup,
  139842. ** this routine simply sets the EOF flag.
  139843. **
  139844. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  139845. ** even if we reach end-of-file. The fts3EofMethod() will be called
  139846. ** subsequently to determine whether or not an EOF was hit.
  139847. */
  139848. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  139849. int rc;
  139850. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  139851. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  139852. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  139853. pCsr->isEof = 1;
  139854. rc = sqlite3_reset(pCsr->pStmt);
  139855. }else{
  139856. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  139857. rc = SQLITE_OK;
  139858. }
  139859. }else{
  139860. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  139861. }
  139862. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  139863. return rc;
  139864. }
  139865. /*
  139866. ** The following are copied from sqliteInt.h.
  139867. **
  139868. ** Constants for the largest and smallest possible 64-bit signed integers.
  139869. ** These macros are designed to work correctly on both 32-bit and 64-bit
  139870. ** compilers.
  139871. */
  139872. #ifndef SQLITE_AMALGAMATION
  139873. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  139874. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  139875. #endif
  139876. /*
  139877. ** If the numeric type of argument pVal is "integer", then return it
  139878. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  139879. ** the second parameter, iDefault.
  139880. */
  139881. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  139882. if( pVal ){
  139883. int eType = sqlite3_value_numeric_type(pVal);
  139884. if( eType==SQLITE_INTEGER ){
  139885. return sqlite3_value_int64(pVal);
  139886. }
  139887. }
  139888. return iDefault;
  139889. }
  139890. /*
  139891. ** This is the xFilter interface for the virtual table. See
  139892. ** the virtual table xFilter method documentation for additional
  139893. ** information.
  139894. **
  139895. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  139896. ** the %_content table.
  139897. **
  139898. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  139899. ** in the %_content table.
  139900. **
  139901. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  139902. ** column on the left-hand side of the MATCH operator is column
  139903. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  139904. ** side of the MATCH operator.
  139905. */
  139906. static int fts3FilterMethod(
  139907. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  139908. int idxNum, /* Strategy index */
  139909. const char *idxStr, /* Unused */
  139910. int nVal, /* Number of elements in apVal */
  139911. sqlite3_value **apVal /* Arguments for the indexing scheme */
  139912. ){
  139913. int rc = SQLITE_OK;
  139914. char *zSql; /* SQL statement used to access %_content */
  139915. int eSearch;
  139916. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  139917. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  139918. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  139919. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  139920. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  139921. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  139922. int iIdx;
  139923. UNUSED_PARAMETER(idxStr);
  139924. UNUSED_PARAMETER(nVal);
  139925. eSearch = (idxNum & 0x0000FFFF);
  139926. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  139927. assert( p->pSegments==0 );
  139928. /* Collect arguments into local variables */
  139929. iIdx = 0;
  139930. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  139931. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  139932. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  139933. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  139934. assert( iIdx==nVal );
  139935. /* In case the cursor has been used before, clear it now. */
  139936. fts3CursorFinalizeStmt(pCsr);
  139937. sqlite3_free(pCsr->aDoclist);
  139938. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  139939. sqlite3Fts3ExprFree(pCsr->pExpr);
  139940. memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  139941. /* Set the lower and upper bounds on docids to return */
  139942. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  139943. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  139944. if( idxStr ){
  139945. pCsr->bDesc = (idxStr[0]=='D');
  139946. }else{
  139947. pCsr->bDesc = p->bDescIdx;
  139948. }
  139949. pCsr->eSearch = (i16)eSearch;
  139950. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  139951. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  139952. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  139953. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  139954. return SQLITE_NOMEM;
  139955. }
  139956. pCsr->iLangid = 0;
  139957. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  139958. assert( p->base.zErrMsg==0 );
  139959. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  139960. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  139961. &p->base.zErrMsg
  139962. );
  139963. if( rc!=SQLITE_OK ){
  139964. return rc;
  139965. }
  139966. rc = fts3EvalStart(pCsr);
  139967. sqlite3Fts3SegmentsClose(p);
  139968. if( rc!=SQLITE_OK ) return rc;
  139969. pCsr->pNextId = pCsr->aDoclist;
  139970. pCsr->iPrevId = 0;
  139971. }
  139972. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  139973. ** statement loops through all rows of the %_content table. For a
  139974. ** full-text query or docid lookup, the statement retrieves a single
  139975. ** row by docid.
  139976. */
  139977. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  139978. if( pDocidGe || pDocidLe ){
  139979. zSql = sqlite3_mprintf(
  139980. "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
  139981. p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
  139982. (pCsr->bDesc ? "DESC" : "ASC")
  139983. );
  139984. }else{
  139985. zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
  139986. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  139987. );
  139988. }
  139989. if( zSql ){
  139990. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  139991. sqlite3_free(zSql);
  139992. }else{
  139993. rc = SQLITE_NOMEM;
  139994. }
  139995. }else if( eSearch==FTS3_DOCID_SEARCH ){
  139996. rc = fts3CursorSeekStmt(pCsr);
  139997. if( rc==SQLITE_OK ){
  139998. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  139999. }
  140000. }
  140001. if( rc!=SQLITE_OK ) return rc;
  140002. return fts3NextMethod(pCursor);
  140003. }
  140004. /*
  140005. ** This is the xEof method of the virtual table. SQLite calls this
  140006. ** routine to find out if it has reached the end of a result set.
  140007. */
  140008. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  140009. return ((Fts3Cursor *)pCursor)->isEof;
  140010. }
  140011. /*
  140012. ** This is the xRowid method. The SQLite core calls this routine to
  140013. ** retrieve the rowid for the current row of the result set. fts3
  140014. ** exposes %_content.docid as the rowid for the virtual table. The
  140015. ** rowid should be written to *pRowid.
  140016. */
  140017. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  140018. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  140019. *pRowid = pCsr->iPrevId;
  140020. return SQLITE_OK;
  140021. }
  140022. /*
  140023. ** This is the xColumn method, called by SQLite to request a value from
  140024. ** the row that the supplied cursor currently points to.
  140025. **
  140026. ** If:
  140027. **
  140028. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  140029. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  140030. ** (iCol == p->nColumn+1) -> Docid column
  140031. ** (iCol == p->nColumn+2) -> Langid column
  140032. */
  140033. static int fts3ColumnMethod(
  140034. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  140035. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  140036. int iCol /* Index of column to read value from */
  140037. ){
  140038. int rc = SQLITE_OK; /* Return Code */
  140039. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  140040. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  140041. /* The column value supplied by SQLite must be in range. */
  140042. assert( iCol>=0 && iCol<=p->nColumn+2 );
  140043. switch( iCol-p->nColumn ){
  140044. case 0:
  140045. /* The special 'table-name' column */
  140046. sqlite3_result_blob(pCtx, &pCsr, sizeof(Fts3Cursor*), SQLITE_TRANSIENT);
  140047. sqlite3_result_subtype(pCtx, SQLITE_BLOB);
  140048. break;
  140049. case 1:
  140050. /* The docid column */
  140051. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  140052. break;
  140053. case 2:
  140054. if( pCsr->pExpr ){
  140055. sqlite3_result_int64(pCtx, pCsr->iLangid);
  140056. break;
  140057. }else if( p->zLanguageid==0 ){
  140058. sqlite3_result_int(pCtx, 0);
  140059. break;
  140060. }else{
  140061. iCol = p->nColumn;
  140062. /* fall-through */
  140063. }
  140064. default:
  140065. /* A user column. Or, if this is a full-table scan, possibly the
  140066. ** language-id column. Seek the cursor. */
  140067. rc = fts3CursorSeek(0, pCsr);
  140068. if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){
  140069. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  140070. }
  140071. break;
  140072. }
  140073. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  140074. return rc;
  140075. }
  140076. /*
  140077. ** This function is the implementation of the xUpdate callback used by
  140078. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  140079. ** inserted, updated or deleted.
  140080. */
  140081. static int fts3UpdateMethod(
  140082. sqlite3_vtab *pVtab, /* Virtual table handle */
  140083. int nArg, /* Size of argument array */
  140084. sqlite3_value **apVal, /* Array of arguments */
  140085. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  140086. ){
  140087. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  140088. }
  140089. /*
  140090. ** Implementation of xSync() method. Flush the contents of the pending-terms
  140091. ** hash-table to the database.
  140092. */
  140093. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  140094. /* Following an incremental-merge operation, assuming that the input
  140095. ** segments are not completely consumed (the usual case), they are updated
  140096. ** in place to remove the entries that have already been merged. This
  140097. ** involves updating the leaf block that contains the smallest unmerged
  140098. ** entry and each block (if any) between the leaf and the root node. So
  140099. ** if the height of the input segment b-trees is N, and input segments
  140100. ** are merged eight at a time, updating the input segments at the end
  140101. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  140102. ** small - often between 0 and 2. So the overhead of the incremental
  140103. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  140104. ** dwarfing the actual productive work accomplished, the incremental merge
  140105. ** is only attempted if it will write at least 64 leaf blocks. Hence
  140106. ** nMinMerge.
  140107. **
  140108. ** Of course, updating the input segments also involves deleting a bunch
  140109. ** of blocks from the segments table. But this is not considered overhead
  140110. ** as it would also be required by a crisis-merge that used the same input
  140111. ** segments.
  140112. */
  140113. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  140114. Fts3Table *p = (Fts3Table*)pVtab;
  140115. int rc;
  140116. i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
  140117. rc = sqlite3Fts3PendingTermsFlush(p);
  140118. if( rc==SQLITE_OK
  140119. && p->nLeafAdd>(nMinMerge/16)
  140120. && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
  140121. ){
  140122. int mxLevel = 0; /* Maximum relative level value in db */
  140123. int A; /* Incr-merge parameter A */
  140124. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  140125. assert( rc==SQLITE_OK || mxLevel==0 );
  140126. A = p->nLeafAdd * mxLevel;
  140127. A += (A/2);
  140128. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
  140129. }
  140130. sqlite3Fts3SegmentsClose(p);
  140131. sqlite3_set_last_insert_rowid(p->db, iLastRowid);
  140132. return rc;
  140133. }
  140134. /*
  140135. ** If it is currently unknown whether or not the FTS table has an %_stat
  140136. ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
  140137. ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
  140138. ** if an error occurs.
  140139. */
  140140. static int fts3SetHasStat(Fts3Table *p){
  140141. int rc = SQLITE_OK;
  140142. if( p->bHasStat==2 ){
  140143. char *zTbl = sqlite3_mprintf("%s_stat", p->zName);
  140144. if( zTbl ){
  140145. int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);
  140146. sqlite3_free(zTbl);
  140147. p->bHasStat = (res==SQLITE_OK);
  140148. }else{
  140149. rc = SQLITE_NOMEM;
  140150. }
  140151. }
  140152. return rc;
  140153. }
  140154. /*
  140155. ** Implementation of xBegin() method.
  140156. */
  140157. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  140158. Fts3Table *p = (Fts3Table*)pVtab;
  140159. UNUSED_PARAMETER(pVtab);
  140160. assert( p->pSegments==0 );
  140161. assert( p->nPendingData==0 );
  140162. assert( p->inTransaction!=1 );
  140163. TESTONLY( p->inTransaction = 1 );
  140164. TESTONLY( p->mxSavepoint = -1; );
  140165. p->nLeafAdd = 0;
  140166. return fts3SetHasStat(p);
  140167. }
  140168. /*
  140169. ** Implementation of xCommit() method. This is a no-op. The contents of
  140170. ** the pending-terms hash-table have already been flushed into the database
  140171. ** by fts3SyncMethod().
  140172. */
  140173. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  140174. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  140175. UNUSED_PARAMETER(pVtab);
  140176. assert( p->nPendingData==0 );
  140177. assert( p->inTransaction!=0 );
  140178. assert( p->pSegments==0 );
  140179. TESTONLY( p->inTransaction = 0 );
  140180. TESTONLY( p->mxSavepoint = -1; );
  140181. return SQLITE_OK;
  140182. }
  140183. /*
  140184. ** Implementation of xRollback(). Discard the contents of the pending-terms
  140185. ** hash-table. Any changes made to the database are reverted by SQLite.
  140186. */
  140187. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  140188. Fts3Table *p = (Fts3Table*)pVtab;
  140189. sqlite3Fts3PendingTermsClear(p);
  140190. assert( p->inTransaction!=0 );
  140191. TESTONLY( p->inTransaction = 0 );
  140192. TESTONLY( p->mxSavepoint = -1; );
  140193. return SQLITE_OK;
  140194. }
  140195. /*
  140196. ** When called, *ppPoslist must point to the byte immediately following the
  140197. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  140198. ** moves *ppPoslist so that it instead points to the first byte of the
  140199. ** same position list.
  140200. */
  140201. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  140202. char *p = &(*ppPoslist)[-2];
  140203. char c = 0;
  140204. /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
  140205. while( p>pStart && (c=*p--)==0 );
  140206. /* Search backwards for a varint with value zero (the end of the previous
  140207. ** poslist). This is an 0x00 byte preceded by some byte that does not
  140208. ** have the 0x80 bit set. */
  140209. while( p>pStart && (*p & 0x80) | c ){
  140210. c = *p--;
  140211. }
  140212. assert( p==pStart || c==0 );
  140213. /* At this point p points to that preceding byte without the 0x80 bit
  140214. ** set. So to find the start of the poslist, skip forward 2 bytes then
  140215. ** over a varint.
  140216. **
  140217. ** Normally. The other case is that p==pStart and the poslist to return
  140218. ** is the first in the doclist. In this case do not skip forward 2 bytes.
  140219. ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
  140220. ** is required for cases where the first byte of a doclist and the
  140221. ** doclist is empty. For example, if the first docid is 10, a doclist
  140222. ** that begins with:
  140223. **
  140224. ** 0x0A 0x00 <next docid delta varint>
  140225. */
  140226. if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
  140227. while( *p++&0x80 );
  140228. *ppPoslist = p;
  140229. }
  140230. /*
  140231. ** Helper function used by the implementation of the overloaded snippet(),
  140232. ** offsets() and optimize() SQL functions.
  140233. **
  140234. ** If the value passed as the third argument is a blob of size
  140235. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  140236. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  140237. ** message is written to context pContext and SQLITE_ERROR returned. The
  140238. ** string passed via zFunc is used as part of the error message.
  140239. */
  140240. static int fts3FunctionArg(
  140241. sqlite3_context *pContext, /* SQL function call context */
  140242. const char *zFunc, /* Function name */
  140243. sqlite3_value *pVal, /* argv[0] passed to function */
  140244. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  140245. ){
  140246. int rc = SQLITE_OK;
  140247. if( sqlite3_value_subtype(pVal)==SQLITE_BLOB ){
  140248. *ppCsr = *(Fts3Cursor**)sqlite3_value_blob(pVal);
  140249. }else{
  140250. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  140251. sqlite3_result_error(pContext, zErr, -1);
  140252. sqlite3_free(zErr);
  140253. rc = SQLITE_ERROR;
  140254. }
  140255. return rc;
  140256. }
  140257. /*
  140258. ** Implementation of the snippet() function for FTS3
  140259. */
  140260. static void fts3SnippetFunc(
  140261. sqlite3_context *pContext, /* SQLite function call context */
  140262. int nVal, /* Size of apVal[] array */
  140263. sqlite3_value **apVal /* Array of arguments */
  140264. ){
  140265. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  140266. const char *zStart = "<b>";
  140267. const char *zEnd = "</b>";
  140268. const char *zEllipsis = "<b>...</b>";
  140269. int iCol = -1;
  140270. int nToken = 15; /* Default number of tokens in snippet */
  140271. /* There must be at least one argument passed to this function (otherwise
  140272. ** the non-overloaded version would have been called instead of this one).
  140273. */
  140274. assert( nVal>=1 );
  140275. if( nVal>6 ){
  140276. sqlite3_result_error(pContext,
  140277. "wrong number of arguments to function snippet()", -1);
  140278. return;
  140279. }
  140280. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  140281. switch( nVal ){
  140282. case 6: nToken = sqlite3_value_int(apVal[5]);
  140283. case 5: iCol = sqlite3_value_int(apVal[4]);
  140284. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  140285. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  140286. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  140287. }
  140288. if( !zEllipsis || !zEnd || !zStart ){
  140289. sqlite3_result_error_nomem(pContext);
  140290. }else if( nToken==0 ){
  140291. sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
  140292. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  140293. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  140294. }
  140295. }
  140296. /*
  140297. ** Implementation of the offsets() function for FTS3
  140298. */
  140299. static void fts3OffsetsFunc(
  140300. sqlite3_context *pContext, /* SQLite function call context */
  140301. int nVal, /* Size of argument array */
  140302. sqlite3_value **apVal /* Array of arguments */
  140303. ){
  140304. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  140305. UNUSED_PARAMETER(nVal);
  140306. assert( nVal==1 );
  140307. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  140308. assert( pCsr );
  140309. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  140310. sqlite3Fts3Offsets(pContext, pCsr);
  140311. }
  140312. }
  140313. /*
  140314. ** Implementation of the special optimize() function for FTS3. This
  140315. ** function merges all segments in the database to a single segment.
  140316. ** Example usage is:
  140317. **
  140318. ** SELECT optimize(t) FROM t LIMIT 1;
  140319. **
  140320. ** where 't' is the name of an FTS3 table.
  140321. */
  140322. static void fts3OptimizeFunc(
  140323. sqlite3_context *pContext, /* SQLite function call context */
  140324. int nVal, /* Size of argument array */
  140325. sqlite3_value **apVal /* Array of arguments */
  140326. ){
  140327. int rc; /* Return code */
  140328. Fts3Table *p; /* Virtual table handle */
  140329. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  140330. UNUSED_PARAMETER(nVal);
  140331. assert( nVal==1 );
  140332. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  140333. p = (Fts3Table *)pCursor->base.pVtab;
  140334. assert( p );
  140335. rc = sqlite3Fts3Optimize(p);
  140336. switch( rc ){
  140337. case SQLITE_OK:
  140338. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  140339. break;
  140340. case SQLITE_DONE:
  140341. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  140342. break;
  140343. default:
  140344. sqlite3_result_error_code(pContext, rc);
  140345. break;
  140346. }
  140347. }
  140348. /*
  140349. ** Implementation of the matchinfo() function for FTS3
  140350. */
  140351. static void fts3MatchinfoFunc(
  140352. sqlite3_context *pContext, /* SQLite function call context */
  140353. int nVal, /* Size of argument array */
  140354. sqlite3_value **apVal /* Array of arguments */
  140355. ){
  140356. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  140357. assert( nVal==1 || nVal==2 );
  140358. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  140359. const char *zArg = 0;
  140360. if( nVal>1 ){
  140361. zArg = (const char *)sqlite3_value_text(apVal[1]);
  140362. }
  140363. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  140364. }
  140365. }
  140366. /*
  140367. ** This routine implements the xFindFunction method for the FTS3
  140368. ** virtual table.
  140369. */
  140370. static int fts3FindFunctionMethod(
  140371. sqlite3_vtab *pVtab, /* Virtual table handle */
  140372. int nArg, /* Number of SQL function arguments */
  140373. const char *zName, /* Name of SQL function */
  140374. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  140375. void **ppArg /* Unused */
  140376. ){
  140377. struct Overloaded {
  140378. const char *zName;
  140379. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  140380. } aOverload[] = {
  140381. { "snippet", fts3SnippetFunc },
  140382. { "offsets", fts3OffsetsFunc },
  140383. { "optimize", fts3OptimizeFunc },
  140384. { "matchinfo", fts3MatchinfoFunc },
  140385. };
  140386. int i; /* Iterator variable */
  140387. UNUSED_PARAMETER(pVtab);
  140388. UNUSED_PARAMETER(nArg);
  140389. UNUSED_PARAMETER(ppArg);
  140390. for(i=0; i<SizeofArray(aOverload); i++){
  140391. if( strcmp(zName, aOverload[i].zName)==0 ){
  140392. *pxFunc = aOverload[i].xFunc;
  140393. return 1;
  140394. }
  140395. }
  140396. /* No function of the specified name was found. Return 0. */
  140397. return 0;
  140398. }
  140399. /*
  140400. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  140401. */
  140402. static int fts3RenameMethod(
  140403. sqlite3_vtab *pVtab, /* Virtual table handle */
  140404. const char *zName /* New name of table */
  140405. ){
  140406. Fts3Table *p = (Fts3Table *)pVtab;
  140407. sqlite3 *db = p->db; /* Database connection */
  140408. int rc; /* Return Code */
  140409. /* At this point it must be known if the %_stat table exists or not.
  140410. ** So bHasStat may not be 2. */
  140411. rc = fts3SetHasStat(p);
  140412. /* As it happens, the pending terms table is always empty here. This is
  140413. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  140414. ** always opens a savepoint transaction. And the xSavepoint() method
  140415. ** flushes the pending terms table. But leave the (no-op) call to
  140416. ** PendingTermsFlush() in in case that changes.
  140417. */
  140418. assert( p->nPendingData==0 );
  140419. if( rc==SQLITE_OK ){
  140420. rc = sqlite3Fts3PendingTermsFlush(p);
  140421. }
  140422. if( p->zContentTbl==0 ){
  140423. fts3DbExec(&rc, db,
  140424. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  140425. p->zDb, p->zName, zName
  140426. );
  140427. }
  140428. if( p->bHasDocsize ){
  140429. fts3DbExec(&rc, db,
  140430. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  140431. p->zDb, p->zName, zName
  140432. );
  140433. }
  140434. if( p->bHasStat ){
  140435. fts3DbExec(&rc, db,
  140436. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  140437. p->zDb, p->zName, zName
  140438. );
  140439. }
  140440. fts3DbExec(&rc, db,
  140441. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  140442. p->zDb, p->zName, zName
  140443. );
  140444. fts3DbExec(&rc, db,
  140445. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  140446. p->zDb, p->zName, zName
  140447. );
  140448. return rc;
  140449. }
  140450. /*
  140451. ** The xSavepoint() method.
  140452. **
  140453. ** Flush the contents of the pending-terms table to disk.
  140454. */
  140455. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  140456. int rc = SQLITE_OK;
  140457. UNUSED_PARAMETER(iSavepoint);
  140458. assert( ((Fts3Table *)pVtab)->inTransaction );
  140459. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  140460. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  140461. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  140462. rc = fts3SyncMethod(pVtab);
  140463. }
  140464. return rc;
  140465. }
  140466. /*
  140467. ** The xRelease() method.
  140468. **
  140469. ** This is a no-op.
  140470. */
  140471. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  140472. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  140473. UNUSED_PARAMETER(iSavepoint);
  140474. UNUSED_PARAMETER(pVtab);
  140475. assert( p->inTransaction );
  140476. assert( p->mxSavepoint >= iSavepoint );
  140477. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  140478. return SQLITE_OK;
  140479. }
  140480. /*
  140481. ** The xRollbackTo() method.
  140482. **
  140483. ** Discard the contents of the pending terms table.
  140484. */
  140485. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  140486. Fts3Table *p = (Fts3Table*)pVtab;
  140487. UNUSED_PARAMETER(iSavepoint);
  140488. assert( p->inTransaction );
  140489. assert( p->mxSavepoint >= iSavepoint );
  140490. TESTONLY( p->mxSavepoint = iSavepoint );
  140491. sqlite3Fts3PendingTermsClear(p);
  140492. return SQLITE_OK;
  140493. }
  140494. static const sqlite3_module fts3Module = {
  140495. /* iVersion */ 2,
  140496. /* xCreate */ fts3CreateMethod,
  140497. /* xConnect */ fts3ConnectMethod,
  140498. /* xBestIndex */ fts3BestIndexMethod,
  140499. /* xDisconnect */ fts3DisconnectMethod,
  140500. /* xDestroy */ fts3DestroyMethod,
  140501. /* xOpen */ fts3OpenMethod,
  140502. /* xClose */ fts3CloseMethod,
  140503. /* xFilter */ fts3FilterMethod,
  140504. /* xNext */ fts3NextMethod,
  140505. /* xEof */ fts3EofMethod,
  140506. /* xColumn */ fts3ColumnMethod,
  140507. /* xRowid */ fts3RowidMethod,
  140508. /* xUpdate */ fts3UpdateMethod,
  140509. /* xBegin */ fts3BeginMethod,
  140510. /* xSync */ fts3SyncMethod,
  140511. /* xCommit */ fts3CommitMethod,
  140512. /* xRollback */ fts3RollbackMethod,
  140513. /* xFindFunction */ fts3FindFunctionMethod,
  140514. /* xRename */ fts3RenameMethod,
  140515. /* xSavepoint */ fts3SavepointMethod,
  140516. /* xRelease */ fts3ReleaseMethod,
  140517. /* xRollbackTo */ fts3RollbackToMethod,
  140518. };
  140519. /*
  140520. ** This function is registered as the module destructor (called when an
  140521. ** FTS3 enabled database connection is closed). It frees the memory
  140522. ** allocated for the tokenizer hash table.
  140523. */
  140524. static void hashDestroy(void *p){
  140525. Fts3Hash *pHash = (Fts3Hash *)p;
  140526. sqlite3Fts3HashClear(pHash);
  140527. sqlite3_free(pHash);
  140528. }
  140529. /*
  140530. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  140531. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  140532. ** respectively. The following three forward declarations are for functions
  140533. ** declared in these files used to retrieve the respective implementations.
  140534. **
  140535. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  140536. ** to by the argument to point to the "simple" tokenizer implementation.
  140537. ** And so on.
  140538. */
  140539. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  140540. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  140541. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  140542. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  140543. #endif
  140544. #ifdef SQLITE_ENABLE_ICU
  140545. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  140546. #endif
  140547. /*
  140548. ** Initialize the fts3 extension. If this extension is built as part
  140549. ** of the sqlite library, then this function is called directly by
  140550. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  140551. ** function is called by the sqlite3_extension_init() entry point.
  140552. */
  140553. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  140554. int rc = SQLITE_OK;
  140555. Fts3Hash *pHash = 0;
  140556. const sqlite3_tokenizer_module *pSimple = 0;
  140557. const sqlite3_tokenizer_module *pPorter = 0;
  140558. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  140559. const sqlite3_tokenizer_module *pUnicode = 0;
  140560. #endif
  140561. #ifdef SQLITE_ENABLE_ICU
  140562. const sqlite3_tokenizer_module *pIcu = 0;
  140563. sqlite3Fts3IcuTokenizerModule(&pIcu);
  140564. #endif
  140565. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  140566. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  140567. #endif
  140568. #ifdef SQLITE_TEST
  140569. rc = sqlite3Fts3InitTerm(db);
  140570. if( rc!=SQLITE_OK ) return rc;
  140571. #endif
  140572. rc = sqlite3Fts3InitAux(db);
  140573. if( rc!=SQLITE_OK ) return rc;
  140574. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  140575. sqlite3Fts3PorterTokenizerModule(&pPorter);
  140576. /* Allocate and initialize the hash-table used to store tokenizers. */
  140577. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  140578. if( !pHash ){
  140579. rc = SQLITE_NOMEM;
  140580. }else{
  140581. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  140582. }
  140583. /* Load the built-in tokenizers into the hash table */
  140584. if( rc==SQLITE_OK ){
  140585. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  140586. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  140587. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  140588. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  140589. #endif
  140590. #ifdef SQLITE_ENABLE_ICU
  140591. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  140592. #endif
  140593. ){
  140594. rc = SQLITE_NOMEM;
  140595. }
  140596. }
  140597. #ifdef SQLITE_TEST
  140598. if( rc==SQLITE_OK ){
  140599. rc = sqlite3Fts3ExprInitTestInterface(db);
  140600. }
  140601. #endif
  140602. /* Create the virtual table wrapper around the hash-table and overload
  140603. ** the four scalar functions. If this is successful, register the
  140604. ** module with sqlite.
  140605. */
  140606. if( SQLITE_OK==rc
  140607. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  140608. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  140609. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  140610. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  140611. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  140612. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  140613. ){
  140614. rc = sqlite3_create_module_v2(
  140615. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  140616. );
  140617. if( rc==SQLITE_OK ){
  140618. rc = sqlite3_create_module_v2(
  140619. db, "fts4", &fts3Module, (void *)pHash, 0
  140620. );
  140621. }
  140622. if( rc==SQLITE_OK ){
  140623. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  140624. }
  140625. return rc;
  140626. }
  140627. /* An error has occurred. Delete the hash table and return the error code. */
  140628. assert( rc!=SQLITE_OK );
  140629. if( pHash ){
  140630. sqlite3Fts3HashClear(pHash);
  140631. sqlite3_free(pHash);
  140632. }
  140633. return rc;
  140634. }
  140635. /*
  140636. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  140637. ** by pExpr.
  140638. **
  140639. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  140640. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  140641. ** Fts3SegReader objects internally to provide an interface to seek or scan
  140642. ** within the union of all segments of a b-tree. Hence the name.
  140643. **
  140644. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  140645. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  140646. ** there exists prefix b-tree of the right length) then it may be traversed
  140647. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  140648. ** doclist and then traversed.
  140649. */
  140650. static void fts3EvalAllocateReaders(
  140651. Fts3Cursor *pCsr, /* FTS cursor handle */
  140652. Fts3Expr *pExpr, /* Allocate readers for this expression */
  140653. int *pnToken, /* OUT: Total number of tokens in phrase. */
  140654. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  140655. int *pRc /* IN/OUT: Error code */
  140656. ){
  140657. if( pExpr && SQLITE_OK==*pRc ){
  140658. if( pExpr->eType==FTSQUERY_PHRASE ){
  140659. int i;
  140660. int nToken = pExpr->pPhrase->nToken;
  140661. *pnToken += nToken;
  140662. for(i=0; i<nToken; i++){
  140663. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  140664. int rc = fts3TermSegReaderCursor(pCsr,
  140665. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  140666. );
  140667. if( rc!=SQLITE_OK ){
  140668. *pRc = rc;
  140669. return;
  140670. }
  140671. }
  140672. assert( pExpr->pPhrase->iDoclistToken==0 );
  140673. pExpr->pPhrase->iDoclistToken = -1;
  140674. }else{
  140675. *pnOr += (pExpr->eType==FTSQUERY_OR);
  140676. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  140677. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  140678. }
  140679. }
  140680. }
  140681. /*
  140682. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  140683. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  140684. **
  140685. ** This function assumes that pList points to a buffer allocated using
  140686. ** sqlite3_malloc(). This function takes responsibility for eventually
  140687. ** freeing the buffer.
  140688. **
  140689. ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
  140690. */
  140691. static int fts3EvalPhraseMergeToken(
  140692. Fts3Table *pTab, /* FTS Table pointer */
  140693. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  140694. int iToken, /* Token pList/nList corresponds to */
  140695. char *pList, /* Pointer to doclist */
  140696. int nList /* Number of bytes in pList */
  140697. ){
  140698. int rc = SQLITE_OK;
  140699. assert( iToken!=p->iDoclistToken );
  140700. if( pList==0 ){
  140701. sqlite3_free(p->doclist.aAll);
  140702. p->doclist.aAll = 0;
  140703. p->doclist.nAll = 0;
  140704. }
  140705. else if( p->iDoclistToken<0 ){
  140706. p->doclist.aAll = pList;
  140707. p->doclist.nAll = nList;
  140708. }
  140709. else if( p->doclist.aAll==0 ){
  140710. sqlite3_free(pList);
  140711. }
  140712. else {
  140713. char *pLeft;
  140714. char *pRight;
  140715. int nLeft;
  140716. int nRight;
  140717. int nDiff;
  140718. if( p->iDoclistToken<iToken ){
  140719. pLeft = p->doclist.aAll;
  140720. nLeft = p->doclist.nAll;
  140721. pRight = pList;
  140722. nRight = nList;
  140723. nDiff = iToken - p->iDoclistToken;
  140724. }else{
  140725. pRight = p->doclist.aAll;
  140726. nRight = p->doclist.nAll;
  140727. pLeft = pList;
  140728. nLeft = nList;
  140729. nDiff = p->iDoclistToken - iToken;
  140730. }
  140731. rc = fts3DoclistPhraseMerge(
  140732. pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
  140733. );
  140734. sqlite3_free(pLeft);
  140735. p->doclist.aAll = pRight;
  140736. p->doclist.nAll = nRight;
  140737. }
  140738. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  140739. return rc;
  140740. }
  140741. /*
  140742. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  140743. ** does not take deferred tokens into account.
  140744. **
  140745. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  140746. */
  140747. static int fts3EvalPhraseLoad(
  140748. Fts3Cursor *pCsr, /* FTS Cursor handle */
  140749. Fts3Phrase *p /* Phrase object */
  140750. ){
  140751. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  140752. int iToken;
  140753. int rc = SQLITE_OK;
  140754. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  140755. Fts3PhraseToken *pToken = &p->aToken[iToken];
  140756. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  140757. if( pToken->pSegcsr ){
  140758. int nThis = 0;
  140759. char *pThis = 0;
  140760. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  140761. if( rc==SQLITE_OK ){
  140762. rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  140763. }
  140764. }
  140765. assert( pToken->pSegcsr==0 );
  140766. }
  140767. return rc;
  140768. }
  140769. /*
  140770. ** This function is called on each phrase after the position lists for
  140771. ** any deferred tokens have been loaded into memory. It updates the phrases
  140772. ** current position list to include only those positions that are really
  140773. ** instances of the phrase (after considering deferred tokens). If this
  140774. ** means that the phrase does not appear in the current row, doclist.pList
  140775. ** and doclist.nList are both zeroed.
  140776. **
  140777. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  140778. */
  140779. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  140780. int iToken; /* Used to iterate through phrase tokens */
  140781. char *aPoslist = 0; /* Position list for deferred tokens */
  140782. int nPoslist = 0; /* Number of bytes in aPoslist */
  140783. int iPrev = -1; /* Token number of previous deferred token */
  140784. assert( pPhrase->doclist.bFreeList==0 );
  140785. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  140786. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  140787. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  140788. if( pDeferred ){
  140789. char *pList;
  140790. int nList;
  140791. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  140792. if( rc!=SQLITE_OK ) return rc;
  140793. if( pList==0 ){
  140794. sqlite3_free(aPoslist);
  140795. pPhrase->doclist.pList = 0;
  140796. pPhrase->doclist.nList = 0;
  140797. return SQLITE_OK;
  140798. }else if( aPoslist==0 ){
  140799. aPoslist = pList;
  140800. nPoslist = nList;
  140801. }else{
  140802. char *aOut = pList;
  140803. char *p1 = aPoslist;
  140804. char *p2 = aOut;
  140805. assert( iPrev>=0 );
  140806. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  140807. sqlite3_free(aPoslist);
  140808. aPoslist = pList;
  140809. nPoslist = (int)(aOut - aPoslist);
  140810. if( nPoslist==0 ){
  140811. sqlite3_free(aPoslist);
  140812. pPhrase->doclist.pList = 0;
  140813. pPhrase->doclist.nList = 0;
  140814. return SQLITE_OK;
  140815. }
  140816. }
  140817. iPrev = iToken;
  140818. }
  140819. }
  140820. if( iPrev>=0 ){
  140821. int nMaxUndeferred = pPhrase->iDoclistToken;
  140822. if( nMaxUndeferred<0 ){
  140823. pPhrase->doclist.pList = aPoslist;
  140824. pPhrase->doclist.nList = nPoslist;
  140825. pPhrase->doclist.iDocid = pCsr->iPrevId;
  140826. pPhrase->doclist.bFreeList = 1;
  140827. }else{
  140828. int nDistance;
  140829. char *p1;
  140830. char *p2;
  140831. char *aOut;
  140832. if( nMaxUndeferred>iPrev ){
  140833. p1 = aPoslist;
  140834. p2 = pPhrase->doclist.pList;
  140835. nDistance = nMaxUndeferred - iPrev;
  140836. }else{
  140837. p1 = pPhrase->doclist.pList;
  140838. p2 = aPoslist;
  140839. nDistance = iPrev - nMaxUndeferred;
  140840. }
  140841. aOut = (char *)sqlite3_malloc(nPoslist+8);
  140842. if( !aOut ){
  140843. sqlite3_free(aPoslist);
  140844. return SQLITE_NOMEM;
  140845. }
  140846. pPhrase->doclist.pList = aOut;
  140847. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  140848. pPhrase->doclist.bFreeList = 1;
  140849. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  140850. }else{
  140851. sqlite3_free(aOut);
  140852. pPhrase->doclist.pList = 0;
  140853. pPhrase->doclist.nList = 0;
  140854. }
  140855. sqlite3_free(aPoslist);
  140856. }
  140857. }
  140858. return SQLITE_OK;
  140859. }
  140860. /*
  140861. ** Maximum number of tokens a phrase may have to be considered for the
  140862. ** incremental doclists strategy.
  140863. */
  140864. #define MAX_INCR_PHRASE_TOKENS 4
  140865. /*
  140866. ** This function is called for each Fts3Phrase in a full-text query
  140867. ** expression to initialize the mechanism for returning rows. Once this
  140868. ** function has been called successfully on an Fts3Phrase, it may be
  140869. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  140870. **
  140871. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  140872. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  140873. ** memory within this call.
  140874. **
  140875. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  140876. */
  140877. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  140878. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  140879. int rc = SQLITE_OK; /* Error code */
  140880. int i;
  140881. /* Determine if doclists may be loaded from disk incrementally. This is
  140882. ** possible if the bOptOk argument is true, the FTS doclists will be
  140883. ** scanned in forward order, and the phrase consists of
  140884. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  140885. ** tokens or prefix tokens that cannot use a prefix-index. */
  140886. int bHaveIncr = 0;
  140887. int bIncrOk = (bOptOk
  140888. && pCsr->bDesc==pTab->bDescIdx
  140889. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  140890. #ifdef SQLITE_TEST
  140891. && pTab->bNoIncrDoclist==0
  140892. #endif
  140893. );
  140894. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  140895. Fts3PhraseToken *pToken = &p->aToken[i];
  140896. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  140897. bIncrOk = 0;
  140898. }
  140899. if( pToken->pSegcsr ) bHaveIncr = 1;
  140900. }
  140901. if( bIncrOk && bHaveIncr ){
  140902. /* Use the incremental approach. */
  140903. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  140904. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  140905. Fts3PhraseToken *pToken = &p->aToken[i];
  140906. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  140907. if( pSegcsr ){
  140908. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  140909. }
  140910. }
  140911. p->bIncr = 1;
  140912. }else{
  140913. /* Load the full doclist for the phrase into memory. */
  140914. rc = fts3EvalPhraseLoad(pCsr, p);
  140915. p->bIncr = 0;
  140916. }
  140917. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  140918. return rc;
  140919. }
  140920. /*
  140921. ** This function is used to iterate backwards (from the end to start)
  140922. ** through doclists. It is used by this module to iterate through phrase
  140923. ** doclists in reverse and by the fts3_write.c module to iterate through
  140924. ** pending-terms lists when writing to databases with "order=desc".
  140925. **
  140926. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  140927. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  140928. ** function iterates from the end of the doclist to the beginning.
  140929. */
  140930. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  140931. int bDescIdx, /* True if the doclist is desc */
  140932. char *aDoclist, /* Pointer to entire doclist */
  140933. int nDoclist, /* Length of aDoclist in bytes */
  140934. char **ppIter, /* IN/OUT: Iterator pointer */
  140935. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  140936. int *pnList, /* OUT: List length pointer */
  140937. u8 *pbEof /* OUT: End-of-file flag */
  140938. ){
  140939. char *p = *ppIter;
  140940. assert( nDoclist>0 );
  140941. assert( *pbEof==0 );
  140942. assert( p || *piDocid==0 );
  140943. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  140944. if( p==0 ){
  140945. sqlite3_int64 iDocid = 0;
  140946. char *pNext = 0;
  140947. char *pDocid = aDoclist;
  140948. char *pEnd = &aDoclist[nDoclist];
  140949. int iMul = 1;
  140950. while( pDocid<pEnd ){
  140951. sqlite3_int64 iDelta;
  140952. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  140953. iDocid += (iMul * iDelta);
  140954. pNext = pDocid;
  140955. fts3PoslistCopy(0, &pDocid);
  140956. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  140957. iMul = (bDescIdx ? -1 : 1);
  140958. }
  140959. *pnList = (int)(pEnd - pNext);
  140960. *ppIter = pNext;
  140961. *piDocid = iDocid;
  140962. }else{
  140963. int iMul = (bDescIdx ? -1 : 1);
  140964. sqlite3_int64 iDelta;
  140965. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  140966. *piDocid -= (iMul * iDelta);
  140967. if( p==aDoclist ){
  140968. *pbEof = 1;
  140969. }else{
  140970. char *pSave = p;
  140971. fts3ReversePoslist(aDoclist, &p);
  140972. *pnList = (int)(pSave - p);
  140973. }
  140974. *ppIter = p;
  140975. }
  140976. }
  140977. /*
  140978. ** Iterate forwards through a doclist.
  140979. */
  140980. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  140981. int bDescIdx, /* True if the doclist is desc */
  140982. char *aDoclist, /* Pointer to entire doclist */
  140983. int nDoclist, /* Length of aDoclist in bytes */
  140984. char **ppIter, /* IN/OUT: Iterator pointer */
  140985. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  140986. u8 *pbEof /* OUT: End-of-file flag */
  140987. ){
  140988. char *p = *ppIter;
  140989. assert( nDoclist>0 );
  140990. assert( *pbEof==0 );
  140991. assert( p || *piDocid==0 );
  140992. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  140993. if( p==0 ){
  140994. p = aDoclist;
  140995. p += sqlite3Fts3GetVarint(p, piDocid);
  140996. }else{
  140997. fts3PoslistCopy(0, &p);
  140998. while( p<&aDoclist[nDoclist] && *p==0 ) p++;
  140999. if( p>=&aDoclist[nDoclist] ){
  141000. *pbEof = 1;
  141001. }else{
  141002. sqlite3_int64 iVar;
  141003. p += sqlite3Fts3GetVarint(p, &iVar);
  141004. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  141005. }
  141006. }
  141007. *ppIter = p;
  141008. }
  141009. /*
  141010. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  141011. ** to true if EOF is reached.
  141012. */
  141013. static void fts3EvalDlPhraseNext(
  141014. Fts3Table *pTab,
  141015. Fts3Doclist *pDL,
  141016. u8 *pbEof
  141017. ){
  141018. char *pIter; /* Used to iterate through aAll */
  141019. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  141020. if( pDL->pNextDocid ){
  141021. pIter = pDL->pNextDocid;
  141022. }else{
  141023. pIter = pDL->aAll;
  141024. }
  141025. if( pIter>=pEnd ){
  141026. /* We have already reached the end of this doclist. EOF. */
  141027. *pbEof = 1;
  141028. }else{
  141029. sqlite3_int64 iDelta;
  141030. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  141031. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  141032. pDL->iDocid += iDelta;
  141033. }else{
  141034. pDL->iDocid -= iDelta;
  141035. }
  141036. pDL->pList = pIter;
  141037. fts3PoslistCopy(0, &pIter);
  141038. pDL->nList = (int)(pIter - pDL->pList);
  141039. /* pIter now points just past the 0x00 that terminates the position-
  141040. ** list for document pDL->iDocid. However, if this position-list was
  141041. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  141042. ** point to the start of the next docid value. The following line deals
  141043. ** with this case by advancing pIter past the zero-padding added by
  141044. ** fts3EvalNearTrim(). */
  141045. while( pIter<pEnd && *pIter==0 ) pIter++;
  141046. pDL->pNextDocid = pIter;
  141047. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  141048. *pbEof = 0;
  141049. }
  141050. }
  141051. /*
  141052. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  141053. */
  141054. typedef struct TokenDoclist TokenDoclist;
  141055. struct TokenDoclist {
  141056. int bIgnore;
  141057. sqlite3_int64 iDocid;
  141058. char *pList;
  141059. int nList;
  141060. };
  141061. /*
  141062. ** Token pToken is an incrementally loaded token that is part of a
  141063. ** multi-token phrase. Advance it to the next matching document in the
  141064. ** database and populate output variable *p with the details of the new
  141065. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  141066. **
  141067. ** If an error occurs, return an SQLite error code. Otherwise, return
  141068. ** SQLITE_OK.
  141069. */
  141070. static int incrPhraseTokenNext(
  141071. Fts3Table *pTab, /* Virtual table handle */
  141072. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  141073. int iToken, /* Specific token to advance */
  141074. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  141075. u8 *pbEof /* OUT: True if iterator is at EOF */
  141076. ){
  141077. int rc = SQLITE_OK;
  141078. if( pPhrase->iDoclistToken==iToken ){
  141079. assert( p->bIgnore==0 );
  141080. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  141081. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  141082. p->pList = pPhrase->doclist.pList;
  141083. p->nList = pPhrase->doclist.nList;
  141084. p->iDocid = pPhrase->doclist.iDocid;
  141085. }else{
  141086. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  141087. assert( pToken->pDeferred==0 );
  141088. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  141089. if( pToken->pSegcsr ){
  141090. assert( p->bIgnore==0 );
  141091. rc = sqlite3Fts3MsrIncrNext(
  141092. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  141093. );
  141094. if( p->pList==0 ) *pbEof = 1;
  141095. }else{
  141096. p->bIgnore = 1;
  141097. }
  141098. }
  141099. return rc;
  141100. }
  141101. /*
  141102. ** The phrase iterator passed as the second argument:
  141103. **
  141104. ** * features at least one token that uses an incremental doclist, and
  141105. **
  141106. ** * does not contain any deferred tokens.
  141107. **
  141108. ** Advance it to the next matching documnent in the database and populate
  141109. ** the Fts3Doclist.pList and nList fields.
  141110. **
  141111. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  141112. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  141113. ** successfully advanced, *pbEof is set to 0.
  141114. **
  141115. ** If an error occurs, return an SQLite error code. Otherwise, return
  141116. ** SQLITE_OK.
  141117. */
  141118. static int fts3EvalIncrPhraseNext(
  141119. Fts3Cursor *pCsr, /* FTS Cursor handle */
  141120. Fts3Phrase *p, /* Phrase object to advance to next docid */
  141121. u8 *pbEof /* OUT: Set to 1 if EOF */
  141122. ){
  141123. int rc = SQLITE_OK;
  141124. Fts3Doclist *pDL = &p->doclist;
  141125. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  141126. u8 bEof = 0;
  141127. /* This is only called if it is guaranteed that the phrase has at least
  141128. ** one incremental token. In which case the bIncr flag is set. */
  141129. assert( p->bIncr==1 );
  141130. if( p->nToken==1 ){
  141131. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  141132. &pDL->iDocid, &pDL->pList, &pDL->nList
  141133. );
  141134. if( pDL->pList==0 ) bEof = 1;
  141135. }else{
  141136. int bDescDoclist = pCsr->bDesc;
  141137. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  141138. memset(a, 0, sizeof(a));
  141139. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  141140. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  141141. while( bEof==0 ){
  141142. int bMaxSet = 0;
  141143. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  141144. int i; /* Used to iterate through tokens */
  141145. /* Advance the iterator for each token in the phrase once. */
  141146. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  141147. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  141148. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  141149. iMax = a[i].iDocid;
  141150. bMaxSet = 1;
  141151. }
  141152. }
  141153. assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
  141154. assert( rc!=SQLITE_OK || bMaxSet );
  141155. /* Keep advancing iterators until they all point to the same document */
  141156. for(i=0; i<p->nToken; i++){
  141157. while( rc==SQLITE_OK && bEof==0
  141158. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  141159. ){
  141160. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  141161. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  141162. iMax = a[i].iDocid;
  141163. i = 0;
  141164. }
  141165. }
  141166. }
  141167. /* Check if the current entries really are a phrase match */
  141168. if( bEof==0 ){
  141169. int nList = 0;
  141170. int nByte = a[p->nToken-1].nList;
  141171. char *aDoclist = sqlite3_malloc(nByte+1);
  141172. if( !aDoclist ) return SQLITE_NOMEM;
  141173. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  141174. for(i=0; i<(p->nToken-1); i++){
  141175. if( a[i].bIgnore==0 ){
  141176. char *pL = a[i].pList;
  141177. char *pR = aDoclist;
  141178. char *pOut = aDoclist;
  141179. int nDist = p->nToken-1-i;
  141180. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  141181. if( res==0 ) break;
  141182. nList = (int)(pOut - aDoclist);
  141183. }
  141184. }
  141185. if( i==(p->nToken-1) ){
  141186. pDL->iDocid = iMax;
  141187. pDL->pList = aDoclist;
  141188. pDL->nList = nList;
  141189. pDL->bFreeList = 1;
  141190. break;
  141191. }
  141192. sqlite3_free(aDoclist);
  141193. }
  141194. }
  141195. }
  141196. *pbEof = bEof;
  141197. return rc;
  141198. }
  141199. /*
  141200. ** Attempt to move the phrase iterator to point to the next matching docid.
  141201. ** If an error occurs, return an SQLite error code. Otherwise, return
  141202. ** SQLITE_OK.
  141203. **
  141204. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  141205. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  141206. ** successfully advanced, *pbEof is set to 0.
  141207. */
  141208. static int fts3EvalPhraseNext(
  141209. Fts3Cursor *pCsr, /* FTS Cursor handle */
  141210. Fts3Phrase *p, /* Phrase object to advance to next docid */
  141211. u8 *pbEof /* OUT: Set to 1 if EOF */
  141212. ){
  141213. int rc = SQLITE_OK;
  141214. Fts3Doclist *pDL = &p->doclist;
  141215. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  141216. if( p->bIncr ){
  141217. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  141218. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  141219. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  141220. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  141221. );
  141222. pDL->pList = pDL->pNextDocid;
  141223. }else{
  141224. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  141225. }
  141226. return rc;
  141227. }
  141228. /*
  141229. **
  141230. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  141231. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  141232. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  141233. ** expressions for which all descendent tokens are deferred.
  141234. **
  141235. ** If parameter bOptOk is zero, then it is guaranteed that the
  141236. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  141237. ** each phrase in the expression (subject to deferred token processing).
  141238. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  141239. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  141240. **
  141241. ** If an error occurs within this function, *pRc is set to an SQLite error
  141242. ** code before returning.
  141243. */
  141244. static void fts3EvalStartReaders(
  141245. Fts3Cursor *pCsr, /* FTS Cursor handle */
  141246. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  141247. int *pRc /* IN/OUT: Error code */
  141248. ){
  141249. if( pExpr && SQLITE_OK==*pRc ){
  141250. if( pExpr->eType==FTSQUERY_PHRASE ){
  141251. int nToken = pExpr->pPhrase->nToken;
  141252. if( nToken ){
  141253. int i;
  141254. for(i=0; i<nToken; i++){
  141255. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  141256. }
  141257. pExpr->bDeferred = (i==nToken);
  141258. }
  141259. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  141260. }else{
  141261. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  141262. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  141263. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  141264. }
  141265. }
  141266. }
  141267. /*
  141268. ** An array of the following structures is assembled as part of the process
  141269. ** of selecting tokens to defer before the query starts executing (as part
  141270. ** of the xFilter() method). There is one element in the array for each
  141271. ** token in the FTS expression.
  141272. **
  141273. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  141274. ** to phrases that are connected only by AND and NEAR operators (not OR or
  141275. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  141276. ** separately. The root of a tokens AND/NEAR cluster is stored in
  141277. ** Fts3TokenAndCost.pRoot.
  141278. */
  141279. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  141280. struct Fts3TokenAndCost {
  141281. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  141282. int iToken; /* Position of token in phrase */
  141283. Fts3PhraseToken *pToken; /* The token itself */
  141284. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  141285. int nOvfl; /* Number of overflow pages to load doclist */
  141286. int iCol; /* The column the token must match */
  141287. };
  141288. /*
  141289. ** This function is used to populate an allocated Fts3TokenAndCost array.
  141290. **
  141291. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  141292. ** Otherwise, if an error occurs during execution, *pRc is set to an
  141293. ** SQLite error code.
  141294. */
  141295. static void fts3EvalTokenCosts(
  141296. Fts3Cursor *pCsr, /* FTS Cursor handle */
  141297. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  141298. Fts3Expr *pExpr, /* Expression to consider */
  141299. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  141300. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  141301. int *pRc /* IN/OUT: Error code */
  141302. ){
  141303. if( *pRc==SQLITE_OK ){
  141304. if( pExpr->eType==FTSQUERY_PHRASE ){
  141305. Fts3Phrase *pPhrase = pExpr->pPhrase;
  141306. int i;
  141307. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  141308. Fts3TokenAndCost *pTC = (*ppTC)++;
  141309. pTC->pPhrase = pPhrase;
  141310. pTC->iToken = i;
  141311. pTC->pRoot = pRoot;
  141312. pTC->pToken = &pPhrase->aToken[i];
  141313. pTC->iCol = pPhrase->iColumn;
  141314. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  141315. }
  141316. }else if( pExpr->eType!=FTSQUERY_NOT ){
  141317. assert( pExpr->eType==FTSQUERY_OR
  141318. || pExpr->eType==FTSQUERY_AND
  141319. || pExpr->eType==FTSQUERY_NEAR
  141320. );
  141321. assert( pExpr->pLeft && pExpr->pRight );
  141322. if( pExpr->eType==FTSQUERY_OR ){
  141323. pRoot = pExpr->pLeft;
  141324. **ppOr = pRoot;
  141325. (*ppOr)++;
  141326. }
  141327. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  141328. if( pExpr->eType==FTSQUERY_OR ){
  141329. pRoot = pExpr->pRight;
  141330. **ppOr = pRoot;
  141331. (*ppOr)++;
  141332. }
  141333. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  141334. }
  141335. }
  141336. }
  141337. /*
  141338. ** Determine the average document (row) size in pages. If successful,
  141339. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  141340. ** an SQLite error code.
  141341. **
  141342. ** The average document size in pages is calculated by first calculating
  141343. ** determining the average size in bytes, B. If B is less than the amount
  141344. ** of data that will fit on a single leaf page of an intkey table in
  141345. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  141346. ** the number of overflow pages consumed by a record B bytes in size.
  141347. */
  141348. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  141349. int rc = SQLITE_OK;
  141350. if( pCsr->nRowAvg==0 ){
  141351. /* The average document size, which is required to calculate the cost
  141352. ** of each doclist, has not yet been determined. Read the required
  141353. ** data from the %_stat table to calculate it.
  141354. **
  141355. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  141356. ** varints, where nCol is the number of columns in the FTS3 table.
  141357. ** The first varint is the number of documents currently stored in
  141358. ** the table. The following nCol varints contain the total amount of
  141359. ** data stored in all rows of each column of the table, from left
  141360. ** to right.
  141361. */
  141362. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  141363. sqlite3_stmt *pStmt;
  141364. sqlite3_int64 nDoc = 0;
  141365. sqlite3_int64 nByte = 0;
  141366. const char *pEnd;
  141367. const char *a;
  141368. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  141369. if( rc!=SQLITE_OK ) return rc;
  141370. a = sqlite3_column_blob(pStmt, 0);
  141371. assert( a );
  141372. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  141373. a += sqlite3Fts3GetVarint(a, &nDoc);
  141374. while( a<pEnd ){
  141375. a += sqlite3Fts3GetVarint(a, &nByte);
  141376. }
  141377. if( nDoc==0 || nByte==0 ){
  141378. sqlite3_reset(pStmt);
  141379. return FTS_CORRUPT_VTAB;
  141380. }
  141381. pCsr->nDoc = nDoc;
  141382. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  141383. assert( pCsr->nRowAvg>0 );
  141384. rc = sqlite3_reset(pStmt);
  141385. }
  141386. *pnPage = pCsr->nRowAvg;
  141387. return rc;
  141388. }
  141389. /*
  141390. ** This function is called to select the tokens (if any) that will be
  141391. ** deferred. The array aTC[] has already been populated when this is
  141392. ** called.
  141393. **
  141394. ** This function is called once for each AND/NEAR cluster in the
  141395. ** expression. Each invocation determines which tokens to defer within
  141396. ** the cluster with root node pRoot. See comments above the definition
  141397. ** of struct Fts3TokenAndCost for more details.
  141398. **
  141399. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  141400. ** called on each token to defer. Otherwise, an SQLite error code is
  141401. ** returned.
  141402. */
  141403. static int fts3EvalSelectDeferred(
  141404. Fts3Cursor *pCsr, /* FTS Cursor handle */
  141405. Fts3Expr *pRoot, /* Consider tokens with this root node */
  141406. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  141407. int nTC /* Number of entries in aTC[] */
  141408. ){
  141409. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  141410. int nDocSize = 0; /* Number of pages per doc loaded */
  141411. int rc = SQLITE_OK; /* Return code */
  141412. int ii; /* Iterator variable for various purposes */
  141413. int nOvfl = 0; /* Total overflow pages used by doclists */
  141414. int nToken = 0; /* Total number of tokens in cluster */
  141415. int nMinEst = 0; /* The minimum count for any phrase so far. */
  141416. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  141417. /* Tokens are never deferred for FTS tables created using the content=xxx
  141418. ** option. The reason being that it is not guaranteed that the content
  141419. ** table actually contains the same data as the index. To prevent this from
  141420. ** causing any problems, the deferred token optimization is completely
  141421. ** disabled for content=xxx tables. */
  141422. if( pTab->zContentTbl ){
  141423. return SQLITE_OK;
  141424. }
  141425. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  141426. ** associated with the tokens spill onto overflow pages, or if there is
  141427. ** only 1 token, exit early. No tokens to defer in this case. */
  141428. for(ii=0; ii<nTC; ii++){
  141429. if( aTC[ii].pRoot==pRoot ){
  141430. nOvfl += aTC[ii].nOvfl;
  141431. nToken++;
  141432. }
  141433. }
  141434. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  141435. /* Obtain the average docsize (in pages). */
  141436. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  141437. assert( rc!=SQLITE_OK || nDocSize>0 );
  141438. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  141439. ** of the number of overflow pages that will be loaded by the pager layer
  141440. ** to retrieve the entire doclist for the token from the full-text index.
  141441. ** Load the doclists for tokens that are either:
  141442. **
  141443. ** a. The cheapest token in the entire query (i.e. the one visited by the
  141444. ** first iteration of this loop), or
  141445. **
  141446. ** b. Part of a multi-token phrase.
  141447. **
  141448. ** After each token doclist is loaded, merge it with the others from the
  141449. ** same phrase and count the number of documents that the merged doclist
  141450. ** contains. Set variable "nMinEst" to the smallest number of documents in
  141451. ** any phrase doclist for which 1 or more token doclists have been loaded.
  141452. ** Let nOther be the number of other phrases for which it is certain that
  141453. ** one or more tokens will not be deferred.
  141454. **
  141455. ** Then, for each token, defer it if loading the doclist would result in
  141456. ** loading N or more overflow pages into memory, where N is computed as:
  141457. **
  141458. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  141459. */
  141460. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  141461. int iTC; /* Used to iterate through aTC[] array. */
  141462. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  141463. /* Set pTC to point to the cheapest remaining token. */
  141464. for(iTC=0; iTC<nTC; iTC++){
  141465. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  141466. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  141467. ){
  141468. pTC = &aTC[iTC];
  141469. }
  141470. }
  141471. assert( pTC );
  141472. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  141473. /* The number of overflow pages to load for this (and therefore all
  141474. ** subsequent) tokens is greater than the estimated number of pages
  141475. ** that will be loaded if all subsequent tokens are deferred.
  141476. */
  141477. Fts3PhraseToken *pToken = pTC->pToken;
  141478. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  141479. fts3SegReaderCursorFree(pToken->pSegcsr);
  141480. pToken->pSegcsr = 0;
  141481. }else{
  141482. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  141483. ** for-loop. Except, limit the value to 2^24 to prevent it from
  141484. ** overflowing the 32-bit integer it is stored in. */
  141485. if( ii<12 ) nLoad4 = nLoad4*4;
  141486. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  141487. /* Either this is the cheapest token in the entire query, or it is
  141488. ** part of a multi-token phrase. Either way, the entire doclist will
  141489. ** (eventually) be loaded into memory. It may as well be now. */
  141490. Fts3PhraseToken *pToken = pTC->pToken;
  141491. int nList = 0;
  141492. char *pList = 0;
  141493. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  141494. assert( rc==SQLITE_OK || pList==0 );
  141495. if( rc==SQLITE_OK ){
  141496. rc = fts3EvalPhraseMergeToken(
  141497. pTab, pTC->pPhrase, pTC->iToken,pList,nList
  141498. );
  141499. }
  141500. if( rc==SQLITE_OK ){
  141501. int nCount;
  141502. nCount = fts3DoclistCountDocids(
  141503. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  141504. );
  141505. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  141506. }
  141507. }
  141508. }
  141509. pTC->pToken = 0;
  141510. }
  141511. return rc;
  141512. }
  141513. /*
  141514. ** This function is called from within the xFilter method. It initializes
  141515. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  141516. ** the results of a query, the caller does:
  141517. **
  141518. ** fts3EvalStart(pCsr);
  141519. ** while( 1 ){
  141520. ** fts3EvalNext(pCsr);
  141521. ** if( pCsr->bEof ) break;
  141522. ** ... return row pCsr->iPrevId to the caller ...
  141523. ** }
  141524. */
  141525. static int fts3EvalStart(Fts3Cursor *pCsr){
  141526. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  141527. int rc = SQLITE_OK;
  141528. int nToken = 0;
  141529. int nOr = 0;
  141530. /* Allocate a MultiSegReader for each token in the expression. */
  141531. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  141532. /* Determine which, if any, tokens in the expression should be deferred. */
  141533. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  141534. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  141535. Fts3TokenAndCost *aTC;
  141536. Fts3Expr **apOr;
  141537. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  141538. sizeof(Fts3TokenAndCost) * nToken
  141539. + sizeof(Fts3Expr *) * nOr * 2
  141540. );
  141541. apOr = (Fts3Expr **)&aTC[nToken];
  141542. if( !aTC ){
  141543. rc = SQLITE_NOMEM;
  141544. }else{
  141545. int ii;
  141546. Fts3TokenAndCost *pTC = aTC;
  141547. Fts3Expr **ppOr = apOr;
  141548. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  141549. nToken = (int)(pTC-aTC);
  141550. nOr = (int)(ppOr-apOr);
  141551. if( rc==SQLITE_OK ){
  141552. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  141553. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  141554. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  141555. }
  141556. }
  141557. sqlite3_free(aTC);
  141558. }
  141559. }
  141560. #endif
  141561. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  141562. return rc;
  141563. }
  141564. /*
  141565. ** Invalidate the current position list for phrase pPhrase.
  141566. */
  141567. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  141568. if( pPhrase->doclist.bFreeList ){
  141569. sqlite3_free(pPhrase->doclist.pList);
  141570. }
  141571. pPhrase->doclist.pList = 0;
  141572. pPhrase->doclist.nList = 0;
  141573. pPhrase->doclist.bFreeList = 0;
  141574. }
  141575. /*
  141576. ** This function is called to edit the position list associated with
  141577. ** the phrase object passed as the fifth argument according to a NEAR
  141578. ** condition. For example:
  141579. **
  141580. ** abc NEAR/5 "def ghi"
  141581. **
  141582. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  141583. ** the example above). When this function is called, *paPoslist points to
  141584. ** the position list, and *pnToken is the number of phrase tokens in, the
  141585. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  141586. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  141587. ** the position list associated with phrase "abc".
  141588. **
  141589. ** All positions in the pPhrase position list that are not sufficiently
  141590. ** close to a position in the *paPoslist position list are removed. If this
  141591. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  141592. **
  141593. ** Before returning, *paPoslist is set to point to the position lsit
  141594. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  141595. ** pPhrase.
  141596. */
  141597. static int fts3EvalNearTrim(
  141598. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  141599. char *aTmp, /* Temporary space to use */
  141600. char **paPoslist, /* IN/OUT: Position list */
  141601. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  141602. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  141603. ){
  141604. int nParam1 = nNear + pPhrase->nToken;
  141605. int nParam2 = nNear + *pnToken;
  141606. int nNew;
  141607. char *p2;
  141608. char *pOut;
  141609. int res;
  141610. assert( pPhrase->doclist.pList );
  141611. p2 = pOut = pPhrase->doclist.pList;
  141612. res = fts3PoslistNearMerge(
  141613. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  141614. );
  141615. if( res ){
  141616. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  141617. assert( pPhrase->doclist.pList[nNew]=='\0' );
  141618. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  141619. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  141620. pPhrase->doclist.nList = nNew;
  141621. *paPoslist = pPhrase->doclist.pList;
  141622. *pnToken = pPhrase->nToken;
  141623. }
  141624. return res;
  141625. }
  141626. /*
  141627. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  141628. ** Otherwise, it advances the expression passed as the second argument to
  141629. ** point to the next matching row in the database. Expressions iterate through
  141630. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  141631. ** or descending if it is non-zero.
  141632. **
  141633. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  141634. ** successful, the following variables in pExpr are set:
  141635. **
  141636. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  141637. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  141638. **
  141639. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  141640. ** at EOF, then the following variables are populated with the position list
  141641. ** for the phrase for the visited row:
  141642. **
  141643. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  141644. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  141645. **
  141646. ** It says above that this function advances the expression to the next
  141647. ** matching row. This is usually true, but there are the following exceptions:
  141648. **
  141649. ** 1. Deferred tokens are not taken into account. If a phrase consists
  141650. ** entirely of deferred tokens, it is assumed to match every row in
  141651. ** the db. In this case the position-list is not populated at all.
  141652. **
  141653. ** Or, if a phrase contains one or more deferred tokens and one or
  141654. ** more non-deferred tokens, then the expression is advanced to the
  141655. ** next possible match, considering only non-deferred tokens. In other
  141656. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  141657. ** is advanced to the next row that contains an instance of "A * C",
  141658. ** where "*" may match any single token. The position list in this case
  141659. ** is populated as for "A * C" before returning.
  141660. **
  141661. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  141662. ** advanced to point to the next row that matches "x AND y".
  141663. **
  141664. ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
  141665. ** really a match, taking into account deferred tokens and NEAR operators.
  141666. */
  141667. static void fts3EvalNextRow(
  141668. Fts3Cursor *pCsr, /* FTS Cursor handle */
  141669. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  141670. int *pRc /* IN/OUT: Error code */
  141671. ){
  141672. if( *pRc==SQLITE_OK ){
  141673. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  141674. assert( pExpr->bEof==0 );
  141675. pExpr->bStart = 1;
  141676. switch( pExpr->eType ){
  141677. case FTSQUERY_NEAR:
  141678. case FTSQUERY_AND: {
  141679. Fts3Expr *pLeft = pExpr->pLeft;
  141680. Fts3Expr *pRight = pExpr->pRight;
  141681. assert( !pLeft->bDeferred || !pRight->bDeferred );
  141682. if( pLeft->bDeferred ){
  141683. /* LHS is entirely deferred. So we assume it matches every row.
  141684. ** Advance the RHS iterator to find the next row visited. */
  141685. fts3EvalNextRow(pCsr, pRight, pRc);
  141686. pExpr->iDocid = pRight->iDocid;
  141687. pExpr->bEof = pRight->bEof;
  141688. }else if( pRight->bDeferred ){
  141689. /* RHS is entirely deferred. So we assume it matches every row.
  141690. ** Advance the LHS iterator to find the next row visited. */
  141691. fts3EvalNextRow(pCsr, pLeft, pRc);
  141692. pExpr->iDocid = pLeft->iDocid;
  141693. pExpr->bEof = pLeft->bEof;
  141694. }else{
  141695. /* Neither the RHS or LHS are deferred. */
  141696. fts3EvalNextRow(pCsr, pLeft, pRc);
  141697. fts3EvalNextRow(pCsr, pRight, pRc);
  141698. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  141699. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  141700. if( iDiff==0 ) break;
  141701. if( iDiff<0 ){
  141702. fts3EvalNextRow(pCsr, pLeft, pRc);
  141703. }else{
  141704. fts3EvalNextRow(pCsr, pRight, pRc);
  141705. }
  141706. }
  141707. pExpr->iDocid = pLeft->iDocid;
  141708. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  141709. if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
  141710. assert( pRight->eType==FTSQUERY_PHRASE );
  141711. if( pRight->pPhrase->doclist.aAll ){
  141712. Fts3Doclist *pDl = &pRight->pPhrase->doclist;
  141713. while( *pRc==SQLITE_OK && pRight->bEof==0 ){
  141714. memset(pDl->pList, 0, pDl->nList);
  141715. fts3EvalNextRow(pCsr, pRight, pRc);
  141716. }
  141717. }
  141718. if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
  141719. Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
  141720. while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
  141721. memset(pDl->pList, 0, pDl->nList);
  141722. fts3EvalNextRow(pCsr, pLeft, pRc);
  141723. }
  141724. }
  141725. }
  141726. }
  141727. break;
  141728. }
  141729. case FTSQUERY_OR: {
  141730. Fts3Expr *pLeft = pExpr->pLeft;
  141731. Fts3Expr *pRight = pExpr->pRight;
  141732. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  141733. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  141734. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  141735. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  141736. fts3EvalNextRow(pCsr, pLeft, pRc);
  141737. }else if( pLeft->bEof || iCmp>0 ){
  141738. fts3EvalNextRow(pCsr, pRight, pRc);
  141739. }else{
  141740. fts3EvalNextRow(pCsr, pLeft, pRc);
  141741. fts3EvalNextRow(pCsr, pRight, pRc);
  141742. }
  141743. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  141744. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  141745. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  141746. pExpr->iDocid = pLeft->iDocid;
  141747. }else{
  141748. pExpr->iDocid = pRight->iDocid;
  141749. }
  141750. break;
  141751. }
  141752. case FTSQUERY_NOT: {
  141753. Fts3Expr *pLeft = pExpr->pLeft;
  141754. Fts3Expr *pRight = pExpr->pRight;
  141755. if( pRight->bStart==0 ){
  141756. fts3EvalNextRow(pCsr, pRight, pRc);
  141757. assert( *pRc!=SQLITE_OK || pRight->bStart );
  141758. }
  141759. fts3EvalNextRow(pCsr, pLeft, pRc);
  141760. if( pLeft->bEof==0 ){
  141761. while( !*pRc
  141762. && !pRight->bEof
  141763. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  141764. ){
  141765. fts3EvalNextRow(pCsr, pRight, pRc);
  141766. }
  141767. }
  141768. pExpr->iDocid = pLeft->iDocid;
  141769. pExpr->bEof = pLeft->bEof;
  141770. break;
  141771. }
  141772. default: {
  141773. Fts3Phrase *pPhrase = pExpr->pPhrase;
  141774. fts3EvalInvalidatePoslist(pPhrase);
  141775. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  141776. pExpr->iDocid = pPhrase->doclist.iDocid;
  141777. break;
  141778. }
  141779. }
  141780. }
  141781. }
  141782. /*
  141783. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  141784. ** cluster, then this function returns 1 immediately.
  141785. **
  141786. ** Otherwise, it checks if the current row really does match the NEAR
  141787. ** expression, using the data currently stored in the position lists
  141788. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  141789. **
  141790. ** If the current row is a match, the position list associated with each
  141791. ** phrase in the NEAR expression is edited in place to contain only those
  141792. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  141793. ** constraints. In this case it returns 1. If the NEAR expression does not
  141794. ** match the current row, 0 is returned. The position lists may or may not
  141795. ** be edited if 0 is returned.
  141796. */
  141797. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  141798. int res = 1;
  141799. /* The following block runs if pExpr is the root of a NEAR query.
  141800. ** For example, the query:
  141801. **
  141802. ** "w" NEAR "x" NEAR "y" NEAR "z"
  141803. **
  141804. ** which is represented in tree form as:
  141805. **
  141806. ** |
  141807. ** +--NEAR--+ <-- root of NEAR query
  141808. ** | |
  141809. ** +--NEAR--+ "z"
  141810. ** | |
  141811. ** +--NEAR--+ "y"
  141812. ** | |
  141813. ** "w" "x"
  141814. **
  141815. ** The right-hand child of a NEAR node is always a phrase. The
  141816. ** left-hand child may be either a phrase or a NEAR node. There are
  141817. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  141818. */
  141819. if( *pRc==SQLITE_OK
  141820. && pExpr->eType==FTSQUERY_NEAR
  141821. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  141822. ){
  141823. Fts3Expr *p;
  141824. int nTmp = 0; /* Bytes of temp space */
  141825. char *aTmp; /* Temp space for PoslistNearMerge() */
  141826. /* Allocate temporary working space. */
  141827. for(p=pExpr; p->pLeft; p=p->pLeft){
  141828. assert( p->pRight->pPhrase->doclist.nList>0 );
  141829. nTmp += p->pRight->pPhrase->doclist.nList;
  141830. }
  141831. nTmp += p->pPhrase->doclist.nList;
  141832. aTmp = sqlite3_malloc(nTmp*2);
  141833. if( !aTmp ){
  141834. *pRc = SQLITE_NOMEM;
  141835. res = 0;
  141836. }else{
  141837. char *aPoslist = p->pPhrase->doclist.pList;
  141838. int nToken = p->pPhrase->nToken;
  141839. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  141840. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  141841. int nNear = p->nNear;
  141842. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  141843. }
  141844. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  141845. nToken = pExpr->pRight->pPhrase->nToken;
  141846. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  141847. int nNear;
  141848. Fts3Phrase *pPhrase;
  141849. assert( p->pParent && p->pParent->pLeft==p );
  141850. nNear = p->pParent->nNear;
  141851. pPhrase = (
  141852. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  141853. );
  141854. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  141855. }
  141856. }
  141857. sqlite3_free(aTmp);
  141858. }
  141859. return res;
  141860. }
  141861. /*
  141862. ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
  141863. ** Assuming no error occurs or has occurred, It returns non-zero if the
  141864. ** expression passed as the second argument matches the row that pCsr
  141865. ** currently points to, or zero if it does not.
  141866. **
  141867. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  141868. ** If an error occurs during execution of this function, *pRc is set to
  141869. ** the appropriate SQLite error code. In this case the returned value is
  141870. ** undefined.
  141871. */
  141872. static int fts3EvalTestExpr(
  141873. Fts3Cursor *pCsr, /* FTS cursor handle */
  141874. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  141875. int *pRc /* IN/OUT: Error code */
  141876. ){
  141877. int bHit = 1; /* Return value */
  141878. if( *pRc==SQLITE_OK ){
  141879. switch( pExpr->eType ){
  141880. case FTSQUERY_NEAR:
  141881. case FTSQUERY_AND:
  141882. bHit = (
  141883. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  141884. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  141885. && fts3EvalNearTest(pExpr, pRc)
  141886. );
  141887. /* If the NEAR expression does not match any rows, zero the doclist for
  141888. ** all phrases involved in the NEAR. This is because the snippet(),
  141889. ** offsets() and matchinfo() functions are not supposed to recognize
  141890. ** any instances of phrases that are part of unmatched NEAR queries.
  141891. ** For example if this expression:
  141892. **
  141893. ** ... MATCH 'a OR (b NEAR c)'
  141894. **
  141895. ** is matched against a row containing:
  141896. **
  141897. ** 'a b d e'
  141898. **
  141899. ** then any snippet() should ony highlight the "a" term, not the "b"
  141900. ** (as "b" is part of a non-matching NEAR clause).
  141901. */
  141902. if( bHit==0
  141903. && pExpr->eType==FTSQUERY_NEAR
  141904. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  141905. ){
  141906. Fts3Expr *p;
  141907. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  141908. if( p->pRight->iDocid==pCsr->iPrevId ){
  141909. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  141910. }
  141911. }
  141912. if( p->iDocid==pCsr->iPrevId ){
  141913. fts3EvalInvalidatePoslist(p->pPhrase);
  141914. }
  141915. }
  141916. break;
  141917. case FTSQUERY_OR: {
  141918. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  141919. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  141920. bHit = bHit1 || bHit2;
  141921. break;
  141922. }
  141923. case FTSQUERY_NOT:
  141924. bHit = (
  141925. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  141926. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  141927. );
  141928. break;
  141929. default: {
  141930. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  141931. if( pCsr->pDeferred
  141932. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  141933. ){
  141934. Fts3Phrase *pPhrase = pExpr->pPhrase;
  141935. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  141936. if( pExpr->bDeferred ){
  141937. fts3EvalInvalidatePoslist(pPhrase);
  141938. }
  141939. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  141940. bHit = (pPhrase->doclist.pList!=0);
  141941. pExpr->iDocid = pCsr->iPrevId;
  141942. }else
  141943. #endif
  141944. {
  141945. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  141946. }
  141947. break;
  141948. }
  141949. }
  141950. }
  141951. return bHit;
  141952. }
  141953. /*
  141954. ** This function is called as the second part of each xNext operation when
  141955. ** iterating through the results of a full-text query. At this point the
  141956. ** cursor points to a row that matches the query expression, with the
  141957. ** following caveats:
  141958. **
  141959. ** * Up until this point, "NEAR" operators in the expression have been
  141960. ** treated as "AND".
  141961. **
  141962. ** * Deferred tokens have not yet been considered.
  141963. **
  141964. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  141965. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  141966. ** operators and deferred tokens the current row is still a match for the
  141967. ** expression. It returns 1 if both of the following are true:
  141968. **
  141969. ** 1. *pRc is SQLITE_OK when this function returns, and
  141970. **
  141971. ** 2. After scanning the current FTS table row for the deferred tokens,
  141972. ** it is determined that the row does *not* match the query.
  141973. **
  141974. ** Or, if no error occurs and it seems the current row does match the FTS
  141975. ** query, return 0.
  141976. */
  141977. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
  141978. int rc = *pRc;
  141979. int bMiss = 0;
  141980. if( rc==SQLITE_OK ){
  141981. /* If there are one or more deferred tokens, load the current row into
  141982. ** memory and scan it to determine the position list for each deferred
  141983. ** token. Then, see if this row is really a match, considering deferred
  141984. ** tokens and NEAR operators (neither of which were taken into account
  141985. ** earlier, by fts3EvalNextRow()).
  141986. */
  141987. if( pCsr->pDeferred ){
  141988. rc = fts3CursorSeek(0, pCsr);
  141989. if( rc==SQLITE_OK ){
  141990. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  141991. }
  141992. }
  141993. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  141994. /* Free the position-lists accumulated for each deferred token above. */
  141995. sqlite3Fts3FreeDeferredDoclists(pCsr);
  141996. *pRc = rc;
  141997. }
  141998. return (rc==SQLITE_OK && bMiss);
  141999. }
  142000. /*
  142001. ** Advance to the next document that matches the FTS expression in
  142002. ** Fts3Cursor.pExpr.
  142003. */
  142004. static int fts3EvalNext(Fts3Cursor *pCsr){
  142005. int rc = SQLITE_OK; /* Return Code */
  142006. Fts3Expr *pExpr = pCsr->pExpr;
  142007. assert( pCsr->isEof==0 );
  142008. if( pExpr==0 ){
  142009. pCsr->isEof = 1;
  142010. }else{
  142011. do {
  142012. if( pCsr->isRequireSeek==0 ){
  142013. sqlite3_reset(pCsr->pStmt);
  142014. }
  142015. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  142016. fts3EvalNextRow(pCsr, pExpr, &rc);
  142017. pCsr->isEof = pExpr->bEof;
  142018. pCsr->isRequireSeek = 1;
  142019. pCsr->isMatchinfoNeeded = 1;
  142020. pCsr->iPrevId = pExpr->iDocid;
  142021. }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
  142022. }
  142023. /* Check if the cursor is past the end of the docid range specified
  142024. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  142025. if( rc==SQLITE_OK && (
  142026. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  142027. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  142028. )){
  142029. pCsr->isEof = 1;
  142030. }
  142031. return rc;
  142032. }
  142033. /*
  142034. ** Restart interation for expression pExpr so that the next call to
  142035. ** fts3EvalNext() visits the first row. Do not allow incremental
  142036. ** loading or merging of phrase doclists for this iteration.
  142037. **
  142038. ** If *pRc is other than SQLITE_OK when this function is called, it is
  142039. ** a no-op. If an error occurs within this function, *pRc is set to an
  142040. ** SQLite error code before returning.
  142041. */
  142042. static void fts3EvalRestart(
  142043. Fts3Cursor *pCsr,
  142044. Fts3Expr *pExpr,
  142045. int *pRc
  142046. ){
  142047. if( pExpr && *pRc==SQLITE_OK ){
  142048. Fts3Phrase *pPhrase = pExpr->pPhrase;
  142049. if( pPhrase ){
  142050. fts3EvalInvalidatePoslist(pPhrase);
  142051. if( pPhrase->bIncr ){
  142052. int i;
  142053. for(i=0; i<pPhrase->nToken; i++){
  142054. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  142055. assert( pToken->pDeferred==0 );
  142056. if( pToken->pSegcsr ){
  142057. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  142058. }
  142059. }
  142060. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  142061. }
  142062. pPhrase->doclist.pNextDocid = 0;
  142063. pPhrase->doclist.iDocid = 0;
  142064. pPhrase->pOrPoslist = 0;
  142065. }
  142066. pExpr->iDocid = 0;
  142067. pExpr->bEof = 0;
  142068. pExpr->bStart = 0;
  142069. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  142070. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  142071. }
  142072. }
  142073. /*
  142074. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  142075. ** expression rooted at pExpr, the cursor iterates through all rows matched
  142076. ** by pExpr, calling this function for each row. This function increments
  142077. ** the values in Fts3Expr.aMI[] according to the position-list currently
  142078. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  142079. ** expression nodes.
  142080. */
  142081. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  142082. if( pExpr ){
  142083. Fts3Phrase *pPhrase = pExpr->pPhrase;
  142084. if( pPhrase && pPhrase->doclist.pList ){
  142085. int iCol = 0;
  142086. char *p = pPhrase->doclist.pList;
  142087. assert( *p );
  142088. while( 1 ){
  142089. u8 c = 0;
  142090. int iCnt = 0;
  142091. while( 0xFE & (*p | c) ){
  142092. if( (c&0x80)==0 ) iCnt++;
  142093. c = *p++ & 0x80;
  142094. }
  142095. /* aMI[iCol*3 + 1] = Number of occurrences
  142096. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  142097. */
  142098. pExpr->aMI[iCol*3 + 1] += iCnt;
  142099. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  142100. if( *p==0x00 ) break;
  142101. p++;
  142102. p += fts3GetVarint32(p, &iCol);
  142103. }
  142104. }
  142105. fts3EvalUpdateCounts(pExpr->pLeft);
  142106. fts3EvalUpdateCounts(pExpr->pRight);
  142107. }
  142108. }
  142109. /*
  142110. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  142111. **
  142112. ** If it is not already allocated and populated, this function allocates and
  142113. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  142114. ** of a NEAR expression, then it also allocates and populates the same array
  142115. ** for all other phrases that are part of the NEAR expression.
  142116. **
  142117. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  142118. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  142119. */
  142120. static int fts3EvalGatherStats(
  142121. Fts3Cursor *pCsr, /* Cursor object */
  142122. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  142123. ){
  142124. int rc = SQLITE_OK; /* Return code */
  142125. assert( pExpr->eType==FTSQUERY_PHRASE );
  142126. if( pExpr->aMI==0 ){
  142127. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  142128. Fts3Expr *pRoot; /* Root of NEAR expression */
  142129. Fts3Expr *p; /* Iterator used for several purposes */
  142130. sqlite3_int64 iPrevId = pCsr->iPrevId;
  142131. sqlite3_int64 iDocid;
  142132. u8 bEof;
  142133. /* Find the root of the NEAR expression */
  142134. pRoot = pExpr;
  142135. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  142136. pRoot = pRoot->pParent;
  142137. }
  142138. iDocid = pRoot->iDocid;
  142139. bEof = pRoot->bEof;
  142140. assert( pRoot->bStart );
  142141. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  142142. for(p=pRoot; p; p=p->pLeft){
  142143. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  142144. assert( pE->aMI==0 );
  142145. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  142146. if( !pE->aMI ) return SQLITE_NOMEM;
  142147. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  142148. }
  142149. fts3EvalRestart(pCsr, pRoot, &rc);
  142150. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  142151. do {
  142152. /* Ensure the %_content statement is reset. */
  142153. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  142154. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  142155. /* Advance to the next document */
  142156. fts3EvalNextRow(pCsr, pRoot, &rc);
  142157. pCsr->isEof = pRoot->bEof;
  142158. pCsr->isRequireSeek = 1;
  142159. pCsr->isMatchinfoNeeded = 1;
  142160. pCsr->iPrevId = pRoot->iDocid;
  142161. }while( pCsr->isEof==0
  142162. && pRoot->eType==FTSQUERY_NEAR
  142163. && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
  142164. );
  142165. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  142166. fts3EvalUpdateCounts(pRoot);
  142167. }
  142168. }
  142169. pCsr->isEof = 0;
  142170. pCsr->iPrevId = iPrevId;
  142171. if( bEof ){
  142172. pRoot->bEof = bEof;
  142173. }else{
  142174. /* Caution: pRoot may iterate through docids in ascending or descending
  142175. ** order. For this reason, even though it seems more defensive, the
  142176. ** do loop can not be written:
  142177. **
  142178. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  142179. */
  142180. fts3EvalRestart(pCsr, pRoot, &rc);
  142181. do {
  142182. fts3EvalNextRow(pCsr, pRoot, &rc);
  142183. assert( pRoot->bEof==0 );
  142184. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  142185. }
  142186. }
  142187. return rc;
  142188. }
  142189. /*
  142190. ** This function is used by the matchinfo() module to query a phrase
  142191. ** expression node for the following information:
  142192. **
  142193. ** 1. The total number of occurrences of the phrase in each column of
  142194. ** the FTS table (considering all rows), and
  142195. **
  142196. ** 2. For each column, the number of rows in the table for which the
  142197. ** column contains at least one instance of the phrase.
  142198. **
  142199. ** If no error occurs, SQLITE_OK is returned and the values for each column
  142200. ** written into the array aiOut as follows:
  142201. **
  142202. ** aiOut[iCol*3 + 1] = Number of occurrences
  142203. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  142204. **
  142205. ** Caveats:
  142206. **
  142207. ** * If a phrase consists entirely of deferred tokens, then all output
  142208. ** values are set to the number of documents in the table. In other
  142209. ** words we assume that very common tokens occur exactly once in each
  142210. ** column of each row of the table.
  142211. **
  142212. ** * If a phrase contains some deferred tokens (and some non-deferred
  142213. ** tokens), count the potential occurrence identified by considering
  142214. ** the non-deferred tokens instead of actual phrase occurrences.
  142215. **
  142216. ** * If the phrase is part of a NEAR expression, then only phrase instances
  142217. ** that meet the NEAR constraint are included in the counts.
  142218. */
  142219. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  142220. Fts3Cursor *pCsr, /* FTS cursor handle */
  142221. Fts3Expr *pExpr, /* Phrase expression */
  142222. u32 *aiOut /* Array to write results into (see above) */
  142223. ){
  142224. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  142225. int rc = SQLITE_OK;
  142226. int iCol;
  142227. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  142228. assert( pCsr->nDoc>0 );
  142229. for(iCol=0; iCol<pTab->nColumn; iCol++){
  142230. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  142231. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  142232. }
  142233. }else{
  142234. rc = fts3EvalGatherStats(pCsr, pExpr);
  142235. if( rc==SQLITE_OK ){
  142236. assert( pExpr->aMI );
  142237. for(iCol=0; iCol<pTab->nColumn; iCol++){
  142238. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  142239. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  142240. }
  142241. }
  142242. }
  142243. return rc;
  142244. }
  142245. /*
  142246. ** The expression pExpr passed as the second argument to this function
  142247. ** must be of type FTSQUERY_PHRASE.
  142248. **
  142249. ** The returned value is either NULL or a pointer to a buffer containing
  142250. ** a position-list indicating the occurrences of the phrase in column iCol
  142251. ** of the current row.
  142252. **
  142253. ** More specifically, the returned buffer contains 1 varint for each
  142254. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  142255. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  142256. ** if the requested column contains "a b X c d X X" and the position-list
  142257. ** for 'X' is requested, the buffer returned may contain:
  142258. **
  142259. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  142260. **
  142261. ** This function works regardless of whether or not the phrase is deferred,
  142262. ** incremental, or neither.
  142263. */
  142264. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  142265. Fts3Cursor *pCsr, /* FTS3 cursor object */
  142266. Fts3Expr *pExpr, /* Phrase to return doclist for */
  142267. int iCol, /* Column to return position list for */
  142268. char **ppOut /* OUT: Pointer to position list */
  142269. ){
  142270. Fts3Phrase *pPhrase = pExpr->pPhrase;
  142271. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  142272. char *pIter;
  142273. int iThis;
  142274. sqlite3_int64 iDocid;
  142275. /* If this phrase is applies specifically to some column other than
  142276. ** column iCol, return a NULL pointer. */
  142277. *ppOut = 0;
  142278. assert( iCol>=0 && iCol<pTab->nColumn );
  142279. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  142280. return SQLITE_OK;
  142281. }
  142282. iDocid = pExpr->iDocid;
  142283. pIter = pPhrase->doclist.pList;
  142284. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  142285. int rc = SQLITE_OK;
  142286. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  142287. int bOr = 0;
  142288. u8 bTreeEof = 0;
  142289. Fts3Expr *p; /* Used to iterate from pExpr to root */
  142290. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  142291. int bMatch;
  142292. /* Check if this phrase descends from an OR expression node. If not,
  142293. ** return NULL. Otherwise, the entry that corresponds to docid
  142294. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  142295. ** tree that the node is part of has been marked as EOF, but the node
  142296. ** itself is not EOF, then it may point to an earlier entry. */
  142297. pNear = pExpr;
  142298. for(p=pExpr->pParent; p; p=p->pParent){
  142299. if( p->eType==FTSQUERY_OR ) bOr = 1;
  142300. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  142301. if( p->bEof ) bTreeEof = 1;
  142302. }
  142303. if( bOr==0 ) return SQLITE_OK;
  142304. /* This is the descendent of an OR node. In this case we cannot use
  142305. ** an incremental phrase. Load the entire doclist for the phrase
  142306. ** into memory in this case. */
  142307. if( pPhrase->bIncr ){
  142308. int bEofSave = pNear->bEof;
  142309. fts3EvalRestart(pCsr, pNear, &rc);
  142310. while( rc==SQLITE_OK && !pNear->bEof ){
  142311. fts3EvalNextRow(pCsr, pNear, &rc);
  142312. if( bEofSave==0 && pNear->iDocid==iDocid ) break;
  142313. }
  142314. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  142315. }
  142316. if( bTreeEof ){
  142317. while( rc==SQLITE_OK && !pNear->bEof ){
  142318. fts3EvalNextRow(pCsr, pNear, &rc);
  142319. }
  142320. }
  142321. if( rc!=SQLITE_OK ) return rc;
  142322. bMatch = 1;
  142323. for(p=pNear; p; p=p->pLeft){
  142324. u8 bEof = 0;
  142325. Fts3Expr *pTest = p;
  142326. Fts3Phrase *pPh;
  142327. assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
  142328. if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
  142329. assert( pTest->eType==FTSQUERY_PHRASE );
  142330. pPh = pTest->pPhrase;
  142331. pIter = pPh->pOrPoslist;
  142332. iDocid = pPh->iOrDocid;
  142333. if( pCsr->bDesc==bDescDoclist ){
  142334. bEof = !pPh->doclist.nAll ||
  142335. (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
  142336. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  142337. sqlite3Fts3DoclistNext(
  142338. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  142339. &pIter, &iDocid, &bEof
  142340. );
  142341. }
  142342. }else{
  142343. bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
  142344. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  142345. int dummy;
  142346. sqlite3Fts3DoclistPrev(
  142347. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  142348. &pIter, &iDocid, &dummy, &bEof
  142349. );
  142350. }
  142351. }
  142352. pPh->pOrPoslist = pIter;
  142353. pPh->iOrDocid = iDocid;
  142354. if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
  142355. }
  142356. if( bMatch ){
  142357. pIter = pPhrase->pOrPoslist;
  142358. }else{
  142359. pIter = 0;
  142360. }
  142361. }
  142362. if( pIter==0 ) return SQLITE_OK;
  142363. if( *pIter==0x01 ){
  142364. pIter++;
  142365. pIter += fts3GetVarint32(pIter, &iThis);
  142366. }else{
  142367. iThis = 0;
  142368. }
  142369. while( iThis<iCol ){
  142370. fts3ColumnlistCopy(0, &pIter);
  142371. if( *pIter==0x00 ) return SQLITE_OK;
  142372. pIter++;
  142373. pIter += fts3GetVarint32(pIter, &iThis);
  142374. }
  142375. if( *pIter==0x00 ){
  142376. pIter = 0;
  142377. }
  142378. *ppOut = ((iCol==iThis)?pIter:0);
  142379. return SQLITE_OK;
  142380. }
  142381. /*
  142382. ** Free all components of the Fts3Phrase structure that were allocated by
  142383. ** the eval module. Specifically, this means to free:
  142384. **
  142385. ** * the contents of pPhrase->doclist, and
  142386. ** * any Fts3MultiSegReader objects held by phrase tokens.
  142387. */
  142388. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  142389. if( pPhrase ){
  142390. int i;
  142391. sqlite3_free(pPhrase->doclist.aAll);
  142392. fts3EvalInvalidatePoslist(pPhrase);
  142393. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  142394. for(i=0; i<pPhrase->nToken; i++){
  142395. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  142396. pPhrase->aToken[i].pSegcsr = 0;
  142397. }
  142398. }
  142399. }
  142400. /*
  142401. ** Return SQLITE_CORRUPT_VTAB.
  142402. */
  142403. #ifdef SQLITE_DEBUG
  142404. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  142405. return SQLITE_CORRUPT_VTAB;
  142406. }
  142407. #endif
  142408. #if !SQLITE_CORE
  142409. /*
  142410. ** Initialize API pointer table, if required.
  142411. */
  142412. #ifdef _WIN32
  142413. __declspec(dllexport)
  142414. #endif
  142415. SQLITE_API int sqlite3_fts3_init(
  142416. sqlite3 *db,
  142417. char **pzErrMsg,
  142418. const sqlite3_api_routines *pApi
  142419. ){
  142420. SQLITE_EXTENSION_INIT2(pApi)
  142421. return sqlite3Fts3Init(db);
  142422. }
  142423. #endif
  142424. #endif
  142425. /************** End of fts3.c ************************************************/
  142426. /************** Begin file fts3_aux.c ****************************************/
  142427. /*
  142428. ** 2011 Jan 27
  142429. **
  142430. ** The author disclaims copyright to this source code. In place of
  142431. ** a legal notice, here is a blessing:
  142432. **
  142433. ** May you do good and not evil.
  142434. ** May you find forgiveness for yourself and forgive others.
  142435. ** May you share freely, never taking more than you give.
  142436. **
  142437. ******************************************************************************
  142438. **
  142439. */
  142440. /* #include "fts3Int.h" */
  142441. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  142442. /* #include <string.h> */
  142443. /* #include <assert.h> */
  142444. typedef struct Fts3auxTable Fts3auxTable;
  142445. typedef struct Fts3auxCursor Fts3auxCursor;
  142446. struct Fts3auxTable {
  142447. sqlite3_vtab base; /* Base class used by SQLite core */
  142448. Fts3Table *pFts3Tab;
  142449. };
  142450. struct Fts3auxCursor {
  142451. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  142452. Fts3MultiSegReader csr; /* Must be right after "base" */
  142453. Fts3SegFilter filter;
  142454. char *zStop;
  142455. int nStop; /* Byte-length of string zStop */
  142456. int iLangid; /* Language id to query */
  142457. int isEof; /* True if cursor is at EOF */
  142458. sqlite3_int64 iRowid; /* Current rowid */
  142459. int iCol; /* Current value of 'col' column */
  142460. int nStat; /* Size of aStat[] array */
  142461. struct Fts3auxColstats {
  142462. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  142463. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  142464. } *aStat;
  142465. };
  142466. /*
  142467. ** Schema of the terms table.
  142468. */
  142469. #define FTS3_AUX_SCHEMA \
  142470. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  142471. /*
  142472. ** This function does all the work for both the xConnect and xCreate methods.
  142473. ** These tables have no persistent representation of their own, so xConnect
  142474. ** and xCreate are identical operations.
  142475. */
  142476. static int fts3auxConnectMethod(
  142477. sqlite3 *db, /* Database connection */
  142478. void *pUnused, /* Unused */
  142479. int argc, /* Number of elements in argv array */
  142480. const char * const *argv, /* xCreate/xConnect argument array */
  142481. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  142482. char **pzErr /* OUT: sqlite3_malloc'd error message */
  142483. ){
  142484. char const *zDb; /* Name of database (e.g. "main") */
  142485. char const *zFts3; /* Name of fts3 table */
  142486. int nDb; /* Result of strlen(zDb) */
  142487. int nFts3; /* Result of strlen(zFts3) */
  142488. int nByte; /* Bytes of space to allocate here */
  142489. int rc; /* value returned by declare_vtab() */
  142490. Fts3auxTable *p; /* Virtual table object to return */
  142491. UNUSED_PARAMETER(pUnused);
  142492. /* The user should invoke this in one of two forms:
  142493. **
  142494. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  142495. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  142496. */
  142497. if( argc!=4 && argc!=5 ) goto bad_args;
  142498. zDb = argv[1];
  142499. nDb = (int)strlen(zDb);
  142500. if( argc==5 ){
  142501. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  142502. zDb = argv[3];
  142503. nDb = (int)strlen(zDb);
  142504. zFts3 = argv[4];
  142505. }else{
  142506. goto bad_args;
  142507. }
  142508. }else{
  142509. zFts3 = argv[3];
  142510. }
  142511. nFts3 = (int)strlen(zFts3);
  142512. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  142513. if( rc!=SQLITE_OK ) return rc;
  142514. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  142515. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  142516. if( !p ) return SQLITE_NOMEM;
  142517. memset(p, 0, nByte);
  142518. p->pFts3Tab = (Fts3Table *)&p[1];
  142519. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  142520. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  142521. p->pFts3Tab->db = db;
  142522. p->pFts3Tab->nIndex = 1;
  142523. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  142524. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  142525. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  142526. *ppVtab = (sqlite3_vtab *)p;
  142527. return SQLITE_OK;
  142528. bad_args:
  142529. sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
  142530. return SQLITE_ERROR;
  142531. }
  142532. /*
  142533. ** This function does the work for both the xDisconnect and xDestroy methods.
  142534. ** These tables have no persistent representation of their own, so xDisconnect
  142535. ** and xDestroy are identical operations.
  142536. */
  142537. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  142538. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  142539. Fts3Table *pFts3 = p->pFts3Tab;
  142540. int i;
  142541. /* Free any prepared statements held */
  142542. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  142543. sqlite3_finalize(pFts3->aStmt[i]);
  142544. }
  142545. sqlite3_free(pFts3->zSegmentsTbl);
  142546. sqlite3_free(p);
  142547. return SQLITE_OK;
  142548. }
  142549. #define FTS4AUX_EQ_CONSTRAINT 1
  142550. #define FTS4AUX_GE_CONSTRAINT 2
  142551. #define FTS4AUX_LE_CONSTRAINT 4
  142552. /*
  142553. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  142554. */
  142555. static int fts3auxBestIndexMethod(
  142556. sqlite3_vtab *pVTab,
  142557. sqlite3_index_info *pInfo
  142558. ){
  142559. int i;
  142560. int iEq = -1;
  142561. int iGe = -1;
  142562. int iLe = -1;
  142563. int iLangid = -1;
  142564. int iNext = 1; /* Next free argvIndex value */
  142565. UNUSED_PARAMETER(pVTab);
  142566. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  142567. if( pInfo->nOrderBy==1
  142568. && pInfo->aOrderBy[0].iColumn==0
  142569. && pInfo->aOrderBy[0].desc==0
  142570. ){
  142571. pInfo->orderByConsumed = 1;
  142572. }
  142573. /* Search for equality and range constraints on the "term" column.
  142574. ** And equality constraints on the hidden "languageid" column. */
  142575. for(i=0; i<pInfo->nConstraint; i++){
  142576. if( pInfo->aConstraint[i].usable ){
  142577. int op = pInfo->aConstraint[i].op;
  142578. int iCol = pInfo->aConstraint[i].iColumn;
  142579. if( iCol==0 ){
  142580. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  142581. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  142582. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  142583. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  142584. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  142585. }
  142586. if( iCol==4 ){
  142587. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  142588. }
  142589. }
  142590. }
  142591. if( iEq>=0 ){
  142592. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  142593. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  142594. pInfo->estimatedCost = 5;
  142595. }else{
  142596. pInfo->idxNum = 0;
  142597. pInfo->estimatedCost = 20000;
  142598. if( iGe>=0 ){
  142599. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  142600. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  142601. pInfo->estimatedCost /= 2;
  142602. }
  142603. if( iLe>=0 ){
  142604. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  142605. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  142606. pInfo->estimatedCost /= 2;
  142607. }
  142608. }
  142609. if( iLangid>=0 ){
  142610. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  142611. pInfo->estimatedCost--;
  142612. }
  142613. return SQLITE_OK;
  142614. }
  142615. /*
  142616. ** xOpen - Open a cursor.
  142617. */
  142618. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  142619. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  142620. UNUSED_PARAMETER(pVTab);
  142621. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  142622. if( !pCsr ) return SQLITE_NOMEM;
  142623. memset(pCsr, 0, sizeof(Fts3auxCursor));
  142624. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  142625. return SQLITE_OK;
  142626. }
  142627. /*
  142628. ** xClose - Close a cursor.
  142629. */
  142630. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  142631. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  142632. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  142633. sqlite3Fts3SegmentsClose(pFts3);
  142634. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  142635. sqlite3_free((void *)pCsr->filter.zTerm);
  142636. sqlite3_free(pCsr->zStop);
  142637. sqlite3_free(pCsr->aStat);
  142638. sqlite3_free(pCsr);
  142639. return SQLITE_OK;
  142640. }
  142641. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  142642. if( nSize>pCsr->nStat ){
  142643. struct Fts3auxColstats *aNew;
  142644. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  142645. sizeof(struct Fts3auxColstats) * nSize
  142646. );
  142647. if( aNew==0 ) return SQLITE_NOMEM;
  142648. memset(&aNew[pCsr->nStat], 0,
  142649. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  142650. );
  142651. pCsr->aStat = aNew;
  142652. pCsr->nStat = nSize;
  142653. }
  142654. return SQLITE_OK;
  142655. }
  142656. /*
  142657. ** xNext - Advance the cursor to the next row, if any.
  142658. */
  142659. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  142660. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  142661. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  142662. int rc;
  142663. /* Increment our pretend rowid value. */
  142664. pCsr->iRowid++;
  142665. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  142666. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  142667. }
  142668. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  142669. if( rc==SQLITE_ROW ){
  142670. int i = 0;
  142671. int nDoclist = pCsr->csr.nDoclist;
  142672. char *aDoclist = pCsr->csr.aDoclist;
  142673. int iCol;
  142674. int eState = 0;
  142675. if( pCsr->zStop ){
  142676. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  142677. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  142678. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  142679. pCsr->isEof = 1;
  142680. return SQLITE_OK;
  142681. }
  142682. }
  142683. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  142684. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  142685. iCol = 0;
  142686. while( i<nDoclist ){
  142687. sqlite3_int64 v = 0;
  142688. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  142689. switch( eState ){
  142690. /* State 0. In this state the integer just read was a docid. */
  142691. case 0:
  142692. pCsr->aStat[0].nDoc++;
  142693. eState = 1;
  142694. iCol = 0;
  142695. break;
  142696. /* State 1. In this state we are expecting either a 1, indicating
  142697. ** that the following integer will be a column number, or the
  142698. ** start of a position list for column 0.
  142699. **
  142700. ** The only difference between state 1 and state 2 is that if the
  142701. ** integer encountered in state 1 is not 0 or 1, then we need to
  142702. ** increment the column 0 "nDoc" count for this term.
  142703. */
  142704. case 1:
  142705. assert( iCol==0 );
  142706. if( v>1 ){
  142707. pCsr->aStat[1].nDoc++;
  142708. }
  142709. eState = 2;
  142710. /* fall through */
  142711. case 2:
  142712. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  142713. eState = 0;
  142714. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  142715. eState = 3;
  142716. }else{ /* 2 or greater. A position. */
  142717. pCsr->aStat[iCol+1].nOcc++;
  142718. pCsr->aStat[0].nOcc++;
  142719. }
  142720. break;
  142721. /* State 3. The integer just read is a column number. */
  142722. default: assert( eState==3 );
  142723. iCol = (int)v;
  142724. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  142725. pCsr->aStat[iCol+1].nDoc++;
  142726. eState = 2;
  142727. break;
  142728. }
  142729. }
  142730. pCsr->iCol = 0;
  142731. rc = SQLITE_OK;
  142732. }else{
  142733. pCsr->isEof = 1;
  142734. }
  142735. return rc;
  142736. }
  142737. /*
  142738. ** xFilter - Initialize a cursor to point at the start of its data.
  142739. */
  142740. static int fts3auxFilterMethod(
  142741. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  142742. int idxNum, /* Strategy index */
  142743. const char *idxStr, /* Unused */
  142744. int nVal, /* Number of elements in apVal */
  142745. sqlite3_value **apVal /* Arguments for the indexing scheme */
  142746. ){
  142747. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  142748. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  142749. int rc;
  142750. int isScan = 0;
  142751. int iLangVal = 0; /* Language id to query */
  142752. int iEq = -1; /* Index of term=? value in apVal */
  142753. int iGe = -1; /* Index of term>=? value in apVal */
  142754. int iLe = -1; /* Index of term<=? value in apVal */
  142755. int iLangid = -1; /* Index of languageid=? value in apVal */
  142756. int iNext = 0;
  142757. UNUSED_PARAMETER(nVal);
  142758. UNUSED_PARAMETER(idxStr);
  142759. assert( idxStr==0 );
  142760. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  142761. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  142762. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  142763. );
  142764. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  142765. iEq = iNext++;
  142766. }else{
  142767. isScan = 1;
  142768. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  142769. iGe = iNext++;
  142770. }
  142771. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  142772. iLe = iNext++;
  142773. }
  142774. }
  142775. if( iNext<nVal ){
  142776. iLangid = iNext++;
  142777. }
  142778. /* In case this cursor is being reused, close and zero it. */
  142779. testcase(pCsr->filter.zTerm);
  142780. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  142781. sqlite3_free((void *)pCsr->filter.zTerm);
  142782. sqlite3_free(pCsr->aStat);
  142783. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  142784. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  142785. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  142786. if( iEq>=0 || iGe>=0 ){
  142787. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  142788. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  142789. if( zStr ){
  142790. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  142791. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  142792. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  142793. }
  142794. }
  142795. if( iLe>=0 ){
  142796. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  142797. pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
  142798. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  142799. }
  142800. if( iLangid>=0 ){
  142801. iLangVal = sqlite3_value_int(apVal[iLangid]);
  142802. /* If the user specified a negative value for the languageid, use zero
  142803. ** instead. This works, as the "languageid=?" constraint will also
  142804. ** be tested by the VDBE layer. The test will always be false (since
  142805. ** this module will not return a row with a negative languageid), and
  142806. ** so the overall query will return zero rows. */
  142807. if( iLangVal<0 ) iLangVal = 0;
  142808. }
  142809. pCsr->iLangid = iLangVal;
  142810. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  142811. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  142812. );
  142813. if( rc==SQLITE_OK ){
  142814. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  142815. }
  142816. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  142817. return rc;
  142818. }
  142819. /*
  142820. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  142821. */
  142822. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  142823. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  142824. return pCsr->isEof;
  142825. }
  142826. /*
  142827. ** xColumn - Return a column value.
  142828. */
  142829. static int fts3auxColumnMethod(
  142830. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  142831. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  142832. int iCol /* Index of column to read value from */
  142833. ){
  142834. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  142835. assert( p->isEof==0 );
  142836. switch( iCol ){
  142837. case 0: /* term */
  142838. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  142839. break;
  142840. case 1: /* col */
  142841. if( p->iCol ){
  142842. sqlite3_result_int(pCtx, p->iCol-1);
  142843. }else{
  142844. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  142845. }
  142846. break;
  142847. case 2: /* documents */
  142848. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  142849. break;
  142850. case 3: /* occurrences */
  142851. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  142852. break;
  142853. default: /* languageid */
  142854. assert( iCol==4 );
  142855. sqlite3_result_int(pCtx, p->iLangid);
  142856. break;
  142857. }
  142858. return SQLITE_OK;
  142859. }
  142860. /*
  142861. ** xRowid - Return the current rowid for the cursor.
  142862. */
  142863. static int fts3auxRowidMethod(
  142864. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  142865. sqlite_int64 *pRowid /* OUT: Rowid value */
  142866. ){
  142867. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  142868. *pRowid = pCsr->iRowid;
  142869. return SQLITE_OK;
  142870. }
  142871. /*
  142872. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  142873. ** if successful or an error code if sqlite3_create_module() fails.
  142874. */
  142875. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  142876. static const sqlite3_module fts3aux_module = {
  142877. 0, /* iVersion */
  142878. fts3auxConnectMethod, /* xCreate */
  142879. fts3auxConnectMethod, /* xConnect */
  142880. fts3auxBestIndexMethod, /* xBestIndex */
  142881. fts3auxDisconnectMethod, /* xDisconnect */
  142882. fts3auxDisconnectMethod, /* xDestroy */
  142883. fts3auxOpenMethod, /* xOpen */
  142884. fts3auxCloseMethod, /* xClose */
  142885. fts3auxFilterMethod, /* xFilter */
  142886. fts3auxNextMethod, /* xNext */
  142887. fts3auxEofMethod, /* xEof */
  142888. fts3auxColumnMethod, /* xColumn */
  142889. fts3auxRowidMethod, /* xRowid */
  142890. 0, /* xUpdate */
  142891. 0, /* xBegin */
  142892. 0, /* xSync */
  142893. 0, /* xCommit */
  142894. 0, /* xRollback */
  142895. 0, /* xFindFunction */
  142896. 0, /* xRename */
  142897. 0, /* xSavepoint */
  142898. 0, /* xRelease */
  142899. 0 /* xRollbackTo */
  142900. };
  142901. int rc; /* Return code */
  142902. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  142903. return rc;
  142904. }
  142905. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  142906. /************** End of fts3_aux.c ********************************************/
  142907. /************** Begin file fts3_expr.c ***************************************/
  142908. /*
  142909. ** 2008 Nov 28
  142910. **
  142911. ** The author disclaims copyright to this source code. In place of
  142912. ** a legal notice, here is a blessing:
  142913. **
  142914. ** May you do good and not evil.
  142915. ** May you find forgiveness for yourself and forgive others.
  142916. ** May you share freely, never taking more than you give.
  142917. **
  142918. ******************************************************************************
  142919. **
  142920. ** This module contains code that implements a parser for fts3 query strings
  142921. ** (the right-hand argument to the MATCH operator). Because the supported
  142922. ** syntax is relatively simple, the whole tokenizer/parser system is
  142923. ** hand-coded.
  142924. */
  142925. /* #include "fts3Int.h" */
  142926. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  142927. /*
  142928. ** By default, this module parses the legacy syntax that has been
  142929. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  142930. ** is defined, then it uses the new syntax. The differences between
  142931. ** the new and the old syntaxes are:
  142932. **
  142933. ** a) The new syntax supports parenthesis. The old does not.
  142934. **
  142935. ** b) The new syntax supports the AND and NOT operators. The old does not.
  142936. **
  142937. ** c) The old syntax supports the "-" token qualifier. This is not
  142938. ** supported by the new syntax (it is replaced by the NOT operator).
  142939. **
  142940. ** d) When using the old syntax, the OR operator has a greater precedence
  142941. ** than an implicit AND. When using the new, both implicity and explicit
  142942. ** AND operators have a higher precedence than OR.
  142943. **
  142944. ** If compiled with SQLITE_TEST defined, then this module exports the
  142945. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  142946. ** to zero causes the module to use the old syntax. If it is set to
  142947. ** non-zero the new syntax is activated. This is so both syntaxes can
  142948. ** be tested using a single build of testfixture.
  142949. **
  142950. ** The following describes the syntax supported by the fts3 MATCH
  142951. ** operator in a similar format to that used by the lemon parser
  142952. ** generator. This module does not use actually lemon, it uses a
  142953. ** custom parser.
  142954. **
  142955. ** query ::= andexpr (OR andexpr)*.
  142956. **
  142957. ** andexpr ::= notexpr (AND? notexpr)*.
  142958. **
  142959. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  142960. ** notexpr ::= LP query RP.
  142961. **
  142962. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  142963. **
  142964. ** distance_opt ::= .
  142965. ** distance_opt ::= / INTEGER.
  142966. **
  142967. ** phrase ::= TOKEN.
  142968. ** phrase ::= COLUMN:TOKEN.
  142969. ** phrase ::= "TOKEN TOKEN TOKEN...".
  142970. */
  142971. #ifdef SQLITE_TEST
  142972. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  142973. #else
  142974. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  142975. # define sqlite3_fts3_enable_parentheses 1
  142976. # else
  142977. # define sqlite3_fts3_enable_parentheses 0
  142978. # endif
  142979. #endif
  142980. /*
  142981. ** Default span for NEAR operators.
  142982. */
  142983. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  142984. /* #include <string.h> */
  142985. /* #include <assert.h> */
  142986. /*
  142987. ** isNot:
  142988. ** This variable is used by function getNextNode(). When getNextNode() is
  142989. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  142990. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  142991. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  142992. ** zero.
  142993. */
  142994. typedef struct ParseContext ParseContext;
  142995. struct ParseContext {
  142996. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  142997. int iLangid; /* Language id used with tokenizer */
  142998. const char **azCol; /* Array of column names for fts3 table */
  142999. int bFts4; /* True to allow FTS4-only syntax */
  143000. int nCol; /* Number of entries in azCol[] */
  143001. int iDefaultCol; /* Default column to query */
  143002. int isNot; /* True if getNextNode() sees a unary - */
  143003. sqlite3_context *pCtx; /* Write error message here */
  143004. int nNest; /* Number of nested brackets */
  143005. };
  143006. /*
  143007. ** This function is equivalent to the standard isspace() function.
  143008. **
  143009. ** The standard isspace() can be awkward to use safely, because although it
  143010. ** is defined to accept an argument of type int, its behavior when passed
  143011. ** an integer that falls outside of the range of the unsigned char type
  143012. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  143013. ** is defined to accept an argument of type char, and always returns 0 for
  143014. ** any values that fall outside of the range of the unsigned char type (i.e.
  143015. ** negative values).
  143016. */
  143017. static int fts3isspace(char c){
  143018. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  143019. }
  143020. /*
  143021. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  143022. ** zero the memory before returning a pointer to it. If unsuccessful,
  143023. ** return NULL.
  143024. */
  143025. static void *fts3MallocZero(int nByte){
  143026. void *pRet = sqlite3_malloc(nByte);
  143027. if( pRet ) memset(pRet, 0, nByte);
  143028. return pRet;
  143029. }
  143030. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  143031. sqlite3_tokenizer *pTokenizer,
  143032. int iLangid,
  143033. const char *z,
  143034. int n,
  143035. sqlite3_tokenizer_cursor **ppCsr
  143036. ){
  143037. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  143038. sqlite3_tokenizer_cursor *pCsr = 0;
  143039. int rc;
  143040. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  143041. assert( rc==SQLITE_OK || pCsr==0 );
  143042. if( rc==SQLITE_OK ){
  143043. pCsr->pTokenizer = pTokenizer;
  143044. if( pModule->iVersion>=1 ){
  143045. rc = pModule->xLanguageid(pCsr, iLangid);
  143046. if( rc!=SQLITE_OK ){
  143047. pModule->xClose(pCsr);
  143048. pCsr = 0;
  143049. }
  143050. }
  143051. }
  143052. *ppCsr = pCsr;
  143053. return rc;
  143054. }
  143055. /*
  143056. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  143057. ** call fts3ExprParse(). So this forward declaration is required.
  143058. */
  143059. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  143060. /*
  143061. ** Extract the next token from buffer z (length n) using the tokenizer
  143062. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  143063. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  143064. ** single token and set *ppExpr to point to it. If the end of the buffer is
  143065. ** reached before a token is found, set *ppExpr to zero. It is the
  143066. ** responsibility of the caller to eventually deallocate the allocated
  143067. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  143068. **
  143069. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  143070. ** fails.
  143071. */
  143072. static int getNextToken(
  143073. ParseContext *pParse, /* fts3 query parse context */
  143074. int iCol, /* Value for Fts3Phrase.iColumn */
  143075. const char *z, int n, /* Input string */
  143076. Fts3Expr **ppExpr, /* OUT: expression */
  143077. int *pnConsumed /* OUT: Number of bytes consumed */
  143078. ){
  143079. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  143080. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  143081. int rc;
  143082. sqlite3_tokenizer_cursor *pCursor;
  143083. Fts3Expr *pRet = 0;
  143084. int i = 0;
  143085. /* Set variable i to the maximum number of bytes of input to tokenize. */
  143086. for(i=0; i<n; i++){
  143087. if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
  143088. if( z[i]=='"' ) break;
  143089. }
  143090. *pnConsumed = i;
  143091. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
  143092. if( rc==SQLITE_OK ){
  143093. const char *zToken;
  143094. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  143095. int nByte; /* total space to allocate */
  143096. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  143097. if( rc==SQLITE_OK ){
  143098. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  143099. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  143100. if( !pRet ){
  143101. rc = SQLITE_NOMEM;
  143102. }else{
  143103. pRet->eType = FTSQUERY_PHRASE;
  143104. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  143105. pRet->pPhrase->nToken = 1;
  143106. pRet->pPhrase->iColumn = iCol;
  143107. pRet->pPhrase->aToken[0].n = nToken;
  143108. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  143109. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  143110. if( iEnd<n && z[iEnd]=='*' ){
  143111. pRet->pPhrase->aToken[0].isPrefix = 1;
  143112. iEnd++;
  143113. }
  143114. while( 1 ){
  143115. if( !sqlite3_fts3_enable_parentheses
  143116. && iStart>0 && z[iStart-1]=='-'
  143117. ){
  143118. pParse->isNot = 1;
  143119. iStart--;
  143120. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  143121. pRet->pPhrase->aToken[0].bFirst = 1;
  143122. iStart--;
  143123. }else{
  143124. break;
  143125. }
  143126. }
  143127. }
  143128. *pnConsumed = iEnd;
  143129. }else if( i && rc==SQLITE_DONE ){
  143130. rc = SQLITE_OK;
  143131. }
  143132. pModule->xClose(pCursor);
  143133. }
  143134. *ppExpr = pRet;
  143135. return rc;
  143136. }
  143137. /*
  143138. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  143139. ** then free the old allocation.
  143140. */
  143141. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  143142. void *pRet = sqlite3_realloc(pOrig, nNew);
  143143. if( !pRet ){
  143144. sqlite3_free(pOrig);
  143145. }
  143146. return pRet;
  143147. }
  143148. /*
  143149. ** Buffer zInput, length nInput, contains the contents of a quoted string
  143150. ** that appeared as part of an fts3 query expression. Neither quote character
  143151. ** is included in the buffer. This function attempts to tokenize the entire
  143152. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  143153. ** containing the results.
  143154. **
  143155. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  143156. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  143157. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  143158. ** to 0.
  143159. */
  143160. static int getNextString(
  143161. ParseContext *pParse, /* fts3 query parse context */
  143162. const char *zInput, int nInput, /* Input string */
  143163. Fts3Expr **ppExpr /* OUT: expression */
  143164. ){
  143165. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  143166. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  143167. int rc;
  143168. Fts3Expr *p = 0;
  143169. sqlite3_tokenizer_cursor *pCursor = 0;
  143170. char *zTemp = 0;
  143171. int nTemp = 0;
  143172. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  143173. int nToken = 0;
  143174. /* The final Fts3Expr data structure, including the Fts3Phrase,
  143175. ** Fts3PhraseToken structures token buffers are all stored as a single
  143176. ** allocation so that the expression can be freed with a single call to
  143177. ** sqlite3_free(). Setting this up requires a two pass approach.
  143178. **
  143179. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  143180. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  143181. ** to assemble data in two dynamic buffers:
  143182. **
  143183. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  143184. ** structure, followed by the array of Fts3PhraseToken
  143185. ** structures. This pass only populates the Fts3PhraseToken array.
  143186. **
  143187. ** Buffer zTemp: Contains copies of all tokens.
  143188. **
  143189. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  143190. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  143191. ** structures.
  143192. */
  143193. rc = sqlite3Fts3OpenTokenizer(
  143194. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  143195. if( rc==SQLITE_OK ){
  143196. int ii;
  143197. for(ii=0; rc==SQLITE_OK; ii++){
  143198. const char *zByte;
  143199. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  143200. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  143201. if( rc==SQLITE_OK ){
  143202. Fts3PhraseToken *pToken;
  143203. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  143204. if( !p ) goto no_mem;
  143205. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  143206. if( !zTemp ) goto no_mem;
  143207. assert( nToken==ii );
  143208. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  143209. memset(pToken, 0, sizeof(Fts3PhraseToken));
  143210. memcpy(&zTemp[nTemp], zByte, nByte);
  143211. nTemp += nByte;
  143212. pToken->n = nByte;
  143213. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  143214. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  143215. nToken = ii+1;
  143216. }
  143217. }
  143218. pModule->xClose(pCursor);
  143219. pCursor = 0;
  143220. }
  143221. if( rc==SQLITE_DONE ){
  143222. int jj;
  143223. char *zBuf = 0;
  143224. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  143225. if( !p ) goto no_mem;
  143226. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  143227. p->eType = FTSQUERY_PHRASE;
  143228. p->pPhrase = (Fts3Phrase *)&p[1];
  143229. p->pPhrase->iColumn = pParse->iDefaultCol;
  143230. p->pPhrase->nToken = nToken;
  143231. zBuf = (char *)&p->pPhrase->aToken[nToken];
  143232. if( zTemp ){
  143233. memcpy(zBuf, zTemp, nTemp);
  143234. sqlite3_free(zTemp);
  143235. }else{
  143236. assert( nTemp==0 );
  143237. }
  143238. for(jj=0; jj<p->pPhrase->nToken; jj++){
  143239. p->pPhrase->aToken[jj].z = zBuf;
  143240. zBuf += p->pPhrase->aToken[jj].n;
  143241. }
  143242. rc = SQLITE_OK;
  143243. }
  143244. *ppExpr = p;
  143245. return rc;
  143246. no_mem:
  143247. if( pCursor ){
  143248. pModule->xClose(pCursor);
  143249. }
  143250. sqlite3_free(zTemp);
  143251. sqlite3_free(p);
  143252. *ppExpr = 0;
  143253. return SQLITE_NOMEM;
  143254. }
  143255. /*
  143256. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  143257. ** structure, or set to 0 if the end of the input buffer is reached.
  143258. **
  143259. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  143260. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  143261. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  143262. */
  143263. static int getNextNode(
  143264. ParseContext *pParse, /* fts3 query parse context */
  143265. const char *z, int n, /* Input string */
  143266. Fts3Expr **ppExpr, /* OUT: expression */
  143267. int *pnConsumed /* OUT: Number of bytes consumed */
  143268. ){
  143269. static const struct Fts3Keyword {
  143270. char *z; /* Keyword text */
  143271. unsigned char n; /* Length of the keyword */
  143272. unsigned char parenOnly; /* Only valid in paren mode */
  143273. unsigned char eType; /* Keyword code */
  143274. } aKeyword[] = {
  143275. { "OR" , 2, 0, FTSQUERY_OR },
  143276. { "AND", 3, 1, FTSQUERY_AND },
  143277. { "NOT", 3, 1, FTSQUERY_NOT },
  143278. { "NEAR", 4, 0, FTSQUERY_NEAR }
  143279. };
  143280. int ii;
  143281. int iCol;
  143282. int iColLen;
  143283. int rc;
  143284. Fts3Expr *pRet = 0;
  143285. const char *zInput = z;
  143286. int nInput = n;
  143287. pParse->isNot = 0;
  143288. /* Skip over any whitespace before checking for a keyword, an open or
  143289. ** close bracket, or a quoted string.
  143290. */
  143291. while( nInput>0 && fts3isspace(*zInput) ){
  143292. nInput--;
  143293. zInput++;
  143294. }
  143295. if( nInput==0 ){
  143296. return SQLITE_DONE;
  143297. }
  143298. /* See if we are dealing with a keyword. */
  143299. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  143300. const struct Fts3Keyword *pKey = &aKeyword[ii];
  143301. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  143302. continue;
  143303. }
  143304. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  143305. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  143306. int nKey = pKey->n;
  143307. char cNext;
  143308. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  143309. if( pKey->eType==FTSQUERY_NEAR ){
  143310. assert( nKey==4 );
  143311. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  143312. nNear = 0;
  143313. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  143314. nNear = nNear * 10 + (zInput[nKey] - '0');
  143315. }
  143316. }
  143317. }
  143318. /* At this point this is probably a keyword. But for that to be true,
  143319. ** the next byte must contain either whitespace, an open or close
  143320. ** parenthesis, a quote character, or EOF.
  143321. */
  143322. cNext = zInput[nKey];
  143323. if( fts3isspace(cNext)
  143324. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  143325. ){
  143326. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  143327. if( !pRet ){
  143328. return SQLITE_NOMEM;
  143329. }
  143330. pRet->eType = pKey->eType;
  143331. pRet->nNear = nNear;
  143332. *ppExpr = pRet;
  143333. *pnConsumed = (int)((zInput - z) + nKey);
  143334. return SQLITE_OK;
  143335. }
  143336. /* Turns out that wasn't a keyword after all. This happens if the
  143337. ** user has supplied a token such as "ORacle". Continue.
  143338. */
  143339. }
  143340. }
  143341. /* See if we are dealing with a quoted phrase. If this is the case, then
  143342. ** search for the closing quote and pass the whole string to getNextString()
  143343. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  143344. ** a quote character embedded in a string.
  143345. */
  143346. if( *zInput=='"' ){
  143347. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  143348. *pnConsumed = (int)((zInput - z) + ii + 1);
  143349. if( ii==nInput ){
  143350. return SQLITE_ERROR;
  143351. }
  143352. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  143353. }
  143354. if( sqlite3_fts3_enable_parentheses ){
  143355. if( *zInput=='(' ){
  143356. int nConsumed = 0;
  143357. pParse->nNest++;
  143358. rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
  143359. if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
  143360. *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
  143361. return rc;
  143362. }else if( *zInput==')' ){
  143363. pParse->nNest--;
  143364. *pnConsumed = (int)((zInput - z) + 1);
  143365. *ppExpr = 0;
  143366. return SQLITE_DONE;
  143367. }
  143368. }
  143369. /* If control flows to this point, this must be a regular token, or
  143370. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  143371. ** interface. Before doing so, figure out if there is an explicit
  143372. ** column specifier for the token.
  143373. **
  143374. ** TODO: Strangely, it is not possible to associate a column specifier
  143375. ** with a quoted phrase, only with a single token. Not sure if this was
  143376. ** an implementation artifact or an intentional decision when fts3 was
  143377. ** first implemented. Whichever it was, this module duplicates the
  143378. ** limitation.
  143379. */
  143380. iCol = pParse->iDefaultCol;
  143381. iColLen = 0;
  143382. for(ii=0; ii<pParse->nCol; ii++){
  143383. const char *zStr = pParse->azCol[ii];
  143384. int nStr = (int)strlen(zStr);
  143385. if( nInput>nStr && zInput[nStr]==':'
  143386. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  143387. ){
  143388. iCol = ii;
  143389. iColLen = (int)((zInput - z) + nStr + 1);
  143390. break;
  143391. }
  143392. }
  143393. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  143394. *pnConsumed += iColLen;
  143395. return rc;
  143396. }
  143397. /*
  143398. ** The argument is an Fts3Expr structure for a binary operator (any type
  143399. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  143400. ** precedence of the operator. Lower values have a higher precedence (i.e.
  143401. ** group more tightly). For example, in the C language, the == operator
  143402. ** groups more tightly than ||, and would therefore have a higher precedence.
  143403. **
  143404. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  143405. ** is defined), the order of the operators in precedence from highest to
  143406. ** lowest is:
  143407. **
  143408. ** NEAR
  143409. ** NOT
  143410. ** AND (including implicit ANDs)
  143411. ** OR
  143412. **
  143413. ** Note that when using the old query syntax, the OR operator has a higher
  143414. ** precedence than the AND operator.
  143415. */
  143416. static int opPrecedence(Fts3Expr *p){
  143417. assert( p->eType!=FTSQUERY_PHRASE );
  143418. if( sqlite3_fts3_enable_parentheses ){
  143419. return p->eType;
  143420. }else if( p->eType==FTSQUERY_NEAR ){
  143421. return 1;
  143422. }else if( p->eType==FTSQUERY_OR ){
  143423. return 2;
  143424. }
  143425. assert( p->eType==FTSQUERY_AND );
  143426. return 3;
  143427. }
  143428. /*
  143429. ** Argument ppHead contains a pointer to the current head of a query
  143430. ** expression tree being parsed. pPrev is the expression node most recently
  143431. ** inserted into the tree. This function adds pNew, which is always a binary
  143432. ** operator node, into the expression tree based on the relative precedence
  143433. ** of pNew and the existing nodes of the tree. This may result in the head
  143434. ** of the tree changing, in which case *ppHead is set to the new root node.
  143435. */
  143436. static void insertBinaryOperator(
  143437. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  143438. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  143439. Fts3Expr *pNew /* New binary node to insert into expression tree */
  143440. ){
  143441. Fts3Expr *pSplit = pPrev;
  143442. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  143443. pSplit = pSplit->pParent;
  143444. }
  143445. if( pSplit->pParent ){
  143446. assert( pSplit->pParent->pRight==pSplit );
  143447. pSplit->pParent->pRight = pNew;
  143448. pNew->pParent = pSplit->pParent;
  143449. }else{
  143450. *ppHead = pNew;
  143451. }
  143452. pNew->pLeft = pSplit;
  143453. pSplit->pParent = pNew;
  143454. }
  143455. /*
  143456. ** Parse the fts3 query expression found in buffer z, length n. This function
  143457. ** returns either when the end of the buffer is reached or an unmatched
  143458. ** closing bracket - ')' - is encountered.
  143459. **
  143460. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  143461. ** parsed form of the expression and *pnConsumed is set to the number of
  143462. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  143463. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  143464. */
  143465. static int fts3ExprParse(
  143466. ParseContext *pParse, /* fts3 query parse context */
  143467. const char *z, int n, /* Text of MATCH query */
  143468. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  143469. int *pnConsumed /* OUT: Number of bytes consumed */
  143470. ){
  143471. Fts3Expr *pRet = 0;
  143472. Fts3Expr *pPrev = 0;
  143473. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  143474. int nIn = n;
  143475. const char *zIn = z;
  143476. int rc = SQLITE_OK;
  143477. int isRequirePhrase = 1;
  143478. while( rc==SQLITE_OK ){
  143479. Fts3Expr *p = 0;
  143480. int nByte = 0;
  143481. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  143482. assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
  143483. if( rc==SQLITE_OK ){
  143484. if( p ){
  143485. int isPhrase;
  143486. if( !sqlite3_fts3_enable_parentheses
  143487. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  143488. ){
  143489. /* Create an implicit NOT operator. */
  143490. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  143491. if( !pNot ){
  143492. sqlite3Fts3ExprFree(p);
  143493. rc = SQLITE_NOMEM;
  143494. goto exprparse_out;
  143495. }
  143496. pNot->eType = FTSQUERY_NOT;
  143497. pNot->pRight = p;
  143498. p->pParent = pNot;
  143499. if( pNotBranch ){
  143500. pNot->pLeft = pNotBranch;
  143501. pNotBranch->pParent = pNot;
  143502. }
  143503. pNotBranch = pNot;
  143504. p = pPrev;
  143505. }else{
  143506. int eType = p->eType;
  143507. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  143508. /* The isRequirePhrase variable is set to true if a phrase or
  143509. ** an expression contained in parenthesis is required. If a
  143510. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  143511. ** isRequirePhrase is set, this is a syntax error.
  143512. */
  143513. if( !isPhrase && isRequirePhrase ){
  143514. sqlite3Fts3ExprFree(p);
  143515. rc = SQLITE_ERROR;
  143516. goto exprparse_out;
  143517. }
  143518. if( isPhrase && !isRequirePhrase ){
  143519. /* Insert an implicit AND operator. */
  143520. Fts3Expr *pAnd;
  143521. assert( pRet && pPrev );
  143522. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  143523. if( !pAnd ){
  143524. sqlite3Fts3ExprFree(p);
  143525. rc = SQLITE_NOMEM;
  143526. goto exprparse_out;
  143527. }
  143528. pAnd->eType = FTSQUERY_AND;
  143529. insertBinaryOperator(&pRet, pPrev, pAnd);
  143530. pPrev = pAnd;
  143531. }
  143532. /* This test catches attempts to make either operand of a NEAR
  143533. ** operator something other than a phrase. For example, either of
  143534. ** the following:
  143535. **
  143536. ** (bracketed expression) NEAR phrase
  143537. ** phrase NEAR (bracketed expression)
  143538. **
  143539. ** Return an error in either case.
  143540. */
  143541. if( pPrev && (
  143542. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  143543. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  143544. )){
  143545. sqlite3Fts3ExprFree(p);
  143546. rc = SQLITE_ERROR;
  143547. goto exprparse_out;
  143548. }
  143549. if( isPhrase ){
  143550. if( pRet ){
  143551. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  143552. pPrev->pRight = p;
  143553. p->pParent = pPrev;
  143554. }else{
  143555. pRet = p;
  143556. }
  143557. }else{
  143558. insertBinaryOperator(&pRet, pPrev, p);
  143559. }
  143560. isRequirePhrase = !isPhrase;
  143561. }
  143562. pPrev = p;
  143563. }
  143564. assert( nByte>0 );
  143565. }
  143566. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  143567. nIn -= nByte;
  143568. zIn += nByte;
  143569. }
  143570. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  143571. rc = SQLITE_ERROR;
  143572. }
  143573. if( rc==SQLITE_DONE ){
  143574. rc = SQLITE_OK;
  143575. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  143576. if( !pRet ){
  143577. rc = SQLITE_ERROR;
  143578. }else{
  143579. Fts3Expr *pIter = pNotBranch;
  143580. while( pIter->pLeft ){
  143581. pIter = pIter->pLeft;
  143582. }
  143583. pIter->pLeft = pRet;
  143584. pRet->pParent = pIter;
  143585. pRet = pNotBranch;
  143586. }
  143587. }
  143588. }
  143589. *pnConsumed = n - nIn;
  143590. exprparse_out:
  143591. if( rc!=SQLITE_OK ){
  143592. sqlite3Fts3ExprFree(pRet);
  143593. sqlite3Fts3ExprFree(pNotBranch);
  143594. pRet = 0;
  143595. }
  143596. *ppExpr = pRet;
  143597. return rc;
  143598. }
  143599. /*
  143600. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  143601. ** as the only argument is more than nMaxDepth.
  143602. */
  143603. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  143604. int rc = SQLITE_OK;
  143605. if( p ){
  143606. if( nMaxDepth<0 ){
  143607. rc = SQLITE_TOOBIG;
  143608. }else{
  143609. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  143610. if( rc==SQLITE_OK ){
  143611. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  143612. }
  143613. }
  143614. }
  143615. return rc;
  143616. }
  143617. /*
  143618. ** This function attempts to transform the expression tree at (*pp) to
  143619. ** an equivalent but more balanced form. The tree is modified in place.
  143620. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  143621. ** new root expression node.
  143622. **
  143623. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  143624. **
  143625. ** Otherwise, if an error occurs, an SQLite error code is returned and
  143626. ** expression (*pp) freed.
  143627. */
  143628. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  143629. int rc = SQLITE_OK; /* Return code */
  143630. Fts3Expr *pRoot = *pp; /* Initial root node */
  143631. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  143632. int eType = pRoot->eType; /* Type of node in this tree */
  143633. if( nMaxDepth==0 ){
  143634. rc = SQLITE_ERROR;
  143635. }
  143636. if( rc==SQLITE_OK ){
  143637. if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  143638. Fts3Expr **apLeaf;
  143639. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  143640. if( 0==apLeaf ){
  143641. rc = SQLITE_NOMEM;
  143642. }else{
  143643. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  143644. }
  143645. if( rc==SQLITE_OK ){
  143646. int i;
  143647. Fts3Expr *p;
  143648. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  143649. for(p=pRoot; p->eType==eType; p=p->pLeft){
  143650. assert( p->pParent==0 || p->pParent->pLeft==p );
  143651. assert( p->pLeft && p->pRight );
  143652. }
  143653. /* This loop runs once for each leaf in the tree of eType nodes. */
  143654. while( 1 ){
  143655. int iLvl;
  143656. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  143657. assert( pParent==0 || pParent->pLeft==p );
  143658. p->pParent = 0;
  143659. if( pParent ){
  143660. pParent->pLeft = 0;
  143661. }else{
  143662. pRoot = 0;
  143663. }
  143664. rc = fts3ExprBalance(&p, nMaxDepth-1);
  143665. if( rc!=SQLITE_OK ) break;
  143666. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  143667. if( apLeaf[iLvl]==0 ){
  143668. apLeaf[iLvl] = p;
  143669. p = 0;
  143670. }else{
  143671. assert( pFree );
  143672. pFree->pLeft = apLeaf[iLvl];
  143673. pFree->pRight = p;
  143674. pFree->pLeft->pParent = pFree;
  143675. pFree->pRight->pParent = pFree;
  143676. p = pFree;
  143677. pFree = pFree->pParent;
  143678. p->pParent = 0;
  143679. apLeaf[iLvl] = 0;
  143680. }
  143681. }
  143682. if( p ){
  143683. sqlite3Fts3ExprFree(p);
  143684. rc = SQLITE_TOOBIG;
  143685. break;
  143686. }
  143687. /* If that was the last leaf node, break out of the loop */
  143688. if( pParent==0 ) break;
  143689. /* Set $p to point to the next leaf in the tree of eType nodes */
  143690. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  143691. /* Remove pParent from the original tree. */
  143692. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  143693. pParent->pRight->pParent = pParent->pParent;
  143694. if( pParent->pParent ){
  143695. pParent->pParent->pLeft = pParent->pRight;
  143696. }else{
  143697. assert( pParent==pRoot );
  143698. pRoot = pParent->pRight;
  143699. }
  143700. /* Link pParent into the free node list. It will be used as an
  143701. ** internal node of the new tree. */
  143702. pParent->pParent = pFree;
  143703. pFree = pParent;
  143704. }
  143705. if( rc==SQLITE_OK ){
  143706. p = 0;
  143707. for(i=0; i<nMaxDepth; i++){
  143708. if( apLeaf[i] ){
  143709. if( p==0 ){
  143710. p = apLeaf[i];
  143711. p->pParent = 0;
  143712. }else{
  143713. assert( pFree!=0 );
  143714. pFree->pRight = p;
  143715. pFree->pLeft = apLeaf[i];
  143716. pFree->pLeft->pParent = pFree;
  143717. pFree->pRight->pParent = pFree;
  143718. p = pFree;
  143719. pFree = pFree->pParent;
  143720. p->pParent = 0;
  143721. }
  143722. }
  143723. }
  143724. pRoot = p;
  143725. }else{
  143726. /* An error occurred. Delete the contents of the apLeaf[] array
  143727. ** and pFree list. Everything else is cleaned up by the call to
  143728. ** sqlite3Fts3ExprFree(pRoot) below. */
  143729. Fts3Expr *pDel;
  143730. for(i=0; i<nMaxDepth; i++){
  143731. sqlite3Fts3ExprFree(apLeaf[i]);
  143732. }
  143733. while( (pDel=pFree)!=0 ){
  143734. pFree = pDel->pParent;
  143735. sqlite3_free(pDel);
  143736. }
  143737. }
  143738. assert( pFree==0 );
  143739. sqlite3_free( apLeaf );
  143740. }
  143741. }else if( eType==FTSQUERY_NOT ){
  143742. Fts3Expr *pLeft = pRoot->pLeft;
  143743. Fts3Expr *pRight = pRoot->pRight;
  143744. pRoot->pLeft = 0;
  143745. pRoot->pRight = 0;
  143746. pLeft->pParent = 0;
  143747. pRight->pParent = 0;
  143748. rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
  143749. if( rc==SQLITE_OK ){
  143750. rc = fts3ExprBalance(&pRight, nMaxDepth-1);
  143751. }
  143752. if( rc!=SQLITE_OK ){
  143753. sqlite3Fts3ExprFree(pRight);
  143754. sqlite3Fts3ExprFree(pLeft);
  143755. }else{
  143756. assert( pLeft && pRight );
  143757. pRoot->pLeft = pLeft;
  143758. pLeft->pParent = pRoot;
  143759. pRoot->pRight = pRight;
  143760. pRight->pParent = pRoot;
  143761. }
  143762. }
  143763. }
  143764. if( rc!=SQLITE_OK ){
  143765. sqlite3Fts3ExprFree(pRoot);
  143766. pRoot = 0;
  143767. }
  143768. *pp = pRoot;
  143769. return rc;
  143770. }
  143771. /*
  143772. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  143773. ** differences:
  143774. **
  143775. ** 1. It does not do expression rebalancing.
  143776. ** 2. It does not check that the expression does not exceed the
  143777. ** maximum allowable depth.
  143778. ** 3. Even if it fails, *ppExpr may still be set to point to an
  143779. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  143780. ** in this case.
  143781. */
  143782. static int fts3ExprParseUnbalanced(
  143783. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  143784. int iLangid, /* Language id for tokenizer */
  143785. char **azCol, /* Array of column names for fts3 table */
  143786. int bFts4, /* True to allow FTS4-only syntax */
  143787. int nCol, /* Number of entries in azCol[] */
  143788. int iDefaultCol, /* Default column to query */
  143789. const char *z, int n, /* Text of MATCH query */
  143790. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  143791. ){
  143792. int nParsed;
  143793. int rc;
  143794. ParseContext sParse;
  143795. memset(&sParse, 0, sizeof(ParseContext));
  143796. sParse.pTokenizer = pTokenizer;
  143797. sParse.iLangid = iLangid;
  143798. sParse.azCol = (const char **)azCol;
  143799. sParse.nCol = nCol;
  143800. sParse.iDefaultCol = iDefaultCol;
  143801. sParse.bFts4 = bFts4;
  143802. if( z==0 ){
  143803. *ppExpr = 0;
  143804. return SQLITE_OK;
  143805. }
  143806. if( n<0 ){
  143807. n = (int)strlen(z);
  143808. }
  143809. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  143810. assert( rc==SQLITE_OK || *ppExpr==0 );
  143811. /* Check for mismatched parenthesis */
  143812. if( rc==SQLITE_OK && sParse.nNest ){
  143813. rc = SQLITE_ERROR;
  143814. }
  143815. return rc;
  143816. }
  143817. /*
  143818. ** Parameters z and n contain a pointer to and length of a buffer containing
  143819. ** an fts3 query expression, respectively. This function attempts to parse the
  143820. ** query expression and create a tree of Fts3Expr structures representing the
  143821. ** parsed expression. If successful, *ppExpr is set to point to the head
  143822. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  143823. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  143824. ** error) is returned and *ppExpr is set to 0.
  143825. **
  143826. ** If parameter n is a negative number, then z is assumed to point to a
  143827. ** nul-terminated string and the length is determined using strlen().
  143828. **
  143829. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  143830. ** use to normalize query tokens while parsing the expression. The azCol[]
  143831. ** array, which is assumed to contain nCol entries, should contain the names
  143832. ** of each column in the target fts3 table, in order from left to right.
  143833. ** Column names must be nul-terminated strings.
  143834. **
  143835. ** The iDefaultCol parameter should be passed the index of the table column
  143836. ** that appears on the left-hand-side of the MATCH operator (the default
  143837. ** column to match against for tokens for which a column name is not explicitly
  143838. ** specified as part of the query string), or -1 if tokens may by default
  143839. ** match any table column.
  143840. */
  143841. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  143842. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  143843. int iLangid, /* Language id for tokenizer */
  143844. char **azCol, /* Array of column names for fts3 table */
  143845. int bFts4, /* True to allow FTS4-only syntax */
  143846. int nCol, /* Number of entries in azCol[] */
  143847. int iDefaultCol, /* Default column to query */
  143848. const char *z, int n, /* Text of MATCH query */
  143849. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  143850. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  143851. ){
  143852. int rc = fts3ExprParseUnbalanced(
  143853. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  143854. );
  143855. /* Rebalance the expression. And check that its depth does not exceed
  143856. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  143857. if( rc==SQLITE_OK && *ppExpr ){
  143858. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  143859. if( rc==SQLITE_OK ){
  143860. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  143861. }
  143862. }
  143863. if( rc!=SQLITE_OK ){
  143864. sqlite3Fts3ExprFree(*ppExpr);
  143865. *ppExpr = 0;
  143866. if( rc==SQLITE_TOOBIG ){
  143867. sqlite3Fts3ErrMsg(pzErr,
  143868. "FTS expression tree is too large (maximum depth %d)",
  143869. SQLITE_FTS3_MAX_EXPR_DEPTH
  143870. );
  143871. rc = SQLITE_ERROR;
  143872. }else if( rc==SQLITE_ERROR ){
  143873. sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
  143874. }
  143875. }
  143876. return rc;
  143877. }
  143878. /*
  143879. ** Free a single node of an expression tree.
  143880. */
  143881. static void fts3FreeExprNode(Fts3Expr *p){
  143882. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  143883. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  143884. sqlite3_free(p->aMI);
  143885. sqlite3_free(p);
  143886. }
  143887. /*
  143888. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  143889. **
  143890. ** This function would be simpler if it recursively called itself. But
  143891. ** that would mean passing a sufficiently large expression to ExprParse()
  143892. ** could cause a stack overflow.
  143893. */
  143894. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  143895. Fts3Expr *p;
  143896. assert( pDel==0 || pDel->pParent==0 );
  143897. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  143898. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  143899. }
  143900. while( p ){
  143901. Fts3Expr *pParent = p->pParent;
  143902. fts3FreeExprNode(p);
  143903. if( pParent && p==pParent->pLeft && pParent->pRight ){
  143904. p = pParent->pRight;
  143905. while( p && (p->pLeft || p->pRight) ){
  143906. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  143907. p = (p->pLeft ? p->pLeft : p->pRight);
  143908. }
  143909. }else{
  143910. p = pParent;
  143911. }
  143912. }
  143913. }
  143914. /****************************************************************************
  143915. *****************************************************************************
  143916. ** Everything after this point is just test code.
  143917. */
  143918. #ifdef SQLITE_TEST
  143919. /* #include <stdio.h> */
  143920. /*
  143921. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  143922. */
  143923. static int queryTestTokenizer(
  143924. sqlite3 *db,
  143925. const char *zName,
  143926. const sqlite3_tokenizer_module **pp
  143927. ){
  143928. int rc;
  143929. sqlite3_stmt *pStmt;
  143930. const char zSql[] = "SELECT fts3_tokenizer(?)";
  143931. *pp = 0;
  143932. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  143933. if( rc!=SQLITE_OK ){
  143934. return rc;
  143935. }
  143936. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  143937. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  143938. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  143939. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  143940. }
  143941. }
  143942. return sqlite3_finalize(pStmt);
  143943. }
  143944. /*
  143945. ** Return a pointer to a buffer containing a text representation of the
  143946. ** expression passed as the first argument. The buffer is obtained from
  143947. ** sqlite3_malloc(). It is the responsibility of the caller to use
  143948. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  143949. ** NULL is returned.
  143950. **
  143951. ** If the second argument is not NULL, then its contents are prepended to
  143952. ** the returned expression text and then freed using sqlite3_free().
  143953. */
  143954. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  143955. if( pExpr==0 ){
  143956. return sqlite3_mprintf("");
  143957. }
  143958. switch( pExpr->eType ){
  143959. case FTSQUERY_PHRASE: {
  143960. Fts3Phrase *pPhrase = pExpr->pPhrase;
  143961. int i;
  143962. zBuf = sqlite3_mprintf(
  143963. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  143964. for(i=0; zBuf && i<pPhrase->nToken; i++){
  143965. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  143966. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  143967. (pPhrase->aToken[i].isPrefix?"+":"")
  143968. );
  143969. }
  143970. return zBuf;
  143971. }
  143972. case FTSQUERY_NEAR:
  143973. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  143974. break;
  143975. case FTSQUERY_NOT:
  143976. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  143977. break;
  143978. case FTSQUERY_AND:
  143979. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  143980. break;
  143981. case FTSQUERY_OR:
  143982. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  143983. break;
  143984. }
  143985. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  143986. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  143987. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  143988. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  143989. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  143990. return zBuf;
  143991. }
  143992. /*
  143993. ** This is the implementation of a scalar SQL function used to test the
  143994. ** expression parser. It should be called as follows:
  143995. **
  143996. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  143997. **
  143998. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  143999. ** to parse the query expression (see README.tokenizers). The second argument
  144000. ** is the query expression to parse. Each subsequent argument is the name
  144001. ** of a column of the fts3 table that the query expression may refer to.
  144002. ** For example:
  144003. **
  144004. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  144005. */
  144006. static void fts3ExprTest(
  144007. sqlite3_context *context,
  144008. int argc,
  144009. sqlite3_value **argv
  144010. ){
  144011. sqlite3_tokenizer_module const *pModule = 0;
  144012. sqlite3_tokenizer *pTokenizer = 0;
  144013. int rc;
  144014. char **azCol = 0;
  144015. const char *zExpr;
  144016. int nExpr;
  144017. int nCol;
  144018. int ii;
  144019. Fts3Expr *pExpr;
  144020. char *zBuf = 0;
  144021. sqlite3 *db = sqlite3_context_db_handle(context);
  144022. if( argc<3 ){
  144023. sqlite3_result_error(context,
  144024. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  144025. );
  144026. return;
  144027. }
  144028. rc = queryTestTokenizer(db,
  144029. (const char *)sqlite3_value_text(argv[0]), &pModule);
  144030. if( rc==SQLITE_NOMEM ){
  144031. sqlite3_result_error_nomem(context);
  144032. goto exprtest_out;
  144033. }else if( !pModule ){
  144034. sqlite3_result_error(context, "No such tokenizer module", -1);
  144035. goto exprtest_out;
  144036. }
  144037. rc = pModule->xCreate(0, 0, &pTokenizer);
  144038. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  144039. if( rc==SQLITE_NOMEM ){
  144040. sqlite3_result_error_nomem(context);
  144041. goto exprtest_out;
  144042. }
  144043. pTokenizer->pModule = pModule;
  144044. zExpr = (const char *)sqlite3_value_text(argv[1]);
  144045. nExpr = sqlite3_value_bytes(argv[1]);
  144046. nCol = argc-2;
  144047. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  144048. if( !azCol ){
  144049. sqlite3_result_error_nomem(context);
  144050. goto exprtest_out;
  144051. }
  144052. for(ii=0; ii<nCol; ii++){
  144053. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  144054. }
  144055. if( sqlite3_user_data(context) ){
  144056. char *zDummy = 0;
  144057. rc = sqlite3Fts3ExprParse(
  144058. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  144059. );
  144060. assert( rc==SQLITE_OK || pExpr==0 );
  144061. sqlite3_free(zDummy);
  144062. }else{
  144063. rc = fts3ExprParseUnbalanced(
  144064. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  144065. );
  144066. }
  144067. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  144068. sqlite3Fts3ExprFree(pExpr);
  144069. sqlite3_result_error(context, "Error parsing expression", -1);
  144070. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  144071. sqlite3_result_error_nomem(context);
  144072. }else{
  144073. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  144074. sqlite3_free(zBuf);
  144075. }
  144076. sqlite3Fts3ExprFree(pExpr);
  144077. exprtest_out:
  144078. if( pModule && pTokenizer ){
  144079. rc = pModule->xDestroy(pTokenizer);
  144080. }
  144081. sqlite3_free(azCol);
  144082. }
  144083. /*
  144084. ** Register the query expression parser test function fts3_exprtest()
  144085. ** with database connection db.
  144086. */
  144087. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  144088. int rc = sqlite3_create_function(
  144089. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  144090. );
  144091. if( rc==SQLITE_OK ){
  144092. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  144093. -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
  144094. );
  144095. }
  144096. return rc;
  144097. }
  144098. #endif
  144099. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  144100. /************** End of fts3_expr.c *******************************************/
  144101. /************** Begin file fts3_hash.c ***************************************/
  144102. /*
  144103. ** 2001 September 22
  144104. **
  144105. ** The author disclaims copyright to this source code. In place of
  144106. ** a legal notice, here is a blessing:
  144107. **
  144108. ** May you do good and not evil.
  144109. ** May you find forgiveness for yourself and forgive others.
  144110. ** May you share freely, never taking more than you give.
  144111. **
  144112. *************************************************************************
  144113. ** This is the implementation of generic hash-tables used in SQLite.
  144114. ** We've modified it slightly to serve as a standalone hash table
  144115. ** implementation for the full-text indexing module.
  144116. */
  144117. /*
  144118. ** The code in this file is only compiled if:
  144119. **
  144120. ** * The FTS3 module is being built as an extension
  144121. ** (in which case SQLITE_CORE is not defined), or
  144122. **
  144123. ** * The FTS3 module is being built into the core of
  144124. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  144125. */
  144126. /* #include "fts3Int.h" */
  144127. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  144128. /* #include <assert.h> */
  144129. /* #include <stdlib.h> */
  144130. /* #include <string.h> */
  144131. /* #include "fts3_hash.h" */
  144132. /*
  144133. ** Malloc and Free functions
  144134. */
  144135. static void *fts3HashMalloc(int n){
  144136. void *p = sqlite3_malloc(n);
  144137. if( p ){
  144138. memset(p, 0, n);
  144139. }
  144140. return p;
  144141. }
  144142. static void fts3HashFree(void *p){
  144143. sqlite3_free(p);
  144144. }
  144145. /* Turn bulk memory into a hash table object by initializing the
  144146. ** fields of the Hash structure.
  144147. **
  144148. ** "pNew" is a pointer to the hash table that is to be initialized.
  144149. ** keyClass is one of the constants
  144150. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  144151. ** determines what kind of key the hash table will use. "copyKey" is
  144152. ** true if the hash table should make its own private copy of keys and
  144153. ** false if it should just use the supplied pointer.
  144154. */
  144155. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  144156. assert( pNew!=0 );
  144157. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  144158. pNew->keyClass = keyClass;
  144159. pNew->copyKey = copyKey;
  144160. pNew->first = 0;
  144161. pNew->count = 0;
  144162. pNew->htsize = 0;
  144163. pNew->ht = 0;
  144164. }
  144165. /* Remove all entries from a hash table. Reclaim all memory.
  144166. ** Call this routine to delete a hash table or to reset a hash table
  144167. ** to the empty state.
  144168. */
  144169. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  144170. Fts3HashElem *elem; /* For looping over all elements of the table */
  144171. assert( pH!=0 );
  144172. elem = pH->first;
  144173. pH->first = 0;
  144174. fts3HashFree(pH->ht);
  144175. pH->ht = 0;
  144176. pH->htsize = 0;
  144177. while( elem ){
  144178. Fts3HashElem *next_elem = elem->next;
  144179. if( pH->copyKey && elem->pKey ){
  144180. fts3HashFree(elem->pKey);
  144181. }
  144182. fts3HashFree(elem);
  144183. elem = next_elem;
  144184. }
  144185. pH->count = 0;
  144186. }
  144187. /*
  144188. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  144189. */
  144190. static int fts3StrHash(const void *pKey, int nKey){
  144191. const char *z = (const char *)pKey;
  144192. unsigned h = 0;
  144193. if( nKey<=0 ) nKey = (int) strlen(z);
  144194. while( nKey > 0 ){
  144195. h = (h<<3) ^ h ^ *z++;
  144196. nKey--;
  144197. }
  144198. return (int)(h & 0x7fffffff);
  144199. }
  144200. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  144201. if( n1!=n2 ) return 1;
  144202. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  144203. }
  144204. /*
  144205. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  144206. */
  144207. static int fts3BinHash(const void *pKey, int nKey){
  144208. int h = 0;
  144209. const char *z = (const char *)pKey;
  144210. while( nKey-- > 0 ){
  144211. h = (h<<3) ^ h ^ *(z++);
  144212. }
  144213. return h & 0x7fffffff;
  144214. }
  144215. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  144216. if( n1!=n2 ) return 1;
  144217. return memcmp(pKey1,pKey2,n1);
  144218. }
  144219. /*
  144220. ** Return a pointer to the appropriate hash function given the key class.
  144221. **
  144222. ** The C syntax in this function definition may be unfamilar to some
  144223. ** programmers, so we provide the following additional explanation:
  144224. **
  144225. ** The name of the function is "ftsHashFunction". The function takes a
  144226. ** single parameter "keyClass". The return value of ftsHashFunction()
  144227. ** is a pointer to another function. Specifically, the return value
  144228. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  144229. ** with types "const void*" and "int" and returns an "int".
  144230. */
  144231. static int (*ftsHashFunction(int keyClass))(const void*,int){
  144232. if( keyClass==FTS3_HASH_STRING ){
  144233. return &fts3StrHash;
  144234. }else{
  144235. assert( keyClass==FTS3_HASH_BINARY );
  144236. return &fts3BinHash;
  144237. }
  144238. }
  144239. /*
  144240. ** Return a pointer to the appropriate hash function given the key class.
  144241. **
  144242. ** For help in interpreted the obscure C code in the function definition,
  144243. ** see the header comment on the previous function.
  144244. */
  144245. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  144246. if( keyClass==FTS3_HASH_STRING ){
  144247. return &fts3StrCompare;
  144248. }else{
  144249. assert( keyClass==FTS3_HASH_BINARY );
  144250. return &fts3BinCompare;
  144251. }
  144252. }
  144253. /* Link an element into the hash table
  144254. */
  144255. static void fts3HashInsertElement(
  144256. Fts3Hash *pH, /* The complete hash table */
  144257. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  144258. Fts3HashElem *pNew /* The element to be inserted */
  144259. ){
  144260. Fts3HashElem *pHead; /* First element already in pEntry */
  144261. pHead = pEntry->chain;
  144262. if( pHead ){
  144263. pNew->next = pHead;
  144264. pNew->prev = pHead->prev;
  144265. if( pHead->prev ){ pHead->prev->next = pNew; }
  144266. else { pH->first = pNew; }
  144267. pHead->prev = pNew;
  144268. }else{
  144269. pNew->next = pH->first;
  144270. if( pH->first ){ pH->first->prev = pNew; }
  144271. pNew->prev = 0;
  144272. pH->first = pNew;
  144273. }
  144274. pEntry->count++;
  144275. pEntry->chain = pNew;
  144276. }
  144277. /* Resize the hash table so that it cantains "new_size" buckets.
  144278. ** "new_size" must be a power of 2. The hash table might fail
  144279. ** to resize if sqliteMalloc() fails.
  144280. **
  144281. ** Return non-zero if a memory allocation error occurs.
  144282. */
  144283. static int fts3Rehash(Fts3Hash *pH, int new_size){
  144284. struct _fts3ht *new_ht; /* The new hash table */
  144285. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  144286. int (*xHash)(const void*,int); /* The hash function */
  144287. assert( (new_size & (new_size-1))==0 );
  144288. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  144289. if( new_ht==0 ) return 1;
  144290. fts3HashFree(pH->ht);
  144291. pH->ht = new_ht;
  144292. pH->htsize = new_size;
  144293. xHash = ftsHashFunction(pH->keyClass);
  144294. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  144295. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  144296. next_elem = elem->next;
  144297. fts3HashInsertElement(pH, &new_ht[h], elem);
  144298. }
  144299. return 0;
  144300. }
  144301. /* This function (for internal use only) locates an element in an
  144302. ** hash table that matches the given key. The hash for this key has
  144303. ** already been computed and is passed as the 4th parameter.
  144304. */
  144305. static Fts3HashElem *fts3FindElementByHash(
  144306. const Fts3Hash *pH, /* The pH to be searched */
  144307. const void *pKey, /* The key we are searching for */
  144308. int nKey,
  144309. int h /* The hash for this key. */
  144310. ){
  144311. Fts3HashElem *elem; /* Used to loop thru the element list */
  144312. int count; /* Number of elements left to test */
  144313. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  144314. if( pH->ht ){
  144315. struct _fts3ht *pEntry = &pH->ht[h];
  144316. elem = pEntry->chain;
  144317. count = pEntry->count;
  144318. xCompare = ftsCompareFunction(pH->keyClass);
  144319. while( count-- && elem ){
  144320. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  144321. return elem;
  144322. }
  144323. elem = elem->next;
  144324. }
  144325. }
  144326. return 0;
  144327. }
  144328. /* Remove a single entry from the hash table given a pointer to that
  144329. ** element and a hash on the element's key.
  144330. */
  144331. static void fts3RemoveElementByHash(
  144332. Fts3Hash *pH, /* The pH containing "elem" */
  144333. Fts3HashElem* elem, /* The element to be removed from the pH */
  144334. int h /* Hash value for the element */
  144335. ){
  144336. struct _fts3ht *pEntry;
  144337. if( elem->prev ){
  144338. elem->prev->next = elem->next;
  144339. }else{
  144340. pH->first = elem->next;
  144341. }
  144342. if( elem->next ){
  144343. elem->next->prev = elem->prev;
  144344. }
  144345. pEntry = &pH->ht[h];
  144346. if( pEntry->chain==elem ){
  144347. pEntry->chain = elem->next;
  144348. }
  144349. pEntry->count--;
  144350. if( pEntry->count<=0 ){
  144351. pEntry->chain = 0;
  144352. }
  144353. if( pH->copyKey && elem->pKey ){
  144354. fts3HashFree(elem->pKey);
  144355. }
  144356. fts3HashFree( elem );
  144357. pH->count--;
  144358. if( pH->count<=0 ){
  144359. assert( pH->first==0 );
  144360. assert( pH->count==0 );
  144361. fts3HashClear(pH);
  144362. }
  144363. }
  144364. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  144365. const Fts3Hash *pH,
  144366. const void *pKey,
  144367. int nKey
  144368. ){
  144369. int h; /* A hash on key */
  144370. int (*xHash)(const void*,int); /* The hash function */
  144371. if( pH==0 || pH->ht==0 ) return 0;
  144372. xHash = ftsHashFunction(pH->keyClass);
  144373. assert( xHash!=0 );
  144374. h = (*xHash)(pKey,nKey);
  144375. assert( (pH->htsize & (pH->htsize-1))==0 );
  144376. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  144377. }
  144378. /*
  144379. ** Attempt to locate an element of the hash table pH with a key
  144380. ** that matches pKey,nKey. Return the data for this element if it is
  144381. ** found, or NULL if there is no match.
  144382. */
  144383. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  144384. Fts3HashElem *pElem; /* The element that matches key (if any) */
  144385. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  144386. return pElem ? pElem->data : 0;
  144387. }
  144388. /* Insert an element into the hash table pH. The key is pKey,nKey
  144389. ** and the data is "data".
  144390. **
  144391. ** If no element exists with a matching key, then a new
  144392. ** element is created. A copy of the key is made if the copyKey
  144393. ** flag is set. NULL is returned.
  144394. **
  144395. ** If another element already exists with the same key, then the
  144396. ** new data replaces the old data and the old data is returned.
  144397. ** The key is not copied in this instance. If a malloc fails, then
  144398. ** the new data is returned and the hash table is unchanged.
  144399. **
  144400. ** If the "data" parameter to this function is NULL, then the
  144401. ** element corresponding to "key" is removed from the hash table.
  144402. */
  144403. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  144404. Fts3Hash *pH, /* The hash table to insert into */
  144405. const void *pKey, /* The key */
  144406. int nKey, /* Number of bytes in the key */
  144407. void *data /* The data */
  144408. ){
  144409. int hraw; /* Raw hash value of the key */
  144410. int h; /* the hash of the key modulo hash table size */
  144411. Fts3HashElem *elem; /* Used to loop thru the element list */
  144412. Fts3HashElem *new_elem; /* New element added to the pH */
  144413. int (*xHash)(const void*,int); /* The hash function */
  144414. assert( pH!=0 );
  144415. xHash = ftsHashFunction(pH->keyClass);
  144416. assert( xHash!=0 );
  144417. hraw = (*xHash)(pKey, nKey);
  144418. assert( (pH->htsize & (pH->htsize-1))==0 );
  144419. h = hraw & (pH->htsize-1);
  144420. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  144421. if( elem ){
  144422. void *old_data = elem->data;
  144423. if( data==0 ){
  144424. fts3RemoveElementByHash(pH,elem,h);
  144425. }else{
  144426. elem->data = data;
  144427. }
  144428. return old_data;
  144429. }
  144430. if( data==0 ) return 0;
  144431. if( (pH->htsize==0 && fts3Rehash(pH,8))
  144432. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  144433. ){
  144434. pH->count = 0;
  144435. return data;
  144436. }
  144437. assert( pH->htsize>0 );
  144438. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  144439. if( new_elem==0 ) return data;
  144440. if( pH->copyKey && pKey!=0 ){
  144441. new_elem->pKey = fts3HashMalloc( nKey );
  144442. if( new_elem->pKey==0 ){
  144443. fts3HashFree(new_elem);
  144444. return data;
  144445. }
  144446. memcpy((void*)new_elem->pKey, pKey, nKey);
  144447. }else{
  144448. new_elem->pKey = (void*)pKey;
  144449. }
  144450. new_elem->nKey = nKey;
  144451. pH->count++;
  144452. assert( pH->htsize>0 );
  144453. assert( (pH->htsize & (pH->htsize-1))==0 );
  144454. h = hraw & (pH->htsize-1);
  144455. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  144456. new_elem->data = data;
  144457. return 0;
  144458. }
  144459. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  144460. /************** End of fts3_hash.c *******************************************/
  144461. /************** Begin file fts3_porter.c *************************************/
  144462. /*
  144463. ** 2006 September 30
  144464. **
  144465. ** The author disclaims copyright to this source code. In place of
  144466. ** a legal notice, here is a blessing:
  144467. **
  144468. ** May you do good and not evil.
  144469. ** May you find forgiveness for yourself and forgive others.
  144470. ** May you share freely, never taking more than you give.
  144471. **
  144472. *************************************************************************
  144473. ** Implementation of the full-text-search tokenizer that implements
  144474. ** a Porter stemmer.
  144475. */
  144476. /*
  144477. ** The code in this file is only compiled if:
  144478. **
  144479. ** * The FTS3 module is being built as an extension
  144480. ** (in which case SQLITE_CORE is not defined), or
  144481. **
  144482. ** * The FTS3 module is being built into the core of
  144483. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  144484. */
  144485. /* #include "fts3Int.h" */
  144486. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  144487. /* #include <assert.h> */
  144488. /* #include <stdlib.h> */
  144489. /* #include <stdio.h> */
  144490. /* #include <string.h> */
  144491. /* #include "fts3_tokenizer.h" */
  144492. /*
  144493. ** Class derived from sqlite3_tokenizer
  144494. */
  144495. typedef struct porter_tokenizer {
  144496. sqlite3_tokenizer base; /* Base class */
  144497. } porter_tokenizer;
  144498. /*
  144499. ** Class derived from sqlite3_tokenizer_cursor
  144500. */
  144501. typedef struct porter_tokenizer_cursor {
  144502. sqlite3_tokenizer_cursor base;
  144503. const char *zInput; /* input we are tokenizing */
  144504. int nInput; /* size of the input */
  144505. int iOffset; /* current position in zInput */
  144506. int iToken; /* index of next token to be returned */
  144507. char *zToken; /* storage for current token */
  144508. int nAllocated; /* space allocated to zToken buffer */
  144509. } porter_tokenizer_cursor;
  144510. /*
  144511. ** Create a new tokenizer instance.
  144512. */
  144513. static int porterCreate(
  144514. int argc, const char * const *argv,
  144515. sqlite3_tokenizer **ppTokenizer
  144516. ){
  144517. porter_tokenizer *t;
  144518. UNUSED_PARAMETER(argc);
  144519. UNUSED_PARAMETER(argv);
  144520. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  144521. if( t==NULL ) return SQLITE_NOMEM;
  144522. memset(t, 0, sizeof(*t));
  144523. *ppTokenizer = &t->base;
  144524. return SQLITE_OK;
  144525. }
  144526. /*
  144527. ** Destroy a tokenizer
  144528. */
  144529. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  144530. sqlite3_free(pTokenizer);
  144531. return SQLITE_OK;
  144532. }
  144533. /*
  144534. ** Prepare to begin tokenizing a particular string. The input
  144535. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  144536. ** used to incrementally tokenize this string is returned in
  144537. ** *ppCursor.
  144538. */
  144539. static int porterOpen(
  144540. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  144541. const char *zInput, int nInput, /* String to be tokenized */
  144542. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  144543. ){
  144544. porter_tokenizer_cursor *c;
  144545. UNUSED_PARAMETER(pTokenizer);
  144546. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  144547. if( c==NULL ) return SQLITE_NOMEM;
  144548. c->zInput = zInput;
  144549. if( zInput==0 ){
  144550. c->nInput = 0;
  144551. }else if( nInput<0 ){
  144552. c->nInput = (int)strlen(zInput);
  144553. }else{
  144554. c->nInput = nInput;
  144555. }
  144556. c->iOffset = 0; /* start tokenizing at the beginning */
  144557. c->iToken = 0;
  144558. c->zToken = NULL; /* no space allocated, yet. */
  144559. c->nAllocated = 0;
  144560. *ppCursor = &c->base;
  144561. return SQLITE_OK;
  144562. }
  144563. /*
  144564. ** Close a tokenization cursor previously opened by a call to
  144565. ** porterOpen() above.
  144566. */
  144567. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  144568. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  144569. sqlite3_free(c->zToken);
  144570. sqlite3_free(c);
  144571. return SQLITE_OK;
  144572. }
  144573. /*
  144574. ** Vowel or consonant
  144575. */
  144576. static const char cType[] = {
  144577. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  144578. 1, 1, 1, 2, 1
  144579. };
  144580. /*
  144581. ** isConsonant() and isVowel() determine if their first character in
  144582. ** the string they point to is a consonant or a vowel, according
  144583. ** to Porter ruls.
  144584. **
  144585. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  144586. ** 'Y' is a consonant unless it follows another consonant,
  144587. ** in which case it is a vowel.
  144588. **
  144589. ** In these routine, the letters are in reverse order. So the 'y' rule
  144590. ** is that 'y' is a consonant unless it is followed by another
  144591. ** consonent.
  144592. */
  144593. static int isVowel(const char*);
  144594. static int isConsonant(const char *z){
  144595. int j;
  144596. char x = *z;
  144597. if( x==0 ) return 0;
  144598. assert( x>='a' && x<='z' );
  144599. j = cType[x-'a'];
  144600. if( j<2 ) return j;
  144601. return z[1]==0 || isVowel(z + 1);
  144602. }
  144603. static int isVowel(const char *z){
  144604. int j;
  144605. char x = *z;
  144606. if( x==0 ) return 0;
  144607. assert( x>='a' && x<='z' );
  144608. j = cType[x-'a'];
  144609. if( j<2 ) return 1-j;
  144610. return isConsonant(z + 1);
  144611. }
  144612. /*
  144613. ** Let any sequence of one or more vowels be represented by V and let
  144614. ** C be sequence of one or more consonants. Then every word can be
  144615. ** represented as:
  144616. **
  144617. ** [C] (VC){m} [V]
  144618. **
  144619. ** In prose: A word is an optional consonant followed by zero or
  144620. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  144621. ** number of vowel consonant pairs. This routine computes the value
  144622. ** of m for the first i bytes of a word.
  144623. **
  144624. ** Return true if the m-value for z is 1 or more. In other words,
  144625. ** return true if z contains at least one vowel that is followed
  144626. ** by a consonant.
  144627. **
  144628. ** In this routine z[] is in reverse order. So we are really looking
  144629. ** for an instance of a consonant followed by a vowel.
  144630. */
  144631. static int m_gt_0(const char *z){
  144632. while( isVowel(z) ){ z++; }
  144633. if( *z==0 ) return 0;
  144634. while( isConsonant(z) ){ z++; }
  144635. return *z!=0;
  144636. }
  144637. /* Like mgt0 above except we are looking for a value of m which is
  144638. ** exactly 1
  144639. */
  144640. static int m_eq_1(const char *z){
  144641. while( isVowel(z) ){ z++; }
  144642. if( *z==0 ) return 0;
  144643. while( isConsonant(z) ){ z++; }
  144644. if( *z==0 ) return 0;
  144645. while( isVowel(z) ){ z++; }
  144646. if( *z==0 ) return 1;
  144647. while( isConsonant(z) ){ z++; }
  144648. return *z==0;
  144649. }
  144650. /* Like mgt0 above except we are looking for a value of m>1 instead
  144651. ** or m>0
  144652. */
  144653. static int m_gt_1(const char *z){
  144654. while( isVowel(z) ){ z++; }
  144655. if( *z==0 ) return 0;
  144656. while( isConsonant(z) ){ z++; }
  144657. if( *z==0 ) return 0;
  144658. while( isVowel(z) ){ z++; }
  144659. if( *z==0 ) return 0;
  144660. while( isConsonant(z) ){ z++; }
  144661. return *z!=0;
  144662. }
  144663. /*
  144664. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  144665. */
  144666. static int hasVowel(const char *z){
  144667. while( isConsonant(z) ){ z++; }
  144668. return *z!=0;
  144669. }
  144670. /*
  144671. ** Return TRUE if the word ends in a double consonant.
  144672. **
  144673. ** The text is reversed here. So we are really looking at
  144674. ** the first two characters of z[].
  144675. */
  144676. static int doubleConsonant(const char *z){
  144677. return isConsonant(z) && z[0]==z[1];
  144678. }
  144679. /*
  144680. ** Return TRUE if the word ends with three letters which
  144681. ** are consonant-vowel-consonent and where the final consonant
  144682. ** is not 'w', 'x', or 'y'.
  144683. **
  144684. ** The word is reversed here. So we are really checking the
  144685. ** first three letters and the first one cannot be in [wxy].
  144686. */
  144687. static int star_oh(const char *z){
  144688. return
  144689. isConsonant(z) &&
  144690. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  144691. isVowel(z+1) &&
  144692. isConsonant(z+2);
  144693. }
  144694. /*
  144695. ** If the word ends with zFrom and xCond() is true for the stem
  144696. ** of the word that preceeds the zFrom ending, then change the
  144697. ** ending to zTo.
  144698. **
  144699. ** The input word *pz and zFrom are both in reverse order. zTo
  144700. ** is in normal order.
  144701. **
  144702. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  144703. ** match. Not that TRUE is returned even if xCond() fails and
  144704. ** no substitution occurs.
  144705. */
  144706. static int stem(
  144707. char **pz, /* The word being stemmed (Reversed) */
  144708. const char *zFrom, /* If the ending matches this... (Reversed) */
  144709. const char *zTo, /* ... change the ending to this (not reversed) */
  144710. int (*xCond)(const char*) /* Condition that must be true */
  144711. ){
  144712. char *z = *pz;
  144713. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  144714. if( *zFrom!=0 ) return 0;
  144715. if( xCond && !xCond(z) ) return 1;
  144716. while( *zTo ){
  144717. *(--z) = *(zTo++);
  144718. }
  144719. *pz = z;
  144720. return 1;
  144721. }
  144722. /*
  144723. ** This is the fallback stemmer used when the porter stemmer is
  144724. ** inappropriate. The input word is copied into the output with
  144725. ** US-ASCII case folding. If the input word is too long (more
  144726. ** than 20 bytes if it contains no digits or more than 6 bytes if
  144727. ** it contains digits) then word is truncated to 20 or 6 bytes
  144728. ** by taking 10 or 3 bytes from the beginning and end.
  144729. */
  144730. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  144731. int i, mx, j;
  144732. int hasDigit = 0;
  144733. for(i=0; i<nIn; i++){
  144734. char c = zIn[i];
  144735. if( c>='A' && c<='Z' ){
  144736. zOut[i] = c - 'A' + 'a';
  144737. }else{
  144738. if( c>='0' && c<='9' ) hasDigit = 1;
  144739. zOut[i] = c;
  144740. }
  144741. }
  144742. mx = hasDigit ? 3 : 10;
  144743. if( nIn>mx*2 ){
  144744. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  144745. zOut[j] = zOut[i];
  144746. }
  144747. i = j;
  144748. }
  144749. zOut[i] = 0;
  144750. *pnOut = i;
  144751. }
  144752. /*
  144753. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  144754. ** zOut is at least big enough to hold nIn bytes. Write the actual
  144755. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  144756. **
  144757. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  144758. ** are converted to lower case. Upper-case UTF characters are
  144759. ** unchanged.
  144760. **
  144761. ** Words that are longer than about 20 bytes are stemmed by retaining
  144762. ** a few bytes from the beginning and the end of the word. If the
  144763. ** word contains digits, 3 bytes are taken from the beginning and
  144764. ** 3 bytes from the end. For long words without digits, 10 bytes
  144765. ** are taken from each end. US-ASCII case folding still applies.
  144766. **
  144767. ** If the input word contains not digits but does characters not
  144768. ** in [a-zA-Z] then no stemming is attempted and this routine just
  144769. ** copies the input into the input into the output with US-ASCII
  144770. ** case folding.
  144771. **
  144772. ** Stemming never increases the length of the word. So there is
  144773. ** no chance of overflowing the zOut buffer.
  144774. */
  144775. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  144776. int i, j;
  144777. char zReverse[28];
  144778. char *z, *z2;
  144779. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  144780. /* The word is too big or too small for the porter stemmer.
  144781. ** Fallback to the copy stemmer */
  144782. copy_stemmer(zIn, nIn, zOut, pnOut);
  144783. return;
  144784. }
  144785. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  144786. char c = zIn[i];
  144787. if( c>='A' && c<='Z' ){
  144788. zReverse[j] = c + 'a' - 'A';
  144789. }else if( c>='a' && c<='z' ){
  144790. zReverse[j] = c;
  144791. }else{
  144792. /* The use of a character not in [a-zA-Z] means that we fallback
  144793. ** to the copy stemmer */
  144794. copy_stemmer(zIn, nIn, zOut, pnOut);
  144795. return;
  144796. }
  144797. }
  144798. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  144799. z = &zReverse[j+1];
  144800. /* Step 1a */
  144801. if( z[0]=='s' ){
  144802. if(
  144803. !stem(&z, "sess", "ss", 0) &&
  144804. !stem(&z, "sei", "i", 0) &&
  144805. !stem(&z, "ss", "ss", 0)
  144806. ){
  144807. z++;
  144808. }
  144809. }
  144810. /* Step 1b */
  144811. z2 = z;
  144812. if( stem(&z, "dee", "ee", m_gt_0) ){
  144813. /* Do nothing. The work was all in the test */
  144814. }else if(
  144815. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  144816. && z!=z2
  144817. ){
  144818. if( stem(&z, "ta", "ate", 0) ||
  144819. stem(&z, "lb", "ble", 0) ||
  144820. stem(&z, "zi", "ize", 0) ){
  144821. /* Do nothing. The work was all in the test */
  144822. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  144823. z++;
  144824. }else if( m_eq_1(z) && star_oh(z) ){
  144825. *(--z) = 'e';
  144826. }
  144827. }
  144828. /* Step 1c */
  144829. if( z[0]=='y' && hasVowel(z+1) ){
  144830. z[0] = 'i';
  144831. }
  144832. /* Step 2 */
  144833. switch( z[1] ){
  144834. case 'a':
  144835. if( !stem(&z, "lanoita", "ate", m_gt_0) ){
  144836. stem(&z, "lanoit", "tion", m_gt_0);
  144837. }
  144838. break;
  144839. case 'c':
  144840. if( !stem(&z, "icne", "ence", m_gt_0) ){
  144841. stem(&z, "icna", "ance", m_gt_0);
  144842. }
  144843. break;
  144844. case 'e':
  144845. stem(&z, "rezi", "ize", m_gt_0);
  144846. break;
  144847. case 'g':
  144848. stem(&z, "igol", "log", m_gt_0);
  144849. break;
  144850. case 'l':
  144851. if( !stem(&z, "ilb", "ble", m_gt_0)
  144852. && !stem(&z, "illa", "al", m_gt_0)
  144853. && !stem(&z, "iltne", "ent", m_gt_0)
  144854. && !stem(&z, "ile", "e", m_gt_0)
  144855. ){
  144856. stem(&z, "ilsuo", "ous", m_gt_0);
  144857. }
  144858. break;
  144859. case 'o':
  144860. if( !stem(&z, "noitazi", "ize", m_gt_0)
  144861. && !stem(&z, "noita", "ate", m_gt_0)
  144862. ){
  144863. stem(&z, "rota", "ate", m_gt_0);
  144864. }
  144865. break;
  144866. case 's':
  144867. if( !stem(&z, "msila", "al", m_gt_0)
  144868. && !stem(&z, "ssenevi", "ive", m_gt_0)
  144869. && !stem(&z, "ssenluf", "ful", m_gt_0)
  144870. ){
  144871. stem(&z, "ssensuo", "ous", m_gt_0);
  144872. }
  144873. break;
  144874. case 't':
  144875. if( !stem(&z, "itila", "al", m_gt_0)
  144876. && !stem(&z, "itivi", "ive", m_gt_0)
  144877. ){
  144878. stem(&z, "itilib", "ble", m_gt_0);
  144879. }
  144880. break;
  144881. }
  144882. /* Step 3 */
  144883. switch( z[0] ){
  144884. case 'e':
  144885. if( !stem(&z, "etaci", "ic", m_gt_0)
  144886. && !stem(&z, "evita", "", m_gt_0)
  144887. ){
  144888. stem(&z, "ezila", "al", m_gt_0);
  144889. }
  144890. break;
  144891. case 'i':
  144892. stem(&z, "itici", "ic", m_gt_0);
  144893. break;
  144894. case 'l':
  144895. if( !stem(&z, "laci", "ic", m_gt_0) ){
  144896. stem(&z, "luf", "", m_gt_0);
  144897. }
  144898. break;
  144899. case 's':
  144900. stem(&z, "ssen", "", m_gt_0);
  144901. break;
  144902. }
  144903. /* Step 4 */
  144904. switch( z[1] ){
  144905. case 'a':
  144906. if( z[0]=='l' && m_gt_1(z+2) ){
  144907. z += 2;
  144908. }
  144909. break;
  144910. case 'c':
  144911. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  144912. z += 4;
  144913. }
  144914. break;
  144915. case 'e':
  144916. if( z[0]=='r' && m_gt_1(z+2) ){
  144917. z += 2;
  144918. }
  144919. break;
  144920. case 'i':
  144921. if( z[0]=='c' && m_gt_1(z+2) ){
  144922. z += 2;
  144923. }
  144924. break;
  144925. case 'l':
  144926. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  144927. z += 4;
  144928. }
  144929. break;
  144930. case 'n':
  144931. if( z[0]=='t' ){
  144932. if( z[2]=='a' ){
  144933. if( m_gt_1(z+3) ){
  144934. z += 3;
  144935. }
  144936. }else if( z[2]=='e' ){
  144937. if( !stem(&z, "tneme", "", m_gt_1)
  144938. && !stem(&z, "tnem", "", m_gt_1)
  144939. ){
  144940. stem(&z, "tne", "", m_gt_1);
  144941. }
  144942. }
  144943. }
  144944. break;
  144945. case 'o':
  144946. if( z[0]=='u' ){
  144947. if( m_gt_1(z+2) ){
  144948. z += 2;
  144949. }
  144950. }else if( z[3]=='s' || z[3]=='t' ){
  144951. stem(&z, "noi", "", m_gt_1);
  144952. }
  144953. break;
  144954. case 's':
  144955. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  144956. z += 3;
  144957. }
  144958. break;
  144959. case 't':
  144960. if( !stem(&z, "eta", "", m_gt_1) ){
  144961. stem(&z, "iti", "", m_gt_1);
  144962. }
  144963. break;
  144964. case 'u':
  144965. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  144966. z += 3;
  144967. }
  144968. break;
  144969. case 'v':
  144970. case 'z':
  144971. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  144972. z += 3;
  144973. }
  144974. break;
  144975. }
  144976. /* Step 5a */
  144977. if( z[0]=='e' ){
  144978. if( m_gt_1(z+1) ){
  144979. z++;
  144980. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  144981. z++;
  144982. }
  144983. }
  144984. /* Step 5b */
  144985. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  144986. z++;
  144987. }
  144988. /* z[] is now the stemmed word in reverse order. Flip it back
  144989. ** around into forward order and return.
  144990. */
  144991. *pnOut = i = (int)strlen(z);
  144992. zOut[i] = 0;
  144993. while( *z ){
  144994. zOut[--i] = *(z++);
  144995. }
  144996. }
  144997. /*
  144998. ** Characters that can be part of a token. We assume any character
  144999. ** whose value is greater than 0x80 (any UTF character) can be
  145000. ** part of a token. In other words, delimiters all must have
  145001. ** values of 0x7f or lower.
  145002. */
  145003. static const char porterIdChar[] = {
  145004. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  145005. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  145006. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  145007. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  145008. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  145009. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  145010. };
  145011. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  145012. /*
  145013. ** Extract the next token from a tokenization cursor. The cursor must
  145014. ** have been opened by a prior call to porterOpen().
  145015. */
  145016. static int porterNext(
  145017. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  145018. const char **pzToken, /* OUT: *pzToken is the token text */
  145019. int *pnBytes, /* OUT: Number of bytes in token */
  145020. int *piStartOffset, /* OUT: Starting offset of token */
  145021. int *piEndOffset, /* OUT: Ending offset of token */
  145022. int *piPosition /* OUT: Position integer of token */
  145023. ){
  145024. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  145025. const char *z = c->zInput;
  145026. while( c->iOffset<c->nInput ){
  145027. int iStartOffset, ch;
  145028. /* Scan past delimiter characters */
  145029. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  145030. c->iOffset++;
  145031. }
  145032. /* Count non-delimiter characters. */
  145033. iStartOffset = c->iOffset;
  145034. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  145035. c->iOffset++;
  145036. }
  145037. if( c->iOffset>iStartOffset ){
  145038. int n = c->iOffset-iStartOffset;
  145039. if( n>c->nAllocated ){
  145040. char *pNew;
  145041. c->nAllocated = n+20;
  145042. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  145043. if( !pNew ) return SQLITE_NOMEM;
  145044. c->zToken = pNew;
  145045. }
  145046. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  145047. *pzToken = c->zToken;
  145048. *piStartOffset = iStartOffset;
  145049. *piEndOffset = c->iOffset;
  145050. *piPosition = c->iToken++;
  145051. return SQLITE_OK;
  145052. }
  145053. }
  145054. return SQLITE_DONE;
  145055. }
  145056. /*
  145057. ** The set of routines that implement the porter-stemmer tokenizer
  145058. */
  145059. static const sqlite3_tokenizer_module porterTokenizerModule = {
  145060. 0,
  145061. porterCreate,
  145062. porterDestroy,
  145063. porterOpen,
  145064. porterClose,
  145065. porterNext,
  145066. 0
  145067. };
  145068. /*
  145069. ** Allocate a new porter tokenizer. Return a pointer to the new
  145070. ** tokenizer in *ppModule
  145071. */
  145072. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  145073. sqlite3_tokenizer_module const**ppModule
  145074. ){
  145075. *ppModule = &porterTokenizerModule;
  145076. }
  145077. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  145078. /************** End of fts3_porter.c *****************************************/
  145079. /************** Begin file fts3_tokenizer.c **********************************/
  145080. /*
  145081. ** 2007 June 22
  145082. **
  145083. ** The author disclaims copyright to this source code. In place of
  145084. ** a legal notice, here is a blessing:
  145085. **
  145086. ** May you do good and not evil.
  145087. ** May you find forgiveness for yourself and forgive others.
  145088. ** May you share freely, never taking more than you give.
  145089. **
  145090. ******************************************************************************
  145091. **
  145092. ** This is part of an SQLite module implementing full-text search.
  145093. ** This particular file implements the generic tokenizer interface.
  145094. */
  145095. /*
  145096. ** The code in this file is only compiled if:
  145097. **
  145098. ** * The FTS3 module is being built as an extension
  145099. ** (in which case SQLITE_CORE is not defined), or
  145100. **
  145101. ** * The FTS3 module is being built into the core of
  145102. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  145103. */
  145104. /* #include "fts3Int.h" */
  145105. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  145106. /* #include <assert.h> */
  145107. /* #include <string.h> */
  145108. /*
  145109. ** Return true if the two-argument version of fts3_tokenizer()
  145110. ** has been activated via a prior call to sqlite3_db_config(db,
  145111. ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
  145112. */
  145113. static int fts3TokenizerEnabled(sqlite3_context *context){
  145114. sqlite3 *db = sqlite3_context_db_handle(context);
  145115. int isEnabled = 0;
  145116. sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
  145117. return isEnabled;
  145118. }
  145119. /*
  145120. ** Implementation of the SQL scalar function for accessing the underlying
  145121. ** hash table. This function may be called as follows:
  145122. **
  145123. ** SELECT <function-name>(<key-name>);
  145124. ** SELECT <function-name>(<key-name>, <pointer>);
  145125. **
  145126. ** where <function-name> is the name passed as the second argument
  145127. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  145128. **
  145129. ** If the <pointer> argument is specified, it must be a blob value
  145130. ** containing a pointer to be stored as the hash data corresponding
  145131. ** to the string <key-name>. If <pointer> is not specified, then
  145132. ** the string <key-name> must already exist in the has table. Otherwise,
  145133. ** an error is returned.
  145134. **
  145135. ** Whether or not the <pointer> argument is specified, the value returned
  145136. ** is a blob containing the pointer stored as the hash data corresponding
  145137. ** to string <key-name> (after the hash-table is updated, if applicable).
  145138. */
  145139. static void fts3TokenizerFunc(
  145140. sqlite3_context *context,
  145141. int argc,
  145142. sqlite3_value **argv
  145143. ){
  145144. Fts3Hash *pHash;
  145145. void *pPtr = 0;
  145146. const unsigned char *zName;
  145147. int nName;
  145148. assert( argc==1 || argc==2 );
  145149. pHash = (Fts3Hash *)sqlite3_user_data(context);
  145150. zName = sqlite3_value_text(argv[0]);
  145151. nName = sqlite3_value_bytes(argv[0])+1;
  145152. if( argc==2 ){
  145153. if( fts3TokenizerEnabled(context) ){
  145154. void *pOld;
  145155. int n = sqlite3_value_bytes(argv[1]);
  145156. if( zName==0 || n!=sizeof(pPtr) ){
  145157. sqlite3_result_error(context, "argument type mismatch", -1);
  145158. return;
  145159. }
  145160. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  145161. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  145162. if( pOld==pPtr ){
  145163. sqlite3_result_error(context, "out of memory", -1);
  145164. }
  145165. }else{
  145166. sqlite3_result_error(context, "fts3tokenize disabled", -1);
  145167. return;
  145168. }
  145169. }else{
  145170. if( zName ){
  145171. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  145172. }
  145173. if( !pPtr ){
  145174. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  145175. sqlite3_result_error(context, zErr, -1);
  145176. sqlite3_free(zErr);
  145177. return;
  145178. }
  145179. }
  145180. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  145181. }
  145182. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  145183. static const char isFtsIdChar[] = {
  145184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  145185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  145186. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  145187. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  145188. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  145189. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  145190. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  145191. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  145192. };
  145193. return (c&0x80 || isFtsIdChar[(int)(c)]);
  145194. }
  145195. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  145196. const char *z1;
  145197. const char *z2 = 0;
  145198. /* Find the start of the next token. */
  145199. z1 = zStr;
  145200. while( z2==0 ){
  145201. char c = *z1;
  145202. switch( c ){
  145203. case '\0': return 0; /* No more tokens here */
  145204. case '\'':
  145205. case '"':
  145206. case '`': {
  145207. z2 = z1;
  145208. while( *++z2 && (*z2!=c || *++z2==c) );
  145209. break;
  145210. }
  145211. case '[':
  145212. z2 = &z1[1];
  145213. while( *z2 && z2[0]!=']' ) z2++;
  145214. if( *z2 ) z2++;
  145215. break;
  145216. default:
  145217. if( sqlite3Fts3IsIdChar(*z1) ){
  145218. z2 = &z1[1];
  145219. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  145220. }else{
  145221. z1++;
  145222. }
  145223. }
  145224. }
  145225. *pn = (int)(z2-z1);
  145226. return z1;
  145227. }
  145228. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  145229. Fts3Hash *pHash, /* Tokenizer hash table */
  145230. const char *zArg, /* Tokenizer name */
  145231. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  145232. char **pzErr /* OUT: Set to malloced error message */
  145233. ){
  145234. int rc;
  145235. char *z = (char *)zArg;
  145236. int n = 0;
  145237. char *zCopy;
  145238. char *zEnd; /* Pointer to nul-term of zCopy */
  145239. sqlite3_tokenizer_module *m;
  145240. zCopy = sqlite3_mprintf("%s", zArg);
  145241. if( !zCopy ) return SQLITE_NOMEM;
  145242. zEnd = &zCopy[strlen(zCopy)];
  145243. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  145244. if( z==0 ){
  145245. assert( n==0 );
  145246. z = zCopy;
  145247. }
  145248. z[n] = '\0';
  145249. sqlite3Fts3Dequote(z);
  145250. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  145251. if( !m ){
  145252. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
  145253. rc = SQLITE_ERROR;
  145254. }else{
  145255. char const **aArg = 0;
  145256. int iArg = 0;
  145257. z = &z[n+1];
  145258. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  145259. int nNew = sizeof(char *)*(iArg+1);
  145260. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  145261. if( !aNew ){
  145262. sqlite3_free(zCopy);
  145263. sqlite3_free((void *)aArg);
  145264. return SQLITE_NOMEM;
  145265. }
  145266. aArg = aNew;
  145267. aArg[iArg++] = z;
  145268. z[n] = '\0';
  145269. sqlite3Fts3Dequote(z);
  145270. z = &z[n+1];
  145271. }
  145272. rc = m->xCreate(iArg, aArg, ppTok);
  145273. assert( rc!=SQLITE_OK || *ppTok );
  145274. if( rc!=SQLITE_OK ){
  145275. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
  145276. }else{
  145277. (*ppTok)->pModule = m;
  145278. }
  145279. sqlite3_free((void *)aArg);
  145280. }
  145281. sqlite3_free(zCopy);
  145282. return rc;
  145283. }
  145284. #ifdef SQLITE_TEST
  145285. #if defined(INCLUDE_SQLITE_TCL_H)
  145286. # include "sqlite_tcl.h"
  145287. #else
  145288. # include "tcl.h"
  145289. #endif
  145290. /* #include <string.h> */
  145291. /*
  145292. ** Implementation of a special SQL scalar function for testing tokenizers
  145293. ** designed to be used in concert with the Tcl testing framework. This
  145294. ** function must be called with two or more arguments:
  145295. **
  145296. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  145297. **
  145298. ** where <function-name> is the name passed as the second argument
  145299. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  145300. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  145301. **
  145302. ** The return value is a string that may be interpreted as a Tcl
  145303. ** list. For each token in the <input-string>, three elements are
  145304. ** added to the returned list. The first is the token position, the
  145305. ** second is the token text (folded, stemmed, etc.) and the third is the
  145306. ** substring of <input-string> associated with the token. For example,
  145307. ** using the built-in "simple" tokenizer:
  145308. **
  145309. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  145310. **
  145311. ** will return the string:
  145312. **
  145313. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  145314. **
  145315. */
  145316. static void testFunc(
  145317. sqlite3_context *context,
  145318. int argc,
  145319. sqlite3_value **argv
  145320. ){
  145321. Fts3Hash *pHash;
  145322. sqlite3_tokenizer_module *p;
  145323. sqlite3_tokenizer *pTokenizer = 0;
  145324. sqlite3_tokenizer_cursor *pCsr = 0;
  145325. const char *zErr = 0;
  145326. const char *zName;
  145327. int nName;
  145328. const char *zInput;
  145329. int nInput;
  145330. const char *azArg[64];
  145331. const char *zToken;
  145332. int nToken = 0;
  145333. int iStart = 0;
  145334. int iEnd = 0;
  145335. int iPos = 0;
  145336. int i;
  145337. Tcl_Obj *pRet;
  145338. if( argc<2 ){
  145339. sqlite3_result_error(context, "insufficient arguments", -1);
  145340. return;
  145341. }
  145342. nName = sqlite3_value_bytes(argv[0]);
  145343. zName = (const char *)sqlite3_value_text(argv[0]);
  145344. nInput = sqlite3_value_bytes(argv[argc-1]);
  145345. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  145346. pHash = (Fts3Hash *)sqlite3_user_data(context);
  145347. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  145348. if( !p ){
  145349. char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
  145350. sqlite3_result_error(context, zErr2, -1);
  145351. sqlite3_free(zErr2);
  145352. return;
  145353. }
  145354. pRet = Tcl_NewObj();
  145355. Tcl_IncrRefCount(pRet);
  145356. for(i=1; i<argc-1; i++){
  145357. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  145358. }
  145359. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  145360. zErr = "error in xCreate()";
  145361. goto finish;
  145362. }
  145363. pTokenizer->pModule = p;
  145364. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  145365. zErr = "error in xOpen()";
  145366. goto finish;
  145367. }
  145368. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  145369. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  145370. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  145371. zToken = &zInput[iStart];
  145372. nToken = iEnd-iStart;
  145373. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  145374. }
  145375. if( SQLITE_OK!=p->xClose(pCsr) ){
  145376. zErr = "error in xClose()";
  145377. goto finish;
  145378. }
  145379. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  145380. zErr = "error in xDestroy()";
  145381. goto finish;
  145382. }
  145383. finish:
  145384. if( zErr ){
  145385. sqlite3_result_error(context, zErr, -1);
  145386. }else{
  145387. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  145388. }
  145389. Tcl_DecrRefCount(pRet);
  145390. }
  145391. static
  145392. int registerTokenizer(
  145393. sqlite3 *db,
  145394. char *zName,
  145395. const sqlite3_tokenizer_module *p
  145396. ){
  145397. int rc;
  145398. sqlite3_stmt *pStmt;
  145399. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  145400. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  145401. if( rc!=SQLITE_OK ){
  145402. return rc;
  145403. }
  145404. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  145405. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  145406. sqlite3_step(pStmt);
  145407. return sqlite3_finalize(pStmt);
  145408. }
  145409. static
  145410. int queryTokenizer(
  145411. sqlite3 *db,
  145412. char *zName,
  145413. const sqlite3_tokenizer_module **pp
  145414. ){
  145415. int rc;
  145416. sqlite3_stmt *pStmt;
  145417. const char zSql[] = "SELECT fts3_tokenizer(?)";
  145418. *pp = 0;
  145419. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  145420. if( rc!=SQLITE_OK ){
  145421. return rc;
  145422. }
  145423. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  145424. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  145425. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  145426. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  145427. }
  145428. }
  145429. return sqlite3_finalize(pStmt);
  145430. }
  145431. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  145432. /*
  145433. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  145434. ** This function is used for testing only, it is not included in the
  145435. ** build unless SQLITE_TEST is defined.
  145436. **
  145437. ** The purpose of this is to test that the fts3_tokenizer() function
  145438. ** can be used as designed by the C-code in the queryTokenizer and
  145439. ** registerTokenizer() functions above. These two functions are repeated
  145440. ** in the README.tokenizer file as an example, so it is important to
  145441. ** test them.
  145442. **
  145443. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  145444. ** function with no arguments. An assert() will fail if a problem is
  145445. ** detected. i.e.:
  145446. **
  145447. ** SELECT fts3_tokenizer_internal_test();
  145448. **
  145449. */
  145450. static void intTestFunc(
  145451. sqlite3_context *context,
  145452. int argc,
  145453. sqlite3_value **argv
  145454. ){
  145455. int rc;
  145456. const sqlite3_tokenizer_module *p1;
  145457. const sqlite3_tokenizer_module *p2;
  145458. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  145459. UNUSED_PARAMETER(argc);
  145460. UNUSED_PARAMETER(argv);
  145461. /* Test the query function */
  145462. sqlite3Fts3SimpleTokenizerModule(&p1);
  145463. rc = queryTokenizer(db, "simple", &p2);
  145464. assert( rc==SQLITE_OK );
  145465. assert( p1==p2 );
  145466. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  145467. assert( rc==SQLITE_ERROR );
  145468. assert( p2==0 );
  145469. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  145470. /* Test the storage function */
  145471. if( fts3TokenizerEnabled(context) ){
  145472. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  145473. assert( rc==SQLITE_OK );
  145474. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  145475. assert( rc==SQLITE_OK );
  145476. assert( p2==p1 );
  145477. }
  145478. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  145479. }
  145480. #endif
  145481. /*
  145482. ** Set up SQL objects in database db used to access the contents of
  145483. ** the hash table pointed to by argument pHash. The hash table must
  145484. ** been initialized to use string keys, and to take a private copy
  145485. ** of the key when a value is inserted. i.e. by a call similar to:
  145486. **
  145487. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  145488. **
  145489. ** This function adds a scalar function (see header comment above
  145490. ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
  145491. ** defined at compilation time, a temporary virtual table (see header
  145492. ** comment above struct HashTableVtab) to the database schema. Both
  145493. ** provide read/write access to the contents of *pHash.
  145494. **
  145495. ** The third argument to this function, zName, is used as the name
  145496. ** of both the scalar and, if created, the virtual table.
  145497. */
  145498. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  145499. sqlite3 *db,
  145500. Fts3Hash *pHash,
  145501. const char *zName
  145502. ){
  145503. int rc = SQLITE_OK;
  145504. void *p = (void *)pHash;
  145505. const int any = SQLITE_ANY;
  145506. #ifdef SQLITE_TEST
  145507. char *zTest = 0;
  145508. char *zTest2 = 0;
  145509. void *pdb = (void *)db;
  145510. zTest = sqlite3_mprintf("%s_test", zName);
  145511. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  145512. if( !zTest || !zTest2 ){
  145513. rc = SQLITE_NOMEM;
  145514. }
  145515. #endif
  145516. if( SQLITE_OK==rc ){
  145517. rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
  145518. }
  145519. if( SQLITE_OK==rc ){
  145520. rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
  145521. }
  145522. #ifdef SQLITE_TEST
  145523. if( SQLITE_OK==rc ){
  145524. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  145525. }
  145526. if( SQLITE_OK==rc ){
  145527. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  145528. }
  145529. #endif
  145530. #ifdef SQLITE_TEST
  145531. sqlite3_free(zTest);
  145532. sqlite3_free(zTest2);
  145533. #endif
  145534. return rc;
  145535. }
  145536. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  145537. /************** End of fts3_tokenizer.c **************************************/
  145538. /************** Begin file fts3_tokenizer1.c *********************************/
  145539. /*
  145540. ** 2006 Oct 10
  145541. **
  145542. ** The author disclaims copyright to this source code. In place of
  145543. ** a legal notice, here is a blessing:
  145544. **
  145545. ** May you do good and not evil.
  145546. ** May you find forgiveness for yourself and forgive others.
  145547. ** May you share freely, never taking more than you give.
  145548. **
  145549. ******************************************************************************
  145550. **
  145551. ** Implementation of the "simple" full-text-search tokenizer.
  145552. */
  145553. /*
  145554. ** The code in this file is only compiled if:
  145555. **
  145556. ** * The FTS3 module is being built as an extension
  145557. ** (in which case SQLITE_CORE is not defined), or
  145558. **
  145559. ** * The FTS3 module is being built into the core of
  145560. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  145561. */
  145562. /* #include "fts3Int.h" */
  145563. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  145564. /* #include <assert.h> */
  145565. /* #include <stdlib.h> */
  145566. /* #include <stdio.h> */
  145567. /* #include <string.h> */
  145568. /* #include "fts3_tokenizer.h" */
  145569. typedef struct simple_tokenizer {
  145570. sqlite3_tokenizer base;
  145571. char delim[128]; /* flag ASCII delimiters */
  145572. } simple_tokenizer;
  145573. typedef struct simple_tokenizer_cursor {
  145574. sqlite3_tokenizer_cursor base;
  145575. const char *pInput; /* input we are tokenizing */
  145576. int nBytes; /* size of the input */
  145577. int iOffset; /* current position in pInput */
  145578. int iToken; /* index of next token to be returned */
  145579. char *pToken; /* storage for current token */
  145580. int nTokenAllocated; /* space allocated to zToken buffer */
  145581. } simple_tokenizer_cursor;
  145582. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  145583. return c<0x80 && t->delim[c];
  145584. }
  145585. static int fts3_isalnum(int x){
  145586. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  145587. }
  145588. /*
  145589. ** Create a new tokenizer instance.
  145590. */
  145591. static int simpleCreate(
  145592. int argc, const char * const *argv,
  145593. sqlite3_tokenizer **ppTokenizer
  145594. ){
  145595. simple_tokenizer *t;
  145596. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  145597. if( t==NULL ) return SQLITE_NOMEM;
  145598. memset(t, 0, sizeof(*t));
  145599. /* TODO(shess) Delimiters need to remain the same from run to run,
  145600. ** else we need to reindex. One solution would be a meta-table to
  145601. ** track such information in the database, then we'd only want this
  145602. ** information on the initial create.
  145603. */
  145604. if( argc>1 ){
  145605. int i, n = (int)strlen(argv[1]);
  145606. for(i=0; i<n; i++){
  145607. unsigned char ch = argv[1][i];
  145608. /* We explicitly don't support UTF-8 delimiters for now. */
  145609. if( ch>=0x80 ){
  145610. sqlite3_free(t);
  145611. return SQLITE_ERROR;
  145612. }
  145613. t->delim[ch] = 1;
  145614. }
  145615. } else {
  145616. /* Mark non-alphanumeric ASCII characters as delimiters */
  145617. int i;
  145618. for(i=1; i<0x80; i++){
  145619. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  145620. }
  145621. }
  145622. *ppTokenizer = &t->base;
  145623. return SQLITE_OK;
  145624. }
  145625. /*
  145626. ** Destroy a tokenizer
  145627. */
  145628. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  145629. sqlite3_free(pTokenizer);
  145630. return SQLITE_OK;
  145631. }
  145632. /*
  145633. ** Prepare to begin tokenizing a particular string. The input
  145634. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  145635. ** used to incrementally tokenize this string is returned in
  145636. ** *ppCursor.
  145637. */
  145638. static int simpleOpen(
  145639. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  145640. const char *pInput, int nBytes, /* String to be tokenized */
  145641. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  145642. ){
  145643. simple_tokenizer_cursor *c;
  145644. UNUSED_PARAMETER(pTokenizer);
  145645. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  145646. if( c==NULL ) return SQLITE_NOMEM;
  145647. c->pInput = pInput;
  145648. if( pInput==0 ){
  145649. c->nBytes = 0;
  145650. }else if( nBytes<0 ){
  145651. c->nBytes = (int)strlen(pInput);
  145652. }else{
  145653. c->nBytes = nBytes;
  145654. }
  145655. c->iOffset = 0; /* start tokenizing at the beginning */
  145656. c->iToken = 0;
  145657. c->pToken = NULL; /* no space allocated, yet. */
  145658. c->nTokenAllocated = 0;
  145659. *ppCursor = &c->base;
  145660. return SQLITE_OK;
  145661. }
  145662. /*
  145663. ** Close a tokenization cursor previously opened by a call to
  145664. ** simpleOpen() above.
  145665. */
  145666. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  145667. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  145668. sqlite3_free(c->pToken);
  145669. sqlite3_free(c);
  145670. return SQLITE_OK;
  145671. }
  145672. /*
  145673. ** Extract the next token from a tokenization cursor. The cursor must
  145674. ** have been opened by a prior call to simpleOpen().
  145675. */
  145676. static int simpleNext(
  145677. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  145678. const char **ppToken, /* OUT: *ppToken is the token text */
  145679. int *pnBytes, /* OUT: Number of bytes in token */
  145680. int *piStartOffset, /* OUT: Starting offset of token */
  145681. int *piEndOffset, /* OUT: Ending offset of token */
  145682. int *piPosition /* OUT: Position integer of token */
  145683. ){
  145684. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  145685. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  145686. unsigned char *p = (unsigned char *)c->pInput;
  145687. while( c->iOffset<c->nBytes ){
  145688. int iStartOffset;
  145689. /* Scan past delimiter characters */
  145690. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  145691. c->iOffset++;
  145692. }
  145693. /* Count non-delimiter characters. */
  145694. iStartOffset = c->iOffset;
  145695. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  145696. c->iOffset++;
  145697. }
  145698. if( c->iOffset>iStartOffset ){
  145699. int i, n = c->iOffset-iStartOffset;
  145700. if( n>c->nTokenAllocated ){
  145701. char *pNew;
  145702. c->nTokenAllocated = n+20;
  145703. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  145704. if( !pNew ) return SQLITE_NOMEM;
  145705. c->pToken = pNew;
  145706. }
  145707. for(i=0; i<n; i++){
  145708. /* TODO(shess) This needs expansion to handle UTF-8
  145709. ** case-insensitivity.
  145710. */
  145711. unsigned char ch = p[iStartOffset+i];
  145712. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  145713. }
  145714. *ppToken = c->pToken;
  145715. *pnBytes = n;
  145716. *piStartOffset = iStartOffset;
  145717. *piEndOffset = c->iOffset;
  145718. *piPosition = c->iToken++;
  145719. return SQLITE_OK;
  145720. }
  145721. }
  145722. return SQLITE_DONE;
  145723. }
  145724. /*
  145725. ** The set of routines that implement the simple tokenizer
  145726. */
  145727. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  145728. 0,
  145729. simpleCreate,
  145730. simpleDestroy,
  145731. simpleOpen,
  145732. simpleClose,
  145733. simpleNext,
  145734. 0,
  145735. };
  145736. /*
  145737. ** Allocate a new simple tokenizer. Return a pointer to the new
  145738. ** tokenizer in *ppModule
  145739. */
  145740. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  145741. sqlite3_tokenizer_module const**ppModule
  145742. ){
  145743. *ppModule = &simpleTokenizerModule;
  145744. }
  145745. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  145746. /************** End of fts3_tokenizer1.c *************************************/
  145747. /************** Begin file fts3_tokenize_vtab.c ******************************/
  145748. /*
  145749. ** 2013 Apr 22
  145750. **
  145751. ** The author disclaims copyright to this source code. In place of
  145752. ** a legal notice, here is a blessing:
  145753. **
  145754. ** May you do good and not evil.
  145755. ** May you find forgiveness for yourself and forgive others.
  145756. ** May you share freely, never taking more than you give.
  145757. **
  145758. ******************************************************************************
  145759. **
  145760. ** This file contains code for the "fts3tokenize" virtual table module.
  145761. ** An fts3tokenize virtual table is created as follows:
  145762. **
  145763. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  145764. ** <tokenizer-name>, <arg-1>, ...
  145765. ** );
  145766. **
  145767. ** The table created has the following schema:
  145768. **
  145769. ** CREATE TABLE <tbl>(input, token, start, end, position)
  145770. **
  145771. ** When queried, the query must include a WHERE clause of type:
  145772. **
  145773. ** input = <string>
  145774. **
  145775. ** The virtual table module tokenizes this <string>, using the FTS3
  145776. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  145777. ** statement and returns one row for each token in the result. With
  145778. ** fields set as follows:
  145779. **
  145780. ** input: Always set to a copy of <string>
  145781. ** token: A token from the input.
  145782. ** start: Byte offset of the token within the input <string>.
  145783. ** end: Byte offset of the byte immediately following the end of the
  145784. ** token within the input string.
  145785. ** pos: Token offset of token within input.
  145786. **
  145787. */
  145788. /* #include "fts3Int.h" */
  145789. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  145790. /* #include <string.h> */
  145791. /* #include <assert.h> */
  145792. typedef struct Fts3tokTable Fts3tokTable;
  145793. typedef struct Fts3tokCursor Fts3tokCursor;
  145794. /*
  145795. ** Virtual table structure.
  145796. */
  145797. struct Fts3tokTable {
  145798. sqlite3_vtab base; /* Base class used by SQLite core */
  145799. const sqlite3_tokenizer_module *pMod;
  145800. sqlite3_tokenizer *pTok;
  145801. };
  145802. /*
  145803. ** Virtual table cursor structure.
  145804. */
  145805. struct Fts3tokCursor {
  145806. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  145807. char *zInput; /* Input string */
  145808. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  145809. int iRowid; /* Current 'rowid' value */
  145810. const char *zToken; /* Current 'token' value */
  145811. int nToken; /* Size of zToken in bytes */
  145812. int iStart; /* Current 'start' value */
  145813. int iEnd; /* Current 'end' value */
  145814. int iPos; /* Current 'pos' value */
  145815. };
  145816. /*
  145817. ** Query FTS for the tokenizer implementation named zName.
  145818. */
  145819. static int fts3tokQueryTokenizer(
  145820. Fts3Hash *pHash,
  145821. const char *zName,
  145822. const sqlite3_tokenizer_module **pp,
  145823. char **pzErr
  145824. ){
  145825. sqlite3_tokenizer_module *p;
  145826. int nName = (int)strlen(zName);
  145827. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  145828. if( !p ){
  145829. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
  145830. return SQLITE_ERROR;
  145831. }
  145832. *pp = p;
  145833. return SQLITE_OK;
  145834. }
  145835. /*
  145836. ** The second argument, argv[], is an array of pointers to nul-terminated
  145837. ** strings. This function makes a copy of the array and strings into a
  145838. ** single block of memory. It then dequotes any of the strings that appear
  145839. ** to be quoted.
  145840. **
  145841. ** If successful, output parameter *pazDequote is set to point at the
  145842. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  145843. ** responsible for eventually calling sqlite3_free() to free the array
  145844. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  145845. ** The final value of *pazDequote is undefined in this case.
  145846. */
  145847. static int fts3tokDequoteArray(
  145848. int argc, /* Number of elements in argv[] */
  145849. const char * const *argv, /* Input array */
  145850. char ***pazDequote /* Output array */
  145851. ){
  145852. int rc = SQLITE_OK; /* Return code */
  145853. if( argc==0 ){
  145854. *pazDequote = 0;
  145855. }else{
  145856. int i;
  145857. int nByte = 0;
  145858. char **azDequote;
  145859. for(i=0; i<argc; i++){
  145860. nByte += (int)(strlen(argv[i]) + 1);
  145861. }
  145862. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  145863. if( azDequote==0 ){
  145864. rc = SQLITE_NOMEM;
  145865. }else{
  145866. char *pSpace = (char *)&azDequote[argc];
  145867. for(i=0; i<argc; i++){
  145868. int n = (int)strlen(argv[i]);
  145869. azDequote[i] = pSpace;
  145870. memcpy(pSpace, argv[i], n+1);
  145871. sqlite3Fts3Dequote(pSpace);
  145872. pSpace += (n+1);
  145873. }
  145874. }
  145875. }
  145876. return rc;
  145877. }
  145878. /*
  145879. ** Schema of the tokenizer table.
  145880. */
  145881. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  145882. /*
  145883. ** This function does all the work for both the xConnect and xCreate methods.
  145884. ** These tables have no persistent representation of their own, so xConnect
  145885. ** and xCreate are identical operations.
  145886. **
  145887. ** argv[0]: module name
  145888. ** argv[1]: database name
  145889. ** argv[2]: table name
  145890. ** argv[3]: first argument (tokenizer name)
  145891. */
  145892. static int fts3tokConnectMethod(
  145893. sqlite3 *db, /* Database connection */
  145894. void *pHash, /* Hash table of tokenizers */
  145895. int argc, /* Number of elements in argv array */
  145896. const char * const *argv, /* xCreate/xConnect argument array */
  145897. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  145898. char **pzErr /* OUT: sqlite3_malloc'd error message */
  145899. ){
  145900. Fts3tokTable *pTab = 0;
  145901. const sqlite3_tokenizer_module *pMod = 0;
  145902. sqlite3_tokenizer *pTok = 0;
  145903. int rc;
  145904. char **azDequote = 0;
  145905. int nDequote;
  145906. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  145907. if( rc!=SQLITE_OK ) return rc;
  145908. nDequote = argc-3;
  145909. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  145910. if( rc==SQLITE_OK ){
  145911. const char *zModule;
  145912. if( nDequote<1 ){
  145913. zModule = "simple";
  145914. }else{
  145915. zModule = azDequote[0];
  145916. }
  145917. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  145918. }
  145919. assert( (rc==SQLITE_OK)==(pMod!=0) );
  145920. if( rc==SQLITE_OK ){
  145921. const char * const *azArg = (const char * const *)&azDequote[1];
  145922. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  145923. }
  145924. if( rc==SQLITE_OK ){
  145925. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  145926. if( pTab==0 ){
  145927. rc = SQLITE_NOMEM;
  145928. }
  145929. }
  145930. if( rc==SQLITE_OK ){
  145931. memset(pTab, 0, sizeof(Fts3tokTable));
  145932. pTab->pMod = pMod;
  145933. pTab->pTok = pTok;
  145934. *ppVtab = &pTab->base;
  145935. }else{
  145936. if( pTok ){
  145937. pMod->xDestroy(pTok);
  145938. }
  145939. }
  145940. sqlite3_free(azDequote);
  145941. return rc;
  145942. }
  145943. /*
  145944. ** This function does the work for both the xDisconnect and xDestroy methods.
  145945. ** These tables have no persistent representation of their own, so xDisconnect
  145946. ** and xDestroy are identical operations.
  145947. */
  145948. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  145949. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  145950. pTab->pMod->xDestroy(pTab->pTok);
  145951. sqlite3_free(pTab);
  145952. return SQLITE_OK;
  145953. }
  145954. /*
  145955. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  145956. */
  145957. static int fts3tokBestIndexMethod(
  145958. sqlite3_vtab *pVTab,
  145959. sqlite3_index_info *pInfo
  145960. ){
  145961. int i;
  145962. UNUSED_PARAMETER(pVTab);
  145963. for(i=0; i<pInfo->nConstraint; i++){
  145964. if( pInfo->aConstraint[i].usable
  145965. && pInfo->aConstraint[i].iColumn==0
  145966. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  145967. ){
  145968. pInfo->idxNum = 1;
  145969. pInfo->aConstraintUsage[i].argvIndex = 1;
  145970. pInfo->aConstraintUsage[i].omit = 1;
  145971. pInfo->estimatedCost = 1;
  145972. return SQLITE_OK;
  145973. }
  145974. }
  145975. pInfo->idxNum = 0;
  145976. assert( pInfo->estimatedCost>1000000.0 );
  145977. return SQLITE_OK;
  145978. }
  145979. /*
  145980. ** xOpen - Open a cursor.
  145981. */
  145982. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  145983. Fts3tokCursor *pCsr;
  145984. UNUSED_PARAMETER(pVTab);
  145985. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  145986. if( pCsr==0 ){
  145987. return SQLITE_NOMEM;
  145988. }
  145989. memset(pCsr, 0, sizeof(Fts3tokCursor));
  145990. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  145991. return SQLITE_OK;
  145992. }
  145993. /*
  145994. ** Reset the tokenizer cursor passed as the only argument. As if it had
  145995. ** just been returned by fts3tokOpenMethod().
  145996. */
  145997. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  145998. if( pCsr->pCsr ){
  145999. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  146000. pTab->pMod->xClose(pCsr->pCsr);
  146001. pCsr->pCsr = 0;
  146002. }
  146003. sqlite3_free(pCsr->zInput);
  146004. pCsr->zInput = 0;
  146005. pCsr->zToken = 0;
  146006. pCsr->nToken = 0;
  146007. pCsr->iStart = 0;
  146008. pCsr->iEnd = 0;
  146009. pCsr->iPos = 0;
  146010. pCsr->iRowid = 0;
  146011. }
  146012. /*
  146013. ** xClose - Close a cursor.
  146014. */
  146015. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  146016. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  146017. fts3tokResetCursor(pCsr);
  146018. sqlite3_free(pCsr);
  146019. return SQLITE_OK;
  146020. }
  146021. /*
  146022. ** xNext - Advance the cursor to the next row, if any.
  146023. */
  146024. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  146025. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  146026. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  146027. int rc; /* Return code */
  146028. pCsr->iRowid++;
  146029. rc = pTab->pMod->xNext(pCsr->pCsr,
  146030. &pCsr->zToken, &pCsr->nToken,
  146031. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  146032. );
  146033. if( rc!=SQLITE_OK ){
  146034. fts3tokResetCursor(pCsr);
  146035. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  146036. }
  146037. return rc;
  146038. }
  146039. /*
  146040. ** xFilter - Initialize a cursor to point at the start of its data.
  146041. */
  146042. static int fts3tokFilterMethod(
  146043. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  146044. int idxNum, /* Strategy index */
  146045. const char *idxStr, /* Unused */
  146046. int nVal, /* Number of elements in apVal */
  146047. sqlite3_value **apVal /* Arguments for the indexing scheme */
  146048. ){
  146049. int rc = SQLITE_ERROR;
  146050. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  146051. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  146052. UNUSED_PARAMETER(idxStr);
  146053. UNUSED_PARAMETER(nVal);
  146054. fts3tokResetCursor(pCsr);
  146055. if( idxNum==1 ){
  146056. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  146057. int nByte = sqlite3_value_bytes(apVal[0]);
  146058. pCsr->zInput = sqlite3_malloc(nByte+1);
  146059. if( pCsr->zInput==0 ){
  146060. rc = SQLITE_NOMEM;
  146061. }else{
  146062. memcpy(pCsr->zInput, zByte, nByte);
  146063. pCsr->zInput[nByte] = 0;
  146064. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  146065. if( rc==SQLITE_OK ){
  146066. pCsr->pCsr->pTokenizer = pTab->pTok;
  146067. }
  146068. }
  146069. }
  146070. if( rc!=SQLITE_OK ) return rc;
  146071. return fts3tokNextMethod(pCursor);
  146072. }
  146073. /*
  146074. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  146075. */
  146076. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  146077. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  146078. return (pCsr->zToken==0);
  146079. }
  146080. /*
  146081. ** xColumn - Return a column value.
  146082. */
  146083. static int fts3tokColumnMethod(
  146084. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  146085. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  146086. int iCol /* Index of column to read value from */
  146087. ){
  146088. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  146089. /* CREATE TABLE x(input, token, start, end, position) */
  146090. switch( iCol ){
  146091. case 0:
  146092. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  146093. break;
  146094. case 1:
  146095. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  146096. break;
  146097. case 2:
  146098. sqlite3_result_int(pCtx, pCsr->iStart);
  146099. break;
  146100. case 3:
  146101. sqlite3_result_int(pCtx, pCsr->iEnd);
  146102. break;
  146103. default:
  146104. assert( iCol==4 );
  146105. sqlite3_result_int(pCtx, pCsr->iPos);
  146106. break;
  146107. }
  146108. return SQLITE_OK;
  146109. }
  146110. /*
  146111. ** xRowid - Return the current rowid for the cursor.
  146112. */
  146113. static int fts3tokRowidMethod(
  146114. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  146115. sqlite_int64 *pRowid /* OUT: Rowid value */
  146116. ){
  146117. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  146118. *pRowid = (sqlite3_int64)pCsr->iRowid;
  146119. return SQLITE_OK;
  146120. }
  146121. /*
  146122. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  146123. ** if successful or an error code if sqlite3_create_module() fails.
  146124. */
  146125. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  146126. static const sqlite3_module fts3tok_module = {
  146127. 0, /* iVersion */
  146128. fts3tokConnectMethod, /* xCreate */
  146129. fts3tokConnectMethod, /* xConnect */
  146130. fts3tokBestIndexMethod, /* xBestIndex */
  146131. fts3tokDisconnectMethod, /* xDisconnect */
  146132. fts3tokDisconnectMethod, /* xDestroy */
  146133. fts3tokOpenMethod, /* xOpen */
  146134. fts3tokCloseMethod, /* xClose */
  146135. fts3tokFilterMethod, /* xFilter */
  146136. fts3tokNextMethod, /* xNext */
  146137. fts3tokEofMethod, /* xEof */
  146138. fts3tokColumnMethod, /* xColumn */
  146139. fts3tokRowidMethod, /* xRowid */
  146140. 0, /* xUpdate */
  146141. 0, /* xBegin */
  146142. 0, /* xSync */
  146143. 0, /* xCommit */
  146144. 0, /* xRollback */
  146145. 0, /* xFindFunction */
  146146. 0, /* xRename */
  146147. 0, /* xSavepoint */
  146148. 0, /* xRelease */
  146149. 0 /* xRollbackTo */
  146150. };
  146151. int rc; /* Return code */
  146152. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  146153. return rc;
  146154. }
  146155. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  146156. /************** End of fts3_tokenize_vtab.c **********************************/
  146157. /************** Begin file fts3_write.c **************************************/
  146158. /*
  146159. ** 2009 Oct 23
  146160. **
  146161. ** The author disclaims copyright to this source code. In place of
  146162. ** a legal notice, here is a blessing:
  146163. **
  146164. ** May you do good and not evil.
  146165. ** May you find forgiveness for yourself and forgive others.
  146166. ** May you share freely, never taking more than you give.
  146167. **
  146168. ******************************************************************************
  146169. **
  146170. ** This file is part of the SQLite FTS3 extension module. Specifically,
  146171. ** this file contains code to insert, update and delete rows from FTS3
  146172. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  146173. ** of the sub-routines used to merge segments are also used by the query
  146174. ** code in fts3.c.
  146175. */
  146176. /* #include "fts3Int.h" */
  146177. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  146178. /* #include <string.h> */
  146179. /* #include <assert.h> */
  146180. /* #include <stdlib.h> */
  146181. #define FTS_MAX_APPENDABLE_HEIGHT 16
  146182. /*
  146183. ** When full-text index nodes are loaded from disk, the buffer that they
  146184. ** are loaded into has the following number of bytes of padding at the end
  146185. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  146186. ** of 920 bytes is allocated for it.
  146187. **
  146188. ** This means that if we have a pointer into a buffer containing node data,
  146189. ** it is always safe to read up to two varints from it without risking an
  146190. ** overread, even if the node data is corrupted.
  146191. */
  146192. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  146193. /*
  146194. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  146195. ** memory incrementally instead of all at once. This can be a big performance
  146196. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  146197. ** method before retrieving all query results (as may happen, for example,
  146198. ** if a query has a LIMIT clause).
  146199. **
  146200. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  146201. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  146202. ** The code is written so that the hard lower-limit for each of these values
  146203. ** is 1. Clearly such small values would be inefficient, but can be useful
  146204. ** for testing purposes.
  146205. **
  146206. ** If this module is built with SQLITE_TEST defined, these constants may
  146207. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  146208. ** a Tcl interface to read and write the values.
  146209. */
  146210. #ifdef SQLITE_TEST
  146211. int test_fts3_node_chunksize = (4*1024);
  146212. int test_fts3_node_chunk_threshold = (4*1024)*4;
  146213. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  146214. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  146215. #else
  146216. # define FTS3_NODE_CHUNKSIZE (4*1024)
  146217. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  146218. #endif
  146219. /*
  146220. ** The two values that may be meaningfully bound to the :1 parameter in
  146221. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  146222. */
  146223. #define FTS_STAT_DOCTOTAL 0
  146224. #define FTS_STAT_INCRMERGEHINT 1
  146225. #define FTS_STAT_AUTOINCRMERGE 2
  146226. /*
  146227. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  146228. ** and incremental merge operation that takes place. This is used for
  146229. ** debugging FTS only, it should not usually be turned on in production
  146230. ** systems.
  146231. */
  146232. #ifdef FTS3_LOG_MERGES
  146233. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  146234. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  146235. }
  146236. #else
  146237. #define fts3LogMerge(x, y)
  146238. #endif
  146239. typedef struct PendingList PendingList;
  146240. typedef struct SegmentNode SegmentNode;
  146241. typedef struct SegmentWriter SegmentWriter;
  146242. /*
  146243. ** An instance of the following data structure is used to build doclists
  146244. ** incrementally. See function fts3PendingListAppend() for details.
  146245. */
  146246. struct PendingList {
  146247. int nData;
  146248. char *aData;
  146249. int nSpace;
  146250. sqlite3_int64 iLastDocid;
  146251. sqlite3_int64 iLastCol;
  146252. sqlite3_int64 iLastPos;
  146253. };
  146254. /*
  146255. ** Each cursor has a (possibly empty) linked list of the following objects.
  146256. */
  146257. struct Fts3DeferredToken {
  146258. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  146259. int iCol; /* Column token must occur in */
  146260. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  146261. PendingList *pList; /* Doclist is assembled here */
  146262. };
  146263. /*
  146264. ** An instance of this structure is used to iterate through the terms on
  146265. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  146266. ** this structure are only manipulated by code in this file, opaque handles
  146267. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  146268. ** terms when querying the full-text index. See functions:
  146269. **
  146270. ** sqlite3Fts3SegReaderNew()
  146271. ** sqlite3Fts3SegReaderFree()
  146272. ** sqlite3Fts3SegReaderIterate()
  146273. **
  146274. ** Methods used to manipulate Fts3SegReader structures:
  146275. **
  146276. ** fts3SegReaderNext()
  146277. ** fts3SegReaderFirstDocid()
  146278. ** fts3SegReaderNextDocid()
  146279. */
  146280. struct Fts3SegReader {
  146281. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  146282. u8 bLookup; /* True for a lookup only */
  146283. u8 rootOnly; /* True for a root-only reader */
  146284. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  146285. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  146286. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  146287. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  146288. char *aNode; /* Pointer to node data (or NULL) */
  146289. int nNode; /* Size of buffer at aNode (or 0) */
  146290. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  146291. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  146292. Fts3HashElem **ppNextElem;
  146293. /* Variables set by fts3SegReaderNext(). These may be read directly
  146294. ** by the caller. They are valid from the time SegmentReaderNew() returns
  146295. ** until SegmentReaderNext() returns something other than SQLITE_OK
  146296. ** (i.e. SQLITE_DONE).
  146297. */
  146298. int nTerm; /* Number of bytes in current term */
  146299. char *zTerm; /* Pointer to current term */
  146300. int nTermAlloc; /* Allocated size of zTerm buffer */
  146301. char *aDoclist; /* Pointer to doclist of current entry */
  146302. int nDoclist; /* Size of doclist in current entry */
  146303. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  146304. ** through the current doclist (aDoclist/nDoclist).
  146305. */
  146306. char *pOffsetList;
  146307. int nOffsetList; /* For descending pending seg-readers only */
  146308. sqlite3_int64 iDocid;
  146309. };
  146310. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  146311. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  146312. /*
  146313. ** An instance of this structure is used to create a segment b-tree in the
  146314. ** database. The internal details of this type are only accessed by the
  146315. ** following functions:
  146316. **
  146317. ** fts3SegWriterAdd()
  146318. ** fts3SegWriterFlush()
  146319. ** fts3SegWriterFree()
  146320. */
  146321. struct SegmentWriter {
  146322. SegmentNode *pTree; /* Pointer to interior tree structure */
  146323. sqlite3_int64 iFirst; /* First slot in %_segments written */
  146324. sqlite3_int64 iFree; /* Next free slot in %_segments */
  146325. char *zTerm; /* Pointer to previous term buffer */
  146326. int nTerm; /* Number of bytes in zTerm */
  146327. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  146328. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  146329. int nSize; /* Size of allocation at aData */
  146330. int nData; /* Bytes of data in aData */
  146331. char *aData; /* Pointer to block from malloc() */
  146332. i64 nLeafData; /* Number of bytes of leaf data written */
  146333. };
  146334. /*
  146335. ** Type SegmentNode is used by the following three functions to create
  146336. ** the interior part of the segment b+-tree structures (everything except
  146337. ** the leaf nodes). These functions and type are only ever used by code
  146338. ** within the fts3SegWriterXXX() family of functions described above.
  146339. **
  146340. ** fts3NodeAddTerm()
  146341. ** fts3NodeWrite()
  146342. ** fts3NodeFree()
  146343. **
  146344. ** When a b+tree is written to the database (either as a result of a merge
  146345. ** or the pending-terms table being flushed), leaves are written into the
  146346. ** database file as soon as they are completely populated. The interior of
  146347. ** the tree is assembled in memory and written out only once all leaves have
  146348. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  146349. ** very large, meaning that the interior of the tree consumes relatively
  146350. ** little memory.
  146351. */
  146352. struct SegmentNode {
  146353. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  146354. SegmentNode *pRight; /* Pointer to right-sibling */
  146355. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  146356. int nEntry; /* Number of terms written to node so far */
  146357. char *zTerm; /* Pointer to previous term buffer */
  146358. int nTerm; /* Number of bytes in zTerm */
  146359. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  146360. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  146361. int nData; /* Bytes of valid data so far */
  146362. char *aData; /* Node data */
  146363. };
  146364. /*
  146365. ** Valid values for the second argument to fts3SqlStmt().
  146366. */
  146367. #define SQL_DELETE_CONTENT 0
  146368. #define SQL_IS_EMPTY 1
  146369. #define SQL_DELETE_ALL_CONTENT 2
  146370. #define SQL_DELETE_ALL_SEGMENTS 3
  146371. #define SQL_DELETE_ALL_SEGDIR 4
  146372. #define SQL_DELETE_ALL_DOCSIZE 5
  146373. #define SQL_DELETE_ALL_STAT 6
  146374. #define SQL_SELECT_CONTENT_BY_ROWID 7
  146375. #define SQL_NEXT_SEGMENT_INDEX 8
  146376. #define SQL_INSERT_SEGMENTS 9
  146377. #define SQL_NEXT_SEGMENTS_ID 10
  146378. #define SQL_INSERT_SEGDIR 11
  146379. #define SQL_SELECT_LEVEL 12
  146380. #define SQL_SELECT_LEVEL_RANGE 13
  146381. #define SQL_SELECT_LEVEL_COUNT 14
  146382. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  146383. #define SQL_DELETE_SEGDIR_LEVEL 16
  146384. #define SQL_DELETE_SEGMENTS_RANGE 17
  146385. #define SQL_CONTENT_INSERT 18
  146386. #define SQL_DELETE_DOCSIZE 19
  146387. #define SQL_REPLACE_DOCSIZE 20
  146388. #define SQL_SELECT_DOCSIZE 21
  146389. #define SQL_SELECT_STAT 22
  146390. #define SQL_REPLACE_STAT 23
  146391. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  146392. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  146393. #define SQL_DELETE_SEGDIR_RANGE 26
  146394. #define SQL_SELECT_ALL_LANGID 27
  146395. #define SQL_FIND_MERGE_LEVEL 28
  146396. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  146397. #define SQL_DELETE_SEGDIR_ENTRY 30
  146398. #define SQL_SHIFT_SEGDIR_ENTRY 31
  146399. #define SQL_SELECT_SEGDIR 32
  146400. #define SQL_CHOMP_SEGDIR 33
  146401. #define SQL_SEGMENT_IS_APPENDABLE 34
  146402. #define SQL_SELECT_INDEXES 35
  146403. #define SQL_SELECT_MXLEVEL 36
  146404. #define SQL_SELECT_LEVEL_RANGE2 37
  146405. #define SQL_UPDATE_LEVEL_IDX 38
  146406. #define SQL_UPDATE_LEVEL 39
  146407. /*
  146408. ** This function is used to obtain an SQLite prepared statement handle
  146409. ** for the statement identified by the second argument. If successful,
  146410. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  146411. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  146412. **
  146413. ** If argument apVal is not NULL, then it must point to an array with
  146414. ** at least as many entries as the requested statement has bound
  146415. ** parameters. The values are bound to the statements parameters before
  146416. ** returning.
  146417. */
  146418. static int fts3SqlStmt(
  146419. Fts3Table *p, /* Virtual table handle */
  146420. int eStmt, /* One of the SQL_XXX constants above */
  146421. sqlite3_stmt **pp, /* OUT: Statement handle */
  146422. sqlite3_value **apVal /* Values to bind to statement */
  146423. ){
  146424. const char *azSql[] = {
  146425. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  146426. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  146427. /* 2 */ "DELETE FROM %Q.'%q_content'",
  146428. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  146429. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  146430. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  146431. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  146432. /* 7 */ "SELECT %s WHERE rowid=?",
  146433. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  146434. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  146435. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  146436. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  146437. /* Return segments in order from oldest to newest.*/
  146438. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  146439. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  146440. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  146441. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  146442. "ORDER BY level DESC, idx ASC",
  146443. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  146444. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  146445. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  146446. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  146447. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  146448. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  146449. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  146450. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  146451. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  146452. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  146453. /* 24 */ "",
  146454. /* 25 */ "",
  146455. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  146456. /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
  146457. /* This statement is used to determine which level to read the input from
  146458. ** when performing an incremental merge. It returns the absolute level number
  146459. ** of the oldest level in the db that contains at least ? segments. Or,
  146460. ** if no level in the FTS index contains more than ? segments, the statement
  146461. ** returns zero rows. */
  146462. /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
  146463. " GROUP BY level HAVING cnt>=?"
  146464. " ORDER BY (level %% 1024) ASC LIMIT 1",
  146465. /* Estimate the upper limit on the number of leaf nodes in a new segment
  146466. ** created by merging the oldest :2 segments from absolute level :1. See
  146467. ** function sqlite3Fts3Incrmerge() for details. */
  146468. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  146469. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  146470. /* SQL_DELETE_SEGDIR_ENTRY
  146471. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  146472. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  146473. /* SQL_SHIFT_SEGDIR_ENTRY
  146474. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  146475. ** to :1. */
  146476. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  146477. /* SQL_SELECT_SEGDIR
  146478. ** Read a single entry from the %_segdir table. The entry from absolute
  146479. ** level :1 with index value :2. */
  146480. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  146481. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  146482. /* SQL_CHOMP_SEGDIR
  146483. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  146484. ** entry located on absolute level :3 with index :4. */
  146485. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  146486. "WHERE level = ? AND idx = ?",
  146487. /* SQL_SEGMENT_IS_APPENDABLE
  146488. ** Return a single row if the segment with end_block=? is appendable. Or
  146489. ** no rows otherwise. */
  146490. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  146491. /* SQL_SELECT_INDEXES
  146492. ** Return the list of valid segment indexes for absolute level ? */
  146493. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  146494. /* SQL_SELECT_MXLEVEL
  146495. ** Return the largest relative level in the FTS index or indexes. */
  146496. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
  146497. /* Return segments in order from oldest to newest.*/
  146498. /* 37 */ "SELECT level, idx, end_block "
  146499. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
  146500. "ORDER BY level DESC, idx ASC",
  146501. /* Update statements used while promoting segments */
  146502. /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
  146503. "WHERE level=? AND idx=?",
  146504. /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
  146505. };
  146506. int rc = SQLITE_OK;
  146507. sqlite3_stmt *pStmt;
  146508. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  146509. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  146510. pStmt = p->aStmt[eStmt];
  146511. if( !pStmt ){
  146512. char *zSql;
  146513. if( eStmt==SQL_CONTENT_INSERT ){
  146514. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  146515. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  146516. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  146517. }else{
  146518. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  146519. }
  146520. if( !zSql ){
  146521. rc = SQLITE_NOMEM;
  146522. }else{
  146523. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
  146524. sqlite3_free(zSql);
  146525. assert( rc==SQLITE_OK || pStmt==0 );
  146526. p->aStmt[eStmt] = pStmt;
  146527. }
  146528. }
  146529. if( apVal ){
  146530. int i;
  146531. int nParam = sqlite3_bind_parameter_count(pStmt);
  146532. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  146533. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  146534. }
  146535. }
  146536. *pp = pStmt;
  146537. return rc;
  146538. }
  146539. static int fts3SelectDocsize(
  146540. Fts3Table *pTab, /* FTS3 table handle */
  146541. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  146542. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  146543. ){
  146544. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  146545. int rc; /* Return code */
  146546. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  146547. if( rc==SQLITE_OK ){
  146548. sqlite3_bind_int64(pStmt, 1, iDocid);
  146549. rc = sqlite3_step(pStmt);
  146550. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  146551. rc = sqlite3_reset(pStmt);
  146552. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  146553. pStmt = 0;
  146554. }else{
  146555. rc = SQLITE_OK;
  146556. }
  146557. }
  146558. *ppStmt = pStmt;
  146559. return rc;
  146560. }
  146561. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  146562. Fts3Table *pTab, /* Fts3 table handle */
  146563. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  146564. ){
  146565. sqlite3_stmt *pStmt = 0;
  146566. int rc;
  146567. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  146568. if( rc==SQLITE_OK ){
  146569. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  146570. if( sqlite3_step(pStmt)!=SQLITE_ROW
  146571. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  146572. ){
  146573. rc = sqlite3_reset(pStmt);
  146574. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  146575. pStmt = 0;
  146576. }
  146577. }
  146578. *ppStmt = pStmt;
  146579. return rc;
  146580. }
  146581. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  146582. Fts3Table *pTab, /* Fts3 table handle */
  146583. sqlite3_int64 iDocid, /* Docid to read size data for */
  146584. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  146585. ){
  146586. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  146587. }
  146588. /*
  146589. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  146590. ** array apVal[] to the SQL statement identified by eStmt, the statement
  146591. ** is executed.
  146592. **
  146593. ** Returns SQLITE_OK if the statement is successfully executed, or an
  146594. ** SQLite error code otherwise.
  146595. */
  146596. static void fts3SqlExec(
  146597. int *pRC, /* Result code */
  146598. Fts3Table *p, /* The FTS3 table */
  146599. int eStmt, /* Index of statement to evaluate */
  146600. sqlite3_value **apVal /* Parameters to bind */
  146601. ){
  146602. sqlite3_stmt *pStmt;
  146603. int rc;
  146604. if( *pRC ) return;
  146605. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  146606. if( rc==SQLITE_OK ){
  146607. sqlite3_step(pStmt);
  146608. rc = sqlite3_reset(pStmt);
  146609. }
  146610. *pRC = rc;
  146611. }
  146612. /*
  146613. ** This function ensures that the caller has obtained an exclusive
  146614. ** shared-cache table-lock on the %_segdir table. This is required before
  146615. ** writing data to the fts3 table. If this lock is not acquired first, then
  146616. ** the caller may end up attempting to take this lock as part of committing
  146617. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  146618. ** LOCKED_SHAREDCACHEto a COMMIT command.
  146619. **
  146620. ** It is best to avoid this because if FTS3 returns any error when
  146621. ** committing a transaction, the whole transaction will be rolled back.
  146622. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  146623. ** It can still happen if the user locks the underlying tables directly
  146624. ** instead of accessing them via FTS.
  146625. */
  146626. static int fts3Writelock(Fts3Table *p){
  146627. int rc = SQLITE_OK;
  146628. if( p->nPendingData==0 ){
  146629. sqlite3_stmt *pStmt;
  146630. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  146631. if( rc==SQLITE_OK ){
  146632. sqlite3_bind_null(pStmt, 1);
  146633. sqlite3_step(pStmt);
  146634. rc = sqlite3_reset(pStmt);
  146635. }
  146636. }
  146637. return rc;
  146638. }
  146639. /*
  146640. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  146641. ** Within each language id, a separate index is maintained to store the
  146642. ** document terms, and each configured prefix size (configured the FTS
  146643. ** "prefix=" option). And each index consists of multiple levels ("relative
  146644. ** levels").
  146645. **
  146646. ** All three of these values (the language id, the specific index and the
  146647. ** level within the index) are encoded in 64-bit integer values stored
  146648. ** in the %_segdir table on disk. This function is used to convert three
  146649. ** separate component values into the single 64-bit integer value that
  146650. ** can be used to query the %_segdir table.
  146651. **
  146652. ** Specifically, each language-id/index combination is allocated 1024
  146653. ** 64-bit integer level values ("absolute levels"). The main terms index
  146654. ** for language-id 0 is allocate values 0-1023. The first prefix index
  146655. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  146656. ** Language 1 indexes are allocated immediately following language 0.
  146657. **
  146658. ** So, for a system with nPrefix prefix indexes configured, the block of
  146659. ** absolute levels that corresponds to language-id iLangid and index
  146660. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  146661. */
  146662. static sqlite3_int64 getAbsoluteLevel(
  146663. Fts3Table *p, /* FTS3 table handle */
  146664. int iLangid, /* Language id */
  146665. int iIndex, /* Index in p->aIndex[] */
  146666. int iLevel /* Level of segments */
  146667. ){
  146668. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  146669. assert( iLangid>=0 );
  146670. assert( p->nIndex>0 );
  146671. assert( iIndex>=0 && iIndex<p->nIndex );
  146672. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  146673. return iBase + iLevel;
  146674. }
  146675. /*
  146676. ** Set *ppStmt to a statement handle that may be used to iterate through
  146677. ** all rows in the %_segdir table, from oldest to newest. If successful,
  146678. ** return SQLITE_OK. If an error occurs while preparing the statement,
  146679. ** return an SQLite error code.
  146680. **
  146681. ** There is only ever one instance of this SQL statement compiled for
  146682. ** each FTS3 table.
  146683. **
  146684. ** The statement returns the following columns from the %_segdir table:
  146685. **
  146686. ** 0: idx
  146687. ** 1: start_block
  146688. ** 2: leaves_end_block
  146689. ** 3: end_block
  146690. ** 4: root
  146691. */
  146692. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  146693. Fts3Table *p, /* FTS3 table */
  146694. int iLangid, /* Language being queried */
  146695. int iIndex, /* Index for p->aIndex[] */
  146696. int iLevel, /* Level to select (relative level) */
  146697. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  146698. ){
  146699. int rc;
  146700. sqlite3_stmt *pStmt = 0;
  146701. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  146702. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  146703. assert( iIndex>=0 && iIndex<p->nIndex );
  146704. if( iLevel<0 ){
  146705. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  146706. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  146707. if( rc==SQLITE_OK ){
  146708. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  146709. sqlite3_bind_int64(pStmt, 2,
  146710. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  146711. );
  146712. }
  146713. }else{
  146714. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  146715. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  146716. if( rc==SQLITE_OK ){
  146717. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  146718. }
  146719. }
  146720. *ppStmt = pStmt;
  146721. return rc;
  146722. }
  146723. /*
  146724. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  146725. ** if successful, or an SQLite error code otherwise.
  146726. **
  146727. ** This function also serves to allocate the PendingList structure itself.
  146728. ** For example, to create a new PendingList structure containing two
  146729. ** varints:
  146730. **
  146731. ** PendingList *p = 0;
  146732. ** fts3PendingListAppendVarint(&p, 1);
  146733. ** fts3PendingListAppendVarint(&p, 2);
  146734. */
  146735. static int fts3PendingListAppendVarint(
  146736. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  146737. sqlite3_int64 i /* Value to append to data */
  146738. ){
  146739. PendingList *p = *pp;
  146740. /* Allocate or grow the PendingList as required. */
  146741. if( !p ){
  146742. p = sqlite3_malloc(sizeof(*p) + 100);
  146743. if( !p ){
  146744. return SQLITE_NOMEM;
  146745. }
  146746. p->nSpace = 100;
  146747. p->aData = (char *)&p[1];
  146748. p->nData = 0;
  146749. }
  146750. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  146751. int nNew = p->nSpace * 2;
  146752. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  146753. if( !p ){
  146754. sqlite3_free(*pp);
  146755. *pp = 0;
  146756. return SQLITE_NOMEM;
  146757. }
  146758. p->nSpace = nNew;
  146759. p->aData = (char *)&p[1];
  146760. }
  146761. /* Append the new serialized varint to the end of the list. */
  146762. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  146763. p->aData[p->nData] = '\0';
  146764. *pp = p;
  146765. return SQLITE_OK;
  146766. }
  146767. /*
  146768. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  146769. ** is returned if the structure is sqlite3_realloced as part of adding
  146770. ** the entry. Otherwise, zero.
  146771. **
  146772. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  146773. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  146774. ** it is set to SQLITE_OK.
  146775. */
  146776. static int fts3PendingListAppend(
  146777. PendingList **pp, /* IN/OUT: PendingList structure */
  146778. sqlite3_int64 iDocid, /* Docid for entry to add */
  146779. sqlite3_int64 iCol, /* Column for entry to add */
  146780. sqlite3_int64 iPos, /* Position of term for entry to add */
  146781. int *pRc /* OUT: Return code */
  146782. ){
  146783. PendingList *p = *pp;
  146784. int rc = SQLITE_OK;
  146785. assert( !p || p->iLastDocid<=iDocid );
  146786. if( !p || p->iLastDocid!=iDocid ){
  146787. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  146788. if( p ){
  146789. assert( p->nData<p->nSpace );
  146790. assert( p->aData[p->nData]==0 );
  146791. p->nData++;
  146792. }
  146793. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  146794. goto pendinglistappend_out;
  146795. }
  146796. p->iLastCol = -1;
  146797. p->iLastPos = 0;
  146798. p->iLastDocid = iDocid;
  146799. }
  146800. if( iCol>0 && p->iLastCol!=iCol ){
  146801. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  146802. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  146803. ){
  146804. goto pendinglistappend_out;
  146805. }
  146806. p->iLastCol = iCol;
  146807. p->iLastPos = 0;
  146808. }
  146809. if( iCol>=0 ){
  146810. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  146811. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  146812. if( rc==SQLITE_OK ){
  146813. p->iLastPos = iPos;
  146814. }
  146815. }
  146816. pendinglistappend_out:
  146817. *pRc = rc;
  146818. if( p!=*pp ){
  146819. *pp = p;
  146820. return 1;
  146821. }
  146822. return 0;
  146823. }
  146824. /*
  146825. ** Free a PendingList object allocated by fts3PendingListAppend().
  146826. */
  146827. static void fts3PendingListDelete(PendingList *pList){
  146828. sqlite3_free(pList);
  146829. }
  146830. /*
  146831. ** Add an entry to one of the pending-terms hash tables.
  146832. */
  146833. static int fts3PendingTermsAddOne(
  146834. Fts3Table *p,
  146835. int iCol,
  146836. int iPos,
  146837. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  146838. const char *zToken,
  146839. int nToken
  146840. ){
  146841. PendingList *pList;
  146842. int rc = SQLITE_OK;
  146843. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  146844. if( pList ){
  146845. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  146846. }
  146847. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  146848. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  146849. /* Malloc failed while inserting the new entry. This can only
  146850. ** happen if there was no previous entry for this token.
  146851. */
  146852. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  146853. sqlite3_free(pList);
  146854. rc = SQLITE_NOMEM;
  146855. }
  146856. }
  146857. if( rc==SQLITE_OK ){
  146858. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  146859. }
  146860. return rc;
  146861. }
  146862. /*
  146863. ** Tokenize the nul-terminated string zText and add all tokens to the
  146864. ** pending-terms hash-table. The docid used is that currently stored in
  146865. ** p->iPrevDocid, and the column is specified by argument iCol.
  146866. **
  146867. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  146868. */
  146869. static int fts3PendingTermsAdd(
  146870. Fts3Table *p, /* Table into which text will be inserted */
  146871. int iLangid, /* Language id to use */
  146872. const char *zText, /* Text of document to be inserted */
  146873. int iCol, /* Column into which text is being inserted */
  146874. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  146875. ){
  146876. int rc;
  146877. int iStart = 0;
  146878. int iEnd = 0;
  146879. int iPos = 0;
  146880. int nWord = 0;
  146881. char const *zToken;
  146882. int nToken = 0;
  146883. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  146884. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  146885. sqlite3_tokenizer_cursor *pCsr;
  146886. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  146887. const char**,int*,int*,int*,int*);
  146888. assert( pTokenizer && pModule );
  146889. /* If the user has inserted a NULL value, this function may be called with
  146890. ** zText==0. In this case, add zero token entries to the hash table and
  146891. ** return early. */
  146892. if( zText==0 ){
  146893. *pnWord = 0;
  146894. return SQLITE_OK;
  146895. }
  146896. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  146897. if( rc!=SQLITE_OK ){
  146898. return rc;
  146899. }
  146900. xNext = pModule->xNext;
  146901. while( SQLITE_OK==rc
  146902. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  146903. ){
  146904. int i;
  146905. if( iPos>=nWord ) nWord = iPos+1;
  146906. /* Positions cannot be negative; we use -1 as a terminator internally.
  146907. ** Tokens must have a non-zero length.
  146908. */
  146909. if( iPos<0 || !zToken || nToken<=0 ){
  146910. rc = SQLITE_ERROR;
  146911. break;
  146912. }
  146913. /* Add the term to the terms index */
  146914. rc = fts3PendingTermsAddOne(
  146915. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  146916. );
  146917. /* Add the term to each of the prefix indexes that it is not too
  146918. ** short for. */
  146919. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  146920. struct Fts3Index *pIndex = &p->aIndex[i];
  146921. if( nToken<pIndex->nPrefix ) continue;
  146922. rc = fts3PendingTermsAddOne(
  146923. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  146924. );
  146925. }
  146926. }
  146927. pModule->xClose(pCsr);
  146928. *pnWord += nWord;
  146929. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  146930. }
  146931. /*
  146932. ** Calling this function indicates that subsequent calls to
  146933. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  146934. ** contents of the document with docid iDocid.
  146935. */
  146936. static int fts3PendingTermsDocid(
  146937. Fts3Table *p, /* Full-text table handle */
  146938. int bDelete, /* True if this op is a delete */
  146939. int iLangid, /* Language id of row being written */
  146940. sqlite_int64 iDocid /* Docid of row being written */
  146941. ){
  146942. assert( iLangid>=0 );
  146943. assert( bDelete==1 || bDelete==0 );
  146944. /* TODO(shess) Explore whether partially flushing the buffer on
  146945. ** forced-flush would provide better performance. I suspect that if
  146946. ** we ordered the doclists by size and flushed the largest until the
  146947. ** buffer was half empty, that would let the less frequent terms
  146948. ** generate longer doclists.
  146949. */
  146950. if( iDocid<p->iPrevDocid
  146951. || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
  146952. || p->iPrevLangid!=iLangid
  146953. || p->nPendingData>p->nMaxPendingData
  146954. ){
  146955. int rc = sqlite3Fts3PendingTermsFlush(p);
  146956. if( rc!=SQLITE_OK ) return rc;
  146957. }
  146958. p->iPrevDocid = iDocid;
  146959. p->iPrevLangid = iLangid;
  146960. p->bPrevDelete = bDelete;
  146961. return SQLITE_OK;
  146962. }
  146963. /*
  146964. ** Discard the contents of the pending-terms hash tables.
  146965. */
  146966. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  146967. int i;
  146968. for(i=0; i<p->nIndex; i++){
  146969. Fts3HashElem *pElem;
  146970. Fts3Hash *pHash = &p->aIndex[i].hPending;
  146971. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  146972. PendingList *pList = (PendingList *)fts3HashData(pElem);
  146973. fts3PendingListDelete(pList);
  146974. }
  146975. fts3HashClear(pHash);
  146976. }
  146977. p->nPendingData = 0;
  146978. }
  146979. /*
  146980. ** This function is called by the xUpdate() method as part of an INSERT
  146981. ** operation. It adds entries for each term in the new record to the
  146982. ** pendingTerms hash table.
  146983. **
  146984. ** Argument apVal is the same as the similarly named argument passed to
  146985. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  146986. */
  146987. static int fts3InsertTerms(
  146988. Fts3Table *p,
  146989. int iLangid,
  146990. sqlite3_value **apVal,
  146991. u32 *aSz
  146992. ){
  146993. int i; /* Iterator variable */
  146994. for(i=2; i<p->nColumn+2; i++){
  146995. int iCol = i-2;
  146996. if( p->abNotindexed[iCol]==0 ){
  146997. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  146998. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  146999. if( rc!=SQLITE_OK ){
  147000. return rc;
  147001. }
  147002. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  147003. }
  147004. }
  147005. return SQLITE_OK;
  147006. }
  147007. /*
  147008. ** This function is called by the xUpdate() method for an INSERT operation.
  147009. ** The apVal parameter is passed a copy of the apVal argument passed by
  147010. ** SQLite to the xUpdate() method. i.e:
  147011. **
  147012. ** apVal[0] Not used for INSERT.
  147013. ** apVal[1] rowid
  147014. ** apVal[2] Left-most user-defined column
  147015. ** ...
  147016. ** apVal[p->nColumn+1] Right-most user-defined column
  147017. ** apVal[p->nColumn+2] Hidden column with same name as table
  147018. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  147019. ** apVal[p->nColumn+4] Hidden languageid column
  147020. */
  147021. static int fts3InsertData(
  147022. Fts3Table *p, /* Full-text table */
  147023. sqlite3_value **apVal, /* Array of values to insert */
  147024. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  147025. ){
  147026. int rc; /* Return code */
  147027. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  147028. if( p->zContentTbl ){
  147029. sqlite3_value *pRowid = apVal[p->nColumn+3];
  147030. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  147031. pRowid = apVal[1];
  147032. }
  147033. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  147034. return SQLITE_CONSTRAINT;
  147035. }
  147036. *piDocid = sqlite3_value_int64(pRowid);
  147037. return SQLITE_OK;
  147038. }
  147039. /* Locate the statement handle used to insert data into the %_content
  147040. ** table. The SQL for this statement is:
  147041. **
  147042. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  147043. **
  147044. ** The statement features N '?' variables, where N is the number of user
  147045. ** defined columns in the FTS3 table, plus one for the docid field.
  147046. */
  147047. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  147048. if( rc==SQLITE_OK && p->zLanguageid ){
  147049. rc = sqlite3_bind_int(
  147050. pContentInsert, p->nColumn+2,
  147051. sqlite3_value_int(apVal[p->nColumn+4])
  147052. );
  147053. }
  147054. if( rc!=SQLITE_OK ) return rc;
  147055. /* There is a quirk here. The users INSERT statement may have specified
  147056. ** a value for the "rowid" field, for the "docid" field, or for both.
  147057. ** Which is a problem, since "rowid" and "docid" are aliases for the
  147058. ** same value. For example:
  147059. **
  147060. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  147061. **
  147062. ** In FTS3, this is an error. It is an error to specify non-NULL values
  147063. ** for both docid and some other rowid alias.
  147064. */
  147065. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  147066. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  147067. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  147068. ){
  147069. /* A rowid/docid conflict. */
  147070. return SQLITE_ERROR;
  147071. }
  147072. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  147073. if( rc!=SQLITE_OK ) return rc;
  147074. }
  147075. /* Execute the statement to insert the record. Set *piDocid to the
  147076. ** new docid value.
  147077. */
  147078. sqlite3_step(pContentInsert);
  147079. rc = sqlite3_reset(pContentInsert);
  147080. *piDocid = sqlite3_last_insert_rowid(p->db);
  147081. return rc;
  147082. }
  147083. /*
  147084. ** Remove all data from the FTS3 table. Clear the hash table containing
  147085. ** pending terms.
  147086. */
  147087. static int fts3DeleteAll(Fts3Table *p, int bContent){
  147088. int rc = SQLITE_OK; /* Return code */
  147089. /* Discard the contents of the pending-terms hash table. */
  147090. sqlite3Fts3PendingTermsClear(p);
  147091. /* Delete everything from the shadow tables. Except, leave %_content as
  147092. ** is if bContent is false. */
  147093. assert( p->zContentTbl==0 || bContent==0 );
  147094. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  147095. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  147096. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  147097. if( p->bHasDocsize ){
  147098. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  147099. }
  147100. if( p->bHasStat ){
  147101. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  147102. }
  147103. return rc;
  147104. }
  147105. /*
  147106. **
  147107. */
  147108. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  147109. int iLangid = 0;
  147110. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  147111. return iLangid;
  147112. }
  147113. /*
  147114. ** The first element in the apVal[] array is assumed to contain the docid
  147115. ** (an integer) of a row about to be deleted. Remove all terms from the
  147116. ** full-text index.
  147117. */
  147118. static void fts3DeleteTerms(
  147119. int *pRC, /* Result code */
  147120. Fts3Table *p, /* The FTS table to delete from */
  147121. sqlite3_value *pRowid, /* The docid to be deleted */
  147122. u32 *aSz, /* Sizes of deleted document written here */
  147123. int *pbFound /* OUT: Set to true if row really does exist */
  147124. ){
  147125. int rc;
  147126. sqlite3_stmt *pSelect;
  147127. assert( *pbFound==0 );
  147128. if( *pRC ) return;
  147129. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  147130. if( rc==SQLITE_OK ){
  147131. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  147132. int i;
  147133. int iLangid = langidFromSelect(p, pSelect);
  147134. i64 iDocid = sqlite3_column_int64(pSelect, 0);
  147135. rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
  147136. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  147137. int iCol = i-1;
  147138. if( p->abNotindexed[iCol]==0 ){
  147139. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  147140. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  147141. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  147142. }
  147143. }
  147144. if( rc!=SQLITE_OK ){
  147145. sqlite3_reset(pSelect);
  147146. *pRC = rc;
  147147. return;
  147148. }
  147149. *pbFound = 1;
  147150. }
  147151. rc = sqlite3_reset(pSelect);
  147152. }else{
  147153. sqlite3_reset(pSelect);
  147154. }
  147155. *pRC = rc;
  147156. }
  147157. /*
  147158. ** Forward declaration to account for the circular dependency between
  147159. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  147160. */
  147161. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  147162. /*
  147163. ** This function allocates a new level iLevel index in the segdir table.
  147164. ** Usually, indexes are allocated within a level sequentially starting
  147165. ** with 0, so the allocated index is one greater than the value returned
  147166. ** by:
  147167. **
  147168. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  147169. **
  147170. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  147171. ** level, they are merged into a single level (iLevel+1) segment and the
  147172. ** allocated index is 0.
  147173. **
  147174. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  147175. ** returned. Otherwise, an SQLite error code is returned.
  147176. */
  147177. static int fts3AllocateSegdirIdx(
  147178. Fts3Table *p,
  147179. int iLangid, /* Language id */
  147180. int iIndex, /* Index for p->aIndex */
  147181. int iLevel,
  147182. int *piIdx
  147183. ){
  147184. int rc; /* Return Code */
  147185. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  147186. int iNext = 0; /* Result of query pNextIdx */
  147187. assert( iLangid>=0 );
  147188. assert( p->nIndex>=1 );
  147189. /* Set variable iNext to the next available segdir index at level iLevel. */
  147190. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  147191. if( rc==SQLITE_OK ){
  147192. sqlite3_bind_int64(
  147193. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  147194. );
  147195. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  147196. iNext = sqlite3_column_int(pNextIdx, 0);
  147197. }
  147198. rc = sqlite3_reset(pNextIdx);
  147199. }
  147200. if( rc==SQLITE_OK ){
  147201. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  147202. ** full, merge all segments in level iLevel into a single iLevel+1
  147203. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  147204. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  147205. */
  147206. if( iNext>=FTS3_MERGE_COUNT ){
  147207. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  147208. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  147209. *piIdx = 0;
  147210. }else{
  147211. *piIdx = iNext;
  147212. }
  147213. }
  147214. return rc;
  147215. }
  147216. /*
  147217. ** The %_segments table is declared as follows:
  147218. **
  147219. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  147220. **
  147221. ** This function reads data from a single row of the %_segments table. The
  147222. ** specific row is identified by the iBlockid parameter. If paBlob is not
  147223. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  147224. ** with the contents of the blob stored in the "block" column of the
  147225. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  147226. ** to the size of the blob in bytes before returning.
  147227. **
  147228. ** If an error occurs, or the table does not contain the specified row,
  147229. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  147230. ** paBlob is non-NULL, then it is the responsibility of the caller to
  147231. ** eventually free the returned buffer.
  147232. **
  147233. ** This function may leave an open sqlite3_blob* handle in the
  147234. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  147235. ** to this function. The handle may be closed by calling the
  147236. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  147237. ** performance improvement, but the blob handle should always be closed
  147238. ** before control is returned to the user (to prevent a lock being held
  147239. ** on the database file for longer than necessary). Thus, any virtual table
  147240. ** method (xFilter etc.) that may directly or indirectly call this function
  147241. ** must call sqlite3Fts3SegmentsClose() before returning.
  147242. */
  147243. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  147244. Fts3Table *p, /* FTS3 table handle */
  147245. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  147246. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  147247. int *pnBlob, /* OUT: Size of blob data */
  147248. int *pnLoad /* OUT: Bytes actually loaded */
  147249. ){
  147250. int rc; /* Return code */
  147251. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  147252. assert( pnBlob );
  147253. if( p->pSegments ){
  147254. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  147255. }else{
  147256. if( 0==p->zSegmentsTbl ){
  147257. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  147258. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  147259. }
  147260. rc = sqlite3_blob_open(
  147261. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  147262. );
  147263. }
  147264. if( rc==SQLITE_OK ){
  147265. int nByte = sqlite3_blob_bytes(p->pSegments);
  147266. *pnBlob = nByte;
  147267. if( paBlob ){
  147268. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  147269. if( !aByte ){
  147270. rc = SQLITE_NOMEM;
  147271. }else{
  147272. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  147273. nByte = FTS3_NODE_CHUNKSIZE;
  147274. *pnLoad = nByte;
  147275. }
  147276. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  147277. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  147278. if( rc!=SQLITE_OK ){
  147279. sqlite3_free(aByte);
  147280. aByte = 0;
  147281. }
  147282. }
  147283. *paBlob = aByte;
  147284. }
  147285. }
  147286. return rc;
  147287. }
  147288. /*
  147289. ** Close the blob handle at p->pSegments, if it is open. See comments above
  147290. ** the sqlite3Fts3ReadBlock() function for details.
  147291. */
  147292. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  147293. sqlite3_blob_close(p->pSegments);
  147294. p->pSegments = 0;
  147295. }
  147296. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  147297. int nRead; /* Number of bytes to read */
  147298. int rc; /* Return code */
  147299. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  147300. rc = sqlite3_blob_read(
  147301. pReader->pBlob,
  147302. &pReader->aNode[pReader->nPopulate],
  147303. nRead,
  147304. pReader->nPopulate
  147305. );
  147306. if( rc==SQLITE_OK ){
  147307. pReader->nPopulate += nRead;
  147308. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  147309. if( pReader->nPopulate==pReader->nNode ){
  147310. sqlite3_blob_close(pReader->pBlob);
  147311. pReader->pBlob = 0;
  147312. pReader->nPopulate = 0;
  147313. }
  147314. }
  147315. return rc;
  147316. }
  147317. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  147318. int rc = SQLITE_OK;
  147319. assert( !pReader->pBlob
  147320. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  147321. );
  147322. while( pReader->pBlob && rc==SQLITE_OK
  147323. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  147324. ){
  147325. rc = fts3SegReaderIncrRead(pReader);
  147326. }
  147327. return rc;
  147328. }
  147329. /*
  147330. ** Set an Fts3SegReader cursor to point at EOF.
  147331. */
  147332. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  147333. if( !fts3SegReaderIsRootOnly(pSeg) ){
  147334. sqlite3_free(pSeg->aNode);
  147335. sqlite3_blob_close(pSeg->pBlob);
  147336. pSeg->pBlob = 0;
  147337. }
  147338. pSeg->aNode = 0;
  147339. }
  147340. /*
  147341. ** Move the iterator passed as the first argument to the next term in the
  147342. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  147343. ** SQLITE_DONE. Otherwise, an SQLite error code.
  147344. */
  147345. static int fts3SegReaderNext(
  147346. Fts3Table *p,
  147347. Fts3SegReader *pReader,
  147348. int bIncr
  147349. ){
  147350. int rc; /* Return code of various sub-routines */
  147351. char *pNext; /* Cursor variable */
  147352. int nPrefix; /* Number of bytes in term prefix */
  147353. int nSuffix; /* Number of bytes in term suffix */
  147354. if( !pReader->aDoclist ){
  147355. pNext = pReader->aNode;
  147356. }else{
  147357. pNext = &pReader->aDoclist[pReader->nDoclist];
  147358. }
  147359. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  147360. if( fts3SegReaderIsPending(pReader) ){
  147361. Fts3HashElem *pElem = *(pReader->ppNextElem);
  147362. sqlite3_free(pReader->aNode);
  147363. pReader->aNode = 0;
  147364. if( pElem ){
  147365. char *aCopy;
  147366. PendingList *pList = (PendingList *)fts3HashData(pElem);
  147367. int nCopy = pList->nData+1;
  147368. pReader->zTerm = (char *)fts3HashKey(pElem);
  147369. pReader->nTerm = fts3HashKeysize(pElem);
  147370. aCopy = (char*)sqlite3_malloc(nCopy);
  147371. if( !aCopy ) return SQLITE_NOMEM;
  147372. memcpy(aCopy, pList->aData, nCopy);
  147373. pReader->nNode = pReader->nDoclist = nCopy;
  147374. pReader->aNode = pReader->aDoclist = aCopy;
  147375. pReader->ppNextElem++;
  147376. assert( pReader->aNode );
  147377. }
  147378. return SQLITE_OK;
  147379. }
  147380. fts3SegReaderSetEof(pReader);
  147381. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  147382. ** blocks have already been traversed. */
  147383. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  147384. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  147385. return SQLITE_OK;
  147386. }
  147387. rc = sqlite3Fts3ReadBlock(
  147388. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  147389. (bIncr ? &pReader->nPopulate : 0)
  147390. );
  147391. if( rc!=SQLITE_OK ) return rc;
  147392. assert( pReader->pBlob==0 );
  147393. if( bIncr && pReader->nPopulate<pReader->nNode ){
  147394. pReader->pBlob = p->pSegments;
  147395. p->pSegments = 0;
  147396. }
  147397. pNext = pReader->aNode;
  147398. }
  147399. assert( !fts3SegReaderIsPending(pReader) );
  147400. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  147401. if( rc!=SQLITE_OK ) return rc;
  147402. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  147403. ** safe (no risk of overread) even if the node data is corrupted. */
  147404. pNext += fts3GetVarint32(pNext, &nPrefix);
  147405. pNext += fts3GetVarint32(pNext, &nSuffix);
  147406. if( nPrefix<0 || nSuffix<=0
  147407. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  147408. ){
  147409. return FTS_CORRUPT_VTAB;
  147410. }
  147411. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  147412. int nNew = (nPrefix+nSuffix)*2;
  147413. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  147414. if( !zNew ){
  147415. return SQLITE_NOMEM;
  147416. }
  147417. pReader->zTerm = zNew;
  147418. pReader->nTermAlloc = nNew;
  147419. }
  147420. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  147421. if( rc!=SQLITE_OK ) return rc;
  147422. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  147423. pReader->nTerm = nPrefix+nSuffix;
  147424. pNext += nSuffix;
  147425. pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
  147426. pReader->aDoclist = pNext;
  147427. pReader->pOffsetList = 0;
  147428. /* Check that the doclist does not appear to extend past the end of the
  147429. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  147430. ** of these statements is untrue, then the data structure is corrupt.
  147431. */
  147432. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  147433. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  147434. ){
  147435. return FTS_CORRUPT_VTAB;
  147436. }
  147437. return SQLITE_OK;
  147438. }
  147439. /*
  147440. ** Set the SegReader to point to the first docid in the doclist associated
  147441. ** with the current term.
  147442. */
  147443. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  147444. int rc = SQLITE_OK;
  147445. assert( pReader->aDoclist );
  147446. assert( !pReader->pOffsetList );
  147447. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  147448. u8 bEof = 0;
  147449. pReader->iDocid = 0;
  147450. pReader->nOffsetList = 0;
  147451. sqlite3Fts3DoclistPrev(0,
  147452. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  147453. &pReader->iDocid, &pReader->nOffsetList, &bEof
  147454. );
  147455. }else{
  147456. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  147457. if( rc==SQLITE_OK ){
  147458. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  147459. pReader->pOffsetList = &pReader->aDoclist[n];
  147460. }
  147461. }
  147462. return rc;
  147463. }
  147464. /*
  147465. ** Advance the SegReader to point to the next docid in the doclist
  147466. ** associated with the current term.
  147467. **
  147468. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  147469. ** *ppOffsetList is set to point to the first column-offset list
  147470. ** in the doclist entry (i.e. immediately past the docid varint).
  147471. ** *pnOffsetList is set to the length of the set of column-offset
  147472. ** lists, not including the nul-terminator byte. For example:
  147473. */
  147474. static int fts3SegReaderNextDocid(
  147475. Fts3Table *pTab,
  147476. Fts3SegReader *pReader, /* Reader to advance to next docid */
  147477. char **ppOffsetList, /* OUT: Pointer to current position-list */
  147478. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  147479. ){
  147480. int rc = SQLITE_OK;
  147481. char *p = pReader->pOffsetList;
  147482. char c = 0;
  147483. assert( p );
  147484. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  147485. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  147486. ** Pending-terms doclists are always built up in ascending order, so
  147487. ** we have to iterate through them backwards here. */
  147488. u8 bEof = 0;
  147489. if( ppOffsetList ){
  147490. *ppOffsetList = pReader->pOffsetList;
  147491. *pnOffsetList = pReader->nOffsetList - 1;
  147492. }
  147493. sqlite3Fts3DoclistPrev(0,
  147494. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  147495. &pReader->nOffsetList, &bEof
  147496. );
  147497. if( bEof ){
  147498. pReader->pOffsetList = 0;
  147499. }else{
  147500. pReader->pOffsetList = p;
  147501. }
  147502. }else{
  147503. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  147504. /* Pointer p currently points at the first byte of an offset list. The
  147505. ** following block advances it to point one byte past the end of
  147506. ** the same offset list. */
  147507. while( 1 ){
  147508. /* The following line of code (and the "p++" below the while() loop) is
  147509. ** normally all that is required to move pointer p to the desired
  147510. ** position. The exception is if this node is being loaded from disk
  147511. ** incrementally and pointer "p" now points to the first byte past
  147512. ** the populated part of pReader->aNode[].
  147513. */
  147514. while( *p | c ) c = *p++ & 0x80;
  147515. assert( *p==0 );
  147516. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  147517. rc = fts3SegReaderIncrRead(pReader);
  147518. if( rc!=SQLITE_OK ) return rc;
  147519. }
  147520. p++;
  147521. /* If required, populate the output variables with a pointer to and the
  147522. ** size of the previous offset-list.
  147523. */
  147524. if( ppOffsetList ){
  147525. *ppOffsetList = pReader->pOffsetList;
  147526. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  147527. }
  147528. /* List may have been edited in place by fts3EvalNearTrim() */
  147529. while( p<pEnd && *p==0 ) p++;
  147530. /* If there are no more entries in the doclist, set pOffsetList to
  147531. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  147532. ** Fts3SegReader.pOffsetList to point to the next offset list before
  147533. ** returning.
  147534. */
  147535. if( p>=pEnd ){
  147536. pReader->pOffsetList = 0;
  147537. }else{
  147538. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  147539. if( rc==SQLITE_OK ){
  147540. sqlite3_int64 iDelta;
  147541. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  147542. if( pTab->bDescIdx ){
  147543. pReader->iDocid -= iDelta;
  147544. }else{
  147545. pReader->iDocid += iDelta;
  147546. }
  147547. }
  147548. }
  147549. }
  147550. return SQLITE_OK;
  147551. }
  147552. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  147553. Fts3Cursor *pCsr,
  147554. Fts3MultiSegReader *pMsr,
  147555. int *pnOvfl
  147556. ){
  147557. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  147558. int nOvfl = 0;
  147559. int ii;
  147560. int rc = SQLITE_OK;
  147561. int pgsz = p->nPgsz;
  147562. assert( p->bFts4 );
  147563. assert( pgsz>0 );
  147564. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  147565. Fts3SegReader *pReader = pMsr->apSegment[ii];
  147566. if( !fts3SegReaderIsPending(pReader)
  147567. && !fts3SegReaderIsRootOnly(pReader)
  147568. ){
  147569. sqlite3_int64 jj;
  147570. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  147571. int nBlob;
  147572. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  147573. if( rc!=SQLITE_OK ) break;
  147574. if( (nBlob+35)>pgsz ){
  147575. nOvfl += (nBlob + 34)/pgsz;
  147576. }
  147577. }
  147578. }
  147579. }
  147580. *pnOvfl = nOvfl;
  147581. return rc;
  147582. }
  147583. /*
  147584. ** Free all allocations associated with the iterator passed as the
  147585. ** second argument.
  147586. */
  147587. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  147588. if( pReader ){
  147589. if( !fts3SegReaderIsPending(pReader) ){
  147590. sqlite3_free(pReader->zTerm);
  147591. }
  147592. if( !fts3SegReaderIsRootOnly(pReader) ){
  147593. sqlite3_free(pReader->aNode);
  147594. }
  147595. sqlite3_blob_close(pReader->pBlob);
  147596. }
  147597. sqlite3_free(pReader);
  147598. }
  147599. /*
  147600. ** Allocate a new SegReader object.
  147601. */
  147602. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  147603. int iAge, /* Segment "age". */
  147604. int bLookup, /* True for a lookup only */
  147605. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  147606. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  147607. sqlite3_int64 iEndBlock, /* Final block of segment */
  147608. const char *zRoot, /* Buffer containing root node */
  147609. int nRoot, /* Size of buffer containing root node */
  147610. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  147611. ){
  147612. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  147613. int nExtra = 0; /* Bytes to allocate segment root node */
  147614. assert( iStartLeaf<=iEndLeaf );
  147615. if( iStartLeaf==0 ){
  147616. nExtra = nRoot + FTS3_NODE_PADDING;
  147617. }
  147618. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  147619. if( !pReader ){
  147620. return SQLITE_NOMEM;
  147621. }
  147622. memset(pReader, 0, sizeof(Fts3SegReader));
  147623. pReader->iIdx = iAge;
  147624. pReader->bLookup = bLookup!=0;
  147625. pReader->iStartBlock = iStartLeaf;
  147626. pReader->iLeafEndBlock = iEndLeaf;
  147627. pReader->iEndBlock = iEndBlock;
  147628. if( nExtra ){
  147629. /* The entire segment is stored in the root node. */
  147630. pReader->aNode = (char *)&pReader[1];
  147631. pReader->rootOnly = 1;
  147632. pReader->nNode = nRoot;
  147633. memcpy(pReader->aNode, zRoot, nRoot);
  147634. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  147635. }else{
  147636. pReader->iCurrentBlock = iStartLeaf-1;
  147637. }
  147638. *ppReader = pReader;
  147639. return SQLITE_OK;
  147640. }
  147641. /*
  147642. ** This is a comparison function used as a qsort() callback when sorting
  147643. ** an array of pending terms by term. This occurs as part of flushing
  147644. ** the contents of the pending-terms hash table to the database.
  147645. */
  147646. static int SQLITE_CDECL fts3CompareElemByTerm(
  147647. const void *lhs,
  147648. const void *rhs
  147649. ){
  147650. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  147651. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  147652. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  147653. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  147654. int n = (n1<n2 ? n1 : n2);
  147655. int c = memcmp(z1, z2, n);
  147656. if( c==0 ){
  147657. c = n1 - n2;
  147658. }
  147659. return c;
  147660. }
  147661. /*
  147662. ** This function is used to allocate an Fts3SegReader that iterates through
  147663. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  147664. **
  147665. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  147666. ** through each term in the pending-terms table. Or, if isPrefixIter is
  147667. ** non-zero, it iterates through each term and its prefixes. For example, if
  147668. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  147669. ** "firebird", then the iterator visits the following 'terms' (in the order
  147670. ** shown):
  147671. **
  147672. ** f fi fir fire fireb firebi firebir firebird
  147673. ** m my mys mysq mysql
  147674. ** s sq sql sqli sqlit sqlite
  147675. **
  147676. ** Whereas if isPrefixIter is zero, the terms visited are:
  147677. **
  147678. ** firebird mysql sqlite
  147679. */
  147680. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  147681. Fts3Table *p, /* Virtual table handle */
  147682. int iIndex, /* Index for p->aIndex */
  147683. const char *zTerm, /* Term to search for */
  147684. int nTerm, /* Size of buffer zTerm */
  147685. int bPrefix, /* True for a prefix iterator */
  147686. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  147687. ){
  147688. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  147689. Fts3HashElem *pE; /* Iterator variable */
  147690. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  147691. int nElem = 0; /* Size of array at aElem */
  147692. int rc = SQLITE_OK; /* Return Code */
  147693. Fts3Hash *pHash;
  147694. pHash = &p->aIndex[iIndex].hPending;
  147695. if( bPrefix ){
  147696. int nAlloc = 0; /* Size of allocated array at aElem */
  147697. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  147698. char *zKey = (char *)fts3HashKey(pE);
  147699. int nKey = fts3HashKeysize(pE);
  147700. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  147701. if( nElem==nAlloc ){
  147702. Fts3HashElem **aElem2;
  147703. nAlloc += 16;
  147704. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  147705. aElem, nAlloc*sizeof(Fts3HashElem *)
  147706. );
  147707. if( !aElem2 ){
  147708. rc = SQLITE_NOMEM;
  147709. nElem = 0;
  147710. break;
  147711. }
  147712. aElem = aElem2;
  147713. }
  147714. aElem[nElem++] = pE;
  147715. }
  147716. }
  147717. /* If more than one term matches the prefix, sort the Fts3HashElem
  147718. ** objects in term order using qsort(). This uses the same comparison
  147719. ** callback as is used when flushing terms to disk.
  147720. */
  147721. if( nElem>1 ){
  147722. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  147723. }
  147724. }else{
  147725. /* The query is a simple term lookup that matches at most one term in
  147726. ** the index. All that is required is a straight hash-lookup.
  147727. **
  147728. ** Because the stack address of pE may be accessed via the aElem pointer
  147729. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  147730. ** within this entire function, not just this "else{...}" block.
  147731. */
  147732. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  147733. if( pE ){
  147734. aElem = &pE;
  147735. nElem = 1;
  147736. }
  147737. }
  147738. if( nElem>0 ){
  147739. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  147740. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  147741. if( !pReader ){
  147742. rc = SQLITE_NOMEM;
  147743. }else{
  147744. memset(pReader, 0, nByte);
  147745. pReader->iIdx = 0x7FFFFFFF;
  147746. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  147747. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  147748. }
  147749. }
  147750. if( bPrefix ){
  147751. sqlite3_free(aElem);
  147752. }
  147753. *ppReader = pReader;
  147754. return rc;
  147755. }
  147756. /*
  147757. ** Compare the entries pointed to by two Fts3SegReader structures.
  147758. ** Comparison is as follows:
  147759. **
  147760. ** 1) EOF is greater than not EOF.
  147761. **
  147762. ** 2) The current terms (if any) are compared using memcmp(). If one
  147763. ** term is a prefix of another, the longer term is considered the
  147764. ** larger.
  147765. **
  147766. ** 3) By segment age. An older segment is considered larger.
  147767. */
  147768. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  147769. int rc;
  147770. if( pLhs->aNode && pRhs->aNode ){
  147771. int rc2 = pLhs->nTerm - pRhs->nTerm;
  147772. if( rc2<0 ){
  147773. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  147774. }else{
  147775. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  147776. }
  147777. if( rc==0 ){
  147778. rc = rc2;
  147779. }
  147780. }else{
  147781. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  147782. }
  147783. if( rc==0 ){
  147784. rc = pRhs->iIdx - pLhs->iIdx;
  147785. }
  147786. assert( rc!=0 );
  147787. return rc;
  147788. }
  147789. /*
  147790. ** A different comparison function for SegReader structures. In this
  147791. ** version, it is assumed that each SegReader points to an entry in
  147792. ** a doclist for identical terms. Comparison is made as follows:
  147793. **
  147794. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  147795. **
  147796. ** 2) By current docid.
  147797. **
  147798. ** 3) By segment age. An older segment is considered larger.
  147799. */
  147800. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  147801. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  147802. if( rc==0 ){
  147803. if( pLhs->iDocid==pRhs->iDocid ){
  147804. rc = pRhs->iIdx - pLhs->iIdx;
  147805. }else{
  147806. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  147807. }
  147808. }
  147809. assert( pLhs->aNode && pRhs->aNode );
  147810. return rc;
  147811. }
  147812. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  147813. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  147814. if( rc==0 ){
  147815. if( pLhs->iDocid==pRhs->iDocid ){
  147816. rc = pRhs->iIdx - pLhs->iIdx;
  147817. }else{
  147818. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  147819. }
  147820. }
  147821. assert( pLhs->aNode && pRhs->aNode );
  147822. return rc;
  147823. }
  147824. /*
  147825. ** Compare the term that the Fts3SegReader object passed as the first argument
  147826. ** points to with the term specified by arguments zTerm and nTerm.
  147827. **
  147828. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  147829. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  147830. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  147831. */
  147832. static int fts3SegReaderTermCmp(
  147833. Fts3SegReader *pSeg, /* Segment reader object */
  147834. const char *zTerm, /* Term to compare to */
  147835. int nTerm /* Size of term zTerm in bytes */
  147836. ){
  147837. int res = 0;
  147838. if( pSeg->aNode ){
  147839. if( pSeg->nTerm>nTerm ){
  147840. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  147841. }else{
  147842. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  147843. }
  147844. if( res==0 ){
  147845. res = pSeg->nTerm-nTerm;
  147846. }
  147847. }
  147848. return res;
  147849. }
  147850. /*
  147851. ** Argument apSegment is an array of nSegment elements. It is known that
  147852. ** the final (nSegment-nSuspect) members are already in sorted order
  147853. ** (according to the comparison function provided). This function shuffles
  147854. ** the array around until all entries are in sorted order.
  147855. */
  147856. static void fts3SegReaderSort(
  147857. Fts3SegReader **apSegment, /* Array to sort entries of */
  147858. int nSegment, /* Size of apSegment array */
  147859. int nSuspect, /* Unsorted entry count */
  147860. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  147861. ){
  147862. int i; /* Iterator variable */
  147863. assert( nSuspect<=nSegment );
  147864. if( nSuspect==nSegment ) nSuspect--;
  147865. for(i=nSuspect-1; i>=0; i--){
  147866. int j;
  147867. for(j=i; j<(nSegment-1); j++){
  147868. Fts3SegReader *pTmp;
  147869. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  147870. pTmp = apSegment[j+1];
  147871. apSegment[j+1] = apSegment[j];
  147872. apSegment[j] = pTmp;
  147873. }
  147874. }
  147875. #ifndef NDEBUG
  147876. /* Check that the list really is sorted now. */
  147877. for(i=0; i<(nSuspect-1); i++){
  147878. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  147879. }
  147880. #endif
  147881. }
  147882. /*
  147883. ** Insert a record into the %_segments table.
  147884. */
  147885. static int fts3WriteSegment(
  147886. Fts3Table *p, /* Virtual table handle */
  147887. sqlite3_int64 iBlock, /* Block id for new block */
  147888. char *z, /* Pointer to buffer containing block data */
  147889. int n /* Size of buffer z in bytes */
  147890. ){
  147891. sqlite3_stmt *pStmt;
  147892. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  147893. if( rc==SQLITE_OK ){
  147894. sqlite3_bind_int64(pStmt, 1, iBlock);
  147895. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  147896. sqlite3_step(pStmt);
  147897. rc = sqlite3_reset(pStmt);
  147898. }
  147899. return rc;
  147900. }
  147901. /*
  147902. ** Find the largest relative level number in the table. If successful, set
  147903. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  147904. ** set *pnMax to zero and return an SQLite error code.
  147905. */
  147906. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  147907. int rc;
  147908. int mxLevel = 0;
  147909. sqlite3_stmt *pStmt = 0;
  147910. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  147911. if( rc==SQLITE_OK ){
  147912. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  147913. mxLevel = sqlite3_column_int(pStmt, 0);
  147914. }
  147915. rc = sqlite3_reset(pStmt);
  147916. }
  147917. *pnMax = mxLevel;
  147918. return rc;
  147919. }
  147920. /*
  147921. ** Insert a record into the %_segdir table.
  147922. */
  147923. static int fts3WriteSegdir(
  147924. Fts3Table *p, /* Virtual table handle */
  147925. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  147926. int iIdx, /* Value for "idx" field */
  147927. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  147928. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  147929. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  147930. sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
  147931. char *zRoot, /* Blob value for "root" field */
  147932. int nRoot /* Number of bytes in buffer zRoot */
  147933. ){
  147934. sqlite3_stmt *pStmt;
  147935. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  147936. if( rc==SQLITE_OK ){
  147937. sqlite3_bind_int64(pStmt, 1, iLevel);
  147938. sqlite3_bind_int(pStmt, 2, iIdx);
  147939. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  147940. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  147941. if( nLeafData==0 ){
  147942. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  147943. }else{
  147944. char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
  147945. if( !zEnd ) return SQLITE_NOMEM;
  147946. sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
  147947. }
  147948. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  147949. sqlite3_step(pStmt);
  147950. rc = sqlite3_reset(pStmt);
  147951. }
  147952. return rc;
  147953. }
  147954. /*
  147955. ** Return the size of the common prefix (if any) shared by zPrev and
  147956. ** zNext, in bytes. For example,
  147957. **
  147958. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  147959. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  147960. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  147961. */
  147962. static int fts3PrefixCompress(
  147963. const char *zPrev, /* Buffer containing previous term */
  147964. int nPrev, /* Size of buffer zPrev in bytes */
  147965. const char *zNext, /* Buffer containing next term */
  147966. int nNext /* Size of buffer zNext in bytes */
  147967. ){
  147968. int n;
  147969. UNUSED_PARAMETER(nNext);
  147970. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  147971. return n;
  147972. }
  147973. /*
  147974. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  147975. ** (according to memcmp) than the previous term.
  147976. */
  147977. static int fts3NodeAddTerm(
  147978. Fts3Table *p, /* Virtual table handle */
  147979. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  147980. int isCopyTerm, /* True if zTerm/nTerm is transient */
  147981. const char *zTerm, /* Pointer to buffer containing term */
  147982. int nTerm /* Size of term in bytes */
  147983. ){
  147984. SegmentNode *pTree = *ppTree;
  147985. int rc;
  147986. SegmentNode *pNew;
  147987. /* First try to append the term to the current node. Return early if
  147988. ** this is possible.
  147989. */
  147990. if( pTree ){
  147991. int nData = pTree->nData; /* Current size of node in bytes */
  147992. int nReq = nData; /* Required space after adding zTerm */
  147993. int nPrefix; /* Number of bytes of prefix compression */
  147994. int nSuffix; /* Suffix length */
  147995. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  147996. nSuffix = nTerm-nPrefix;
  147997. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  147998. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  147999. if( nReq>p->nNodeSize ){
  148000. /* An unusual case: this is the first term to be added to the node
  148001. ** and the static node buffer (p->nNodeSize bytes) is not large
  148002. ** enough. Use a separately malloced buffer instead This wastes
  148003. ** p->nNodeSize bytes, but since this scenario only comes about when
  148004. ** the database contain two terms that share a prefix of almost 2KB,
  148005. ** this is not expected to be a serious problem.
  148006. */
  148007. assert( pTree->aData==(char *)&pTree[1] );
  148008. pTree->aData = (char *)sqlite3_malloc(nReq);
  148009. if( !pTree->aData ){
  148010. return SQLITE_NOMEM;
  148011. }
  148012. }
  148013. if( pTree->zTerm ){
  148014. /* There is no prefix-length field for first term in a node */
  148015. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  148016. }
  148017. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  148018. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  148019. pTree->nData = nData + nSuffix;
  148020. pTree->nEntry++;
  148021. if( isCopyTerm ){
  148022. if( pTree->nMalloc<nTerm ){
  148023. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  148024. if( !zNew ){
  148025. return SQLITE_NOMEM;
  148026. }
  148027. pTree->nMalloc = nTerm*2;
  148028. pTree->zMalloc = zNew;
  148029. }
  148030. pTree->zTerm = pTree->zMalloc;
  148031. memcpy(pTree->zTerm, zTerm, nTerm);
  148032. pTree->nTerm = nTerm;
  148033. }else{
  148034. pTree->zTerm = (char *)zTerm;
  148035. pTree->nTerm = nTerm;
  148036. }
  148037. return SQLITE_OK;
  148038. }
  148039. }
  148040. /* If control flows to here, it was not possible to append zTerm to the
  148041. ** current node. Create a new node (a right-sibling of the current node).
  148042. ** If this is the first node in the tree, the term is added to it.
  148043. **
  148044. ** Otherwise, the term is not added to the new node, it is left empty for
  148045. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  148046. ** has no parent, one is created here.
  148047. */
  148048. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  148049. if( !pNew ){
  148050. return SQLITE_NOMEM;
  148051. }
  148052. memset(pNew, 0, sizeof(SegmentNode));
  148053. pNew->nData = 1 + FTS3_VARINT_MAX;
  148054. pNew->aData = (char *)&pNew[1];
  148055. if( pTree ){
  148056. SegmentNode *pParent = pTree->pParent;
  148057. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  148058. if( pTree->pParent==0 ){
  148059. pTree->pParent = pParent;
  148060. }
  148061. pTree->pRight = pNew;
  148062. pNew->pLeftmost = pTree->pLeftmost;
  148063. pNew->pParent = pParent;
  148064. pNew->zMalloc = pTree->zMalloc;
  148065. pNew->nMalloc = pTree->nMalloc;
  148066. pTree->zMalloc = 0;
  148067. }else{
  148068. pNew->pLeftmost = pNew;
  148069. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  148070. }
  148071. *ppTree = pNew;
  148072. return rc;
  148073. }
  148074. /*
  148075. ** Helper function for fts3NodeWrite().
  148076. */
  148077. static int fts3TreeFinishNode(
  148078. SegmentNode *pTree,
  148079. int iHeight,
  148080. sqlite3_int64 iLeftChild
  148081. ){
  148082. int nStart;
  148083. assert( iHeight>=1 && iHeight<128 );
  148084. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  148085. pTree->aData[nStart] = (char)iHeight;
  148086. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  148087. return nStart;
  148088. }
  148089. /*
  148090. ** Write the buffer for the segment node pTree and all of its peers to the
  148091. ** database. Then call this function recursively to write the parent of
  148092. ** pTree and its peers to the database.
  148093. **
  148094. ** Except, if pTree is a root node, do not write it to the database. Instead,
  148095. ** set output variables *paRoot and *pnRoot to contain the root node.
  148096. **
  148097. ** If successful, SQLITE_OK is returned and output variable *piLast is
  148098. ** set to the largest blockid written to the database (or zero if no
  148099. ** blocks were written to the db). Otherwise, an SQLite error code is
  148100. ** returned.
  148101. */
  148102. static int fts3NodeWrite(
  148103. Fts3Table *p, /* Virtual table handle */
  148104. SegmentNode *pTree, /* SegmentNode handle */
  148105. int iHeight, /* Height of this node in tree */
  148106. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  148107. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  148108. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  148109. char **paRoot, /* OUT: Data for root node */
  148110. int *pnRoot /* OUT: Size of root node in bytes */
  148111. ){
  148112. int rc = SQLITE_OK;
  148113. if( !pTree->pParent ){
  148114. /* Root node of the tree. */
  148115. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  148116. *piLast = iFree-1;
  148117. *pnRoot = pTree->nData - nStart;
  148118. *paRoot = &pTree->aData[nStart];
  148119. }else{
  148120. SegmentNode *pIter;
  148121. sqlite3_int64 iNextFree = iFree;
  148122. sqlite3_int64 iNextLeaf = iLeaf;
  148123. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  148124. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  148125. int nWrite = pIter->nData - nStart;
  148126. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  148127. iNextFree++;
  148128. iNextLeaf += (pIter->nEntry+1);
  148129. }
  148130. if( rc==SQLITE_OK ){
  148131. assert( iNextLeaf==iFree );
  148132. rc = fts3NodeWrite(
  148133. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  148134. );
  148135. }
  148136. }
  148137. return rc;
  148138. }
  148139. /*
  148140. ** Free all memory allocations associated with the tree pTree.
  148141. */
  148142. static void fts3NodeFree(SegmentNode *pTree){
  148143. if( pTree ){
  148144. SegmentNode *p = pTree->pLeftmost;
  148145. fts3NodeFree(p->pParent);
  148146. while( p ){
  148147. SegmentNode *pRight = p->pRight;
  148148. if( p->aData!=(char *)&p[1] ){
  148149. sqlite3_free(p->aData);
  148150. }
  148151. assert( pRight==0 || p->zMalloc==0 );
  148152. sqlite3_free(p->zMalloc);
  148153. sqlite3_free(p);
  148154. p = pRight;
  148155. }
  148156. }
  148157. }
  148158. /*
  148159. ** Add a term to the segment being constructed by the SegmentWriter object
  148160. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  148161. ** be passed NULL. This function will allocate a new SegmentWriter object
  148162. ** and return it via the input/output variable *ppWriter in this case.
  148163. **
  148164. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  148165. */
  148166. static int fts3SegWriterAdd(
  148167. Fts3Table *p, /* Virtual table handle */
  148168. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  148169. int isCopyTerm, /* True if buffer zTerm must be copied */
  148170. const char *zTerm, /* Pointer to buffer containing term */
  148171. int nTerm, /* Size of term in bytes */
  148172. const char *aDoclist, /* Pointer to buffer containing doclist */
  148173. int nDoclist /* Size of doclist in bytes */
  148174. ){
  148175. int nPrefix; /* Size of term prefix in bytes */
  148176. int nSuffix; /* Size of term suffix in bytes */
  148177. int nReq; /* Number of bytes required on leaf page */
  148178. int nData;
  148179. SegmentWriter *pWriter = *ppWriter;
  148180. if( !pWriter ){
  148181. int rc;
  148182. sqlite3_stmt *pStmt;
  148183. /* Allocate the SegmentWriter structure */
  148184. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  148185. if( !pWriter ) return SQLITE_NOMEM;
  148186. memset(pWriter, 0, sizeof(SegmentWriter));
  148187. *ppWriter = pWriter;
  148188. /* Allocate a buffer in which to accumulate data */
  148189. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  148190. if( !pWriter->aData ) return SQLITE_NOMEM;
  148191. pWriter->nSize = p->nNodeSize;
  148192. /* Find the next free blockid in the %_segments table */
  148193. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  148194. if( rc!=SQLITE_OK ) return rc;
  148195. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  148196. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  148197. pWriter->iFirst = pWriter->iFree;
  148198. }
  148199. rc = sqlite3_reset(pStmt);
  148200. if( rc!=SQLITE_OK ) return rc;
  148201. }
  148202. nData = pWriter->nData;
  148203. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  148204. nSuffix = nTerm-nPrefix;
  148205. /* Figure out how many bytes are required by this new entry */
  148206. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  148207. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  148208. nSuffix + /* Term suffix */
  148209. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  148210. nDoclist; /* Doclist data */
  148211. if( nData>0 && nData+nReq>p->nNodeSize ){
  148212. int rc;
  148213. /* The current leaf node is full. Write it out to the database. */
  148214. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  148215. if( rc!=SQLITE_OK ) return rc;
  148216. p->nLeafAdd++;
  148217. /* Add the current term to the interior node tree. The term added to
  148218. ** the interior tree must:
  148219. **
  148220. ** a) be greater than the largest term on the leaf node just written
  148221. ** to the database (still available in pWriter->zTerm), and
  148222. **
  148223. ** b) be less than or equal to the term about to be added to the new
  148224. ** leaf node (zTerm/nTerm).
  148225. **
  148226. ** In other words, it must be the prefix of zTerm 1 byte longer than
  148227. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  148228. */
  148229. assert( nPrefix<nTerm );
  148230. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  148231. if( rc!=SQLITE_OK ) return rc;
  148232. nData = 0;
  148233. pWriter->nTerm = 0;
  148234. nPrefix = 0;
  148235. nSuffix = nTerm;
  148236. nReq = 1 + /* varint containing prefix size */
  148237. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  148238. nTerm + /* Term suffix */
  148239. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  148240. nDoclist; /* Doclist data */
  148241. }
  148242. /* Increase the total number of bytes written to account for the new entry. */
  148243. pWriter->nLeafData += nReq;
  148244. /* If the buffer currently allocated is too small for this entry, realloc
  148245. ** the buffer to make it large enough.
  148246. */
  148247. if( nReq>pWriter->nSize ){
  148248. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  148249. if( !aNew ) return SQLITE_NOMEM;
  148250. pWriter->aData = aNew;
  148251. pWriter->nSize = nReq;
  148252. }
  148253. assert( nData+nReq<=pWriter->nSize );
  148254. /* Append the prefix-compressed term and doclist to the buffer. */
  148255. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  148256. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  148257. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  148258. nData += nSuffix;
  148259. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  148260. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  148261. pWriter->nData = nData + nDoclist;
  148262. /* Save the current term so that it can be used to prefix-compress the next.
  148263. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  148264. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  148265. ** store a copy of the pointer.
  148266. */
  148267. if( isCopyTerm ){
  148268. if( nTerm>pWriter->nMalloc ){
  148269. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  148270. if( !zNew ){
  148271. return SQLITE_NOMEM;
  148272. }
  148273. pWriter->nMalloc = nTerm*2;
  148274. pWriter->zMalloc = zNew;
  148275. pWriter->zTerm = zNew;
  148276. }
  148277. assert( pWriter->zTerm==pWriter->zMalloc );
  148278. memcpy(pWriter->zTerm, zTerm, nTerm);
  148279. }else{
  148280. pWriter->zTerm = (char *)zTerm;
  148281. }
  148282. pWriter->nTerm = nTerm;
  148283. return SQLITE_OK;
  148284. }
  148285. /*
  148286. ** Flush all data associated with the SegmentWriter object pWriter to the
  148287. ** database. This function must be called after all terms have been added
  148288. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  148289. ** returned. Otherwise, an SQLite error code.
  148290. */
  148291. static int fts3SegWriterFlush(
  148292. Fts3Table *p, /* Virtual table handle */
  148293. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  148294. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  148295. int iIdx /* Value for 'idx' column of %_segdir */
  148296. ){
  148297. int rc; /* Return code */
  148298. if( pWriter->pTree ){
  148299. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  148300. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  148301. char *zRoot = NULL; /* Pointer to buffer containing root node */
  148302. int nRoot = 0; /* Size of buffer zRoot */
  148303. iLastLeaf = pWriter->iFree;
  148304. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  148305. if( rc==SQLITE_OK ){
  148306. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  148307. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  148308. }
  148309. if( rc==SQLITE_OK ){
  148310. rc = fts3WriteSegdir(p, iLevel, iIdx,
  148311. pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
  148312. }
  148313. }else{
  148314. /* The entire tree fits on the root node. Write it to the segdir table. */
  148315. rc = fts3WriteSegdir(p, iLevel, iIdx,
  148316. 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
  148317. }
  148318. p->nLeafAdd++;
  148319. return rc;
  148320. }
  148321. /*
  148322. ** Release all memory held by the SegmentWriter object passed as the
  148323. ** first argument.
  148324. */
  148325. static void fts3SegWriterFree(SegmentWriter *pWriter){
  148326. if( pWriter ){
  148327. sqlite3_free(pWriter->aData);
  148328. sqlite3_free(pWriter->zMalloc);
  148329. fts3NodeFree(pWriter->pTree);
  148330. sqlite3_free(pWriter);
  148331. }
  148332. }
  148333. /*
  148334. ** The first value in the apVal[] array is assumed to contain an integer.
  148335. ** This function tests if there exist any documents with docid values that
  148336. ** are different from that integer. i.e. if deleting the document with docid
  148337. ** pRowid would mean the FTS3 table were empty.
  148338. **
  148339. ** If successful, *pisEmpty is set to true if the table is empty except for
  148340. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  148341. ** error occurs, an SQLite error code is returned.
  148342. */
  148343. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  148344. sqlite3_stmt *pStmt;
  148345. int rc;
  148346. if( p->zContentTbl ){
  148347. /* If using the content=xxx option, assume the table is never empty */
  148348. *pisEmpty = 0;
  148349. rc = SQLITE_OK;
  148350. }else{
  148351. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  148352. if( rc==SQLITE_OK ){
  148353. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  148354. *pisEmpty = sqlite3_column_int(pStmt, 0);
  148355. }
  148356. rc = sqlite3_reset(pStmt);
  148357. }
  148358. }
  148359. return rc;
  148360. }
  148361. /*
  148362. ** Set *pnMax to the largest segment level in the database for the index
  148363. ** iIndex.
  148364. **
  148365. ** Segment levels are stored in the 'level' column of the %_segdir table.
  148366. **
  148367. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  148368. */
  148369. static int fts3SegmentMaxLevel(
  148370. Fts3Table *p,
  148371. int iLangid,
  148372. int iIndex,
  148373. sqlite3_int64 *pnMax
  148374. ){
  148375. sqlite3_stmt *pStmt;
  148376. int rc;
  148377. assert( iIndex>=0 && iIndex<p->nIndex );
  148378. /* Set pStmt to the compiled version of:
  148379. **
  148380. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  148381. **
  148382. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  148383. */
  148384. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  148385. if( rc!=SQLITE_OK ) return rc;
  148386. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  148387. sqlite3_bind_int64(pStmt, 2,
  148388. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  148389. );
  148390. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  148391. *pnMax = sqlite3_column_int64(pStmt, 0);
  148392. }
  148393. return sqlite3_reset(pStmt);
  148394. }
  148395. /*
  148396. ** iAbsLevel is an absolute level that may be assumed to exist within
  148397. ** the database. This function checks if it is the largest level number
  148398. ** within its index. Assuming no error occurs, *pbMax is set to 1 if
  148399. ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
  148400. ** is returned. If an error occurs, an error code is returned and the
  148401. ** final value of *pbMax is undefined.
  148402. */
  148403. static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
  148404. /* Set pStmt to the compiled version of:
  148405. **
  148406. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  148407. **
  148408. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  148409. */
  148410. sqlite3_stmt *pStmt;
  148411. int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  148412. if( rc!=SQLITE_OK ) return rc;
  148413. sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
  148414. sqlite3_bind_int64(pStmt, 2,
  148415. ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
  148416. );
  148417. *pbMax = 0;
  148418. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  148419. *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
  148420. }
  148421. return sqlite3_reset(pStmt);
  148422. }
  148423. /*
  148424. ** Delete all entries in the %_segments table associated with the segment
  148425. ** opened with seg-reader pSeg. This function does not affect the contents
  148426. ** of the %_segdir table.
  148427. */
  148428. static int fts3DeleteSegment(
  148429. Fts3Table *p, /* FTS table handle */
  148430. Fts3SegReader *pSeg /* Segment to delete */
  148431. ){
  148432. int rc = SQLITE_OK; /* Return code */
  148433. if( pSeg->iStartBlock ){
  148434. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  148435. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  148436. if( rc==SQLITE_OK ){
  148437. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  148438. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  148439. sqlite3_step(pDelete);
  148440. rc = sqlite3_reset(pDelete);
  148441. }
  148442. }
  148443. return rc;
  148444. }
  148445. /*
  148446. ** This function is used after merging multiple segments into a single large
  148447. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  148448. ** it:
  148449. **
  148450. ** 1) Deletes all %_segments entries for the segments associated with
  148451. ** each of the SegReader objects in the array passed as the third
  148452. ** argument, and
  148453. **
  148454. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  148455. ** entries regardless of level if (iLevel<0).
  148456. **
  148457. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  148458. */
  148459. static int fts3DeleteSegdir(
  148460. Fts3Table *p, /* Virtual table handle */
  148461. int iLangid, /* Language id */
  148462. int iIndex, /* Index for p->aIndex */
  148463. int iLevel, /* Level of %_segdir entries to delete */
  148464. Fts3SegReader **apSegment, /* Array of SegReader objects */
  148465. int nReader /* Size of array apSegment */
  148466. ){
  148467. int rc = SQLITE_OK; /* Return Code */
  148468. int i; /* Iterator variable */
  148469. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  148470. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  148471. rc = fts3DeleteSegment(p, apSegment[i]);
  148472. }
  148473. if( rc!=SQLITE_OK ){
  148474. return rc;
  148475. }
  148476. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  148477. if( iLevel==FTS3_SEGCURSOR_ALL ){
  148478. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  148479. if( rc==SQLITE_OK ){
  148480. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  148481. sqlite3_bind_int64(pDelete, 2,
  148482. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  148483. );
  148484. }
  148485. }else{
  148486. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  148487. if( rc==SQLITE_OK ){
  148488. sqlite3_bind_int64(
  148489. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  148490. );
  148491. }
  148492. }
  148493. if( rc==SQLITE_OK ){
  148494. sqlite3_step(pDelete);
  148495. rc = sqlite3_reset(pDelete);
  148496. }
  148497. return rc;
  148498. }
  148499. /*
  148500. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  148501. ** a position list that may (or may not) feature multiple columns. This
  148502. ** function adjusts the pointer *ppList and the length *pnList so that they
  148503. ** identify the subset of the position list that corresponds to column iCol.
  148504. **
  148505. ** If there are no entries in the input position list for column iCol, then
  148506. ** *pnList is set to zero before returning.
  148507. **
  148508. ** If parameter bZero is non-zero, then any part of the input list following
  148509. ** the end of the output list is zeroed before returning.
  148510. */
  148511. static void fts3ColumnFilter(
  148512. int iCol, /* Column to filter on */
  148513. int bZero, /* Zero out anything following *ppList */
  148514. char **ppList, /* IN/OUT: Pointer to position list */
  148515. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  148516. ){
  148517. char *pList = *ppList;
  148518. int nList = *pnList;
  148519. char *pEnd = &pList[nList];
  148520. int iCurrent = 0;
  148521. char *p = pList;
  148522. assert( iCol>=0 );
  148523. while( 1 ){
  148524. char c = 0;
  148525. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  148526. if( iCol==iCurrent ){
  148527. nList = (int)(p - pList);
  148528. break;
  148529. }
  148530. nList -= (int)(p - pList);
  148531. pList = p;
  148532. if( nList==0 ){
  148533. break;
  148534. }
  148535. p = &pList[1];
  148536. p += fts3GetVarint32(p, &iCurrent);
  148537. }
  148538. if( bZero && &pList[nList]!=pEnd ){
  148539. memset(&pList[nList], 0, pEnd - &pList[nList]);
  148540. }
  148541. *ppList = pList;
  148542. *pnList = nList;
  148543. }
  148544. /*
  148545. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  148546. ** existing data). Grow the buffer if required.
  148547. **
  148548. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  148549. ** trying to resize the buffer, return SQLITE_NOMEM.
  148550. */
  148551. static int fts3MsrBufferData(
  148552. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  148553. char *pList,
  148554. int nList
  148555. ){
  148556. if( nList>pMsr->nBuffer ){
  148557. char *pNew;
  148558. pMsr->nBuffer = nList*2;
  148559. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  148560. if( !pNew ) return SQLITE_NOMEM;
  148561. pMsr->aBuffer = pNew;
  148562. }
  148563. memcpy(pMsr->aBuffer, pList, nList);
  148564. return SQLITE_OK;
  148565. }
  148566. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  148567. Fts3Table *p, /* Virtual table handle */
  148568. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  148569. sqlite3_int64 *piDocid, /* OUT: Docid value */
  148570. char **paPoslist, /* OUT: Pointer to position list */
  148571. int *pnPoslist /* OUT: Size of position list in bytes */
  148572. ){
  148573. int nMerge = pMsr->nAdvance;
  148574. Fts3SegReader **apSegment = pMsr->apSegment;
  148575. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  148576. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  148577. );
  148578. if( nMerge==0 ){
  148579. *paPoslist = 0;
  148580. return SQLITE_OK;
  148581. }
  148582. while( 1 ){
  148583. Fts3SegReader *pSeg;
  148584. pSeg = pMsr->apSegment[0];
  148585. if( pSeg->pOffsetList==0 ){
  148586. *paPoslist = 0;
  148587. break;
  148588. }else{
  148589. int rc;
  148590. char *pList;
  148591. int nList;
  148592. int j;
  148593. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  148594. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  148595. j = 1;
  148596. while( rc==SQLITE_OK
  148597. && j<nMerge
  148598. && apSegment[j]->pOffsetList
  148599. && apSegment[j]->iDocid==iDocid
  148600. ){
  148601. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  148602. j++;
  148603. }
  148604. if( rc!=SQLITE_OK ) return rc;
  148605. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  148606. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  148607. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  148608. if( rc!=SQLITE_OK ) return rc;
  148609. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  148610. pList = pMsr->aBuffer;
  148611. }
  148612. if( pMsr->iColFilter>=0 ){
  148613. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  148614. }
  148615. if( nList>0 ){
  148616. *paPoslist = pList;
  148617. *piDocid = iDocid;
  148618. *pnPoslist = nList;
  148619. break;
  148620. }
  148621. }
  148622. }
  148623. return SQLITE_OK;
  148624. }
  148625. static int fts3SegReaderStart(
  148626. Fts3Table *p, /* Virtual table handle */
  148627. Fts3MultiSegReader *pCsr, /* Cursor object */
  148628. const char *zTerm, /* Term searched for (or NULL) */
  148629. int nTerm /* Length of zTerm in bytes */
  148630. ){
  148631. int i;
  148632. int nSeg = pCsr->nSegment;
  148633. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  148634. ** for, then advance each segment iterator until it points to a term of
  148635. ** equal or greater value than the specified term. This prevents many
  148636. ** unnecessary merge/sort operations for the case where single segment
  148637. ** b-tree leaf nodes contain more than one term.
  148638. */
  148639. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  148640. int res = 0;
  148641. Fts3SegReader *pSeg = pCsr->apSegment[i];
  148642. do {
  148643. int rc = fts3SegReaderNext(p, pSeg, 0);
  148644. if( rc!=SQLITE_OK ) return rc;
  148645. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  148646. if( pSeg->bLookup && res!=0 ){
  148647. fts3SegReaderSetEof(pSeg);
  148648. }
  148649. }
  148650. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  148651. return SQLITE_OK;
  148652. }
  148653. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  148654. Fts3Table *p, /* Virtual table handle */
  148655. Fts3MultiSegReader *pCsr, /* Cursor object */
  148656. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  148657. ){
  148658. pCsr->pFilter = pFilter;
  148659. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  148660. }
  148661. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  148662. Fts3Table *p, /* Virtual table handle */
  148663. Fts3MultiSegReader *pCsr, /* Cursor object */
  148664. int iCol, /* Column to match on. */
  148665. const char *zTerm, /* Term to iterate through a doclist for */
  148666. int nTerm /* Number of bytes in zTerm */
  148667. ){
  148668. int i;
  148669. int rc;
  148670. int nSegment = pCsr->nSegment;
  148671. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  148672. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  148673. );
  148674. assert( pCsr->pFilter==0 );
  148675. assert( zTerm && nTerm>0 );
  148676. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  148677. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  148678. if( rc!=SQLITE_OK ) return rc;
  148679. /* Determine how many of the segments actually point to zTerm/nTerm. */
  148680. for(i=0; i<nSegment; i++){
  148681. Fts3SegReader *pSeg = pCsr->apSegment[i];
  148682. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  148683. break;
  148684. }
  148685. }
  148686. pCsr->nAdvance = i;
  148687. /* Advance each of the segments to point to the first docid. */
  148688. for(i=0; i<pCsr->nAdvance; i++){
  148689. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  148690. if( rc!=SQLITE_OK ) return rc;
  148691. }
  148692. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  148693. assert( iCol<0 || iCol<p->nColumn );
  148694. pCsr->iColFilter = iCol;
  148695. return SQLITE_OK;
  148696. }
  148697. /*
  148698. ** This function is called on a MultiSegReader that has been started using
  148699. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  148700. ** have been made. Calling this function puts the MultiSegReader in such
  148701. ** a state that if the next two calls are:
  148702. **
  148703. ** sqlite3Fts3SegReaderStart()
  148704. ** sqlite3Fts3SegReaderStep()
  148705. **
  148706. ** then the entire doclist for the term is available in
  148707. ** MultiSegReader.aDoclist/nDoclist.
  148708. */
  148709. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  148710. int i; /* Used to iterate through segment-readers */
  148711. assert( pCsr->zTerm==0 );
  148712. assert( pCsr->nTerm==0 );
  148713. assert( pCsr->aDoclist==0 );
  148714. assert( pCsr->nDoclist==0 );
  148715. pCsr->nAdvance = 0;
  148716. pCsr->bRestart = 1;
  148717. for(i=0; i<pCsr->nSegment; i++){
  148718. pCsr->apSegment[i]->pOffsetList = 0;
  148719. pCsr->apSegment[i]->nOffsetList = 0;
  148720. pCsr->apSegment[i]->iDocid = 0;
  148721. }
  148722. return SQLITE_OK;
  148723. }
  148724. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  148725. Fts3Table *p, /* Virtual table handle */
  148726. Fts3MultiSegReader *pCsr /* Cursor object */
  148727. ){
  148728. int rc = SQLITE_OK;
  148729. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  148730. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  148731. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  148732. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  148733. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  148734. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  148735. Fts3SegReader **apSegment = pCsr->apSegment;
  148736. int nSegment = pCsr->nSegment;
  148737. Fts3SegFilter *pFilter = pCsr->pFilter;
  148738. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  148739. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  148740. );
  148741. if( pCsr->nSegment==0 ) return SQLITE_OK;
  148742. do {
  148743. int nMerge;
  148744. int i;
  148745. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  148746. ** forward. Then sort the list in order of current term again.
  148747. */
  148748. for(i=0; i<pCsr->nAdvance; i++){
  148749. Fts3SegReader *pSeg = apSegment[i];
  148750. if( pSeg->bLookup ){
  148751. fts3SegReaderSetEof(pSeg);
  148752. }else{
  148753. rc = fts3SegReaderNext(p, pSeg, 0);
  148754. }
  148755. if( rc!=SQLITE_OK ) return rc;
  148756. }
  148757. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  148758. pCsr->nAdvance = 0;
  148759. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  148760. assert( rc==SQLITE_OK );
  148761. if( apSegment[0]->aNode==0 ) break;
  148762. pCsr->nTerm = apSegment[0]->nTerm;
  148763. pCsr->zTerm = apSegment[0]->zTerm;
  148764. /* If this is a prefix-search, and if the term that apSegment[0] points
  148765. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  148766. ** required callbacks have been made. In this case exit early.
  148767. **
  148768. ** Similarly, if this is a search for an exact match, and the first term
  148769. ** of segment apSegment[0] is not a match, exit early.
  148770. */
  148771. if( pFilter->zTerm && !isScan ){
  148772. if( pCsr->nTerm<pFilter->nTerm
  148773. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  148774. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  148775. ){
  148776. break;
  148777. }
  148778. }
  148779. nMerge = 1;
  148780. while( nMerge<nSegment
  148781. && apSegment[nMerge]->aNode
  148782. && apSegment[nMerge]->nTerm==pCsr->nTerm
  148783. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  148784. ){
  148785. nMerge++;
  148786. }
  148787. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  148788. if( nMerge==1
  148789. && !isIgnoreEmpty
  148790. && !isFirst
  148791. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  148792. ){
  148793. pCsr->nDoclist = apSegment[0]->nDoclist;
  148794. if( fts3SegReaderIsPending(apSegment[0]) ){
  148795. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  148796. pCsr->aDoclist = pCsr->aBuffer;
  148797. }else{
  148798. pCsr->aDoclist = apSegment[0]->aDoclist;
  148799. }
  148800. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  148801. }else{
  148802. int nDoclist = 0; /* Size of doclist */
  148803. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  148804. /* The current term of the first nMerge entries in the array
  148805. ** of Fts3SegReader objects is the same. The doclists must be merged
  148806. ** and a single term returned with the merged doclist.
  148807. */
  148808. for(i=0; i<nMerge; i++){
  148809. fts3SegReaderFirstDocid(p, apSegment[i]);
  148810. }
  148811. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  148812. while( apSegment[0]->pOffsetList ){
  148813. int j; /* Number of segments that share a docid */
  148814. char *pList = 0;
  148815. int nList = 0;
  148816. int nByte;
  148817. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  148818. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  148819. j = 1;
  148820. while( j<nMerge
  148821. && apSegment[j]->pOffsetList
  148822. && apSegment[j]->iDocid==iDocid
  148823. ){
  148824. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  148825. j++;
  148826. }
  148827. if( isColFilter ){
  148828. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  148829. }
  148830. if( !isIgnoreEmpty || nList>0 ){
  148831. /* Calculate the 'docid' delta value to write into the merged
  148832. ** doclist. */
  148833. sqlite3_int64 iDelta;
  148834. if( p->bDescIdx && nDoclist>0 ){
  148835. iDelta = iPrev - iDocid;
  148836. }else{
  148837. iDelta = iDocid - iPrev;
  148838. }
  148839. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  148840. assert( nDoclist>0 || iDelta==iDocid );
  148841. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  148842. if( nDoclist+nByte>pCsr->nBuffer ){
  148843. char *aNew;
  148844. pCsr->nBuffer = (nDoclist+nByte)*2;
  148845. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  148846. if( !aNew ){
  148847. return SQLITE_NOMEM;
  148848. }
  148849. pCsr->aBuffer = aNew;
  148850. }
  148851. if( isFirst ){
  148852. char *a = &pCsr->aBuffer[nDoclist];
  148853. int nWrite;
  148854. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  148855. if( nWrite ){
  148856. iPrev = iDocid;
  148857. nDoclist += nWrite;
  148858. }
  148859. }else{
  148860. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  148861. iPrev = iDocid;
  148862. if( isRequirePos ){
  148863. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  148864. nDoclist += nList;
  148865. pCsr->aBuffer[nDoclist++] = '\0';
  148866. }
  148867. }
  148868. }
  148869. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  148870. }
  148871. if( nDoclist>0 ){
  148872. pCsr->aDoclist = pCsr->aBuffer;
  148873. pCsr->nDoclist = nDoclist;
  148874. rc = SQLITE_ROW;
  148875. }
  148876. }
  148877. pCsr->nAdvance = nMerge;
  148878. }while( rc==SQLITE_OK );
  148879. return rc;
  148880. }
  148881. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  148882. Fts3MultiSegReader *pCsr /* Cursor object */
  148883. ){
  148884. if( pCsr ){
  148885. int i;
  148886. for(i=0; i<pCsr->nSegment; i++){
  148887. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  148888. }
  148889. sqlite3_free(pCsr->apSegment);
  148890. sqlite3_free(pCsr->aBuffer);
  148891. pCsr->nSegment = 0;
  148892. pCsr->apSegment = 0;
  148893. pCsr->aBuffer = 0;
  148894. }
  148895. }
  148896. /*
  148897. ** Decode the "end_block" field, selected by column iCol of the SELECT
  148898. ** statement passed as the first argument.
  148899. **
  148900. ** The "end_block" field may contain either an integer, or a text field
  148901. ** containing the text representation of two non-negative integers separated
  148902. ** by one or more space (0x20) characters. In the first case, set *piEndBlock
  148903. ** to the integer value and *pnByte to zero before returning. In the second,
  148904. ** set *piEndBlock to the first value and *pnByte to the second.
  148905. */
  148906. static void fts3ReadEndBlockField(
  148907. sqlite3_stmt *pStmt,
  148908. int iCol,
  148909. i64 *piEndBlock,
  148910. i64 *pnByte
  148911. ){
  148912. const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
  148913. if( zText ){
  148914. int i;
  148915. int iMul = 1;
  148916. i64 iVal = 0;
  148917. for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
  148918. iVal = iVal*10 + (zText[i] - '0');
  148919. }
  148920. *piEndBlock = iVal;
  148921. while( zText[i]==' ' ) i++;
  148922. iVal = 0;
  148923. if( zText[i]=='-' ){
  148924. i++;
  148925. iMul = -1;
  148926. }
  148927. for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
  148928. iVal = iVal*10 + (zText[i] - '0');
  148929. }
  148930. *pnByte = (iVal * (i64)iMul);
  148931. }
  148932. }
  148933. /*
  148934. ** A segment of size nByte bytes has just been written to absolute level
  148935. ** iAbsLevel. Promote any segments that should be promoted as a result.
  148936. */
  148937. static int fts3PromoteSegments(
  148938. Fts3Table *p, /* FTS table handle */
  148939. sqlite3_int64 iAbsLevel, /* Absolute level just updated */
  148940. sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
  148941. ){
  148942. int rc = SQLITE_OK;
  148943. sqlite3_stmt *pRange;
  148944. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
  148945. if( rc==SQLITE_OK ){
  148946. int bOk = 0;
  148947. i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
  148948. i64 nLimit = (nByte*3)/2;
  148949. /* Loop through all entries in the %_segdir table corresponding to
  148950. ** segments in this index on levels greater than iAbsLevel. If there is
  148951. ** at least one such segment, and it is possible to determine that all
  148952. ** such segments are smaller than nLimit bytes in size, they will be
  148953. ** promoted to level iAbsLevel. */
  148954. sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
  148955. sqlite3_bind_int64(pRange, 2, iLast);
  148956. while( SQLITE_ROW==sqlite3_step(pRange) ){
  148957. i64 nSize = 0, dummy;
  148958. fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
  148959. if( nSize<=0 || nSize>nLimit ){
  148960. /* If nSize==0, then the %_segdir.end_block field does not not
  148961. ** contain a size value. This happens if it was written by an
  148962. ** old version of FTS. In this case it is not possible to determine
  148963. ** the size of the segment, and so segment promotion does not
  148964. ** take place. */
  148965. bOk = 0;
  148966. break;
  148967. }
  148968. bOk = 1;
  148969. }
  148970. rc = sqlite3_reset(pRange);
  148971. if( bOk ){
  148972. int iIdx = 0;
  148973. sqlite3_stmt *pUpdate1 = 0;
  148974. sqlite3_stmt *pUpdate2 = 0;
  148975. if( rc==SQLITE_OK ){
  148976. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
  148977. }
  148978. if( rc==SQLITE_OK ){
  148979. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
  148980. }
  148981. if( rc==SQLITE_OK ){
  148982. /* Loop through all %_segdir entries for segments in this index with
  148983. ** levels equal to or greater than iAbsLevel. As each entry is visited,
  148984. ** updated it to set (level = -1) and (idx = N), where N is 0 for the
  148985. ** oldest segment in the range, 1 for the next oldest, and so on.
  148986. **
  148987. ** In other words, move all segments being promoted to level -1,
  148988. ** setting the "idx" fields as appropriate to keep them in the same
  148989. ** order. The contents of level -1 (which is never used, except
  148990. ** transiently here), will be moved back to level iAbsLevel below. */
  148991. sqlite3_bind_int64(pRange, 1, iAbsLevel);
  148992. while( SQLITE_ROW==sqlite3_step(pRange) ){
  148993. sqlite3_bind_int(pUpdate1, 1, iIdx++);
  148994. sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
  148995. sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
  148996. sqlite3_step(pUpdate1);
  148997. rc = sqlite3_reset(pUpdate1);
  148998. if( rc!=SQLITE_OK ){
  148999. sqlite3_reset(pRange);
  149000. break;
  149001. }
  149002. }
  149003. }
  149004. if( rc==SQLITE_OK ){
  149005. rc = sqlite3_reset(pRange);
  149006. }
  149007. /* Move level -1 to level iAbsLevel */
  149008. if( rc==SQLITE_OK ){
  149009. sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
  149010. sqlite3_step(pUpdate2);
  149011. rc = sqlite3_reset(pUpdate2);
  149012. }
  149013. }
  149014. }
  149015. return rc;
  149016. }
  149017. /*
  149018. ** Merge all level iLevel segments in the database into a single
  149019. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  149020. ** single segment with a level equal to the numerically largest level
  149021. ** currently present in the database.
  149022. **
  149023. ** If this function is called with iLevel<0, but there is only one
  149024. ** segment in the database, SQLITE_DONE is returned immediately.
  149025. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  149026. ** an SQLite error code is returned.
  149027. */
  149028. static int fts3SegmentMerge(
  149029. Fts3Table *p,
  149030. int iLangid, /* Language id to merge */
  149031. int iIndex, /* Index in p->aIndex[] to merge */
  149032. int iLevel /* Level to merge */
  149033. ){
  149034. int rc; /* Return code */
  149035. int iIdx = 0; /* Index of new segment */
  149036. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  149037. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  149038. Fts3SegFilter filter; /* Segment term filter condition */
  149039. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  149040. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  149041. i64 iMaxLevel = 0; /* Max level number for this index/langid */
  149042. assert( iLevel==FTS3_SEGCURSOR_ALL
  149043. || iLevel==FTS3_SEGCURSOR_PENDING
  149044. || iLevel>=0
  149045. );
  149046. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  149047. assert( iIndex>=0 && iIndex<p->nIndex );
  149048. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  149049. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  149050. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  149051. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
  149052. if( rc!=SQLITE_OK ) goto finished;
  149053. }
  149054. if( iLevel==FTS3_SEGCURSOR_ALL ){
  149055. /* This call is to merge all segments in the database to a single
  149056. ** segment. The level of the new segment is equal to the numerically
  149057. ** greatest segment level currently present in the database for this
  149058. ** index. The idx of the new segment is always 0. */
  149059. if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
  149060. rc = SQLITE_DONE;
  149061. goto finished;
  149062. }
  149063. iNewLevel = iMaxLevel;
  149064. bIgnoreEmpty = 1;
  149065. }else{
  149066. /* This call is to merge all segments at level iLevel. find the next
  149067. ** available segment index at level iLevel+1. The call to
  149068. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  149069. ** a single iLevel+2 segment if necessary. */
  149070. assert( FTS3_SEGCURSOR_PENDING==-1 );
  149071. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  149072. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  149073. bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
  149074. }
  149075. if( rc!=SQLITE_OK ) goto finished;
  149076. assert( csr.nSegment>0 );
  149077. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  149078. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  149079. memset(&filter, 0, sizeof(Fts3SegFilter));
  149080. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  149081. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  149082. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  149083. while( SQLITE_OK==rc ){
  149084. rc = sqlite3Fts3SegReaderStep(p, &csr);
  149085. if( rc!=SQLITE_ROW ) break;
  149086. rc = fts3SegWriterAdd(p, &pWriter, 1,
  149087. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  149088. }
  149089. if( rc!=SQLITE_OK ) goto finished;
  149090. assert( pWriter || bIgnoreEmpty );
  149091. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  149092. rc = fts3DeleteSegdir(
  149093. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  149094. );
  149095. if( rc!=SQLITE_OK ) goto finished;
  149096. }
  149097. if( pWriter ){
  149098. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  149099. if( rc==SQLITE_OK ){
  149100. if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
  149101. rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
  149102. }
  149103. }
  149104. }
  149105. finished:
  149106. fts3SegWriterFree(pWriter);
  149107. sqlite3Fts3SegReaderFinish(&csr);
  149108. return rc;
  149109. }
  149110. /*
  149111. ** Flush the contents of pendingTerms to level 0 segments.
  149112. */
  149113. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  149114. int rc = SQLITE_OK;
  149115. int i;
  149116. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  149117. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  149118. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  149119. }
  149120. sqlite3Fts3PendingTermsClear(p);
  149121. /* Determine the auto-incr-merge setting if unknown. If enabled,
  149122. ** estimate the number of leaf blocks of content to be written
  149123. */
  149124. if( rc==SQLITE_OK && p->bHasStat
  149125. && p->nAutoincrmerge==0xff && p->nLeafAdd>0
  149126. ){
  149127. sqlite3_stmt *pStmt = 0;
  149128. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  149129. if( rc==SQLITE_OK ){
  149130. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  149131. rc = sqlite3_step(pStmt);
  149132. if( rc==SQLITE_ROW ){
  149133. p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
  149134. if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
  149135. }else if( rc==SQLITE_DONE ){
  149136. p->nAutoincrmerge = 0;
  149137. }
  149138. rc = sqlite3_reset(pStmt);
  149139. }
  149140. }
  149141. return rc;
  149142. }
  149143. /*
  149144. ** Encode N integers as varints into a blob.
  149145. */
  149146. static void fts3EncodeIntArray(
  149147. int N, /* The number of integers to encode */
  149148. u32 *a, /* The integer values */
  149149. char *zBuf, /* Write the BLOB here */
  149150. int *pNBuf /* Write number of bytes if zBuf[] used here */
  149151. ){
  149152. int i, j;
  149153. for(i=j=0; i<N; i++){
  149154. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  149155. }
  149156. *pNBuf = j;
  149157. }
  149158. /*
  149159. ** Decode a blob of varints into N integers
  149160. */
  149161. static void fts3DecodeIntArray(
  149162. int N, /* The number of integers to decode */
  149163. u32 *a, /* Write the integer values */
  149164. const char *zBuf, /* The BLOB containing the varints */
  149165. int nBuf /* size of the BLOB */
  149166. ){
  149167. int i, j;
  149168. UNUSED_PARAMETER(nBuf);
  149169. for(i=j=0; i<N; i++){
  149170. sqlite3_int64 x;
  149171. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  149172. assert(j<=nBuf);
  149173. a[i] = (u32)(x & 0xffffffff);
  149174. }
  149175. }
  149176. /*
  149177. ** Insert the sizes (in tokens) for each column of the document
  149178. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  149179. ** a blob of varints.
  149180. */
  149181. static void fts3InsertDocsize(
  149182. int *pRC, /* Result code */
  149183. Fts3Table *p, /* Table into which to insert */
  149184. u32 *aSz /* Sizes of each column, in tokens */
  149185. ){
  149186. char *pBlob; /* The BLOB encoding of the document size */
  149187. int nBlob; /* Number of bytes in the BLOB */
  149188. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  149189. int rc; /* Result code from subfunctions */
  149190. if( *pRC ) return;
  149191. pBlob = sqlite3_malloc( 10*p->nColumn );
  149192. if( pBlob==0 ){
  149193. *pRC = SQLITE_NOMEM;
  149194. return;
  149195. }
  149196. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  149197. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  149198. if( rc ){
  149199. sqlite3_free(pBlob);
  149200. *pRC = rc;
  149201. return;
  149202. }
  149203. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  149204. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  149205. sqlite3_step(pStmt);
  149206. *pRC = sqlite3_reset(pStmt);
  149207. }
  149208. /*
  149209. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  149210. ** where N is the number of user defined columns in the fts3 table plus
  149211. ** two. If nCol is the number of user defined columns, then values of the
  149212. ** varints are set as follows:
  149213. **
  149214. ** Varint 0: Total number of rows in the table.
  149215. **
  149216. ** Varint 1..nCol: For each column, the total number of tokens stored in
  149217. ** the column for all rows of the table.
  149218. **
  149219. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  149220. ** columns of all rows of the table.
  149221. **
  149222. */
  149223. static void fts3UpdateDocTotals(
  149224. int *pRC, /* The result code */
  149225. Fts3Table *p, /* Table being updated */
  149226. u32 *aSzIns, /* Size increases */
  149227. u32 *aSzDel, /* Size decreases */
  149228. int nChng /* Change in the number of documents */
  149229. ){
  149230. char *pBlob; /* Storage for BLOB written into %_stat */
  149231. int nBlob; /* Size of BLOB written into %_stat */
  149232. u32 *a; /* Array of integers that becomes the BLOB */
  149233. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  149234. int i; /* Loop counter */
  149235. int rc; /* Result code from subfunctions */
  149236. const int nStat = p->nColumn+2;
  149237. if( *pRC ) return;
  149238. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  149239. if( a==0 ){
  149240. *pRC = SQLITE_NOMEM;
  149241. return;
  149242. }
  149243. pBlob = (char*)&a[nStat];
  149244. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  149245. if( rc ){
  149246. sqlite3_free(a);
  149247. *pRC = rc;
  149248. return;
  149249. }
  149250. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  149251. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  149252. fts3DecodeIntArray(nStat, a,
  149253. sqlite3_column_blob(pStmt, 0),
  149254. sqlite3_column_bytes(pStmt, 0));
  149255. }else{
  149256. memset(a, 0, sizeof(u32)*(nStat) );
  149257. }
  149258. rc = sqlite3_reset(pStmt);
  149259. if( rc!=SQLITE_OK ){
  149260. sqlite3_free(a);
  149261. *pRC = rc;
  149262. return;
  149263. }
  149264. if( nChng<0 && a[0]<(u32)(-nChng) ){
  149265. a[0] = 0;
  149266. }else{
  149267. a[0] += nChng;
  149268. }
  149269. for(i=0; i<p->nColumn+1; i++){
  149270. u32 x = a[i+1];
  149271. if( x+aSzIns[i] < aSzDel[i] ){
  149272. x = 0;
  149273. }else{
  149274. x = x + aSzIns[i] - aSzDel[i];
  149275. }
  149276. a[i+1] = x;
  149277. }
  149278. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  149279. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  149280. if( rc ){
  149281. sqlite3_free(a);
  149282. *pRC = rc;
  149283. return;
  149284. }
  149285. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  149286. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  149287. sqlite3_step(pStmt);
  149288. *pRC = sqlite3_reset(pStmt);
  149289. sqlite3_free(a);
  149290. }
  149291. /*
  149292. ** Merge the entire database so that there is one segment for each
  149293. ** iIndex/iLangid combination.
  149294. */
  149295. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  149296. int bSeenDone = 0;
  149297. int rc;
  149298. sqlite3_stmt *pAllLangid = 0;
  149299. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  149300. if( rc==SQLITE_OK ){
  149301. int rc2;
  149302. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  149303. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  149304. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  149305. int i;
  149306. int iLangid = sqlite3_column_int(pAllLangid, 0);
  149307. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  149308. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  149309. if( rc==SQLITE_DONE ){
  149310. bSeenDone = 1;
  149311. rc = SQLITE_OK;
  149312. }
  149313. }
  149314. }
  149315. rc2 = sqlite3_reset(pAllLangid);
  149316. if( rc==SQLITE_OK ) rc = rc2;
  149317. }
  149318. sqlite3Fts3SegmentsClose(p);
  149319. sqlite3Fts3PendingTermsClear(p);
  149320. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  149321. }
  149322. /*
  149323. ** This function is called when the user executes the following statement:
  149324. **
  149325. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  149326. **
  149327. ** The entire FTS index is discarded and rebuilt. If the table is one
  149328. ** created using the content=xxx option, then the new index is based on
  149329. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  149330. ** on the contents of the %_content table.
  149331. */
  149332. static int fts3DoRebuild(Fts3Table *p){
  149333. int rc; /* Return Code */
  149334. rc = fts3DeleteAll(p, 0);
  149335. if( rc==SQLITE_OK ){
  149336. u32 *aSz = 0;
  149337. u32 *aSzIns = 0;
  149338. u32 *aSzDel = 0;
  149339. sqlite3_stmt *pStmt = 0;
  149340. int nEntry = 0;
  149341. /* Compose and prepare an SQL statement to loop through the content table */
  149342. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  149343. if( !zSql ){
  149344. rc = SQLITE_NOMEM;
  149345. }else{
  149346. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  149347. sqlite3_free(zSql);
  149348. }
  149349. if( rc==SQLITE_OK ){
  149350. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  149351. aSz = (u32 *)sqlite3_malloc(nByte);
  149352. if( aSz==0 ){
  149353. rc = SQLITE_NOMEM;
  149354. }else{
  149355. memset(aSz, 0, nByte);
  149356. aSzIns = &aSz[p->nColumn+1];
  149357. aSzDel = &aSzIns[p->nColumn+1];
  149358. }
  149359. }
  149360. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  149361. int iCol;
  149362. int iLangid = langidFromSelect(p, pStmt);
  149363. rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
  149364. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  149365. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  149366. if( p->abNotindexed[iCol]==0 ){
  149367. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  149368. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  149369. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  149370. }
  149371. }
  149372. if( p->bHasDocsize ){
  149373. fts3InsertDocsize(&rc, p, aSz);
  149374. }
  149375. if( rc!=SQLITE_OK ){
  149376. sqlite3_finalize(pStmt);
  149377. pStmt = 0;
  149378. }else{
  149379. nEntry++;
  149380. for(iCol=0; iCol<=p->nColumn; iCol++){
  149381. aSzIns[iCol] += aSz[iCol];
  149382. }
  149383. }
  149384. }
  149385. if( p->bFts4 ){
  149386. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  149387. }
  149388. sqlite3_free(aSz);
  149389. if( pStmt ){
  149390. int rc2 = sqlite3_finalize(pStmt);
  149391. if( rc==SQLITE_OK ){
  149392. rc = rc2;
  149393. }
  149394. }
  149395. }
  149396. return rc;
  149397. }
  149398. /*
  149399. ** This function opens a cursor used to read the input data for an
  149400. ** incremental merge operation. Specifically, it opens a cursor to scan
  149401. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  149402. ** level iAbsLevel.
  149403. */
  149404. static int fts3IncrmergeCsr(
  149405. Fts3Table *p, /* FTS3 table handle */
  149406. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  149407. int nSeg, /* Number of segments to merge */
  149408. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  149409. ){
  149410. int rc; /* Return Code */
  149411. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  149412. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  149413. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  149414. memset(pCsr, 0, sizeof(*pCsr));
  149415. nByte = sizeof(Fts3SegReader *) * nSeg;
  149416. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  149417. if( pCsr->apSegment==0 ){
  149418. rc = SQLITE_NOMEM;
  149419. }else{
  149420. memset(pCsr->apSegment, 0, nByte);
  149421. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  149422. }
  149423. if( rc==SQLITE_OK ){
  149424. int i;
  149425. int rc2;
  149426. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  149427. assert( pCsr->nSegment==0 );
  149428. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  149429. rc = sqlite3Fts3SegReaderNew(i, 0,
  149430. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  149431. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  149432. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  149433. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  149434. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  149435. &pCsr->apSegment[i]
  149436. );
  149437. pCsr->nSegment++;
  149438. }
  149439. rc2 = sqlite3_reset(pStmt);
  149440. if( rc==SQLITE_OK ) rc = rc2;
  149441. }
  149442. return rc;
  149443. }
  149444. typedef struct IncrmergeWriter IncrmergeWriter;
  149445. typedef struct NodeWriter NodeWriter;
  149446. typedef struct Blob Blob;
  149447. typedef struct NodeReader NodeReader;
  149448. /*
  149449. ** An instance of the following structure is used as a dynamic buffer
  149450. ** to build up nodes or other blobs of data in.
  149451. **
  149452. ** The function blobGrowBuffer() is used to extend the allocation.
  149453. */
  149454. struct Blob {
  149455. char *a; /* Pointer to allocation */
  149456. int n; /* Number of valid bytes of data in a[] */
  149457. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  149458. };
  149459. /*
  149460. ** This structure is used to build up buffers containing segment b-tree
  149461. ** nodes (blocks).
  149462. */
  149463. struct NodeWriter {
  149464. sqlite3_int64 iBlock; /* Current block id */
  149465. Blob key; /* Last key written to the current block */
  149466. Blob block; /* Current block image */
  149467. };
  149468. /*
  149469. ** An object of this type contains the state required to create or append
  149470. ** to an appendable b-tree segment.
  149471. */
  149472. struct IncrmergeWriter {
  149473. int nLeafEst; /* Space allocated for leaf blocks */
  149474. int nWork; /* Number of leaf pages flushed */
  149475. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  149476. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  149477. sqlite3_int64 iStart; /* Block number of first allocated block */
  149478. sqlite3_int64 iEnd; /* Block number of last allocated block */
  149479. sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
  149480. u8 bNoLeafData; /* If true, store 0 for segment size */
  149481. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  149482. };
  149483. /*
  149484. ** An object of the following type is used to read data from a single
  149485. ** FTS segment node. See the following functions:
  149486. **
  149487. ** nodeReaderInit()
  149488. ** nodeReaderNext()
  149489. ** nodeReaderRelease()
  149490. */
  149491. struct NodeReader {
  149492. const char *aNode;
  149493. int nNode;
  149494. int iOff; /* Current offset within aNode[] */
  149495. /* Output variables. Containing the current node entry. */
  149496. sqlite3_int64 iChild; /* Pointer to child node */
  149497. Blob term; /* Current term */
  149498. const char *aDoclist; /* Pointer to doclist */
  149499. int nDoclist; /* Size of doclist in bytes */
  149500. };
  149501. /*
  149502. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  149503. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  149504. ** bytes in size, extend (realloc) it to be so.
  149505. **
  149506. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  149507. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  149508. ** to reflect the new size of the pBlob->a[] buffer.
  149509. */
  149510. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  149511. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  149512. int nAlloc = nMin;
  149513. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  149514. if( a ){
  149515. pBlob->nAlloc = nAlloc;
  149516. pBlob->a = a;
  149517. }else{
  149518. *pRc = SQLITE_NOMEM;
  149519. }
  149520. }
  149521. }
  149522. /*
  149523. ** Attempt to advance the node-reader object passed as the first argument to
  149524. ** the next entry on the node.
  149525. **
  149526. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  149527. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  149528. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  149529. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  149530. ** variables for the new entry.
  149531. */
  149532. static int nodeReaderNext(NodeReader *p){
  149533. int bFirst = (p->term.n==0); /* True for first term on the node */
  149534. int nPrefix = 0; /* Bytes to copy from previous term */
  149535. int nSuffix = 0; /* Bytes to append to the prefix */
  149536. int rc = SQLITE_OK; /* Return code */
  149537. assert( p->aNode );
  149538. if( p->iChild && bFirst==0 ) p->iChild++;
  149539. if( p->iOff>=p->nNode ){
  149540. /* EOF */
  149541. p->aNode = 0;
  149542. }else{
  149543. if( bFirst==0 ){
  149544. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  149545. }
  149546. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  149547. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  149548. if( rc==SQLITE_OK ){
  149549. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  149550. p->term.n = nPrefix+nSuffix;
  149551. p->iOff += nSuffix;
  149552. if( p->iChild==0 ){
  149553. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  149554. p->aDoclist = &p->aNode[p->iOff];
  149555. p->iOff += p->nDoclist;
  149556. }
  149557. }
  149558. }
  149559. assert( p->iOff<=p->nNode );
  149560. return rc;
  149561. }
  149562. /*
  149563. ** Release all dynamic resources held by node-reader object *p.
  149564. */
  149565. static void nodeReaderRelease(NodeReader *p){
  149566. sqlite3_free(p->term.a);
  149567. }
  149568. /*
  149569. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  149570. **
  149571. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  149572. ** point to the first entry on the node (if any). Otherwise, an SQLite
  149573. ** error code is returned.
  149574. */
  149575. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  149576. memset(p, 0, sizeof(NodeReader));
  149577. p->aNode = aNode;
  149578. p->nNode = nNode;
  149579. /* Figure out if this is a leaf or an internal node. */
  149580. if( p->aNode[0] ){
  149581. /* An internal node. */
  149582. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  149583. }else{
  149584. p->iOff = 1;
  149585. }
  149586. return nodeReaderNext(p);
  149587. }
  149588. /*
  149589. ** This function is called while writing an FTS segment each time a leaf o
  149590. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  149591. ** to be greater than the largest key on the node just written, but smaller
  149592. ** than or equal to the first key that will be written to the next leaf
  149593. ** node.
  149594. **
  149595. ** The block id of the leaf node just written to disk may be found in
  149596. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  149597. */
  149598. static int fts3IncrmergePush(
  149599. Fts3Table *p, /* Fts3 table handle */
  149600. IncrmergeWriter *pWriter, /* Writer object */
  149601. const char *zTerm, /* Term to write to internal node */
  149602. int nTerm /* Bytes at zTerm */
  149603. ){
  149604. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  149605. int iLayer;
  149606. assert( nTerm>0 );
  149607. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  149608. sqlite3_int64 iNextPtr = 0;
  149609. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  149610. int rc = SQLITE_OK;
  149611. int nPrefix;
  149612. int nSuffix;
  149613. int nSpace;
  149614. /* Figure out how much space the key will consume if it is written to
  149615. ** the current node of layer iLayer. Due to the prefix compression,
  149616. ** the space required changes depending on which node the key is to
  149617. ** be added to. */
  149618. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  149619. nSuffix = nTerm - nPrefix;
  149620. nSpace = sqlite3Fts3VarintLen(nPrefix);
  149621. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  149622. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  149623. /* If the current node of layer iLayer contains zero keys, or if adding
  149624. ** the key to it will not cause it to grow to larger than nNodeSize
  149625. ** bytes in size, write the key here. */
  149626. Blob *pBlk = &pNode->block;
  149627. if( pBlk->n==0 ){
  149628. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  149629. if( rc==SQLITE_OK ){
  149630. pBlk->a[0] = (char)iLayer;
  149631. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  149632. }
  149633. }
  149634. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  149635. blobGrowBuffer(&pNode->key, nTerm, &rc);
  149636. if( rc==SQLITE_OK ){
  149637. if( pNode->key.n ){
  149638. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  149639. }
  149640. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  149641. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  149642. pBlk->n += nSuffix;
  149643. memcpy(pNode->key.a, zTerm, nTerm);
  149644. pNode->key.n = nTerm;
  149645. }
  149646. }else{
  149647. /* Otherwise, flush the current node of layer iLayer to disk.
  149648. ** Then allocate a new, empty sibling node. The key will be written
  149649. ** into the parent of this node. */
  149650. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  149651. assert( pNode->block.nAlloc>=p->nNodeSize );
  149652. pNode->block.a[0] = (char)iLayer;
  149653. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  149654. iNextPtr = pNode->iBlock;
  149655. pNode->iBlock++;
  149656. pNode->key.n = 0;
  149657. }
  149658. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  149659. iPtr = iNextPtr;
  149660. }
  149661. assert( 0 );
  149662. return 0;
  149663. }
  149664. /*
  149665. ** Append a term and (optionally) doclist to the FTS segment node currently
  149666. ** stored in blob *pNode. The node need not contain any terms, but the
  149667. ** header must be written before this function is called.
  149668. **
  149669. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  149670. ** followed by the left-hand-child varint for an internal node.
  149671. **
  149672. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  149673. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  149674. ** node, both aDoclist and nDoclist must be passed 0.
  149675. **
  149676. ** If the size of the value in blob pPrev is zero, then this is the first
  149677. ** term written to the node. Otherwise, pPrev contains a copy of the
  149678. ** previous term. Before this function returns, it is updated to contain a
  149679. ** copy of zTerm/nTerm.
  149680. **
  149681. ** It is assumed that the buffer associated with pNode is already large
  149682. ** enough to accommodate the new entry. The buffer associated with pPrev
  149683. ** is extended by this function if requrired.
  149684. **
  149685. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  149686. ** returned. Otherwise, SQLITE_OK.
  149687. */
  149688. static int fts3AppendToNode(
  149689. Blob *pNode, /* Current node image to append to */
  149690. Blob *pPrev, /* Buffer containing previous term written */
  149691. const char *zTerm, /* New term to write */
  149692. int nTerm, /* Size of zTerm in bytes */
  149693. const char *aDoclist, /* Doclist (or NULL) to write */
  149694. int nDoclist /* Size of aDoclist in bytes */
  149695. ){
  149696. int rc = SQLITE_OK; /* Return code */
  149697. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  149698. int nPrefix; /* Size of term prefix in bytes */
  149699. int nSuffix; /* Size of term suffix in bytes */
  149700. /* Node must have already been started. There must be a doclist for a
  149701. ** leaf node, and there must not be a doclist for an internal node. */
  149702. assert( pNode->n>0 );
  149703. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  149704. blobGrowBuffer(pPrev, nTerm, &rc);
  149705. if( rc!=SQLITE_OK ) return rc;
  149706. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  149707. nSuffix = nTerm - nPrefix;
  149708. memcpy(pPrev->a, zTerm, nTerm);
  149709. pPrev->n = nTerm;
  149710. if( bFirst==0 ){
  149711. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  149712. }
  149713. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  149714. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  149715. pNode->n += nSuffix;
  149716. if( aDoclist ){
  149717. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  149718. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  149719. pNode->n += nDoclist;
  149720. }
  149721. assert( pNode->n<=pNode->nAlloc );
  149722. return SQLITE_OK;
  149723. }
  149724. /*
  149725. ** Append the current term and doclist pointed to by cursor pCsr to the
  149726. ** appendable b-tree segment opened for writing by pWriter.
  149727. **
  149728. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  149729. */
  149730. static int fts3IncrmergeAppend(
  149731. Fts3Table *p, /* Fts3 table handle */
  149732. IncrmergeWriter *pWriter, /* Writer object */
  149733. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  149734. ){
  149735. const char *zTerm = pCsr->zTerm;
  149736. int nTerm = pCsr->nTerm;
  149737. const char *aDoclist = pCsr->aDoclist;
  149738. int nDoclist = pCsr->nDoclist;
  149739. int rc = SQLITE_OK; /* Return code */
  149740. int nSpace; /* Total space in bytes required on leaf */
  149741. int nPrefix; /* Size of prefix shared with previous term */
  149742. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  149743. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  149744. pLeaf = &pWriter->aNodeWriter[0];
  149745. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  149746. nSuffix = nTerm - nPrefix;
  149747. nSpace = sqlite3Fts3VarintLen(nPrefix);
  149748. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  149749. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  149750. /* If the current block is not empty, and if adding this term/doclist
  149751. ** to the current block would make it larger than Fts3Table.nNodeSize
  149752. ** bytes, write this block out to the database. */
  149753. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  149754. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  149755. pWriter->nWork++;
  149756. /* Add the current term to the parent node. The term added to the
  149757. ** parent must:
  149758. **
  149759. ** a) be greater than the largest term on the leaf node just written
  149760. ** to the database (still available in pLeaf->key), and
  149761. **
  149762. ** b) be less than or equal to the term about to be added to the new
  149763. ** leaf node (zTerm/nTerm).
  149764. **
  149765. ** In other words, it must be the prefix of zTerm 1 byte longer than
  149766. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  149767. */
  149768. if( rc==SQLITE_OK ){
  149769. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  149770. }
  149771. /* Advance to the next output block */
  149772. pLeaf->iBlock++;
  149773. pLeaf->key.n = 0;
  149774. pLeaf->block.n = 0;
  149775. nSuffix = nTerm;
  149776. nSpace = 1;
  149777. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  149778. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  149779. }
  149780. pWriter->nLeafData += nSpace;
  149781. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  149782. if( rc==SQLITE_OK ){
  149783. if( pLeaf->block.n==0 ){
  149784. pLeaf->block.n = 1;
  149785. pLeaf->block.a[0] = '\0';
  149786. }
  149787. rc = fts3AppendToNode(
  149788. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  149789. );
  149790. }
  149791. return rc;
  149792. }
  149793. /*
  149794. ** This function is called to release all dynamic resources held by the
  149795. ** merge-writer object pWriter, and if no error has occurred, to flush
  149796. ** all outstanding node buffers held by pWriter to disk.
  149797. **
  149798. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  149799. ** is made to write any data to disk. Instead, this function serves only
  149800. ** to release outstanding resources.
  149801. **
  149802. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  149803. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  149804. ** returning.
  149805. */
  149806. static void fts3IncrmergeRelease(
  149807. Fts3Table *p, /* FTS3 table handle */
  149808. IncrmergeWriter *pWriter, /* Merge-writer object */
  149809. int *pRc /* IN/OUT: Error code */
  149810. ){
  149811. int i; /* Used to iterate through non-root layers */
  149812. int iRoot; /* Index of root in pWriter->aNodeWriter */
  149813. NodeWriter *pRoot; /* NodeWriter for root node */
  149814. int rc = *pRc; /* Error code */
  149815. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  149816. ** root node. If the segment fits entirely on a single leaf node, iRoot
  149817. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  149818. ** will be 1. And so on. */
  149819. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  149820. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  149821. if( pNode->block.n>0 ) break;
  149822. assert( *pRc || pNode->block.nAlloc==0 );
  149823. assert( *pRc || pNode->key.nAlloc==0 );
  149824. sqlite3_free(pNode->block.a);
  149825. sqlite3_free(pNode->key.a);
  149826. }
  149827. /* Empty output segment. This is a no-op. */
  149828. if( iRoot<0 ) return;
  149829. /* The entire output segment fits on a single node. Normally, this means
  149830. ** the node would be stored as a blob in the "root" column of the %_segdir
  149831. ** table. However, this is not permitted in this case. The problem is that
  149832. ** space has already been reserved in the %_segments table, and so the
  149833. ** start_block and end_block fields of the %_segdir table must be populated.
  149834. ** And, by design or by accident, released versions of FTS cannot handle
  149835. ** segments that fit entirely on the root node with start_block!=0.
  149836. **
  149837. ** Instead, create a synthetic root node that contains nothing but a
  149838. ** pointer to the single content node. So that the segment consists of a
  149839. ** single leaf and a single interior (root) node.
  149840. **
  149841. ** Todo: Better might be to defer allocating space in the %_segments
  149842. ** table until we are sure it is needed.
  149843. */
  149844. if( iRoot==0 ){
  149845. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  149846. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  149847. if( rc==SQLITE_OK ){
  149848. pBlock->a[0] = 0x01;
  149849. pBlock->n = 1 + sqlite3Fts3PutVarint(
  149850. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  149851. );
  149852. }
  149853. iRoot = 1;
  149854. }
  149855. pRoot = &pWriter->aNodeWriter[iRoot];
  149856. /* Flush all currently outstanding nodes to disk. */
  149857. for(i=0; i<iRoot; i++){
  149858. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  149859. if( pNode->block.n>0 && rc==SQLITE_OK ){
  149860. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  149861. }
  149862. sqlite3_free(pNode->block.a);
  149863. sqlite3_free(pNode->key.a);
  149864. }
  149865. /* Write the %_segdir record. */
  149866. if( rc==SQLITE_OK ){
  149867. rc = fts3WriteSegdir(p,
  149868. pWriter->iAbsLevel+1, /* level */
  149869. pWriter->iIdx, /* idx */
  149870. pWriter->iStart, /* start_block */
  149871. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  149872. pWriter->iEnd, /* end_block */
  149873. (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
  149874. pRoot->block.a, pRoot->block.n /* root */
  149875. );
  149876. }
  149877. sqlite3_free(pRoot->block.a);
  149878. sqlite3_free(pRoot->key.a);
  149879. *pRc = rc;
  149880. }
  149881. /*
  149882. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  149883. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  149884. ** the other, it is considered to be smaller than the other.
  149885. **
  149886. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  149887. ** if it is greater.
  149888. */
  149889. static int fts3TermCmp(
  149890. const char *zLhs, int nLhs, /* LHS of comparison */
  149891. const char *zRhs, int nRhs /* RHS of comparison */
  149892. ){
  149893. int nCmp = MIN(nLhs, nRhs);
  149894. int res;
  149895. res = memcmp(zLhs, zRhs, nCmp);
  149896. if( res==0 ) res = nLhs - nRhs;
  149897. return res;
  149898. }
  149899. /*
  149900. ** Query to see if the entry in the %_segments table with blockid iEnd is
  149901. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  149902. ** returning. Otherwise, set *pbRes to 0.
  149903. **
  149904. ** Or, if an error occurs while querying the database, return an SQLite
  149905. ** error code. The final value of *pbRes is undefined in this case.
  149906. **
  149907. ** This is used to test if a segment is an "appendable" segment. If it
  149908. ** is, then a NULL entry has been inserted into the %_segments table
  149909. ** with blockid %_segdir.end_block.
  149910. */
  149911. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  149912. int bRes = 0; /* Result to set *pbRes to */
  149913. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  149914. int rc; /* Return code */
  149915. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  149916. if( rc==SQLITE_OK ){
  149917. sqlite3_bind_int64(pCheck, 1, iEnd);
  149918. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  149919. rc = sqlite3_reset(pCheck);
  149920. }
  149921. *pbRes = bRes;
  149922. return rc;
  149923. }
  149924. /*
  149925. ** This function is called when initializing an incremental-merge operation.
  149926. ** It checks if the existing segment with index value iIdx at absolute level
  149927. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  149928. ** merge-writer object *pWriter is initialized to write to it.
  149929. **
  149930. ** An existing segment can be appended to by an incremental merge if:
  149931. **
  149932. ** * It was initially created as an appendable segment (with all required
  149933. ** space pre-allocated), and
  149934. **
  149935. ** * The first key read from the input (arguments zKey and nKey) is
  149936. ** greater than the largest key currently stored in the potential
  149937. ** output segment.
  149938. */
  149939. static int fts3IncrmergeLoad(
  149940. Fts3Table *p, /* Fts3 table handle */
  149941. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  149942. int iIdx, /* Index of candidate output segment */
  149943. const char *zKey, /* First key to write */
  149944. int nKey, /* Number of bytes in nKey */
  149945. IncrmergeWriter *pWriter /* Populate this object */
  149946. ){
  149947. int rc; /* Return code */
  149948. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  149949. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  149950. if( rc==SQLITE_OK ){
  149951. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  149952. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  149953. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  149954. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  149955. int nRoot = 0; /* Size of aRoot[] in bytes */
  149956. int rc2; /* Return code from sqlite3_reset() */
  149957. int bAppendable = 0; /* Set to true if segment is appendable */
  149958. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  149959. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  149960. sqlite3_bind_int(pSelect, 2, iIdx);
  149961. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  149962. iStart = sqlite3_column_int64(pSelect, 1);
  149963. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  149964. fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
  149965. if( pWriter->nLeafData<0 ){
  149966. pWriter->nLeafData = pWriter->nLeafData * -1;
  149967. }
  149968. pWriter->bNoLeafData = (pWriter->nLeafData==0);
  149969. nRoot = sqlite3_column_bytes(pSelect, 4);
  149970. aRoot = sqlite3_column_blob(pSelect, 4);
  149971. }else{
  149972. return sqlite3_reset(pSelect);
  149973. }
  149974. /* Check for the zero-length marker in the %_segments table */
  149975. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  149976. /* Check that zKey/nKey is larger than the largest key the candidate */
  149977. if( rc==SQLITE_OK && bAppendable ){
  149978. char *aLeaf = 0;
  149979. int nLeaf = 0;
  149980. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  149981. if( rc==SQLITE_OK ){
  149982. NodeReader reader;
  149983. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  149984. rc==SQLITE_OK && reader.aNode;
  149985. rc = nodeReaderNext(&reader)
  149986. ){
  149987. assert( reader.aNode );
  149988. }
  149989. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  149990. bAppendable = 0;
  149991. }
  149992. nodeReaderRelease(&reader);
  149993. }
  149994. sqlite3_free(aLeaf);
  149995. }
  149996. if( rc==SQLITE_OK && bAppendable ){
  149997. /* It is possible to append to this segment. Set up the IncrmergeWriter
  149998. ** object to do so. */
  149999. int i;
  150000. int nHeight = (int)aRoot[0];
  150001. NodeWriter *pNode;
  150002. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  150003. pWriter->iStart = iStart;
  150004. pWriter->iEnd = iEnd;
  150005. pWriter->iAbsLevel = iAbsLevel;
  150006. pWriter->iIdx = iIdx;
  150007. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  150008. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  150009. }
  150010. pNode = &pWriter->aNodeWriter[nHeight];
  150011. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  150012. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  150013. if( rc==SQLITE_OK ){
  150014. memcpy(pNode->block.a, aRoot, nRoot);
  150015. pNode->block.n = nRoot;
  150016. }
  150017. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  150018. NodeReader reader;
  150019. pNode = &pWriter->aNodeWriter[i];
  150020. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  150021. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  150022. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  150023. if( rc==SQLITE_OK ){
  150024. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  150025. pNode->key.n = reader.term.n;
  150026. if( i>0 ){
  150027. char *aBlock = 0;
  150028. int nBlock = 0;
  150029. pNode = &pWriter->aNodeWriter[i-1];
  150030. pNode->iBlock = reader.iChild;
  150031. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  150032. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  150033. if( rc==SQLITE_OK ){
  150034. memcpy(pNode->block.a, aBlock, nBlock);
  150035. pNode->block.n = nBlock;
  150036. }
  150037. sqlite3_free(aBlock);
  150038. }
  150039. }
  150040. nodeReaderRelease(&reader);
  150041. }
  150042. }
  150043. rc2 = sqlite3_reset(pSelect);
  150044. if( rc==SQLITE_OK ) rc = rc2;
  150045. }
  150046. return rc;
  150047. }
  150048. /*
  150049. ** Determine the largest segment index value that exists within absolute
  150050. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  150051. ** one before returning SQLITE_OK. Or, if there are no segments at all
  150052. ** within level iAbsLevel, set *piIdx to zero.
  150053. **
  150054. ** If an error occurs, return an SQLite error code. The final value of
  150055. ** *piIdx is undefined in this case.
  150056. */
  150057. static int fts3IncrmergeOutputIdx(
  150058. Fts3Table *p, /* FTS Table handle */
  150059. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  150060. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  150061. ){
  150062. int rc;
  150063. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  150064. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  150065. if( rc==SQLITE_OK ){
  150066. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  150067. sqlite3_step(pOutputIdx);
  150068. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  150069. rc = sqlite3_reset(pOutputIdx);
  150070. }
  150071. return rc;
  150072. }
  150073. /*
  150074. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  150075. ** with idx value iIdx.
  150076. **
  150077. ** In the %_segdir table, a segment is defined by the values in three
  150078. ** columns:
  150079. **
  150080. ** start_block
  150081. ** leaves_end_block
  150082. ** end_block
  150083. **
  150084. ** When an appendable segment is allocated, it is estimated that the
  150085. ** maximum number of leaf blocks that may be required is the sum of the
  150086. ** number of leaf blocks consumed by the input segments, plus the number
  150087. ** of input segments, multiplied by two. This value is stored in stack
  150088. ** variable nLeafEst.
  150089. **
  150090. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  150091. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  150092. ** array of leaf nodes starts at the first block allocated. The array
  150093. ** of interior nodes that are parents of the leaf nodes start at block
  150094. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  150095. **
  150096. ** In the actual code below, the value "16" is replaced with the
  150097. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  150098. */
  150099. static int fts3IncrmergeWriter(
  150100. Fts3Table *p, /* Fts3 table handle */
  150101. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  150102. int iIdx, /* Index of new output segment */
  150103. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  150104. IncrmergeWriter *pWriter /* Populate this object */
  150105. ){
  150106. int rc; /* Return Code */
  150107. int i; /* Iterator variable */
  150108. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  150109. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  150110. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  150111. /* Calculate nLeafEst. */
  150112. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  150113. if( rc==SQLITE_OK ){
  150114. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  150115. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  150116. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  150117. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  150118. }
  150119. rc = sqlite3_reset(pLeafEst);
  150120. }
  150121. if( rc!=SQLITE_OK ) return rc;
  150122. /* Calculate the first block to use in the output segment */
  150123. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  150124. if( rc==SQLITE_OK ){
  150125. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  150126. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  150127. pWriter->iEnd = pWriter->iStart - 1;
  150128. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  150129. }
  150130. rc = sqlite3_reset(pFirstBlock);
  150131. }
  150132. if( rc!=SQLITE_OK ) return rc;
  150133. /* Insert the marker in the %_segments table to make sure nobody tries
  150134. ** to steal the space just allocated. This is also used to identify
  150135. ** appendable segments. */
  150136. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  150137. if( rc!=SQLITE_OK ) return rc;
  150138. pWriter->iAbsLevel = iAbsLevel;
  150139. pWriter->nLeafEst = nLeafEst;
  150140. pWriter->iIdx = iIdx;
  150141. /* Set up the array of NodeWriter objects */
  150142. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  150143. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  150144. }
  150145. return SQLITE_OK;
  150146. }
  150147. /*
  150148. ** Remove an entry from the %_segdir table. This involves running the
  150149. ** following two statements:
  150150. **
  150151. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  150152. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  150153. **
  150154. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  150155. ** statement ensures that the remaining segments have contiguously allocated
  150156. ** idx values.
  150157. */
  150158. static int fts3RemoveSegdirEntry(
  150159. Fts3Table *p, /* FTS3 table handle */
  150160. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  150161. int iIdx /* Index of %_segdir entry to delete */
  150162. ){
  150163. int rc; /* Return code */
  150164. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  150165. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  150166. if( rc==SQLITE_OK ){
  150167. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  150168. sqlite3_bind_int(pDelete, 2, iIdx);
  150169. sqlite3_step(pDelete);
  150170. rc = sqlite3_reset(pDelete);
  150171. }
  150172. return rc;
  150173. }
  150174. /*
  150175. ** One or more segments have just been removed from absolute level iAbsLevel.
  150176. ** Update the 'idx' values of the remaining segments in the level so that
  150177. ** the idx values are a contiguous sequence starting from 0.
  150178. */
  150179. static int fts3RepackSegdirLevel(
  150180. Fts3Table *p, /* FTS3 table handle */
  150181. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  150182. ){
  150183. int rc; /* Return code */
  150184. int *aIdx = 0; /* Array of remaining idx values */
  150185. int nIdx = 0; /* Valid entries in aIdx[] */
  150186. int nAlloc = 0; /* Allocated size of aIdx[] */
  150187. int i; /* Iterator variable */
  150188. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  150189. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  150190. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  150191. if( rc==SQLITE_OK ){
  150192. int rc2;
  150193. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  150194. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  150195. if( nIdx>=nAlloc ){
  150196. int *aNew;
  150197. nAlloc += 16;
  150198. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  150199. if( !aNew ){
  150200. rc = SQLITE_NOMEM;
  150201. break;
  150202. }
  150203. aIdx = aNew;
  150204. }
  150205. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  150206. }
  150207. rc2 = sqlite3_reset(pSelect);
  150208. if( rc==SQLITE_OK ) rc = rc2;
  150209. }
  150210. if( rc==SQLITE_OK ){
  150211. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  150212. }
  150213. if( rc==SQLITE_OK ){
  150214. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  150215. }
  150216. assert( p->bIgnoreSavepoint==0 );
  150217. p->bIgnoreSavepoint = 1;
  150218. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  150219. if( aIdx[i]!=i ){
  150220. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  150221. sqlite3_bind_int(pUpdate, 1, i);
  150222. sqlite3_step(pUpdate);
  150223. rc = sqlite3_reset(pUpdate);
  150224. }
  150225. }
  150226. p->bIgnoreSavepoint = 0;
  150227. sqlite3_free(aIdx);
  150228. return rc;
  150229. }
  150230. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  150231. pNode->a[0] = (char)iHeight;
  150232. if( iChild ){
  150233. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  150234. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  150235. }else{
  150236. assert( pNode->nAlloc>=1 );
  150237. pNode->n = 1;
  150238. }
  150239. }
  150240. /*
  150241. ** The first two arguments are a pointer to and the size of a segment b-tree
  150242. ** node. The node may be a leaf or an internal node.
  150243. **
  150244. ** This function creates a new node image in blob object *pNew by copying
  150245. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  150246. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  150247. */
  150248. static int fts3TruncateNode(
  150249. const char *aNode, /* Current node image */
  150250. int nNode, /* Size of aNode in bytes */
  150251. Blob *pNew, /* OUT: Write new node image here */
  150252. const char *zTerm, /* Omit all terms smaller than this */
  150253. int nTerm, /* Size of zTerm in bytes */
  150254. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  150255. ){
  150256. NodeReader reader; /* Reader object */
  150257. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  150258. int rc = SQLITE_OK; /* Return code */
  150259. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  150260. /* Allocate required output space */
  150261. blobGrowBuffer(pNew, nNode, &rc);
  150262. if( rc!=SQLITE_OK ) return rc;
  150263. pNew->n = 0;
  150264. /* Populate new node buffer */
  150265. for(rc = nodeReaderInit(&reader, aNode, nNode);
  150266. rc==SQLITE_OK && reader.aNode;
  150267. rc = nodeReaderNext(&reader)
  150268. ){
  150269. if( pNew->n==0 ){
  150270. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  150271. if( res<0 || (bLeaf==0 && res==0) ) continue;
  150272. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  150273. *piBlock = reader.iChild;
  150274. }
  150275. rc = fts3AppendToNode(
  150276. pNew, &prev, reader.term.a, reader.term.n,
  150277. reader.aDoclist, reader.nDoclist
  150278. );
  150279. if( rc!=SQLITE_OK ) break;
  150280. }
  150281. if( pNew->n==0 ){
  150282. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  150283. *piBlock = reader.iChild;
  150284. }
  150285. assert( pNew->n<=pNew->nAlloc );
  150286. nodeReaderRelease(&reader);
  150287. sqlite3_free(prev.a);
  150288. return rc;
  150289. }
  150290. /*
  150291. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  150292. ** level iAbsLevel. This may involve deleting entries from the %_segments
  150293. ** table, and modifying existing entries in both the %_segments and %_segdir
  150294. ** tables.
  150295. **
  150296. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  150297. ** SQLite error code otherwise.
  150298. */
  150299. static int fts3TruncateSegment(
  150300. Fts3Table *p, /* FTS3 table handle */
  150301. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  150302. int iIdx, /* Index within level of segment to modify */
  150303. const char *zTerm, /* Remove terms smaller than this */
  150304. int nTerm /* Number of bytes in buffer zTerm */
  150305. ){
  150306. int rc = SQLITE_OK; /* Return code */
  150307. Blob root = {0,0,0}; /* New root page image */
  150308. Blob block = {0,0,0}; /* Buffer used for any other block */
  150309. sqlite3_int64 iBlock = 0; /* Block id */
  150310. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  150311. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  150312. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  150313. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  150314. if( rc==SQLITE_OK ){
  150315. int rc2; /* sqlite3_reset() return code */
  150316. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  150317. sqlite3_bind_int(pFetch, 2, iIdx);
  150318. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  150319. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  150320. int nRoot = sqlite3_column_bytes(pFetch, 4);
  150321. iOldStart = sqlite3_column_int64(pFetch, 1);
  150322. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  150323. }
  150324. rc2 = sqlite3_reset(pFetch);
  150325. if( rc==SQLITE_OK ) rc = rc2;
  150326. }
  150327. while( rc==SQLITE_OK && iBlock ){
  150328. char *aBlock = 0;
  150329. int nBlock = 0;
  150330. iNewStart = iBlock;
  150331. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  150332. if( rc==SQLITE_OK ){
  150333. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  150334. }
  150335. if( rc==SQLITE_OK ){
  150336. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  150337. }
  150338. sqlite3_free(aBlock);
  150339. }
  150340. /* Variable iNewStart now contains the first valid leaf node. */
  150341. if( rc==SQLITE_OK && iNewStart ){
  150342. sqlite3_stmt *pDel = 0;
  150343. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  150344. if( rc==SQLITE_OK ){
  150345. sqlite3_bind_int64(pDel, 1, iOldStart);
  150346. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  150347. sqlite3_step(pDel);
  150348. rc = sqlite3_reset(pDel);
  150349. }
  150350. }
  150351. if( rc==SQLITE_OK ){
  150352. sqlite3_stmt *pChomp = 0;
  150353. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  150354. if( rc==SQLITE_OK ){
  150355. sqlite3_bind_int64(pChomp, 1, iNewStart);
  150356. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  150357. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  150358. sqlite3_bind_int(pChomp, 4, iIdx);
  150359. sqlite3_step(pChomp);
  150360. rc = sqlite3_reset(pChomp);
  150361. }
  150362. }
  150363. sqlite3_free(root.a);
  150364. sqlite3_free(block.a);
  150365. return rc;
  150366. }
  150367. /*
  150368. ** This function is called after an incrmental-merge operation has run to
  150369. ** merge (or partially merge) two or more segments from absolute level
  150370. ** iAbsLevel.
  150371. **
  150372. ** Each input segment is either removed from the db completely (if all of
  150373. ** its data was copied to the output segment by the incrmerge operation)
  150374. ** or modified in place so that it no longer contains those entries that
  150375. ** have been duplicated in the output segment.
  150376. */
  150377. static int fts3IncrmergeChomp(
  150378. Fts3Table *p, /* FTS table handle */
  150379. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  150380. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  150381. int *pnRem /* Number of segments not deleted */
  150382. ){
  150383. int i;
  150384. int nRem = 0;
  150385. int rc = SQLITE_OK;
  150386. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  150387. Fts3SegReader *pSeg = 0;
  150388. int j;
  150389. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  150390. ** somewhere in the pCsr->apSegment[] array. */
  150391. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  150392. pSeg = pCsr->apSegment[j];
  150393. if( pSeg->iIdx==i ) break;
  150394. }
  150395. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  150396. if( pSeg->aNode==0 ){
  150397. /* Seg-reader is at EOF. Remove the entire input segment. */
  150398. rc = fts3DeleteSegment(p, pSeg);
  150399. if( rc==SQLITE_OK ){
  150400. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  150401. }
  150402. *pnRem = 0;
  150403. }else{
  150404. /* The incremental merge did not copy all the data from this
  150405. ** segment to the upper level. The segment is modified in place
  150406. ** so that it contains no keys smaller than zTerm/nTerm. */
  150407. const char *zTerm = pSeg->zTerm;
  150408. int nTerm = pSeg->nTerm;
  150409. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  150410. nRem++;
  150411. }
  150412. }
  150413. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  150414. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  150415. }
  150416. *pnRem = nRem;
  150417. return rc;
  150418. }
  150419. /*
  150420. ** Store an incr-merge hint in the database.
  150421. */
  150422. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  150423. sqlite3_stmt *pReplace = 0;
  150424. int rc; /* Return code */
  150425. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  150426. if( rc==SQLITE_OK ){
  150427. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  150428. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  150429. sqlite3_step(pReplace);
  150430. rc = sqlite3_reset(pReplace);
  150431. }
  150432. return rc;
  150433. }
  150434. /*
  150435. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  150436. ** exists, is stored in the rowid==1 row of the %_stat table.
  150437. **
  150438. ** If successful, populate blob *pHint with the value read from the %_stat
  150439. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  150440. ** SQLite error code.
  150441. */
  150442. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  150443. sqlite3_stmt *pSelect = 0;
  150444. int rc;
  150445. pHint->n = 0;
  150446. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  150447. if( rc==SQLITE_OK ){
  150448. int rc2;
  150449. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  150450. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  150451. const char *aHint = sqlite3_column_blob(pSelect, 0);
  150452. int nHint = sqlite3_column_bytes(pSelect, 0);
  150453. if( aHint ){
  150454. blobGrowBuffer(pHint, nHint, &rc);
  150455. if( rc==SQLITE_OK ){
  150456. memcpy(pHint->a, aHint, nHint);
  150457. pHint->n = nHint;
  150458. }
  150459. }
  150460. }
  150461. rc2 = sqlite3_reset(pSelect);
  150462. if( rc==SQLITE_OK ) rc = rc2;
  150463. }
  150464. return rc;
  150465. }
  150466. /*
  150467. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  150468. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  150469. ** consists of two varints, the absolute level number of the input segments
  150470. ** and the number of input segments.
  150471. **
  150472. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  150473. ** set *pRc to an SQLite error code before returning.
  150474. */
  150475. static void fts3IncrmergeHintPush(
  150476. Blob *pHint, /* Hint blob to append to */
  150477. i64 iAbsLevel, /* First varint to store in hint */
  150478. int nInput, /* Second varint to store in hint */
  150479. int *pRc /* IN/OUT: Error code */
  150480. ){
  150481. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  150482. if( *pRc==SQLITE_OK ){
  150483. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  150484. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  150485. }
  150486. }
  150487. /*
  150488. ** Read the last entry (most recently pushed) from the hint blob *pHint
  150489. ** and then remove the entry. Write the two values read to *piAbsLevel and
  150490. ** *pnInput before returning.
  150491. **
  150492. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  150493. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  150494. */
  150495. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  150496. const int nHint = pHint->n;
  150497. int i;
  150498. i = pHint->n-2;
  150499. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  150500. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  150501. pHint->n = i;
  150502. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  150503. i += fts3GetVarint32(&pHint->a[i], pnInput);
  150504. if( i!=nHint ) return FTS_CORRUPT_VTAB;
  150505. return SQLITE_OK;
  150506. }
  150507. /*
  150508. ** Attempt an incremental merge that writes nMerge leaf blocks.
  150509. **
  150510. ** Incremental merges happen nMin segments at a time. The segments
  150511. ** to be merged are the nMin oldest segments (the ones with the smallest
  150512. ** values for the _segdir.idx field) in the highest level that contains
  150513. ** at least nMin segments. Multiple merges might occur in an attempt to
  150514. ** write the quota of nMerge leaf blocks.
  150515. */
  150516. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  150517. int rc; /* Return code */
  150518. int nRem = nMerge; /* Number of leaf pages yet to be written */
  150519. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  150520. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  150521. IncrmergeWriter *pWriter; /* Writer object */
  150522. int nSeg = 0; /* Number of input segments */
  150523. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  150524. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  150525. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  150526. /* Allocate space for the cursor, filter and writer objects */
  150527. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  150528. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  150529. if( !pWriter ) return SQLITE_NOMEM;
  150530. pFilter = (Fts3SegFilter *)&pWriter[1];
  150531. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  150532. rc = fts3IncrmergeHintLoad(p, &hint);
  150533. while( rc==SQLITE_OK && nRem>0 ){
  150534. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  150535. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  150536. int bUseHint = 0; /* True if attempting to append */
  150537. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  150538. /* Search the %_segdir table for the absolute level with the smallest
  150539. ** relative level number that contains at least nMin segments, if any.
  150540. ** If one is found, set iAbsLevel to the absolute level number and
  150541. ** nSeg to nMin. If no level with at least nMin segments can be found,
  150542. ** set nSeg to -1.
  150543. */
  150544. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  150545. sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
  150546. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  150547. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  150548. nSeg = sqlite3_column_int(pFindLevel, 1);
  150549. assert( nSeg>=2 );
  150550. }else{
  150551. nSeg = -1;
  150552. }
  150553. rc = sqlite3_reset(pFindLevel);
  150554. /* If the hint read from the %_stat table is not empty, check if the
  150555. ** last entry in it specifies a relative level smaller than or equal
  150556. ** to the level identified by the block above (if any). If so, this
  150557. ** iteration of the loop will work on merging at the hinted level.
  150558. */
  150559. if( rc==SQLITE_OK && hint.n ){
  150560. int nHint = hint.n;
  150561. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  150562. int nHintSeg = 0; /* Hint number of segments */
  150563. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  150564. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  150565. iAbsLevel = iHintAbsLevel;
  150566. nSeg = nHintSeg;
  150567. bUseHint = 1;
  150568. bDirtyHint = 1;
  150569. }else{
  150570. /* This undoes the effect of the HintPop() above - so that no entry
  150571. ** is removed from the hint blob. */
  150572. hint.n = nHint;
  150573. }
  150574. }
  150575. /* If nSeg is less that zero, then there is no level with at least
  150576. ** nMin segments and no hint in the %_stat table. No work to do.
  150577. ** Exit early in this case. */
  150578. if( nSeg<0 ) break;
  150579. /* Open a cursor to iterate through the contents of the oldest nSeg
  150580. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  150581. ** the 'hint' parameters, it is possible that there are less than nSeg
  150582. ** segments available in level iAbsLevel. In this case, no work is
  150583. ** done on iAbsLevel - fall through to the next iteration of the loop
  150584. ** to start work on some other level. */
  150585. memset(pWriter, 0, nAlloc);
  150586. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  150587. if( rc==SQLITE_OK ){
  150588. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  150589. assert( bUseHint==1 || bUseHint==0 );
  150590. if( iIdx==0 || (bUseHint && iIdx==1) ){
  150591. int bIgnore = 0;
  150592. rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
  150593. if( bIgnore ){
  150594. pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
  150595. }
  150596. }
  150597. }
  150598. if( rc==SQLITE_OK ){
  150599. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  150600. }
  150601. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  150602. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  150603. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  150604. ){
  150605. if( bUseHint && iIdx>0 ){
  150606. const char *zKey = pCsr->zTerm;
  150607. int nKey = pCsr->nTerm;
  150608. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  150609. }else{
  150610. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  150611. }
  150612. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  150613. fts3LogMerge(nSeg, iAbsLevel);
  150614. do {
  150615. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  150616. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  150617. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  150618. }while( rc==SQLITE_ROW );
  150619. /* Update or delete the input segments */
  150620. if( rc==SQLITE_OK ){
  150621. nRem -= (1 + pWriter->nWork);
  150622. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  150623. if( nSeg!=0 ){
  150624. bDirtyHint = 1;
  150625. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  150626. }
  150627. }
  150628. }
  150629. if( nSeg!=0 ){
  150630. pWriter->nLeafData = pWriter->nLeafData * -1;
  150631. }
  150632. fts3IncrmergeRelease(p, pWriter, &rc);
  150633. if( nSeg==0 && pWriter->bNoLeafData==0 ){
  150634. fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
  150635. }
  150636. }
  150637. sqlite3Fts3SegReaderFinish(pCsr);
  150638. }
  150639. /* Write the hint values into the %_stat table for the next incr-merger */
  150640. if( bDirtyHint && rc==SQLITE_OK ){
  150641. rc = fts3IncrmergeHintStore(p, &hint);
  150642. }
  150643. sqlite3_free(pWriter);
  150644. sqlite3_free(hint.a);
  150645. return rc;
  150646. }
  150647. /*
  150648. ** Convert the text beginning at *pz into an integer and return
  150649. ** its value. Advance *pz to point to the first character past
  150650. ** the integer.
  150651. **
  150652. ** This function used for parameters to merge= and incrmerge=
  150653. ** commands.
  150654. */
  150655. static int fts3Getint(const char **pz){
  150656. const char *z = *pz;
  150657. int i = 0;
  150658. while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
  150659. *pz = z;
  150660. return i;
  150661. }
  150662. /*
  150663. ** Process statements of the form:
  150664. **
  150665. ** INSERT INTO table(table) VALUES('merge=A,B');
  150666. **
  150667. ** A and B are integers that decode to be the number of leaf pages
  150668. ** written for the merge, and the minimum number of segments on a level
  150669. ** before it will be selected for a merge, respectively.
  150670. */
  150671. static int fts3DoIncrmerge(
  150672. Fts3Table *p, /* FTS3 table handle */
  150673. const char *zParam /* Nul-terminated string containing "A,B" */
  150674. ){
  150675. int rc;
  150676. int nMin = (FTS3_MERGE_COUNT / 2);
  150677. int nMerge = 0;
  150678. const char *z = zParam;
  150679. /* Read the first integer value */
  150680. nMerge = fts3Getint(&z);
  150681. /* If the first integer value is followed by a ',', read the second
  150682. ** integer value. */
  150683. if( z[0]==',' && z[1]!='\0' ){
  150684. z++;
  150685. nMin = fts3Getint(&z);
  150686. }
  150687. if( z[0]!='\0' || nMin<2 ){
  150688. rc = SQLITE_ERROR;
  150689. }else{
  150690. rc = SQLITE_OK;
  150691. if( !p->bHasStat ){
  150692. assert( p->bFts4==0 );
  150693. sqlite3Fts3CreateStatTable(&rc, p);
  150694. }
  150695. if( rc==SQLITE_OK ){
  150696. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  150697. }
  150698. sqlite3Fts3SegmentsClose(p);
  150699. }
  150700. return rc;
  150701. }
  150702. /*
  150703. ** Process statements of the form:
  150704. **
  150705. ** INSERT INTO table(table) VALUES('automerge=X');
  150706. **
  150707. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  150708. ** turn it on. The setting is persistent.
  150709. */
  150710. static int fts3DoAutoincrmerge(
  150711. Fts3Table *p, /* FTS3 table handle */
  150712. const char *zParam /* Nul-terminated string containing boolean */
  150713. ){
  150714. int rc = SQLITE_OK;
  150715. sqlite3_stmt *pStmt = 0;
  150716. p->nAutoincrmerge = fts3Getint(&zParam);
  150717. if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
  150718. p->nAutoincrmerge = 8;
  150719. }
  150720. if( !p->bHasStat ){
  150721. assert( p->bFts4==0 );
  150722. sqlite3Fts3CreateStatTable(&rc, p);
  150723. if( rc ) return rc;
  150724. }
  150725. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  150726. if( rc ) return rc;
  150727. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  150728. sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
  150729. sqlite3_step(pStmt);
  150730. rc = sqlite3_reset(pStmt);
  150731. return rc;
  150732. }
  150733. /*
  150734. ** Return a 64-bit checksum for the FTS index entry specified by the
  150735. ** arguments to this function.
  150736. */
  150737. static u64 fts3ChecksumEntry(
  150738. const char *zTerm, /* Pointer to buffer containing term */
  150739. int nTerm, /* Size of zTerm in bytes */
  150740. int iLangid, /* Language id for current row */
  150741. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  150742. i64 iDocid, /* Docid for current row. */
  150743. int iCol, /* Column number */
  150744. int iPos /* Position */
  150745. ){
  150746. int i;
  150747. u64 ret = (u64)iDocid;
  150748. ret += (ret<<3) + iLangid;
  150749. ret += (ret<<3) + iIndex;
  150750. ret += (ret<<3) + iCol;
  150751. ret += (ret<<3) + iPos;
  150752. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  150753. return ret;
  150754. }
  150755. /*
  150756. ** Return a checksum of all entries in the FTS index that correspond to
  150757. ** language id iLangid. The checksum is calculated by XORing the checksums
  150758. ** of each individual entry (see fts3ChecksumEntry()) together.
  150759. **
  150760. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  150761. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  150762. ** return value is undefined in this case.
  150763. */
  150764. static u64 fts3ChecksumIndex(
  150765. Fts3Table *p, /* FTS3 table handle */
  150766. int iLangid, /* Language id to return cksum for */
  150767. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  150768. int *pRc /* OUT: Return code */
  150769. ){
  150770. Fts3SegFilter filter;
  150771. Fts3MultiSegReader csr;
  150772. int rc;
  150773. u64 cksum = 0;
  150774. assert( *pRc==SQLITE_OK );
  150775. memset(&filter, 0, sizeof(filter));
  150776. memset(&csr, 0, sizeof(csr));
  150777. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  150778. filter.flags |= FTS3_SEGMENT_SCAN;
  150779. rc = sqlite3Fts3SegReaderCursor(
  150780. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  150781. );
  150782. if( rc==SQLITE_OK ){
  150783. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  150784. }
  150785. if( rc==SQLITE_OK ){
  150786. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  150787. char *pCsr = csr.aDoclist;
  150788. char *pEnd = &pCsr[csr.nDoclist];
  150789. i64 iDocid = 0;
  150790. i64 iCol = 0;
  150791. i64 iPos = 0;
  150792. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  150793. while( pCsr<pEnd ){
  150794. i64 iVal = 0;
  150795. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  150796. if( pCsr<pEnd ){
  150797. if( iVal==0 || iVal==1 ){
  150798. iCol = 0;
  150799. iPos = 0;
  150800. if( iVal ){
  150801. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  150802. }else{
  150803. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  150804. iDocid += iVal;
  150805. }
  150806. }else{
  150807. iPos += (iVal - 2);
  150808. cksum = cksum ^ fts3ChecksumEntry(
  150809. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  150810. (int)iCol, (int)iPos
  150811. );
  150812. }
  150813. }
  150814. }
  150815. }
  150816. }
  150817. sqlite3Fts3SegReaderFinish(&csr);
  150818. *pRc = rc;
  150819. return cksum;
  150820. }
  150821. /*
  150822. ** Check if the contents of the FTS index match the current contents of the
  150823. ** content table. If no error occurs and the contents do match, set *pbOk
  150824. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  150825. ** to false before returning.
  150826. **
  150827. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  150828. ** code. The final value of *pbOk is undefined in this case.
  150829. */
  150830. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  150831. int rc = SQLITE_OK; /* Return code */
  150832. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  150833. u64 cksum2 = 0; /* Checksum based on %_content contents */
  150834. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  150835. /* This block calculates the checksum according to the FTS index. */
  150836. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  150837. if( rc==SQLITE_OK ){
  150838. int rc2;
  150839. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  150840. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  150841. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  150842. int iLangid = sqlite3_column_int(pAllLangid, 0);
  150843. int i;
  150844. for(i=0; i<p->nIndex; i++){
  150845. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  150846. }
  150847. }
  150848. rc2 = sqlite3_reset(pAllLangid);
  150849. if( rc==SQLITE_OK ) rc = rc2;
  150850. }
  150851. /* This block calculates the checksum according to the %_content table */
  150852. if( rc==SQLITE_OK ){
  150853. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  150854. sqlite3_stmt *pStmt = 0;
  150855. char *zSql;
  150856. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  150857. if( !zSql ){
  150858. rc = SQLITE_NOMEM;
  150859. }else{
  150860. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  150861. sqlite3_free(zSql);
  150862. }
  150863. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  150864. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  150865. int iLang = langidFromSelect(p, pStmt);
  150866. int iCol;
  150867. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  150868. if( p->abNotindexed[iCol]==0 ){
  150869. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  150870. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  150871. sqlite3_tokenizer_cursor *pT = 0;
  150872. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
  150873. while( rc==SQLITE_OK ){
  150874. char const *zToken; /* Buffer containing token */
  150875. int nToken = 0; /* Number of bytes in token */
  150876. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  150877. int iPos = 0; /* Position of token in zText */
  150878. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  150879. if( rc==SQLITE_OK ){
  150880. int i;
  150881. cksum2 = cksum2 ^ fts3ChecksumEntry(
  150882. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  150883. );
  150884. for(i=1; i<p->nIndex; i++){
  150885. if( p->aIndex[i].nPrefix<=nToken ){
  150886. cksum2 = cksum2 ^ fts3ChecksumEntry(
  150887. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  150888. );
  150889. }
  150890. }
  150891. }
  150892. }
  150893. if( pT ) pModule->xClose(pT);
  150894. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  150895. }
  150896. }
  150897. }
  150898. sqlite3_finalize(pStmt);
  150899. }
  150900. *pbOk = (cksum1==cksum2);
  150901. return rc;
  150902. }
  150903. /*
  150904. ** Run the integrity-check. If no error occurs and the current contents of
  150905. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  150906. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  150907. **
  150908. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  150909. ** error code.
  150910. **
  150911. ** The integrity-check works as follows. For each token and indexed token
  150912. ** prefix in the document set, a 64-bit checksum is calculated (by code
  150913. ** in fts3ChecksumEntry()) based on the following:
  150914. **
  150915. ** + The index number (0 for the main index, 1 for the first prefix
  150916. ** index etc.),
  150917. ** + The token (or token prefix) text itself,
  150918. ** + The language-id of the row it appears in,
  150919. ** + The docid of the row it appears in,
  150920. ** + The column it appears in, and
  150921. ** + The tokens position within that column.
  150922. **
  150923. ** The checksums for all entries in the index are XORed together to create
  150924. ** a single checksum for the entire index.
  150925. **
  150926. ** The integrity-check code calculates the same checksum in two ways:
  150927. **
  150928. ** 1. By scanning the contents of the FTS index, and
  150929. ** 2. By scanning and tokenizing the content table.
  150930. **
  150931. ** If the two checksums are identical, the integrity-check is deemed to have
  150932. ** passed.
  150933. */
  150934. static int fts3DoIntegrityCheck(
  150935. Fts3Table *p /* FTS3 table handle */
  150936. ){
  150937. int rc;
  150938. int bOk = 0;
  150939. rc = fts3IntegrityCheck(p, &bOk);
  150940. if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
  150941. return rc;
  150942. }
  150943. /*
  150944. ** Handle a 'special' INSERT of the form:
  150945. **
  150946. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  150947. **
  150948. ** Argument pVal contains the result of <expr>. Currently the only
  150949. ** meaningful value to insert is the text 'optimize'.
  150950. */
  150951. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  150952. int rc; /* Return Code */
  150953. const char *zVal = (const char *)sqlite3_value_text(pVal);
  150954. int nVal = sqlite3_value_bytes(pVal);
  150955. if( !zVal ){
  150956. return SQLITE_NOMEM;
  150957. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  150958. rc = fts3DoOptimize(p, 0);
  150959. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  150960. rc = fts3DoRebuild(p);
  150961. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  150962. rc = fts3DoIntegrityCheck(p);
  150963. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  150964. rc = fts3DoIncrmerge(p, &zVal[6]);
  150965. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  150966. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  150967. #ifdef SQLITE_TEST
  150968. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  150969. p->nNodeSize = atoi(&zVal[9]);
  150970. rc = SQLITE_OK;
  150971. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  150972. p->nMaxPendingData = atoi(&zVal[11]);
  150973. rc = SQLITE_OK;
  150974. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  150975. p->bNoIncrDoclist = atoi(&zVal[21]);
  150976. rc = SQLITE_OK;
  150977. #endif
  150978. }else{
  150979. rc = SQLITE_ERROR;
  150980. }
  150981. return rc;
  150982. }
  150983. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  150984. /*
  150985. ** Delete all cached deferred doclists. Deferred doclists are cached
  150986. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  150987. */
  150988. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  150989. Fts3DeferredToken *pDef;
  150990. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  150991. fts3PendingListDelete(pDef->pList);
  150992. pDef->pList = 0;
  150993. }
  150994. }
  150995. /*
  150996. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  150997. ** this list using sqlite3Fts3DeferToken().
  150998. */
  150999. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  151000. Fts3DeferredToken *pDef;
  151001. Fts3DeferredToken *pNext;
  151002. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  151003. pNext = pDef->pNext;
  151004. fts3PendingListDelete(pDef->pList);
  151005. sqlite3_free(pDef);
  151006. }
  151007. pCsr->pDeferred = 0;
  151008. }
  151009. /*
  151010. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  151011. ** based on the row that pCsr currently points to.
  151012. **
  151013. ** A deferred-doclist is like any other doclist with position information
  151014. ** included, except that it only contains entries for a single row of the
  151015. ** table, not for all rows.
  151016. */
  151017. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  151018. int rc = SQLITE_OK; /* Return code */
  151019. if( pCsr->pDeferred ){
  151020. int i; /* Used to iterate through table columns */
  151021. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  151022. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  151023. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  151024. sqlite3_tokenizer *pT = p->pTokenizer;
  151025. sqlite3_tokenizer_module const *pModule = pT->pModule;
  151026. assert( pCsr->isRequireSeek==0 );
  151027. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  151028. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  151029. if( p->abNotindexed[i]==0 ){
  151030. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  151031. sqlite3_tokenizer_cursor *pTC = 0;
  151032. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  151033. while( rc==SQLITE_OK ){
  151034. char const *zToken; /* Buffer containing token */
  151035. int nToken = 0; /* Number of bytes in token */
  151036. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  151037. int iPos = 0; /* Position of token in zText */
  151038. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  151039. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  151040. Fts3PhraseToken *pPT = pDef->pToken;
  151041. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  151042. && (pPT->bFirst==0 || iPos==0)
  151043. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  151044. && (0==memcmp(zToken, pPT->z, pPT->n))
  151045. ){
  151046. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  151047. }
  151048. }
  151049. }
  151050. if( pTC ) pModule->xClose(pTC);
  151051. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  151052. }
  151053. }
  151054. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  151055. if( pDef->pList ){
  151056. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  151057. }
  151058. }
  151059. }
  151060. return rc;
  151061. }
  151062. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  151063. Fts3DeferredToken *p,
  151064. char **ppData,
  151065. int *pnData
  151066. ){
  151067. char *pRet;
  151068. int nSkip;
  151069. sqlite3_int64 dummy;
  151070. *ppData = 0;
  151071. *pnData = 0;
  151072. if( p->pList==0 ){
  151073. return SQLITE_OK;
  151074. }
  151075. pRet = (char *)sqlite3_malloc(p->pList->nData);
  151076. if( !pRet ) return SQLITE_NOMEM;
  151077. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  151078. *pnData = p->pList->nData - nSkip;
  151079. *ppData = pRet;
  151080. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  151081. return SQLITE_OK;
  151082. }
  151083. /*
  151084. ** Add an entry for token pToken to the pCsr->pDeferred list.
  151085. */
  151086. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  151087. Fts3Cursor *pCsr, /* Fts3 table cursor */
  151088. Fts3PhraseToken *pToken, /* Token to defer */
  151089. int iCol /* Column that token must appear in (or -1) */
  151090. ){
  151091. Fts3DeferredToken *pDeferred;
  151092. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  151093. if( !pDeferred ){
  151094. return SQLITE_NOMEM;
  151095. }
  151096. memset(pDeferred, 0, sizeof(*pDeferred));
  151097. pDeferred->pToken = pToken;
  151098. pDeferred->pNext = pCsr->pDeferred;
  151099. pDeferred->iCol = iCol;
  151100. pCsr->pDeferred = pDeferred;
  151101. assert( pToken->pDeferred==0 );
  151102. pToken->pDeferred = pDeferred;
  151103. return SQLITE_OK;
  151104. }
  151105. #endif
  151106. /*
  151107. ** SQLite value pRowid contains the rowid of a row that may or may not be
  151108. ** present in the FTS3 table. If it is, delete it and adjust the contents
  151109. ** of subsiduary data structures accordingly.
  151110. */
  151111. static int fts3DeleteByRowid(
  151112. Fts3Table *p,
  151113. sqlite3_value *pRowid,
  151114. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  151115. u32 *aSzDel
  151116. ){
  151117. int rc = SQLITE_OK; /* Return code */
  151118. int bFound = 0; /* True if *pRowid really is in the table */
  151119. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  151120. if( bFound && rc==SQLITE_OK ){
  151121. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  151122. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  151123. if( rc==SQLITE_OK ){
  151124. if( isEmpty ){
  151125. /* Deleting this row means the whole table is empty. In this case
  151126. ** delete the contents of all three tables and throw away any
  151127. ** data in the pendingTerms hash table. */
  151128. rc = fts3DeleteAll(p, 1);
  151129. *pnChng = 0;
  151130. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  151131. }else{
  151132. *pnChng = *pnChng - 1;
  151133. if( p->zContentTbl==0 ){
  151134. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  151135. }
  151136. if( p->bHasDocsize ){
  151137. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  151138. }
  151139. }
  151140. }
  151141. }
  151142. return rc;
  151143. }
  151144. /*
  151145. ** This function does the work for the xUpdate method of FTS3 virtual
  151146. ** tables. The schema of the virtual table being:
  151147. **
  151148. ** CREATE TABLE <table name>(
  151149. ** <user columns>,
  151150. ** <table name> HIDDEN,
  151151. ** docid HIDDEN,
  151152. ** <langid> HIDDEN
  151153. ** );
  151154. **
  151155. **
  151156. */
  151157. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  151158. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  151159. int nArg, /* Size of argument array */
  151160. sqlite3_value **apVal, /* Array of arguments */
  151161. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  151162. ){
  151163. Fts3Table *p = (Fts3Table *)pVtab;
  151164. int rc = SQLITE_OK; /* Return Code */
  151165. int isRemove = 0; /* True for an UPDATE or DELETE */
  151166. u32 *aSzIns = 0; /* Sizes of inserted documents */
  151167. u32 *aSzDel = 0; /* Sizes of deleted documents */
  151168. int nChng = 0; /* Net change in number of documents */
  151169. int bInsertDone = 0;
  151170. /* At this point it must be known if the %_stat table exists or not.
  151171. ** So bHasStat may not be 2. */
  151172. assert( p->bHasStat==0 || p->bHasStat==1 );
  151173. assert( p->pSegments==0 );
  151174. assert(
  151175. nArg==1 /* DELETE operations */
  151176. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  151177. );
  151178. /* Check for a "special" INSERT operation. One of the form:
  151179. **
  151180. ** INSERT INTO xyz(xyz) VALUES('command');
  151181. */
  151182. if( nArg>1
  151183. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  151184. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  151185. ){
  151186. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  151187. goto update_out;
  151188. }
  151189. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  151190. rc = SQLITE_CONSTRAINT;
  151191. goto update_out;
  151192. }
  151193. /* Allocate space to hold the change in document sizes */
  151194. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  151195. if( aSzDel==0 ){
  151196. rc = SQLITE_NOMEM;
  151197. goto update_out;
  151198. }
  151199. aSzIns = &aSzDel[p->nColumn+1];
  151200. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  151201. rc = fts3Writelock(p);
  151202. if( rc!=SQLITE_OK ) goto update_out;
  151203. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  151204. ** value, then this operation requires constraint handling.
  151205. **
  151206. ** If the on-conflict mode is REPLACE, this means that the existing row
  151207. ** should be deleted from the database before inserting the new row. Or,
  151208. ** if the on-conflict mode is other than REPLACE, then this method must
  151209. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  151210. ** modify the database file.
  151211. */
  151212. if( nArg>1 && p->zContentTbl==0 ){
  151213. /* Find the value object that holds the new rowid value. */
  151214. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  151215. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  151216. pNewRowid = apVal[1];
  151217. }
  151218. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  151219. sqlite3_value_type(apVal[0])==SQLITE_NULL
  151220. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  151221. )){
  151222. /* The new rowid is not NULL (in this case the rowid will be
  151223. ** automatically assigned and there is no chance of a conflict), and
  151224. ** the statement is either an INSERT or an UPDATE that modifies the
  151225. ** rowid column. So if the conflict mode is REPLACE, then delete any
  151226. ** existing row with rowid=pNewRowid.
  151227. **
  151228. ** Or, if the conflict mode is not REPLACE, insert the new record into
  151229. ** the %_content table. If we hit the duplicate rowid constraint (or any
  151230. ** other error) while doing so, return immediately.
  151231. **
  151232. ** This branch may also run if pNewRowid contains a value that cannot
  151233. ** be losslessly converted to an integer. In this case, the eventual
  151234. ** call to fts3InsertData() (either just below or further on in this
  151235. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  151236. ** invoked, it will delete zero rows (since no row will have
  151237. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  151238. */
  151239. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  151240. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  151241. }else{
  151242. rc = fts3InsertData(p, apVal, pRowid);
  151243. bInsertDone = 1;
  151244. }
  151245. }
  151246. }
  151247. if( rc!=SQLITE_OK ){
  151248. goto update_out;
  151249. }
  151250. /* If this is a DELETE or UPDATE operation, remove the old record. */
  151251. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  151252. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  151253. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  151254. isRemove = 1;
  151255. }
  151256. /* If this is an INSERT or UPDATE operation, insert the new record. */
  151257. if( nArg>1 && rc==SQLITE_OK ){
  151258. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  151259. if( bInsertDone==0 ){
  151260. rc = fts3InsertData(p, apVal, pRowid);
  151261. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  151262. rc = FTS_CORRUPT_VTAB;
  151263. }
  151264. }
  151265. if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
  151266. rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
  151267. }
  151268. if( rc==SQLITE_OK ){
  151269. assert( p->iPrevDocid==*pRowid );
  151270. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  151271. }
  151272. if( p->bHasDocsize ){
  151273. fts3InsertDocsize(&rc, p, aSzIns);
  151274. }
  151275. nChng++;
  151276. }
  151277. if( p->bFts4 ){
  151278. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  151279. }
  151280. update_out:
  151281. sqlite3_free(aSzDel);
  151282. sqlite3Fts3SegmentsClose(p);
  151283. return rc;
  151284. }
  151285. /*
  151286. ** Flush any data in the pending-terms hash table to disk. If successful,
  151287. ** merge all segments in the database (including the new segment, if
  151288. ** there was any data to flush) into a single segment.
  151289. */
  151290. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  151291. int rc;
  151292. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  151293. if( rc==SQLITE_OK ){
  151294. rc = fts3DoOptimize(p, 1);
  151295. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  151296. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  151297. if( rc2!=SQLITE_OK ) rc = rc2;
  151298. }else{
  151299. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  151300. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  151301. }
  151302. }
  151303. sqlite3Fts3SegmentsClose(p);
  151304. return rc;
  151305. }
  151306. #endif
  151307. /************** End of fts3_write.c ******************************************/
  151308. /************** Begin file fts3_snippet.c ************************************/
  151309. /*
  151310. ** 2009 Oct 23
  151311. **
  151312. ** The author disclaims copyright to this source code. In place of
  151313. ** a legal notice, here is a blessing:
  151314. **
  151315. ** May you do good and not evil.
  151316. ** May you find forgiveness for yourself and forgive others.
  151317. ** May you share freely, never taking more than you give.
  151318. **
  151319. ******************************************************************************
  151320. */
  151321. /* #include "fts3Int.h" */
  151322. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  151323. /* #include <string.h> */
  151324. /* #include <assert.h> */
  151325. /*
  151326. ** Characters that may appear in the second argument to matchinfo().
  151327. */
  151328. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  151329. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  151330. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  151331. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  151332. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  151333. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  151334. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  151335. #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
  151336. #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
  151337. /*
  151338. ** The default value for the second argument to matchinfo().
  151339. */
  151340. #define FTS3_MATCHINFO_DEFAULT "pcx"
  151341. /*
  151342. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  151343. ** Fts3Expr.aDoclist[]/nDoclist.
  151344. */
  151345. typedef struct LoadDoclistCtx LoadDoclistCtx;
  151346. struct LoadDoclistCtx {
  151347. Fts3Cursor *pCsr; /* FTS3 Cursor */
  151348. int nPhrase; /* Number of phrases seen so far */
  151349. int nToken; /* Number of tokens seen so far */
  151350. };
  151351. /*
  151352. ** The following types are used as part of the implementation of the
  151353. ** fts3BestSnippet() routine.
  151354. */
  151355. typedef struct SnippetIter SnippetIter;
  151356. typedef struct SnippetPhrase SnippetPhrase;
  151357. typedef struct SnippetFragment SnippetFragment;
  151358. struct SnippetIter {
  151359. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  151360. int iCol; /* Extract snippet from this column */
  151361. int nSnippet; /* Requested snippet length (in tokens) */
  151362. int nPhrase; /* Number of phrases in query */
  151363. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  151364. int iCurrent; /* First token of current snippet */
  151365. };
  151366. struct SnippetPhrase {
  151367. int nToken; /* Number of tokens in phrase */
  151368. char *pList; /* Pointer to start of phrase position list */
  151369. int iHead; /* Next value in position list */
  151370. char *pHead; /* Position list data following iHead */
  151371. int iTail; /* Next value in trailing position list */
  151372. char *pTail; /* Position list data following iTail */
  151373. };
  151374. struct SnippetFragment {
  151375. int iCol; /* Column snippet is extracted from */
  151376. int iPos; /* Index of first token in snippet */
  151377. u64 covered; /* Mask of query phrases covered */
  151378. u64 hlmask; /* Mask of snippet terms to highlight */
  151379. };
  151380. /*
  151381. ** This type is used as an fts3ExprIterate() context object while
  151382. ** accumulating the data returned by the matchinfo() function.
  151383. */
  151384. typedef struct MatchInfo MatchInfo;
  151385. struct MatchInfo {
  151386. Fts3Cursor *pCursor; /* FTS3 Cursor */
  151387. int nCol; /* Number of columns in table */
  151388. int nPhrase; /* Number of matchable phrases in query */
  151389. sqlite3_int64 nDoc; /* Number of docs in database */
  151390. char flag;
  151391. u32 *aMatchinfo; /* Pre-allocated buffer */
  151392. };
  151393. /*
  151394. ** An instance of this structure is used to manage a pair of buffers, each
  151395. ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
  151396. ** for details.
  151397. */
  151398. struct MatchinfoBuffer {
  151399. u8 aRef[3];
  151400. int nElem;
  151401. int bGlobal; /* Set if global data is loaded */
  151402. char *zMatchinfo;
  151403. u32 aMatchinfo[1];
  151404. };
  151405. /*
  151406. ** The snippet() and offsets() functions both return text values. An instance
  151407. ** of the following structure is used to accumulate those values while the
  151408. ** functions are running. See fts3StringAppend() for details.
  151409. */
  151410. typedef struct StrBuffer StrBuffer;
  151411. struct StrBuffer {
  151412. char *z; /* Pointer to buffer containing string */
  151413. int n; /* Length of z in bytes (excl. nul-term) */
  151414. int nAlloc; /* Allocated size of buffer z in bytes */
  151415. };
  151416. /*************************************************************************
  151417. ** Start of MatchinfoBuffer code.
  151418. */
  151419. /*
  151420. ** Allocate a two-slot MatchinfoBuffer object.
  151421. */
  151422. static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
  151423. MatchinfoBuffer *pRet;
  151424. int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
  151425. int nStr = (int)strlen(zMatchinfo);
  151426. pRet = sqlite3_malloc(nByte + nStr+1);
  151427. if( pRet ){
  151428. memset(pRet, 0, nByte);
  151429. pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
  151430. pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
  151431. pRet->nElem = nElem;
  151432. pRet->zMatchinfo = ((char*)pRet) + nByte;
  151433. memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
  151434. pRet->aRef[0] = 1;
  151435. }
  151436. return pRet;
  151437. }
  151438. static void fts3MIBufferFree(void *p){
  151439. MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
  151440. assert( (u32*)p==&pBuf->aMatchinfo[1]
  151441. || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
  151442. );
  151443. if( (u32*)p==&pBuf->aMatchinfo[1] ){
  151444. pBuf->aRef[1] = 0;
  151445. }else{
  151446. pBuf->aRef[2] = 0;
  151447. }
  151448. if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
  151449. sqlite3_free(pBuf);
  151450. }
  151451. }
  151452. static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
  151453. void (*xRet)(void*) = 0;
  151454. u32 *aOut = 0;
  151455. if( p->aRef[1]==0 ){
  151456. p->aRef[1] = 1;
  151457. aOut = &p->aMatchinfo[1];
  151458. xRet = fts3MIBufferFree;
  151459. }
  151460. else if( p->aRef[2]==0 ){
  151461. p->aRef[2] = 1;
  151462. aOut = &p->aMatchinfo[p->nElem+2];
  151463. xRet = fts3MIBufferFree;
  151464. }else{
  151465. aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
  151466. if( aOut ){
  151467. xRet = sqlite3_free;
  151468. if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
  151469. }
  151470. }
  151471. *paOut = aOut;
  151472. return xRet;
  151473. }
  151474. static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
  151475. p->bGlobal = 1;
  151476. memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
  151477. }
  151478. /*
  151479. ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
  151480. */
  151481. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
  151482. if( p ){
  151483. assert( p->aRef[0]==1 );
  151484. p->aRef[0] = 0;
  151485. if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
  151486. sqlite3_free(p);
  151487. }
  151488. }
  151489. }
  151490. /*
  151491. ** End of MatchinfoBuffer code.
  151492. *************************************************************************/
  151493. /*
  151494. ** This function is used to help iterate through a position-list. A position
  151495. ** list is a list of unique integers, sorted from smallest to largest. Each
  151496. ** element of the list is represented by an FTS3 varint that takes the value
  151497. ** of the difference between the current element and the previous one plus
  151498. ** two. For example, to store the position-list:
  151499. **
  151500. ** 4 9 113
  151501. **
  151502. ** the three varints:
  151503. **
  151504. ** 6 7 106
  151505. **
  151506. ** are encoded.
  151507. **
  151508. ** When this function is called, *pp points to the start of an element of
  151509. ** the list. *piPos contains the value of the previous entry in the list.
  151510. ** After it returns, *piPos contains the value of the next element of the
  151511. ** list and *pp is advanced to the following varint.
  151512. */
  151513. static void fts3GetDeltaPosition(char **pp, int *piPos){
  151514. int iVal;
  151515. *pp += fts3GetVarint32(*pp, &iVal);
  151516. *piPos += (iVal-2);
  151517. }
  151518. /*
  151519. ** Helper function for fts3ExprIterate() (see below).
  151520. */
  151521. static int fts3ExprIterate2(
  151522. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  151523. int *piPhrase, /* Pointer to phrase counter */
  151524. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  151525. void *pCtx /* Second argument to pass to callback */
  151526. ){
  151527. int rc; /* Return code */
  151528. int eType = pExpr->eType; /* Type of expression node pExpr */
  151529. if( eType!=FTSQUERY_PHRASE ){
  151530. assert( pExpr->pLeft && pExpr->pRight );
  151531. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  151532. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  151533. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  151534. }
  151535. }else{
  151536. rc = x(pExpr, *piPhrase, pCtx);
  151537. (*piPhrase)++;
  151538. }
  151539. return rc;
  151540. }
  151541. /*
  151542. ** Iterate through all phrase nodes in an FTS3 query, except those that
  151543. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  151544. ** For each phrase node found, the supplied callback function is invoked.
  151545. **
  151546. ** If the callback function returns anything other than SQLITE_OK,
  151547. ** the iteration is abandoned and the error code returned immediately.
  151548. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  151549. ** all eligible phrase nodes.
  151550. */
  151551. static int fts3ExprIterate(
  151552. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  151553. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  151554. void *pCtx /* Second argument to pass to callback */
  151555. ){
  151556. int iPhrase = 0; /* Variable used as the phrase counter */
  151557. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  151558. }
  151559. /*
  151560. ** This is an fts3ExprIterate() callback used while loading the doclists
  151561. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  151562. ** fts3ExprLoadDoclists().
  151563. */
  151564. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  151565. int rc = SQLITE_OK;
  151566. Fts3Phrase *pPhrase = pExpr->pPhrase;
  151567. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  151568. UNUSED_PARAMETER(iPhrase);
  151569. p->nPhrase++;
  151570. p->nToken += pPhrase->nToken;
  151571. return rc;
  151572. }
  151573. /*
  151574. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  151575. ** pCsr.
  151576. **
  151577. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  151578. ** phrases in the expression (all phrases except those directly or
  151579. ** indirectly descended from the right-hand-side of a NOT operator). If
  151580. ** pnToken is not NULL, then it is set to the number of tokens in all
  151581. ** matchable phrases of the expression.
  151582. */
  151583. static int fts3ExprLoadDoclists(
  151584. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  151585. int *pnPhrase, /* OUT: Number of phrases in query */
  151586. int *pnToken /* OUT: Number of tokens in query */
  151587. ){
  151588. int rc; /* Return Code */
  151589. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  151590. sCtx.pCsr = pCsr;
  151591. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  151592. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  151593. if( pnToken ) *pnToken = sCtx.nToken;
  151594. return rc;
  151595. }
  151596. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  151597. (*(int *)ctx)++;
  151598. pExpr->iPhrase = iPhrase;
  151599. return SQLITE_OK;
  151600. }
  151601. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  151602. int nPhrase = 0;
  151603. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  151604. return nPhrase;
  151605. }
  151606. /*
  151607. ** Advance the position list iterator specified by the first two
  151608. ** arguments so that it points to the first element with a value greater
  151609. ** than or equal to parameter iNext.
  151610. */
  151611. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  151612. char *pIter = *ppIter;
  151613. if( pIter ){
  151614. int iIter = *piIter;
  151615. while( iIter<iNext ){
  151616. if( 0==(*pIter & 0xFE) ){
  151617. iIter = -1;
  151618. pIter = 0;
  151619. break;
  151620. }
  151621. fts3GetDeltaPosition(&pIter, &iIter);
  151622. }
  151623. *piIter = iIter;
  151624. *ppIter = pIter;
  151625. }
  151626. }
  151627. /*
  151628. ** Advance the snippet iterator to the next candidate snippet.
  151629. */
  151630. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  151631. int i; /* Loop counter */
  151632. if( pIter->iCurrent<0 ){
  151633. /* The SnippetIter object has just been initialized. The first snippet
  151634. ** candidate always starts at offset 0 (even if this candidate has a
  151635. ** score of 0.0).
  151636. */
  151637. pIter->iCurrent = 0;
  151638. /* Advance the 'head' iterator of each phrase to the first offset that
  151639. ** is greater than or equal to (iNext+nSnippet).
  151640. */
  151641. for(i=0; i<pIter->nPhrase; i++){
  151642. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  151643. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  151644. }
  151645. }else{
  151646. int iStart;
  151647. int iEnd = 0x7FFFFFFF;
  151648. for(i=0; i<pIter->nPhrase; i++){
  151649. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  151650. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  151651. iEnd = pPhrase->iHead;
  151652. }
  151653. }
  151654. if( iEnd==0x7FFFFFFF ){
  151655. return 1;
  151656. }
  151657. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  151658. for(i=0; i<pIter->nPhrase; i++){
  151659. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  151660. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  151661. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  151662. }
  151663. }
  151664. return 0;
  151665. }
  151666. /*
  151667. ** Retrieve information about the current candidate snippet of snippet
  151668. ** iterator pIter.
  151669. */
  151670. static void fts3SnippetDetails(
  151671. SnippetIter *pIter, /* Snippet iterator */
  151672. u64 mCovered, /* Bitmask of phrases already covered */
  151673. int *piToken, /* OUT: First token of proposed snippet */
  151674. int *piScore, /* OUT: "Score" for this snippet */
  151675. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  151676. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  151677. ){
  151678. int iStart = pIter->iCurrent; /* First token of snippet */
  151679. int iScore = 0; /* Score of this snippet */
  151680. int i; /* Loop counter */
  151681. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  151682. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  151683. for(i=0; i<pIter->nPhrase; i++){
  151684. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  151685. if( pPhrase->pTail ){
  151686. char *pCsr = pPhrase->pTail;
  151687. int iCsr = pPhrase->iTail;
  151688. while( iCsr<(iStart+pIter->nSnippet) ){
  151689. int j;
  151690. u64 mPhrase = (u64)1 << i;
  151691. u64 mPos = (u64)1 << (iCsr - iStart);
  151692. assert( iCsr>=iStart );
  151693. if( (mCover|mCovered)&mPhrase ){
  151694. iScore++;
  151695. }else{
  151696. iScore += 1000;
  151697. }
  151698. mCover |= mPhrase;
  151699. for(j=0; j<pPhrase->nToken; j++){
  151700. mHighlight |= (mPos>>j);
  151701. }
  151702. if( 0==(*pCsr & 0x0FE) ) break;
  151703. fts3GetDeltaPosition(&pCsr, &iCsr);
  151704. }
  151705. }
  151706. }
  151707. /* Set the output variables before returning. */
  151708. *piToken = iStart;
  151709. *piScore = iScore;
  151710. *pmCover = mCover;
  151711. *pmHighlight = mHighlight;
  151712. }
  151713. /*
  151714. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  151715. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  151716. */
  151717. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  151718. SnippetIter *p = (SnippetIter *)ctx;
  151719. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  151720. char *pCsr;
  151721. int rc;
  151722. pPhrase->nToken = pExpr->pPhrase->nToken;
  151723. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  151724. assert( rc==SQLITE_OK || pCsr==0 );
  151725. if( pCsr ){
  151726. int iFirst = 0;
  151727. pPhrase->pList = pCsr;
  151728. fts3GetDeltaPosition(&pCsr, &iFirst);
  151729. assert( iFirst>=0 );
  151730. pPhrase->pHead = pCsr;
  151731. pPhrase->pTail = pCsr;
  151732. pPhrase->iHead = iFirst;
  151733. pPhrase->iTail = iFirst;
  151734. }else{
  151735. assert( rc!=SQLITE_OK || (
  151736. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  151737. ));
  151738. }
  151739. return rc;
  151740. }
  151741. /*
  151742. ** Select the fragment of text consisting of nFragment contiguous tokens
  151743. ** from column iCol that represent the "best" snippet. The best snippet
  151744. ** is the snippet with the highest score, where scores are calculated
  151745. ** by adding:
  151746. **
  151747. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  151748. **
  151749. ** (b) +1000 points for the first occurrence of each matchable phrase in
  151750. ** the snippet for which the corresponding mCovered bit is not set.
  151751. **
  151752. ** The selected snippet parameters are stored in structure *pFragment before
  151753. ** returning. The score of the selected snippet is stored in *piScore
  151754. ** before returning.
  151755. */
  151756. static int fts3BestSnippet(
  151757. int nSnippet, /* Desired snippet length */
  151758. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  151759. int iCol, /* Index of column to create snippet from */
  151760. u64 mCovered, /* Mask of phrases already covered */
  151761. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  151762. SnippetFragment *pFragment, /* OUT: Best snippet found */
  151763. int *piScore /* OUT: Score of snippet pFragment */
  151764. ){
  151765. int rc; /* Return Code */
  151766. int nList; /* Number of phrases in expression */
  151767. SnippetIter sIter; /* Iterates through snippet candidates */
  151768. int nByte; /* Number of bytes of space to allocate */
  151769. int iBestScore = -1; /* Best snippet score found so far */
  151770. int i; /* Loop counter */
  151771. memset(&sIter, 0, sizeof(sIter));
  151772. /* Iterate through the phrases in the expression to count them. The same
  151773. ** callback makes sure the doclists are loaded for each phrase.
  151774. */
  151775. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  151776. if( rc!=SQLITE_OK ){
  151777. return rc;
  151778. }
  151779. /* Now that it is known how many phrases there are, allocate and zero
  151780. ** the required space using malloc().
  151781. */
  151782. nByte = sizeof(SnippetPhrase) * nList;
  151783. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  151784. if( !sIter.aPhrase ){
  151785. return SQLITE_NOMEM;
  151786. }
  151787. memset(sIter.aPhrase, 0, nByte);
  151788. /* Initialize the contents of the SnippetIter object. Then iterate through
  151789. ** the set of phrases in the expression to populate the aPhrase[] array.
  151790. */
  151791. sIter.pCsr = pCsr;
  151792. sIter.iCol = iCol;
  151793. sIter.nSnippet = nSnippet;
  151794. sIter.nPhrase = nList;
  151795. sIter.iCurrent = -1;
  151796. rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
  151797. if( rc==SQLITE_OK ){
  151798. /* Set the *pmSeen output variable. */
  151799. for(i=0; i<nList; i++){
  151800. if( sIter.aPhrase[i].pHead ){
  151801. *pmSeen |= (u64)1 << i;
  151802. }
  151803. }
  151804. /* Loop through all candidate snippets. Store the best snippet in
  151805. ** *pFragment. Store its associated 'score' in iBestScore.
  151806. */
  151807. pFragment->iCol = iCol;
  151808. while( !fts3SnippetNextCandidate(&sIter) ){
  151809. int iPos;
  151810. int iScore;
  151811. u64 mCover;
  151812. u64 mHighlite;
  151813. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
  151814. assert( iScore>=0 );
  151815. if( iScore>iBestScore ){
  151816. pFragment->iPos = iPos;
  151817. pFragment->hlmask = mHighlite;
  151818. pFragment->covered = mCover;
  151819. iBestScore = iScore;
  151820. }
  151821. }
  151822. *piScore = iBestScore;
  151823. }
  151824. sqlite3_free(sIter.aPhrase);
  151825. return rc;
  151826. }
  151827. /*
  151828. ** Append a string to the string-buffer passed as the first argument.
  151829. **
  151830. ** If nAppend is negative, then the length of the string zAppend is
  151831. ** determined using strlen().
  151832. */
  151833. static int fts3StringAppend(
  151834. StrBuffer *pStr, /* Buffer to append to */
  151835. const char *zAppend, /* Pointer to data to append to buffer */
  151836. int nAppend /* Size of zAppend in bytes (or -1) */
  151837. ){
  151838. if( nAppend<0 ){
  151839. nAppend = (int)strlen(zAppend);
  151840. }
  151841. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  151842. ** to grow the buffer until so that it is big enough to accomadate the
  151843. ** appended data.
  151844. */
  151845. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  151846. int nAlloc = pStr->nAlloc+nAppend+100;
  151847. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  151848. if( !zNew ){
  151849. return SQLITE_NOMEM;
  151850. }
  151851. pStr->z = zNew;
  151852. pStr->nAlloc = nAlloc;
  151853. }
  151854. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  151855. /* Append the data to the string buffer. */
  151856. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  151857. pStr->n += nAppend;
  151858. pStr->z[pStr->n] = '\0';
  151859. return SQLITE_OK;
  151860. }
  151861. /*
  151862. ** The fts3BestSnippet() function often selects snippets that end with a
  151863. ** query term. That is, the final term of the snippet is always a term
  151864. ** that requires highlighting. For example, if 'X' is a highlighted term
  151865. ** and '.' is a non-highlighted term, BestSnippet() may select:
  151866. **
  151867. ** ........X.....X
  151868. **
  151869. ** This function "shifts" the beginning of the snippet forward in the
  151870. ** document so that there are approximately the same number of
  151871. ** non-highlighted terms to the right of the final highlighted term as there
  151872. ** are to the left of the first highlighted term. For example, to this:
  151873. **
  151874. ** ....X.....X....
  151875. **
  151876. ** This is done as part of extracting the snippet text, not when selecting
  151877. ** the snippet. Snippet selection is done based on doclists only, so there
  151878. ** is no way for fts3BestSnippet() to know whether or not the document
  151879. ** actually contains terms that follow the final highlighted term.
  151880. */
  151881. static int fts3SnippetShift(
  151882. Fts3Table *pTab, /* FTS3 table snippet comes from */
  151883. int iLangid, /* Language id to use in tokenizing */
  151884. int nSnippet, /* Number of tokens desired for snippet */
  151885. const char *zDoc, /* Document text to extract snippet from */
  151886. int nDoc, /* Size of buffer zDoc in bytes */
  151887. int *piPos, /* IN/OUT: First token of snippet */
  151888. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  151889. ){
  151890. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  151891. if( hlmask ){
  151892. int nLeft; /* Tokens to the left of first highlight */
  151893. int nRight; /* Tokens to the right of last highlight */
  151894. int nDesired; /* Ideal number of tokens to shift forward */
  151895. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  151896. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  151897. nDesired = (nLeft-nRight)/2;
  151898. /* Ideally, the start of the snippet should be pushed forward in the
  151899. ** document nDesired tokens. This block checks if there are actually
  151900. ** nDesired tokens to the right of the snippet. If so, *piPos and
  151901. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  151902. ** right. Otherwise, the snippet is shifted by the number of tokens
  151903. ** available.
  151904. */
  151905. if( nDesired>0 ){
  151906. int nShift; /* Number of tokens to shift snippet by */
  151907. int iCurrent = 0; /* Token counter */
  151908. int rc; /* Return Code */
  151909. sqlite3_tokenizer_module *pMod;
  151910. sqlite3_tokenizer_cursor *pC;
  151911. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  151912. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  151913. ** or more tokens in zDoc/nDoc.
  151914. */
  151915. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  151916. if( rc!=SQLITE_OK ){
  151917. return rc;
  151918. }
  151919. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  151920. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  151921. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  151922. }
  151923. pMod->xClose(pC);
  151924. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  151925. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  151926. assert( nShift<=nDesired );
  151927. if( nShift>0 ){
  151928. *piPos += nShift;
  151929. *pHlmask = hlmask >> nShift;
  151930. }
  151931. }
  151932. }
  151933. return SQLITE_OK;
  151934. }
  151935. /*
  151936. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  151937. ** append it to string buffer pOut.
  151938. */
  151939. static int fts3SnippetText(
  151940. Fts3Cursor *pCsr, /* FTS3 Cursor */
  151941. SnippetFragment *pFragment, /* Snippet to extract */
  151942. int iFragment, /* Fragment number */
  151943. int isLast, /* True for final fragment in snippet */
  151944. int nSnippet, /* Number of tokens in extracted snippet */
  151945. const char *zOpen, /* String inserted before highlighted term */
  151946. const char *zClose, /* String inserted after highlighted term */
  151947. const char *zEllipsis, /* String inserted between snippets */
  151948. StrBuffer *pOut /* Write output here */
  151949. ){
  151950. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  151951. int rc; /* Return code */
  151952. const char *zDoc; /* Document text to extract snippet from */
  151953. int nDoc; /* Size of zDoc in bytes */
  151954. int iCurrent = 0; /* Current token number of document */
  151955. int iEnd = 0; /* Byte offset of end of current token */
  151956. int isShiftDone = 0; /* True after snippet is shifted */
  151957. int iPos = pFragment->iPos; /* First token of snippet */
  151958. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  151959. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  151960. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  151961. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  151962. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  151963. if( zDoc==0 ){
  151964. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  151965. return SQLITE_NOMEM;
  151966. }
  151967. return SQLITE_OK;
  151968. }
  151969. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  151970. /* Open a token cursor on the document. */
  151971. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  151972. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  151973. if( rc!=SQLITE_OK ){
  151974. return rc;
  151975. }
  151976. while( rc==SQLITE_OK ){
  151977. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  151978. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  151979. int iBegin = 0; /* Offset in zDoc of start of token */
  151980. int iFin = 0; /* Offset in zDoc of end of token */
  151981. int isHighlight = 0; /* True for highlighted terms */
  151982. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  151983. ** in the FTS code the variable that the third argument to xNext points to
  151984. ** is initialized to zero before the first (*but not necessarily
  151985. ** subsequent*) call to xNext(). This is done for a particular application
  151986. ** that needs to know whether or not the tokenizer is being used for
  151987. ** snippet generation or for some other purpose.
  151988. **
  151989. ** Extreme care is required when writing code to depend on this
  151990. ** initialization. It is not a documented part of the tokenizer interface.
  151991. ** If a tokenizer is used directly by any code outside of FTS, this
  151992. ** convention might not be respected. */
  151993. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  151994. if( rc!=SQLITE_OK ){
  151995. if( rc==SQLITE_DONE ){
  151996. /* Special case - the last token of the snippet is also the last token
  151997. ** of the column. Append any punctuation that occurred between the end
  151998. ** of the previous token and the end of the document to the output.
  151999. ** Then break out of the loop. */
  152000. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  152001. }
  152002. break;
  152003. }
  152004. if( iCurrent<iPos ){ continue; }
  152005. if( !isShiftDone ){
  152006. int n = nDoc - iBegin;
  152007. rc = fts3SnippetShift(
  152008. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  152009. );
  152010. isShiftDone = 1;
  152011. /* Now that the shift has been done, check if the initial "..." are
  152012. ** required. They are required if (a) this is not the first fragment,
  152013. ** or (b) this fragment does not begin at position 0 of its column.
  152014. */
  152015. if( rc==SQLITE_OK ){
  152016. if( iPos>0 || iFragment>0 ){
  152017. rc = fts3StringAppend(pOut, zEllipsis, -1);
  152018. }else if( iBegin ){
  152019. rc = fts3StringAppend(pOut, zDoc, iBegin);
  152020. }
  152021. }
  152022. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  152023. }
  152024. if( iCurrent>=(iPos+nSnippet) ){
  152025. if( isLast ){
  152026. rc = fts3StringAppend(pOut, zEllipsis, -1);
  152027. }
  152028. break;
  152029. }
  152030. /* Set isHighlight to true if this term should be highlighted. */
  152031. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  152032. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  152033. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  152034. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  152035. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  152036. iEnd = iFin;
  152037. }
  152038. pMod->xClose(pC);
  152039. return rc;
  152040. }
  152041. /*
  152042. ** This function is used to count the entries in a column-list (a
  152043. ** delta-encoded list of term offsets within a single column of a single
  152044. ** row). When this function is called, *ppCollist should point to the
  152045. ** beginning of the first varint in the column-list (the varint that
  152046. ** contains the position of the first matching term in the column data).
  152047. ** Before returning, *ppCollist is set to point to the first byte after
  152048. ** the last varint in the column-list (either the 0x00 signifying the end
  152049. ** of the position-list, or the 0x01 that precedes the column number of
  152050. ** the next column in the position-list).
  152051. **
  152052. ** The number of elements in the column-list is returned.
  152053. */
  152054. static int fts3ColumnlistCount(char **ppCollist){
  152055. char *pEnd = *ppCollist;
  152056. char c = 0;
  152057. int nEntry = 0;
  152058. /* A column-list is terminated by either a 0x01 or 0x00. */
  152059. while( 0xFE & (*pEnd | c) ){
  152060. c = *pEnd++ & 0x80;
  152061. if( !c ) nEntry++;
  152062. }
  152063. *ppCollist = pEnd;
  152064. return nEntry;
  152065. }
  152066. /*
  152067. ** This function gathers 'y' or 'b' data for a single phrase.
  152068. */
  152069. static void fts3ExprLHits(
  152070. Fts3Expr *pExpr, /* Phrase expression node */
  152071. MatchInfo *p /* Matchinfo context */
  152072. ){
  152073. Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
  152074. int iStart;
  152075. Fts3Phrase *pPhrase = pExpr->pPhrase;
  152076. char *pIter = pPhrase->doclist.pList;
  152077. int iCol = 0;
  152078. assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
  152079. if( p->flag==FTS3_MATCHINFO_LHITS ){
  152080. iStart = pExpr->iPhrase * p->nCol;
  152081. }else{
  152082. iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
  152083. }
  152084. while( 1 ){
  152085. int nHit = fts3ColumnlistCount(&pIter);
  152086. if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
  152087. if( p->flag==FTS3_MATCHINFO_LHITS ){
  152088. p->aMatchinfo[iStart + iCol] = (u32)nHit;
  152089. }else if( nHit ){
  152090. p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
  152091. }
  152092. }
  152093. assert( *pIter==0x00 || *pIter==0x01 );
  152094. if( *pIter!=0x01 ) break;
  152095. pIter++;
  152096. pIter += fts3GetVarint32(pIter, &iCol);
  152097. }
  152098. }
  152099. /*
  152100. ** Gather the results for matchinfo directives 'y' and 'b'.
  152101. */
  152102. static void fts3ExprLHitGather(
  152103. Fts3Expr *pExpr,
  152104. MatchInfo *p
  152105. ){
  152106. assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
  152107. if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
  152108. if( pExpr->pLeft ){
  152109. fts3ExprLHitGather(pExpr->pLeft, p);
  152110. fts3ExprLHitGather(pExpr->pRight, p);
  152111. }else{
  152112. fts3ExprLHits(pExpr, p);
  152113. }
  152114. }
  152115. }
  152116. /*
  152117. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  152118. ** for a single query.
  152119. **
  152120. ** fts3ExprIterate() callback to load the 'global' elements of a
  152121. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  152122. ** of the matchinfo array that are constant for all rows returned by the
  152123. ** current query.
  152124. **
  152125. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  152126. ** function populates Matchinfo.aMatchinfo[] as follows:
  152127. **
  152128. ** for(iCol=0; iCol<nCol; iCol++){
  152129. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  152130. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  152131. ** }
  152132. **
  152133. ** where X is the number of matches for phrase iPhrase is column iCol of all
  152134. ** rows of the table. Y is the number of rows for which column iCol contains
  152135. ** at least one instance of phrase iPhrase.
  152136. **
  152137. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  152138. ** Y values are set to nDoc, where nDoc is the number of documents in the
  152139. ** file system. This is done because the full-text index doclist is required
  152140. ** to calculate these values properly, and the full-text index doclist is
  152141. ** not available for deferred tokens.
  152142. */
  152143. static int fts3ExprGlobalHitsCb(
  152144. Fts3Expr *pExpr, /* Phrase expression node */
  152145. int iPhrase, /* Phrase number (numbered from zero) */
  152146. void *pCtx /* Pointer to MatchInfo structure */
  152147. ){
  152148. MatchInfo *p = (MatchInfo *)pCtx;
  152149. return sqlite3Fts3EvalPhraseStats(
  152150. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  152151. );
  152152. }
  152153. /*
  152154. ** fts3ExprIterate() callback used to collect the "local" part of the
  152155. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  152156. ** array that are different for each row returned by the query.
  152157. */
  152158. static int fts3ExprLocalHitsCb(
  152159. Fts3Expr *pExpr, /* Phrase expression node */
  152160. int iPhrase, /* Phrase number */
  152161. void *pCtx /* Pointer to MatchInfo structure */
  152162. ){
  152163. int rc = SQLITE_OK;
  152164. MatchInfo *p = (MatchInfo *)pCtx;
  152165. int iStart = iPhrase * p->nCol * 3;
  152166. int i;
  152167. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  152168. char *pCsr;
  152169. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  152170. if( pCsr ){
  152171. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  152172. }else{
  152173. p->aMatchinfo[iStart+i*3] = 0;
  152174. }
  152175. }
  152176. return rc;
  152177. }
  152178. static int fts3MatchinfoCheck(
  152179. Fts3Table *pTab,
  152180. char cArg,
  152181. char **pzErr
  152182. ){
  152183. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  152184. || (cArg==FTS3_MATCHINFO_NCOL)
  152185. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  152186. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  152187. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  152188. || (cArg==FTS3_MATCHINFO_LCS)
  152189. || (cArg==FTS3_MATCHINFO_HITS)
  152190. || (cArg==FTS3_MATCHINFO_LHITS)
  152191. || (cArg==FTS3_MATCHINFO_LHITS_BM)
  152192. ){
  152193. return SQLITE_OK;
  152194. }
  152195. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
  152196. return SQLITE_ERROR;
  152197. }
  152198. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  152199. int nVal; /* Number of integers output by cArg */
  152200. switch( cArg ){
  152201. case FTS3_MATCHINFO_NDOC:
  152202. case FTS3_MATCHINFO_NPHRASE:
  152203. case FTS3_MATCHINFO_NCOL:
  152204. nVal = 1;
  152205. break;
  152206. case FTS3_MATCHINFO_AVGLENGTH:
  152207. case FTS3_MATCHINFO_LENGTH:
  152208. case FTS3_MATCHINFO_LCS:
  152209. nVal = pInfo->nCol;
  152210. break;
  152211. case FTS3_MATCHINFO_LHITS:
  152212. nVal = pInfo->nCol * pInfo->nPhrase;
  152213. break;
  152214. case FTS3_MATCHINFO_LHITS_BM:
  152215. nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
  152216. break;
  152217. default:
  152218. assert( cArg==FTS3_MATCHINFO_HITS );
  152219. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  152220. break;
  152221. }
  152222. return nVal;
  152223. }
  152224. static int fts3MatchinfoSelectDoctotal(
  152225. Fts3Table *pTab,
  152226. sqlite3_stmt **ppStmt,
  152227. sqlite3_int64 *pnDoc,
  152228. const char **paLen
  152229. ){
  152230. sqlite3_stmt *pStmt;
  152231. const char *a;
  152232. sqlite3_int64 nDoc;
  152233. if( !*ppStmt ){
  152234. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  152235. if( rc!=SQLITE_OK ) return rc;
  152236. }
  152237. pStmt = *ppStmt;
  152238. assert( sqlite3_data_count(pStmt)==1 );
  152239. a = sqlite3_column_blob(pStmt, 0);
  152240. a += sqlite3Fts3GetVarint(a, &nDoc);
  152241. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  152242. *pnDoc = (u32)nDoc;
  152243. if( paLen ) *paLen = a;
  152244. return SQLITE_OK;
  152245. }
  152246. /*
  152247. ** An instance of the following structure is used to store state while
  152248. ** iterating through a multi-column position-list corresponding to the
  152249. ** hits for a single phrase on a single row in order to calculate the
  152250. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  152251. */
  152252. typedef struct LcsIterator LcsIterator;
  152253. struct LcsIterator {
  152254. Fts3Expr *pExpr; /* Pointer to phrase expression */
  152255. int iPosOffset; /* Tokens count up to end of this phrase */
  152256. char *pRead; /* Cursor used to iterate through aDoclist */
  152257. int iPos; /* Current position */
  152258. };
  152259. /*
  152260. ** If LcsIterator.iCol is set to the following value, the iterator has
  152261. ** finished iterating through all offsets for all columns.
  152262. */
  152263. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  152264. static int fts3MatchinfoLcsCb(
  152265. Fts3Expr *pExpr, /* Phrase expression node */
  152266. int iPhrase, /* Phrase number (numbered from zero) */
  152267. void *pCtx /* Pointer to MatchInfo structure */
  152268. ){
  152269. LcsIterator *aIter = (LcsIterator *)pCtx;
  152270. aIter[iPhrase].pExpr = pExpr;
  152271. return SQLITE_OK;
  152272. }
  152273. /*
  152274. ** Advance the iterator passed as an argument to the next position. Return
  152275. ** 1 if the iterator is at EOF or if it now points to the start of the
  152276. ** position list for the next column.
  152277. */
  152278. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  152279. char *pRead = pIter->pRead;
  152280. sqlite3_int64 iRead;
  152281. int rc = 0;
  152282. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  152283. if( iRead==0 || iRead==1 ){
  152284. pRead = 0;
  152285. rc = 1;
  152286. }else{
  152287. pIter->iPos += (int)(iRead-2);
  152288. }
  152289. pIter->pRead = pRead;
  152290. return rc;
  152291. }
  152292. /*
  152293. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  152294. **
  152295. ** If the call is successful, the longest-common-substring lengths for each
  152296. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  152297. ** array before returning. SQLITE_OK is returned in this case.
  152298. **
  152299. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  152300. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  152301. ** undefined.
  152302. */
  152303. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  152304. LcsIterator *aIter;
  152305. int i;
  152306. int iCol;
  152307. int nToken = 0;
  152308. /* Allocate and populate the array of LcsIterator objects. The array
  152309. ** contains one element for each matchable phrase in the query.
  152310. **/
  152311. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  152312. if( !aIter ) return SQLITE_NOMEM;
  152313. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  152314. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  152315. for(i=0; i<pInfo->nPhrase; i++){
  152316. LcsIterator *pIter = &aIter[i];
  152317. nToken -= pIter->pExpr->pPhrase->nToken;
  152318. pIter->iPosOffset = nToken;
  152319. }
  152320. for(iCol=0; iCol<pInfo->nCol; iCol++){
  152321. int nLcs = 0; /* LCS value for this column */
  152322. int nLive = 0; /* Number of iterators in aIter not at EOF */
  152323. for(i=0; i<pInfo->nPhrase; i++){
  152324. int rc;
  152325. LcsIterator *pIt = &aIter[i];
  152326. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  152327. if( rc!=SQLITE_OK ) return rc;
  152328. if( pIt->pRead ){
  152329. pIt->iPos = pIt->iPosOffset;
  152330. fts3LcsIteratorAdvance(&aIter[i]);
  152331. nLive++;
  152332. }
  152333. }
  152334. while( nLive>0 ){
  152335. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  152336. int nThisLcs = 0; /* LCS for the current iterator positions */
  152337. for(i=0; i<pInfo->nPhrase; i++){
  152338. LcsIterator *pIter = &aIter[i];
  152339. if( pIter->pRead==0 ){
  152340. /* This iterator is already at EOF for this column. */
  152341. nThisLcs = 0;
  152342. }else{
  152343. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  152344. pAdv = pIter;
  152345. }
  152346. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  152347. nThisLcs++;
  152348. }else{
  152349. nThisLcs = 1;
  152350. }
  152351. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  152352. }
  152353. }
  152354. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  152355. }
  152356. pInfo->aMatchinfo[iCol] = nLcs;
  152357. }
  152358. sqlite3_free(aIter);
  152359. return SQLITE_OK;
  152360. }
  152361. /*
  152362. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  152363. ** be returned by the matchinfo() function. Argument zArg contains the
  152364. ** format string passed as the second argument to matchinfo (or the
  152365. ** default value "pcx" if no second argument was specified). The format
  152366. ** string has already been validated and the pInfo->aMatchinfo[] array
  152367. ** is guaranteed to be large enough for the output.
  152368. **
  152369. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  152370. ** If it is false, then assume that those fields that do not change between
  152371. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  152372. ** have already been populated.
  152373. **
  152374. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  152375. ** occurs. If a value other than SQLITE_OK is returned, the state the
  152376. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  152377. */
  152378. static int fts3MatchinfoValues(
  152379. Fts3Cursor *pCsr, /* FTS3 cursor object */
  152380. int bGlobal, /* True to grab the global stats */
  152381. MatchInfo *pInfo, /* Matchinfo context object */
  152382. const char *zArg /* Matchinfo format string */
  152383. ){
  152384. int rc = SQLITE_OK;
  152385. int i;
  152386. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  152387. sqlite3_stmt *pSelect = 0;
  152388. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  152389. pInfo->flag = zArg[i];
  152390. switch( zArg[i] ){
  152391. case FTS3_MATCHINFO_NPHRASE:
  152392. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  152393. break;
  152394. case FTS3_MATCHINFO_NCOL:
  152395. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  152396. break;
  152397. case FTS3_MATCHINFO_NDOC:
  152398. if( bGlobal ){
  152399. sqlite3_int64 nDoc = 0;
  152400. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  152401. pInfo->aMatchinfo[0] = (u32)nDoc;
  152402. }
  152403. break;
  152404. case FTS3_MATCHINFO_AVGLENGTH:
  152405. if( bGlobal ){
  152406. sqlite3_int64 nDoc; /* Number of rows in table */
  152407. const char *a; /* Aggregate column length array */
  152408. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  152409. if( rc==SQLITE_OK ){
  152410. int iCol;
  152411. for(iCol=0; iCol<pInfo->nCol; iCol++){
  152412. u32 iVal;
  152413. sqlite3_int64 nToken;
  152414. a += sqlite3Fts3GetVarint(a, &nToken);
  152415. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  152416. pInfo->aMatchinfo[iCol] = iVal;
  152417. }
  152418. }
  152419. }
  152420. break;
  152421. case FTS3_MATCHINFO_LENGTH: {
  152422. sqlite3_stmt *pSelectDocsize = 0;
  152423. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  152424. if( rc==SQLITE_OK ){
  152425. int iCol;
  152426. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  152427. for(iCol=0; iCol<pInfo->nCol; iCol++){
  152428. sqlite3_int64 nToken;
  152429. a += sqlite3Fts3GetVarint(a, &nToken);
  152430. pInfo->aMatchinfo[iCol] = (u32)nToken;
  152431. }
  152432. }
  152433. sqlite3_reset(pSelectDocsize);
  152434. break;
  152435. }
  152436. case FTS3_MATCHINFO_LCS:
  152437. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  152438. if( rc==SQLITE_OK ){
  152439. rc = fts3MatchinfoLcs(pCsr, pInfo);
  152440. }
  152441. break;
  152442. case FTS3_MATCHINFO_LHITS_BM:
  152443. case FTS3_MATCHINFO_LHITS: {
  152444. int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
  152445. memset(pInfo->aMatchinfo, 0, nZero);
  152446. fts3ExprLHitGather(pCsr->pExpr, pInfo);
  152447. break;
  152448. }
  152449. default: {
  152450. Fts3Expr *pExpr;
  152451. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  152452. pExpr = pCsr->pExpr;
  152453. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  152454. if( rc!=SQLITE_OK ) break;
  152455. if( bGlobal ){
  152456. if( pCsr->pDeferred ){
  152457. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  152458. if( rc!=SQLITE_OK ) break;
  152459. }
  152460. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  152461. sqlite3Fts3EvalTestDeferred(pCsr, &rc);
  152462. if( rc!=SQLITE_OK ) break;
  152463. }
  152464. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  152465. break;
  152466. }
  152467. }
  152468. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  152469. }
  152470. sqlite3_reset(pSelect);
  152471. return rc;
  152472. }
  152473. /*
  152474. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  152475. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  152476. */
  152477. static void fts3GetMatchinfo(
  152478. sqlite3_context *pCtx, /* Return results here */
  152479. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  152480. const char *zArg /* Second argument to matchinfo() function */
  152481. ){
  152482. MatchInfo sInfo;
  152483. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  152484. int rc = SQLITE_OK;
  152485. int bGlobal = 0; /* Collect 'global' stats as well as local */
  152486. u32 *aOut = 0;
  152487. void (*xDestroyOut)(void*) = 0;
  152488. memset(&sInfo, 0, sizeof(MatchInfo));
  152489. sInfo.pCursor = pCsr;
  152490. sInfo.nCol = pTab->nColumn;
  152491. /* If there is cached matchinfo() data, but the format string for the
  152492. ** cache does not match the format string for this request, discard
  152493. ** the cached data. */
  152494. if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
  152495. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  152496. pCsr->pMIBuffer = 0;
  152497. }
  152498. /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
  152499. ** matchinfo function has been called for this query. In this case
  152500. ** allocate the array used to accumulate the matchinfo data and
  152501. ** initialize those elements that are constant for every row.
  152502. */
  152503. if( pCsr->pMIBuffer==0 ){
  152504. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  152505. int i; /* Used to iterate through zArg */
  152506. /* Determine the number of phrases in the query */
  152507. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  152508. sInfo.nPhrase = pCsr->nPhrase;
  152509. /* Determine the number of integers in the buffer returned by this call. */
  152510. for(i=0; zArg[i]; i++){
  152511. char *zErr = 0;
  152512. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  152513. sqlite3_result_error(pCtx, zErr, -1);
  152514. sqlite3_free(zErr);
  152515. return;
  152516. }
  152517. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  152518. }
  152519. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  152520. pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
  152521. if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
  152522. pCsr->isMatchinfoNeeded = 1;
  152523. bGlobal = 1;
  152524. }
  152525. if( rc==SQLITE_OK ){
  152526. xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
  152527. if( xDestroyOut==0 ){
  152528. rc = SQLITE_NOMEM;
  152529. }
  152530. }
  152531. if( rc==SQLITE_OK ){
  152532. sInfo.aMatchinfo = aOut;
  152533. sInfo.nPhrase = pCsr->nPhrase;
  152534. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  152535. if( bGlobal ){
  152536. fts3MIBufferSetGlobal(pCsr->pMIBuffer);
  152537. }
  152538. }
  152539. if( rc!=SQLITE_OK ){
  152540. sqlite3_result_error_code(pCtx, rc);
  152541. if( xDestroyOut ) xDestroyOut(aOut);
  152542. }else{
  152543. int n = pCsr->pMIBuffer->nElem * sizeof(u32);
  152544. sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
  152545. }
  152546. }
  152547. /*
  152548. ** Implementation of snippet() function.
  152549. */
  152550. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  152551. sqlite3_context *pCtx, /* SQLite function call context */
  152552. Fts3Cursor *pCsr, /* Cursor object */
  152553. const char *zStart, /* Snippet start text - "<b>" */
  152554. const char *zEnd, /* Snippet end text - "</b>" */
  152555. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  152556. int iCol, /* Extract snippet from this column */
  152557. int nToken /* Approximate number of tokens in snippet */
  152558. ){
  152559. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  152560. int rc = SQLITE_OK;
  152561. int i;
  152562. StrBuffer res = {0, 0, 0};
  152563. /* The returned text includes up to four fragments of text extracted from
  152564. ** the data in the current row. The first iteration of the for(...) loop
  152565. ** below attempts to locate a single fragment of text nToken tokens in
  152566. ** size that contains at least one instance of all phrases in the query
  152567. ** expression that appear in the current row. If such a fragment of text
  152568. ** cannot be found, the second iteration of the loop attempts to locate
  152569. ** a pair of fragments, and so on.
  152570. */
  152571. int nSnippet = 0; /* Number of fragments in this snippet */
  152572. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  152573. int nFToken = -1; /* Number of tokens in each fragment */
  152574. if( !pCsr->pExpr ){
  152575. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  152576. return;
  152577. }
  152578. for(nSnippet=1; 1; nSnippet++){
  152579. int iSnip; /* Loop counter 0..nSnippet-1 */
  152580. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  152581. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  152582. if( nToken>=0 ){
  152583. nFToken = (nToken+nSnippet-1) / nSnippet;
  152584. }else{
  152585. nFToken = -1 * nToken;
  152586. }
  152587. for(iSnip=0; iSnip<nSnippet; iSnip++){
  152588. int iBestScore = -1; /* Best score of columns checked so far */
  152589. int iRead; /* Used to iterate through columns */
  152590. SnippetFragment *pFragment = &aSnippet[iSnip];
  152591. memset(pFragment, 0, sizeof(*pFragment));
  152592. /* Loop through all columns of the table being considered for snippets.
  152593. ** If the iCol argument to this function was negative, this means all
  152594. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  152595. */
  152596. for(iRead=0; iRead<pTab->nColumn; iRead++){
  152597. SnippetFragment sF = {0, 0, 0, 0};
  152598. int iS = 0;
  152599. if( iCol>=0 && iRead!=iCol ) continue;
  152600. /* Find the best snippet of nFToken tokens in column iRead. */
  152601. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  152602. if( rc!=SQLITE_OK ){
  152603. goto snippet_out;
  152604. }
  152605. if( iS>iBestScore ){
  152606. *pFragment = sF;
  152607. iBestScore = iS;
  152608. }
  152609. }
  152610. mCovered |= pFragment->covered;
  152611. }
  152612. /* If all query phrases seen by fts3BestSnippet() are present in at least
  152613. ** one of the nSnippet snippet fragments, break out of the loop.
  152614. */
  152615. assert( (mCovered&mSeen)==mCovered );
  152616. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  152617. }
  152618. assert( nFToken>0 );
  152619. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  152620. rc = fts3SnippetText(pCsr, &aSnippet[i],
  152621. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  152622. );
  152623. }
  152624. snippet_out:
  152625. sqlite3Fts3SegmentsClose(pTab);
  152626. if( rc!=SQLITE_OK ){
  152627. sqlite3_result_error_code(pCtx, rc);
  152628. sqlite3_free(res.z);
  152629. }else{
  152630. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  152631. }
  152632. }
  152633. typedef struct TermOffset TermOffset;
  152634. typedef struct TermOffsetCtx TermOffsetCtx;
  152635. struct TermOffset {
  152636. char *pList; /* Position-list */
  152637. int iPos; /* Position just read from pList */
  152638. int iOff; /* Offset of this term from read positions */
  152639. };
  152640. struct TermOffsetCtx {
  152641. Fts3Cursor *pCsr;
  152642. int iCol; /* Column of table to populate aTerm for */
  152643. int iTerm;
  152644. sqlite3_int64 iDocid;
  152645. TermOffset *aTerm;
  152646. };
  152647. /*
  152648. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  152649. */
  152650. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  152651. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  152652. int nTerm; /* Number of tokens in phrase */
  152653. int iTerm; /* For looping through nTerm phrase terms */
  152654. char *pList; /* Pointer to position list for phrase */
  152655. int iPos = 0; /* First position in position-list */
  152656. int rc;
  152657. UNUSED_PARAMETER(iPhrase);
  152658. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  152659. nTerm = pExpr->pPhrase->nToken;
  152660. if( pList ){
  152661. fts3GetDeltaPosition(&pList, &iPos);
  152662. assert( iPos>=0 );
  152663. }
  152664. for(iTerm=0; iTerm<nTerm; iTerm++){
  152665. TermOffset *pT = &p->aTerm[p->iTerm++];
  152666. pT->iOff = nTerm-iTerm-1;
  152667. pT->pList = pList;
  152668. pT->iPos = iPos;
  152669. }
  152670. return rc;
  152671. }
  152672. /*
  152673. ** Implementation of offsets() function.
  152674. */
  152675. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  152676. sqlite3_context *pCtx, /* SQLite function call context */
  152677. Fts3Cursor *pCsr /* Cursor object */
  152678. ){
  152679. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  152680. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  152681. int rc; /* Return Code */
  152682. int nToken; /* Number of tokens in query */
  152683. int iCol; /* Column currently being processed */
  152684. StrBuffer res = {0, 0, 0}; /* Result string */
  152685. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  152686. if( !pCsr->pExpr ){
  152687. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  152688. return;
  152689. }
  152690. memset(&sCtx, 0, sizeof(sCtx));
  152691. assert( pCsr->isRequireSeek==0 );
  152692. /* Count the number of terms in the query */
  152693. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  152694. if( rc!=SQLITE_OK ) goto offsets_out;
  152695. /* Allocate the array of TermOffset iterators. */
  152696. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  152697. if( 0==sCtx.aTerm ){
  152698. rc = SQLITE_NOMEM;
  152699. goto offsets_out;
  152700. }
  152701. sCtx.iDocid = pCsr->iPrevId;
  152702. sCtx.pCsr = pCsr;
  152703. /* Loop through the table columns, appending offset information to
  152704. ** string-buffer res for each column.
  152705. */
  152706. for(iCol=0; iCol<pTab->nColumn; iCol++){
  152707. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  152708. const char *ZDUMMY; /* Dummy argument used with xNext() */
  152709. int NDUMMY = 0; /* Dummy argument used with xNext() */
  152710. int iStart = 0;
  152711. int iEnd = 0;
  152712. int iCurrent = 0;
  152713. const char *zDoc;
  152714. int nDoc;
  152715. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  152716. ** no way that this operation can fail, so the return code from
  152717. ** fts3ExprIterate() can be discarded.
  152718. */
  152719. sCtx.iCol = iCol;
  152720. sCtx.iTerm = 0;
  152721. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
  152722. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  152723. ** in column iCol, jump immediately to the next iteration of the loop.
  152724. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  152725. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  152726. ** to the caller.
  152727. */
  152728. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  152729. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  152730. if( zDoc==0 ){
  152731. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  152732. continue;
  152733. }
  152734. rc = SQLITE_NOMEM;
  152735. goto offsets_out;
  152736. }
  152737. /* Initialize a tokenizer iterator to iterate through column iCol. */
  152738. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  152739. zDoc, nDoc, &pC
  152740. );
  152741. if( rc!=SQLITE_OK ) goto offsets_out;
  152742. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  152743. while( rc==SQLITE_OK ){
  152744. int i; /* Used to loop through terms */
  152745. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  152746. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  152747. for(i=0; i<nToken; i++){
  152748. TermOffset *pT = &sCtx.aTerm[i];
  152749. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  152750. iMinPos = pT->iPos-pT->iOff;
  152751. pTerm = pT;
  152752. }
  152753. }
  152754. if( !pTerm ){
  152755. /* All offsets for this column have been gathered. */
  152756. rc = SQLITE_DONE;
  152757. }else{
  152758. assert( iCurrent<=iMinPos );
  152759. if( 0==(0xFE&*pTerm->pList) ){
  152760. pTerm->pList = 0;
  152761. }else{
  152762. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  152763. }
  152764. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  152765. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  152766. }
  152767. if( rc==SQLITE_OK ){
  152768. char aBuffer[64];
  152769. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  152770. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  152771. );
  152772. rc = fts3StringAppend(&res, aBuffer, -1);
  152773. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  152774. rc = FTS_CORRUPT_VTAB;
  152775. }
  152776. }
  152777. }
  152778. if( rc==SQLITE_DONE ){
  152779. rc = SQLITE_OK;
  152780. }
  152781. pMod->xClose(pC);
  152782. if( rc!=SQLITE_OK ) goto offsets_out;
  152783. }
  152784. offsets_out:
  152785. sqlite3_free(sCtx.aTerm);
  152786. assert( rc!=SQLITE_DONE );
  152787. sqlite3Fts3SegmentsClose(pTab);
  152788. if( rc!=SQLITE_OK ){
  152789. sqlite3_result_error_code(pCtx, rc);
  152790. sqlite3_free(res.z);
  152791. }else{
  152792. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  152793. }
  152794. return;
  152795. }
  152796. /*
  152797. ** Implementation of matchinfo() function.
  152798. */
  152799. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  152800. sqlite3_context *pContext, /* Function call context */
  152801. Fts3Cursor *pCsr, /* FTS3 table cursor */
  152802. const char *zArg /* Second arg to matchinfo() function */
  152803. ){
  152804. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  152805. const char *zFormat;
  152806. if( zArg ){
  152807. zFormat = zArg;
  152808. }else{
  152809. zFormat = FTS3_MATCHINFO_DEFAULT;
  152810. }
  152811. if( !pCsr->pExpr ){
  152812. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  152813. return;
  152814. }else{
  152815. /* Retrieve matchinfo() data. */
  152816. fts3GetMatchinfo(pContext, pCsr, zFormat);
  152817. sqlite3Fts3SegmentsClose(pTab);
  152818. }
  152819. }
  152820. #endif
  152821. /************** End of fts3_snippet.c ****************************************/
  152822. /************** Begin file fts3_unicode.c ************************************/
  152823. /*
  152824. ** 2012 May 24
  152825. **
  152826. ** The author disclaims copyright to this source code. In place of
  152827. ** a legal notice, here is a blessing:
  152828. **
  152829. ** May you do good and not evil.
  152830. ** May you find forgiveness for yourself and forgive others.
  152831. ** May you share freely, never taking more than you give.
  152832. **
  152833. ******************************************************************************
  152834. **
  152835. ** Implementation of the "unicode" full-text-search tokenizer.
  152836. */
  152837. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  152838. /* #include "fts3Int.h" */
  152839. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  152840. /* #include <assert.h> */
  152841. /* #include <stdlib.h> */
  152842. /* #include <stdio.h> */
  152843. /* #include <string.h> */
  152844. /* #include "fts3_tokenizer.h" */
  152845. /*
  152846. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  152847. ** from the sqlite3 source file utf.c. If this file is compiled as part
  152848. ** of the amalgamation, they are not required.
  152849. */
  152850. #ifndef SQLITE_AMALGAMATION
  152851. static const unsigned char sqlite3Utf8Trans1[] = {
  152852. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  152853. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  152854. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  152855. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  152856. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  152857. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  152858. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  152859. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  152860. };
  152861. #define READ_UTF8(zIn, zTerm, c) \
  152862. c = *(zIn++); \
  152863. if( c>=0xc0 ){ \
  152864. c = sqlite3Utf8Trans1[c-0xc0]; \
  152865. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  152866. c = (c<<6) + (0x3f & *(zIn++)); \
  152867. } \
  152868. if( c<0x80 \
  152869. || (c&0xFFFFF800)==0xD800 \
  152870. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  152871. }
  152872. #define WRITE_UTF8(zOut, c) { \
  152873. if( c<0x00080 ){ \
  152874. *zOut++ = (u8)(c&0xFF); \
  152875. } \
  152876. else if( c<0x00800 ){ \
  152877. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  152878. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  152879. } \
  152880. else if( c<0x10000 ){ \
  152881. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  152882. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  152883. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  152884. }else{ \
  152885. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  152886. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  152887. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  152888. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  152889. } \
  152890. }
  152891. #endif /* ifndef SQLITE_AMALGAMATION */
  152892. typedef struct unicode_tokenizer unicode_tokenizer;
  152893. typedef struct unicode_cursor unicode_cursor;
  152894. struct unicode_tokenizer {
  152895. sqlite3_tokenizer base;
  152896. int bRemoveDiacritic;
  152897. int nException;
  152898. int *aiException;
  152899. };
  152900. struct unicode_cursor {
  152901. sqlite3_tokenizer_cursor base;
  152902. const unsigned char *aInput; /* Input text being tokenized */
  152903. int nInput; /* Size of aInput[] in bytes */
  152904. int iOff; /* Current offset within aInput[] */
  152905. int iToken; /* Index of next token to be returned */
  152906. char *zToken; /* storage for current token */
  152907. int nAlloc; /* space allocated at zToken */
  152908. };
  152909. /*
  152910. ** Destroy a tokenizer allocated by unicodeCreate().
  152911. */
  152912. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  152913. if( pTokenizer ){
  152914. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  152915. sqlite3_free(p->aiException);
  152916. sqlite3_free(p);
  152917. }
  152918. return SQLITE_OK;
  152919. }
  152920. /*
  152921. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  152922. ** statement has specified that the tokenizer for this table shall consider
  152923. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  152924. ** token characters (if bAlnum==1).
  152925. **
  152926. ** For each codepoint in the zIn/nIn string, this function checks if the
  152927. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  152928. ** If so, no action is taken. Otherwise, the codepoint is added to the
  152929. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  152930. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  152931. ** codepoints in the aiException[] array.
  152932. **
  152933. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  152934. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  152935. ** It is not possible to change the behavior of the tokenizer with respect
  152936. ** to these codepoints.
  152937. */
  152938. static int unicodeAddExceptions(
  152939. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  152940. int bAlnum, /* Replace Isalnum() return value with this */
  152941. const char *zIn, /* Array of characters to make exceptions */
  152942. int nIn /* Length of z in bytes */
  152943. ){
  152944. const unsigned char *z = (const unsigned char *)zIn;
  152945. const unsigned char *zTerm = &z[nIn];
  152946. unsigned int iCode;
  152947. int nEntry = 0;
  152948. assert( bAlnum==0 || bAlnum==1 );
  152949. while( z<zTerm ){
  152950. READ_UTF8(z, zTerm, iCode);
  152951. assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );
  152952. if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
  152953. && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
  152954. ){
  152955. nEntry++;
  152956. }
  152957. }
  152958. if( nEntry ){
  152959. int *aNew; /* New aiException[] array */
  152960. int nNew; /* Number of valid entries in array aNew[] */
  152961. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  152962. if( aNew==0 ) return SQLITE_NOMEM;
  152963. nNew = p->nException;
  152964. z = (const unsigned char *)zIn;
  152965. while( z<zTerm ){
  152966. READ_UTF8(z, zTerm, iCode);
  152967. if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
  152968. && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
  152969. ){
  152970. int i, j;
  152971. for(i=0; i<nNew && aNew[i]<(int)iCode; i++);
  152972. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  152973. aNew[i] = (int)iCode;
  152974. nNew++;
  152975. }
  152976. }
  152977. p->aiException = aNew;
  152978. p->nException = nNew;
  152979. }
  152980. return SQLITE_OK;
  152981. }
  152982. /*
  152983. ** Return true if the p->aiException[] array contains the value iCode.
  152984. */
  152985. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  152986. if( p->nException>0 ){
  152987. int *a = p->aiException;
  152988. int iLo = 0;
  152989. int iHi = p->nException-1;
  152990. while( iHi>=iLo ){
  152991. int iTest = (iHi + iLo) / 2;
  152992. if( iCode==a[iTest] ){
  152993. return 1;
  152994. }else if( iCode>a[iTest] ){
  152995. iLo = iTest+1;
  152996. }else{
  152997. iHi = iTest-1;
  152998. }
  152999. }
  153000. }
  153001. return 0;
  153002. }
  153003. /*
  153004. ** Return true if, for the purposes of tokenization, codepoint iCode is
  153005. ** considered a token character (not a separator).
  153006. */
  153007. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  153008. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  153009. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  153010. }
  153011. /*
  153012. ** Create a new tokenizer instance.
  153013. */
  153014. static int unicodeCreate(
  153015. int nArg, /* Size of array argv[] */
  153016. const char * const *azArg, /* Tokenizer creation arguments */
  153017. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  153018. ){
  153019. unicode_tokenizer *pNew; /* New tokenizer object */
  153020. int i;
  153021. int rc = SQLITE_OK;
  153022. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  153023. if( pNew==NULL ) return SQLITE_NOMEM;
  153024. memset(pNew, 0, sizeof(unicode_tokenizer));
  153025. pNew->bRemoveDiacritic = 1;
  153026. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  153027. const char *z = azArg[i];
  153028. int n = (int)strlen(z);
  153029. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  153030. pNew->bRemoveDiacritic = 1;
  153031. }
  153032. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  153033. pNew->bRemoveDiacritic = 0;
  153034. }
  153035. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  153036. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  153037. }
  153038. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  153039. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  153040. }
  153041. else{
  153042. /* Unrecognized argument */
  153043. rc = SQLITE_ERROR;
  153044. }
  153045. }
  153046. if( rc!=SQLITE_OK ){
  153047. unicodeDestroy((sqlite3_tokenizer *)pNew);
  153048. pNew = 0;
  153049. }
  153050. *pp = (sqlite3_tokenizer *)pNew;
  153051. return rc;
  153052. }
  153053. /*
  153054. ** Prepare to begin tokenizing a particular string. The input
  153055. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  153056. ** used to incrementally tokenize this string is returned in
  153057. ** *ppCursor.
  153058. */
  153059. static int unicodeOpen(
  153060. sqlite3_tokenizer *p, /* The tokenizer */
  153061. const char *aInput, /* Input string */
  153062. int nInput, /* Size of string aInput in bytes */
  153063. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  153064. ){
  153065. unicode_cursor *pCsr;
  153066. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  153067. if( pCsr==0 ){
  153068. return SQLITE_NOMEM;
  153069. }
  153070. memset(pCsr, 0, sizeof(unicode_cursor));
  153071. pCsr->aInput = (const unsigned char *)aInput;
  153072. if( aInput==0 ){
  153073. pCsr->nInput = 0;
  153074. }else if( nInput<0 ){
  153075. pCsr->nInput = (int)strlen(aInput);
  153076. }else{
  153077. pCsr->nInput = nInput;
  153078. }
  153079. *pp = &pCsr->base;
  153080. UNUSED_PARAMETER(p);
  153081. return SQLITE_OK;
  153082. }
  153083. /*
  153084. ** Close a tokenization cursor previously opened by a call to
  153085. ** simpleOpen() above.
  153086. */
  153087. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  153088. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  153089. sqlite3_free(pCsr->zToken);
  153090. sqlite3_free(pCsr);
  153091. return SQLITE_OK;
  153092. }
  153093. /*
  153094. ** Extract the next token from a tokenization cursor. The cursor must
  153095. ** have been opened by a prior call to simpleOpen().
  153096. */
  153097. static int unicodeNext(
  153098. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  153099. const char **paToken, /* OUT: Token text */
  153100. int *pnToken, /* OUT: Number of bytes at *paToken */
  153101. int *piStart, /* OUT: Starting offset of token */
  153102. int *piEnd, /* OUT: Ending offset of token */
  153103. int *piPos /* OUT: Position integer of token */
  153104. ){
  153105. unicode_cursor *pCsr = (unicode_cursor *)pC;
  153106. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  153107. unsigned int iCode = 0;
  153108. char *zOut;
  153109. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  153110. const unsigned char *zStart = z;
  153111. const unsigned char *zEnd;
  153112. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  153113. /* Scan past any delimiter characters before the start of the next token.
  153114. ** Return SQLITE_DONE early if this takes us all the way to the end of
  153115. ** the input. */
  153116. while( z<zTerm ){
  153117. READ_UTF8(z, zTerm, iCode);
  153118. if( unicodeIsAlnum(p, (int)iCode) ) break;
  153119. zStart = z;
  153120. }
  153121. if( zStart>=zTerm ) return SQLITE_DONE;
  153122. zOut = pCsr->zToken;
  153123. do {
  153124. int iOut;
  153125. /* Grow the output buffer if required. */
  153126. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  153127. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  153128. if( !zNew ) return SQLITE_NOMEM;
  153129. zOut = &zNew[zOut - pCsr->zToken];
  153130. pCsr->zToken = zNew;
  153131. pCsr->nAlloc += 64;
  153132. }
  153133. /* Write the folded case of the last character read to the output */
  153134. zEnd = z;
  153135. iOut = sqlite3FtsUnicodeFold((int)iCode, p->bRemoveDiacritic);
  153136. if( iOut ){
  153137. WRITE_UTF8(zOut, iOut);
  153138. }
  153139. /* If the cursor is not at EOF, read the next character */
  153140. if( z>=zTerm ) break;
  153141. READ_UTF8(z, zTerm, iCode);
  153142. }while( unicodeIsAlnum(p, (int)iCode)
  153143. || sqlite3FtsUnicodeIsdiacritic((int)iCode)
  153144. );
  153145. /* Set the output variables and return. */
  153146. pCsr->iOff = (int)(z - pCsr->aInput);
  153147. *paToken = pCsr->zToken;
  153148. *pnToken = (int)(zOut - pCsr->zToken);
  153149. *piStart = (int)(zStart - pCsr->aInput);
  153150. *piEnd = (int)(zEnd - pCsr->aInput);
  153151. *piPos = pCsr->iToken++;
  153152. return SQLITE_OK;
  153153. }
  153154. /*
  153155. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  153156. ** structure for the unicode tokenizer.
  153157. */
  153158. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  153159. static const sqlite3_tokenizer_module module = {
  153160. 0,
  153161. unicodeCreate,
  153162. unicodeDestroy,
  153163. unicodeOpen,
  153164. unicodeClose,
  153165. unicodeNext,
  153166. 0,
  153167. };
  153168. *ppModule = &module;
  153169. }
  153170. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  153171. #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
  153172. /************** End of fts3_unicode.c ****************************************/
  153173. /************** Begin file fts3_unicode2.c ***********************************/
  153174. /*
  153175. ** 2012 May 25
  153176. **
  153177. ** The author disclaims copyright to this source code. In place of
  153178. ** a legal notice, here is a blessing:
  153179. **
  153180. ** May you do good and not evil.
  153181. ** May you find forgiveness for yourself and forgive others.
  153182. ** May you share freely, never taking more than you give.
  153183. **
  153184. ******************************************************************************
  153185. */
  153186. /*
  153187. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  153188. */
  153189. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  153190. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  153191. /* #include <assert.h> */
  153192. /*
  153193. ** Return true if the argument corresponds to a unicode codepoint
  153194. ** classified as either a letter or a number. Otherwise false.
  153195. **
  153196. ** The results are undefined if the value passed to this function
  153197. ** is less than zero.
  153198. */
  153199. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  153200. /* Each unsigned integer in the following array corresponds to a contiguous
  153201. ** range of unicode codepoints that are not either letters or numbers (i.e.
  153202. ** codepoints for which this function should return 0).
  153203. **
  153204. ** The most significant 22 bits in each 32-bit value contain the first
  153205. ** codepoint in the range. The least significant 10 bits are used to store
  153206. ** the size of the range (always at least 1). In other words, the value
  153207. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  153208. ** C. It is not possible to represent a range larger than 1023 codepoints
  153209. ** using this format.
  153210. */
  153211. static const unsigned int aEntry[] = {
  153212. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  153213. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  153214. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  153215. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  153216. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  153217. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  153218. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  153219. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  153220. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  153221. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  153222. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  153223. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  153224. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  153225. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  153226. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  153227. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  153228. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  153229. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  153230. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  153231. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  153232. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  153233. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  153234. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  153235. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  153236. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  153237. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  153238. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  153239. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  153240. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  153241. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  153242. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  153243. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  153244. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  153245. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  153246. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  153247. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  153248. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  153249. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  153250. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  153251. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  153252. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  153253. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  153254. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  153255. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  153256. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  153257. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  153258. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  153259. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  153260. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  153261. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  153262. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  153263. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  153264. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  153265. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  153266. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  153267. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  153268. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  153269. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  153270. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  153271. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  153272. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  153273. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  153274. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  153275. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  153276. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  153277. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  153278. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  153279. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  153280. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  153281. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  153282. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  153283. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  153284. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  153285. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  153286. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  153287. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  153288. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  153289. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  153290. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  153291. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  153292. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  153293. 0x380400F0,
  153294. };
  153295. static const unsigned int aAscii[4] = {
  153296. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  153297. };
  153298. if( (unsigned int)c<128 ){
  153299. return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 );
  153300. }else if( (unsigned int)c<(1<<22) ){
  153301. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  153302. int iRes = 0;
  153303. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  153304. int iLo = 0;
  153305. while( iHi>=iLo ){
  153306. int iTest = (iHi + iLo) / 2;
  153307. if( key >= aEntry[iTest] ){
  153308. iRes = iTest;
  153309. iLo = iTest+1;
  153310. }else{
  153311. iHi = iTest-1;
  153312. }
  153313. }
  153314. assert( aEntry[0]<key );
  153315. assert( key>=aEntry[iRes] );
  153316. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  153317. }
  153318. return 1;
  153319. }
  153320. /*
  153321. ** If the argument is a codepoint corresponding to a lowercase letter
  153322. ** in the ASCII range with a diacritic added, return the codepoint
  153323. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  153324. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  153325. ** E"). The resuls of passing a codepoint that corresponds to an
  153326. ** uppercase letter are undefined.
  153327. */
  153328. static int remove_diacritic(int c){
  153329. unsigned short aDia[] = {
  153330. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  153331. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  153332. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  153333. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  153334. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  153335. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  153336. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  153337. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  153338. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  153339. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  153340. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  153341. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  153342. 62924, 63050, 63082, 63274, 63390,
  153343. };
  153344. char aChar[] = {
  153345. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  153346. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  153347. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  153348. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  153349. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  153350. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  153351. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  153352. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  153353. 'e', 'i', 'o', 'u', 'y',
  153354. };
  153355. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  153356. int iRes = 0;
  153357. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  153358. int iLo = 0;
  153359. while( iHi>=iLo ){
  153360. int iTest = (iHi + iLo) / 2;
  153361. if( key >= aDia[iTest] ){
  153362. iRes = iTest;
  153363. iLo = iTest+1;
  153364. }else{
  153365. iHi = iTest-1;
  153366. }
  153367. }
  153368. assert( key>=aDia[iRes] );
  153369. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  153370. }
  153371. /*
  153372. ** Return true if the argument interpreted as a unicode codepoint
  153373. ** is a diacritical modifier character.
  153374. */
  153375. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  153376. unsigned int mask0 = 0x08029FDF;
  153377. unsigned int mask1 = 0x000361F8;
  153378. if( c<768 || c>817 ) return 0;
  153379. return (c < 768+32) ?
  153380. (mask0 & (1 << (c-768))) :
  153381. (mask1 & (1 << (c-768-32)));
  153382. }
  153383. /*
  153384. ** Interpret the argument as a unicode codepoint. If the codepoint
  153385. ** is an upper case character that has a lower case equivalent,
  153386. ** return the codepoint corresponding to the lower case version.
  153387. ** Otherwise, return a copy of the argument.
  153388. **
  153389. ** The results are undefined if the value passed to this function
  153390. ** is less than zero.
  153391. */
  153392. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  153393. /* Each entry in the following array defines a rule for folding a range
  153394. ** of codepoints to lower case. The rule applies to a range of nRange
  153395. ** codepoints starting at codepoint iCode.
  153396. **
  153397. ** If the least significant bit in flags is clear, then the rule applies
  153398. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  153399. ** need to be folded). Or, if it is set, then the rule only applies to
  153400. ** every second codepoint in the range, starting with codepoint C.
  153401. **
  153402. ** The 7 most significant bits in flags are an index into the aiOff[]
  153403. ** array. If a specific codepoint C does require folding, then its lower
  153404. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  153405. **
  153406. ** The contents of this array are generated by parsing the CaseFolding.txt
  153407. ** file distributed as part of the "Unicode Character Database". See
  153408. ** http://www.unicode.org for details.
  153409. */
  153410. static const struct TableEntry {
  153411. unsigned short iCode;
  153412. unsigned char flags;
  153413. unsigned char nRange;
  153414. } aEntry[] = {
  153415. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  153416. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  153417. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  153418. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  153419. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  153420. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  153421. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  153422. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  153423. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  153424. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  153425. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  153426. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  153427. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  153428. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  153429. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  153430. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  153431. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  153432. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  153433. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  153434. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  153435. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  153436. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  153437. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  153438. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  153439. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  153440. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  153441. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  153442. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  153443. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  153444. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  153445. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  153446. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  153447. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  153448. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  153449. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  153450. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  153451. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  153452. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  153453. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  153454. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  153455. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  153456. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  153457. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  153458. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  153459. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  153460. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  153461. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  153462. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  153463. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  153464. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  153465. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  153466. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  153467. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  153468. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  153469. {65313, 14, 26},
  153470. };
  153471. static const unsigned short aiOff[] = {
  153472. 1, 2, 8, 15, 16, 26, 28, 32,
  153473. 37, 38, 40, 48, 63, 64, 69, 71,
  153474. 79, 80, 116, 202, 203, 205, 206, 207,
  153475. 209, 210, 211, 213, 214, 217, 218, 219,
  153476. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  153477. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  153478. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  153479. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  153480. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  153481. 65514, 65521, 65527, 65528, 65529,
  153482. };
  153483. int ret = c;
  153484. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  153485. if( c<128 ){
  153486. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  153487. }else if( c<65536 ){
  153488. const struct TableEntry *p;
  153489. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  153490. int iLo = 0;
  153491. int iRes = -1;
  153492. assert( c>aEntry[0].iCode );
  153493. while( iHi>=iLo ){
  153494. int iTest = (iHi + iLo) / 2;
  153495. int cmp = (c - aEntry[iTest].iCode);
  153496. if( cmp>=0 ){
  153497. iRes = iTest;
  153498. iLo = iTest+1;
  153499. }else{
  153500. iHi = iTest-1;
  153501. }
  153502. }
  153503. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  153504. p = &aEntry[iRes];
  153505. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  153506. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  153507. assert( ret>0 );
  153508. }
  153509. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  153510. }
  153511. else if( c>=66560 && c<66600 ){
  153512. ret = c + 40;
  153513. }
  153514. return ret;
  153515. }
  153516. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  153517. #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
  153518. /************** End of fts3_unicode2.c ***************************************/
  153519. /************** Begin file rtree.c *******************************************/
  153520. /*
  153521. ** 2001 September 15
  153522. **
  153523. ** The author disclaims copyright to this source code. In place of
  153524. ** a legal notice, here is a blessing:
  153525. **
  153526. ** May you do good and not evil.
  153527. ** May you find forgiveness for yourself and forgive others.
  153528. ** May you share freely, never taking more than you give.
  153529. **
  153530. *************************************************************************
  153531. ** This file contains code for implementations of the r-tree and r*-tree
  153532. ** algorithms packaged as an SQLite virtual table module.
  153533. */
  153534. /*
  153535. ** Database Format of R-Tree Tables
  153536. ** --------------------------------
  153537. **
  153538. ** The data structure for a single virtual r-tree table is stored in three
  153539. ** native SQLite tables declared as follows. In each case, the '%' character
  153540. ** in the table name is replaced with the user-supplied name of the r-tree
  153541. ** table.
  153542. **
  153543. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  153544. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  153545. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  153546. **
  153547. ** The data for each node of the r-tree structure is stored in the %_node
  153548. ** table. For each node that is not the root node of the r-tree, there is
  153549. ** an entry in the %_parent table associating the node with its parent.
  153550. ** And for each row of data in the table, there is an entry in the %_rowid
  153551. ** table that maps from the entries rowid to the id of the node that it
  153552. ** is stored on.
  153553. **
  153554. ** The root node of an r-tree always exists, even if the r-tree table is
  153555. ** empty. The nodeno of the root node is always 1. All other nodes in the
  153556. ** table must be the same size as the root node. The content of each node
  153557. ** is formatted as follows:
  153558. **
  153559. ** 1. If the node is the root node (node 1), then the first 2 bytes
  153560. ** of the node contain the tree depth as a big-endian integer.
  153561. ** For non-root nodes, the first 2 bytes are left unused.
  153562. **
  153563. ** 2. The next 2 bytes contain the number of entries currently
  153564. ** stored in the node.
  153565. **
  153566. ** 3. The remainder of the node contains the node entries. Each entry
  153567. ** consists of a single 8-byte integer followed by an even number
  153568. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  153569. ** of a record. For internal nodes it is the node number of a
  153570. ** child page.
  153571. */
  153572. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  153573. #ifndef SQLITE_CORE
  153574. /* #include "sqlite3ext.h" */
  153575. SQLITE_EXTENSION_INIT1
  153576. #else
  153577. /* #include "sqlite3.h" */
  153578. #endif
  153579. /* #include <string.h> */
  153580. /* #include <assert.h> */
  153581. /* #include <stdio.h> */
  153582. #ifndef SQLITE_AMALGAMATION
  153583. #include "sqlite3rtree.h"
  153584. typedef sqlite3_int64 i64;
  153585. typedef sqlite3_uint64 u64;
  153586. typedef unsigned char u8;
  153587. typedef unsigned short u16;
  153588. typedef unsigned int u32;
  153589. #endif
  153590. /* The following macro is used to suppress compiler warnings.
  153591. */
  153592. #ifndef UNUSED_PARAMETER
  153593. # define UNUSED_PARAMETER(x) (void)(x)
  153594. #endif
  153595. typedef struct Rtree Rtree;
  153596. typedef struct RtreeCursor RtreeCursor;
  153597. typedef struct RtreeNode RtreeNode;
  153598. typedef struct RtreeCell RtreeCell;
  153599. typedef struct RtreeConstraint RtreeConstraint;
  153600. typedef struct RtreeMatchArg RtreeMatchArg;
  153601. typedef struct RtreeGeomCallback RtreeGeomCallback;
  153602. typedef union RtreeCoord RtreeCoord;
  153603. typedef struct RtreeSearchPoint RtreeSearchPoint;
  153604. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  153605. #define RTREE_MAX_DIMENSIONS 5
  153606. /* Size of hash table Rtree.aHash. This hash table is not expected to
  153607. ** ever contain very many entries, so a fixed number of buckets is
  153608. ** used.
  153609. */
  153610. #define HASHSIZE 97
  153611. /* The xBestIndex method of this virtual table requires an estimate of
  153612. ** the number of rows in the virtual table to calculate the costs of
  153613. ** various strategies. If possible, this estimate is loaded from the
  153614. ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
  153615. ** Otherwise, if no sqlite_stat1 entry is available, use
  153616. ** RTREE_DEFAULT_ROWEST.
  153617. */
  153618. #define RTREE_DEFAULT_ROWEST 1048576
  153619. #define RTREE_MIN_ROWEST 100
  153620. /*
  153621. ** An rtree virtual-table object.
  153622. */
  153623. struct Rtree {
  153624. sqlite3_vtab base; /* Base class. Must be first */
  153625. sqlite3 *db; /* Host database connection */
  153626. int iNodeSize; /* Size in bytes of each node in the node table */
  153627. u8 nDim; /* Number of dimensions */
  153628. u8 nDim2; /* Twice the number of dimensions */
  153629. u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
  153630. u8 nBytesPerCell; /* Bytes consumed per cell */
  153631. u8 inWrTrans; /* True if inside write transaction */
  153632. int iDepth; /* Current depth of the r-tree structure */
  153633. char *zDb; /* Name of database containing r-tree table */
  153634. char *zName; /* Name of r-tree table */
  153635. u32 nBusy; /* Current number of users of this structure */
  153636. i64 nRowEst; /* Estimated number of rows in this table */
  153637. u32 nCursor; /* Number of open cursors */
  153638. /* List of nodes removed during a CondenseTree operation. List is
  153639. ** linked together via the pointer normally used for hash chains -
  153640. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  153641. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  153642. */
  153643. RtreeNode *pDeleted;
  153644. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  153645. /* Blob I/O on xxx_node */
  153646. sqlite3_blob *pNodeBlob;
  153647. /* Statements to read/write/delete a record from xxx_node */
  153648. sqlite3_stmt *pWriteNode;
  153649. sqlite3_stmt *pDeleteNode;
  153650. /* Statements to read/write/delete a record from xxx_rowid */
  153651. sqlite3_stmt *pReadRowid;
  153652. sqlite3_stmt *pWriteRowid;
  153653. sqlite3_stmt *pDeleteRowid;
  153654. /* Statements to read/write/delete a record from xxx_parent */
  153655. sqlite3_stmt *pReadParent;
  153656. sqlite3_stmt *pWriteParent;
  153657. sqlite3_stmt *pDeleteParent;
  153658. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  153659. };
  153660. /* Possible values for Rtree.eCoordType: */
  153661. #define RTREE_COORD_REAL32 0
  153662. #define RTREE_COORD_INT32 1
  153663. /*
  153664. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  153665. ** only deal with integer coordinates. No floating point operations
  153666. ** will be done.
  153667. */
  153668. #ifdef SQLITE_RTREE_INT_ONLY
  153669. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  153670. typedef int RtreeValue; /* Low accuracy coordinate */
  153671. # define RTREE_ZERO 0
  153672. #else
  153673. typedef double RtreeDValue; /* High accuracy coordinate */
  153674. typedef float RtreeValue; /* Low accuracy coordinate */
  153675. # define RTREE_ZERO 0.0
  153676. #endif
  153677. /*
  153678. ** When doing a search of an r-tree, instances of the following structure
  153679. ** record intermediate results from the tree walk.
  153680. **
  153681. ** The id is always a node-id. For iLevel>=1 the id is the node-id of
  153682. ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
  153683. ** the id is of the parent node and the cell that RtreeSearchPoint
  153684. ** represents is the iCell-th entry in the parent node.
  153685. */
  153686. struct RtreeSearchPoint {
  153687. RtreeDValue rScore; /* The score for this node. Smallest goes first. */
  153688. sqlite3_int64 id; /* Node ID */
  153689. u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
  153690. u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
  153691. u8 iCell; /* Cell index within the node */
  153692. };
  153693. /*
  153694. ** The minimum number of cells allowed for a node is a third of the
  153695. ** maximum. In Gutman's notation:
  153696. **
  153697. ** m = M/3
  153698. **
  153699. ** If an R*-tree "Reinsert" operation is required, the same number of
  153700. ** cells are removed from the overfull node and reinserted into the tree.
  153701. */
  153702. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  153703. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  153704. #define RTREE_MAXCELLS 51
  153705. /*
  153706. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  153707. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  153708. ** Therefore all non-root nodes must contain at least 3 entries. Since
  153709. ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
  153710. ** 40 or less.
  153711. */
  153712. #define RTREE_MAX_DEPTH 40
  153713. /*
  153714. ** Number of entries in the cursor RtreeNode cache. The first entry is
  153715. ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
  153716. ** entries cache the RtreeNode for the first elements of the priority queue.
  153717. */
  153718. #define RTREE_CACHE_SZ 5
  153719. /*
  153720. ** An rtree cursor object.
  153721. */
  153722. struct RtreeCursor {
  153723. sqlite3_vtab_cursor base; /* Base class. Must be first */
  153724. u8 atEOF; /* True if at end of search */
  153725. u8 bPoint; /* True if sPoint is valid */
  153726. int iStrategy; /* Copy of idxNum search parameter */
  153727. int nConstraint; /* Number of entries in aConstraint */
  153728. RtreeConstraint *aConstraint; /* Search constraints. */
  153729. int nPointAlloc; /* Number of slots allocated for aPoint[] */
  153730. int nPoint; /* Number of slots used in aPoint[] */
  153731. int mxLevel; /* iLevel value for root of the tree */
  153732. RtreeSearchPoint *aPoint; /* Priority queue for search points */
  153733. RtreeSearchPoint sPoint; /* Cached next search point */
  153734. RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
  153735. u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
  153736. };
  153737. /* Return the Rtree of a RtreeCursor */
  153738. #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
  153739. /*
  153740. ** A coordinate can be either a floating point number or a integer. All
  153741. ** coordinates within a single R-Tree are always of the same time.
  153742. */
  153743. union RtreeCoord {
  153744. RtreeValue f; /* Floating point value */
  153745. int i; /* Integer value */
  153746. u32 u; /* Unsigned for byte-order conversions */
  153747. };
  153748. /*
  153749. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  153750. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  153751. ** variable pRtree points to the Rtree structure associated with the
  153752. ** RtreeCoord.
  153753. */
  153754. #ifdef SQLITE_RTREE_INT_ONLY
  153755. # define DCOORD(coord) ((RtreeDValue)coord.i)
  153756. #else
  153757. # define DCOORD(coord) ( \
  153758. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  153759. ((double)coord.f) : \
  153760. ((double)coord.i) \
  153761. )
  153762. #endif
  153763. /*
  153764. ** A search constraint.
  153765. */
  153766. struct RtreeConstraint {
  153767. int iCoord; /* Index of constrained coordinate */
  153768. int op; /* Constraining operation */
  153769. union {
  153770. RtreeDValue rValue; /* Constraint value. */
  153771. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
  153772. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  153773. } u;
  153774. sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
  153775. };
  153776. /* Possible values for RtreeConstraint.op */
  153777. #define RTREE_EQ 0x41 /* A */
  153778. #define RTREE_LE 0x42 /* B */
  153779. #define RTREE_LT 0x43 /* C */
  153780. #define RTREE_GE 0x44 /* D */
  153781. #define RTREE_GT 0x45 /* E */
  153782. #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
  153783. #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
  153784. /*
  153785. ** An rtree structure node.
  153786. */
  153787. struct RtreeNode {
  153788. RtreeNode *pParent; /* Parent node */
  153789. i64 iNode; /* The node number */
  153790. int nRef; /* Number of references to this node */
  153791. int isDirty; /* True if the node needs to be written to disk */
  153792. u8 *zData; /* Content of the node, as should be on disk */
  153793. RtreeNode *pNext; /* Next node in this hash collision chain */
  153794. };
  153795. /* Return the number of cells in a node */
  153796. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  153797. /*
  153798. ** A single cell from a node, deserialized
  153799. */
  153800. struct RtreeCell {
  153801. i64 iRowid; /* Node or entry ID */
  153802. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
  153803. };
  153804. /*
  153805. ** This object becomes the sqlite3_user_data() for the SQL functions
  153806. ** that are created by sqlite3_rtree_geometry_callback() and
  153807. ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
  153808. ** operators in order to constrain a search.
  153809. **
  153810. ** xGeom and xQueryFunc are the callback functions. Exactly one of
  153811. ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
  153812. ** SQL function was created using sqlite3_rtree_geometry_callback() or
  153813. ** sqlite3_rtree_query_callback().
  153814. **
  153815. ** This object is deleted automatically by the destructor mechanism in
  153816. ** sqlite3_create_function_v2().
  153817. */
  153818. struct RtreeGeomCallback {
  153819. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  153820. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  153821. void (*xDestructor)(void*);
  153822. void *pContext;
  153823. };
  153824. /*
  153825. ** Value for the first field of every RtreeMatchArg object. The MATCH
  153826. ** operator tests that the first field of a blob operand matches this
  153827. ** value to avoid operating on invalid blobs (which could cause a segfault).
  153828. */
  153829. #define RTREE_GEOMETRY_MAGIC 0x891245AB
  153830. /*
  153831. ** An instance of this structure (in the form of a BLOB) is returned by
  153832. ** the SQL functions that sqlite3_rtree_geometry_callback() and
  153833. ** sqlite3_rtree_query_callback() create, and is read as the right-hand
  153834. ** operand to the MATCH operator of an R-Tree.
  153835. */
  153836. struct RtreeMatchArg {
  153837. u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
  153838. RtreeGeomCallback cb; /* Info about the callback functions */
  153839. int nParam; /* Number of parameters to the SQL function */
  153840. sqlite3_value **apSqlParam; /* Original SQL parameter values */
  153841. RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
  153842. };
  153843. #ifndef MAX
  153844. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  153845. #endif
  153846. #ifndef MIN
  153847. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  153848. #endif
  153849. /* What version of GCC is being used. 0 means GCC is not being used .
  153850. ** Note that the GCC_VERSION macro will also be set correctly when using
  153851. ** clang, since clang works hard to be gcc compatible. So the gcc
  153852. ** optimizations will also work when compiling with clang.
  153853. */
  153854. #ifndef GCC_VERSION
  153855. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  153856. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  153857. #else
  153858. # define GCC_VERSION 0
  153859. #endif
  153860. #endif
  153861. /* The testcase() macro should already be defined in the amalgamation. If
  153862. ** it is not, make it a no-op.
  153863. */
  153864. #ifndef SQLITE_AMALGAMATION
  153865. # define testcase(X)
  153866. #endif
  153867. /*
  153868. ** Macros to determine whether the machine is big or little endian,
  153869. ** and whether or not that determination is run-time or compile-time.
  153870. **
  153871. ** For best performance, an attempt is made to guess at the byte-order
  153872. ** using C-preprocessor macros. If that is unsuccessful, or if
  153873. ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
  153874. ** at run-time.
  153875. */
  153876. #ifndef SQLITE_BYTEORDER
  153877. #if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  153878. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  153879. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  153880. defined(__arm__)
  153881. # define SQLITE_BYTEORDER 1234
  153882. #elif defined(sparc) || defined(__ppc__)
  153883. # define SQLITE_BYTEORDER 4321
  153884. #else
  153885. # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
  153886. #endif
  153887. #endif
  153888. /* What version of MSVC is being used. 0 means MSVC is not being used */
  153889. #ifndef MSVC_VERSION
  153890. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  153891. # define MSVC_VERSION _MSC_VER
  153892. #else
  153893. # define MSVC_VERSION 0
  153894. #endif
  153895. #endif
  153896. /*
  153897. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  153898. ** 64 bit integer. The deserialized value is returned.
  153899. */
  153900. static int readInt16(u8 *p){
  153901. return (p[0]<<8) + p[1];
  153902. }
  153903. static void readCoord(u8 *p, RtreeCoord *pCoord){
  153904. assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
  153905. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  153906. pCoord->u = _byteswap_ulong(*(u32*)p);
  153907. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  153908. pCoord->u = __builtin_bswap32(*(u32*)p);
  153909. #elif SQLITE_BYTEORDER==4321
  153910. pCoord->u = *(u32*)p;
  153911. #else
  153912. pCoord->u = (
  153913. (((u32)p[0]) << 24) +
  153914. (((u32)p[1]) << 16) +
  153915. (((u32)p[2]) << 8) +
  153916. (((u32)p[3]) << 0)
  153917. );
  153918. #endif
  153919. }
  153920. static i64 readInt64(u8 *p){
  153921. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  153922. u64 x;
  153923. memcpy(&x, p, 8);
  153924. return (i64)_byteswap_uint64(x);
  153925. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  153926. u64 x;
  153927. memcpy(&x, p, 8);
  153928. return (i64)__builtin_bswap64(x);
  153929. #elif SQLITE_BYTEORDER==4321
  153930. i64 x;
  153931. memcpy(&x, p, 8);
  153932. return x;
  153933. #else
  153934. return (i64)(
  153935. (((u64)p[0]) << 56) +
  153936. (((u64)p[1]) << 48) +
  153937. (((u64)p[2]) << 40) +
  153938. (((u64)p[3]) << 32) +
  153939. (((u64)p[4]) << 24) +
  153940. (((u64)p[5]) << 16) +
  153941. (((u64)p[6]) << 8) +
  153942. (((u64)p[7]) << 0)
  153943. );
  153944. #endif
  153945. }
  153946. /*
  153947. ** Functions to serialize a 16 bit integer, 32 bit real number and
  153948. ** 64 bit integer. The value returned is the number of bytes written
  153949. ** to the argument buffer (always 2, 4 and 8 respectively).
  153950. */
  153951. static void writeInt16(u8 *p, int i){
  153952. p[0] = (i>> 8)&0xFF;
  153953. p[1] = (i>> 0)&0xFF;
  153954. }
  153955. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  153956. u32 i;
  153957. assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
  153958. assert( sizeof(RtreeCoord)==4 );
  153959. assert( sizeof(u32)==4 );
  153960. #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  153961. i = __builtin_bswap32(pCoord->u);
  153962. memcpy(p, &i, 4);
  153963. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  153964. i = _byteswap_ulong(pCoord->u);
  153965. memcpy(p, &i, 4);
  153966. #elif SQLITE_BYTEORDER==4321
  153967. i = pCoord->u;
  153968. memcpy(p, &i, 4);
  153969. #else
  153970. i = pCoord->u;
  153971. p[0] = (i>>24)&0xFF;
  153972. p[1] = (i>>16)&0xFF;
  153973. p[2] = (i>> 8)&0xFF;
  153974. p[3] = (i>> 0)&0xFF;
  153975. #endif
  153976. return 4;
  153977. }
  153978. static int writeInt64(u8 *p, i64 i){
  153979. #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  153980. i = (i64)__builtin_bswap64((u64)i);
  153981. memcpy(p, &i, 8);
  153982. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  153983. i = (i64)_byteswap_uint64((u64)i);
  153984. memcpy(p, &i, 8);
  153985. #elif SQLITE_BYTEORDER==4321
  153986. memcpy(p, &i, 8);
  153987. #else
  153988. p[0] = (i>>56)&0xFF;
  153989. p[1] = (i>>48)&0xFF;
  153990. p[2] = (i>>40)&0xFF;
  153991. p[3] = (i>>32)&0xFF;
  153992. p[4] = (i>>24)&0xFF;
  153993. p[5] = (i>>16)&0xFF;
  153994. p[6] = (i>> 8)&0xFF;
  153995. p[7] = (i>> 0)&0xFF;
  153996. #endif
  153997. return 8;
  153998. }
  153999. /*
  154000. ** Increment the reference count of node p.
  154001. */
  154002. static void nodeReference(RtreeNode *p){
  154003. if( p ){
  154004. p->nRef++;
  154005. }
  154006. }
  154007. /*
  154008. ** Clear the content of node p (set all bytes to 0x00).
  154009. */
  154010. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  154011. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  154012. p->isDirty = 1;
  154013. }
  154014. /*
  154015. ** Given a node number iNode, return the corresponding key to use
  154016. ** in the Rtree.aHash table.
  154017. */
  154018. static int nodeHash(i64 iNode){
  154019. return iNode % HASHSIZE;
  154020. }
  154021. /*
  154022. ** Search the node hash table for node iNode. If found, return a pointer
  154023. ** to it. Otherwise, return 0.
  154024. */
  154025. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  154026. RtreeNode *p;
  154027. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  154028. return p;
  154029. }
  154030. /*
  154031. ** Add node pNode to the node hash table.
  154032. */
  154033. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  154034. int iHash;
  154035. assert( pNode->pNext==0 );
  154036. iHash = nodeHash(pNode->iNode);
  154037. pNode->pNext = pRtree->aHash[iHash];
  154038. pRtree->aHash[iHash] = pNode;
  154039. }
  154040. /*
  154041. ** Remove node pNode from the node hash table.
  154042. */
  154043. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  154044. RtreeNode **pp;
  154045. if( pNode->iNode!=0 ){
  154046. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  154047. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  154048. *pp = pNode->pNext;
  154049. pNode->pNext = 0;
  154050. }
  154051. }
  154052. /*
  154053. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  154054. ** indicating that node has not yet been assigned a node number. It is
  154055. ** assigned a node number when nodeWrite() is called to write the
  154056. ** node contents out to the database.
  154057. */
  154058. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  154059. RtreeNode *pNode;
  154060. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  154061. if( pNode ){
  154062. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  154063. pNode->zData = (u8 *)&pNode[1];
  154064. pNode->nRef = 1;
  154065. pNode->pParent = pParent;
  154066. pNode->isDirty = 1;
  154067. nodeReference(pParent);
  154068. }
  154069. return pNode;
  154070. }
  154071. /*
  154072. ** Clear the Rtree.pNodeBlob object
  154073. */
  154074. static void nodeBlobReset(Rtree *pRtree){
  154075. if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
  154076. sqlite3_blob *pBlob = pRtree->pNodeBlob;
  154077. pRtree->pNodeBlob = 0;
  154078. sqlite3_blob_close(pBlob);
  154079. }
  154080. }
  154081. /*
  154082. ** Obtain a reference to an r-tree node.
  154083. */
  154084. static int nodeAcquire(
  154085. Rtree *pRtree, /* R-tree structure */
  154086. i64 iNode, /* Node number to load */
  154087. RtreeNode *pParent, /* Either the parent node or NULL */
  154088. RtreeNode **ppNode /* OUT: Acquired node */
  154089. ){
  154090. int rc = SQLITE_OK;
  154091. RtreeNode *pNode = 0;
  154092. /* Check if the requested node is already in the hash table. If so,
  154093. ** increase its reference count and return it.
  154094. */
  154095. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  154096. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  154097. if( pParent && !pNode->pParent ){
  154098. nodeReference(pParent);
  154099. pNode->pParent = pParent;
  154100. }
  154101. pNode->nRef++;
  154102. *ppNode = pNode;
  154103. return SQLITE_OK;
  154104. }
  154105. if( pRtree->pNodeBlob ){
  154106. sqlite3_blob *pBlob = pRtree->pNodeBlob;
  154107. pRtree->pNodeBlob = 0;
  154108. rc = sqlite3_blob_reopen(pBlob, iNode);
  154109. pRtree->pNodeBlob = pBlob;
  154110. if( rc ){
  154111. nodeBlobReset(pRtree);
  154112. if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
  154113. }
  154114. }
  154115. if( pRtree->pNodeBlob==0 ){
  154116. char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
  154117. if( zTab==0 ) return SQLITE_NOMEM;
  154118. rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
  154119. &pRtree->pNodeBlob);
  154120. sqlite3_free(zTab);
  154121. }
  154122. if( rc ){
  154123. nodeBlobReset(pRtree);
  154124. *ppNode = 0;
  154125. /* If unable to open an sqlite3_blob on the desired row, that can only
  154126. ** be because the shadow tables hold erroneous data. */
  154127. if( rc==SQLITE_ERROR ) rc = SQLITE_CORRUPT_VTAB;
  154128. }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
  154129. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  154130. if( !pNode ){
  154131. rc = SQLITE_NOMEM;
  154132. }else{
  154133. pNode->pParent = pParent;
  154134. pNode->zData = (u8 *)&pNode[1];
  154135. pNode->nRef = 1;
  154136. pNode->iNode = iNode;
  154137. pNode->isDirty = 0;
  154138. pNode->pNext = 0;
  154139. rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
  154140. pRtree->iNodeSize, 0);
  154141. nodeReference(pParent);
  154142. }
  154143. }
  154144. /* If the root node was just loaded, set pRtree->iDepth to the height
  154145. ** of the r-tree structure. A height of zero means all data is stored on
  154146. ** the root node. A height of one means the children of the root node
  154147. ** are the leaves, and so on. If the depth as specified on the root node
  154148. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  154149. */
  154150. if( pNode && iNode==1 ){
  154151. pRtree->iDepth = readInt16(pNode->zData);
  154152. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  154153. rc = SQLITE_CORRUPT_VTAB;
  154154. }
  154155. }
  154156. /* If no error has occurred so far, check if the "number of entries"
  154157. ** field on the node is too large. If so, set the return code to
  154158. ** SQLITE_CORRUPT_VTAB.
  154159. */
  154160. if( pNode && rc==SQLITE_OK ){
  154161. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  154162. rc = SQLITE_CORRUPT_VTAB;
  154163. }
  154164. }
  154165. if( rc==SQLITE_OK ){
  154166. if( pNode!=0 ){
  154167. nodeHashInsert(pRtree, pNode);
  154168. }else{
  154169. rc = SQLITE_CORRUPT_VTAB;
  154170. }
  154171. *ppNode = pNode;
  154172. }else{
  154173. sqlite3_free(pNode);
  154174. *ppNode = 0;
  154175. }
  154176. return rc;
  154177. }
  154178. /*
  154179. ** Overwrite cell iCell of node pNode with the contents of pCell.
  154180. */
  154181. static void nodeOverwriteCell(
  154182. Rtree *pRtree, /* The overall R-Tree */
  154183. RtreeNode *pNode, /* The node into which the cell is to be written */
  154184. RtreeCell *pCell, /* The cell to write */
  154185. int iCell /* Index into pNode into which pCell is written */
  154186. ){
  154187. int ii;
  154188. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  154189. p += writeInt64(p, pCell->iRowid);
  154190. for(ii=0; ii<pRtree->nDim2; ii++){
  154191. p += writeCoord(p, &pCell->aCoord[ii]);
  154192. }
  154193. pNode->isDirty = 1;
  154194. }
  154195. /*
  154196. ** Remove the cell with index iCell from node pNode.
  154197. */
  154198. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  154199. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  154200. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  154201. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  154202. memmove(pDst, pSrc, nByte);
  154203. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  154204. pNode->isDirty = 1;
  154205. }
  154206. /*
  154207. ** Insert the contents of cell pCell into node pNode. If the insert
  154208. ** is successful, return SQLITE_OK.
  154209. **
  154210. ** If there is not enough free space in pNode, return SQLITE_FULL.
  154211. */
  154212. static int nodeInsertCell(
  154213. Rtree *pRtree, /* The overall R-Tree */
  154214. RtreeNode *pNode, /* Write new cell into this node */
  154215. RtreeCell *pCell /* The cell to be inserted */
  154216. ){
  154217. int nCell; /* Current number of cells in pNode */
  154218. int nMaxCell; /* Maximum number of cells for pNode */
  154219. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  154220. nCell = NCELL(pNode);
  154221. assert( nCell<=nMaxCell );
  154222. if( nCell<nMaxCell ){
  154223. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  154224. writeInt16(&pNode->zData[2], nCell+1);
  154225. pNode->isDirty = 1;
  154226. }
  154227. return (nCell==nMaxCell);
  154228. }
  154229. /*
  154230. ** If the node is dirty, write it out to the database.
  154231. */
  154232. static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  154233. int rc = SQLITE_OK;
  154234. if( pNode->isDirty ){
  154235. sqlite3_stmt *p = pRtree->pWriteNode;
  154236. if( pNode->iNode ){
  154237. sqlite3_bind_int64(p, 1, pNode->iNode);
  154238. }else{
  154239. sqlite3_bind_null(p, 1);
  154240. }
  154241. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  154242. sqlite3_step(p);
  154243. pNode->isDirty = 0;
  154244. rc = sqlite3_reset(p);
  154245. if( pNode->iNode==0 && rc==SQLITE_OK ){
  154246. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  154247. nodeHashInsert(pRtree, pNode);
  154248. }
  154249. }
  154250. return rc;
  154251. }
  154252. /*
  154253. ** Release a reference to a node. If the node is dirty and the reference
  154254. ** count drops to zero, the node data is written to the database.
  154255. */
  154256. static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  154257. int rc = SQLITE_OK;
  154258. if( pNode ){
  154259. assert( pNode->nRef>0 );
  154260. pNode->nRef--;
  154261. if( pNode->nRef==0 ){
  154262. if( pNode->iNode==1 ){
  154263. pRtree->iDepth = -1;
  154264. }
  154265. if( pNode->pParent ){
  154266. rc = nodeRelease(pRtree, pNode->pParent);
  154267. }
  154268. if( rc==SQLITE_OK ){
  154269. rc = nodeWrite(pRtree, pNode);
  154270. }
  154271. nodeHashDelete(pRtree, pNode);
  154272. sqlite3_free(pNode);
  154273. }
  154274. }
  154275. return rc;
  154276. }
  154277. /*
  154278. ** Return the 64-bit integer value associated with cell iCell of
  154279. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  154280. ** an internal node, then the 64-bit integer is a child page number.
  154281. */
  154282. static i64 nodeGetRowid(
  154283. Rtree *pRtree, /* The overall R-Tree */
  154284. RtreeNode *pNode, /* The node from which to extract the ID */
  154285. int iCell /* The cell index from which to extract the ID */
  154286. ){
  154287. assert( iCell<NCELL(pNode) );
  154288. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  154289. }
  154290. /*
  154291. ** Return coordinate iCoord from cell iCell in node pNode.
  154292. */
  154293. static void nodeGetCoord(
  154294. Rtree *pRtree, /* The overall R-Tree */
  154295. RtreeNode *pNode, /* The node from which to extract a coordinate */
  154296. int iCell, /* The index of the cell within the node */
  154297. int iCoord, /* Which coordinate to extract */
  154298. RtreeCoord *pCoord /* OUT: Space to write result to */
  154299. ){
  154300. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  154301. }
  154302. /*
  154303. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  154304. ** to by pCell with the results.
  154305. */
  154306. static void nodeGetCell(
  154307. Rtree *pRtree, /* The overall R-Tree */
  154308. RtreeNode *pNode, /* The node containing the cell to be read */
  154309. int iCell, /* Index of the cell within the node */
  154310. RtreeCell *pCell /* OUT: Write the cell contents here */
  154311. ){
  154312. u8 *pData;
  154313. RtreeCoord *pCoord;
  154314. int ii = 0;
  154315. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  154316. pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
  154317. pCoord = pCell->aCoord;
  154318. do{
  154319. readCoord(pData, &pCoord[ii]);
  154320. readCoord(pData+4, &pCoord[ii+1]);
  154321. pData += 8;
  154322. ii += 2;
  154323. }while( ii<pRtree->nDim2 );
  154324. }
  154325. /* Forward declaration for the function that does the work of
  154326. ** the virtual table module xCreate() and xConnect() methods.
  154327. */
  154328. static int rtreeInit(
  154329. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  154330. );
  154331. /*
  154332. ** Rtree virtual table module xCreate method.
  154333. */
  154334. static int rtreeCreate(
  154335. sqlite3 *db,
  154336. void *pAux,
  154337. int argc, const char *const*argv,
  154338. sqlite3_vtab **ppVtab,
  154339. char **pzErr
  154340. ){
  154341. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  154342. }
  154343. /*
  154344. ** Rtree virtual table module xConnect method.
  154345. */
  154346. static int rtreeConnect(
  154347. sqlite3 *db,
  154348. void *pAux,
  154349. int argc, const char *const*argv,
  154350. sqlite3_vtab **ppVtab,
  154351. char **pzErr
  154352. ){
  154353. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  154354. }
  154355. /*
  154356. ** Increment the r-tree reference count.
  154357. */
  154358. static void rtreeReference(Rtree *pRtree){
  154359. pRtree->nBusy++;
  154360. }
  154361. /*
  154362. ** Decrement the r-tree reference count. When the reference count reaches
  154363. ** zero the structure is deleted.
  154364. */
  154365. static void rtreeRelease(Rtree *pRtree){
  154366. pRtree->nBusy--;
  154367. if( pRtree->nBusy==0 ){
  154368. pRtree->inWrTrans = 0;
  154369. pRtree->nCursor = 0;
  154370. nodeBlobReset(pRtree);
  154371. sqlite3_finalize(pRtree->pWriteNode);
  154372. sqlite3_finalize(pRtree->pDeleteNode);
  154373. sqlite3_finalize(pRtree->pReadRowid);
  154374. sqlite3_finalize(pRtree->pWriteRowid);
  154375. sqlite3_finalize(pRtree->pDeleteRowid);
  154376. sqlite3_finalize(pRtree->pReadParent);
  154377. sqlite3_finalize(pRtree->pWriteParent);
  154378. sqlite3_finalize(pRtree->pDeleteParent);
  154379. sqlite3_free(pRtree);
  154380. }
  154381. }
  154382. /*
  154383. ** Rtree virtual table module xDisconnect method.
  154384. */
  154385. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  154386. rtreeRelease((Rtree *)pVtab);
  154387. return SQLITE_OK;
  154388. }
  154389. /*
  154390. ** Rtree virtual table module xDestroy method.
  154391. */
  154392. static int rtreeDestroy(sqlite3_vtab *pVtab){
  154393. Rtree *pRtree = (Rtree *)pVtab;
  154394. int rc;
  154395. char *zCreate = sqlite3_mprintf(
  154396. "DROP TABLE '%q'.'%q_node';"
  154397. "DROP TABLE '%q'.'%q_rowid';"
  154398. "DROP TABLE '%q'.'%q_parent';",
  154399. pRtree->zDb, pRtree->zName,
  154400. pRtree->zDb, pRtree->zName,
  154401. pRtree->zDb, pRtree->zName
  154402. );
  154403. if( !zCreate ){
  154404. rc = SQLITE_NOMEM;
  154405. }else{
  154406. nodeBlobReset(pRtree);
  154407. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  154408. sqlite3_free(zCreate);
  154409. }
  154410. if( rc==SQLITE_OK ){
  154411. rtreeRelease(pRtree);
  154412. }
  154413. return rc;
  154414. }
  154415. /*
  154416. ** Rtree virtual table module xOpen method.
  154417. */
  154418. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  154419. int rc = SQLITE_NOMEM;
  154420. Rtree *pRtree = (Rtree *)pVTab;
  154421. RtreeCursor *pCsr;
  154422. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  154423. if( pCsr ){
  154424. memset(pCsr, 0, sizeof(RtreeCursor));
  154425. pCsr->base.pVtab = pVTab;
  154426. rc = SQLITE_OK;
  154427. pRtree->nCursor++;
  154428. }
  154429. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  154430. return rc;
  154431. }
  154432. /*
  154433. ** Free the RtreeCursor.aConstraint[] array and its contents.
  154434. */
  154435. static void freeCursorConstraints(RtreeCursor *pCsr){
  154436. if( pCsr->aConstraint ){
  154437. int i; /* Used to iterate through constraint array */
  154438. for(i=0; i<pCsr->nConstraint; i++){
  154439. sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
  154440. if( pInfo ){
  154441. if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
  154442. sqlite3_free(pInfo);
  154443. }
  154444. }
  154445. sqlite3_free(pCsr->aConstraint);
  154446. pCsr->aConstraint = 0;
  154447. }
  154448. }
  154449. /*
  154450. ** Rtree virtual table module xClose method.
  154451. */
  154452. static int rtreeClose(sqlite3_vtab_cursor *cur){
  154453. Rtree *pRtree = (Rtree *)(cur->pVtab);
  154454. int ii;
  154455. RtreeCursor *pCsr = (RtreeCursor *)cur;
  154456. assert( pRtree->nCursor>0 );
  154457. freeCursorConstraints(pCsr);
  154458. sqlite3_free(pCsr->aPoint);
  154459. for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
  154460. sqlite3_free(pCsr);
  154461. pRtree->nCursor--;
  154462. nodeBlobReset(pRtree);
  154463. return SQLITE_OK;
  154464. }
  154465. /*
  154466. ** Rtree virtual table module xEof method.
  154467. **
  154468. ** Return non-zero if the cursor does not currently point to a valid
  154469. ** record (i.e if the scan has finished), or zero otherwise.
  154470. */
  154471. static int rtreeEof(sqlite3_vtab_cursor *cur){
  154472. RtreeCursor *pCsr = (RtreeCursor *)cur;
  154473. return pCsr->atEOF;
  154474. }
  154475. /*
  154476. ** Convert raw bits from the on-disk RTree record into a coordinate value.
  154477. ** The on-disk format is big-endian and needs to be converted for little-
  154478. ** endian platforms. The on-disk record stores integer coordinates if
  154479. ** eInt is true and it stores 32-bit floating point records if eInt is
  154480. ** false. a[] is the four bytes of the on-disk record to be decoded.
  154481. ** Store the results in "r".
  154482. **
  154483. ** There are five versions of this macro. The last one is generic. The
  154484. ** other four are various architectures-specific optimizations.
  154485. */
  154486. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  154487. #define RTREE_DECODE_COORD(eInt, a, r) { \
  154488. RtreeCoord c; /* Coordinate decoded */ \
  154489. c.u = _byteswap_ulong(*(u32*)a); \
  154490. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  154491. }
  154492. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  154493. #define RTREE_DECODE_COORD(eInt, a, r) { \
  154494. RtreeCoord c; /* Coordinate decoded */ \
  154495. c.u = __builtin_bswap32(*(u32*)a); \
  154496. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  154497. }
  154498. #elif SQLITE_BYTEORDER==1234
  154499. #define RTREE_DECODE_COORD(eInt, a, r) { \
  154500. RtreeCoord c; /* Coordinate decoded */ \
  154501. memcpy(&c.u,a,4); \
  154502. c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
  154503. ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
  154504. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  154505. }
  154506. #elif SQLITE_BYTEORDER==4321
  154507. #define RTREE_DECODE_COORD(eInt, a, r) { \
  154508. RtreeCoord c; /* Coordinate decoded */ \
  154509. memcpy(&c.u,a,4); \
  154510. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  154511. }
  154512. #else
  154513. #define RTREE_DECODE_COORD(eInt, a, r) { \
  154514. RtreeCoord c; /* Coordinate decoded */ \
  154515. c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
  154516. +((u32)a[2]<<8) + a[3]; \
  154517. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  154518. }
  154519. #endif
  154520. /*
  154521. ** Check the RTree node or entry given by pCellData and p against the MATCH
  154522. ** constraint pConstraint.
  154523. */
  154524. static int rtreeCallbackConstraint(
  154525. RtreeConstraint *pConstraint, /* The constraint to test */
  154526. int eInt, /* True if RTree holding integer coordinates */
  154527. u8 *pCellData, /* Raw cell content */
  154528. RtreeSearchPoint *pSearch, /* Container of this cell */
  154529. sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
  154530. int *peWithin /* OUT: visibility of the cell */
  154531. ){
  154532. sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
  154533. int nCoord = pInfo->nCoord; /* No. of coordinates */
  154534. int rc; /* Callback return code */
  154535. RtreeCoord c; /* Translator union */
  154536. sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
  154537. assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
  154538. assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
  154539. if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
  154540. pInfo->iRowid = readInt64(pCellData);
  154541. }
  154542. pCellData += 8;
  154543. #ifndef SQLITE_RTREE_INT_ONLY
  154544. if( eInt==0 ){
  154545. switch( nCoord ){
  154546. case 10: readCoord(pCellData+36, &c); aCoord[9] = c.f;
  154547. readCoord(pCellData+32, &c); aCoord[8] = c.f;
  154548. case 8: readCoord(pCellData+28, &c); aCoord[7] = c.f;
  154549. readCoord(pCellData+24, &c); aCoord[6] = c.f;
  154550. case 6: readCoord(pCellData+20, &c); aCoord[5] = c.f;
  154551. readCoord(pCellData+16, &c); aCoord[4] = c.f;
  154552. case 4: readCoord(pCellData+12, &c); aCoord[3] = c.f;
  154553. readCoord(pCellData+8, &c); aCoord[2] = c.f;
  154554. default: readCoord(pCellData+4, &c); aCoord[1] = c.f;
  154555. readCoord(pCellData, &c); aCoord[0] = c.f;
  154556. }
  154557. }else
  154558. #endif
  154559. {
  154560. switch( nCoord ){
  154561. case 10: readCoord(pCellData+36, &c); aCoord[9] = c.i;
  154562. readCoord(pCellData+32, &c); aCoord[8] = c.i;
  154563. case 8: readCoord(pCellData+28, &c); aCoord[7] = c.i;
  154564. readCoord(pCellData+24, &c); aCoord[6] = c.i;
  154565. case 6: readCoord(pCellData+20, &c); aCoord[5] = c.i;
  154566. readCoord(pCellData+16, &c); aCoord[4] = c.i;
  154567. case 4: readCoord(pCellData+12, &c); aCoord[3] = c.i;
  154568. readCoord(pCellData+8, &c); aCoord[2] = c.i;
  154569. default: readCoord(pCellData+4, &c); aCoord[1] = c.i;
  154570. readCoord(pCellData, &c); aCoord[0] = c.i;
  154571. }
  154572. }
  154573. if( pConstraint->op==RTREE_MATCH ){
  154574. int eWithin = 0;
  154575. rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
  154576. nCoord, aCoord, &eWithin);
  154577. if( eWithin==0 ) *peWithin = NOT_WITHIN;
  154578. *prScore = RTREE_ZERO;
  154579. }else{
  154580. pInfo->aCoord = aCoord;
  154581. pInfo->iLevel = pSearch->iLevel - 1;
  154582. pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
  154583. pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
  154584. rc = pConstraint->u.xQueryFunc(pInfo);
  154585. if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
  154586. if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
  154587. *prScore = pInfo->rScore;
  154588. }
  154589. }
  154590. return rc;
  154591. }
  154592. /*
  154593. ** Check the internal RTree node given by pCellData against constraint p.
  154594. ** If this constraint cannot be satisfied by any child within the node,
  154595. ** set *peWithin to NOT_WITHIN.
  154596. */
  154597. static void rtreeNonleafConstraint(
  154598. RtreeConstraint *p, /* The constraint to test */
  154599. int eInt, /* True if RTree holds integer coordinates */
  154600. u8 *pCellData, /* Raw cell content as appears on disk */
  154601. int *peWithin /* Adjust downward, as appropriate */
  154602. ){
  154603. sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
  154604. /* p->iCoord might point to either a lower or upper bound coordinate
  154605. ** in a coordinate pair. But make pCellData point to the lower bound.
  154606. */
  154607. pCellData += 8 + 4*(p->iCoord&0xfe);
  154608. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  154609. || p->op==RTREE_GT || p->op==RTREE_EQ );
  154610. assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
  154611. switch( p->op ){
  154612. case RTREE_LE:
  154613. case RTREE_LT:
  154614. case RTREE_EQ:
  154615. RTREE_DECODE_COORD(eInt, pCellData, val);
  154616. /* val now holds the lower bound of the coordinate pair */
  154617. if( p->u.rValue>=val ) return;
  154618. if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
  154619. /* Fall through for the RTREE_EQ case */
  154620. default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
  154621. pCellData += 4;
  154622. RTREE_DECODE_COORD(eInt, pCellData, val);
  154623. /* val now holds the upper bound of the coordinate pair */
  154624. if( p->u.rValue<=val ) return;
  154625. }
  154626. *peWithin = NOT_WITHIN;
  154627. }
  154628. /*
  154629. ** Check the leaf RTree cell given by pCellData against constraint p.
  154630. ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
  154631. ** If the constraint is satisfied, leave *peWithin unchanged.
  154632. **
  154633. ** The constraint is of the form: xN op $val
  154634. **
  154635. ** The op is given by p->op. The xN is p->iCoord-th coordinate in
  154636. ** pCellData. $val is given by p->u.rValue.
  154637. */
  154638. static void rtreeLeafConstraint(
  154639. RtreeConstraint *p, /* The constraint to test */
  154640. int eInt, /* True if RTree holds integer coordinates */
  154641. u8 *pCellData, /* Raw cell content as appears on disk */
  154642. int *peWithin /* Adjust downward, as appropriate */
  154643. ){
  154644. RtreeDValue xN; /* Coordinate value converted to a double */
  154645. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  154646. || p->op==RTREE_GT || p->op==RTREE_EQ );
  154647. pCellData += 8 + p->iCoord*4;
  154648. assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
  154649. RTREE_DECODE_COORD(eInt, pCellData, xN);
  154650. switch( p->op ){
  154651. case RTREE_LE: if( xN <= p->u.rValue ) return; break;
  154652. case RTREE_LT: if( xN < p->u.rValue ) return; break;
  154653. case RTREE_GE: if( xN >= p->u.rValue ) return; break;
  154654. case RTREE_GT: if( xN > p->u.rValue ) return; break;
  154655. default: if( xN == p->u.rValue ) return; break;
  154656. }
  154657. *peWithin = NOT_WITHIN;
  154658. }
  154659. /*
  154660. ** One of the cells in node pNode is guaranteed to have a 64-bit
  154661. ** integer value equal to iRowid. Return the index of this cell.
  154662. */
  154663. static int nodeRowidIndex(
  154664. Rtree *pRtree,
  154665. RtreeNode *pNode,
  154666. i64 iRowid,
  154667. int *piIndex
  154668. ){
  154669. int ii;
  154670. int nCell = NCELL(pNode);
  154671. assert( nCell<200 );
  154672. for(ii=0; ii<nCell; ii++){
  154673. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  154674. *piIndex = ii;
  154675. return SQLITE_OK;
  154676. }
  154677. }
  154678. return SQLITE_CORRUPT_VTAB;
  154679. }
  154680. /*
  154681. ** Return the index of the cell containing a pointer to node pNode
  154682. ** in its parent. If pNode is the root node, return -1.
  154683. */
  154684. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  154685. RtreeNode *pParent = pNode->pParent;
  154686. if( pParent ){
  154687. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  154688. }
  154689. *piIndex = -1;
  154690. return SQLITE_OK;
  154691. }
  154692. /*
  154693. ** Compare two search points. Return negative, zero, or positive if the first
  154694. ** is less than, equal to, or greater than the second.
  154695. **
  154696. ** The rScore is the primary key. Smaller rScore values come first.
  154697. ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
  154698. ** iLevel values coming first. In this way, if rScore is the same for all
  154699. ** SearchPoints, then iLevel becomes the deciding factor and the result
  154700. ** is a depth-first search, which is the desired default behavior.
  154701. */
  154702. static int rtreeSearchPointCompare(
  154703. const RtreeSearchPoint *pA,
  154704. const RtreeSearchPoint *pB
  154705. ){
  154706. if( pA->rScore<pB->rScore ) return -1;
  154707. if( pA->rScore>pB->rScore ) return +1;
  154708. if( pA->iLevel<pB->iLevel ) return -1;
  154709. if( pA->iLevel>pB->iLevel ) return +1;
  154710. return 0;
  154711. }
  154712. /*
  154713. ** Interchange two search points in a cursor.
  154714. */
  154715. static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
  154716. RtreeSearchPoint t = p->aPoint[i];
  154717. assert( i<j );
  154718. p->aPoint[i] = p->aPoint[j];
  154719. p->aPoint[j] = t;
  154720. i++; j++;
  154721. if( i<RTREE_CACHE_SZ ){
  154722. if( j>=RTREE_CACHE_SZ ){
  154723. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  154724. p->aNode[i] = 0;
  154725. }else{
  154726. RtreeNode *pTemp = p->aNode[i];
  154727. p->aNode[i] = p->aNode[j];
  154728. p->aNode[j] = pTemp;
  154729. }
  154730. }
  154731. }
  154732. /*
  154733. ** Return the search point with the lowest current score.
  154734. */
  154735. static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
  154736. return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
  154737. }
  154738. /*
  154739. ** Get the RtreeNode for the search point with the lowest score.
  154740. */
  154741. static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
  154742. sqlite3_int64 id;
  154743. int ii = 1 - pCur->bPoint;
  154744. assert( ii==0 || ii==1 );
  154745. assert( pCur->bPoint || pCur->nPoint );
  154746. if( pCur->aNode[ii]==0 ){
  154747. assert( pRC!=0 );
  154748. id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
  154749. *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
  154750. }
  154751. return pCur->aNode[ii];
  154752. }
  154753. /*
  154754. ** Push a new element onto the priority queue
  154755. */
  154756. static RtreeSearchPoint *rtreeEnqueue(
  154757. RtreeCursor *pCur, /* The cursor */
  154758. RtreeDValue rScore, /* Score for the new search point */
  154759. u8 iLevel /* Level for the new search point */
  154760. ){
  154761. int i, j;
  154762. RtreeSearchPoint *pNew;
  154763. if( pCur->nPoint>=pCur->nPointAlloc ){
  154764. int nNew = pCur->nPointAlloc*2 + 8;
  154765. pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
  154766. if( pNew==0 ) return 0;
  154767. pCur->aPoint = pNew;
  154768. pCur->nPointAlloc = nNew;
  154769. }
  154770. i = pCur->nPoint++;
  154771. pNew = pCur->aPoint + i;
  154772. pNew->rScore = rScore;
  154773. pNew->iLevel = iLevel;
  154774. assert( iLevel<=RTREE_MAX_DEPTH );
  154775. while( i>0 ){
  154776. RtreeSearchPoint *pParent;
  154777. j = (i-1)/2;
  154778. pParent = pCur->aPoint + j;
  154779. if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
  154780. rtreeSearchPointSwap(pCur, j, i);
  154781. i = j;
  154782. pNew = pParent;
  154783. }
  154784. return pNew;
  154785. }
  154786. /*
  154787. ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
  154788. ** NULL if malloc fails.
  154789. */
  154790. static RtreeSearchPoint *rtreeSearchPointNew(
  154791. RtreeCursor *pCur, /* The cursor */
  154792. RtreeDValue rScore, /* Score for the new search point */
  154793. u8 iLevel /* Level for the new search point */
  154794. ){
  154795. RtreeSearchPoint *pNew, *pFirst;
  154796. pFirst = rtreeSearchPointFirst(pCur);
  154797. pCur->anQueue[iLevel]++;
  154798. if( pFirst==0
  154799. || pFirst->rScore>rScore
  154800. || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
  154801. ){
  154802. if( pCur->bPoint ){
  154803. int ii;
  154804. pNew = rtreeEnqueue(pCur, rScore, iLevel);
  154805. if( pNew==0 ) return 0;
  154806. ii = (int)(pNew - pCur->aPoint) + 1;
  154807. if( ii<RTREE_CACHE_SZ ){
  154808. assert( pCur->aNode[ii]==0 );
  154809. pCur->aNode[ii] = pCur->aNode[0];
  154810. }else{
  154811. nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
  154812. }
  154813. pCur->aNode[0] = 0;
  154814. *pNew = pCur->sPoint;
  154815. }
  154816. pCur->sPoint.rScore = rScore;
  154817. pCur->sPoint.iLevel = iLevel;
  154818. pCur->bPoint = 1;
  154819. return &pCur->sPoint;
  154820. }else{
  154821. return rtreeEnqueue(pCur, rScore, iLevel);
  154822. }
  154823. }
  154824. #if 0
  154825. /* Tracing routines for the RtreeSearchPoint queue */
  154826. static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
  154827. if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
  154828. printf(" %d.%05lld.%02d %g %d",
  154829. p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
  154830. );
  154831. idx++;
  154832. if( idx<RTREE_CACHE_SZ ){
  154833. printf(" %p\n", pCur->aNode[idx]);
  154834. }else{
  154835. printf("\n");
  154836. }
  154837. }
  154838. static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
  154839. int ii;
  154840. printf("=== %9s ", zPrefix);
  154841. if( pCur->bPoint ){
  154842. tracePoint(&pCur->sPoint, -1, pCur);
  154843. }
  154844. for(ii=0; ii<pCur->nPoint; ii++){
  154845. if( ii>0 || pCur->bPoint ) printf(" ");
  154846. tracePoint(&pCur->aPoint[ii], ii, pCur);
  154847. }
  154848. }
  154849. # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
  154850. #else
  154851. # define RTREE_QUEUE_TRACE(A,B) /* no-op */
  154852. #endif
  154853. /* Remove the search point with the lowest current score.
  154854. */
  154855. static void rtreeSearchPointPop(RtreeCursor *p){
  154856. int i, j, k, n;
  154857. i = 1 - p->bPoint;
  154858. assert( i==0 || i==1 );
  154859. if( p->aNode[i] ){
  154860. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  154861. p->aNode[i] = 0;
  154862. }
  154863. if( p->bPoint ){
  154864. p->anQueue[p->sPoint.iLevel]--;
  154865. p->bPoint = 0;
  154866. }else if( p->nPoint ){
  154867. p->anQueue[p->aPoint[0].iLevel]--;
  154868. n = --p->nPoint;
  154869. p->aPoint[0] = p->aPoint[n];
  154870. if( n<RTREE_CACHE_SZ-1 ){
  154871. p->aNode[1] = p->aNode[n+1];
  154872. p->aNode[n+1] = 0;
  154873. }
  154874. i = 0;
  154875. while( (j = i*2+1)<n ){
  154876. k = j+1;
  154877. if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
  154878. if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
  154879. rtreeSearchPointSwap(p, i, k);
  154880. i = k;
  154881. }else{
  154882. break;
  154883. }
  154884. }else{
  154885. if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
  154886. rtreeSearchPointSwap(p, i, j);
  154887. i = j;
  154888. }else{
  154889. break;
  154890. }
  154891. }
  154892. }
  154893. }
  154894. }
  154895. /*
  154896. ** Continue the search on cursor pCur until the front of the queue
  154897. ** contains an entry suitable for returning as a result-set row,
  154898. ** or until the RtreeSearchPoint queue is empty, indicating that the
  154899. ** query has completed.
  154900. */
  154901. static int rtreeStepToLeaf(RtreeCursor *pCur){
  154902. RtreeSearchPoint *p;
  154903. Rtree *pRtree = RTREE_OF_CURSOR(pCur);
  154904. RtreeNode *pNode;
  154905. int eWithin;
  154906. int rc = SQLITE_OK;
  154907. int nCell;
  154908. int nConstraint = pCur->nConstraint;
  154909. int ii;
  154910. int eInt;
  154911. RtreeSearchPoint x;
  154912. eInt = pRtree->eCoordType==RTREE_COORD_INT32;
  154913. while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
  154914. pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
  154915. if( rc ) return rc;
  154916. nCell = NCELL(pNode);
  154917. assert( nCell<200 );
  154918. while( p->iCell<nCell ){
  154919. sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
  154920. u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
  154921. eWithin = FULLY_WITHIN;
  154922. for(ii=0; ii<nConstraint; ii++){
  154923. RtreeConstraint *pConstraint = pCur->aConstraint + ii;
  154924. if( pConstraint->op>=RTREE_MATCH ){
  154925. rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
  154926. &rScore, &eWithin);
  154927. if( rc ) return rc;
  154928. }else if( p->iLevel==1 ){
  154929. rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
  154930. }else{
  154931. rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
  154932. }
  154933. if( eWithin==NOT_WITHIN ) break;
  154934. }
  154935. p->iCell++;
  154936. if( eWithin==NOT_WITHIN ) continue;
  154937. x.iLevel = p->iLevel - 1;
  154938. if( x.iLevel ){
  154939. x.id = readInt64(pCellData);
  154940. x.iCell = 0;
  154941. }else{
  154942. x.id = p->id;
  154943. x.iCell = p->iCell - 1;
  154944. }
  154945. if( p->iCell>=nCell ){
  154946. RTREE_QUEUE_TRACE(pCur, "POP-S:");
  154947. rtreeSearchPointPop(pCur);
  154948. }
  154949. if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
  154950. p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
  154951. if( p==0 ) return SQLITE_NOMEM;
  154952. p->eWithin = (u8)eWithin;
  154953. p->id = x.id;
  154954. p->iCell = x.iCell;
  154955. RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
  154956. break;
  154957. }
  154958. if( p->iCell>=nCell ){
  154959. RTREE_QUEUE_TRACE(pCur, "POP-Se:");
  154960. rtreeSearchPointPop(pCur);
  154961. }
  154962. }
  154963. pCur->atEOF = p==0;
  154964. return SQLITE_OK;
  154965. }
  154966. /*
  154967. ** Rtree virtual table module xNext method.
  154968. */
  154969. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  154970. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  154971. int rc = SQLITE_OK;
  154972. /* Move to the next entry that matches the configured constraints. */
  154973. RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
  154974. rtreeSearchPointPop(pCsr);
  154975. rc = rtreeStepToLeaf(pCsr);
  154976. return rc;
  154977. }
  154978. /*
  154979. ** Rtree virtual table module xRowid method.
  154980. */
  154981. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  154982. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  154983. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  154984. int rc = SQLITE_OK;
  154985. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  154986. if( rc==SQLITE_OK && p ){
  154987. *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
  154988. }
  154989. return rc;
  154990. }
  154991. /*
  154992. ** Rtree virtual table module xColumn method.
  154993. */
  154994. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  154995. Rtree *pRtree = (Rtree *)cur->pVtab;
  154996. RtreeCursor *pCsr = (RtreeCursor *)cur;
  154997. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  154998. RtreeCoord c;
  154999. int rc = SQLITE_OK;
  155000. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  155001. if( rc ) return rc;
  155002. if( p==0 ) return SQLITE_OK;
  155003. if( i==0 ){
  155004. sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
  155005. }else{
  155006. nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
  155007. #ifndef SQLITE_RTREE_INT_ONLY
  155008. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  155009. sqlite3_result_double(ctx, c.f);
  155010. }else
  155011. #endif
  155012. {
  155013. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  155014. sqlite3_result_int(ctx, c.i);
  155015. }
  155016. }
  155017. return SQLITE_OK;
  155018. }
  155019. /*
  155020. ** Use nodeAcquire() to obtain the leaf node containing the record with
  155021. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  155022. ** return SQLITE_OK. If there is no such record in the table, set
  155023. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  155024. ** to zero and return an SQLite error code.
  155025. */
  155026. static int findLeafNode(
  155027. Rtree *pRtree, /* RTree to search */
  155028. i64 iRowid, /* The rowid searching for */
  155029. RtreeNode **ppLeaf, /* Write the node here */
  155030. sqlite3_int64 *piNode /* Write the node-id here */
  155031. ){
  155032. int rc;
  155033. *ppLeaf = 0;
  155034. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  155035. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  155036. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  155037. if( piNode ) *piNode = iNode;
  155038. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  155039. sqlite3_reset(pRtree->pReadRowid);
  155040. }else{
  155041. rc = sqlite3_reset(pRtree->pReadRowid);
  155042. }
  155043. return rc;
  155044. }
  155045. /*
  155046. ** This function is called to configure the RtreeConstraint object passed
  155047. ** as the second argument for a MATCH constraint. The value passed as the
  155048. ** first argument to this function is the right-hand operand to the MATCH
  155049. ** operator.
  155050. */
  155051. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  155052. RtreeMatchArg *pBlob; /* BLOB returned by geometry function */
  155053. sqlite3_rtree_query_info *pInfo; /* Callback information */
  155054. int nBlob; /* Size of the geometry function blob */
  155055. int nExpected; /* Expected size of the BLOB */
  155056. /* Check that value is actually a blob. */
  155057. if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
  155058. /* Check that the blob is roughly the right size. */
  155059. nBlob = sqlite3_value_bytes(pValue);
  155060. if( nBlob<(int)sizeof(RtreeMatchArg) ){
  155061. return SQLITE_ERROR;
  155062. }
  155063. pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
  155064. if( !pInfo ) return SQLITE_NOMEM;
  155065. memset(pInfo, 0, sizeof(*pInfo));
  155066. pBlob = (RtreeMatchArg*)&pInfo[1];
  155067. memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
  155068. nExpected = (int)(sizeof(RtreeMatchArg) +
  155069. pBlob->nParam*sizeof(sqlite3_value*) +
  155070. (pBlob->nParam-1)*sizeof(RtreeDValue));
  155071. if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
  155072. sqlite3_free(pInfo);
  155073. return SQLITE_ERROR;
  155074. }
  155075. pInfo->pContext = pBlob->cb.pContext;
  155076. pInfo->nParam = pBlob->nParam;
  155077. pInfo->aParam = pBlob->aParam;
  155078. pInfo->apSqlParam = pBlob->apSqlParam;
  155079. if( pBlob->cb.xGeom ){
  155080. pCons->u.xGeom = pBlob->cb.xGeom;
  155081. }else{
  155082. pCons->op = RTREE_QUERY;
  155083. pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
  155084. }
  155085. pCons->pInfo = pInfo;
  155086. return SQLITE_OK;
  155087. }
  155088. /*
  155089. ** Rtree virtual table module xFilter method.
  155090. */
  155091. static int rtreeFilter(
  155092. sqlite3_vtab_cursor *pVtabCursor,
  155093. int idxNum, const char *idxStr,
  155094. int argc, sqlite3_value **argv
  155095. ){
  155096. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  155097. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  155098. RtreeNode *pRoot = 0;
  155099. int ii;
  155100. int rc = SQLITE_OK;
  155101. int iCell = 0;
  155102. rtreeReference(pRtree);
  155103. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  155104. freeCursorConstraints(pCsr);
  155105. sqlite3_free(pCsr->aPoint);
  155106. memset(pCsr, 0, sizeof(RtreeCursor));
  155107. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  155108. pCsr->iStrategy = idxNum;
  155109. if( idxNum==1 ){
  155110. /* Special case - lookup by rowid. */
  155111. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  155112. RtreeSearchPoint *p; /* Search point for the leaf */
  155113. i64 iRowid = sqlite3_value_int64(argv[0]);
  155114. i64 iNode = 0;
  155115. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  155116. if( rc==SQLITE_OK && pLeaf!=0 ){
  155117. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  155118. assert( p!=0 ); /* Always returns pCsr->sPoint */
  155119. pCsr->aNode[0] = pLeaf;
  155120. p->id = iNode;
  155121. p->eWithin = PARTLY_WITHIN;
  155122. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  155123. p->iCell = (u8)iCell;
  155124. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  155125. }else{
  155126. pCsr->atEOF = 1;
  155127. }
  155128. }else{
  155129. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  155130. ** with the configured constraints.
  155131. */
  155132. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  155133. if( rc==SQLITE_OK && argc>0 ){
  155134. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  155135. pCsr->nConstraint = argc;
  155136. if( !pCsr->aConstraint ){
  155137. rc = SQLITE_NOMEM;
  155138. }else{
  155139. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  155140. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  155141. assert( (idxStr==0 && argc==0)
  155142. || (idxStr && (int)strlen(idxStr)==argc*2) );
  155143. for(ii=0; ii<argc; ii++){
  155144. RtreeConstraint *p = &pCsr->aConstraint[ii];
  155145. p->op = idxStr[ii*2];
  155146. p->iCoord = idxStr[ii*2+1]-'0';
  155147. if( p->op>=RTREE_MATCH ){
  155148. /* A MATCH operator. The right-hand-side must be a blob that
  155149. ** can be cast into an RtreeMatchArg object. One created using
  155150. ** an sqlite3_rtree_geometry_callback() SQL user function.
  155151. */
  155152. rc = deserializeGeometry(argv[ii], p);
  155153. if( rc!=SQLITE_OK ){
  155154. break;
  155155. }
  155156. p->pInfo->nCoord = pRtree->nDim2;
  155157. p->pInfo->anQueue = pCsr->anQueue;
  155158. p->pInfo->mxLevel = pRtree->iDepth + 1;
  155159. }else{
  155160. #ifdef SQLITE_RTREE_INT_ONLY
  155161. p->u.rValue = sqlite3_value_int64(argv[ii]);
  155162. #else
  155163. p->u.rValue = sqlite3_value_double(argv[ii]);
  155164. #endif
  155165. }
  155166. }
  155167. }
  155168. }
  155169. if( rc==SQLITE_OK ){
  155170. RtreeSearchPoint *pNew;
  155171. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
  155172. if( pNew==0 ) return SQLITE_NOMEM;
  155173. pNew->id = 1;
  155174. pNew->iCell = 0;
  155175. pNew->eWithin = PARTLY_WITHIN;
  155176. assert( pCsr->bPoint==1 );
  155177. pCsr->aNode[0] = pRoot;
  155178. pRoot = 0;
  155179. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  155180. rc = rtreeStepToLeaf(pCsr);
  155181. }
  155182. }
  155183. nodeRelease(pRtree, pRoot);
  155184. rtreeRelease(pRtree);
  155185. return rc;
  155186. }
  155187. /*
  155188. ** Rtree virtual table module xBestIndex method. There are three
  155189. ** table scan strategies to choose from (in order from most to
  155190. ** least desirable):
  155191. **
  155192. ** idxNum idxStr Strategy
  155193. ** ------------------------------------------------
  155194. ** 1 Unused Direct lookup by rowid.
  155195. ** 2 See below R-tree query or full-table scan.
  155196. ** ------------------------------------------------
  155197. **
  155198. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  155199. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  155200. ** constraint used. The first two bytes of idxStr correspond to
  155201. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  155202. ** (argvIndex==1) etc.
  155203. **
  155204. ** The first of each pair of bytes in idxStr identifies the constraint
  155205. ** operator as follows:
  155206. **
  155207. ** Operator Byte Value
  155208. ** ----------------------
  155209. ** = 0x41 ('A')
  155210. ** <= 0x42 ('B')
  155211. ** < 0x43 ('C')
  155212. ** >= 0x44 ('D')
  155213. ** > 0x45 ('E')
  155214. ** MATCH 0x46 ('F')
  155215. ** ----------------------
  155216. **
  155217. ** The second of each pair of bytes identifies the coordinate column
  155218. ** to which the constraint applies. The leftmost coordinate column
  155219. ** is 'a', the second from the left 'b' etc.
  155220. */
  155221. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  155222. Rtree *pRtree = (Rtree*)tab;
  155223. int rc = SQLITE_OK;
  155224. int ii;
  155225. int bMatch = 0; /* True if there exists a MATCH constraint */
  155226. i64 nRow; /* Estimated rows returned by this scan */
  155227. int iIdx = 0;
  155228. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  155229. memset(zIdxStr, 0, sizeof(zIdxStr));
  155230. /* Check if there exists a MATCH constraint - even an unusable one. If there
  155231. ** is, do not consider the lookup-by-rowid plan as using such a plan would
  155232. ** require the VDBE to evaluate the MATCH constraint, which is not currently
  155233. ** possible. */
  155234. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  155235. if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  155236. bMatch = 1;
  155237. }
  155238. }
  155239. assert( pIdxInfo->idxStr==0 );
  155240. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  155241. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  155242. if( bMatch==0 && p->usable
  155243. && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
  155244. ){
  155245. /* We have an equality constraint on the rowid. Use strategy 1. */
  155246. int jj;
  155247. for(jj=0; jj<ii; jj++){
  155248. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  155249. pIdxInfo->aConstraintUsage[jj].omit = 0;
  155250. }
  155251. pIdxInfo->idxNum = 1;
  155252. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  155253. pIdxInfo->aConstraintUsage[jj].omit = 1;
  155254. /* This strategy involves a two rowid lookups on an B-Tree structures
  155255. ** and then a linear search of an R-Tree node. This should be
  155256. ** considered almost as quick as a direct rowid lookup (for which
  155257. ** sqlite uses an internal cost of 0.0). It is expected to return
  155258. ** a single row.
  155259. */
  155260. pIdxInfo->estimatedCost = 30.0;
  155261. pIdxInfo->estimatedRows = 1;
  155262. return SQLITE_OK;
  155263. }
  155264. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  155265. u8 op;
  155266. switch( p->op ){
  155267. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  155268. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  155269. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  155270. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  155271. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  155272. default:
  155273. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  155274. op = RTREE_MATCH;
  155275. break;
  155276. }
  155277. zIdxStr[iIdx++] = op;
  155278. zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
  155279. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  155280. pIdxInfo->aConstraintUsage[ii].omit = 1;
  155281. }
  155282. }
  155283. pIdxInfo->idxNum = 2;
  155284. pIdxInfo->needToFreeIdxStr = 1;
  155285. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  155286. return SQLITE_NOMEM;
  155287. }
  155288. nRow = pRtree->nRowEst >> (iIdx/2);
  155289. pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
  155290. pIdxInfo->estimatedRows = nRow;
  155291. return rc;
  155292. }
  155293. /*
  155294. ** Return the N-dimensional volumn of the cell stored in *p.
  155295. */
  155296. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  155297. RtreeDValue area = (RtreeDValue)1;
  155298. assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
  155299. #ifndef SQLITE_RTREE_INT_ONLY
  155300. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  155301. switch( pRtree->nDim ){
  155302. case 5: area = p->aCoord[9].f - p->aCoord[8].f;
  155303. case 4: area *= p->aCoord[7].f - p->aCoord[6].f;
  155304. case 3: area *= p->aCoord[5].f - p->aCoord[4].f;
  155305. case 2: area *= p->aCoord[3].f - p->aCoord[2].f;
  155306. default: area *= p->aCoord[1].f - p->aCoord[0].f;
  155307. }
  155308. }else
  155309. #endif
  155310. {
  155311. switch( pRtree->nDim ){
  155312. case 5: area = p->aCoord[9].i - p->aCoord[8].i;
  155313. case 4: area *= p->aCoord[7].i - p->aCoord[6].i;
  155314. case 3: area *= p->aCoord[5].i - p->aCoord[4].i;
  155315. case 2: area *= p->aCoord[3].i - p->aCoord[2].i;
  155316. default: area *= p->aCoord[1].i - p->aCoord[0].i;
  155317. }
  155318. }
  155319. return area;
  155320. }
  155321. /*
  155322. ** Return the margin length of cell p. The margin length is the sum
  155323. ** of the objects size in each dimension.
  155324. */
  155325. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  155326. RtreeDValue margin = 0;
  155327. int ii = pRtree->nDim2 - 2;
  155328. do{
  155329. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  155330. ii -= 2;
  155331. }while( ii>=0 );
  155332. return margin;
  155333. }
  155334. /*
  155335. ** Store the union of cells p1 and p2 in p1.
  155336. */
  155337. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  155338. int ii = 0;
  155339. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  155340. do{
  155341. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  155342. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  155343. ii += 2;
  155344. }while( ii<pRtree->nDim2 );
  155345. }else{
  155346. do{
  155347. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  155348. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  155349. ii += 2;
  155350. }while( ii<pRtree->nDim2 );
  155351. }
  155352. }
  155353. /*
  155354. ** Return true if the area covered by p2 is a subset of the area covered
  155355. ** by p1. False otherwise.
  155356. */
  155357. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  155358. int ii;
  155359. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  155360. for(ii=0; ii<pRtree->nDim2; ii+=2){
  155361. RtreeCoord *a1 = &p1->aCoord[ii];
  155362. RtreeCoord *a2 = &p2->aCoord[ii];
  155363. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  155364. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  155365. ){
  155366. return 0;
  155367. }
  155368. }
  155369. return 1;
  155370. }
  155371. /*
  155372. ** Return the amount cell p would grow by if it were unioned with pCell.
  155373. */
  155374. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  155375. RtreeDValue area;
  155376. RtreeCell cell;
  155377. memcpy(&cell, p, sizeof(RtreeCell));
  155378. area = cellArea(pRtree, &cell);
  155379. cellUnion(pRtree, &cell, pCell);
  155380. return (cellArea(pRtree, &cell)-area);
  155381. }
  155382. static RtreeDValue cellOverlap(
  155383. Rtree *pRtree,
  155384. RtreeCell *p,
  155385. RtreeCell *aCell,
  155386. int nCell
  155387. ){
  155388. int ii;
  155389. RtreeDValue overlap = RTREE_ZERO;
  155390. for(ii=0; ii<nCell; ii++){
  155391. int jj;
  155392. RtreeDValue o = (RtreeDValue)1;
  155393. for(jj=0; jj<pRtree->nDim2; jj+=2){
  155394. RtreeDValue x1, x2;
  155395. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  155396. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  155397. if( x2<x1 ){
  155398. o = (RtreeDValue)0;
  155399. break;
  155400. }else{
  155401. o = o * (x2-x1);
  155402. }
  155403. }
  155404. overlap += o;
  155405. }
  155406. return overlap;
  155407. }
  155408. /*
  155409. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  155410. ** ChooseSubTree in r*tree terminology.
  155411. */
  155412. static int ChooseLeaf(
  155413. Rtree *pRtree, /* Rtree table */
  155414. RtreeCell *pCell, /* Cell to insert into rtree */
  155415. int iHeight, /* Height of sub-tree rooted at pCell */
  155416. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  155417. ){
  155418. int rc;
  155419. int ii;
  155420. RtreeNode *pNode;
  155421. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  155422. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  155423. int iCell;
  155424. sqlite3_int64 iBest = 0;
  155425. RtreeDValue fMinGrowth = RTREE_ZERO;
  155426. RtreeDValue fMinArea = RTREE_ZERO;
  155427. int nCell = NCELL(pNode);
  155428. RtreeCell cell;
  155429. RtreeNode *pChild;
  155430. RtreeCell *aCell = 0;
  155431. /* Select the child node which will be enlarged the least if pCell
  155432. ** is inserted into it. Resolve ties by choosing the entry with
  155433. ** the smallest area.
  155434. */
  155435. for(iCell=0; iCell<nCell; iCell++){
  155436. int bBest = 0;
  155437. RtreeDValue growth;
  155438. RtreeDValue area;
  155439. nodeGetCell(pRtree, pNode, iCell, &cell);
  155440. growth = cellGrowth(pRtree, &cell, pCell);
  155441. area = cellArea(pRtree, &cell);
  155442. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  155443. bBest = 1;
  155444. }
  155445. if( bBest ){
  155446. fMinGrowth = growth;
  155447. fMinArea = area;
  155448. iBest = cell.iRowid;
  155449. }
  155450. }
  155451. sqlite3_free(aCell);
  155452. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  155453. nodeRelease(pRtree, pNode);
  155454. pNode = pChild;
  155455. }
  155456. *ppLeaf = pNode;
  155457. return rc;
  155458. }
  155459. /*
  155460. ** A cell with the same content as pCell has just been inserted into
  155461. ** the node pNode. This function updates the bounding box cells in
  155462. ** all ancestor elements.
  155463. */
  155464. static int AdjustTree(
  155465. Rtree *pRtree, /* Rtree table */
  155466. RtreeNode *pNode, /* Adjust ancestry of this node. */
  155467. RtreeCell *pCell /* This cell was just inserted */
  155468. ){
  155469. RtreeNode *p = pNode;
  155470. while( p->pParent ){
  155471. RtreeNode *pParent = p->pParent;
  155472. RtreeCell cell;
  155473. int iCell;
  155474. if( nodeParentIndex(pRtree, p, &iCell) ){
  155475. return SQLITE_CORRUPT_VTAB;
  155476. }
  155477. nodeGetCell(pRtree, pParent, iCell, &cell);
  155478. if( !cellContains(pRtree, &cell, pCell) ){
  155479. cellUnion(pRtree, &cell, pCell);
  155480. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  155481. }
  155482. p = pParent;
  155483. }
  155484. return SQLITE_OK;
  155485. }
  155486. /*
  155487. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  155488. */
  155489. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  155490. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  155491. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  155492. sqlite3_step(pRtree->pWriteRowid);
  155493. return sqlite3_reset(pRtree->pWriteRowid);
  155494. }
  155495. /*
  155496. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  155497. */
  155498. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  155499. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  155500. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  155501. sqlite3_step(pRtree->pWriteParent);
  155502. return sqlite3_reset(pRtree->pWriteParent);
  155503. }
  155504. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  155505. /*
  155506. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  155507. ** nIdx. The aIdx array contains the set of integers from 0 to
  155508. ** (nIdx-1) in no particular order. This function sorts the values
  155509. ** in aIdx according to the indexed values in aDistance. For
  155510. ** example, assuming the inputs:
  155511. **
  155512. ** aIdx = { 0, 1, 2, 3 }
  155513. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  155514. **
  155515. ** this function sets the aIdx array to contain:
  155516. **
  155517. ** aIdx = { 0, 1, 2, 3 }
  155518. **
  155519. ** The aSpare array is used as temporary working space by the
  155520. ** sorting algorithm.
  155521. */
  155522. static void SortByDistance(
  155523. int *aIdx,
  155524. int nIdx,
  155525. RtreeDValue *aDistance,
  155526. int *aSpare
  155527. ){
  155528. if( nIdx>1 ){
  155529. int iLeft = 0;
  155530. int iRight = 0;
  155531. int nLeft = nIdx/2;
  155532. int nRight = nIdx-nLeft;
  155533. int *aLeft = aIdx;
  155534. int *aRight = &aIdx[nLeft];
  155535. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  155536. SortByDistance(aRight, nRight, aDistance, aSpare);
  155537. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  155538. aLeft = aSpare;
  155539. while( iLeft<nLeft || iRight<nRight ){
  155540. if( iLeft==nLeft ){
  155541. aIdx[iLeft+iRight] = aRight[iRight];
  155542. iRight++;
  155543. }else if( iRight==nRight ){
  155544. aIdx[iLeft+iRight] = aLeft[iLeft];
  155545. iLeft++;
  155546. }else{
  155547. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  155548. RtreeDValue fRight = aDistance[aRight[iRight]];
  155549. if( fLeft<fRight ){
  155550. aIdx[iLeft+iRight] = aLeft[iLeft];
  155551. iLeft++;
  155552. }else{
  155553. aIdx[iLeft+iRight] = aRight[iRight];
  155554. iRight++;
  155555. }
  155556. }
  155557. }
  155558. #if 0
  155559. /* Check that the sort worked */
  155560. {
  155561. int jj;
  155562. for(jj=1; jj<nIdx; jj++){
  155563. RtreeDValue left = aDistance[aIdx[jj-1]];
  155564. RtreeDValue right = aDistance[aIdx[jj]];
  155565. assert( left<=right );
  155566. }
  155567. }
  155568. #endif
  155569. }
  155570. }
  155571. /*
  155572. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  155573. ** nIdx. The aIdx array contains the set of integers from 0 to
  155574. ** (nIdx-1) in no particular order. This function sorts the values
  155575. ** in aIdx according to dimension iDim of the cells in aCell. The
  155576. ** minimum value of dimension iDim is considered first, the
  155577. ** maximum used to break ties.
  155578. **
  155579. ** The aSpare array is used as temporary working space by the
  155580. ** sorting algorithm.
  155581. */
  155582. static void SortByDimension(
  155583. Rtree *pRtree,
  155584. int *aIdx,
  155585. int nIdx,
  155586. int iDim,
  155587. RtreeCell *aCell,
  155588. int *aSpare
  155589. ){
  155590. if( nIdx>1 ){
  155591. int iLeft = 0;
  155592. int iRight = 0;
  155593. int nLeft = nIdx/2;
  155594. int nRight = nIdx-nLeft;
  155595. int *aLeft = aIdx;
  155596. int *aRight = &aIdx[nLeft];
  155597. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  155598. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  155599. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  155600. aLeft = aSpare;
  155601. while( iLeft<nLeft || iRight<nRight ){
  155602. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  155603. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  155604. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  155605. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  155606. if( (iLeft!=nLeft) && ((iRight==nRight)
  155607. || (xleft1<xright1)
  155608. || (xleft1==xright1 && xleft2<xright2)
  155609. )){
  155610. aIdx[iLeft+iRight] = aLeft[iLeft];
  155611. iLeft++;
  155612. }else{
  155613. aIdx[iLeft+iRight] = aRight[iRight];
  155614. iRight++;
  155615. }
  155616. }
  155617. #if 0
  155618. /* Check that the sort worked */
  155619. {
  155620. int jj;
  155621. for(jj=1; jj<nIdx; jj++){
  155622. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  155623. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  155624. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  155625. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  155626. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  155627. }
  155628. }
  155629. #endif
  155630. }
  155631. }
  155632. /*
  155633. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  155634. */
  155635. static int splitNodeStartree(
  155636. Rtree *pRtree,
  155637. RtreeCell *aCell,
  155638. int nCell,
  155639. RtreeNode *pLeft,
  155640. RtreeNode *pRight,
  155641. RtreeCell *pBboxLeft,
  155642. RtreeCell *pBboxRight
  155643. ){
  155644. int **aaSorted;
  155645. int *aSpare;
  155646. int ii;
  155647. int iBestDim = 0;
  155648. int iBestSplit = 0;
  155649. RtreeDValue fBestMargin = RTREE_ZERO;
  155650. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  155651. aaSorted = (int **)sqlite3_malloc(nByte);
  155652. if( !aaSorted ){
  155653. return SQLITE_NOMEM;
  155654. }
  155655. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  155656. memset(aaSorted, 0, nByte);
  155657. for(ii=0; ii<pRtree->nDim; ii++){
  155658. int jj;
  155659. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  155660. for(jj=0; jj<nCell; jj++){
  155661. aaSorted[ii][jj] = jj;
  155662. }
  155663. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  155664. }
  155665. for(ii=0; ii<pRtree->nDim; ii++){
  155666. RtreeDValue margin = RTREE_ZERO;
  155667. RtreeDValue fBestOverlap = RTREE_ZERO;
  155668. RtreeDValue fBestArea = RTREE_ZERO;
  155669. int iBestLeft = 0;
  155670. int nLeft;
  155671. for(
  155672. nLeft=RTREE_MINCELLS(pRtree);
  155673. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  155674. nLeft++
  155675. ){
  155676. RtreeCell left;
  155677. RtreeCell right;
  155678. int kk;
  155679. RtreeDValue overlap;
  155680. RtreeDValue area;
  155681. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  155682. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  155683. for(kk=1; kk<(nCell-1); kk++){
  155684. if( kk<nLeft ){
  155685. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  155686. }else{
  155687. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  155688. }
  155689. }
  155690. margin += cellMargin(pRtree, &left);
  155691. margin += cellMargin(pRtree, &right);
  155692. overlap = cellOverlap(pRtree, &left, &right, 1);
  155693. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  155694. if( (nLeft==RTREE_MINCELLS(pRtree))
  155695. || (overlap<fBestOverlap)
  155696. || (overlap==fBestOverlap && area<fBestArea)
  155697. ){
  155698. iBestLeft = nLeft;
  155699. fBestOverlap = overlap;
  155700. fBestArea = area;
  155701. }
  155702. }
  155703. if( ii==0 || margin<fBestMargin ){
  155704. iBestDim = ii;
  155705. fBestMargin = margin;
  155706. iBestSplit = iBestLeft;
  155707. }
  155708. }
  155709. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  155710. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  155711. for(ii=0; ii<nCell; ii++){
  155712. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  155713. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  155714. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  155715. nodeInsertCell(pRtree, pTarget, pCell);
  155716. cellUnion(pRtree, pBbox, pCell);
  155717. }
  155718. sqlite3_free(aaSorted);
  155719. return SQLITE_OK;
  155720. }
  155721. static int updateMapping(
  155722. Rtree *pRtree,
  155723. i64 iRowid,
  155724. RtreeNode *pNode,
  155725. int iHeight
  155726. ){
  155727. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  155728. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  155729. if( iHeight>0 ){
  155730. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  155731. if( pChild ){
  155732. nodeRelease(pRtree, pChild->pParent);
  155733. nodeReference(pNode);
  155734. pChild->pParent = pNode;
  155735. }
  155736. }
  155737. return xSetMapping(pRtree, iRowid, pNode->iNode);
  155738. }
  155739. static int SplitNode(
  155740. Rtree *pRtree,
  155741. RtreeNode *pNode,
  155742. RtreeCell *pCell,
  155743. int iHeight
  155744. ){
  155745. int i;
  155746. int newCellIsRight = 0;
  155747. int rc = SQLITE_OK;
  155748. int nCell = NCELL(pNode);
  155749. RtreeCell *aCell;
  155750. int *aiUsed;
  155751. RtreeNode *pLeft = 0;
  155752. RtreeNode *pRight = 0;
  155753. RtreeCell leftbbox;
  155754. RtreeCell rightbbox;
  155755. /* Allocate an array and populate it with a copy of pCell and
  155756. ** all cells from node pLeft. Then zero the original node.
  155757. */
  155758. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  155759. if( !aCell ){
  155760. rc = SQLITE_NOMEM;
  155761. goto splitnode_out;
  155762. }
  155763. aiUsed = (int *)&aCell[nCell+1];
  155764. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  155765. for(i=0; i<nCell; i++){
  155766. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  155767. }
  155768. nodeZero(pRtree, pNode);
  155769. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  155770. nCell++;
  155771. if( pNode->iNode==1 ){
  155772. pRight = nodeNew(pRtree, pNode);
  155773. pLeft = nodeNew(pRtree, pNode);
  155774. pRtree->iDepth++;
  155775. pNode->isDirty = 1;
  155776. writeInt16(pNode->zData, pRtree->iDepth);
  155777. }else{
  155778. pLeft = pNode;
  155779. pRight = nodeNew(pRtree, pLeft->pParent);
  155780. nodeReference(pLeft);
  155781. }
  155782. if( !pLeft || !pRight ){
  155783. rc = SQLITE_NOMEM;
  155784. goto splitnode_out;
  155785. }
  155786. memset(pLeft->zData, 0, pRtree->iNodeSize);
  155787. memset(pRight->zData, 0, pRtree->iNodeSize);
  155788. rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
  155789. &leftbbox, &rightbbox);
  155790. if( rc!=SQLITE_OK ){
  155791. goto splitnode_out;
  155792. }
  155793. /* Ensure both child nodes have node numbers assigned to them by calling
  155794. ** nodeWrite(). Node pRight always needs a node number, as it was created
  155795. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  155796. ** In this case avoid the all to nodeWrite().
  155797. */
  155798. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  155799. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  155800. ){
  155801. goto splitnode_out;
  155802. }
  155803. rightbbox.iRowid = pRight->iNode;
  155804. leftbbox.iRowid = pLeft->iNode;
  155805. if( pNode->iNode==1 ){
  155806. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  155807. if( rc!=SQLITE_OK ){
  155808. goto splitnode_out;
  155809. }
  155810. }else{
  155811. RtreeNode *pParent = pLeft->pParent;
  155812. int iCell;
  155813. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  155814. if( rc==SQLITE_OK ){
  155815. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  155816. rc = AdjustTree(pRtree, pParent, &leftbbox);
  155817. }
  155818. if( rc!=SQLITE_OK ){
  155819. goto splitnode_out;
  155820. }
  155821. }
  155822. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  155823. goto splitnode_out;
  155824. }
  155825. for(i=0; i<NCELL(pRight); i++){
  155826. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  155827. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  155828. if( iRowid==pCell->iRowid ){
  155829. newCellIsRight = 1;
  155830. }
  155831. if( rc!=SQLITE_OK ){
  155832. goto splitnode_out;
  155833. }
  155834. }
  155835. if( pNode->iNode==1 ){
  155836. for(i=0; i<NCELL(pLeft); i++){
  155837. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  155838. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  155839. if( rc!=SQLITE_OK ){
  155840. goto splitnode_out;
  155841. }
  155842. }
  155843. }else if( newCellIsRight==0 ){
  155844. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  155845. }
  155846. if( rc==SQLITE_OK ){
  155847. rc = nodeRelease(pRtree, pRight);
  155848. pRight = 0;
  155849. }
  155850. if( rc==SQLITE_OK ){
  155851. rc = nodeRelease(pRtree, pLeft);
  155852. pLeft = 0;
  155853. }
  155854. splitnode_out:
  155855. nodeRelease(pRtree, pRight);
  155856. nodeRelease(pRtree, pLeft);
  155857. sqlite3_free(aCell);
  155858. return rc;
  155859. }
  155860. /*
  155861. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  155862. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  155863. ** the pLeaf->pParent chain all the way up to the root node.
  155864. **
  155865. ** This operation is required when a row is deleted (or updated - an update
  155866. ** is implemented as a delete followed by an insert). SQLite provides the
  155867. ** rowid of the row to delete, which can be used to find the leaf on which
  155868. ** the entry resides (argument pLeaf). Once the leaf is located, this
  155869. ** function is called to determine its ancestry.
  155870. */
  155871. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  155872. int rc = SQLITE_OK;
  155873. RtreeNode *pChild = pLeaf;
  155874. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  155875. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  155876. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  155877. rc = sqlite3_step(pRtree->pReadParent);
  155878. if( rc==SQLITE_ROW ){
  155879. RtreeNode *pTest; /* Used to test for reference loops */
  155880. i64 iNode; /* Node number of parent node */
  155881. /* Before setting pChild->pParent, test that we are not creating a
  155882. ** loop of references (as we would if, say, pChild==pParent). We don't
  155883. ** want to do this as it leads to a memory leak when trying to delete
  155884. ** the referenced counted node structures.
  155885. */
  155886. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  155887. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  155888. if( !pTest ){
  155889. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  155890. }
  155891. }
  155892. rc = sqlite3_reset(pRtree->pReadParent);
  155893. if( rc==SQLITE_OK ) rc = rc2;
  155894. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  155895. pChild = pChild->pParent;
  155896. }
  155897. return rc;
  155898. }
  155899. static int deleteCell(Rtree *, RtreeNode *, int, int);
  155900. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  155901. int rc;
  155902. int rc2;
  155903. RtreeNode *pParent = 0;
  155904. int iCell;
  155905. assert( pNode->nRef==1 );
  155906. /* Remove the entry in the parent cell. */
  155907. rc = nodeParentIndex(pRtree, pNode, &iCell);
  155908. if( rc==SQLITE_OK ){
  155909. pParent = pNode->pParent;
  155910. pNode->pParent = 0;
  155911. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  155912. }
  155913. rc2 = nodeRelease(pRtree, pParent);
  155914. if( rc==SQLITE_OK ){
  155915. rc = rc2;
  155916. }
  155917. if( rc!=SQLITE_OK ){
  155918. return rc;
  155919. }
  155920. /* Remove the xxx_node entry. */
  155921. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  155922. sqlite3_step(pRtree->pDeleteNode);
  155923. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  155924. return rc;
  155925. }
  155926. /* Remove the xxx_parent entry. */
  155927. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  155928. sqlite3_step(pRtree->pDeleteParent);
  155929. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  155930. return rc;
  155931. }
  155932. /* Remove the node from the in-memory hash table and link it into
  155933. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  155934. */
  155935. nodeHashDelete(pRtree, pNode);
  155936. pNode->iNode = iHeight;
  155937. pNode->pNext = pRtree->pDeleted;
  155938. pNode->nRef++;
  155939. pRtree->pDeleted = pNode;
  155940. return SQLITE_OK;
  155941. }
  155942. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  155943. RtreeNode *pParent = pNode->pParent;
  155944. int rc = SQLITE_OK;
  155945. if( pParent ){
  155946. int ii;
  155947. int nCell = NCELL(pNode);
  155948. RtreeCell box; /* Bounding box for pNode */
  155949. nodeGetCell(pRtree, pNode, 0, &box);
  155950. for(ii=1; ii<nCell; ii++){
  155951. RtreeCell cell;
  155952. nodeGetCell(pRtree, pNode, ii, &cell);
  155953. cellUnion(pRtree, &box, &cell);
  155954. }
  155955. box.iRowid = pNode->iNode;
  155956. rc = nodeParentIndex(pRtree, pNode, &ii);
  155957. if( rc==SQLITE_OK ){
  155958. nodeOverwriteCell(pRtree, pParent, &box, ii);
  155959. rc = fixBoundingBox(pRtree, pParent);
  155960. }
  155961. }
  155962. return rc;
  155963. }
  155964. /*
  155965. ** Delete the cell at index iCell of node pNode. After removing the
  155966. ** cell, adjust the r-tree data structure if required.
  155967. */
  155968. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  155969. RtreeNode *pParent;
  155970. int rc;
  155971. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  155972. return rc;
  155973. }
  155974. /* Remove the cell from the node. This call just moves bytes around
  155975. ** the in-memory node image, so it cannot fail.
  155976. */
  155977. nodeDeleteCell(pRtree, pNode, iCell);
  155978. /* If the node is not the tree root and now has less than the minimum
  155979. ** number of cells, remove it from the tree. Otherwise, update the
  155980. ** cell in the parent node so that it tightly contains the updated
  155981. ** node.
  155982. */
  155983. pParent = pNode->pParent;
  155984. assert( pParent || pNode->iNode==1 );
  155985. if( pParent ){
  155986. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  155987. rc = removeNode(pRtree, pNode, iHeight);
  155988. }else{
  155989. rc = fixBoundingBox(pRtree, pNode);
  155990. }
  155991. }
  155992. return rc;
  155993. }
  155994. static int Reinsert(
  155995. Rtree *pRtree,
  155996. RtreeNode *pNode,
  155997. RtreeCell *pCell,
  155998. int iHeight
  155999. ){
  156000. int *aOrder;
  156001. int *aSpare;
  156002. RtreeCell *aCell;
  156003. RtreeDValue *aDistance;
  156004. int nCell;
  156005. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  156006. int iDim;
  156007. int ii;
  156008. int rc = SQLITE_OK;
  156009. int n;
  156010. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  156011. nCell = NCELL(pNode)+1;
  156012. n = (nCell+1)&(~1);
  156013. /* Allocate the buffers used by this operation. The allocation is
  156014. ** relinquished before this function returns.
  156015. */
  156016. aCell = (RtreeCell *)sqlite3_malloc(n * (
  156017. sizeof(RtreeCell) + /* aCell array */
  156018. sizeof(int) + /* aOrder array */
  156019. sizeof(int) + /* aSpare array */
  156020. sizeof(RtreeDValue) /* aDistance array */
  156021. ));
  156022. if( !aCell ){
  156023. return SQLITE_NOMEM;
  156024. }
  156025. aOrder = (int *)&aCell[n];
  156026. aSpare = (int *)&aOrder[n];
  156027. aDistance = (RtreeDValue *)&aSpare[n];
  156028. for(ii=0; ii<nCell; ii++){
  156029. if( ii==(nCell-1) ){
  156030. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  156031. }else{
  156032. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  156033. }
  156034. aOrder[ii] = ii;
  156035. for(iDim=0; iDim<pRtree->nDim; iDim++){
  156036. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  156037. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  156038. }
  156039. }
  156040. for(iDim=0; iDim<pRtree->nDim; iDim++){
  156041. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  156042. }
  156043. for(ii=0; ii<nCell; ii++){
  156044. aDistance[ii] = RTREE_ZERO;
  156045. for(iDim=0; iDim<pRtree->nDim; iDim++){
  156046. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  156047. DCOORD(aCell[ii].aCoord[iDim*2]));
  156048. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  156049. }
  156050. }
  156051. SortByDistance(aOrder, nCell, aDistance, aSpare);
  156052. nodeZero(pRtree, pNode);
  156053. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  156054. RtreeCell *p = &aCell[aOrder[ii]];
  156055. nodeInsertCell(pRtree, pNode, p);
  156056. if( p->iRowid==pCell->iRowid ){
  156057. if( iHeight==0 ){
  156058. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  156059. }else{
  156060. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  156061. }
  156062. }
  156063. }
  156064. if( rc==SQLITE_OK ){
  156065. rc = fixBoundingBox(pRtree, pNode);
  156066. }
  156067. for(; rc==SQLITE_OK && ii<nCell; ii++){
  156068. /* Find a node to store this cell in. pNode->iNode currently contains
  156069. ** the height of the sub-tree headed by the cell.
  156070. */
  156071. RtreeNode *pInsert;
  156072. RtreeCell *p = &aCell[aOrder[ii]];
  156073. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  156074. if( rc==SQLITE_OK ){
  156075. int rc2;
  156076. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  156077. rc2 = nodeRelease(pRtree, pInsert);
  156078. if( rc==SQLITE_OK ){
  156079. rc = rc2;
  156080. }
  156081. }
  156082. }
  156083. sqlite3_free(aCell);
  156084. return rc;
  156085. }
  156086. /*
  156087. ** Insert cell pCell into node pNode. Node pNode is the head of a
  156088. ** subtree iHeight high (leaf nodes have iHeight==0).
  156089. */
  156090. static int rtreeInsertCell(
  156091. Rtree *pRtree,
  156092. RtreeNode *pNode,
  156093. RtreeCell *pCell,
  156094. int iHeight
  156095. ){
  156096. int rc = SQLITE_OK;
  156097. if( iHeight>0 ){
  156098. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  156099. if( pChild ){
  156100. nodeRelease(pRtree, pChild->pParent);
  156101. nodeReference(pNode);
  156102. pChild->pParent = pNode;
  156103. }
  156104. }
  156105. if( nodeInsertCell(pRtree, pNode, pCell) ){
  156106. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  156107. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  156108. }else{
  156109. pRtree->iReinsertHeight = iHeight;
  156110. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  156111. }
  156112. }else{
  156113. rc = AdjustTree(pRtree, pNode, pCell);
  156114. if( rc==SQLITE_OK ){
  156115. if( iHeight==0 ){
  156116. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  156117. }else{
  156118. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  156119. }
  156120. }
  156121. }
  156122. return rc;
  156123. }
  156124. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  156125. int ii;
  156126. int rc = SQLITE_OK;
  156127. int nCell = NCELL(pNode);
  156128. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  156129. RtreeNode *pInsert;
  156130. RtreeCell cell;
  156131. nodeGetCell(pRtree, pNode, ii, &cell);
  156132. /* Find a node to store this cell in. pNode->iNode currently contains
  156133. ** the height of the sub-tree headed by the cell.
  156134. */
  156135. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  156136. if( rc==SQLITE_OK ){
  156137. int rc2;
  156138. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  156139. rc2 = nodeRelease(pRtree, pInsert);
  156140. if( rc==SQLITE_OK ){
  156141. rc = rc2;
  156142. }
  156143. }
  156144. }
  156145. return rc;
  156146. }
  156147. /*
  156148. ** Select a currently unused rowid for a new r-tree record.
  156149. */
  156150. static int newRowid(Rtree *pRtree, i64 *piRowid){
  156151. int rc;
  156152. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  156153. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  156154. sqlite3_step(pRtree->pWriteRowid);
  156155. rc = sqlite3_reset(pRtree->pWriteRowid);
  156156. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  156157. return rc;
  156158. }
  156159. /*
  156160. ** Remove the entry with rowid=iDelete from the r-tree structure.
  156161. */
  156162. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  156163. int rc; /* Return code */
  156164. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  156165. int iCell; /* Index of iDelete cell in pLeaf */
  156166. RtreeNode *pRoot; /* Root node of rtree structure */
  156167. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  156168. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  156169. /* Obtain a reference to the leaf node that contains the entry
  156170. ** about to be deleted.
  156171. */
  156172. if( rc==SQLITE_OK ){
  156173. rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
  156174. }
  156175. /* Delete the cell in question from the leaf node. */
  156176. if( rc==SQLITE_OK ){
  156177. int rc2;
  156178. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  156179. if( rc==SQLITE_OK ){
  156180. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  156181. }
  156182. rc2 = nodeRelease(pRtree, pLeaf);
  156183. if( rc==SQLITE_OK ){
  156184. rc = rc2;
  156185. }
  156186. }
  156187. /* Delete the corresponding entry in the <rtree>_rowid table. */
  156188. if( rc==SQLITE_OK ){
  156189. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  156190. sqlite3_step(pRtree->pDeleteRowid);
  156191. rc = sqlite3_reset(pRtree->pDeleteRowid);
  156192. }
  156193. /* Check if the root node now has exactly one child. If so, remove
  156194. ** it, schedule the contents of the child for reinsertion and
  156195. ** reduce the tree height by one.
  156196. **
  156197. ** This is equivalent to copying the contents of the child into
  156198. ** the root node (the operation that Gutman's paper says to perform
  156199. ** in this scenario).
  156200. */
  156201. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  156202. int rc2;
  156203. RtreeNode *pChild;
  156204. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  156205. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  156206. if( rc==SQLITE_OK ){
  156207. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  156208. }
  156209. rc2 = nodeRelease(pRtree, pChild);
  156210. if( rc==SQLITE_OK ) rc = rc2;
  156211. if( rc==SQLITE_OK ){
  156212. pRtree->iDepth--;
  156213. writeInt16(pRoot->zData, pRtree->iDepth);
  156214. pRoot->isDirty = 1;
  156215. }
  156216. }
  156217. /* Re-insert the contents of any underfull nodes removed from the tree. */
  156218. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  156219. if( rc==SQLITE_OK ){
  156220. rc = reinsertNodeContent(pRtree, pLeaf);
  156221. }
  156222. pRtree->pDeleted = pLeaf->pNext;
  156223. sqlite3_free(pLeaf);
  156224. }
  156225. /* Release the reference to the root node. */
  156226. if( rc==SQLITE_OK ){
  156227. rc = nodeRelease(pRtree, pRoot);
  156228. }else{
  156229. nodeRelease(pRtree, pRoot);
  156230. }
  156231. return rc;
  156232. }
  156233. /*
  156234. ** Rounding constants for float->double conversion.
  156235. */
  156236. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  156237. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  156238. #if !defined(SQLITE_RTREE_INT_ONLY)
  156239. /*
  156240. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  156241. ** while taking care to round toward negative or positive, respectively.
  156242. */
  156243. static RtreeValue rtreeValueDown(sqlite3_value *v){
  156244. double d = sqlite3_value_double(v);
  156245. float f = (float)d;
  156246. if( f>d ){
  156247. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  156248. }
  156249. return f;
  156250. }
  156251. static RtreeValue rtreeValueUp(sqlite3_value *v){
  156252. double d = sqlite3_value_double(v);
  156253. float f = (float)d;
  156254. if( f<d ){
  156255. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  156256. }
  156257. return f;
  156258. }
  156259. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  156260. /*
  156261. ** A constraint has failed while inserting a row into an rtree table.
  156262. ** Assuming no OOM error occurs, this function sets the error message
  156263. ** (at pRtree->base.zErrMsg) to an appropriate value and returns
  156264. ** SQLITE_CONSTRAINT.
  156265. **
  156266. ** Parameter iCol is the index of the leftmost column involved in the
  156267. ** constraint failure. If it is 0, then the constraint that failed is
  156268. ** the unique constraint on the id column. Otherwise, it is the rtree
  156269. ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
  156270. **
  156271. ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
  156272. */
  156273. static int rtreeConstraintError(Rtree *pRtree, int iCol){
  156274. sqlite3_stmt *pStmt = 0;
  156275. char *zSql;
  156276. int rc;
  156277. assert( iCol==0 || iCol%2 );
  156278. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
  156279. if( zSql ){
  156280. rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
  156281. }else{
  156282. rc = SQLITE_NOMEM;
  156283. }
  156284. sqlite3_free(zSql);
  156285. if( rc==SQLITE_OK ){
  156286. if( iCol==0 ){
  156287. const char *zCol = sqlite3_column_name(pStmt, 0);
  156288. pRtree->base.zErrMsg = sqlite3_mprintf(
  156289. "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
  156290. );
  156291. }else{
  156292. const char *zCol1 = sqlite3_column_name(pStmt, iCol);
  156293. const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
  156294. pRtree->base.zErrMsg = sqlite3_mprintf(
  156295. "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
  156296. );
  156297. }
  156298. }
  156299. sqlite3_finalize(pStmt);
  156300. return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
  156301. }
  156302. /*
  156303. ** The xUpdate method for rtree module virtual tables.
  156304. */
  156305. static int rtreeUpdate(
  156306. sqlite3_vtab *pVtab,
  156307. int nData,
  156308. sqlite3_value **azData,
  156309. sqlite_int64 *pRowid
  156310. ){
  156311. Rtree *pRtree = (Rtree *)pVtab;
  156312. int rc = SQLITE_OK;
  156313. RtreeCell cell; /* New cell to insert if nData>1 */
  156314. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  156315. rtreeReference(pRtree);
  156316. assert(nData>=1);
  156317. cell.iRowid = 0; /* Used only to suppress a compiler warning */
  156318. /* Constraint handling. A write operation on an r-tree table may return
  156319. ** SQLITE_CONSTRAINT for two reasons:
  156320. **
  156321. ** 1. A duplicate rowid value, or
  156322. ** 2. The supplied data violates the "x2>=x1" constraint.
  156323. **
  156324. ** In the first case, if the conflict-handling mode is REPLACE, then
  156325. ** the conflicting row can be removed before proceeding. In the second
  156326. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  156327. ** conflict-handling mode specified by the user.
  156328. */
  156329. if( nData>1 ){
  156330. int ii;
  156331. /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
  156332. **
  156333. ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
  156334. ** with "column" that are interpreted as table constraints.
  156335. ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
  156336. ** This problem was discovered after years of use, so we silently ignore
  156337. ** these kinds of misdeclared tables to avoid breaking any legacy.
  156338. */
  156339. assert( nData<=(pRtree->nDim2 + 3) );
  156340. #ifndef SQLITE_RTREE_INT_ONLY
  156341. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  156342. for(ii=0; ii<nData-4; ii+=2){
  156343. cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
  156344. cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
  156345. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  156346. rc = rtreeConstraintError(pRtree, ii+1);
  156347. goto constraint;
  156348. }
  156349. }
  156350. }else
  156351. #endif
  156352. {
  156353. for(ii=0; ii<nData-4; ii+=2){
  156354. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  156355. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  156356. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  156357. rc = rtreeConstraintError(pRtree, ii+1);
  156358. goto constraint;
  156359. }
  156360. }
  156361. }
  156362. /* If a rowid value was supplied, check if it is already present in
  156363. ** the table. If so, the constraint has failed. */
  156364. if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
  156365. cell.iRowid = sqlite3_value_int64(azData[2]);
  156366. if( sqlite3_value_type(azData[0])==SQLITE_NULL
  156367. || sqlite3_value_int64(azData[0])!=cell.iRowid
  156368. ){
  156369. int steprc;
  156370. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  156371. steprc = sqlite3_step(pRtree->pReadRowid);
  156372. rc = sqlite3_reset(pRtree->pReadRowid);
  156373. if( SQLITE_ROW==steprc ){
  156374. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  156375. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  156376. }else{
  156377. rc = rtreeConstraintError(pRtree, 0);
  156378. goto constraint;
  156379. }
  156380. }
  156381. }
  156382. bHaveRowid = 1;
  156383. }
  156384. }
  156385. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  156386. ** record to delete from the r-tree table. The following block does
  156387. ** just that.
  156388. */
  156389. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  156390. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
  156391. }
  156392. /* If the azData[] array contains more than one element, elements
  156393. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  156394. ** the r-tree structure.
  156395. */
  156396. if( rc==SQLITE_OK && nData>1 ){
  156397. /* Insert the new record into the r-tree */
  156398. RtreeNode *pLeaf = 0;
  156399. /* Figure out the rowid of the new row. */
  156400. if( bHaveRowid==0 ){
  156401. rc = newRowid(pRtree, &cell.iRowid);
  156402. }
  156403. *pRowid = cell.iRowid;
  156404. if( rc==SQLITE_OK ){
  156405. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  156406. }
  156407. if( rc==SQLITE_OK ){
  156408. int rc2;
  156409. pRtree->iReinsertHeight = -1;
  156410. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  156411. rc2 = nodeRelease(pRtree, pLeaf);
  156412. if( rc==SQLITE_OK ){
  156413. rc = rc2;
  156414. }
  156415. }
  156416. }
  156417. constraint:
  156418. rtreeRelease(pRtree);
  156419. return rc;
  156420. }
  156421. /*
  156422. ** Called when a transaction starts.
  156423. */
  156424. static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
  156425. Rtree *pRtree = (Rtree *)pVtab;
  156426. assert( pRtree->inWrTrans==0 );
  156427. pRtree->inWrTrans++;
  156428. return SQLITE_OK;
  156429. }
  156430. /*
  156431. ** Called when a transaction completes (either by COMMIT or ROLLBACK).
  156432. ** The sqlite3_blob object should be released at this point.
  156433. */
  156434. static int rtreeEndTransaction(sqlite3_vtab *pVtab){
  156435. Rtree *pRtree = (Rtree *)pVtab;
  156436. pRtree->inWrTrans = 0;
  156437. nodeBlobReset(pRtree);
  156438. return SQLITE_OK;
  156439. }
  156440. /*
  156441. ** The xRename method for rtree module virtual tables.
  156442. */
  156443. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  156444. Rtree *pRtree = (Rtree *)pVtab;
  156445. int rc = SQLITE_NOMEM;
  156446. char *zSql = sqlite3_mprintf(
  156447. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  156448. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  156449. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  156450. , pRtree->zDb, pRtree->zName, zNewName
  156451. , pRtree->zDb, pRtree->zName, zNewName
  156452. , pRtree->zDb, pRtree->zName, zNewName
  156453. );
  156454. if( zSql ){
  156455. nodeBlobReset(pRtree);
  156456. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  156457. sqlite3_free(zSql);
  156458. }
  156459. return rc;
  156460. }
  156461. /*
  156462. ** The xSavepoint method.
  156463. **
  156464. ** This module does not need to do anything to support savepoints. However,
  156465. ** it uses this hook to close any open blob handle. This is done because a
  156466. ** DROP TABLE command - which fortunately always opens a savepoint - cannot
  156467. ** succeed if there are any open blob handles. i.e. if the blob handle were
  156468. ** not closed here, the following would fail:
  156469. **
  156470. ** BEGIN;
  156471. ** INSERT INTO rtree...
  156472. ** DROP TABLE <tablename>; -- Would fail with SQLITE_LOCKED
  156473. ** COMMIT;
  156474. */
  156475. static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
  156476. Rtree *pRtree = (Rtree *)pVtab;
  156477. int iwt = pRtree->inWrTrans;
  156478. UNUSED_PARAMETER(iSavepoint);
  156479. pRtree->inWrTrans = 0;
  156480. nodeBlobReset(pRtree);
  156481. pRtree->inWrTrans = iwt;
  156482. return SQLITE_OK;
  156483. }
  156484. /*
  156485. ** This function populates the pRtree->nRowEst variable with an estimate
  156486. ** of the number of rows in the virtual table. If possible, this is based
  156487. ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
  156488. */
  156489. static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
  156490. const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
  156491. char *zSql;
  156492. sqlite3_stmt *p;
  156493. int rc;
  156494. i64 nRow = 0;
  156495. rc = sqlite3_table_column_metadata(
  156496. db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
  156497. );
  156498. if( rc!=SQLITE_OK ){
  156499. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  156500. return rc==SQLITE_ERROR ? SQLITE_OK : rc;
  156501. }
  156502. zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
  156503. if( zSql==0 ){
  156504. rc = SQLITE_NOMEM;
  156505. }else{
  156506. rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
  156507. if( rc==SQLITE_OK ){
  156508. if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
  156509. rc = sqlite3_finalize(p);
  156510. }else if( rc!=SQLITE_NOMEM ){
  156511. rc = SQLITE_OK;
  156512. }
  156513. if( rc==SQLITE_OK ){
  156514. if( nRow==0 ){
  156515. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  156516. }else{
  156517. pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
  156518. }
  156519. }
  156520. sqlite3_free(zSql);
  156521. }
  156522. return rc;
  156523. }
  156524. static sqlite3_module rtreeModule = {
  156525. 2, /* iVersion */
  156526. rtreeCreate, /* xCreate - create a table */
  156527. rtreeConnect, /* xConnect - connect to an existing table */
  156528. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  156529. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  156530. rtreeDestroy, /* xDestroy - Drop a table */
  156531. rtreeOpen, /* xOpen - open a cursor */
  156532. rtreeClose, /* xClose - close a cursor */
  156533. rtreeFilter, /* xFilter - configure scan constraints */
  156534. rtreeNext, /* xNext - advance a cursor */
  156535. rtreeEof, /* xEof */
  156536. rtreeColumn, /* xColumn - read data */
  156537. rtreeRowid, /* xRowid - read data */
  156538. rtreeUpdate, /* xUpdate - write data */
  156539. rtreeBeginTransaction, /* xBegin - begin transaction */
  156540. rtreeEndTransaction, /* xSync - sync transaction */
  156541. rtreeEndTransaction, /* xCommit - commit transaction */
  156542. rtreeEndTransaction, /* xRollback - rollback transaction */
  156543. 0, /* xFindFunction - function overloading */
  156544. rtreeRename, /* xRename - rename the table */
  156545. rtreeSavepoint, /* xSavepoint */
  156546. 0, /* xRelease */
  156547. 0, /* xRollbackTo */
  156548. };
  156549. static int rtreeSqlInit(
  156550. Rtree *pRtree,
  156551. sqlite3 *db,
  156552. const char *zDb,
  156553. const char *zPrefix,
  156554. int isCreate
  156555. ){
  156556. int rc = SQLITE_OK;
  156557. #define N_STATEMENT 8
  156558. static const char *azSql[N_STATEMENT] = {
  156559. /* Write the xxx_node table */
  156560. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  156561. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  156562. /* Read and write the xxx_rowid table */
  156563. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  156564. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  156565. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  156566. /* Read and write the xxx_parent table */
  156567. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  156568. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  156569. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  156570. };
  156571. sqlite3_stmt **appStmt[N_STATEMENT];
  156572. int i;
  156573. pRtree->db = db;
  156574. if( isCreate ){
  156575. char *zCreate = sqlite3_mprintf(
  156576. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  156577. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  156578. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
  156579. " parentnode INTEGER);"
  156580. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  156581. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  156582. );
  156583. if( !zCreate ){
  156584. return SQLITE_NOMEM;
  156585. }
  156586. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  156587. sqlite3_free(zCreate);
  156588. if( rc!=SQLITE_OK ){
  156589. return rc;
  156590. }
  156591. }
  156592. appStmt[0] = &pRtree->pWriteNode;
  156593. appStmt[1] = &pRtree->pDeleteNode;
  156594. appStmt[2] = &pRtree->pReadRowid;
  156595. appStmt[3] = &pRtree->pWriteRowid;
  156596. appStmt[4] = &pRtree->pDeleteRowid;
  156597. appStmt[5] = &pRtree->pReadParent;
  156598. appStmt[6] = &pRtree->pWriteParent;
  156599. appStmt[7] = &pRtree->pDeleteParent;
  156600. rc = rtreeQueryStat1(db, pRtree);
  156601. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  156602. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  156603. if( zSql ){
  156604. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  156605. }else{
  156606. rc = SQLITE_NOMEM;
  156607. }
  156608. sqlite3_free(zSql);
  156609. }
  156610. return rc;
  156611. }
  156612. /*
  156613. ** The second argument to this function contains the text of an SQL statement
  156614. ** that returns a single integer value. The statement is compiled and executed
  156615. ** using database connection db. If successful, the integer value returned
  156616. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  156617. ** code is returned and the value of *piVal after returning is not defined.
  156618. */
  156619. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  156620. int rc = SQLITE_NOMEM;
  156621. if( zSql ){
  156622. sqlite3_stmt *pStmt = 0;
  156623. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  156624. if( rc==SQLITE_OK ){
  156625. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  156626. *piVal = sqlite3_column_int(pStmt, 0);
  156627. }
  156628. rc = sqlite3_finalize(pStmt);
  156629. }
  156630. }
  156631. return rc;
  156632. }
  156633. /*
  156634. ** This function is called from within the xConnect() or xCreate() method to
  156635. ** determine the node-size used by the rtree table being created or connected
  156636. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  156637. ** Otherwise, an SQLite error code is returned.
  156638. **
  156639. ** If this function is being called as part of an xConnect(), then the rtree
  156640. ** table already exists. In this case the node-size is determined by inspecting
  156641. ** the root node of the tree.
  156642. **
  156643. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  156644. ** This ensures that each node is stored on a single database page. If the
  156645. ** database page-size is so large that more than RTREE_MAXCELLS entries
  156646. ** would fit in a single node, use a smaller node-size.
  156647. */
  156648. static int getNodeSize(
  156649. sqlite3 *db, /* Database handle */
  156650. Rtree *pRtree, /* Rtree handle */
  156651. int isCreate, /* True for xCreate, false for xConnect */
  156652. char **pzErr /* OUT: Error message, if any */
  156653. ){
  156654. int rc;
  156655. char *zSql;
  156656. if( isCreate ){
  156657. int iPageSize = 0;
  156658. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  156659. rc = getIntFromStmt(db, zSql, &iPageSize);
  156660. if( rc==SQLITE_OK ){
  156661. pRtree->iNodeSize = iPageSize-64;
  156662. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  156663. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  156664. }
  156665. }else{
  156666. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  156667. }
  156668. }else{
  156669. zSql = sqlite3_mprintf(
  156670. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  156671. pRtree->zDb, pRtree->zName
  156672. );
  156673. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  156674. if( rc!=SQLITE_OK ){
  156675. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  156676. }
  156677. }
  156678. sqlite3_free(zSql);
  156679. return rc;
  156680. }
  156681. /*
  156682. ** This function is the implementation of both the xConnect and xCreate
  156683. ** methods of the r-tree virtual table.
  156684. **
  156685. ** argv[0] -> module name
  156686. ** argv[1] -> database name
  156687. ** argv[2] -> table name
  156688. ** argv[...] -> column names...
  156689. */
  156690. static int rtreeInit(
  156691. sqlite3 *db, /* Database connection */
  156692. void *pAux, /* One of the RTREE_COORD_* constants */
  156693. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  156694. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  156695. char **pzErr, /* OUT: Error message, if any */
  156696. int isCreate /* True for xCreate, false for xConnect */
  156697. ){
  156698. int rc = SQLITE_OK;
  156699. Rtree *pRtree;
  156700. int nDb; /* Length of string argv[1] */
  156701. int nName; /* Length of string argv[2] */
  156702. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  156703. const char *aErrMsg[] = {
  156704. 0, /* 0 */
  156705. "Wrong number of columns for an rtree table", /* 1 */
  156706. "Too few columns for an rtree table", /* 2 */
  156707. "Too many columns for an rtree table" /* 3 */
  156708. };
  156709. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  156710. if( aErrMsg[iErr] ){
  156711. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  156712. return SQLITE_ERROR;
  156713. }
  156714. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  156715. /* Allocate the sqlite3_vtab structure */
  156716. nDb = (int)strlen(argv[1]);
  156717. nName = (int)strlen(argv[2]);
  156718. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  156719. if( !pRtree ){
  156720. return SQLITE_NOMEM;
  156721. }
  156722. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  156723. pRtree->nBusy = 1;
  156724. pRtree->base.pModule = &rtreeModule;
  156725. pRtree->zDb = (char *)&pRtree[1];
  156726. pRtree->zName = &pRtree->zDb[nDb+1];
  156727. pRtree->nDim = (u8)((argc-4)/2);
  156728. pRtree->nDim2 = pRtree->nDim*2;
  156729. pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
  156730. pRtree->eCoordType = (u8)eCoordType;
  156731. memcpy(pRtree->zDb, argv[1], nDb);
  156732. memcpy(pRtree->zName, argv[2], nName);
  156733. /* Figure out the node size to use. */
  156734. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  156735. /* Create/Connect to the underlying relational database schema. If
  156736. ** that is successful, call sqlite3_declare_vtab() to configure
  156737. ** the r-tree table schema.
  156738. */
  156739. if( rc==SQLITE_OK ){
  156740. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  156741. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  156742. }else{
  156743. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  156744. char *zTmp;
  156745. int ii;
  156746. for(ii=4; zSql && ii<argc; ii++){
  156747. zTmp = zSql;
  156748. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  156749. sqlite3_free(zTmp);
  156750. }
  156751. if( zSql ){
  156752. zTmp = zSql;
  156753. zSql = sqlite3_mprintf("%s);", zTmp);
  156754. sqlite3_free(zTmp);
  156755. }
  156756. if( !zSql ){
  156757. rc = SQLITE_NOMEM;
  156758. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  156759. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  156760. }
  156761. sqlite3_free(zSql);
  156762. }
  156763. }
  156764. if( rc==SQLITE_OK ){
  156765. *ppVtab = (sqlite3_vtab *)pRtree;
  156766. }else{
  156767. assert( *ppVtab==0 );
  156768. assert( pRtree->nBusy==1 );
  156769. rtreeRelease(pRtree);
  156770. }
  156771. return rc;
  156772. }
  156773. /*
  156774. ** Implementation of a scalar function that decodes r-tree nodes to
  156775. ** human readable strings. This can be used for debugging and analysis.
  156776. **
  156777. ** The scalar function takes two arguments: (1) the number of dimensions
  156778. ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
  156779. ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
  156780. ** deserialize all nodes, a statement like:
  156781. **
  156782. ** SELECT rtreenode(2, data) FROM rt_node;
  156783. **
  156784. ** The human readable string takes the form of a Tcl list with one
  156785. ** entry for each cell in the r-tree node. Each entry is itself a
  156786. ** list, containing the 8-byte rowid/pageno followed by the
  156787. ** <num-dimension>*2 coordinates.
  156788. */
  156789. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  156790. char *zText = 0;
  156791. RtreeNode node;
  156792. Rtree tree;
  156793. int ii;
  156794. UNUSED_PARAMETER(nArg);
  156795. memset(&node, 0, sizeof(RtreeNode));
  156796. memset(&tree, 0, sizeof(Rtree));
  156797. tree.nDim = (u8)sqlite3_value_int(apArg[0]);
  156798. tree.nDim2 = tree.nDim*2;
  156799. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  156800. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  156801. for(ii=0; ii<NCELL(&node); ii++){
  156802. char zCell[512];
  156803. int nCell = 0;
  156804. RtreeCell cell;
  156805. int jj;
  156806. nodeGetCell(&tree, &node, ii, &cell);
  156807. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  156808. nCell = (int)strlen(zCell);
  156809. for(jj=0; jj<tree.nDim2; jj++){
  156810. #ifndef SQLITE_RTREE_INT_ONLY
  156811. sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
  156812. (double)cell.aCoord[jj].f);
  156813. #else
  156814. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  156815. cell.aCoord[jj].i);
  156816. #endif
  156817. nCell = (int)strlen(zCell);
  156818. }
  156819. if( zText ){
  156820. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  156821. sqlite3_free(zText);
  156822. zText = zTextNew;
  156823. }else{
  156824. zText = sqlite3_mprintf("{%s}", zCell);
  156825. }
  156826. }
  156827. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  156828. }
  156829. /* This routine implements an SQL function that returns the "depth" parameter
  156830. ** from the front of a blob that is an r-tree node. For example:
  156831. **
  156832. ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
  156833. **
  156834. ** The depth value is 0 for all nodes other than the root node, and the root
  156835. ** node always has nodeno=1, so the example above is the primary use for this
  156836. ** routine. This routine is intended for testing and analysis only.
  156837. */
  156838. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  156839. UNUSED_PARAMETER(nArg);
  156840. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  156841. || sqlite3_value_bytes(apArg[0])<2
  156842. ){
  156843. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  156844. }else{
  156845. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  156846. sqlite3_result_int(ctx, readInt16(zBlob));
  156847. }
  156848. }
  156849. /*
  156850. ** Register the r-tree module with database handle db. This creates the
  156851. ** virtual table module "rtree" and the debugging/analysis scalar
  156852. ** function "rtreenode".
  156853. */
  156854. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  156855. const int utf8 = SQLITE_UTF8;
  156856. int rc;
  156857. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  156858. if( rc==SQLITE_OK ){
  156859. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  156860. }
  156861. if( rc==SQLITE_OK ){
  156862. #ifdef SQLITE_RTREE_INT_ONLY
  156863. void *c = (void *)RTREE_COORD_INT32;
  156864. #else
  156865. void *c = (void *)RTREE_COORD_REAL32;
  156866. #endif
  156867. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  156868. }
  156869. if( rc==SQLITE_OK ){
  156870. void *c = (void *)RTREE_COORD_INT32;
  156871. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  156872. }
  156873. return rc;
  156874. }
  156875. /*
  156876. ** This routine deletes the RtreeGeomCallback object that was attached
  156877. ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
  156878. ** or sqlite3_rtree_query_callback(). In other words, this routine is the
  156879. ** destructor for an RtreeGeomCallback objecct. This routine is called when
  156880. ** the corresponding SQL function is deleted.
  156881. */
  156882. static void rtreeFreeCallback(void *p){
  156883. RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
  156884. if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
  156885. sqlite3_free(p);
  156886. }
  156887. /*
  156888. ** This routine frees the BLOB that is returned by geomCallback().
  156889. */
  156890. static void rtreeMatchArgFree(void *pArg){
  156891. int i;
  156892. RtreeMatchArg *p = (RtreeMatchArg*)pArg;
  156893. for(i=0; i<p->nParam; i++){
  156894. sqlite3_value_free(p->apSqlParam[i]);
  156895. }
  156896. sqlite3_free(p);
  156897. }
  156898. /*
  156899. ** Each call to sqlite3_rtree_geometry_callback() or
  156900. ** sqlite3_rtree_query_callback() creates an ordinary SQLite
  156901. ** scalar function that is implemented by this routine.
  156902. **
  156903. ** All this function does is construct an RtreeMatchArg object that
  156904. ** contains the geometry-checking callback routines and a list of
  156905. ** parameters to this function, then return that RtreeMatchArg object
  156906. ** as a BLOB.
  156907. **
  156908. ** The R-Tree MATCH operator will read the returned BLOB, deserialize
  156909. ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
  156910. ** out which elements of the R-Tree should be returned by the query.
  156911. */
  156912. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  156913. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  156914. RtreeMatchArg *pBlob;
  156915. int nBlob;
  156916. int memErr = 0;
  156917. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
  156918. + nArg*sizeof(sqlite3_value*);
  156919. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  156920. if( !pBlob ){
  156921. sqlite3_result_error_nomem(ctx);
  156922. }else{
  156923. int i;
  156924. pBlob->magic = RTREE_GEOMETRY_MAGIC;
  156925. pBlob->cb = pGeomCtx[0];
  156926. pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
  156927. pBlob->nParam = nArg;
  156928. for(i=0; i<nArg; i++){
  156929. pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
  156930. if( pBlob->apSqlParam[i]==0 ) memErr = 1;
  156931. #ifdef SQLITE_RTREE_INT_ONLY
  156932. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  156933. #else
  156934. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  156935. #endif
  156936. }
  156937. if( memErr ){
  156938. sqlite3_result_error_nomem(ctx);
  156939. rtreeMatchArgFree(pBlob);
  156940. }else{
  156941. sqlite3_result_blob(ctx, pBlob, nBlob, rtreeMatchArgFree);
  156942. }
  156943. }
  156944. }
  156945. /*
  156946. ** Register a new geometry function for use with the r-tree MATCH operator.
  156947. */
  156948. SQLITE_API int sqlite3_rtree_geometry_callback(
  156949. sqlite3 *db, /* Register SQL function on this connection */
  156950. const char *zGeom, /* Name of the new SQL function */
  156951. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
  156952. void *pContext /* Extra data associated with the callback */
  156953. ){
  156954. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  156955. /* Allocate and populate the context object. */
  156956. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  156957. if( !pGeomCtx ) return SQLITE_NOMEM;
  156958. pGeomCtx->xGeom = xGeom;
  156959. pGeomCtx->xQueryFunc = 0;
  156960. pGeomCtx->xDestructor = 0;
  156961. pGeomCtx->pContext = pContext;
  156962. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  156963. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  156964. );
  156965. }
  156966. /*
  156967. ** Register a new 2nd-generation geometry function for use with the
  156968. ** r-tree MATCH operator.
  156969. */
  156970. SQLITE_API int sqlite3_rtree_query_callback(
  156971. sqlite3 *db, /* Register SQL function on this connection */
  156972. const char *zQueryFunc, /* Name of new SQL function */
  156973. int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
  156974. void *pContext, /* Extra data passed into the callback */
  156975. void (*xDestructor)(void*) /* Destructor for the extra data */
  156976. ){
  156977. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  156978. /* Allocate and populate the context object. */
  156979. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  156980. if( !pGeomCtx ) return SQLITE_NOMEM;
  156981. pGeomCtx->xGeom = 0;
  156982. pGeomCtx->xQueryFunc = xQueryFunc;
  156983. pGeomCtx->xDestructor = xDestructor;
  156984. pGeomCtx->pContext = pContext;
  156985. return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
  156986. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  156987. );
  156988. }
  156989. #if !SQLITE_CORE
  156990. #ifdef _WIN32
  156991. __declspec(dllexport)
  156992. #endif
  156993. SQLITE_API int sqlite3_rtree_init(
  156994. sqlite3 *db,
  156995. char **pzErrMsg,
  156996. const sqlite3_api_routines *pApi
  156997. ){
  156998. SQLITE_EXTENSION_INIT2(pApi)
  156999. return sqlite3RtreeInit(db);
  157000. }
  157001. #endif
  157002. #endif
  157003. /************** End of rtree.c ***********************************************/
  157004. /************** Begin file icu.c *********************************************/
  157005. /*
  157006. ** 2007 May 6
  157007. **
  157008. ** The author disclaims copyright to this source code. In place of
  157009. ** a legal notice, here is a blessing:
  157010. **
  157011. ** May you do good and not evil.
  157012. ** May you find forgiveness for yourself and forgive others.
  157013. ** May you share freely, never taking more than you give.
  157014. **
  157015. *************************************************************************
  157016. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  157017. **
  157018. ** This file implements an integration between the ICU library
  157019. ** ("International Components for Unicode", an open-source library
  157020. ** for handling unicode data) and SQLite. The integration uses
  157021. ** ICU to provide the following to SQLite:
  157022. **
  157023. ** * An implementation of the SQL regexp() function (and hence REGEXP
  157024. ** operator) using the ICU uregex_XX() APIs.
  157025. **
  157026. ** * Implementations of the SQL scalar upper() and lower() functions
  157027. ** for case mapping.
  157028. **
  157029. ** * Integration of ICU and SQLite collation sequences.
  157030. **
  157031. ** * An implementation of the LIKE operator that uses ICU to
  157032. ** provide case-independent matching.
  157033. */
  157034. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  157035. /* Include ICU headers */
  157036. #include <unicode/utypes.h>
  157037. #include <unicode/uregex.h>
  157038. #include <unicode/ustring.h>
  157039. #include <unicode/ucol.h>
  157040. /* #include <assert.h> */
  157041. #ifndef SQLITE_CORE
  157042. /* #include "sqlite3ext.h" */
  157043. SQLITE_EXTENSION_INIT1
  157044. #else
  157045. /* #include "sqlite3.h" */
  157046. #endif
  157047. /*
  157048. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  157049. ** operator.
  157050. */
  157051. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  157052. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  157053. #endif
  157054. /*
  157055. ** Version of sqlite3_free() that is always a function, never a macro.
  157056. */
  157057. static void xFree(void *p){
  157058. sqlite3_free(p);
  157059. }
  157060. /*
  157061. ** This lookup table is used to help decode the first byte of
  157062. ** a multi-byte UTF8 character. It is copied here from SQLite source
  157063. ** code file utf8.c.
  157064. */
  157065. static const unsigned char icuUtf8Trans1[] = {
  157066. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  157067. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  157068. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  157069. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  157070. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  157071. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  157072. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  157073. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  157074. };
  157075. #define SQLITE_ICU_READ_UTF8(zIn, c) \
  157076. c = *(zIn++); \
  157077. if( c>=0xc0 ){ \
  157078. c = icuUtf8Trans1[c-0xc0]; \
  157079. while( (*zIn & 0xc0)==0x80 ){ \
  157080. c = (c<<6) + (0x3f & *(zIn++)); \
  157081. } \
  157082. }
  157083. #define SQLITE_ICU_SKIP_UTF8(zIn) \
  157084. assert( *zIn ); \
  157085. if( *(zIn++)>=0xc0 ){ \
  157086. while( (*zIn & 0xc0)==0x80 ){zIn++;} \
  157087. }
  157088. /*
  157089. ** Compare two UTF-8 strings for equality where the first string is
  157090. ** a "LIKE" expression. Return true (1) if they are the same and
  157091. ** false (0) if they are different.
  157092. */
  157093. static int icuLikeCompare(
  157094. const uint8_t *zPattern, /* LIKE pattern */
  157095. const uint8_t *zString, /* The UTF-8 string to compare against */
  157096. const UChar32 uEsc /* The escape character */
  157097. ){
  157098. static const int MATCH_ONE = (UChar32)'_';
  157099. static const int MATCH_ALL = (UChar32)'%';
  157100. int prevEscape = 0; /* True if the previous character was uEsc */
  157101. while( 1 ){
  157102. /* Read (and consume) the next character from the input pattern. */
  157103. UChar32 uPattern;
  157104. SQLITE_ICU_READ_UTF8(zPattern, uPattern);
  157105. if( uPattern==0 ) break;
  157106. /* There are now 4 possibilities:
  157107. **
  157108. ** 1. uPattern is an unescaped match-all character "%",
  157109. ** 2. uPattern is an unescaped match-one character "_",
  157110. ** 3. uPattern is an unescaped escape character, or
  157111. ** 4. uPattern is to be handled as an ordinary character
  157112. */
  157113. if( !prevEscape && uPattern==MATCH_ALL ){
  157114. /* Case 1. */
  157115. uint8_t c;
  157116. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  157117. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  157118. ** test string.
  157119. */
  157120. while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
  157121. if( c==MATCH_ONE ){
  157122. if( *zString==0 ) return 0;
  157123. SQLITE_ICU_SKIP_UTF8(zString);
  157124. }
  157125. zPattern++;
  157126. }
  157127. if( *zPattern==0 ) return 1;
  157128. while( *zString ){
  157129. if( icuLikeCompare(zPattern, zString, uEsc) ){
  157130. return 1;
  157131. }
  157132. SQLITE_ICU_SKIP_UTF8(zString);
  157133. }
  157134. return 0;
  157135. }else if( !prevEscape && uPattern==MATCH_ONE ){
  157136. /* Case 2. */
  157137. if( *zString==0 ) return 0;
  157138. SQLITE_ICU_SKIP_UTF8(zString);
  157139. }else if( !prevEscape && uPattern==uEsc){
  157140. /* Case 3. */
  157141. prevEscape = 1;
  157142. }else{
  157143. /* Case 4. */
  157144. UChar32 uString;
  157145. SQLITE_ICU_READ_UTF8(zString, uString);
  157146. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  157147. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  157148. if( uString!=uPattern ){
  157149. return 0;
  157150. }
  157151. prevEscape = 0;
  157152. }
  157153. }
  157154. return *zString==0;
  157155. }
  157156. /*
  157157. ** Implementation of the like() SQL function. This function implements
  157158. ** the build-in LIKE operator. The first argument to the function is the
  157159. ** pattern and the second argument is the string. So, the SQL statements:
  157160. **
  157161. ** A LIKE B
  157162. **
  157163. ** is implemented as like(B, A). If there is an escape character E,
  157164. **
  157165. ** A LIKE B ESCAPE E
  157166. **
  157167. ** is mapped to like(B, A, E).
  157168. */
  157169. static void icuLikeFunc(
  157170. sqlite3_context *context,
  157171. int argc,
  157172. sqlite3_value **argv
  157173. ){
  157174. const unsigned char *zA = sqlite3_value_text(argv[0]);
  157175. const unsigned char *zB = sqlite3_value_text(argv[1]);
  157176. UChar32 uEsc = 0;
  157177. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  157178. ** of deep recursion and N*N behavior in patternCompare().
  157179. */
  157180. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  157181. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  157182. return;
  157183. }
  157184. if( argc==3 ){
  157185. /* The escape character string must consist of a single UTF-8 character.
  157186. ** Otherwise, return an error.
  157187. */
  157188. int nE= sqlite3_value_bytes(argv[2]);
  157189. const unsigned char *zE = sqlite3_value_text(argv[2]);
  157190. int i = 0;
  157191. if( zE==0 ) return;
  157192. U8_NEXT(zE, i, nE, uEsc);
  157193. if( i!=nE){
  157194. sqlite3_result_error(context,
  157195. "ESCAPE expression must be a single character", -1);
  157196. return;
  157197. }
  157198. }
  157199. if( zA && zB ){
  157200. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  157201. }
  157202. }
  157203. /*
  157204. ** This function is called when an ICU function called from within
  157205. ** the implementation of an SQL scalar function returns an error.
  157206. **
  157207. ** The scalar function context passed as the first argument is
  157208. ** loaded with an error message based on the following two args.
  157209. */
  157210. static void icuFunctionError(
  157211. sqlite3_context *pCtx, /* SQLite scalar function context */
  157212. const char *zName, /* Name of ICU function that failed */
  157213. UErrorCode e /* Error code returned by ICU function */
  157214. ){
  157215. char zBuf[128];
  157216. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  157217. zBuf[127] = '\0';
  157218. sqlite3_result_error(pCtx, zBuf, -1);
  157219. }
  157220. /*
  157221. ** Function to delete compiled regexp objects. Registered as
  157222. ** a destructor function with sqlite3_set_auxdata().
  157223. */
  157224. static void icuRegexpDelete(void *p){
  157225. URegularExpression *pExpr = (URegularExpression *)p;
  157226. uregex_close(pExpr);
  157227. }
  157228. /*
  157229. ** Implementation of SQLite REGEXP operator. This scalar function takes
  157230. ** two arguments. The first is a regular expression pattern to compile
  157231. ** the second is a string to match against that pattern. If either
  157232. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  157233. ** is 1 if the string matches the pattern, or 0 otherwise.
  157234. **
  157235. ** SQLite maps the regexp() function to the regexp() operator such
  157236. ** that the following two are equivalent:
  157237. **
  157238. ** zString REGEXP zPattern
  157239. ** regexp(zPattern, zString)
  157240. **
  157241. ** Uses the following ICU regexp APIs:
  157242. **
  157243. ** uregex_open()
  157244. ** uregex_matches()
  157245. ** uregex_close()
  157246. */
  157247. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  157248. UErrorCode status = U_ZERO_ERROR;
  157249. URegularExpression *pExpr;
  157250. UBool res;
  157251. const UChar *zString = sqlite3_value_text16(apArg[1]);
  157252. (void)nArg; /* Unused parameter */
  157253. /* If the left hand side of the regexp operator is NULL,
  157254. ** then the result is also NULL.
  157255. */
  157256. if( !zString ){
  157257. return;
  157258. }
  157259. pExpr = sqlite3_get_auxdata(p, 0);
  157260. if( !pExpr ){
  157261. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  157262. if( !zPattern ){
  157263. return;
  157264. }
  157265. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  157266. if( U_SUCCESS(status) ){
  157267. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  157268. }else{
  157269. assert(!pExpr);
  157270. icuFunctionError(p, "uregex_open", status);
  157271. return;
  157272. }
  157273. }
  157274. /* Configure the text that the regular expression operates on. */
  157275. uregex_setText(pExpr, zString, -1, &status);
  157276. if( !U_SUCCESS(status) ){
  157277. icuFunctionError(p, "uregex_setText", status);
  157278. return;
  157279. }
  157280. /* Attempt the match */
  157281. res = uregex_matches(pExpr, 0, &status);
  157282. if( !U_SUCCESS(status) ){
  157283. icuFunctionError(p, "uregex_matches", status);
  157284. return;
  157285. }
  157286. /* Set the text that the regular expression operates on to a NULL
  157287. ** pointer. This is not really necessary, but it is tidier than
  157288. ** leaving the regular expression object configured with an invalid
  157289. ** pointer after this function returns.
  157290. */
  157291. uregex_setText(pExpr, 0, 0, &status);
  157292. /* Return 1 or 0. */
  157293. sqlite3_result_int(p, res ? 1 : 0);
  157294. }
  157295. /*
  157296. ** Implementations of scalar functions for case mapping - upper() and
  157297. ** lower(). Function upper() converts its input to upper-case (ABC).
  157298. ** Function lower() converts to lower-case (abc).
  157299. **
  157300. ** ICU provides two types of case mapping, "general" case mapping and
  157301. ** "language specific". Refer to ICU documentation for the differences
  157302. ** between the two.
  157303. **
  157304. ** To utilise "general" case mapping, the upper() or lower() scalar
  157305. ** functions are invoked with one argument:
  157306. **
  157307. ** upper('ABC') -> 'abc'
  157308. ** lower('abc') -> 'ABC'
  157309. **
  157310. ** To access ICU "language specific" case mapping, upper() or lower()
  157311. ** should be invoked with two arguments. The second argument is the name
  157312. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  157313. ** as the second argument is the same as invoking the 1 argument version
  157314. ** of upper() or lower().
  157315. **
  157316. ** lower('I', 'en_us') -> 'i'
  157317. ** lower('I', 'tr_tr') -> '\u131' (small dotless i)
  157318. **
  157319. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  157320. */
  157321. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  157322. const UChar *zInput; /* Pointer to input string */
  157323. UChar *zOutput = 0; /* Pointer to output buffer */
  157324. int nInput; /* Size of utf-16 input string in bytes */
  157325. int nOut; /* Size of output buffer in bytes */
  157326. int cnt;
  157327. int bToUpper; /* True for toupper(), false for tolower() */
  157328. UErrorCode status;
  157329. const char *zLocale = 0;
  157330. assert(nArg==1 || nArg==2);
  157331. bToUpper = (sqlite3_user_data(p)!=0);
  157332. if( nArg==2 ){
  157333. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  157334. }
  157335. zInput = sqlite3_value_text16(apArg[0]);
  157336. if( !zInput ){
  157337. return;
  157338. }
  157339. nOut = nInput = sqlite3_value_bytes16(apArg[0]);
  157340. if( nOut==0 ){
  157341. sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
  157342. return;
  157343. }
  157344. for(cnt=0; cnt<2; cnt++){
  157345. UChar *zNew = sqlite3_realloc(zOutput, nOut);
  157346. if( zNew==0 ){
  157347. sqlite3_free(zOutput);
  157348. sqlite3_result_error_nomem(p);
  157349. return;
  157350. }
  157351. zOutput = zNew;
  157352. status = U_ZERO_ERROR;
  157353. if( bToUpper ){
  157354. nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  157355. }else{
  157356. nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  157357. }
  157358. if( U_SUCCESS(status) ){
  157359. sqlite3_result_text16(p, zOutput, nOut, xFree);
  157360. }else if( status==U_BUFFER_OVERFLOW_ERROR ){
  157361. assert( cnt==0 );
  157362. continue;
  157363. }else{
  157364. icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
  157365. }
  157366. return;
  157367. }
  157368. assert( 0 ); /* Unreachable */
  157369. }
  157370. /*
  157371. ** Collation sequence destructor function. The pCtx argument points to
  157372. ** a UCollator structure previously allocated using ucol_open().
  157373. */
  157374. static void icuCollationDel(void *pCtx){
  157375. UCollator *p = (UCollator *)pCtx;
  157376. ucol_close(p);
  157377. }
  157378. /*
  157379. ** Collation sequence comparison function. The pCtx argument points to
  157380. ** a UCollator structure previously allocated using ucol_open().
  157381. */
  157382. static int icuCollationColl(
  157383. void *pCtx,
  157384. int nLeft,
  157385. const void *zLeft,
  157386. int nRight,
  157387. const void *zRight
  157388. ){
  157389. UCollationResult res;
  157390. UCollator *p = (UCollator *)pCtx;
  157391. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  157392. switch( res ){
  157393. case UCOL_LESS: return -1;
  157394. case UCOL_GREATER: return +1;
  157395. case UCOL_EQUAL: return 0;
  157396. }
  157397. assert(!"Unexpected return value from ucol_strcoll()");
  157398. return 0;
  157399. }
  157400. /*
  157401. ** Implementation of the scalar function icu_load_collation().
  157402. **
  157403. ** This scalar function is used to add ICU collation based collation
  157404. ** types to an SQLite database connection. It is intended to be called
  157405. ** as follows:
  157406. **
  157407. ** SELECT icu_load_collation(<locale>, <collation-name>);
  157408. **
  157409. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  157410. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  157411. ** collation sequence to create.
  157412. */
  157413. static void icuLoadCollation(
  157414. sqlite3_context *p,
  157415. int nArg,
  157416. sqlite3_value **apArg
  157417. ){
  157418. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  157419. UErrorCode status = U_ZERO_ERROR;
  157420. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  157421. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  157422. UCollator *pUCollator; /* ICU library collation object */
  157423. int rc; /* Return code from sqlite3_create_collation_x() */
  157424. assert(nArg==2);
  157425. (void)nArg; /* Unused parameter */
  157426. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  157427. zName = (const char *)sqlite3_value_text(apArg[1]);
  157428. if( !zLocale || !zName ){
  157429. return;
  157430. }
  157431. pUCollator = ucol_open(zLocale, &status);
  157432. if( !U_SUCCESS(status) ){
  157433. icuFunctionError(p, "ucol_open", status);
  157434. return;
  157435. }
  157436. assert(p);
  157437. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  157438. icuCollationColl, icuCollationDel
  157439. );
  157440. if( rc!=SQLITE_OK ){
  157441. ucol_close(pUCollator);
  157442. sqlite3_result_error(p, "Error registering collation function", -1);
  157443. }
  157444. }
  157445. /*
  157446. ** Register the ICU extension functions with database db.
  157447. */
  157448. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  157449. static const struct IcuScalar {
  157450. const char *zName; /* Function name */
  157451. unsigned char nArg; /* Number of arguments */
  157452. unsigned short enc; /* Optimal text encoding */
  157453. unsigned char iContext; /* sqlite3_user_data() context */
  157454. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  157455. } scalars[] = {
  157456. {"icu_load_collation", 2, SQLITE_UTF8, 1, icuLoadCollation},
  157457. {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC, 0, icuRegexpFunc},
  157458. {"lower", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  157459. {"lower", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  157460. {"upper", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  157461. {"upper", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  157462. {"lower", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  157463. {"lower", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  157464. {"upper", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  157465. {"upper", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  157466. {"like", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
  157467. {"like", 3, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
  157468. };
  157469. int rc = SQLITE_OK;
  157470. int i;
  157471. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  157472. const struct IcuScalar *p = &scalars[i];
  157473. rc = sqlite3_create_function(
  157474. db, p->zName, p->nArg, p->enc,
  157475. p->iContext ? (void*)db : (void*)0,
  157476. p->xFunc, 0, 0
  157477. );
  157478. }
  157479. return rc;
  157480. }
  157481. #if !SQLITE_CORE
  157482. #ifdef _WIN32
  157483. __declspec(dllexport)
  157484. #endif
  157485. SQLITE_API int sqlite3_icu_init(
  157486. sqlite3 *db,
  157487. char **pzErrMsg,
  157488. const sqlite3_api_routines *pApi
  157489. ){
  157490. SQLITE_EXTENSION_INIT2(pApi)
  157491. return sqlite3IcuInit(db);
  157492. }
  157493. #endif
  157494. #endif
  157495. /************** End of icu.c *************************************************/
  157496. /************** Begin file fts3_icu.c ****************************************/
  157497. /*
  157498. ** 2007 June 22
  157499. **
  157500. ** The author disclaims copyright to this source code. In place of
  157501. ** a legal notice, here is a blessing:
  157502. **
  157503. ** May you do good and not evil.
  157504. ** May you find forgiveness for yourself and forgive others.
  157505. ** May you share freely, never taking more than you give.
  157506. **
  157507. *************************************************************************
  157508. ** This file implements a tokenizer for fts3 based on the ICU library.
  157509. */
  157510. /* #include "fts3Int.h" */
  157511. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  157512. #ifdef SQLITE_ENABLE_ICU
  157513. /* #include <assert.h> */
  157514. /* #include <string.h> */
  157515. /* #include "fts3_tokenizer.h" */
  157516. #include <unicode/ubrk.h>
  157517. /* #include <unicode/ucol.h> */
  157518. /* #include <unicode/ustring.h> */
  157519. #include <unicode/utf16.h>
  157520. typedef struct IcuTokenizer IcuTokenizer;
  157521. typedef struct IcuCursor IcuCursor;
  157522. struct IcuTokenizer {
  157523. sqlite3_tokenizer base;
  157524. char *zLocale;
  157525. };
  157526. struct IcuCursor {
  157527. sqlite3_tokenizer_cursor base;
  157528. UBreakIterator *pIter; /* ICU break-iterator object */
  157529. int nChar; /* Number of UChar elements in pInput */
  157530. UChar *aChar; /* Copy of input using utf-16 encoding */
  157531. int *aOffset; /* Offsets of each character in utf-8 input */
  157532. int nBuffer;
  157533. char *zBuffer;
  157534. int iToken;
  157535. };
  157536. /*
  157537. ** Create a new tokenizer instance.
  157538. */
  157539. static int icuCreate(
  157540. int argc, /* Number of entries in argv[] */
  157541. const char * const *argv, /* Tokenizer creation arguments */
  157542. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  157543. ){
  157544. IcuTokenizer *p;
  157545. int n = 0;
  157546. if( argc>0 ){
  157547. n = strlen(argv[0])+1;
  157548. }
  157549. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  157550. if( !p ){
  157551. return SQLITE_NOMEM;
  157552. }
  157553. memset(p, 0, sizeof(IcuTokenizer));
  157554. if( n ){
  157555. p->zLocale = (char *)&p[1];
  157556. memcpy(p->zLocale, argv[0], n);
  157557. }
  157558. *ppTokenizer = (sqlite3_tokenizer *)p;
  157559. return SQLITE_OK;
  157560. }
  157561. /*
  157562. ** Destroy a tokenizer
  157563. */
  157564. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  157565. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  157566. sqlite3_free(p);
  157567. return SQLITE_OK;
  157568. }
  157569. /*
  157570. ** Prepare to begin tokenizing a particular string. The input
  157571. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  157572. ** used to incrementally tokenize this string is returned in
  157573. ** *ppCursor.
  157574. */
  157575. static int icuOpen(
  157576. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  157577. const char *zInput, /* Input string */
  157578. int nInput, /* Length of zInput in bytes */
  157579. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  157580. ){
  157581. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  157582. IcuCursor *pCsr;
  157583. const int32_t opt = U_FOLD_CASE_DEFAULT;
  157584. UErrorCode status = U_ZERO_ERROR;
  157585. int nChar;
  157586. UChar32 c;
  157587. int iInput = 0;
  157588. int iOut = 0;
  157589. *ppCursor = 0;
  157590. if( zInput==0 ){
  157591. nInput = 0;
  157592. zInput = "";
  157593. }else if( nInput<0 ){
  157594. nInput = strlen(zInput);
  157595. }
  157596. nChar = nInput+1;
  157597. pCsr = (IcuCursor *)sqlite3_malloc(
  157598. sizeof(IcuCursor) + /* IcuCursor */
  157599. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  157600. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  157601. );
  157602. if( !pCsr ){
  157603. return SQLITE_NOMEM;
  157604. }
  157605. memset(pCsr, 0, sizeof(IcuCursor));
  157606. pCsr->aChar = (UChar *)&pCsr[1];
  157607. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  157608. pCsr->aOffset[iOut] = iInput;
  157609. U8_NEXT(zInput, iInput, nInput, c);
  157610. while( c>0 ){
  157611. int isError = 0;
  157612. c = u_foldCase(c, opt);
  157613. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  157614. if( isError ){
  157615. sqlite3_free(pCsr);
  157616. return SQLITE_ERROR;
  157617. }
  157618. pCsr->aOffset[iOut] = iInput;
  157619. if( iInput<nInput ){
  157620. U8_NEXT(zInput, iInput, nInput, c);
  157621. }else{
  157622. c = 0;
  157623. }
  157624. }
  157625. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  157626. if( !U_SUCCESS(status) ){
  157627. sqlite3_free(pCsr);
  157628. return SQLITE_ERROR;
  157629. }
  157630. pCsr->nChar = iOut;
  157631. ubrk_first(pCsr->pIter);
  157632. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  157633. return SQLITE_OK;
  157634. }
  157635. /*
  157636. ** Close a tokenization cursor previously opened by a call to icuOpen().
  157637. */
  157638. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  157639. IcuCursor *pCsr = (IcuCursor *)pCursor;
  157640. ubrk_close(pCsr->pIter);
  157641. sqlite3_free(pCsr->zBuffer);
  157642. sqlite3_free(pCsr);
  157643. return SQLITE_OK;
  157644. }
  157645. /*
  157646. ** Extract the next token from a tokenization cursor.
  157647. */
  157648. static int icuNext(
  157649. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  157650. const char **ppToken, /* OUT: *ppToken is the token text */
  157651. int *pnBytes, /* OUT: Number of bytes in token */
  157652. int *piStartOffset, /* OUT: Starting offset of token */
  157653. int *piEndOffset, /* OUT: Ending offset of token */
  157654. int *piPosition /* OUT: Position integer of token */
  157655. ){
  157656. IcuCursor *pCsr = (IcuCursor *)pCursor;
  157657. int iStart = 0;
  157658. int iEnd = 0;
  157659. int nByte = 0;
  157660. while( iStart==iEnd ){
  157661. UChar32 c;
  157662. iStart = ubrk_current(pCsr->pIter);
  157663. iEnd = ubrk_next(pCsr->pIter);
  157664. if( iEnd==UBRK_DONE ){
  157665. return SQLITE_DONE;
  157666. }
  157667. while( iStart<iEnd ){
  157668. int iWhite = iStart;
  157669. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  157670. if( u_isspace(c) ){
  157671. iStart = iWhite;
  157672. }else{
  157673. break;
  157674. }
  157675. }
  157676. assert(iStart<=iEnd);
  157677. }
  157678. do {
  157679. UErrorCode status = U_ZERO_ERROR;
  157680. if( nByte ){
  157681. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  157682. if( !zNew ){
  157683. return SQLITE_NOMEM;
  157684. }
  157685. pCsr->zBuffer = zNew;
  157686. pCsr->nBuffer = nByte;
  157687. }
  157688. u_strToUTF8(
  157689. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  157690. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  157691. &status /* Output success/failure */
  157692. );
  157693. } while( nByte>pCsr->nBuffer );
  157694. *ppToken = pCsr->zBuffer;
  157695. *pnBytes = nByte;
  157696. *piStartOffset = pCsr->aOffset[iStart];
  157697. *piEndOffset = pCsr->aOffset[iEnd];
  157698. *piPosition = pCsr->iToken++;
  157699. return SQLITE_OK;
  157700. }
  157701. /*
  157702. ** The set of routines that implement the simple tokenizer
  157703. */
  157704. static const sqlite3_tokenizer_module icuTokenizerModule = {
  157705. 0, /* iVersion */
  157706. icuCreate, /* xCreate */
  157707. icuDestroy, /* xCreate */
  157708. icuOpen, /* xOpen */
  157709. icuClose, /* xClose */
  157710. icuNext, /* xNext */
  157711. 0, /* xLanguageid */
  157712. };
  157713. /*
  157714. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  157715. */
  157716. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  157717. sqlite3_tokenizer_module const**ppModule
  157718. ){
  157719. *ppModule = &icuTokenizerModule;
  157720. }
  157721. #endif /* defined(SQLITE_ENABLE_ICU) */
  157722. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  157723. /************** End of fts3_icu.c ********************************************/
  157724. /************** Begin file sqlite3rbu.c **************************************/
  157725. /*
  157726. ** 2014 August 30
  157727. **
  157728. ** The author disclaims copyright to this source code. In place of
  157729. ** a legal notice, here is a blessing:
  157730. **
  157731. ** May you do good and not evil.
  157732. ** May you find forgiveness for yourself and forgive others.
  157733. ** May you share freely, never taking more than you give.
  157734. **
  157735. *************************************************************************
  157736. **
  157737. **
  157738. ** OVERVIEW
  157739. **
  157740. ** The RBU extension requires that the RBU update be packaged as an
  157741. ** SQLite database. The tables it expects to find are described in
  157742. ** sqlite3rbu.h. Essentially, for each table xyz in the target database
  157743. ** that the user wishes to write to, a corresponding data_xyz table is
  157744. ** created in the RBU database and populated with one row for each row to
  157745. ** update, insert or delete from the target table.
  157746. **
  157747. ** The update proceeds in three stages:
  157748. **
  157749. ** 1) The database is updated. The modified database pages are written
  157750. ** to a *-oal file. A *-oal file is just like a *-wal file, except
  157751. ** that it is named "<database>-oal" instead of "<database>-wal".
  157752. ** Because regular SQLite clients do not look for file named
  157753. ** "<database>-oal", they go on using the original database in
  157754. ** rollback mode while the *-oal file is being generated.
  157755. **
  157756. ** During this stage RBU does not update the database by writing
  157757. ** directly to the target tables. Instead it creates "imposter"
  157758. ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
  157759. ** to update each b-tree individually. All updates required by each
  157760. ** b-tree are completed before moving on to the next, and all
  157761. ** updates are done in sorted key order.
  157762. **
  157763. ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
  157764. ** location using a call to rename(2). Before doing this the RBU
  157765. ** module takes an EXCLUSIVE lock on the database file, ensuring
  157766. ** that there are no other active readers.
  157767. **
  157768. ** Once the EXCLUSIVE lock is released, any other database readers
  157769. ** detect the new *-wal file and read the database in wal mode. At
  157770. ** this point they see the new version of the database - including
  157771. ** the updates made as part of the RBU update.
  157772. **
  157773. ** 3) The new *-wal file is checkpointed. This proceeds in the same way
  157774. ** as a regular database checkpoint, except that a single frame is
  157775. ** checkpointed each time sqlite3rbu_step() is called. If the RBU
  157776. ** handle is closed before the entire *-wal file is checkpointed,
  157777. ** the checkpoint progress is saved in the RBU database and the
  157778. ** checkpoint can be resumed by another RBU client at some point in
  157779. ** the future.
  157780. **
  157781. ** POTENTIAL PROBLEMS
  157782. **
  157783. ** The rename() call might not be portable. And RBU is not currently
  157784. ** syncing the directory after renaming the file.
  157785. **
  157786. ** When state is saved, any commit to the *-oal file and the commit to
  157787. ** the RBU update database are not atomic. So if the power fails at the
  157788. ** wrong moment they might get out of sync. As the main database will be
  157789. ** committed before the RBU update database this will likely either just
  157790. ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
  157791. ** constraint violations).
  157792. **
  157793. ** If some client does modify the target database mid RBU update, or some
  157794. ** other error occurs, the RBU extension will keep throwing errors. It's
  157795. ** not really clear how to get out of this state. The system could just
  157796. ** by delete the RBU update database and *-oal file and have the device
  157797. ** download the update again and start over.
  157798. **
  157799. ** At present, for an UPDATE, both the new.* and old.* records are
  157800. ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
  157801. ** fields are collected. This means we're probably writing a lot more
  157802. ** data to disk when saving the state of an ongoing update to the RBU
  157803. ** update database than is strictly necessary.
  157804. **
  157805. */
  157806. /* #include <assert.h> */
  157807. /* #include <string.h> */
  157808. /* #include <stdio.h> */
  157809. /* #include "sqlite3.h" */
  157810. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
  157811. /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
  157812. /************** Begin file sqlite3rbu.h **************************************/
  157813. /*
  157814. ** 2014 August 30
  157815. **
  157816. ** The author disclaims copyright to this source code. In place of
  157817. ** a legal notice, here is a blessing:
  157818. **
  157819. ** May you do good and not evil.
  157820. ** May you find forgiveness for yourself and forgive others.
  157821. ** May you share freely, never taking more than you give.
  157822. **
  157823. *************************************************************************
  157824. **
  157825. ** This file contains the public interface for the RBU extension.
  157826. */
  157827. /*
  157828. ** SUMMARY
  157829. **
  157830. ** Writing a transaction containing a large number of operations on
  157831. ** b-tree indexes that are collectively larger than the available cache
  157832. ** memory can be very inefficient.
  157833. **
  157834. ** The problem is that in order to update a b-tree, the leaf page (at least)
  157835. ** containing the entry being inserted or deleted must be modified. If the
  157836. ** working set of leaves is larger than the available cache memory, then a
  157837. ** single leaf that is modified more than once as part of the transaction
  157838. ** may be loaded from or written to the persistent media multiple times.
  157839. ** Additionally, because the index updates are likely to be applied in
  157840. ** random order, access to pages within the database is also likely to be in
  157841. ** random order, which is itself quite inefficient.
  157842. **
  157843. ** One way to improve the situation is to sort the operations on each index
  157844. ** by index key before applying them to the b-tree. This leads to an IO
  157845. ** pattern that resembles a single linear scan through the index b-tree,
  157846. ** and all but guarantees each modified leaf page is loaded and stored
  157847. ** exactly once. SQLite uses this trick to improve the performance of
  157848. ** CREATE INDEX commands. This extension allows it to be used to improve
  157849. ** the performance of large transactions on existing databases.
  157850. **
  157851. ** Additionally, this extension allows the work involved in writing the
  157852. ** large transaction to be broken down into sub-transactions performed
  157853. ** sequentially by separate processes. This is useful if the system cannot
  157854. ** guarantee that a single update process will run for long enough to apply
  157855. ** the entire update, for example because the update is being applied on a
  157856. ** mobile device that is frequently rebooted. Even after the writer process
  157857. ** has committed one or more sub-transactions, other database clients continue
  157858. ** to read from the original database snapshot. In other words, partially
  157859. ** applied transactions are not visible to other clients.
  157860. **
  157861. ** "RBU" stands for "Resumable Bulk Update". As in a large database update
  157862. ** transmitted via a wireless network to a mobile device. A transaction
  157863. ** applied using this extension is hence refered to as an "RBU update".
  157864. **
  157865. **
  157866. ** LIMITATIONS
  157867. **
  157868. ** An "RBU update" transaction is subject to the following limitations:
  157869. **
  157870. ** * The transaction must consist of INSERT, UPDATE and DELETE operations
  157871. ** only.
  157872. **
  157873. ** * INSERT statements may not use any default values.
  157874. **
  157875. ** * UPDATE and DELETE statements must identify their target rows by
  157876. ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
  157877. ** KEY fields may not be updated or deleted. If the table being written
  157878. ** has no PRIMARY KEY, affected rows must be identified by rowid.
  157879. **
  157880. ** * UPDATE statements may not modify PRIMARY KEY columns.
  157881. **
  157882. ** * No triggers will be fired.
  157883. **
  157884. ** * No foreign key violations are detected or reported.
  157885. **
  157886. ** * CHECK constraints are not enforced.
  157887. **
  157888. ** * No constraint handling mode except for "OR ROLLBACK" is supported.
  157889. **
  157890. **
  157891. ** PREPARATION
  157892. **
  157893. ** An "RBU update" is stored as a separate SQLite database. A database
  157894. ** containing an RBU update is an "RBU database". For each table in the
  157895. ** target database to be updated, the RBU database should contain a table
  157896. ** named "data_<target name>" containing the same set of columns as the
  157897. ** target table, and one more - "rbu_control". The data_% table should
  157898. ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
  157899. ** the same type as the corresponding column in the target database.
  157900. ** The "rbu_control" column should have no type at all. For example, if
  157901. ** the target database contains:
  157902. **
  157903. ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
  157904. **
  157905. ** Then the RBU database should contain:
  157906. **
  157907. ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
  157908. **
  157909. ** The order of the columns in the data_% table does not matter.
  157910. **
  157911. ** Instead of a regular table, the RBU database may also contain virtual
  157912. ** tables or view named using the data_<target> naming scheme.
  157913. **
  157914. ** Instead of the plain data_<target> naming scheme, RBU database tables
  157915. ** may also be named data<integer>_<target>, where <integer> is any sequence
  157916. ** of zero or more numeric characters (0-9). This can be significant because
  157917. ** tables within the RBU database are always processed in order sorted by
  157918. ** name. By judicious selection of the <integer> portion of the names
  157919. ** of the RBU tables the user can therefore control the order in which they
  157920. ** are processed. This can be useful, for example, to ensure that "external
  157921. ** content" FTS4 tables are updated before their underlying content tables.
  157922. **
  157923. ** If the target database table is a virtual table or a table that has no
  157924. ** PRIMARY KEY declaration, the data_% table must also contain a column
  157925. ** named "rbu_rowid". This column is mapped to the tables implicit primary
  157926. ** key column - "rowid". Virtual tables for which the "rowid" column does
  157927. ** not function like a primary key value cannot be updated using RBU. For
  157928. ** example, if the target db contains either of the following:
  157929. **
  157930. ** CREATE VIRTUAL TABLE x1 USING fts3(a, b);
  157931. ** CREATE TABLE x1(a, b)
  157932. **
  157933. ** then the RBU database should contain:
  157934. **
  157935. ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
  157936. **
  157937. ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
  157938. ** target table must be present in the input table. For virtual tables,
  157939. ** hidden columns are optional - they are updated by RBU if present in
  157940. ** the input table, or not otherwise. For example, to write to an fts4
  157941. ** table with a hidden languageid column such as:
  157942. **
  157943. ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
  157944. **
  157945. ** Either of the following input table schemas may be used:
  157946. **
  157947. ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
  157948. ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
  157949. **
  157950. ** For each row to INSERT into the target database as part of the RBU
  157951. ** update, the corresponding data_% table should contain a single record
  157952. ** with the "rbu_control" column set to contain integer value 0. The
  157953. ** other columns should be set to the values that make up the new record
  157954. ** to insert.
  157955. **
  157956. ** If the target database table has an INTEGER PRIMARY KEY, it is not
  157957. ** possible to insert a NULL value into the IPK column. Attempting to
  157958. ** do so results in an SQLITE_MISMATCH error.
  157959. **
  157960. ** For each row to DELETE from the target database as part of the RBU
  157961. ** update, the corresponding data_% table should contain a single record
  157962. ** with the "rbu_control" column set to contain integer value 1. The
  157963. ** real primary key values of the row to delete should be stored in the
  157964. ** corresponding columns of the data_% table. The values stored in the
  157965. ** other columns are not used.
  157966. **
  157967. ** For each row to UPDATE from the target database as part of the RBU
  157968. ** update, the corresponding data_% table should contain a single record
  157969. ** with the "rbu_control" column set to contain a value of type text.
  157970. ** The real primary key values identifying the row to update should be
  157971. ** stored in the corresponding columns of the data_% table row, as should
  157972. ** the new values of all columns being update. The text value in the
  157973. ** "rbu_control" column must contain the same number of characters as
  157974. ** there are columns in the target database table, and must consist entirely
  157975. ** of 'x' and '.' characters (or in some special cases 'd' - see below). For
  157976. ** each column that is being updated, the corresponding character is set to
  157977. ** 'x'. For those that remain as they are, the corresponding character of the
  157978. ** rbu_control value should be set to '.'. For example, given the tables
  157979. ** above, the update statement:
  157980. **
  157981. ** UPDATE t1 SET c = 'usa' WHERE a = 4;
  157982. **
  157983. ** is represented by the data_t1 row created by:
  157984. **
  157985. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
  157986. **
  157987. ** Instead of an 'x' character, characters of the rbu_control value specified
  157988. ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
  157989. ** target table with the value stored in the corresponding data_% column, the
  157990. ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
  157991. ** the target table column. rbu_delta() is invoked with two arguments - the
  157992. ** original value currently stored in the target table column and the
  157993. ** value specified in the data_xxx table.
  157994. **
  157995. ** For example, this row:
  157996. **
  157997. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
  157998. **
  157999. ** is similar to an UPDATE statement such as:
  158000. **
  158001. ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
  158002. **
  158003. ** Finally, if an 'f' character appears in place of a 'd' or 's' in an
  158004. ** ota_control string, the contents of the data_xxx table column is assumed
  158005. ** to be a "fossil delta" - a patch to be applied to a blob value in the
  158006. ** format used by the fossil source-code management system. In this case
  158007. ** the existing value within the target database table must be of type BLOB.
  158008. ** It is replaced by the result of applying the specified fossil delta to
  158009. ** itself.
  158010. **
  158011. ** If the target database table is a virtual table or a table with no PRIMARY
  158012. ** KEY, the rbu_control value should not include a character corresponding
  158013. ** to the rbu_rowid value. For example, this:
  158014. **
  158015. ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
  158016. ** VALUES(NULL, 'usa', 12, '.x');
  158017. **
  158018. ** causes a result similar to:
  158019. **
  158020. ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
  158021. **
  158022. ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
  158023. ** However, RBU is more efficient if reading the rows in from each data_xxx
  158024. ** table in "rowid" order is roughly the same as reading them sorted by
  158025. ** the PRIMARY KEY of the corresponding target database table. In other
  158026. ** words, rows should be sorted using the destination table PRIMARY KEY
  158027. ** fields before they are inserted into the data_xxx tables.
  158028. **
  158029. ** USAGE
  158030. **
  158031. ** The API declared below allows an application to apply an RBU update
  158032. ** stored on disk to an existing target database. Essentially, the
  158033. ** application:
  158034. **
  158035. ** 1) Opens an RBU handle using the sqlite3rbu_open() function.
  158036. **
  158037. ** 2) Registers any required virtual table modules with the database
  158038. ** handle returned by sqlite3rbu_db(). Also, if required, register
  158039. ** the rbu_delta() implementation.
  158040. **
  158041. ** 3) Calls the sqlite3rbu_step() function one or more times on
  158042. ** the new handle. Each call to sqlite3rbu_step() performs a single
  158043. ** b-tree operation, so thousands of calls may be required to apply
  158044. ** a complete update.
  158045. **
  158046. ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If
  158047. ** sqlite3rbu_step() has been called enough times to completely
  158048. ** apply the update to the target database, then the RBU database
  158049. ** is marked as fully applied. Otherwise, the state of the RBU
  158050. ** update application is saved in the RBU database for later
  158051. ** resumption.
  158052. **
  158053. ** See comments below for more detail on APIs.
  158054. **
  158055. ** If an update is only partially applied to the target database by the
  158056. ** time sqlite3rbu_close() is called, various state information is saved
  158057. ** within the RBU database. This allows subsequent processes to automatically
  158058. ** resume the RBU update from where it left off.
  158059. **
  158060. ** To remove all RBU extension state information, returning an RBU database
  158061. ** to its original contents, it is sufficient to drop all tables that begin
  158062. ** with the prefix "rbu_"
  158063. **
  158064. ** DATABASE LOCKING
  158065. **
  158066. ** An RBU update may not be applied to a database in WAL mode. Attempting
  158067. ** to do so is an error (SQLITE_ERROR).
  158068. **
  158069. ** While an RBU handle is open, a SHARED lock may be held on the target
  158070. ** database file. This means it is possible for other clients to read the
  158071. ** database, but not to write it.
  158072. **
  158073. ** If an RBU update is started and then suspended before it is completed,
  158074. ** then an external client writes to the database, then attempting to resume
  158075. ** the suspended RBU update is also an error (SQLITE_BUSY).
  158076. */
  158077. #ifndef _SQLITE3RBU_H
  158078. #define _SQLITE3RBU_H
  158079. /* #include "sqlite3.h" ** Required for error code definitions ** */
  158080. #if 0
  158081. extern "C" {
  158082. #endif
  158083. typedef struct sqlite3rbu sqlite3rbu;
  158084. /*
  158085. ** Open an RBU handle.
  158086. **
  158087. ** Argument zTarget is the path to the target database. Argument zRbu is
  158088. ** the path to the RBU database. Each call to this function must be matched
  158089. ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
  158090. ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
  158091. ** or zRbu begin with "file:", it will be interpreted as an SQLite
  158092. ** database URI, not a regular file name.
  158093. **
  158094. ** If the zState argument is passed a NULL value, the RBU extension stores
  158095. ** the current state of the update (how many rows have been updated, which
  158096. ** indexes are yet to be updated etc.) within the RBU database itself. This
  158097. ** can be convenient, as it means that the RBU application does not need to
  158098. ** organize removing a separate state file after the update is concluded.
  158099. ** Or, if zState is non-NULL, it must be a path to a database file in which
  158100. ** the RBU extension can store the state of the update.
  158101. **
  158102. ** When resuming an RBU update, the zState argument must be passed the same
  158103. ** value as when the RBU update was started.
  158104. **
  158105. ** Once the RBU update is finished, the RBU extension does not
  158106. ** automatically remove any zState database file, even if it created it.
  158107. **
  158108. ** By default, RBU uses the default VFS to access the files on disk. To
  158109. ** use a VFS other than the default, an SQLite "file:" URI containing a
  158110. ** "vfs=..." option may be passed as the zTarget option.
  158111. **
  158112. ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
  158113. ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
  158114. ** not work out of the box with zipvfs. Refer to the comment describing
  158115. ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
  158116. */
  158117. SQLITE_API sqlite3rbu *sqlite3rbu_open(
  158118. const char *zTarget,
  158119. const char *zRbu,
  158120. const char *zState
  158121. );
  158122. /*
  158123. ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
  158124. ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
  158125. ** that it can be suspended and resumed like an RBU update.
  158126. **
  158127. ** The second argument to this function identifies a database in which
  158128. ** to store the state of the RBU vacuum operation if it is suspended. The
  158129. ** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
  158130. ** operation, the state database should either not exist or be empty
  158131. ** (contain no tables). If an RBU vacuum is suspended by calling
  158132. ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
  158133. ** returned SQLITE_DONE, the vacuum state is stored in the state database.
  158134. ** The vacuum can be resumed by calling this function to open a new RBU
  158135. ** handle specifying the same target and state databases.
  158136. **
  158137. ** If the second argument passed to this function is NULL, then the
  158138. ** name of the state database is "<database>-vacuum", where <database>
  158139. ** is the name of the target database file. In this case, on UNIX, if the
  158140. ** state database is not already present in the file-system, it is created
  158141. ** with the same permissions as the target db is made.
  158142. **
  158143. ** This function does not delete the state database after an RBU vacuum
  158144. ** is completed, even if it created it. However, if the call to
  158145. ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
  158146. ** of the state tables within the state database are zeroed. This way,
  158147. ** the next call to sqlite3rbu_vacuum() opens a handle that starts a
  158148. ** new RBU vacuum operation.
  158149. **
  158150. ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
  158151. ** describing the sqlite3rbu_create_vfs() API function below for
  158152. ** a description of the complications associated with using RBU with
  158153. ** zipvfs databases.
  158154. */
  158155. SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
  158156. const char *zTarget,
  158157. const char *zState
  158158. );
  158159. /*
  158160. ** Internally, each RBU connection uses a separate SQLite database
  158161. ** connection to access the target and rbu update databases. This
  158162. ** API allows the application direct access to these database handles.
  158163. **
  158164. ** The first argument passed to this function must be a valid, open, RBU
  158165. ** handle. The second argument should be passed zero to access the target
  158166. ** database handle, or non-zero to access the rbu update database handle.
  158167. ** Accessing the underlying database handles may be useful in the
  158168. ** following scenarios:
  158169. **
  158170. ** * If any target tables are virtual tables, it may be necessary to
  158171. ** call sqlite3_create_module() on the target database handle to
  158172. ** register the required virtual table implementations.
  158173. **
  158174. ** * If the data_xxx tables in the RBU source database are virtual
  158175. ** tables, the application may need to call sqlite3_create_module() on
  158176. ** the rbu update db handle to any required virtual table
  158177. ** implementations.
  158178. **
  158179. ** * If the application uses the "rbu_delta()" feature described above,
  158180. ** it must use sqlite3_create_function() or similar to register the
  158181. ** rbu_delta() implementation with the target database handle.
  158182. **
  158183. ** If an error has occurred, either while opening or stepping the RBU object,
  158184. ** this function may return NULL. The error code and message may be collected
  158185. ** when sqlite3rbu_close() is called.
  158186. **
  158187. ** Database handles returned by this function remain valid until the next
  158188. ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
  158189. */
  158190. SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
  158191. /*
  158192. ** Do some work towards applying the RBU update to the target db.
  158193. **
  158194. ** Return SQLITE_DONE if the update has been completely applied, or
  158195. ** SQLITE_OK if no error occurs but there remains work to do to apply
  158196. ** the RBU update. If an error does occur, some other error code is
  158197. ** returned.
  158198. **
  158199. ** Once a call to sqlite3rbu_step() has returned a value other than
  158200. ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
  158201. ** that immediately return the same value.
  158202. */
  158203. SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
  158204. /*
  158205. ** Force RBU to save its state to disk.
  158206. **
  158207. ** If a power failure or application crash occurs during an update, following
  158208. ** system recovery RBU may resume the update from the point at which the state
  158209. ** was last saved. In other words, from the most recent successful call to
  158210. ** sqlite3rbu_close() or this function.
  158211. **
  158212. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  158213. */
  158214. SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
  158215. /*
  158216. ** Close an RBU handle.
  158217. **
  158218. ** If the RBU update has been completely applied, mark the RBU database
  158219. ** as fully applied. Otherwise, assuming no error has occurred, save the
  158220. ** current state of the RBU update appliation to the RBU database.
  158221. **
  158222. ** If an error has already occurred as part of an sqlite3rbu_step()
  158223. ** or sqlite3rbu_open() call, or if one occurs within this function, an
  158224. ** SQLite error code is returned. Additionally, *pzErrmsg may be set to
  158225. ** point to a buffer containing a utf-8 formatted English language error
  158226. ** message. It is the responsibility of the caller to eventually free any
  158227. ** such buffer using sqlite3_free().
  158228. **
  158229. ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
  158230. ** update has been partially applied, or SQLITE_DONE if it has been
  158231. ** completely applied.
  158232. */
  158233. SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
  158234. /*
  158235. ** Return the total number of key-value operations (inserts, deletes or
  158236. ** updates) that have been performed on the target database since the
  158237. ** current RBU update was started.
  158238. */
  158239. SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
  158240. /*
  158241. ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
  158242. ** progress indications for the two stages of an RBU update. This API may
  158243. ** be useful for driving GUI progress indicators and similar.
  158244. **
  158245. ** An RBU update is divided into two stages:
  158246. **
  158247. ** * Stage 1, in which changes are accumulated in an oal/wal file, and
  158248. ** * Stage 2, in which the contents of the wal file are copied into the
  158249. ** main database.
  158250. **
  158251. ** The update is visible to non-RBU clients during stage 2. During stage 1
  158252. ** non-RBU reader clients may see the original database.
  158253. **
  158254. ** If this API is called during stage 2 of the update, output variable
  158255. ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
  158256. ** to a value between 0 and 10000 to indicate the permyriadage progress of
  158257. ** stage 2. A value of 5000 indicates that stage 2 is half finished,
  158258. ** 9000 indicates that it is 90% finished, and so on.
  158259. **
  158260. ** If this API is called during stage 1 of the update, output variable
  158261. ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
  158262. ** value to which (*pnOne) is set depends on whether or not the RBU
  158263. ** database contains an "rbu_count" table. The rbu_count table, if it
  158264. ** exists, must contain the same columns as the following:
  158265. **
  158266. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  158267. **
  158268. ** There must be one row in the table for each source (data_xxx) table within
  158269. ** the RBU database. The 'tbl' column should contain the name of the source
  158270. ** table. The 'cnt' column should contain the number of rows within the
  158271. ** source table.
  158272. **
  158273. ** If the rbu_count table is present and populated correctly and this
  158274. ** API is called during stage 1, the *pnOne output variable is set to the
  158275. ** permyriadage progress of the same stage. If the rbu_count table does
  158276. ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
  158277. ** table exists but is not correctly populated, the value of the *pnOne
  158278. ** output variable during stage 1 is undefined.
  158279. */
  158280. SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int *pnTwo);
  158281. /*
  158282. ** Obtain an indication as to the current stage of an RBU update or vacuum.
  158283. ** This function always returns one of the SQLITE_RBU_STATE_XXX constants
  158284. ** defined in this file. Return values should be interpreted as follows:
  158285. **
  158286. ** SQLITE_RBU_STATE_OAL:
  158287. ** RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
  158288. ** may either add further data to the *-oal file, or compute data that will
  158289. ** be added by a subsequent call.
  158290. **
  158291. ** SQLITE_RBU_STATE_MOVE:
  158292. ** RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
  158293. ** will move the *-oal file to the equivalent *-wal path. If the current
  158294. ** operation is an RBU update, then the updated version of the database
  158295. ** file will become visible to ordinary SQLite clients following the next
  158296. ** call to sqlite3rbu_step().
  158297. **
  158298. ** SQLITE_RBU_STATE_CHECKPOINT:
  158299. ** RBU is currently performing an incremental checkpoint. The next call to
  158300. ** sqlite3rbu_step() will copy a page of data from the *-wal file into
  158301. ** the target database file.
  158302. **
  158303. ** SQLITE_RBU_STATE_DONE:
  158304. ** The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
  158305. ** will immediately return SQLITE_DONE.
  158306. **
  158307. ** SQLITE_RBU_STATE_ERROR:
  158308. ** An error has occurred. Any subsequent calls to sqlite3rbu_step() will
  158309. ** immediately return the SQLite error code associated with the error.
  158310. */
  158311. #define SQLITE_RBU_STATE_OAL 1
  158312. #define SQLITE_RBU_STATE_MOVE 2
  158313. #define SQLITE_RBU_STATE_CHECKPOINT 3
  158314. #define SQLITE_RBU_STATE_DONE 4
  158315. #define SQLITE_RBU_STATE_ERROR 5
  158316. SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
  158317. /*
  158318. ** Create an RBU VFS named zName that accesses the underlying file-system
  158319. ** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
  158320. ** then the new RBU VFS uses the default system VFS to access the file-system.
  158321. ** The new object is registered as a non-default VFS with SQLite before
  158322. ** returning.
  158323. **
  158324. ** Part of the RBU implementation uses a custom VFS object. Usually, this
  158325. ** object is created and deleted automatically by RBU.
  158326. **
  158327. ** The exception is for applications that also use zipvfs. In this case,
  158328. ** the custom VFS must be explicitly created by the user before the RBU
  158329. ** handle is opened. The RBU VFS should be installed so that the zipvfs
  158330. ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
  158331. ** (for example multiplexor) to access the file-system. For example,
  158332. ** to assemble an RBU enabled VFS stack that uses both zipvfs and
  158333. ** multiplexor (error checking omitted):
  158334. **
  158335. ** // Create a VFS named "multiplex" (not the default).
  158336. ** sqlite3_multiplex_initialize(0, 0);
  158337. **
  158338. ** // Create an rbu VFS named "rbu" that uses multiplexor. If the
  158339. ** // second argument were replaced with NULL, the "rbu" VFS would
  158340. ** // access the file-system via the system default VFS, bypassing the
  158341. ** // multiplexor.
  158342. ** sqlite3rbu_create_vfs("rbu", "multiplex");
  158343. **
  158344. ** // Create a zipvfs VFS named "zipvfs" that uses rbu.
  158345. ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
  158346. **
  158347. ** // Make zipvfs the default VFS.
  158348. ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
  158349. **
  158350. ** Because the default VFS created above includes a RBU functionality, it
  158351. ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
  158352. ** that does not include the RBU layer results in an error.
  158353. **
  158354. ** The overhead of adding the "rbu" VFS to the system is negligible for
  158355. ** non-RBU users. There is no harm in an application accessing the
  158356. ** file-system via "rbu" all the time, even if it only uses RBU functionality
  158357. ** occasionally.
  158358. */
  158359. SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
  158360. /*
  158361. ** Deregister and destroy an RBU vfs created by an earlier call to
  158362. ** sqlite3rbu_create_vfs().
  158363. **
  158364. ** VFS objects are not reference counted. If a VFS object is destroyed
  158365. ** before all database handles that use it have been closed, the results
  158366. ** are undefined.
  158367. */
  158368. SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
  158369. #if 0
  158370. } /* end of the 'extern "C"' block */
  158371. #endif
  158372. #endif /* _SQLITE3RBU_H */
  158373. /************** End of sqlite3rbu.h ******************************************/
  158374. /************** Continuing where we left off in sqlite3rbu.c *****************/
  158375. #if defined(_WIN32_WCE)
  158376. /* #include "windows.h" */
  158377. #endif
  158378. /* Maximum number of prepared UPDATE statements held by this module */
  158379. #define SQLITE_RBU_UPDATE_CACHESIZE 16
  158380. /*
  158381. ** Swap two objects of type TYPE.
  158382. */
  158383. #if !defined(SQLITE_AMALGAMATION)
  158384. # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  158385. #endif
  158386. /*
  158387. ** The rbu_state table is used to save the state of a partially applied
  158388. ** update so that it can be resumed later. The table consists of integer
  158389. ** keys mapped to values as follows:
  158390. **
  158391. ** RBU_STATE_STAGE:
  158392. ** May be set to integer values 1, 2, 4 or 5. As follows:
  158393. ** 1: the *-rbu file is currently under construction.
  158394. ** 2: the *-rbu file has been constructed, but not yet moved
  158395. ** to the *-wal path.
  158396. ** 4: the checkpoint is underway.
  158397. ** 5: the rbu update has been checkpointed.
  158398. **
  158399. ** RBU_STATE_TBL:
  158400. ** Only valid if STAGE==1. The target database name of the table
  158401. ** currently being written.
  158402. **
  158403. ** RBU_STATE_IDX:
  158404. ** Only valid if STAGE==1. The target database name of the index
  158405. ** currently being written, or NULL if the main table is currently being
  158406. ** updated.
  158407. **
  158408. ** RBU_STATE_ROW:
  158409. ** Only valid if STAGE==1. Number of rows already processed for the current
  158410. ** table/index.
  158411. **
  158412. ** RBU_STATE_PROGRESS:
  158413. ** Trbul number of sqlite3rbu_step() calls made so far as part of this
  158414. ** rbu update.
  158415. **
  158416. ** RBU_STATE_CKPT:
  158417. ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
  158418. ** header created by recovering the *-wal file. This is used to detect
  158419. ** cases when another client appends frames to the *-wal file in the
  158420. ** middle of an incremental checkpoint (an incremental checkpoint cannot
  158421. ** be continued if this happens).
  158422. **
  158423. ** RBU_STATE_COOKIE:
  158424. ** Valid if STAGE==1. The current change-counter cookie value in the
  158425. ** target db file.
  158426. **
  158427. ** RBU_STATE_OALSZ:
  158428. ** Valid if STAGE==1. The size in bytes of the *-oal file.
  158429. */
  158430. #define RBU_STATE_STAGE 1
  158431. #define RBU_STATE_TBL 2
  158432. #define RBU_STATE_IDX 3
  158433. #define RBU_STATE_ROW 4
  158434. #define RBU_STATE_PROGRESS 5
  158435. #define RBU_STATE_CKPT 6
  158436. #define RBU_STATE_COOKIE 7
  158437. #define RBU_STATE_OALSZ 8
  158438. #define RBU_STATE_PHASEONESTEP 9
  158439. #define RBU_STAGE_OAL 1
  158440. #define RBU_STAGE_MOVE 2
  158441. #define RBU_STAGE_CAPTURE 3
  158442. #define RBU_STAGE_CKPT 4
  158443. #define RBU_STAGE_DONE 5
  158444. #define RBU_CREATE_STATE \
  158445. "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
  158446. typedef struct RbuFrame RbuFrame;
  158447. typedef struct RbuObjIter RbuObjIter;
  158448. typedef struct RbuState RbuState;
  158449. typedef struct rbu_vfs rbu_vfs;
  158450. typedef struct rbu_file rbu_file;
  158451. typedef struct RbuUpdateStmt RbuUpdateStmt;
  158452. #if !defined(SQLITE_AMALGAMATION)
  158453. typedef unsigned int u32;
  158454. typedef unsigned short u16;
  158455. typedef unsigned char u8;
  158456. typedef sqlite3_int64 i64;
  158457. #endif
  158458. /*
  158459. ** These values must match the values defined in wal.c for the equivalent
  158460. ** locks. These are not magic numbers as they are part of the SQLite file
  158461. ** format.
  158462. */
  158463. #define WAL_LOCK_WRITE 0
  158464. #define WAL_LOCK_CKPT 1
  158465. #define WAL_LOCK_READ0 3
  158466. #define SQLITE_FCNTL_RBUCNT 5149216
  158467. /*
  158468. ** A structure to store values read from the rbu_state table in memory.
  158469. */
  158470. struct RbuState {
  158471. int eStage;
  158472. char *zTbl;
  158473. char *zIdx;
  158474. i64 iWalCksum;
  158475. int nRow;
  158476. i64 nProgress;
  158477. u32 iCookie;
  158478. i64 iOalSz;
  158479. i64 nPhaseOneStep;
  158480. };
  158481. struct RbuUpdateStmt {
  158482. char *zMask; /* Copy of update mask used with pUpdate */
  158483. sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
  158484. RbuUpdateStmt *pNext;
  158485. };
  158486. /*
  158487. ** An iterator of this type is used to iterate through all objects in
  158488. ** the target database that require updating. For each such table, the
  158489. ** iterator visits, in order:
  158490. **
  158491. ** * the table itself,
  158492. ** * each index of the table (zero or more points to visit), and
  158493. ** * a special "cleanup table" state.
  158494. **
  158495. ** abIndexed:
  158496. ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
  158497. ** it points to an array of flags nTblCol elements in size. The flag is
  158498. ** set for each column that is either a part of the PK or a part of an
  158499. ** index. Or clear otherwise.
  158500. **
  158501. */
  158502. struct RbuObjIter {
  158503. sqlite3_stmt *pTblIter; /* Iterate through tables */
  158504. sqlite3_stmt *pIdxIter; /* Index iterator */
  158505. int nTblCol; /* Size of azTblCol[] array */
  158506. char **azTblCol; /* Array of unquoted target column names */
  158507. char **azTblType; /* Array of target column types */
  158508. int *aiSrcOrder; /* src table col -> target table col */
  158509. u8 *abTblPk; /* Array of flags, set on target PK columns */
  158510. u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
  158511. u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
  158512. int eType; /* Table type - an RBU_PK_XXX value */
  158513. /* Output variables. zTbl==0 implies EOF. */
  158514. int bCleanup; /* True in "cleanup" state */
  158515. const char *zTbl; /* Name of target db table */
  158516. const char *zDataTbl; /* Name of rbu db table (or null) */
  158517. const char *zIdx; /* Name of target db index (or null) */
  158518. int iTnum; /* Root page of current object */
  158519. int iPkTnum; /* If eType==EXTERNAL, root of PK index */
  158520. int bUnique; /* Current index is unique */
  158521. int nIndex; /* Number of aux. indexes on table zTbl */
  158522. /* Statements created by rbuObjIterPrepareAll() */
  158523. int nCol; /* Number of columns in current object */
  158524. sqlite3_stmt *pSelect; /* Source data */
  158525. sqlite3_stmt *pInsert; /* Statement for INSERT operations */
  158526. sqlite3_stmt *pDelete; /* Statement for DELETE ops */
  158527. sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */
  158528. /* Last UPDATE used (for PK b-tree updates only), or NULL. */
  158529. RbuUpdateStmt *pRbuUpdate;
  158530. };
  158531. /*
  158532. ** Values for RbuObjIter.eType
  158533. **
  158534. ** 0: Table does not exist (error)
  158535. ** 1: Table has an implicit rowid.
  158536. ** 2: Table has an explicit IPK column.
  158537. ** 3: Table has an external PK index.
  158538. ** 4: Table is WITHOUT ROWID.
  158539. ** 5: Table is a virtual table.
  158540. */
  158541. #define RBU_PK_NOTABLE 0
  158542. #define RBU_PK_NONE 1
  158543. #define RBU_PK_IPK 2
  158544. #define RBU_PK_EXTERNAL 3
  158545. #define RBU_PK_WITHOUT_ROWID 4
  158546. #define RBU_PK_VTAB 5
  158547. /*
  158548. ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
  158549. ** one of the following operations.
  158550. */
  158551. #define RBU_INSERT 1 /* Insert on a main table b-tree */
  158552. #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
  158553. #define RBU_REPLACE 3 /* Delete and then insert a row */
  158554. #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */
  158555. #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */
  158556. #define RBU_UPDATE 6 /* Update a row in a main table b-tree */
  158557. /*
  158558. ** A single step of an incremental checkpoint - frame iWalFrame of the wal
  158559. ** file should be copied to page iDbPage of the database file.
  158560. */
  158561. struct RbuFrame {
  158562. u32 iDbPage;
  158563. u32 iWalFrame;
  158564. };
  158565. /*
  158566. ** RBU handle.
  158567. **
  158568. ** nPhaseOneStep:
  158569. ** If the RBU database contains an rbu_count table, this value is set to
  158570. ** a running estimate of the number of b-tree operations required to
  158571. ** finish populating the *-oal file. This allows the sqlite3_bp_progress()
  158572. ** API to calculate the permyriadage progress of populating the *-oal file
  158573. ** using the formula:
  158574. **
  158575. ** permyriadage = (10000 * nProgress) / nPhaseOneStep
  158576. **
  158577. ** nPhaseOneStep is initialized to the sum of:
  158578. **
  158579. ** nRow * (nIndex + 1)
  158580. **
  158581. ** for all source tables in the RBU database, where nRow is the number
  158582. ** of rows in the source table and nIndex the number of indexes on the
  158583. ** corresponding target database table.
  158584. **
  158585. ** This estimate is accurate if the RBU update consists entirely of
  158586. ** INSERT operations. However, it is inaccurate if:
  158587. **
  158588. ** * the RBU update contains any UPDATE operations. If the PK specified
  158589. ** for an UPDATE operation does not exist in the target table, then
  158590. ** no b-tree operations are required on index b-trees. Or if the
  158591. ** specified PK does exist, then (nIndex*2) such operations are
  158592. ** required (one delete and one insert on each index b-tree).
  158593. **
  158594. ** * the RBU update contains any DELETE operations for which the specified
  158595. ** PK does not exist. In this case no operations are required on index
  158596. ** b-trees.
  158597. **
  158598. ** * the RBU update contains REPLACE operations. These are similar to
  158599. ** UPDATE operations.
  158600. **
  158601. ** nPhaseOneStep is updated to account for the conditions above during the
  158602. ** first pass of each source table. The updated nPhaseOneStep value is
  158603. ** stored in the rbu_state table if the RBU update is suspended.
  158604. */
  158605. struct sqlite3rbu {
  158606. int eStage; /* Value of RBU_STATE_STAGE field */
  158607. sqlite3 *dbMain; /* target database handle */
  158608. sqlite3 *dbRbu; /* rbu database handle */
  158609. char *zTarget; /* Path to target db */
  158610. char *zRbu; /* Path to rbu db */
  158611. char *zState; /* Path to state db (or NULL if zRbu) */
  158612. char zStateDb[5]; /* Db name for state ("stat" or "main") */
  158613. int rc; /* Value returned by last rbu_step() call */
  158614. char *zErrmsg; /* Error message if rc!=SQLITE_OK */
  158615. int nStep; /* Rows processed for current object */
  158616. int nProgress; /* Rows processed for all objects */
  158617. RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
  158618. const char *zVfsName; /* Name of automatically created rbu vfs */
  158619. rbu_file *pTargetFd; /* File handle open on target db */
  158620. int nPagePerSector; /* Pages per sector for pTargetFd */
  158621. i64 iOalSz;
  158622. i64 nPhaseOneStep;
  158623. /* The following state variables are used as part of the incremental
  158624. ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
  158625. ** function rbuSetupCheckpoint() for details. */
  158626. u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
  158627. u32 mLock;
  158628. int nFrame; /* Entries in aFrame[] array */
  158629. int nFrameAlloc; /* Allocated size of aFrame[] array */
  158630. RbuFrame *aFrame;
  158631. int pgsz;
  158632. u8 *aBuf;
  158633. i64 iWalCksum;
  158634. /* Used in RBU vacuum mode only */
  158635. int nRbu; /* Number of RBU VFS in the stack */
  158636. rbu_file *pRbuFd; /* Fd for main db of dbRbu */
  158637. };
  158638. /*
  158639. ** An rbu VFS is implemented using an instance of this structure.
  158640. */
  158641. struct rbu_vfs {
  158642. sqlite3_vfs base; /* rbu VFS shim methods */
  158643. sqlite3_vfs *pRealVfs; /* Underlying VFS */
  158644. sqlite3_mutex *mutex; /* Mutex to protect pMain */
  158645. rbu_file *pMain; /* Linked list of main db files */
  158646. };
  158647. /*
  158648. ** Each file opened by an rbu VFS is represented by an instance of
  158649. ** the following structure.
  158650. */
  158651. struct rbu_file {
  158652. sqlite3_file base; /* sqlite3_file methods */
  158653. sqlite3_file *pReal; /* Underlying file handle */
  158654. rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
  158655. sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
  158656. int openFlags; /* Flags this file was opened with */
  158657. u32 iCookie; /* Cookie value for main db files */
  158658. u8 iWriteVer; /* "write-version" value for main db files */
  158659. u8 bNolock; /* True to fail EXCLUSIVE locks */
  158660. int nShm; /* Number of entries in apShm[] array */
  158661. char **apShm; /* Array of mmap'd *-shm regions */
  158662. char *zDel; /* Delete this when closing file */
  158663. const char *zWal; /* Wal filename for this main db file */
  158664. rbu_file *pWalFd; /* Wal file descriptor for this main db */
  158665. rbu_file *pMainNext; /* Next MAIN_DB file */
  158666. };
  158667. /*
  158668. ** True for an RBU vacuum handle, or false otherwise.
  158669. */
  158670. #define rbuIsVacuum(p) ((p)->zTarget==0)
  158671. /*************************************************************************
  158672. ** The following three functions, found below:
  158673. **
  158674. ** rbuDeltaGetInt()
  158675. ** rbuDeltaChecksum()
  158676. ** rbuDeltaApply()
  158677. **
  158678. ** are lifted from the fossil source code (http://fossil-scm.org). They
  158679. ** are used to implement the scalar SQL function rbu_fossil_delta().
  158680. */
  158681. /*
  158682. ** Read bytes from *pz and convert them into a positive integer. When
  158683. ** finished, leave *pz pointing to the first character past the end of
  158684. ** the integer. The *pLen parameter holds the length of the string
  158685. ** in *pz and is decremented once for each character in the integer.
  158686. */
  158687. static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
  158688. static const signed char zValue[] = {
  158689. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  158690. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  158691. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  158692. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  158693. -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
  158694. 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
  158695. -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  158696. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
  158697. };
  158698. unsigned int v = 0;
  158699. int c;
  158700. unsigned char *z = (unsigned char*)*pz;
  158701. unsigned char *zStart = z;
  158702. while( (c = zValue[0x7f&*(z++)])>=0 ){
  158703. v = (v<<6) + c;
  158704. }
  158705. z--;
  158706. *pLen -= z - zStart;
  158707. *pz = (char*)z;
  158708. return v;
  158709. }
  158710. /*
  158711. ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
  158712. */
  158713. static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
  158714. const unsigned char *z = (const unsigned char *)zIn;
  158715. unsigned sum0 = 0;
  158716. unsigned sum1 = 0;
  158717. unsigned sum2 = 0;
  158718. unsigned sum3 = 0;
  158719. while(N >= 16){
  158720. sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
  158721. sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
  158722. sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
  158723. sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
  158724. z += 16;
  158725. N -= 16;
  158726. }
  158727. while(N >= 4){
  158728. sum0 += z[0];
  158729. sum1 += z[1];
  158730. sum2 += z[2];
  158731. sum3 += z[3];
  158732. z += 4;
  158733. N -= 4;
  158734. }
  158735. sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
  158736. switch(N){
  158737. case 3: sum3 += (z[2] << 8);
  158738. case 2: sum3 += (z[1] << 16);
  158739. case 1: sum3 += (z[0] << 24);
  158740. default: ;
  158741. }
  158742. return sum3;
  158743. }
  158744. /*
  158745. ** Apply a delta.
  158746. **
  158747. ** The output buffer should be big enough to hold the whole output
  158748. ** file and a NUL terminator at the end. The delta_output_size()
  158749. ** routine will determine this size for you.
  158750. **
  158751. ** The delta string should be null-terminated. But the delta string
  158752. ** may contain embedded NUL characters (if the input and output are
  158753. ** binary files) so we also have to pass in the length of the delta in
  158754. ** the lenDelta parameter.
  158755. **
  158756. ** This function returns the size of the output file in bytes (excluding
  158757. ** the final NUL terminator character). Except, if the delta string is
  158758. ** malformed or intended for use with a source file other than zSrc,
  158759. ** then this routine returns -1.
  158760. **
  158761. ** Refer to the delta_create() documentation above for a description
  158762. ** of the delta file format.
  158763. */
  158764. static int rbuDeltaApply(
  158765. const char *zSrc, /* The source or pattern file */
  158766. int lenSrc, /* Length of the source file */
  158767. const char *zDelta, /* Delta to apply to the pattern */
  158768. int lenDelta, /* Length of the delta */
  158769. char *zOut /* Write the output into this preallocated buffer */
  158770. ){
  158771. unsigned int limit;
  158772. unsigned int total = 0;
  158773. #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
  158774. char *zOrigOut = zOut;
  158775. #endif
  158776. limit = rbuDeltaGetInt(&zDelta, &lenDelta);
  158777. if( *zDelta!='\n' ){
  158778. /* ERROR: size integer not terminated by "\n" */
  158779. return -1;
  158780. }
  158781. zDelta++; lenDelta--;
  158782. while( *zDelta && lenDelta>0 ){
  158783. unsigned int cnt, ofst;
  158784. cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
  158785. switch( zDelta[0] ){
  158786. case '@': {
  158787. zDelta++; lenDelta--;
  158788. ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
  158789. if( lenDelta>0 && zDelta[0]!=',' ){
  158790. /* ERROR: copy command not terminated by ',' */
  158791. return -1;
  158792. }
  158793. zDelta++; lenDelta--;
  158794. total += cnt;
  158795. if( total>limit ){
  158796. /* ERROR: copy exceeds output file size */
  158797. return -1;
  158798. }
  158799. if( (int)(ofst+cnt) > lenSrc ){
  158800. /* ERROR: copy extends past end of input */
  158801. return -1;
  158802. }
  158803. memcpy(zOut, &zSrc[ofst], cnt);
  158804. zOut += cnt;
  158805. break;
  158806. }
  158807. case ':': {
  158808. zDelta++; lenDelta--;
  158809. total += cnt;
  158810. if( total>limit ){
  158811. /* ERROR: insert command gives an output larger than predicted */
  158812. return -1;
  158813. }
  158814. if( (int)cnt>lenDelta ){
  158815. /* ERROR: insert count exceeds size of delta */
  158816. return -1;
  158817. }
  158818. memcpy(zOut, zDelta, cnt);
  158819. zOut += cnt;
  158820. zDelta += cnt;
  158821. lenDelta -= cnt;
  158822. break;
  158823. }
  158824. case ';': {
  158825. zDelta++; lenDelta--;
  158826. zOut[0] = 0;
  158827. #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
  158828. if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
  158829. /* ERROR: bad checksum */
  158830. return -1;
  158831. }
  158832. #endif
  158833. if( total!=limit ){
  158834. /* ERROR: generated size does not match predicted size */
  158835. return -1;
  158836. }
  158837. return total;
  158838. }
  158839. default: {
  158840. /* ERROR: unknown delta operator */
  158841. return -1;
  158842. }
  158843. }
  158844. }
  158845. /* ERROR: unterminated delta */
  158846. return -1;
  158847. }
  158848. static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
  158849. int size;
  158850. size = rbuDeltaGetInt(&zDelta, &lenDelta);
  158851. if( *zDelta!='\n' ){
  158852. /* ERROR: size integer not terminated by "\n" */
  158853. return -1;
  158854. }
  158855. return size;
  158856. }
  158857. /*
  158858. ** End of code taken from fossil.
  158859. *************************************************************************/
  158860. /*
  158861. ** Implementation of SQL scalar function rbu_fossil_delta().
  158862. **
  158863. ** This function applies a fossil delta patch to a blob. Exactly two
  158864. ** arguments must be passed to this function. The first is the blob to
  158865. ** patch and the second the patch to apply. If no error occurs, this
  158866. ** function returns the patched blob.
  158867. */
  158868. static void rbuFossilDeltaFunc(
  158869. sqlite3_context *context,
  158870. int argc,
  158871. sqlite3_value **argv
  158872. ){
  158873. const char *aDelta;
  158874. int nDelta;
  158875. const char *aOrig;
  158876. int nOrig;
  158877. int nOut;
  158878. int nOut2;
  158879. char *aOut;
  158880. assert( argc==2 );
  158881. nOrig = sqlite3_value_bytes(argv[0]);
  158882. aOrig = (const char*)sqlite3_value_blob(argv[0]);
  158883. nDelta = sqlite3_value_bytes(argv[1]);
  158884. aDelta = (const char*)sqlite3_value_blob(argv[1]);
  158885. /* Figure out the size of the output */
  158886. nOut = rbuDeltaOutputSize(aDelta, nDelta);
  158887. if( nOut<0 ){
  158888. sqlite3_result_error(context, "corrupt fossil delta", -1);
  158889. return;
  158890. }
  158891. aOut = sqlite3_malloc(nOut+1);
  158892. if( aOut==0 ){
  158893. sqlite3_result_error_nomem(context);
  158894. }else{
  158895. nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
  158896. if( nOut2!=nOut ){
  158897. sqlite3_result_error(context, "corrupt fossil delta", -1);
  158898. }else{
  158899. sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
  158900. }
  158901. }
  158902. }
  158903. /*
  158904. ** Prepare the SQL statement in buffer zSql against database handle db.
  158905. ** If successful, set *ppStmt to point to the new statement and return
  158906. ** SQLITE_OK.
  158907. **
  158908. ** Otherwise, if an error does occur, set *ppStmt to NULL and return
  158909. ** an SQLite error code. Additionally, set output variable *pzErrmsg to
  158910. ** point to a buffer containing an error message. It is the responsibility
  158911. ** of the caller to (eventually) free this buffer using sqlite3_free().
  158912. */
  158913. static int prepareAndCollectError(
  158914. sqlite3 *db,
  158915. sqlite3_stmt **ppStmt,
  158916. char **pzErrmsg,
  158917. const char *zSql
  158918. ){
  158919. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  158920. if( rc!=SQLITE_OK ){
  158921. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  158922. *ppStmt = 0;
  158923. }
  158924. return rc;
  158925. }
  158926. /*
  158927. ** Reset the SQL statement passed as the first argument. Return a copy
  158928. ** of the value returned by sqlite3_reset().
  158929. **
  158930. ** If an error has occurred, then set *pzErrmsg to point to a buffer
  158931. ** containing an error message. It is the responsibility of the caller
  158932. ** to eventually free this buffer using sqlite3_free().
  158933. */
  158934. static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
  158935. int rc = sqlite3_reset(pStmt);
  158936. if( rc!=SQLITE_OK ){
  158937. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
  158938. }
  158939. return rc;
  158940. }
  158941. /*
  158942. ** Unless it is NULL, argument zSql points to a buffer allocated using
  158943. ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
  158944. ** statement against database db and frees the buffer. If statement
  158945. ** compilation is successful, *ppStmt is set to point to the new statement
  158946. ** handle and SQLITE_OK is returned.
  158947. **
  158948. ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
  158949. ** returned. In this case, *pzErrmsg may also be set to point to an error
  158950. ** message. It is the responsibility of the caller to free this error message
  158951. ** buffer using sqlite3_free().
  158952. **
  158953. ** If argument zSql is NULL, this function assumes that an OOM has occurred.
  158954. ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
  158955. */
  158956. static int prepareFreeAndCollectError(
  158957. sqlite3 *db,
  158958. sqlite3_stmt **ppStmt,
  158959. char **pzErrmsg,
  158960. char *zSql
  158961. ){
  158962. int rc;
  158963. assert( *pzErrmsg==0 );
  158964. if( zSql==0 ){
  158965. rc = SQLITE_NOMEM;
  158966. *ppStmt = 0;
  158967. }else{
  158968. rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
  158969. sqlite3_free(zSql);
  158970. }
  158971. return rc;
  158972. }
  158973. /*
  158974. ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
  158975. ** by an earlier call to rbuObjIterCacheTableInfo().
  158976. */
  158977. static void rbuObjIterFreeCols(RbuObjIter *pIter){
  158978. int i;
  158979. for(i=0; i<pIter->nTblCol; i++){
  158980. sqlite3_free(pIter->azTblCol[i]);
  158981. sqlite3_free(pIter->azTblType[i]);
  158982. }
  158983. sqlite3_free(pIter->azTblCol);
  158984. pIter->azTblCol = 0;
  158985. pIter->azTblType = 0;
  158986. pIter->aiSrcOrder = 0;
  158987. pIter->abTblPk = 0;
  158988. pIter->abNotNull = 0;
  158989. pIter->nTblCol = 0;
  158990. pIter->eType = 0; /* Invalid value */
  158991. }
  158992. /*
  158993. ** Finalize all statements and free all allocations that are specific to
  158994. ** the current object (table/index pair).
  158995. */
  158996. static void rbuObjIterClearStatements(RbuObjIter *pIter){
  158997. RbuUpdateStmt *pUp;
  158998. sqlite3_finalize(pIter->pSelect);
  158999. sqlite3_finalize(pIter->pInsert);
  159000. sqlite3_finalize(pIter->pDelete);
  159001. sqlite3_finalize(pIter->pTmpInsert);
  159002. pUp = pIter->pRbuUpdate;
  159003. while( pUp ){
  159004. RbuUpdateStmt *pTmp = pUp->pNext;
  159005. sqlite3_finalize(pUp->pUpdate);
  159006. sqlite3_free(pUp);
  159007. pUp = pTmp;
  159008. }
  159009. pIter->pSelect = 0;
  159010. pIter->pInsert = 0;
  159011. pIter->pDelete = 0;
  159012. pIter->pRbuUpdate = 0;
  159013. pIter->pTmpInsert = 0;
  159014. pIter->nCol = 0;
  159015. }
  159016. /*
  159017. ** Clean up any resources allocated as part of the iterator object passed
  159018. ** as the only argument.
  159019. */
  159020. static void rbuObjIterFinalize(RbuObjIter *pIter){
  159021. rbuObjIterClearStatements(pIter);
  159022. sqlite3_finalize(pIter->pTblIter);
  159023. sqlite3_finalize(pIter->pIdxIter);
  159024. rbuObjIterFreeCols(pIter);
  159025. memset(pIter, 0, sizeof(RbuObjIter));
  159026. }
  159027. /*
  159028. ** Advance the iterator to the next position.
  159029. **
  159030. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  159031. ** pointing to the next entry. Otherwise, an error code and message is
  159032. ** left in the RBU handle passed as the first argument. A copy of the
  159033. ** error code is returned.
  159034. */
  159035. static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
  159036. int rc = p->rc;
  159037. if( rc==SQLITE_OK ){
  159038. /* Free any SQLite statements used while processing the previous object */
  159039. rbuObjIterClearStatements(pIter);
  159040. if( pIter->zIdx==0 ){
  159041. rc = sqlite3_exec(p->dbMain,
  159042. "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
  159043. "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
  159044. "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
  159045. "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
  159046. , 0, 0, &p->zErrmsg
  159047. );
  159048. }
  159049. if( rc==SQLITE_OK ){
  159050. if( pIter->bCleanup ){
  159051. rbuObjIterFreeCols(pIter);
  159052. pIter->bCleanup = 0;
  159053. rc = sqlite3_step(pIter->pTblIter);
  159054. if( rc!=SQLITE_ROW ){
  159055. rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
  159056. pIter->zTbl = 0;
  159057. }else{
  159058. pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
  159059. pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
  159060. rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
  159061. }
  159062. }else{
  159063. if( pIter->zIdx==0 ){
  159064. sqlite3_stmt *pIdx = pIter->pIdxIter;
  159065. rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
  159066. }
  159067. if( rc==SQLITE_OK ){
  159068. rc = sqlite3_step(pIter->pIdxIter);
  159069. if( rc!=SQLITE_ROW ){
  159070. rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
  159071. pIter->bCleanup = 1;
  159072. pIter->zIdx = 0;
  159073. }else{
  159074. pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
  159075. pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
  159076. pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
  159077. rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
  159078. }
  159079. }
  159080. }
  159081. }
  159082. }
  159083. if( rc!=SQLITE_OK ){
  159084. rbuObjIterFinalize(pIter);
  159085. p->rc = rc;
  159086. }
  159087. return rc;
  159088. }
  159089. /*
  159090. ** The implementation of the rbu_target_name() SQL function. This function
  159091. ** accepts one or two arguments. The first argument is the name of a table -
  159092. ** the name of a table in the RBU database. The second, if it is present, is 1
  159093. ** for a view or 0 for a table.
  159094. **
  159095. ** For a non-vacuum RBU handle, if the table name matches the pattern:
  159096. **
  159097. ** data[0-9]_<name>
  159098. **
  159099. ** where <name> is any sequence of 1 or more characters, <name> is returned.
  159100. ** Otherwise, if the only argument does not match the above pattern, an SQL
  159101. ** NULL is returned.
  159102. **
  159103. ** "data_t1" -> "t1"
  159104. ** "data0123_t2" -> "t2"
  159105. ** "dataAB_t3" -> NULL
  159106. **
  159107. ** For an rbu vacuum handle, a copy of the first argument is returned if
  159108. ** the second argument is either missing or 0 (not a view).
  159109. */
  159110. static void rbuTargetNameFunc(
  159111. sqlite3_context *pCtx,
  159112. int argc,
  159113. sqlite3_value **argv
  159114. ){
  159115. sqlite3rbu *p = sqlite3_user_data(pCtx);
  159116. const char *zIn;
  159117. assert( argc==1 || argc==2 );
  159118. zIn = (const char*)sqlite3_value_text(argv[0]);
  159119. if( zIn ){
  159120. if( rbuIsVacuum(p) ){
  159121. if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
  159122. sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
  159123. }
  159124. }else{
  159125. if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
  159126. int i;
  159127. for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
  159128. if( zIn[i]=='_' && zIn[i+1] ){
  159129. sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
  159130. }
  159131. }
  159132. }
  159133. }
  159134. }
  159135. /*
  159136. ** Initialize the iterator structure passed as the second argument.
  159137. **
  159138. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  159139. ** pointing to the first entry. Otherwise, an error code and message is
  159140. ** left in the RBU handle passed as the first argument. A copy of the
  159141. ** error code is returned.
  159142. */
  159143. static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
  159144. int rc;
  159145. memset(pIter, 0, sizeof(RbuObjIter));
  159146. rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
  159147. sqlite3_mprintf(
  159148. "SELECT rbu_target_name(name, type='view') AS target, name "
  159149. "FROM sqlite_master "
  159150. "WHERE type IN ('table', 'view') AND target IS NOT NULL "
  159151. " %s "
  159152. "ORDER BY name"
  159153. , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
  159154. if( rc==SQLITE_OK ){
  159155. rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
  159156. "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
  159157. " FROM main.sqlite_master "
  159158. " WHERE type='index' AND tbl_name = ?"
  159159. );
  159160. }
  159161. pIter->bCleanup = 1;
  159162. p->rc = rc;
  159163. return rbuObjIterNext(p, pIter);
  159164. }
  159165. /*
  159166. ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
  159167. ** an error code is stored in the RBU handle passed as the first argument.
  159168. **
  159169. ** If an error has already occurred (p->rc is already set to something other
  159170. ** than SQLITE_OK), then this function returns NULL without modifying the
  159171. ** stored error code. In this case it still calls sqlite3_free() on any
  159172. ** printf() parameters associated with %z conversions.
  159173. */
  159174. static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
  159175. char *zSql = 0;
  159176. va_list ap;
  159177. va_start(ap, zFmt);
  159178. zSql = sqlite3_vmprintf(zFmt, ap);
  159179. if( p->rc==SQLITE_OK ){
  159180. if( zSql==0 ) p->rc = SQLITE_NOMEM;
  159181. }else{
  159182. sqlite3_free(zSql);
  159183. zSql = 0;
  159184. }
  159185. va_end(ap);
  159186. return zSql;
  159187. }
  159188. /*
  159189. ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
  159190. ** arguments are the usual subsitution values. This function performs
  159191. ** the printf() style substitutions and executes the result as an SQL
  159192. ** statement on the RBU handles database.
  159193. **
  159194. ** If an error occurs, an error code and error message is stored in the
  159195. ** RBU handle. If an error has already occurred when this function is
  159196. ** called, it is a no-op.
  159197. */
  159198. static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
  159199. va_list ap;
  159200. char *zSql;
  159201. va_start(ap, zFmt);
  159202. zSql = sqlite3_vmprintf(zFmt, ap);
  159203. if( p->rc==SQLITE_OK ){
  159204. if( zSql==0 ){
  159205. p->rc = SQLITE_NOMEM;
  159206. }else{
  159207. p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
  159208. }
  159209. }
  159210. sqlite3_free(zSql);
  159211. va_end(ap);
  159212. return p->rc;
  159213. }
  159214. /*
  159215. ** Attempt to allocate and return a pointer to a zeroed block of nByte
  159216. ** bytes.
  159217. **
  159218. ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
  159219. ** error code in the rbu handle passed as the first argument. Or, if an
  159220. ** error has already occurred when this function is called, return NULL
  159221. ** immediately without attempting the allocation or modifying the stored
  159222. ** error code.
  159223. */
  159224. static void *rbuMalloc(sqlite3rbu *p, int nByte){
  159225. void *pRet = 0;
  159226. if( p->rc==SQLITE_OK ){
  159227. assert( nByte>0 );
  159228. pRet = sqlite3_malloc64(nByte);
  159229. if( pRet==0 ){
  159230. p->rc = SQLITE_NOMEM;
  159231. }else{
  159232. memset(pRet, 0, nByte);
  159233. }
  159234. }
  159235. return pRet;
  159236. }
  159237. /*
  159238. ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
  159239. ** there is room for at least nCol elements. If an OOM occurs, store an
  159240. ** error code in the RBU handle passed as the first argument.
  159241. */
  159242. static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
  159243. int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
  159244. char **azNew;
  159245. azNew = (char**)rbuMalloc(p, nByte);
  159246. if( azNew ){
  159247. pIter->azTblCol = azNew;
  159248. pIter->azTblType = &azNew[nCol];
  159249. pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
  159250. pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
  159251. pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
  159252. pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
  159253. }
  159254. }
  159255. /*
  159256. ** The first argument must be a nul-terminated string. This function
  159257. ** returns a copy of the string in memory obtained from sqlite3_malloc().
  159258. ** It is the responsibility of the caller to eventually free this memory
  159259. ** using sqlite3_free().
  159260. **
  159261. ** If an OOM condition is encountered when attempting to allocate memory,
  159262. ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
  159263. ** if the allocation succeeds, (*pRc) is left unchanged.
  159264. */
  159265. static char *rbuStrndup(const char *zStr, int *pRc){
  159266. char *zRet = 0;
  159267. assert( *pRc==SQLITE_OK );
  159268. if( zStr ){
  159269. size_t nCopy = strlen(zStr) + 1;
  159270. zRet = (char*)sqlite3_malloc64(nCopy);
  159271. if( zRet ){
  159272. memcpy(zRet, zStr, nCopy);
  159273. }else{
  159274. *pRc = SQLITE_NOMEM;
  159275. }
  159276. }
  159277. return zRet;
  159278. }
  159279. /*
  159280. ** Finalize the statement passed as the second argument.
  159281. **
  159282. ** If the sqlite3_finalize() call indicates that an error occurs, and the
  159283. ** rbu handle error code is not already set, set the error code and error
  159284. ** message accordingly.
  159285. */
  159286. static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
  159287. sqlite3 *db = sqlite3_db_handle(pStmt);
  159288. int rc = sqlite3_finalize(pStmt);
  159289. if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
  159290. p->rc = rc;
  159291. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  159292. }
  159293. }
  159294. /* Determine the type of a table.
  159295. **
  159296. ** peType is of type (int*), a pointer to an output parameter of type
  159297. ** (int). This call sets the output parameter as follows, depending
  159298. ** on the type of the table specified by parameters dbName and zTbl.
  159299. **
  159300. ** RBU_PK_NOTABLE: No such table.
  159301. ** RBU_PK_NONE: Table has an implicit rowid.
  159302. ** RBU_PK_IPK: Table has an explicit IPK column.
  159303. ** RBU_PK_EXTERNAL: Table has an external PK index.
  159304. ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
  159305. ** RBU_PK_VTAB: Table is a virtual table.
  159306. **
  159307. ** Argument *piPk is also of type (int*), and also points to an output
  159308. ** parameter. Unless the table has an external primary key index
  159309. ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
  159310. ** if the table does have an external primary key index, then *piPk
  159311. ** is set to the root page number of the primary key index before
  159312. ** returning.
  159313. **
  159314. ** ALGORITHM:
  159315. **
  159316. ** if( no entry exists in sqlite_master ){
  159317. ** return RBU_PK_NOTABLE
  159318. ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
  159319. ** return RBU_PK_VTAB
  159320. ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
  159321. ** if( the index that is the pk exists in sqlite_master ){
  159322. ** *piPK = rootpage of that index.
  159323. ** return RBU_PK_EXTERNAL
  159324. ** }else{
  159325. ** return RBU_PK_WITHOUT_ROWID
  159326. ** }
  159327. ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
  159328. ** return RBU_PK_IPK
  159329. ** }else{
  159330. ** return RBU_PK_NONE
  159331. ** }
  159332. */
  159333. static void rbuTableType(
  159334. sqlite3rbu *p,
  159335. const char *zTab,
  159336. int *peType,
  159337. int *piTnum,
  159338. int *piPk
  159339. ){
  159340. /*
  159341. ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
  159342. ** 1) PRAGMA index_list = ?
  159343. ** 2) SELECT count(*) FROM sqlite_master where name=%Q
  159344. ** 3) PRAGMA table_info = ?
  159345. */
  159346. sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
  159347. *peType = RBU_PK_NOTABLE;
  159348. *piPk = 0;
  159349. assert( p->rc==SQLITE_OK );
  159350. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
  159351. sqlite3_mprintf(
  159352. "SELECT (sql LIKE 'create virtual%%'), rootpage"
  159353. " FROM sqlite_master"
  159354. " WHERE name=%Q", zTab
  159355. ));
  159356. if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
  159357. /* Either an error, or no such table. */
  159358. goto rbuTableType_end;
  159359. }
  159360. if( sqlite3_column_int(aStmt[0], 0) ){
  159361. *peType = RBU_PK_VTAB; /* virtual table */
  159362. goto rbuTableType_end;
  159363. }
  159364. *piTnum = sqlite3_column_int(aStmt[0], 1);
  159365. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
  159366. sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
  159367. );
  159368. if( p->rc ) goto rbuTableType_end;
  159369. while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
  159370. const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
  159371. const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
  159372. if( zOrig && zIdx && zOrig[0]=='p' ){
  159373. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
  159374. sqlite3_mprintf(
  159375. "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
  159376. ));
  159377. if( p->rc==SQLITE_OK ){
  159378. if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
  159379. *piPk = sqlite3_column_int(aStmt[2], 0);
  159380. *peType = RBU_PK_EXTERNAL;
  159381. }else{
  159382. *peType = RBU_PK_WITHOUT_ROWID;
  159383. }
  159384. }
  159385. goto rbuTableType_end;
  159386. }
  159387. }
  159388. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
  159389. sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
  159390. );
  159391. if( p->rc==SQLITE_OK ){
  159392. while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
  159393. if( sqlite3_column_int(aStmt[3],5)>0 ){
  159394. *peType = RBU_PK_IPK; /* explicit IPK column */
  159395. goto rbuTableType_end;
  159396. }
  159397. }
  159398. *peType = RBU_PK_NONE;
  159399. }
  159400. rbuTableType_end: {
  159401. unsigned int i;
  159402. for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
  159403. rbuFinalize(p, aStmt[i]);
  159404. }
  159405. }
  159406. }
  159407. /*
  159408. ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
  159409. ** the pIter->abIndexed[] array.
  159410. */
  159411. static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
  159412. sqlite3_stmt *pList = 0;
  159413. int bIndex = 0;
  159414. if( p->rc==SQLITE_OK ){
  159415. memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
  159416. p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
  159417. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  159418. );
  159419. }
  159420. pIter->nIndex = 0;
  159421. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
  159422. const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
  159423. sqlite3_stmt *pXInfo = 0;
  159424. if( zIdx==0 ) break;
  159425. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  159426. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  159427. );
  159428. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  159429. int iCid = sqlite3_column_int(pXInfo, 1);
  159430. if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
  159431. }
  159432. rbuFinalize(p, pXInfo);
  159433. bIndex = 1;
  159434. pIter->nIndex++;
  159435. }
  159436. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  159437. /* "PRAGMA index_list" includes the main PK b-tree */
  159438. pIter->nIndex--;
  159439. }
  159440. rbuFinalize(p, pList);
  159441. if( bIndex==0 ) pIter->abIndexed = 0;
  159442. }
  159443. /*
  159444. ** If they are not already populated, populate the pIter->azTblCol[],
  159445. ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
  159446. ** the table (not index) that the iterator currently points to.
  159447. **
  159448. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
  159449. ** an error does occur, an error code and error message are also left in
  159450. ** the RBU handle.
  159451. */
  159452. static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
  159453. if( pIter->azTblCol==0 ){
  159454. sqlite3_stmt *pStmt = 0;
  159455. int nCol = 0;
  159456. int i; /* for() loop iterator variable */
  159457. int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
  159458. int iOrder = 0;
  159459. int iTnum = 0;
  159460. /* Figure out the type of table this step will deal with. */
  159461. assert( pIter->eType==0 );
  159462. rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
  159463. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
  159464. p->rc = SQLITE_ERROR;
  159465. p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
  159466. }
  159467. if( p->rc ) return p->rc;
  159468. if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
  159469. assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
  159470. || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
  159471. || pIter->eType==RBU_PK_VTAB
  159472. );
  159473. /* Populate the azTblCol[] and nTblCol variables based on the columns
  159474. ** of the input table. Ignore any input table columns that begin with
  159475. ** "rbu_". */
  159476. p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  159477. sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
  159478. );
  159479. if( p->rc==SQLITE_OK ){
  159480. nCol = sqlite3_column_count(pStmt);
  159481. rbuAllocateIterArrays(p, pIter, nCol);
  159482. }
  159483. for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
  159484. const char *zName = (const char*)sqlite3_column_name(pStmt, i);
  159485. if( sqlite3_strnicmp("rbu_", zName, 4) ){
  159486. char *zCopy = rbuStrndup(zName, &p->rc);
  159487. pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
  159488. pIter->azTblCol[pIter->nTblCol++] = zCopy;
  159489. }
  159490. else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
  159491. bRbuRowid = 1;
  159492. }
  159493. }
  159494. sqlite3_finalize(pStmt);
  159495. pStmt = 0;
  159496. if( p->rc==SQLITE_OK
  159497. && rbuIsVacuum(p)==0
  159498. && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  159499. ){
  159500. p->rc = SQLITE_ERROR;
  159501. p->zErrmsg = sqlite3_mprintf(
  159502. "table %q %s rbu_rowid column", pIter->zDataTbl,
  159503. (bRbuRowid ? "may not have" : "requires")
  159504. );
  159505. }
  159506. /* Check that all non-HIDDEN columns in the destination table are also
  159507. ** present in the input table. Populate the abTblPk[], azTblType[] and
  159508. ** aiTblOrder[] arrays at the same time. */
  159509. if( p->rc==SQLITE_OK ){
  159510. p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  159511. sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
  159512. );
  159513. }
  159514. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  159515. const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
  159516. if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
  159517. for(i=iOrder; i<pIter->nTblCol; i++){
  159518. if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
  159519. }
  159520. if( i==pIter->nTblCol ){
  159521. p->rc = SQLITE_ERROR;
  159522. p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
  159523. pIter->zDataTbl, zName
  159524. );
  159525. }else{
  159526. int iPk = sqlite3_column_int(pStmt, 5);
  159527. int bNotNull = sqlite3_column_int(pStmt, 3);
  159528. const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
  159529. if( i!=iOrder ){
  159530. SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
  159531. SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
  159532. }
  159533. pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
  159534. pIter->abTblPk[iOrder] = (iPk!=0);
  159535. pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
  159536. iOrder++;
  159537. }
  159538. }
  159539. rbuFinalize(p, pStmt);
  159540. rbuObjIterCacheIndexedCols(p, pIter);
  159541. assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
  159542. assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
  159543. }
  159544. return p->rc;
  159545. }
  159546. /*
  159547. ** This function constructs and returns a pointer to a nul-terminated
  159548. ** string containing some SQL clause or list based on one or more of the
  159549. ** column names currently stored in the pIter->azTblCol[] array.
  159550. */
  159551. static char *rbuObjIterGetCollist(
  159552. sqlite3rbu *p, /* RBU object */
  159553. RbuObjIter *pIter /* Object iterator for column names */
  159554. ){
  159555. char *zList = 0;
  159556. const char *zSep = "";
  159557. int i;
  159558. for(i=0; i<pIter->nTblCol; i++){
  159559. const char *z = pIter->azTblCol[i];
  159560. zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
  159561. zSep = ", ";
  159562. }
  159563. return zList;
  159564. }
  159565. /*
  159566. ** This function is used to create a SELECT list (the list of SQL
  159567. ** expressions that follows a SELECT keyword) for a SELECT statement
  159568. ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
  159569. ** index object currently indicated by the iterator object passed as the
  159570. ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
  159571. ** to obtain the required information.
  159572. **
  159573. ** If the index is of the following form:
  159574. **
  159575. ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
  159576. **
  159577. ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
  159578. ** "ipk", the returned string is:
  159579. **
  159580. ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
  159581. **
  159582. ** As well as the returned string, three other malloc'd strings are
  159583. ** returned via output parameters. As follows:
  159584. **
  159585. ** pzImposterCols: ...
  159586. ** pzImposterPk: ...
  159587. ** pzWhere: ...
  159588. */
  159589. static char *rbuObjIterGetIndexCols(
  159590. sqlite3rbu *p, /* RBU object */
  159591. RbuObjIter *pIter, /* Object iterator for column names */
  159592. char **pzImposterCols, /* OUT: Columns for imposter table */
  159593. char **pzImposterPk, /* OUT: Imposter PK clause */
  159594. char **pzWhere, /* OUT: WHERE clause */
  159595. int *pnBind /* OUT: Trbul number of columns */
  159596. ){
  159597. int rc = p->rc; /* Error code */
  159598. int rc2; /* sqlite3_finalize() return code */
  159599. char *zRet = 0; /* String to return */
  159600. char *zImpCols = 0; /* String to return via *pzImposterCols */
  159601. char *zImpPK = 0; /* String to return via *pzImposterPK */
  159602. char *zWhere = 0; /* String to return via *pzWhere */
  159603. int nBind = 0; /* Value to return via *pnBind */
  159604. const char *zCom = ""; /* Set to ", " later on */
  159605. const char *zAnd = ""; /* Set to " AND " later on */
  159606. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
  159607. if( rc==SQLITE_OK ){
  159608. assert( p->zErrmsg==0 );
  159609. rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  159610. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
  159611. );
  159612. }
  159613. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  159614. int iCid = sqlite3_column_int(pXInfo, 1);
  159615. int bDesc = sqlite3_column_int(pXInfo, 3);
  159616. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  159617. const char *zCol;
  159618. const char *zType;
  159619. if( iCid<0 ){
  159620. /* An integer primary key. If the table has an explicit IPK, use
  159621. ** its name. Otherwise, use "rbu_rowid". */
  159622. if( pIter->eType==RBU_PK_IPK ){
  159623. int i;
  159624. for(i=0; pIter->abTblPk[i]==0; i++);
  159625. assert( i<pIter->nTblCol );
  159626. zCol = pIter->azTblCol[i];
  159627. }else if( rbuIsVacuum(p) ){
  159628. zCol = "_rowid_";
  159629. }else{
  159630. zCol = "rbu_rowid";
  159631. }
  159632. zType = "INTEGER";
  159633. }else{
  159634. zCol = pIter->azTblCol[iCid];
  159635. zType = pIter->azTblType[iCid];
  159636. }
  159637. zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
  159638. if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
  159639. const char *zOrder = (bDesc ? " DESC" : "");
  159640. zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
  159641. zImpPK, zCom, nBind, zCol, zOrder
  159642. );
  159643. }
  159644. zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
  159645. zImpCols, zCom, nBind, zCol, zType, zCollate
  159646. );
  159647. zWhere = sqlite3_mprintf(
  159648. "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
  159649. );
  159650. if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
  159651. zCom = ", ";
  159652. zAnd = " AND ";
  159653. nBind++;
  159654. }
  159655. rc2 = sqlite3_finalize(pXInfo);
  159656. if( rc==SQLITE_OK ) rc = rc2;
  159657. if( rc!=SQLITE_OK ){
  159658. sqlite3_free(zRet);
  159659. sqlite3_free(zImpCols);
  159660. sqlite3_free(zImpPK);
  159661. sqlite3_free(zWhere);
  159662. zRet = 0;
  159663. zImpCols = 0;
  159664. zImpPK = 0;
  159665. zWhere = 0;
  159666. p->rc = rc;
  159667. }
  159668. *pzImposterCols = zImpCols;
  159669. *pzImposterPk = zImpPK;
  159670. *pzWhere = zWhere;
  159671. *pnBind = nBind;
  159672. return zRet;
  159673. }
  159674. /*
  159675. ** Assuming the current table columns are "a", "b" and "c", and the zObj
  159676. ** paramter is passed "old", return a string of the form:
  159677. **
  159678. ** "old.a, old.b, old.b"
  159679. **
  159680. ** With the column names escaped.
  159681. **
  159682. ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
  159683. ** the text ", old._rowid_" to the returned value.
  159684. */
  159685. static char *rbuObjIterGetOldlist(
  159686. sqlite3rbu *p,
  159687. RbuObjIter *pIter,
  159688. const char *zObj
  159689. ){
  159690. char *zList = 0;
  159691. if( p->rc==SQLITE_OK && pIter->abIndexed ){
  159692. const char *zS = "";
  159693. int i;
  159694. for(i=0; i<pIter->nTblCol; i++){
  159695. if( pIter->abIndexed[i] ){
  159696. const char *zCol = pIter->azTblCol[i];
  159697. zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
  159698. }else{
  159699. zList = sqlite3_mprintf("%z%sNULL", zList, zS);
  159700. }
  159701. zS = ", ";
  159702. if( zList==0 ){
  159703. p->rc = SQLITE_NOMEM;
  159704. break;
  159705. }
  159706. }
  159707. /* For a table with implicit rowids, append "old._rowid_" to the list. */
  159708. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  159709. zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
  159710. }
  159711. }
  159712. return zList;
  159713. }
  159714. /*
  159715. ** Return an expression that can be used in a WHERE clause to match the
  159716. ** primary key of the current table. For example, if the table is:
  159717. **
  159718. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
  159719. **
  159720. ** Return the string:
  159721. **
  159722. ** "b = ?1 AND c = ?2"
  159723. */
  159724. static char *rbuObjIterGetWhere(
  159725. sqlite3rbu *p,
  159726. RbuObjIter *pIter
  159727. ){
  159728. char *zList = 0;
  159729. if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
  159730. zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
  159731. }else if( pIter->eType==RBU_PK_EXTERNAL ){
  159732. const char *zSep = "";
  159733. int i;
  159734. for(i=0; i<pIter->nTblCol; i++){
  159735. if( pIter->abTblPk[i] ){
  159736. zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
  159737. zSep = " AND ";
  159738. }
  159739. }
  159740. zList = rbuMPrintf(p,
  159741. "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
  159742. );
  159743. }else{
  159744. const char *zSep = "";
  159745. int i;
  159746. for(i=0; i<pIter->nTblCol; i++){
  159747. if( pIter->abTblPk[i] ){
  159748. const char *zCol = pIter->azTblCol[i];
  159749. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
  159750. zSep = " AND ";
  159751. }
  159752. }
  159753. }
  159754. return zList;
  159755. }
  159756. /*
  159757. ** The SELECT statement iterating through the keys for the current object
  159758. ** (p->objiter.pSelect) currently points to a valid row. However, there
  159759. ** is something wrong with the rbu_control value in the rbu_control value
  159760. ** stored in the (p->nCol+1)'th column. Set the error code and error message
  159761. ** of the RBU handle to something reflecting this.
  159762. */
  159763. static void rbuBadControlError(sqlite3rbu *p){
  159764. p->rc = SQLITE_ERROR;
  159765. p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
  159766. }
  159767. /*
  159768. ** Return a nul-terminated string containing the comma separated list of
  159769. ** assignments that should be included following the "SET" keyword of
  159770. ** an UPDATE statement used to update the table object that the iterator
  159771. ** passed as the second argument currently points to if the rbu_control
  159772. ** column of the data_xxx table entry is set to zMask.
  159773. **
  159774. ** The memory for the returned string is obtained from sqlite3_malloc().
  159775. ** It is the responsibility of the caller to eventually free it using
  159776. ** sqlite3_free().
  159777. **
  159778. ** If an OOM error is encountered when allocating space for the new
  159779. ** string, an error code is left in the rbu handle passed as the first
  159780. ** argument and NULL is returned. Or, if an error has already occurred
  159781. ** when this function is called, NULL is returned immediately, without
  159782. ** attempting the allocation or modifying the stored error code.
  159783. */
  159784. static char *rbuObjIterGetSetlist(
  159785. sqlite3rbu *p,
  159786. RbuObjIter *pIter,
  159787. const char *zMask
  159788. ){
  159789. char *zList = 0;
  159790. if( p->rc==SQLITE_OK ){
  159791. int i;
  159792. if( (int)strlen(zMask)!=pIter->nTblCol ){
  159793. rbuBadControlError(p);
  159794. }else{
  159795. const char *zSep = "";
  159796. for(i=0; i<pIter->nTblCol; i++){
  159797. char c = zMask[pIter->aiSrcOrder[i]];
  159798. if( c=='x' ){
  159799. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
  159800. zList, zSep, pIter->azTblCol[i], i+1
  159801. );
  159802. zSep = ", ";
  159803. }
  159804. else if( c=='d' ){
  159805. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
  159806. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  159807. );
  159808. zSep = ", ";
  159809. }
  159810. else if( c=='f' ){
  159811. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
  159812. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  159813. );
  159814. zSep = ", ";
  159815. }
  159816. }
  159817. }
  159818. }
  159819. return zList;
  159820. }
  159821. /*
  159822. ** Return a nul-terminated string consisting of nByte comma separated
  159823. ** "?" expressions. For example, if nByte is 3, return a pointer to
  159824. ** a buffer containing the string "?,?,?".
  159825. **
  159826. ** The memory for the returned string is obtained from sqlite3_malloc().
  159827. ** It is the responsibility of the caller to eventually free it using
  159828. ** sqlite3_free().
  159829. **
  159830. ** If an OOM error is encountered when allocating space for the new
  159831. ** string, an error code is left in the rbu handle passed as the first
  159832. ** argument and NULL is returned. Or, if an error has already occurred
  159833. ** when this function is called, NULL is returned immediately, without
  159834. ** attempting the allocation or modifying the stored error code.
  159835. */
  159836. static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
  159837. char *zRet = 0;
  159838. int nByte = nBind*2 + 1;
  159839. zRet = (char*)rbuMalloc(p, nByte);
  159840. if( zRet ){
  159841. int i;
  159842. for(i=0; i<nBind; i++){
  159843. zRet[i*2] = '?';
  159844. zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
  159845. }
  159846. }
  159847. return zRet;
  159848. }
  159849. /*
  159850. ** The iterator currently points to a table (not index) of type
  159851. ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
  159852. ** declaration for the corresponding imposter table. For example,
  159853. ** if the iterator points to a table created as:
  159854. **
  159855. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
  159856. **
  159857. ** this function returns:
  159858. **
  159859. ** PRIMARY KEY("b", "a" DESC)
  159860. */
  159861. static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
  159862. char *z = 0;
  159863. assert( pIter->zIdx==0 );
  159864. if( p->rc==SQLITE_OK ){
  159865. const char *zSep = "PRIMARY KEY(";
  159866. sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
  159867. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
  159868. p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
  159869. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  159870. );
  159871. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
  159872. const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
  159873. if( zOrig && strcmp(zOrig, "pk")==0 ){
  159874. const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
  159875. if( zIdx ){
  159876. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  159877. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  159878. );
  159879. }
  159880. break;
  159881. }
  159882. }
  159883. rbuFinalize(p, pXList);
  159884. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  159885. if( sqlite3_column_int(pXInfo, 5) ){
  159886. /* int iCid = sqlite3_column_int(pXInfo, 0); */
  159887. const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
  159888. const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
  159889. z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
  159890. zSep = ", ";
  159891. }
  159892. }
  159893. z = rbuMPrintf(p, "%z)", z);
  159894. rbuFinalize(p, pXInfo);
  159895. }
  159896. return z;
  159897. }
  159898. /*
  159899. ** This function creates the second imposter table used when writing to
  159900. ** a table b-tree where the table has an external primary key. If the
  159901. ** iterator passed as the second argument does not currently point to
  159902. ** a table (not index) with an external primary key, this function is a
  159903. ** no-op.
  159904. **
  159905. ** Assuming the iterator does point to a table with an external PK, this
  159906. ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
  159907. ** used to access that PK index. For example, if the target table is
  159908. ** declared as follows:
  159909. **
  159910. ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
  159911. **
  159912. ** then the imposter table schema is:
  159913. **
  159914. ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
  159915. **
  159916. */
  159917. static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
  159918. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
  159919. int tnum = pIter->iPkTnum; /* Root page of PK index */
  159920. sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
  159921. const char *zIdx = 0; /* Name of PK index */
  159922. sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
  159923. const char *zComma = "";
  159924. char *zCols = 0; /* Used to build up list of table cols */
  159925. char *zPk = 0; /* Used to build up table PK declaration */
  159926. /* Figure out the name of the primary key index for the current table.
  159927. ** This is needed for the argument to "PRAGMA index_xinfo". Set
  159928. ** zIdx to point to a nul-terminated string containing this name. */
  159929. p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
  159930. "SELECT name FROM sqlite_master WHERE rootpage = ?"
  159931. );
  159932. if( p->rc==SQLITE_OK ){
  159933. sqlite3_bind_int(pQuery, 1, tnum);
  159934. if( SQLITE_ROW==sqlite3_step(pQuery) ){
  159935. zIdx = (const char*)sqlite3_column_text(pQuery, 0);
  159936. }
  159937. }
  159938. if( zIdx ){
  159939. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  159940. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  159941. );
  159942. }
  159943. rbuFinalize(p, pQuery);
  159944. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  159945. int bKey = sqlite3_column_int(pXInfo, 5);
  159946. if( bKey ){
  159947. int iCid = sqlite3_column_int(pXInfo, 1);
  159948. int bDesc = sqlite3_column_int(pXInfo, 3);
  159949. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  159950. zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma,
  159951. iCid, pIter->azTblType[iCid], zCollate
  159952. );
  159953. zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
  159954. zComma = ", ";
  159955. }
  159956. }
  159957. zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
  159958. rbuFinalize(p, pXInfo);
  159959. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  159960. rbuMPrintfExec(p, p->dbMain,
  159961. "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
  159962. zCols, zPk
  159963. );
  159964. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  159965. }
  159966. }
  159967. /*
  159968. ** If an error has already occurred when this function is called, it
  159969. ** immediately returns zero (without doing any work). Or, if an error
  159970. ** occurs during the execution of this function, it sets the error code
  159971. ** in the sqlite3rbu object indicated by the first argument and returns
  159972. ** zero.
  159973. **
  159974. ** The iterator passed as the second argument is guaranteed to point to
  159975. ** a table (not an index) when this function is called. This function
  159976. ** attempts to create any imposter table required to write to the main
  159977. ** table b-tree of the table before returning. Non-zero is returned if
  159978. ** an imposter table are created, or zero otherwise.
  159979. **
  159980. ** An imposter table is required in all cases except RBU_PK_VTAB. Only
  159981. ** virtual tables are written to directly. The imposter table has the
  159982. ** same schema as the actual target table (less any UNIQUE constraints).
  159983. ** More precisely, the "same schema" means the same columns, types,
  159984. ** collation sequences. For tables that do not have an external PRIMARY
  159985. ** KEY, it also means the same PRIMARY KEY declaration.
  159986. */
  159987. static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
  159988. if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
  159989. int tnum = pIter->iTnum;
  159990. const char *zComma = "";
  159991. char *zSql = 0;
  159992. int iCol;
  159993. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  159994. for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
  159995. const char *zPk = "";
  159996. const char *zCol = pIter->azTblCol[iCol];
  159997. const char *zColl = 0;
  159998. p->rc = sqlite3_table_column_metadata(
  159999. p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
  160000. );
  160001. if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
  160002. /* If the target table column is an "INTEGER PRIMARY KEY", add
  160003. ** "PRIMARY KEY" to the imposter table column declaration. */
  160004. zPk = "PRIMARY KEY ";
  160005. }
  160006. zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s",
  160007. zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
  160008. (pIter->abNotNull[iCol] ? " NOT NULL" : "")
  160009. );
  160010. zComma = ", ";
  160011. }
  160012. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  160013. char *zPk = rbuWithoutRowidPK(p, pIter);
  160014. if( zPk ){
  160015. zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
  160016. }
  160017. }
  160018. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  160019. rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
  160020. pIter->zTbl, zSql,
  160021. (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
  160022. );
  160023. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  160024. }
  160025. }
  160026. /*
  160027. ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
  160028. ** Specifically a statement of the form:
  160029. **
  160030. ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
  160031. **
  160032. ** The number of bound variables is equal to the number of columns in
  160033. ** the target table, plus one (for the rbu_control column), plus one more
  160034. ** (for the rbu_rowid column) if the target table is an implicit IPK or
  160035. ** virtual table.
  160036. */
  160037. static void rbuObjIterPrepareTmpInsert(
  160038. sqlite3rbu *p,
  160039. RbuObjIter *pIter,
  160040. const char *zCollist,
  160041. const char *zRbuRowid
  160042. ){
  160043. int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
  160044. char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
  160045. if( zBind ){
  160046. assert( pIter->pTmpInsert==0 );
  160047. p->rc = prepareFreeAndCollectError(
  160048. p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
  160049. "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
  160050. p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
  160051. ));
  160052. }
  160053. }
  160054. static void rbuTmpInsertFunc(
  160055. sqlite3_context *pCtx,
  160056. int nVal,
  160057. sqlite3_value **apVal
  160058. ){
  160059. sqlite3rbu *p = sqlite3_user_data(pCtx);
  160060. int rc = SQLITE_OK;
  160061. int i;
  160062. assert( sqlite3_value_int(apVal[0])!=0
  160063. || p->objiter.eType==RBU_PK_EXTERNAL
  160064. || p->objiter.eType==RBU_PK_NONE
  160065. );
  160066. if( sqlite3_value_int(apVal[0])!=0 ){
  160067. p->nPhaseOneStep += p->objiter.nIndex;
  160068. }
  160069. for(i=0; rc==SQLITE_OK && i<nVal; i++){
  160070. rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
  160071. }
  160072. if( rc==SQLITE_OK ){
  160073. sqlite3_step(p->objiter.pTmpInsert);
  160074. rc = sqlite3_reset(p->objiter.pTmpInsert);
  160075. }
  160076. if( rc!=SQLITE_OK ){
  160077. sqlite3_result_error_code(pCtx, rc);
  160078. }
  160079. }
  160080. /*
  160081. ** Ensure that the SQLite statement handles required to update the
  160082. ** target database object currently indicated by the iterator passed
  160083. ** as the second argument are available.
  160084. */
  160085. static int rbuObjIterPrepareAll(
  160086. sqlite3rbu *p,
  160087. RbuObjIter *pIter,
  160088. int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
  160089. ){
  160090. assert( pIter->bCleanup==0 );
  160091. if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
  160092. const int tnum = pIter->iTnum;
  160093. char *zCollist = 0; /* List of indexed columns */
  160094. char **pz = &p->zErrmsg;
  160095. const char *zIdx = pIter->zIdx;
  160096. char *zLimit = 0;
  160097. if( nOffset ){
  160098. zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
  160099. if( !zLimit ) p->rc = SQLITE_NOMEM;
  160100. }
  160101. if( zIdx ){
  160102. const char *zTbl = pIter->zTbl;
  160103. char *zImposterCols = 0; /* Columns for imposter table */
  160104. char *zImposterPK = 0; /* Primary key declaration for imposter */
  160105. char *zWhere = 0; /* WHERE clause on PK columns */
  160106. char *zBind = 0;
  160107. int nBind = 0;
  160108. assert( pIter->eType!=RBU_PK_VTAB );
  160109. zCollist = rbuObjIterGetIndexCols(
  160110. p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
  160111. );
  160112. zBind = rbuObjIterGetBindlist(p, nBind);
  160113. /* Create the imposter table used to write to this index. */
  160114. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  160115. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
  160116. rbuMPrintfExec(p, p->dbMain,
  160117. "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
  160118. zTbl, zImposterCols, zImposterPK
  160119. );
  160120. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  160121. /* Create the statement to insert index entries */
  160122. pIter->nCol = nBind;
  160123. if( p->rc==SQLITE_OK ){
  160124. p->rc = prepareFreeAndCollectError(
  160125. p->dbMain, &pIter->pInsert, &p->zErrmsg,
  160126. sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
  160127. );
  160128. }
  160129. /* And to delete index entries */
  160130. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  160131. p->rc = prepareFreeAndCollectError(
  160132. p->dbMain, &pIter->pDelete, &p->zErrmsg,
  160133. sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
  160134. );
  160135. }
  160136. /* Create the SELECT statement to read keys in sorted order */
  160137. if( p->rc==SQLITE_OK ){
  160138. char *zSql;
  160139. if( rbuIsVacuum(p) ){
  160140. zSql = sqlite3_mprintf(
  160141. "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
  160142. zCollist,
  160143. pIter->zDataTbl,
  160144. zCollist, zLimit
  160145. );
  160146. }else
  160147. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  160148. zSql = sqlite3_mprintf(
  160149. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
  160150. zCollist, p->zStateDb, pIter->zDataTbl,
  160151. zCollist, zLimit
  160152. );
  160153. }else{
  160154. zSql = sqlite3_mprintf(
  160155. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
  160156. "UNION ALL "
  160157. "SELECT %s, rbu_control FROM '%q' "
  160158. "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
  160159. "ORDER BY %s%s",
  160160. zCollist, p->zStateDb, pIter->zDataTbl,
  160161. zCollist, pIter->zDataTbl,
  160162. zCollist, zLimit
  160163. );
  160164. }
  160165. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
  160166. }
  160167. sqlite3_free(zImposterCols);
  160168. sqlite3_free(zImposterPK);
  160169. sqlite3_free(zWhere);
  160170. sqlite3_free(zBind);
  160171. }else{
  160172. int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
  160173. ||(pIter->eType==RBU_PK_NONE)
  160174. ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
  160175. const char *zTbl = pIter->zTbl; /* Table this step applies to */
  160176. const char *zWrite; /* Imposter table name */
  160177. char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
  160178. char *zWhere = rbuObjIterGetWhere(p, pIter);
  160179. char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
  160180. char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
  160181. zCollist = rbuObjIterGetCollist(p, pIter);
  160182. pIter->nCol = pIter->nTblCol;
  160183. /* Create the imposter table or tables (if required). */
  160184. rbuCreateImposterTable(p, pIter);
  160185. rbuCreateImposterTable2(p, pIter);
  160186. zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
  160187. /* Create the INSERT statement to write to the target PK b-tree */
  160188. if( p->rc==SQLITE_OK ){
  160189. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
  160190. sqlite3_mprintf(
  160191. "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
  160192. zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
  160193. )
  160194. );
  160195. }
  160196. /* Create the DELETE statement to write to the target PK b-tree.
  160197. ** Because it only performs INSERT operations, this is not required for
  160198. ** an rbu vacuum handle. */
  160199. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  160200. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
  160201. sqlite3_mprintf(
  160202. "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
  160203. )
  160204. );
  160205. }
  160206. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  160207. const char *zRbuRowid = "";
  160208. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  160209. zRbuRowid = ", rbu_rowid";
  160210. }
  160211. /* Create the rbu_tmp_xxx table and the triggers to populate it. */
  160212. rbuMPrintfExec(p, p->dbRbu,
  160213. "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
  160214. "SELECT *%s FROM '%q' WHERE 0;"
  160215. , p->zStateDb, pIter->zDataTbl
  160216. , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
  160217. , pIter->zDataTbl
  160218. );
  160219. rbuMPrintfExec(p, p->dbMain,
  160220. "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
  160221. "BEGIN "
  160222. " SELECT rbu_tmp_insert(3, %s);"
  160223. "END;"
  160224. "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
  160225. "BEGIN "
  160226. " SELECT rbu_tmp_insert(3, %s);"
  160227. "END;"
  160228. "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
  160229. "BEGIN "
  160230. " SELECT rbu_tmp_insert(4, %s);"
  160231. "END;",
  160232. zWrite, zTbl, zOldlist,
  160233. zWrite, zTbl, zOldlist,
  160234. zWrite, zTbl, zNewlist
  160235. );
  160236. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  160237. rbuMPrintfExec(p, p->dbMain,
  160238. "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
  160239. "BEGIN "
  160240. " SELECT rbu_tmp_insert(0, %s);"
  160241. "END;",
  160242. zWrite, zTbl, zNewlist
  160243. );
  160244. }
  160245. rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
  160246. }
  160247. /* Create the SELECT statement to read keys from data_xxx */
  160248. if( p->rc==SQLITE_OK ){
  160249. const char *zRbuRowid = "";
  160250. if( bRbuRowid ){
  160251. zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
  160252. }
  160253. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
  160254. sqlite3_mprintf(
  160255. "SELECT %s,%s rbu_control%s FROM '%q'%s",
  160256. zCollist,
  160257. (rbuIsVacuum(p) ? "0 AS " : ""),
  160258. zRbuRowid,
  160259. pIter->zDataTbl, zLimit
  160260. )
  160261. );
  160262. }
  160263. sqlite3_free(zWhere);
  160264. sqlite3_free(zOldlist);
  160265. sqlite3_free(zNewlist);
  160266. sqlite3_free(zBindings);
  160267. }
  160268. sqlite3_free(zCollist);
  160269. sqlite3_free(zLimit);
  160270. }
  160271. return p->rc;
  160272. }
  160273. /*
  160274. ** Set output variable *ppStmt to point to an UPDATE statement that may
  160275. ** be used to update the imposter table for the main table b-tree of the
  160276. ** table object that pIter currently points to, assuming that the
  160277. ** rbu_control column of the data_xyz table contains zMask.
  160278. **
  160279. ** If the zMask string does not specify any columns to update, then this
  160280. ** is not an error. Output variable *ppStmt is set to NULL in this case.
  160281. */
  160282. static int rbuGetUpdateStmt(
  160283. sqlite3rbu *p, /* RBU handle */
  160284. RbuObjIter *pIter, /* Object iterator */
  160285. const char *zMask, /* rbu_control value ('x.x.') */
  160286. sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
  160287. ){
  160288. RbuUpdateStmt **pp;
  160289. RbuUpdateStmt *pUp = 0;
  160290. int nUp = 0;
  160291. /* In case an error occurs */
  160292. *ppStmt = 0;
  160293. /* Search for an existing statement. If one is found, shift it to the front
  160294. ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
  160295. ** to the number of statements currently in the cache and pUp to the
  160296. ** last object in the list. */
  160297. for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
  160298. pUp = *pp;
  160299. if( strcmp(pUp->zMask, zMask)==0 ){
  160300. *pp = pUp->pNext;
  160301. pUp->pNext = pIter->pRbuUpdate;
  160302. pIter->pRbuUpdate = pUp;
  160303. *ppStmt = pUp->pUpdate;
  160304. return SQLITE_OK;
  160305. }
  160306. nUp++;
  160307. }
  160308. assert( pUp==0 || pUp->pNext==0 );
  160309. if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
  160310. for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
  160311. *pp = 0;
  160312. sqlite3_finalize(pUp->pUpdate);
  160313. pUp->pUpdate = 0;
  160314. }else{
  160315. pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
  160316. }
  160317. if( pUp ){
  160318. char *zWhere = rbuObjIterGetWhere(p, pIter);
  160319. char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
  160320. char *zUpdate = 0;
  160321. pUp->zMask = (char*)&pUp[1];
  160322. memcpy(pUp->zMask, zMask, pIter->nTblCol);
  160323. pUp->pNext = pIter->pRbuUpdate;
  160324. pIter->pRbuUpdate = pUp;
  160325. if( zSet ){
  160326. const char *zPrefix = "";
  160327. if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
  160328. zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
  160329. zPrefix, pIter->zTbl, zSet, zWhere
  160330. );
  160331. p->rc = prepareFreeAndCollectError(
  160332. p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
  160333. );
  160334. *ppStmt = pUp->pUpdate;
  160335. }
  160336. sqlite3_free(zWhere);
  160337. sqlite3_free(zSet);
  160338. }
  160339. return p->rc;
  160340. }
  160341. static sqlite3 *rbuOpenDbhandle(
  160342. sqlite3rbu *p,
  160343. const char *zName,
  160344. int bUseVfs
  160345. ){
  160346. sqlite3 *db = 0;
  160347. if( p->rc==SQLITE_OK ){
  160348. const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
  160349. p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
  160350. if( p->rc ){
  160351. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  160352. sqlite3_close(db);
  160353. db = 0;
  160354. }
  160355. }
  160356. return db;
  160357. }
  160358. /*
  160359. ** Free an RbuState object allocated by rbuLoadState().
  160360. */
  160361. static void rbuFreeState(RbuState *p){
  160362. if( p ){
  160363. sqlite3_free(p->zTbl);
  160364. sqlite3_free(p->zIdx);
  160365. sqlite3_free(p);
  160366. }
  160367. }
  160368. /*
  160369. ** Allocate an RbuState object and load the contents of the rbu_state
  160370. ** table into it. Return a pointer to the new object. It is the
  160371. ** responsibility of the caller to eventually free the object using
  160372. ** sqlite3_free().
  160373. **
  160374. ** If an error occurs, leave an error code and message in the rbu handle
  160375. ** and return NULL.
  160376. */
  160377. static RbuState *rbuLoadState(sqlite3rbu *p){
  160378. RbuState *pRet = 0;
  160379. sqlite3_stmt *pStmt = 0;
  160380. int rc;
  160381. int rc2;
  160382. pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
  160383. if( pRet==0 ) return 0;
  160384. rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  160385. sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
  160386. );
  160387. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  160388. switch( sqlite3_column_int(pStmt, 0) ){
  160389. case RBU_STATE_STAGE:
  160390. pRet->eStage = sqlite3_column_int(pStmt, 1);
  160391. if( pRet->eStage!=RBU_STAGE_OAL
  160392. && pRet->eStage!=RBU_STAGE_MOVE
  160393. && pRet->eStage!=RBU_STAGE_CKPT
  160394. ){
  160395. p->rc = SQLITE_CORRUPT;
  160396. }
  160397. break;
  160398. case RBU_STATE_TBL:
  160399. pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  160400. break;
  160401. case RBU_STATE_IDX:
  160402. pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  160403. break;
  160404. case RBU_STATE_ROW:
  160405. pRet->nRow = sqlite3_column_int(pStmt, 1);
  160406. break;
  160407. case RBU_STATE_PROGRESS:
  160408. pRet->nProgress = sqlite3_column_int64(pStmt, 1);
  160409. break;
  160410. case RBU_STATE_CKPT:
  160411. pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
  160412. break;
  160413. case RBU_STATE_COOKIE:
  160414. pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
  160415. break;
  160416. case RBU_STATE_OALSZ:
  160417. pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
  160418. break;
  160419. case RBU_STATE_PHASEONESTEP:
  160420. pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
  160421. break;
  160422. default:
  160423. rc = SQLITE_CORRUPT;
  160424. break;
  160425. }
  160426. }
  160427. rc2 = sqlite3_finalize(pStmt);
  160428. if( rc==SQLITE_OK ) rc = rc2;
  160429. p->rc = rc;
  160430. return pRet;
  160431. }
  160432. /*
  160433. ** Open the database handle and attach the RBU database as "rbu". If an
  160434. ** error occurs, leave an error code and message in the RBU handle.
  160435. */
  160436. static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
  160437. assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
  160438. assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
  160439. /* Open the RBU database */
  160440. p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
  160441. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  160442. sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  160443. if( p->zState==0 ){
  160444. const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
  160445. p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
  160446. }
  160447. }
  160448. /* If using separate RBU and state databases, attach the state database to
  160449. ** the RBU db handle now. */
  160450. if( p->zState ){
  160451. rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
  160452. memcpy(p->zStateDb, "stat", 4);
  160453. }else{
  160454. memcpy(p->zStateDb, "main", 4);
  160455. }
  160456. #if 0
  160457. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  160458. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
  160459. }
  160460. #endif
  160461. /* If it has not already been created, create the rbu_state table */
  160462. rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
  160463. #if 0
  160464. if( rbuIsVacuum(p) ){
  160465. if( p->rc==SQLITE_OK ){
  160466. int rc2;
  160467. int bOk = 0;
  160468. sqlite3_stmt *pCnt = 0;
  160469. p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
  160470. "SELECT count(*) FROM stat.sqlite_master"
  160471. );
  160472. if( p->rc==SQLITE_OK
  160473. && sqlite3_step(pCnt)==SQLITE_ROW
  160474. && 1==sqlite3_column_int(pCnt, 0)
  160475. ){
  160476. bOk = 1;
  160477. }
  160478. rc2 = sqlite3_finalize(pCnt);
  160479. if( p->rc==SQLITE_OK ) p->rc = rc2;
  160480. if( p->rc==SQLITE_OK && bOk==0 ){
  160481. p->rc = SQLITE_ERROR;
  160482. p->zErrmsg = sqlite3_mprintf("invalid state database");
  160483. }
  160484. if( p->rc==SQLITE_OK ){
  160485. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  160486. }
  160487. }
  160488. }
  160489. #endif
  160490. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  160491. int bOpen = 0;
  160492. int rc;
  160493. p->nRbu = 0;
  160494. p->pRbuFd = 0;
  160495. rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  160496. if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
  160497. if( p->eStage>=RBU_STAGE_MOVE ){
  160498. bOpen = 1;
  160499. }else{
  160500. RbuState *pState = rbuLoadState(p);
  160501. if( pState ){
  160502. bOpen = (pState->eStage>=RBU_STAGE_MOVE);
  160503. rbuFreeState(pState);
  160504. }
  160505. }
  160506. if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
  160507. }
  160508. p->eStage = 0;
  160509. if( p->rc==SQLITE_OK && p->dbMain==0 ){
  160510. if( !rbuIsVacuum(p) ){
  160511. p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
  160512. }else if( p->pRbuFd->pWalFd ){
  160513. if( pbRetry ){
  160514. p->pRbuFd->bNolock = 0;
  160515. sqlite3_close(p->dbRbu);
  160516. sqlite3_close(p->dbMain);
  160517. p->dbMain = 0;
  160518. p->dbRbu = 0;
  160519. *pbRetry = 1;
  160520. return;
  160521. }
  160522. p->rc = SQLITE_ERROR;
  160523. p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
  160524. }else{
  160525. char *zTarget;
  160526. char *zExtra = 0;
  160527. if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
  160528. zExtra = &p->zRbu[5];
  160529. while( *zExtra ){
  160530. if( *zExtra++=='?' ) break;
  160531. }
  160532. if( *zExtra=='\0' ) zExtra = 0;
  160533. }
  160534. zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s",
  160535. sqlite3_db_filename(p->dbRbu, "main"),
  160536. (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
  160537. );
  160538. if( zTarget==0 ){
  160539. p->rc = SQLITE_NOMEM;
  160540. return;
  160541. }
  160542. p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
  160543. sqlite3_free(zTarget);
  160544. }
  160545. }
  160546. if( p->rc==SQLITE_OK ){
  160547. p->rc = sqlite3_create_function(p->dbMain,
  160548. "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
  160549. );
  160550. }
  160551. if( p->rc==SQLITE_OK ){
  160552. p->rc = sqlite3_create_function(p->dbMain,
  160553. "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
  160554. );
  160555. }
  160556. if( p->rc==SQLITE_OK ){
  160557. p->rc = sqlite3_create_function(p->dbRbu,
  160558. "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
  160559. );
  160560. }
  160561. if( p->rc==SQLITE_OK ){
  160562. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  160563. }
  160564. rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
  160565. /* Mark the database file just opened as an RBU target database. If
  160566. ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
  160567. ** This is an error. */
  160568. if( p->rc==SQLITE_OK ){
  160569. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  160570. }
  160571. if( p->rc==SQLITE_NOTFOUND ){
  160572. p->rc = SQLITE_ERROR;
  160573. p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
  160574. }
  160575. }
  160576. /*
  160577. ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
  160578. ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
  160579. **
  160580. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  160581. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  160582. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  160583. ** three characters, then shorten the suffix on z[] to be the last three
  160584. ** characters of the original suffix.
  160585. **
  160586. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  160587. ** do the suffix shortening regardless of URI parameter.
  160588. **
  160589. ** Examples:
  160590. **
  160591. ** test.db-journal => test.nal
  160592. ** test.db-wal => test.wal
  160593. ** test.db-shm => test.shm
  160594. ** test.db-mj7f3319fa => test.9fa
  160595. */
  160596. static void rbuFileSuffix3(const char *zBase, char *z){
  160597. #ifdef SQLITE_ENABLE_8_3_NAMES
  160598. #if SQLITE_ENABLE_8_3_NAMES<2
  160599. if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
  160600. #endif
  160601. {
  160602. int i, sz;
  160603. sz = (int)strlen(z)&0xffffff;
  160604. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  160605. if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
  160606. }
  160607. #endif
  160608. }
  160609. /*
  160610. ** Return the current wal-index header checksum for the target database
  160611. ** as a 64-bit integer.
  160612. **
  160613. ** The checksum is store in the first page of xShmMap memory as an 8-byte
  160614. ** blob starting at byte offset 40.
  160615. */
  160616. static i64 rbuShmChecksum(sqlite3rbu *p){
  160617. i64 iRet = 0;
  160618. if( p->rc==SQLITE_OK ){
  160619. sqlite3_file *pDb = p->pTargetFd->pReal;
  160620. u32 volatile *ptr;
  160621. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
  160622. if( p->rc==SQLITE_OK ){
  160623. iRet = ((i64)ptr[10] << 32) + ptr[11];
  160624. }
  160625. }
  160626. return iRet;
  160627. }
  160628. /*
  160629. ** This function is called as part of initializing or reinitializing an
  160630. ** incremental checkpoint.
  160631. **
  160632. ** It populates the sqlite3rbu.aFrame[] array with the set of
  160633. ** (wal frame -> db page) copy operations required to checkpoint the
  160634. ** current wal file, and obtains the set of shm locks required to safely
  160635. ** perform the copy operations directly on the file-system.
  160636. **
  160637. ** If argument pState is not NULL, then the incremental checkpoint is
  160638. ** being resumed. In this case, if the checksum of the wal-index-header
  160639. ** following recovery is not the same as the checksum saved in the RbuState
  160640. ** object, then the rbu handle is set to DONE state. This occurs if some
  160641. ** other client appends a transaction to the wal file in the middle of
  160642. ** an incremental checkpoint.
  160643. */
  160644. static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
  160645. /* If pState is NULL, then the wal file may not have been opened and
  160646. ** recovered. Running a read-statement here to ensure that doing so
  160647. ** does not interfere with the "capture" process below. */
  160648. if( pState==0 ){
  160649. p->eStage = 0;
  160650. if( p->rc==SQLITE_OK ){
  160651. p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
  160652. }
  160653. }
  160654. /* Assuming no error has occurred, run a "restart" checkpoint with the
  160655. ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
  160656. ** special behaviour in the rbu VFS:
  160657. **
  160658. ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
  160659. ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
  160660. ** proceed with running a passive checkpoint instead of failing).
  160661. **
  160662. ** * Attempts to read from the *-wal file or write to the database file
  160663. ** do not perform any IO. Instead, the frame/page combinations that
  160664. ** would be read/written are recorded in the sqlite3rbu.aFrame[]
  160665. ** array.
  160666. **
  160667. ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
  160668. ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
  160669. ** no-ops. These locks will not be released until the connection
  160670. ** is closed.
  160671. **
  160672. ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL
  160673. ** error.
  160674. **
  160675. ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
  160676. ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
  160677. ** array populated with a set of (frame -> page) mappings. Because the
  160678. ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
  160679. ** data from the wal file into the database file according to the
  160680. ** contents of aFrame[].
  160681. */
  160682. if( p->rc==SQLITE_OK ){
  160683. int rc2;
  160684. p->eStage = RBU_STAGE_CAPTURE;
  160685. rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
  160686. if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
  160687. }
  160688. if( p->rc==SQLITE_OK && p->nFrame>0 ){
  160689. p->eStage = RBU_STAGE_CKPT;
  160690. p->nStep = (pState ? pState->nRow : 0);
  160691. p->aBuf = rbuMalloc(p, p->pgsz);
  160692. p->iWalCksum = rbuShmChecksum(p);
  160693. }
  160694. if( p->rc==SQLITE_OK ){
  160695. if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
  160696. p->rc = SQLITE_DONE;
  160697. p->eStage = RBU_STAGE_DONE;
  160698. }else{
  160699. int nSectorSize;
  160700. sqlite3_file *pDb = p->pTargetFd->pReal;
  160701. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  160702. assert( p->nPagePerSector==0 );
  160703. nSectorSize = pDb->pMethods->xSectorSize(pDb);
  160704. if( nSectorSize>p->pgsz ){
  160705. p->nPagePerSector = nSectorSize / p->pgsz;
  160706. }else{
  160707. p->nPagePerSector = 1;
  160708. }
  160709. /* Call xSync() on the wal file. This causes SQLite to sync the
  160710. ** directory in which the target database and the wal file reside, in
  160711. ** case it has not been synced since the rename() call in
  160712. ** rbuMoveOalFile(). */
  160713. p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
  160714. }
  160715. }
  160716. }
  160717. /*
  160718. ** Called when iAmt bytes are read from offset iOff of the wal file while
  160719. ** the rbu object is in capture mode. Record the frame number of the frame
  160720. ** being read in the aFrame[] array.
  160721. */
  160722. static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
  160723. const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
  160724. u32 iFrame;
  160725. if( pRbu->mLock!=mReq ){
  160726. pRbu->rc = SQLITE_BUSY;
  160727. return SQLITE_INTERNAL;
  160728. }
  160729. pRbu->pgsz = iAmt;
  160730. if( pRbu->nFrame==pRbu->nFrameAlloc ){
  160731. int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
  160732. RbuFrame *aNew;
  160733. aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
  160734. if( aNew==0 ) return SQLITE_NOMEM;
  160735. pRbu->aFrame = aNew;
  160736. pRbu->nFrameAlloc = nNew;
  160737. }
  160738. iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
  160739. if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
  160740. pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
  160741. pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
  160742. pRbu->nFrame++;
  160743. return SQLITE_OK;
  160744. }
  160745. /*
  160746. ** Called when a page of data is written to offset iOff of the database
  160747. ** file while the rbu handle is in capture mode. Record the page number
  160748. ** of the page being written in the aFrame[] array.
  160749. */
  160750. static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
  160751. pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
  160752. return SQLITE_OK;
  160753. }
  160754. /*
  160755. ** This is called as part of an incremental checkpoint operation. Copy
  160756. ** a single frame of data from the wal file into the database file, as
  160757. ** indicated by the RbuFrame object.
  160758. */
  160759. static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
  160760. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  160761. sqlite3_file *pDb = p->pTargetFd->pReal;
  160762. i64 iOff;
  160763. assert( p->rc==SQLITE_OK );
  160764. iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
  160765. p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
  160766. if( p->rc ) return;
  160767. iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
  160768. p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
  160769. }
  160770. /*
  160771. ** Take an EXCLUSIVE lock on the database file.
  160772. */
  160773. static void rbuLockDatabase(sqlite3rbu *p){
  160774. sqlite3_file *pReal = p->pTargetFd->pReal;
  160775. assert( p->rc==SQLITE_OK );
  160776. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
  160777. if( p->rc==SQLITE_OK ){
  160778. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
  160779. }
  160780. }
  160781. #if defined(_WIN32_WCE)
  160782. static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
  160783. int nChar;
  160784. LPWSTR zWideFilename;
  160785. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  160786. if( nChar==0 ){
  160787. return 0;
  160788. }
  160789. zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
  160790. if( zWideFilename==0 ){
  160791. return 0;
  160792. }
  160793. memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
  160794. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  160795. nChar);
  160796. if( nChar==0 ){
  160797. sqlite3_free(zWideFilename);
  160798. zWideFilename = 0;
  160799. }
  160800. return zWideFilename;
  160801. }
  160802. #endif
  160803. /*
  160804. ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
  160805. ** on the database file. This proc moves the *-oal file to the *-wal path,
  160806. ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
  160807. ** If an error occurs, leave an error code and error message in the rbu
  160808. ** handle.
  160809. */
  160810. static void rbuMoveOalFile(sqlite3rbu *p){
  160811. const char *zBase = sqlite3_db_filename(p->dbMain, "main");
  160812. const char *zMove = zBase;
  160813. char *zOal;
  160814. char *zWal;
  160815. if( rbuIsVacuum(p) ){
  160816. zMove = sqlite3_db_filename(p->dbRbu, "main");
  160817. }
  160818. zOal = sqlite3_mprintf("%s-oal", zMove);
  160819. zWal = sqlite3_mprintf("%s-wal", zMove);
  160820. assert( p->eStage==RBU_STAGE_MOVE );
  160821. assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
  160822. if( zWal==0 || zOal==0 ){
  160823. p->rc = SQLITE_NOMEM;
  160824. }else{
  160825. /* Move the *-oal file to *-wal. At this point connection p->db is
  160826. ** holding a SHARED lock on the target database file (because it is
  160827. ** in WAL mode). So no other connection may be writing the db.
  160828. **
  160829. ** In order to ensure that there are no database readers, an EXCLUSIVE
  160830. ** lock is obtained here before the *-oal is moved to *-wal.
  160831. */
  160832. rbuLockDatabase(p);
  160833. if( p->rc==SQLITE_OK ){
  160834. rbuFileSuffix3(zBase, zWal);
  160835. rbuFileSuffix3(zBase, zOal);
  160836. /* Re-open the databases. */
  160837. rbuObjIterFinalize(&p->objiter);
  160838. sqlite3_close(p->dbRbu);
  160839. sqlite3_close(p->dbMain);
  160840. p->dbMain = 0;
  160841. p->dbRbu = 0;
  160842. #if defined(_WIN32_WCE)
  160843. {
  160844. LPWSTR zWideOal;
  160845. LPWSTR zWideWal;
  160846. zWideOal = rbuWinUtf8ToUnicode(zOal);
  160847. if( zWideOal ){
  160848. zWideWal = rbuWinUtf8ToUnicode(zWal);
  160849. if( zWideWal ){
  160850. if( MoveFileW(zWideOal, zWideWal) ){
  160851. p->rc = SQLITE_OK;
  160852. }else{
  160853. p->rc = SQLITE_IOERR;
  160854. }
  160855. sqlite3_free(zWideWal);
  160856. }else{
  160857. p->rc = SQLITE_IOERR_NOMEM;
  160858. }
  160859. sqlite3_free(zWideOal);
  160860. }else{
  160861. p->rc = SQLITE_IOERR_NOMEM;
  160862. }
  160863. }
  160864. #else
  160865. p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
  160866. #endif
  160867. if( p->rc==SQLITE_OK ){
  160868. rbuOpenDatabase(p, 0);
  160869. rbuSetupCheckpoint(p, 0);
  160870. }
  160871. }
  160872. }
  160873. sqlite3_free(zWal);
  160874. sqlite3_free(zOal);
  160875. }
  160876. /*
  160877. ** The SELECT statement iterating through the keys for the current object
  160878. ** (p->objiter.pSelect) currently points to a valid row. This function
  160879. ** determines the type of operation requested by this row and returns
  160880. ** one of the following values to indicate the result:
  160881. **
  160882. ** * RBU_INSERT
  160883. ** * RBU_DELETE
  160884. ** * RBU_IDX_DELETE
  160885. ** * RBU_UPDATE
  160886. **
  160887. ** If RBU_UPDATE is returned, then output variable *pzMask is set to
  160888. ** point to the text value indicating the columns to update.
  160889. **
  160890. ** If the rbu_control field contains an invalid value, an error code and
  160891. ** message are left in the RBU handle and zero returned.
  160892. */
  160893. static int rbuStepType(sqlite3rbu *p, const char **pzMask){
  160894. int iCol = p->objiter.nCol; /* Index of rbu_control column */
  160895. int res = 0; /* Return value */
  160896. switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
  160897. case SQLITE_INTEGER: {
  160898. int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
  160899. switch( iVal ){
  160900. case 0: res = RBU_INSERT; break;
  160901. case 1: res = RBU_DELETE; break;
  160902. case 2: res = RBU_REPLACE; break;
  160903. case 3: res = RBU_IDX_DELETE; break;
  160904. case 4: res = RBU_IDX_INSERT; break;
  160905. }
  160906. break;
  160907. }
  160908. case SQLITE_TEXT: {
  160909. const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
  160910. if( z==0 ){
  160911. p->rc = SQLITE_NOMEM;
  160912. }else{
  160913. *pzMask = (const char*)z;
  160914. }
  160915. res = RBU_UPDATE;
  160916. break;
  160917. }
  160918. default:
  160919. break;
  160920. }
  160921. if( res==0 ){
  160922. rbuBadControlError(p);
  160923. }
  160924. return res;
  160925. }
  160926. #ifdef SQLITE_DEBUG
  160927. /*
  160928. ** Assert that column iCol of statement pStmt is named zName.
  160929. */
  160930. static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
  160931. const char *zCol = sqlite3_column_name(pStmt, iCol);
  160932. assert( 0==sqlite3_stricmp(zName, zCol) );
  160933. }
  160934. #else
  160935. # define assertColumnName(x,y,z)
  160936. #endif
  160937. /*
  160938. ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
  160939. ** RBU_IDX_DELETE. This function performs the work of a single
  160940. ** sqlite3rbu_step() call for the type of operation specified by eType.
  160941. */
  160942. static void rbuStepOneOp(sqlite3rbu *p, int eType){
  160943. RbuObjIter *pIter = &p->objiter;
  160944. sqlite3_value *pVal;
  160945. sqlite3_stmt *pWriter;
  160946. int i;
  160947. assert( p->rc==SQLITE_OK );
  160948. assert( eType!=RBU_DELETE || pIter->zIdx==0 );
  160949. assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
  160950. || eType==RBU_INSERT || eType==RBU_IDX_INSERT
  160951. );
  160952. /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
  160953. ** statement below does actually delete a row, nPhaseOneStep will be
  160954. ** incremented by the same amount when SQL function rbu_tmp_insert()
  160955. ** is invoked by the trigger. */
  160956. if( eType==RBU_DELETE ){
  160957. p->nPhaseOneStep -= p->objiter.nIndex;
  160958. }
  160959. if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
  160960. pWriter = pIter->pDelete;
  160961. }else{
  160962. pWriter = pIter->pInsert;
  160963. }
  160964. for(i=0; i<pIter->nCol; i++){
  160965. /* If this is an INSERT into a table b-tree and the table has an
  160966. ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
  160967. ** to write a NULL into the IPK column. That is not permitted. */
  160968. if( eType==RBU_INSERT
  160969. && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
  160970. && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
  160971. ){
  160972. p->rc = SQLITE_MISMATCH;
  160973. p->zErrmsg = sqlite3_mprintf("datatype mismatch");
  160974. return;
  160975. }
  160976. if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
  160977. continue;
  160978. }
  160979. pVal = sqlite3_column_value(pIter->pSelect, i);
  160980. p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
  160981. if( p->rc ) return;
  160982. }
  160983. if( pIter->zIdx==0 ){
  160984. if( pIter->eType==RBU_PK_VTAB
  160985. || pIter->eType==RBU_PK_NONE
  160986. || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
  160987. ){
  160988. /* For a virtual table, or a table with no primary key, the
  160989. ** SELECT statement is:
  160990. **
  160991. ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
  160992. **
  160993. ** Hence column_value(pIter->nCol+1).
  160994. */
  160995. assertColumnName(pIter->pSelect, pIter->nCol+1,
  160996. rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
  160997. );
  160998. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  160999. p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
  161000. }
  161001. }
  161002. if( p->rc==SQLITE_OK ){
  161003. sqlite3_step(pWriter);
  161004. p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
  161005. }
  161006. }
  161007. /*
  161008. ** This function does the work for an sqlite3rbu_step() call.
  161009. **
  161010. ** The object-iterator (p->objiter) currently points to a valid object,
  161011. ** and the input cursor (p->objiter.pSelect) currently points to a valid
  161012. ** input row. Perform whatever processing is required and return.
  161013. **
  161014. ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
  161015. ** and message is left in the RBU handle and a copy of the error code
  161016. ** returned.
  161017. */
  161018. static int rbuStep(sqlite3rbu *p){
  161019. RbuObjIter *pIter = &p->objiter;
  161020. const char *zMask = 0;
  161021. int eType = rbuStepType(p, &zMask);
  161022. if( eType ){
  161023. assert( eType==RBU_INSERT || eType==RBU_DELETE
  161024. || eType==RBU_REPLACE || eType==RBU_IDX_DELETE
  161025. || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
  161026. );
  161027. assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
  161028. if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
  161029. rbuBadControlError(p);
  161030. }
  161031. else if( eType==RBU_REPLACE ){
  161032. if( pIter->zIdx==0 ){
  161033. p->nPhaseOneStep += p->objiter.nIndex;
  161034. rbuStepOneOp(p, RBU_DELETE);
  161035. }
  161036. if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
  161037. }
  161038. else if( eType!=RBU_UPDATE ){
  161039. rbuStepOneOp(p, eType);
  161040. }
  161041. else{
  161042. sqlite3_value *pVal;
  161043. sqlite3_stmt *pUpdate = 0;
  161044. assert( eType==RBU_UPDATE );
  161045. p->nPhaseOneStep -= p->objiter.nIndex;
  161046. rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
  161047. if( pUpdate ){
  161048. int i;
  161049. for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
  161050. char c = zMask[pIter->aiSrcOrder[i]];
  161051. pVal = sqlite3_column_value(pIter->pSelect, i);
  161052. if( pIter->abTblPk[i] || c!='.' ){
  161053. p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
  161054. }
  161055. }
  161056. if( p->rc==SQLITE_OK
  161057. && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  161058. ){
  161059. /* Bind the rbu_rowid value to column _rowid_ */
  161060. assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
  161061. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  161062. p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
  161063. }
  161064. if( p->rc==SQLITE_OK ){
  161065. sqlite3_step(pUpdate);
  161066. p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
  161067. }
  161068. }
  161069. }
  161070. }
  161071. return p->rc;
  161072. }
  161073. /*
  161074. ** Increment the schema cookie of the main database opened by p->dbMain.
  161075. **
  161076. ** Or, if this is an RBU vacuum, set the schema cookie of the main db
  161077. ** opened by p->dbMain to one more than the schema cookie of the main
  161078. ** db opened by p->dbRbu.
  161079. */
  161080. static void rbuIncrSchemaCookie(sqlite3rbu *p){
  161081. if( p->rc==SQLITE_OK ){
  161082. sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
  161083. int iCookie = 1000000;
  161084. sqlite3_stmt *pStmt;
  161085. p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
  161086. "PRAGMA schema_version"
  161087. );
  161088. if( p->rc==SQLITE_OK ){
  161089. /* Coverage: it may be that this sqlite3_step() cannot fail. There
  161090. ** is already a transaction open, so the prepared statement cannot
  161091. ** throw an SQLITE_SCHEMA exception. The only database page the
  161092. ** statement reads is page 1, which is guaranteed to be in the cache.
  161093. ** And no memory allocations are required. */
  161094. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  161095. iCookie = sqlite3_column_int(pStmt, 0);
  161096. }
  161097. rbuFinalize(p, pStmt);
  161098. }
  161099. if( p->rc==SQLITE_OK ){
  161100. rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
  161101. }
  161102. }
  161103. }
  161104. /*
  161105. ** Update the contents of the rbu_state table within the rbu database. The
  161106. ** value stored in the RBU_STATE_STAGE column is eStage. All other values
  161107. ** are determined by inspecting the rbu handle passed as the first argument.
  161108. */
  161109. static void rbuSaveState(sqlite3rbu *p, int eStage){
  161110. if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
  161111. sqlite3_stmt *pInsert = 0;
  161112. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  161113. int rc;
  161114. assert( p->zErrmsg==0 );
  161115. rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
  161116. sqlite3_mprintf(
  161117. "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
  161118. "(%d, %d), "
  161119. "(%d, %Q), "
  161120. "(%d, %Q), "
  161121. "(%d, %d), "
  161122. "(%d, %d), "
  161123. "(%d, %lld), "
  161124. "(%d, %lld), "
  161125. "(%d, %lld), "
  161126. "(%d, %lld) ",
  161127. p->zStateDb,
  161128. RBU_STATE_STAGE, eStage,
  161129. RBU_STATE_TBL, p->objiter.zTbl,
  161130. RBU_STATE_IDX, p->objiter.zIdx,
  161131. RBU_STATE_ROW, p->nStep,
  161132. RBU_STATE_PROGRESS, p->nProgress,
  161133. RBU_STATE_CKPT, p->iWalCksum,
  161134. RBU_STATE_COOKIE, (i64)pFd->iCookie,
  161135. RBU_STATE_OALSZ, p->iOalSz,
  161136. RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
  161137. )
  161138. );
  161139. assert( pInsert==0 || rc==SQLITE_OK );
  161140. if( rc==SQLITE_OK ){
  161141. sqlite3_step(pInsert);
  161142. rc = sqlite3_finalize(pInsert);
  161143. }
  161144. if( rc!=SQLITE_OK ) p->rc = rc;
  161145. }
  161146. }
  161147. /*
  161148. ** The second argument passed to this function is the name of a PRAGMA
  161149. ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
  161150. ** This function executes the following on sqlite3rbu.dbRbu:
  161151. **
  161152. ** "PRAGMA main.$zPragma"
  161153. **
  161154. ** where $zPragma is the string passed as the second argument, then
  161155. ** on sqlite3rbu.dbMain:
  161156. **
  161157. ** "PRAGMA main.$zPragma = $val"
  161158. **
  161159. ** where $val is the value returned by the first PRAGMA invocation.
  161160. **
  161161. ** In short, it copies the value of the specified PRAGMA setting from
  161162. ** dbRbu to dbMain.
  161163. */
  161164. static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
  161165. if( p->rc==SQLITE_OK ){
  161166. sqlite3_stmt *pPragma = 0;
  161167. p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
  161168. sqlite3_mprintf("PRAGMA main.%s", zPragma)
  161169. );
  161170. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
  161171. p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
  161172. zPragma, sqlite3_column_int(pPragma, 0)
  161173. );
  161174. }
  161175. rbuFinalize(p, pPragma);
  161176. }
  161177. }
  161178. /*
  161179. ** The RBU handle passed as the only argument has just been opened and
  161180. ** the state database is empty. If this RBU handle was opened for an
  161181. ** RBU vacuum operation, create the schema in the target db.
  161182. */
  161183. static void rbuCreateTargetSchema(sqlite3rbu *p){
  161184. sqlite3_stmt *pSql = 0;
  161185. sqlite3_stmt *pInsert = 0;
  161186. assert( rbuIsVacuum(p) );
  161187. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
  161188. if( p->rc==SQLITE_OK ){
  161189. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  161190. "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
  161191. " AND name!='sqlite_sequence' "
  161192. " ORDER BY type DESC"
  161193. );
  161194. }
  161195. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  161196. const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
  161197. p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
  161198. }
  161199. rbuFinalize(p, pSql);
  161200. if( p->rc!=SQLITE_OK ) return;
  161201. if( p->rc==SQLITE_OK ){
  161202. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  161203. "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
  161204. );
  161205. }
  161206. if( p->rc==SQLITE_OK ){
  161207. p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
  161208. "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
  161209. );
  161210. }
  161211. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  161212. int i;
  161213. for(i=0; i<5; i++){
  161214. sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
  161215. }
  161216. sqlite3_step(pInsert);
  161217. p->rc = sqlite3_reset(pInsert);
  161218. }
  161219. if( p->rc==SQLITE_OK ){
  161220. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
  161221. }
  161222. rbuFinalize(p, pSql);
  161223. rbuFinalize(p, pInsert);
  161224. }
  161225. /*
  161226. ** Step the RBU object.
  161227. */
  161228. SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
  161229. if( p ){
  161230. switch( p->eStage ){
  161231. case RBU_STAGE_OAL: {
  161232. RbuObjIter *pIter = &p->objiter;
  161233. /* If this is an RBU vacuum operation and the state table was empty
  161234. ** when this handle was opened, create the target database schema. */
  161235. if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
  161236. rbuCreateTargetSchema(p);
  161237. rbuCopyPragma(p, "user_version");
  161238. rbuCopyPragma(p, "application_id");
  161239. }
  161240. while( p->rc==SQLITE_OK && pIter->zTbl ){
  161241. if( pIter->bCleanup ){
  161242. /* Clean up the rbu_tmp_xxx table for the previous table. It
  161243. ** cannot be dropped as there are currently active SQL statements.
  161244. ** But the contents can be deleted. */
  161245. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  161246. rbuMPrintfExec(p, p->dbRbu,
  161247. "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
  161248. );
  161249. }
  161250. }else{
  161251. rbuObjIterPrepareAll(p, pIter, 0);
  161252. /* Advance to the next row to process. */
  161253. if( p->rc==SQLITE_OK ){
  161254. int rc = sqlite3_step(pIter->pSelect);
  161255. if( rc==SQLITE_ROW ){
  161256. p->nProgress++;
  161257. p->nStep++;
  161258. return rbuStep(p);
  161259. }
  161260. p->rc = sqlite3_reset(pIter->pSelect);
  161261. p->nStep = 0;
  161262. }
  161263. }
  161264. rbuObjIterNext(p, pIter);
  161265. }
  161266. if( p->rc==SQLITE_OK ){
  161267. assert( pIter->zTbl==0 );
  161268. rbuSaveState(p, RBU_STAGE_MOVE);
  161269. rbuIncrSchemaCookie(p);
  161270. if( p->rc==SQLITE_OK ){
  161271. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  161272. }
  161273. if( p->rc==SQLITE_OK ){
  161274. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  161275. }
  161276. p->eStage = RBU_STAGE_MOVE;
  161277. }
  161278. break;
  161279. }
  161280. case RBU_STAGE_MOVE: {
  161281. if( p->rc==SQLITE_OK ){
  161282. rbuMoveOalFile(p);
  161283. p->nProgress++;
  161284. }
  161285. break;
  161286. }
  161287. case RBU_STAGE_CKPT: {
  161288. if( p->rc==SQLITE_OK ){
  161289. if( p->nStep>=p->nFrame ){
  161290. sqlite3_file *pDb = p->pTargetFd->pReal;
  161291. /* Sync the db file */
  161292. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  161293. /* Update nBackfill */
  161294. if( p->rc==SQLITE_OK ){
  161295. void volatile *ptr;
  161296. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
  161297. if( p->rc==SQLITE_OK ){
  161298. ((u32 volatile*)ptr)[24] = p->iMaxFrame;
  161299. }
  161300. }
  161301. if( p->rc==SQLITE_OK ){
  161302. p->eStage = RBU_STAGE_DONE;
  161303. p->rc = SQLITE_DONE;
  161304. }
  161305. }else{
  161306. /* At one point the following block copied a single frame from the
  161307. ** wal file to the database file. So that one call to sqlite3rbu_step()
  161308. ** checkpointed a single frame.
  161309. **
  161310. ** However, if the sector-size is larger than the page-size, and the
  161311. ** application calls sqlite3rbu_savestate() or close() immediately
  161312. ** after this step, then rbu_step() again, then a power failure occurs,
  161313. ** then the database page written here may be damaged. Work around
  161314. ** this by checkpointing frames until the next page in the aFrame[]
  161315. ** lies on a different disk sector to the current one. */
  161316. u32 iSector;
  161317. do{
  161318. RbuFrame *pFrame = &p->aFrame[p->nStep];
  161319. iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
  161320. rbuCheckpointFrame(p, pFrame);
  161321. p->nStep++;
  161322. }while( p->nStep<p->nFrame
  161323. && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
  161324. && p->rc==SQLITE_OK
  161325. );
  161326. }
  161327. p->nProgress++;
  161328. }
  161329. break;
  161330. }
  161331. default:
  161332. break;
  161333. }
  161334. return p->rc;
  161335. }else{
  161336. return SQLITE_NOMEM;
  161337. }
  161338. }
  161339. /*
  161340. ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
  161341. ** otherwise. Either or both argument may be NULL. Two NULL values are
  161342. ** considered equal, and NULL is considered distinct from all other values.
  161343. */
  161344. static int rbuStrCompare(const char *z1, const char *z2){
  161345. if( z1==0 && z2==0 ) return 0;
  161346. if( z1==0 || z2==0 ) return 1;
  161347. return (sqlite3_stricmp(z1, z2)!=0);
  161348. }
  161349. /*
  161350. ** This function is called as part of sqlite3rbu_open() when initializing
  161351. ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
  161352. ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
  161353. ** things so that the next call to sqlite3rbu_step() continues on from
  161354. ** where the previous rbu handle left off.
  161355. **
  161356. ** If an error occurs, an error code and error message are left in the
  161357. ** rbu handle passed as the first argument.
  161358. */
  161359. static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
  161360. assert( p->rc==SQLITE_OK );
  161361. if( pState->zTbl ){
  161362. RbuObjIter *pIter = &p->objiter;
  161363. int rc = SQLITE_OK;
  161364. while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
  161365. || rbuStrCompare(pIter->zIdx, pState->zIdx)
  161366. || rbuStrCompare(pIter->zTbl, pState->zTbl)
  161367. )){
  161368. rc = rbuObjIterNext(p, pIter);
  161369. }
  161370. if( rc==SQLITE_OK && !pIter->zTbl ){
  161371. rc = SQLITE_ERROR;
  161372. p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
  161373. }
  161374. if( rc==SQLITE_OK ){
  161375. p->nStep = pState->nRow;
  161376. rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
  161377. }
  161378. p->rc = rc;
  161379. }
  161380. }
  161381. /*
  161382. ** If there is a "*-oal" file in the file-system corresponding to the
  161383. ** target database in the file-system, delete it. If an error occurs,
  161384. ** leave an error code and error message in the rbu handle.
  161385. */
  161386. static void rbuDeleteOalFile(sqlite3rbu *p){
  161387. char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
  161388. if( zOal ){
  161389. sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
  161390. assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
  161391. pVfs->xDelete(pVfs, zOal, 0);
  161392. sqlite3_free(zOal);
  161393. }
  161394. }
  161395. /*
  161396. ** Allocate a private rbu VFS for the rbu handle passed as the only
  161397. ** argument. This VFS will be used unless the call to sqlite3rbu_open()
  161398. ** specified a URI with a vfs=? option in place of a target database
  161399. ** file name.
  161400. */
  161401. static void rbuCreateVfs(sqlite3rbu *p){
  161402. int rnd;
  161403. char zRnd[64];
  161404. assert( p->rc==SQLITE_OK );
  161405. sqlite3_randomness(sizeof(int), (void*)&rnd);
  161406. sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
  161407. p->rc = sqlite3rbu_create_vfs(zRnd, 0);
  161408. if( p->rc==SQLITE_OK ){
  161409. sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
  161410. assert( pVfs );
  161411. p->zVfsName = pVfs->zName;
  161412. }
  161413. }
  161414. /*
  161415. ** Destroy the private VFS created for the rbu handle passed as the only
  161416. ** argument by an earlier call to rbuCreateVfs().
  161417. */
  161418. static void rbuDeleteVfs(sqlite3rbu *p){
  161419. if( p->zVfsName ){
  161420. sqlite3rbu_destroy_vfs(p->zVfsName);
  161421. p->zVfsName = 0;
  161422. }
  161423. }
  161424. /*
  161425. ** This user-defined SQL function is invoked with a single argument - the
  161426. ** name of a table expected to appear in the target database. It returns
  161427. ** the number of auxilliary indexes on the table.
  161428. */
  161429. static void rbuIndexCntFunc(
  161430. sqlite3_context *pCtx,
  161431. int nVal,
  161432. sqlite3_value **apVal
  161433. ){
  161434. sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
  161435. sqlite3_stmt *pStmt = 0;
  161436. char *zErrmsg = 0;
  161437. int rc;
  161438. assert( nVal==1 );
  161439. rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg,
  161440. sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
  161441. "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
  161442. );
  161443. if( rc!=SQLITE_OK ){
  161444. sqlite3_result_error(pCtx, zErrmsg, -1);
  161445. }else{
  161446. int nIndex = 0;
  161447. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  161448. nIndex = sqlite3_column_int(pStmt, 0);
  161449. }
  161450. rc = sqlite3_finalize(pStmt);
  161451. if( rc==SQLITE_OK ){
  161452. sqlite3_result_int(pCtx, nIndex);
  161453. }else{
  161454. sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
  161455. }
  161456. }
  161457. sqlite3_free(zErrmsg);
  161458. }
  161459. /*
  161460. ** If the RBU database contains the rbu_count table, use it to initialize
  161461. ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
  161462. ** is assumed to contain the same columns as:
  161463. **
  161464. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  161465. **
  161466. ** There should be one row in the table for each data_xxx table in the
  161467. ** database. The 'tbl' column should contain the name of a data_xxx table,
  161468. ** and the cnt column the number of rows it contains.
  161469. **
  161470. ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
  161471. ** for all rows in the rbu_count table, where nIndex is the number of
  161472. ** indexes on the corresponding target database table.
  161473. */
  161474. static void rbuInitPhaseOneSteps(sqlite3rbu *p){
  161475. if( p->rc==SQLITE_OK ){
  161476. sqlite3_stmt *pStmt = 0;
  161477. int bExists = 0; /* True if rbu_count exists */
  161478. p->nPhaseOneStep = -1;
  161479. p->rc = sqlite3_create_function(p->dbRbu,
  161480. "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
  161481. );
  161482. /* Check for the rbu_count table. If it does not exist, or if an error
  161483. ** occurs, nPhaseOneStep will be left set to -1. */
  161484. if( p->rc==SQLITE_OK ){
  161485. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  161486. "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
  161487. );
  161488. }
  161489. if( p->rc==SQLITE_OK ){
  161490. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  161491. bExists = 1;
  161492. }
  161493. p->rc = sqlite3_finalize(pStmt);
  161494. }
  161495. if( p->rc==SQLITE_OK && bExists ){
  161496. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  161497. "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
  161498. "FROM rbu_count"
  161499. );
  161500. if( p->rc==SQLITE_OK ){
  161501. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  161502. p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
  161503. }
  161504. p->rc = sqlite3_finalize(pStmt);
  161505. }
  161506. }
  161507. }
  161508. }
  161509. static sqlite3rbu *openRbuHandle(
  161510. const char *zTarget,
  161511. const char *zRbu,
  161512. const char *zState
  161513. ){
  161514. sqlite3rbu *p;
  161515. size_t nTarget = zTarget ? strlen(zTarget) : 0;
  161516. size_t nRbu = strlen(zRbu);
  161517. size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
  161518. p = (sqlite3rbu*)sqlite3_malloc64(nByte);
  161519. if( p ){
  161520. RbuState *pState = 0;
  161521. /* Create the custom VFS. */
  161522. memset(p, 0, sizeof(sqlite3rbu));
  161523. rbuCreateVfs(p);
  161524. /* Open the target, RBU and state databases */
  161525. if( p->rc==SQLITE_OK ){
  161526. char *pCsr = (char*)&p[1];
  161527. int bRetry = 0;
  161528. if( zTarget ){
  161529. p->zTarget = pCsr;
  161530. memcpy(p->zTarget, zTarget, nTarget+1);
  161531. pCsr += nTarget+1;
  161532. }
  161533. p->zRbu = pCsr;
  161534. memcpy(p->zRbu, zRbu, nRbu+1);
  161535. pCsr += nRbu+1;
  161536. if( zState ){
  161537. p->zState = rbuMPrintf(p, "%s", zState);
  161538. }
  161539. /* If the first attempt to open the database file fails and the bRetry
  161540. ** flag it set, this means that the db was not opened because it seemed
  161541. ** to be a wal-mode db. But, this may have happened due to an earlier
  161542. ** RBU vacuum operation leaving an old wal file in the directory.
  161543. ** If this is the case, it will have been checkpointed and deleted
  161544. ** when the handle was closed and a second attempt to open the
  161545. ** database may succeed. */
  161546. rbuOpenDatabase(p, &bRetry);
  161547. if( bRetry ){
  161548. rbuOpenDatabase(p, 0);
  161549. }
  161550. }
  161551. if( p->rc==SQLITE_OK ){
  161552. pState = rbuLoadState(p);
  161553. assert( pState || p->rc!=SQLITE_OK );
  161554. if( p->rc==SQLITE_OK ){
  161555. if( pState->eStage==0 ){
  161556. rbuDeleteOalFile(p);
  161557. rbuInitPhaseOneSteps(p);
  161558. p->eStage = RBU_STAGE_OAL;
  161559. }else{
  161560. p->eStage = pState->eStage;
  161561. p->nPhaseOneStep = pState->nPhaseOneStep;
  161562. }
  161563. p->nProgress = pState->nProgress;
  161564. p->iOalSz = pState->iOalSz;
  161565. }
  161566. }
  161567. assert( p->rc!=SQLITE_OK || p->eStage!=0 );
  161568. if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
  161569. if( p->eStage==RBU_STAGE_OAL ){
  161570. p->rc = SQLITE_ERROR;
  161571. p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
  161572. }else if( p->eStage==RBU_STAGE_MOVE ){
  161573. p->eStage = RBU_STAGE_CKPT;
  161574. p->nStep = 0;
  161575. }
  161576. }
  161577. if( p->rc==SQLITE_OK
  161578. && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
  161579. && pState->eStage!=0
  161580. ){
  161581. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  161582. if( pFd->iCookie!=pState->iCookie ){
  161583. /* At this point (pTargetFd->iCookie) contains the value of the
  161584. ** change-counter cookie (the thing that gets incremented when a
  161585. ** transaction is committed in rollback mode) currently stored on
  161586. ** page 1 of the database file. */
  161587. p->rc = SQLITE_BUSY;
  161588. p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
  161589. (rbuIsVacuum(p) ? "vacuum" : "update")
  161590. );
  161591. }
  161592. }
  161593. if( p->rc==SQLITE_OK ){
  161594. if( p->eStage==RBU_STAGE_OAL ){
  161595. sqlite3 *db = p->dbMain;
  161596. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
  161597. /* Point the object iterator at the first object */
  161598. if( p->rc==SQLITE_OK ){
  161599. p->rc = rbuObjIterFirst(p, &p->objiter);
  161600. }
  161601. /* If the RBU database contains no data_xxx tables, declare the RBU
  161602. ** update finished. */
  161603. if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
  161604. p->rc = SQLITE_DONE;
  161605. p->eStage = RBU_STAGE_DONE;
  161606. }else{
  161607. if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
  161608. rbuCopyPragma(p, "page_size");
  161609. rbuCopyPragma(p, "auto_vacuum");
  161610. }
  161611. /* Open transactions both databases. The *-oal file is opened or
  161612. ** created at this point. */
  161613. if( p->rc==SQLITE_OK ){
  161614. p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
  161615. }
  161616. /* Check if the main database is a zipvfs db. If it is, set the upper
  161617. ** level pager to use "journal_mode=off". This prevents it from
  161618. ** generating a large journal using a temp file. */
  161619. if( p->rc==SQLITE_OK ){
  161620. int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
  161621. if( frc==SQLITE_OK ){
  161622. p->rc = sqlite3_exec(
  161623. db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
  161624. }
  161625. }
  161626. if( p->rc==SQLITE_OK ){
  161627. rbuSetupOal(p, pState);
  161628. }
  161629. }
  161630. }else if( p->eStage==RBU_STAGE_MOVE ){
  161631. /* no-op */
  161632. }else if( p->eStage==RBU_STAGE_CKPT ){
  161633. rbuSetupCheckpoint(p, pState);
  161634. }else if( p->eStage==RBU_STAGE_DONE ){
  161635. p->rc = SQLITE_DONE;
  161636. }else{
  161637. p->rc = SQLITE_CORRUPT;
  161638. }
  161639. }
  161640. rbuFreeState(pState);
  161641. }
  161642. return p;
  161643. }
  161644. /*
  161645. ** Allocate and return an RBU handle with all fields zeroed except for the
  161646. ** error code, which is set to SQLITE_MISUSE.
  161647. */
  161648. static sqlite3rbu *rbuMisuseError(void){
  161649. sqlite3rbu *pRet;
  161650. pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
  161651. if( pRet ){
  161652. memset(pRet, 0, sizeof(sqlite3rbu));
  161653. pRet->rc = SQLITE_MISUSE;
  161654. }
  161655. return pRet;
  161656. }
  161657. /*
  161658. ** Open and return a new RBU handle.
  161659. */
  161660. SQLITE_API sqlite3rbu *sqlite3rbu_open(
  161661. const char *zTarget,
  161662. const char *zRbu,
  161663. const char *zState
  161664. ){
  161665. if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
  161666. /* TODO: Check that zTarget and zRbu are non-NULL */
  161667. return openRbuHandle(zTarget, zRbu, zState);
  161668. }
  161669. /*
  161670. ** Open a handle to begin or resume an RBU VACUUM operation.
  161671. */
  161672. SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
  161673. const char *zTarget,
  161674. const char *zState
  161675. ){
  161676. if( zTarget==0 ){ return rbuMisuseError(); }
  161677. /* TODO: Check that both arguments are non-NULL */
  161678. return openRbuHandle(0, zTarget, zState);
  161679. }
  161680. /*
  161681. ** Return the database handle used by pRbu.
  161682. */
  161683. SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
  161684. sqlite3 *db = 0;
  161685. if( pRbu ){
  161686. db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
  161687. }
  161688. return db;
  161689. }
  161690. /*
  161691. ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
  161692. ** then edit any error message string so as to remove all occurrences of
  161693. ** the pattern "rbu_imp_[0-9]*".
  161694. */
  161695. static void rbuEditErrmsg(sqlite3rbu *p){
  161696. if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
  161697. unsigned int i;
  161698. size_t nErrmsg = strlen(p->zErrmsg);
  161699. for(i=0; i<(nErrmsg-8); i++){
  161700. if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
  161701. int nDel = 8;
  161702. while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
  161703. memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
  161704. nErrmsg -= nDel;
  161705. }
  161706. }
  161707. }
  161708. }
  161709. /*
  161710. ** Close the RBU handle.
  161711. */
  161712. SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
  161713. int rc;
  161714. if( p ){
  161715. /* Commit the transaction to the *-oal file. */
  161716. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  161717. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  161718. }
  161719. /* Sync the db file if currently doing an incremental checkpoint */
  161720. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  161721. sqlite3_file *pDb = p->pTargetFd->pReal;
  161722. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  161723. }
  161724. rbuSaveState(p, p->eStage);
  161725. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  161726. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  161727. }
  161728. /* Close any open statement handles. */
  161729. rbuObjIterFinalize(&p->objiter);
  161730. /* If this is an RBU vacuum handle and the vacuum has either finished
  161731. ** successfully or encountered an error, delete the contents of the
  161732. ** state table. This causes the next call to sqlite3rbu_vacuum()
  161733. ** specifying the current target and state databases to start a new
  161734. ** vacuum from scratch. */
  161735. if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
  161736. int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
  161737. if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
  161738. }
  161739. /* Close the open database handle and VFS object. */
  161740. sqlite3_close(p->dbRbu);
  161741. sqlite3_close(p->dbMain);
  161742. rbuDeleteVfs(p);
  161743. sqlite3_free(p->aBuf);
  161744. sqlite3_free(p->aFrame);
  161745. rbuEditErrmsg(p);
  161746. rc = p->rc;
  161747. *pzErrmsg = p->zErrmsg;
  161748. sqlite3_free(p->zState);
  161749. sqlite3_free(p);
  161750. }else{
  161751. rc = SQLITE_NOMEM;
  161752. *pzErrmsg = 0;
  161753. }
  161754. return rc;
  161755. }
  161756. /*
  161757. ** Return the total number of key-value operations (inserts, deletes or
  161758. ** updates) that have been performed on the target database since the
  161759. ** current RBU update was started.
  161760. */
  161761. SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
  161762. return pRbu->nProgress;
  161763. }
  161764. /*
  161765. ** Return permyriadage progress indications for the two main stages of
  161766. ** an RBU update.
  161767. */
  161768. SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
  161769. const int MAX_PROGRESS = 10000;
  161770. switch( p->eStage ){
  161771. case RBU_STAGE_OAL:
  161772. if( p->nPhaseOneStep>0 ){
  161773. *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
  161774. }else{
  161775. *pnOne = -1;
  161776. }
  161777. *pnTwo = 0;
  161778. break;
  161779. case RBU_STAGE_MOVE:
  161780. *pnOne = MAX_PROGRESS;
  161781. *pnTwo = 0;
  161782. break;
  161783. case RBU_STAGE_CKPT:
  161784. *pnOne = MAX_PROGRESS;
  161785. *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
  161786. break;
  161787. case RBU_STAGE_DONE:
  161788. *pnOne = MAX_PROGRESS;
  161789. *pnTwo = MAX_PROGRESS;
  161790. break;
  161791. default:
  161792. assert( 0 );
  161793. }
  161794. }
  161795. /*
  161796. ** Return the current state of the RBU vacuum or update operation.
  161797. */
  161798. SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
  161799. int aRes[] = {
  161800. 0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
  161801. 0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
  161802. };
  161803. assert( RBU_STAGE_OAL==1 );
  161804. assert( RBU_STAGE_MOVE==2 );
  161805. assert( RBU_STAGE_CKPT==4 );
  161806. assert( RBU_STAGE_DONE==5 );
  161807. assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
  161808. assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
  161809. assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
  161810. assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
  161811. if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
  161812. return SQLITE_RBU_STATE_ERROR;
  161813. }else{
  161814. assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
  161815. assert( p->eStage==RBU_STAGE_OAL
  161816. || p->eStage==RBU_STAGE_MOVE
  161817. || p->eStage==RBU_STAGE_CKPT
  161818. || p->eStage==RBU_STAGE_DONE
  161819. );
  161820. return aRes[p->eStage];
  161821. }
  161822. }
  161823. SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
  161824. int rc = p->rc;
  161825. if( rc==SQLITE_DONE ) return SQLITE_OK;
  161826. assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
  161827. if( p->eStage==RBU_STAGE_OAL ){
  161828. assert( rc!=SQLITE_DONE );
  161829. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
  161830. }
  161831. /* Sync the db file */
  161832. if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  161833. sqlite3_file *pDb = p->pTargetFd->pReal;
  161834. rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  161835. }
  161836. p->rc = rc;
  161837. rbuSaveState(p, p->eStage);
  161838. rc = p->rc;
  161839. if( p->eStage==RBU_STAGE_OAL ){
  161840. assert( rc!=SQLITE_DONE );
  161841. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  161842. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
  161843. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
  161844. }
  161845. p->rc = rc;
  161846. return rc;
  161847. }
  161848. /**************************************************************************
  161849. ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
  161850. ** of a standard VFS in the following ways:
  161851. **
  161852. ** 1. Whenever the first page of a main database file is read or
  161853. ** written, the value of the change-counter cookie is stored in
  161854. ** rbu_file.iCookie. Similarly, the value of the "write-version"
  161855. ** database header field is stored in rbu_file.iWriteVer. This ensures
  161856. ** that the values are always trustworthy within an open transaction.
  161857. **
  161858. ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
  161859. ** member variable of the associated database file descriptor is set
  161860. ** to point to the new file. A mutex protected linked list of all main
  161861. ** db fds opened using a particular RBU VFS is maintained at
  161862. ** rbu_vfs.pMain to facilitate this.
  161863. **
  161864. ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
  161865. ** object can be marked as the target database of an RBU update. This
  161866. ** turns on the following extra special behaviour:
  161867. **
  161868. ** 3a. If xAccess() is called to check if there exists a *-wal file
  161869. ** associated with an RBU target database currently in RBU_STAGE_OAL
  161870. ** stage (preparing the *-oal file), the following special handling
  161871. ** applies:
  161872. **
  161873. ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
  161874. ** target database may not be in wal mode already.
  161875. **
  161876. ** * if the *-wal file does not exist, set the output parameter to
  161877. ** non-zero (to tell SQLite that it does exist) anyway.
  161878. **
  161879. ** Then, when xOpen() is called to open the *-wal file associated with
  161880. ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
  161881. ** file, the rbu vfs opens the corresponding *-oal file instead.
  161882. **
  161883. ** 3b. The *-shm pages returned by xShmMap() for a target db file in
  161884. ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
  161885. ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
  161886. ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
  161887. ** because assert() statements in some VFS implementations fail if
  161888. ** xShmLock() is called before xShmMap().
  161889. **
  161890. ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
  161891. ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
  161892. ** fails with an SQLITE_BUSY error. This is to stop RBU connections
  161893. ** from automatically checkpointing a *-wal (or *-oal) file from within
  161894. ** sqlite3_close().
  161895. **
  161896. ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
  161897. ** all xWrite() calls on the target database file perform no IO.
  161898. ** Instead the frame and page numbers that would be read and written
  161899. ** are recorded. Additionally, successful attempts to obtain exclusive
  161900. ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
  161901. ** database file are recorded. xShmLock() calls to unlock the same
  161902. ** locks are no-ops (so that once obtained, these locks are never
  161903. ** relinquished). Finally, calls to xSync() on the target database
  161904. ** file fail with SQLITE_INTERNAL errors.
  161905. */
  161906. static void rbuUnlockShm(rbu_file *p){
  161907. if( p->pRbu ){
  161908. int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
  161909. int i;
  161910. for(i=0; i<SQLITE_SHM_NLOCK;i++){
  161911. if( (1<<i) & p->pRbu->mLock ){
  161912. xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
  161913. }
  161914. }
  161915. p->pRbu->mLock = 0;
  161916. }
  161917. }
  161918. /*
  161919. ** Close an rbu file.
  161920. */
  161921. static int rbuVfsClose(sqlite3_file *pFile){
  161922. rbu_file *p = (rbu_file*)pFile;
  161923. int rc;
  161924. int i;
  161925. /* Free the contents of the apShm[] array. And the array itself. */
  161926. for(i=0; i<p->nShm; i++){
  161927. sqlite3_free(p->apShm[i]);
  161928. }
  161929. sqlite3_free(p->apShm);
  161930. p->apShm = 0;
  161931. sqlite3_free(p->zDel);
  161932. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  161933. rbu_file **pp;
  161934. sqlite3_mutex_enter(p->pRbuVfs->mutex);
  161935. for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
  161936. *pp = p->pMainNext;
  161937. sqlite3_mutex_leave(p->pRbuVfs->mutex);
  161938. rbuUnlockShm(p);
  161939. p->pReal->pMethods->xShmUnmap(p->pReal, 0);
  161940. }
  161941. /* Close the underlying file handle */
  161942. rc = p->pReal->pMethods->xClose(p->pReal);
  161943. return rc;
  161944. }
  161945. /*
  161946. ** Read and return an unsigned 32-bit big-endian integer from the buffer
  161947. ** passed as the only argument.
  161948. */
  161949. static u32 rbuGetU32(u8 *aBuf){
  161950. return ((u32)aBuf[0] << 24)
  161951. + ((u32)aBuf[1] << 16)
  161952. + ((u32)aBuf[2] << 8)
  161953. + ((u32)aBuf[3]);
  161954. }
  161955. /*
  161956. ** Write an unsigned 32-bit value in big-endian format to the supplied
  161957. ** buffer.
  161958. */
  161959. static void rbuPutU32(u8 *aBuf, u32 iVal){
  161960. aBuf[0] = (iVal >> 24) & 0xFF;
  161961. aBuf[1] = (iVal >> 16) & 0xFF;
  161962. aBuf[2] = (iVal >> 8) & 0xFF;
  161963. aBuf[3] = (iVal >> 0) & 0xFF;
  161964. }
  161965. static void rbuPutU16(u8 *aBuf, u16 iVal){
  161966. aBuf[0] = (iVal >> 8) & 0xFF;
  161967. aBuf[1] = (iVal >> 0) & 0xFF;
  161968. }
  161969. /*
  161970. ** Read data from an rbuVfs-file.
  161971. */
  161972. static int rbuVfsRead(
  161973. sqlite3_file *pFile,
  161974. void *zBuf,
  161975. int iAmt,
  161976. sqlite_int64 iOfst
  161977. ){
  161978. rbu_file *p = (rbu_file*)pFile;
  161979. sqlite3rbu *pRbu = p->pRbu;
  161980. int rc;
  161981. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  161982. assert( p->openFlags & SQLITE_OPEN_WAL );
  161983. rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
  161984. }else{
  161985. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  161986. && (p->openFlags & SQLITE_OPEN_WAL)
  161987. && iOfst>=pRbu->iOalSz
  161988. ){
  161989. rc = SQLITE_OK;
  161990. memset(zBuf, 0, iAmt);
  161991. }else{
  161992. rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
  161993. #if 1
  161994. /* If this is being called to read the first page of the target
  161995. ** database as part of an rbu vacuum operation, synthesize the
  161996. ** contents of the first page if it does not yet exist. Otherwise,
  161997. ** SQLite will not check for a *-wal file. */
  161998. if( pRbu && rbuIsVacuum(pRbu)
  161999. && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
  162000. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  162001. && pRbu->rc==SQLITE_OK
  162002. ){
  162003. sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
  162004. rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
  162005. if( rc==SQLITE_OK ){
  162006. u8 *aBuf = (u8*)zBuf;
  162007. u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
  162008. rbuPutU32(&aBuf[52], iRoot); /* largest root page number */
  162009. rbuPutU32(&aBuf[36], 0); /* number of free pages */
  162010. rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */
  162011. rbuPutU32(&aBuf[28], 1); /* size of db file in pages */
  162012. rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */
  162013. if( iAmt>100 ){
  162014. memset(&aBuf[100], 0, iAmt-100);
  162015. rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
  162016. aBuf[100] = 0x0D;
  162017. }
  162018. }
  162019. }
  162020. #endif
  162021. }
  162022. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  162023. /* These look like magic numbers. But they are stable, as they are part
  162024. ** of the definition of the SQLite file format, which may not change. */
  162025. u8 *pBuf = (u8*)zBuf;
  162026. p->iCookie = rbuGetU32(&pBuf[24]);
  162027. p->iWriteVer = pBuf[19];
  162028. }
  162029. }
  162030. return rc;
  162031. }
  162032. /*
  162033. ** Write data to an rbuVfs-file.
  162034. */
  162035. static int rbuVfsWrite(
  162036. sqlite3_file *pFile,
  162037. const void *zBuf,
  162038. int iAmt,
  162039. sqlite_int64 iOfst
  162040. ){
  162041. rbu_file *p = (rbu_file*)pFile;
  162042. sqlite3rbu *pRbu = p->pRbu;
  162043. int rc;
  162044. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  162045. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  162046. rc = rbuCaptureDbWrite(p->pRbu, iOfst);
  162047. }else{
  162048. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  162049. && (p->openFlags & SQLITE_OPEN_WAL)
  162050. && iOfst>=pRbu->iOalSz
  162051. ){
  162052. pRbu->iOalSz = iAmt + iOfst;
  162053. }
  162054. rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
  162055. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  162056. /* These look like magic numbers. But they are stable, as they are part
  162057. ** of the definition of the SQLite file format, which may not change. */
  162058. u8 *pBuf = (u8*)zBuf;
  162059. p->iCookie = rbuGetU32(&pBuf[24]);
  162060. p->iWriteVer = pBuf[19];
  162061. }
  162062. }
  162063. return rc;
  162064. }
  162065. /*
  162066. ** Truncate an rbuVfs-file.
  162067. */
  162068. static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
  162069. rbu_file *p = (rbu_file*)pFile;
  162070. return p->pReal->pMethods->xTruncate(p->pReal, size);
  162071. }
  162072. /*
  162073. ** Sync an rbuVfs-file.
  162074. */
  162075. static int rbuVfsSync(sqlite3_file *pFile, int flags){
  162076. rbu_file *p = (rbu_file *)pFile;
  162077. if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
  162078. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  162079. return SQLITE_INTERNAL;
  162080. }
  162081. return SQLITE_OK;
  162082. }
  162083. return p->pReal->pMethods->xSync(p->pReal, flags);
  162084. }
  162085. /*
  162086. ** Return the current file-size of an rbuVfs-file.
  162087. */
  162088. static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  162089. rbu_file *p = (rbu_file *)pFile;
  162090. int rc;
  162091. rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
  162092. /* If this is an RBU vacuum operation and this is the target database,
  162093. ** pretend that it has at least one page. Otherwise, SQLite will not
  162094. ** check for the existance of a *-wal file. rbuVfsRead() contains
  162095. ** similar logic. */
  162096. if( rc==SQLITE_OK && *pSize==0
  162097. && p->pRbu && rbuIsVacuum(p->pRbu)
  162098. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  162099. ){
  162100. *pSize = 1024;
  162101. }
  162102. return rc;
  162103. }
  162104. /*
  162105. ** Lock an rbuVfs-file.
  162106. */
  162107. static int rbuVfsLock(sqlite3_file *pFile, int eLock){
  162108. rbu_file *p = (rbu_file*)pFile;
  162109. sqlite3rbu *pRbu = p->pRbu;
  162110. int rc = SQLITE_OK;
  162111. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  162112. if( eLock==SQLITE_LOCK_EXCLUSIVE
  162113. && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
  162114. ){
  162115. /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
  162116. ** prevents it from checkpointing the database from sqlite3_close(). */
  162117. rc = SQLITE_BUSY;
  162118. }else{
  162119. rc = p->pReal->pMethods->xLock(p->pReal, eLock);
  162120. }
  162121. return rc;
  162122. }
  162123. /*
  162124. ** Unlock an rbuVfs-file.
  162125. */
  162126. static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
  162127. rbu_file *p = (rbu_file *)pFile;
  162128. return p->pReal->pMethods->xUnlock(p->pReal, eLock);
  162129. }
  162130. /*
  162131. ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
  162132. */
  162133. static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  162134. rbu_file *p = (rbu_file *)pFile;
  162135. return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
  162136. }
  162137. /*
  162138. ** File control method. For custom operations on an rbuVfs-file.
  162139. */
  162140. static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
  162141. rbu_file *p = (rbu_file *)pFile;
  162142. int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
  162143. int rc;
  162144. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
  162145. || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
  162146. );
  162147. if( op==SQLITE_FCNTL_RBU ){
  162148. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  162149. /* First try to find another RBU vfs lower down in the vfs stack. If
  162150. ** one is found, this vfs will operate in pass-through mode. The lower
  162151. ** level vfs will do the special RBU handling. */
  162152. rc = xControl(p->pReal, op, pArg);
  162153. if( rc==SQLITE_NOTFOUND ){
  162154. /* Now search for a zipvfs instance lower down in the VFS stack. If
  162155. ** one is found, this is an error. */
  162156. void *dummy = 0;
  162157. rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
  162158. if( rc==SQLITE_OK ){
  162159. rc = SQLITE_ERROR;
  162160. pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
  162161. }else if( rc==SQLITE_NOTFOUND ){
  162162. pRbu->pTargetFd = p;
  162163. p->pRbu = pRbu;
  162164. if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
  162165. rc = SQLITE_OK;
  162166. }
  162167. }
  162168. return rc;
  162169. }
  162170. else if( op==SQLITE_FCNTL_RBUCNT ){
  162171. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  162172. pRbu->nRbu++;
  162173. pRbu->pRbuFd = p;
  162174. p->bNolock = 1;
  162175. }
  162176. rc = xControl(p->pReal, op, pArg);
  162177. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  162178. rbu_vfs *pRbuVfs = p->pRbuVfs;
  162179. char *zIn = *(char**)pArg;
  162180. char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
  162181. *(char**)pArg = zOut;
  162182. if( zOut==0 ) rc = SQLITE_NOMEM;
  162183. }
  162184. return rc;
  162185. }
  162186. /*
  162187. ** Return the sector-size in bytes for an rbuVfs-file.
  162188. */
  162189. static int rbuVfsSectorSize(sqlite3_file *pFile){
  162190. rbu_file *p = (rbu_file *)pFile;
  162191. return p->pReal->pMethods->xSectorSize(p->pReal);
  162192. }
  162193. /*
  162194. ** Return the device characteristic flags supported by an rbuVfs-file.
  162195. */
  162196. static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
  162197. rbu_file *p = (rbu_file *)pFile;
  162198. return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
  162199. }
  162200. /*
  162201. ** Take or release a shared-memory lock.
  162202. */
  162203. static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
  162204. rbu_file *p = (rbu_file*)pFile;
  162205. sqlite3rbu *pRbu = p->pRbu;
  162206. int rc = SQLITE_OK;
  162207. #ifdef SQLITE_AMALGAMATION
  162208. assert( WAL_CKPT_LOCK==1 );
  162209. #endif
  162210. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  162211. if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
  162212. /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
  162213. ** taking this lock also prevents any checkpoints from occurring.
  162214. ** todo: really, it's not clear why this might occur, as
  162215. ** wal_autocheckpoint ought to be turned off. */
  162216. if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
  162217. }else{
  162218. int bCapture = 0;
  162219. if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
  162220. && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
  162221. && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
  162222. ){
  162223. bCapture = 1;
  162224. }
  162225. if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
  162226. rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
  162227. if( bCapture && rc==SQLITE_OK ){
  162228. pRbu->mLock |= (1 << ofst);
  162229. }
  162230. }
  162231. }
  162232. return rc;
  162233. }
  162234. /*
  162235. ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
  162236. */
  162237. static int rbuVfsShmMap(
  162238. sqlite3_file *pFile,
  162239. int iRegion,
  162240. int szRegion,
  162241. int isWrite,
  162242. void volatile **pp
  162243. ){
  162244. rbu_file *p = (rbu_file*)pFile;
  162245. int rc = SQLITE_OK;
  162246. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  162247. /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
  162248. ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
  162249. ** instead of a file on disk. */
  162250. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  162251. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  162252. if( iRegion<=p->nShm ){
  162253. int nByte = (iRegion+1) * sizeof(char*);
  162254. char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
  162255. if( apNew==0 ){
  162256. rc = SQLITE_NOMEM;
  162257. }else{
  162258. memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
  162259. p->apShm = apNew;
  162260. p->nShm = iRegion+1;
  162261. }
  162262. }
  162263. if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
  162264. char *pNew = (char*)sqlite3_malloc64(szRegion);
  162265. if( pNew==0 ){
  162266. rc = SQLITE_NOMEM;
  162267. }else{
  162268. memset(pNew, 0, szRegion);
  162269. p->apShm[iRegion] = pNew;
  162270. }
  162271. }
  162272. if( rc==SQLITE_OK ){
  162273. *pp = p->apShm[iRegion];
  162274. }else{
  162275. *pp = 0;
  162276. }
  162277. }else{
  162278. assert( p->apShm==0 );
  162279. rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
  162280. }
  162281. return rc;
  162282. }
  162283. /*
  162284. ** Memory barrier.
  162285. */
  162286. static void rbuVfsShmBarrier(sqlite3_file *pFile){
  162287. rbu_file *p = (rbu_file *)pFile;
  162288. p->pReal->pMethods->xShmBarrier(p->pReal);
  162289. }
  162290. /*
  162291. ** The xShmUnmap method.
  162292. */
  162293. static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
  162294. rbu_file *p = (rbu_file*)pFile;
  162295. int rc = SQLITE_OK;
  162296. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  162297. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  162298. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  162299. /* no-op */
  162300. }else{
  162301. /* Release the checkpointer and writer locks */
  162302. rbuUnlockShm(p);
  162303. rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
  162304. }
  162305. return rc;
  162306. }
  162307. /*
  162308. ** Given that zWal points to a buffer containing a wal file name passed to
  162309. ** either the xOpen() or xAccess() VFS method, return a pointer to the
  162310. ** file-handle opened by the same database connection on the corresponding
  162311. ** database file.
  162312. */
  162313. static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
  162314. rbu_file *pDb;
  162315. sqlite3_mutex_enter(pRbuVfs->mutex);
  162316. for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
  162317. sqlite3_mutex_leave(pRbuVfs->mutex);
  162318. return pDb;
  162319. }
  162320. /*
  162321. ** A main database named zName has just been opened. The following
  162322. ** function returns a pointer to a buffer owned by SQLite that contains
  162323. ** the name of the *-wal file this db connection will use. SQLite
  162324. ** happens to pass a pointer to this buffer when using xAccess()
  162325. ** or xOpen() to operate on the *-wal file.
  162326. */
  162327. static const char *rbuMainToWal(const char *zName, int flags){
  162328. int n = (int)strlen(zName);
  162329. const char *z = &zName[n];
  162330. if( flags & SQLITE_OPEN_URI ){
  162331. int odd = 0;
  162332. while( 1 ){
  162333. if( z[0]==0 ){
  162334. odd = 1 - odd;
  162335. if( odd && z[1]==0 ) break;
  162336. }
  162337. z++;
  162338. }
  162339. z += 2;
  162340. }else{
  162341. while( *z==0 ) z++;
  162342. }
  162343. z += (n + 8 + 1);
  162344. return z;
  162345. }
  162346. /*
  162347. ** Open an rbu file handle.
  162348. */
  162349. static int rbuVfsOpen(
  162350. sqlite3_vfs *pVfs,
  162351. const char *zName,
  162352. sqlite3_file *pFile,
  162353. int flags,
  162354. int *pOutFlags
  162355. ){
  162356. static sqlite3_io_methods rbuvfs_io_methods = {
  162357. 2, /* iVersion */
  162358. rbuVfsClose, /* xClose */
  162359. rbuVfsRead, /* xRead */
  162360. rbuVfsWrite, /* xWrite */
  162361. rbuVfsTruncate, /* xTruncate */
  162362. rbuVfsSync, /* xSync */
  162363. rbuVfsFileSize, /* xFileSize */
  162364. rbuVfsLock, /* xLock */
  162365. rbuVfsUnlock, /* xUnlock */
  162366. rbuVfsCheckReservedLock, /* xCheckReservedLock */
  162367. rbuVfsFileControl, /* xFileControl */
  162368. rbuVfsSectorSize, /* xSectorSize */
  162369. rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
  162370. rbuVfsShmMap, /* xShmMap */
  162371. rbuVfsShmLock, /* xShmLock */
  162372. rbuVfsShmBarrier, /* xShmBarrier */
  162373. rbuVfsShmUnmap, /* xShmUnmap */
  162374. 0, 0 /* xFetch, xUnfetch */
  162375. };
  162376. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  162377. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  162378. rbu_file *pFd = (rbu_file *)pFile;
  162379. int rc = SQLITE_OK;
  162380. const char *zOpen = zName;
  162381. int oflags = flags;
  162382. memset(pFd, 0, sizeof(rbu_file));
  162383. pFd->pReal = (sqlite3_file*)&pFd[1];
  162384. pFd->pRbuVfs = pRbuVfs;
  162385. pFd->openFlags = flags;
  162386. if( zName ){
  162387. if( flags & SQLITE_OPEN_MAIN_DB ){
  162388. /* A main database has just been opened. The following block sets
  162389. ** (pFd->zWal) to point to a buffer owned by SQLite that contains
  162390. ** the name of the *-wal file this db connection will use. SQLite
  162391. ** happens to pass a pointer to this buffer when using xAccess()
  162392. ** or xOpen() to operate on the *-wal file. */
  162393. pFd->zWal = rbuMainToWal(zName, flags);
  162394. }
  162395. else if( flags & SQLITE_OPEN_WAL ){
  162396. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
  162397. if( pDb ){
  162398. if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  162399. /* This call is to open a *-wal file. Intead, open the *-oal. This
  162400. ** code ensures that the string passed to xOpen() is terminated by a
  162401. ** pair of '\0' bytes in case the VFS attempts to extract a URI
  162402. ** parameter from it. */
  162403. const char *zBase = zName;
  162404. size_t nCopy;
  162405. char *zCopy;
  162406. if( rbuIsVacuum(pDb->pRbu) ){
  162407. zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
  162408. zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
  162409. }
  162410. nCopy = strlen(zBase);
  162411. zCopy = sqlite3_malloc64(nCopy+2);
  162412. if( zCopy ){
  162413. memcpy(zCopy, zBase, nCopy);
  162414. zCopy[nCopy-3] = 'o';
  162415. zCopy[nCopy] = '\0';
  162416. zCopy[nCopy+1] = '\0';
  162417. zOpen = (const char*)(pFd->zDel = zCopy);
  162418. }else{
  162419. rc = SQLITE_NOMEM;
  162420. }
  162421. pFd->pRbu = pDb->pRbu;
  162422. }
  162423. pDb->pWalFd = pFd;
  162424. }
  162425. }
  162426. }
  162427. if( oflags & SQLITE_OPEN_MAIN_DB
  162428. && sqlite3_uri_boolean(zName, "rbu_memory", 0)
  162429. ){
  162430. assert( oflags & SQLITE_OPEN_MAIN_DB );
  162431. oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  162432. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  162433. zOpen = 0;
  162434. }
  162435. if( rc==SQLITE_OK ){
  162436. rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
  162437. }
  162438. if( pFd->pReal->pMethods ){
  162439. /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
  162440. ** pointer and, if the file is a main database file, link it into the
  162441. ** mutex protected linked list of all such files. */
  162442. pFile->pMethods = &rbuvfs_io_methods;
  162443. if( flags & SQLITE_OPEN_MAIN_DB ){
  162444. sqlite3_mutex_enter(pRbuVfs->mutex);
  162445. pFd->pMainNext = pRbuVfs->pMain;
  162446. pRbuVfs->pMain = pFd;
  162447. sqlite3_mutex_leave(pRbuVfs->mutex);
  162448. }
  162449. }else{
  162450. sqlite3_free(pFd->zDel);
  162451. }
  162452. return rc;
  162453. }
  162454. /*
  162455. ** Delete the file located at zPath.
  162456. */
  162457. static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  162458. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  162459. return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
  162460. }
  162461. /*
  162462. ** Test for access permissions. Return true if the requested permission
  162463. ** is available, or false otherwise.
  162464. */
  162465. static int rbuVfsAccess(
  162466. sqlite3_vfs *pVfs,
  162467. const char *zPath,
  162468. int flags,
  162469. int *pResOut
  162470. ){
  162471. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  162472. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  162473. int rc;
  162474. rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
  162475. /* If this call is to check if a *-wal file associated with an RBU target
  162476. ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
  162477. ** the following special handling is activated:
  162478. **
  162479. ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
  162480. ** ensures that the RBU extension never tries to update a database
  162481. ** in wal mode, even if the first page of the database file has
  162482. ** been damaged.
  162483. **
  162484. ** b) if the *-wal file does not exist, claim that it does anyway,
  162485. ** causing SQLite to call xOpen() to open it. This call will also
  162486. ** be intercepted (see the rbuVfsOpen() function) and the *-oal
  162487. ** file opened instead.
  162488. */
  162489. if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
  162490. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
  162491. if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  162492. if( *pResOut ){
  162493. rc = SQLITE_CANTOPEN;
  162494. }else{
  162495. *pResOut = 1;
  162496. }
  162497. }
  162498. }
  162499. return rc;
  162500. }
  162501. /*
  162502. ** Populate buffer zOut with the full canonical pathname corresponding
  162503. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  162504. ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
  162505. */
  162506. static int rbuVfsFullPathname(
  162507. sqlite3_vfs *pVfs,
  162508. const char *zPath,
  162509. int nOut,
  162510. char *zOut
  162511. ){
  162512. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  162513. return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
  162514. }
  162515. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  162516. /*
  162517. ** Open the dynamic library located at zPath and return a handle.
  162518. */
  162519. static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  162520. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  162521. return pRealVfs->xDlOpen(pRealVfs, zPath);
  162522. }
  162523. /*
  162524. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  162525. ** utf-8 string describing the most recent error encountered associated
  162526. ** with dynamic libraries.
  162527. */
  162528. static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  162529. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  162530. pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
  162531. }
  162532. /*
  162533. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  162534. */
  162535. static void (*rbuVfsDlSym(
  162536. sqlite3_vfs *pVfs,
  162537. void *pArg,
  162538. const char *zSym
  162539. ))(void){
  162540. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  162541. return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
  162542. }
  162543. /*
  162544. ** Close the dynamic library handle pHandle.
  162545. */
  162546. static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  162547. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  162548. pRealVfs->xDlClose(pRealVfs, pHandle);
  162549. }
  162550. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  162551. /*
  162552. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  162553. ** random data.
  162554. */
  162555. static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  162556. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  162557. return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
  162558. }
  162559. /*
  162560. ** Sleep for nMicro microseconds. Return the number of microseconds
  162561. ** actually slept.
  162562. */
  162563. static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
  162564. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  162565. return pRealVfs->xSleep(pRealVfs, nMicro);
  162566. }
  162567. /*
  162568. ** Return the current time as a Julian Day number in *pTimeOut.
  162569. */
  162570. static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  162571. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  162572. return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
  162573. }
  162574. /*
  162575. ** No-op.
  162576. */
  162577. static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  162578. return 0;
  162579. }
  162580. /*
  162581. ** Deregister and destroy an RBU vfs created by an earlier call to
  162582. ** sqlite3rbu_create_vfs().
  162583. */
  162584. SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
  162585. sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
  162586. if( pVfs && pVfs->xOpen==rbuVfsOpen ){
  162587. sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
  162588. sqlite3_vfs_unregister(pVfs);
  162589. sqlite3_free(pVfs);
  162590. }
  162591. }
  162592. /*
  162593. ** Create an RBU VFS named zName that accesses the underlying file-system
  162594. ** via existing VFS zParent. The new object is registered as a non-default
  162595. ** VFS with SQLite before returning.
  162596. */
  162597. SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
  162598. /* Template for VFS */
  162599. static sqlite3_vfs vfs_template = {
  162600. 1, /* iVersion */
  162601. 0, /* szOsFile */
  162602. 0, /* mxPathname */
  162603. 0, /* pNext */
  162604. 0, /* zName */
  162605. 0, /* pAppData */
  162606. rbuVfsOpen, /* xOpen */
  162607. rbuVfsDelete, /* xDelete */
  162608. rbuVfsAccess, /* xAccess */
  162609. rbuVfsFullPathname, /* xFullPathname */
  162610. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  162611. rbuVfsDlOpen, /* xDlOpen */
  162612. rbuVfsDlError, /* xDlError */
  162613. rbuVfsDlSym, /* xDlSym */
  162614. rbuVfsDlClose, /* xDlClose */
  162615. #else
  162616. 0, 0, 0, 0,
  162617. #endif
  162618. rbuVfsRandomness, /* xRandomness */
  162619. rbuVfsSleep, /* xSleep */
  162620. rbuVfsCurrentTime, /* xCurrentTime */
  162621. rbuVfsGetLastError, /* xGetLastError */
  162622. 0, /* xCurrentTimeInt64 (version 2) */
  162623. 0, 0, 0 /* Unimplemented version 3 methods */
  162624. };
  162625. rbu_vfs *pNew = 0; /* Newly allocated VFS */
  162626. int rc = SQLITE_OK;
  162627. size_t nName;
  162628. size_t nByte;
  162629. nName = strlen(zName);
  162630. nByte = sizeof(rbu_vfs) + nName + 1;
  162631. pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
  162632. if( pNew==0 ){
  162633. rc = SQLITE_NOMEM;
  162634. }else{
  162635. sqlite3_vfs *pParent; /* Parent VFS */
  162636. memset(pNew, 0, nByte);
  162637. pParent = sqlite3_vfs_find(zParent);
  162638. if( pParent==0 ){
  162639. rc = SQLITE_NOTFOUND;
  162640. }else{
  162641. char *zSpace;
  162642. memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
  162643. pNew->base.mxPathname = pParent->mxPathname;
  162644. pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
  162645. pNew->pRealVfs = pParent;
  162646. pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
  162647. memcpy(zSpace, zName, nName);
  162648. /* Allocate the mutex and register the new VFS (not as the default) */
  162649. pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
  162650. if( pNew->mutex==0 ){
  162651. rc = SQLITE_NOMEM;
  162652. }else{
  162653. rc = sqlite3_vfs_register(&pNew->base, 0);
  162654. }
  162655. }
  162656. if( rc!=SQLITE_OK ){
  162657. sqlite3_mutex_free(pNew->mutex);
  162658. sqlite3_free(pNew);
  162659. }
  162660. }
  162661. return rc;
  162662. }
  162663. /**************************************************************************/
  162664. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
  162665. /************** End of sqlite3rbu.c ******************************************/
  162666. /************** Begin file dbstat.c ******************************************/
  162667. /*
  162668. ** 2010 July 12
  162669. **
  162670. ** The author disclaims copyright to this source code. In place of
  162671. ** a legal notice, here is a blessing:
  162672. **
  162673. ** May you do good and not evil.
  162674. ** May you find forgiveness for yourself and forgive others.
  162675. ** May you share freely, never taking more than you give.
  162676. **
  162677. ******************************************************************************
  162678. **
  162679. ** This file contains an implementation of the "dbstat" virtual table.
  162680. **
  162681. ** The dbstat virtual table is used to extract low-level formatting
  162682. ** information from an SQLite database in order to implement the
  162683. ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
  162684. ** for an example implementation.
  162685. **
  162686. ** Additional information is available on the "dbstat.html" page of the
  162687. ** official SQLite documentation.
  162688. */
  162689. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  162690. #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
  162691. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  162692. /*
  162693. ** Page paths:
  162694. **
  162695. ** The value of the 'path' column describes the path taken from the
  162696. ** root-node of the b-tree structure to each page. The value of the
  162697. ** root-node path is '/'.
  162698. **
  162699. ** The value of the path for the left-most child page of the root of
  162700. ** a b-tree is '/000/'. (Btrees store content ordered from left to right
  162701. ** so the pages to the left have smaller keys than the pages to the right.)
  162702. ** The next to left-most child of the root page is
  162703. ** '/001', and so on, each sibling page identified by a 3-digit hex
  162704. ** value. The children of the 451st left-most sibling have paths such
  162705. ** as '/1c2/000/, '/1c2/001/' etc.
  162706. **
  162707. ** Overflow pages are specified by appending a '+' character and a
  162708. ** six-digit hexadecimal value to the path to the cell they are linked
  162709. ** from. For example, the three overflow pages in a chain linked from
  162710. ** the left-most cell of the 450th child of the root page are identified
  162711. ** by the paths:
  162712. **
  162713. ** '/1c2/000+000000' // First page in overflow chain
  162714. ** '/1c2/000+000001' // Second page in overflow chain
  162715. ** '/1c2/000+000002' // Third page in overflow chain
  162716. **
  162717. ** If the paths are sorted using the BINARY collation sequence, then
  162718. ** the overflow pages associated with a cell will appear earlier in the
  162719. ** sort-order than its child page:
  162720. **
  162721. ** '/1c2/000/' // Left-most child of 451st child of root
  162722. */
  162723. #define VTAB_SCHEMA \
  162724. "CREATE TABLE xx( " \
  162725. " name TEXT, /* Name of table or index */" \
  162726. " path TEXT, /* Path to page from root */" \
  162727. " pageno INTEGER, /* Page number */" \
  162728. " pagetype TEXT, /* 'internal', 'leaf' or 'overflow' */" \
  162729. " ncell INTEGER, /* Cells on page (0 for overflow) */" \
  162730. " payload INTEGER, /* Bytes of payload on this page */" \
  162731. " unused INTEGER, /* Bytes of unused space on this page */" \
  162732. " mx_payload INTEGER, /* Largest payload size of all cells */" \
  162733. " pgoffset INTEGER, /* Offset of page in file */" \
  162734. " pgsize INTEGER, /* Size of the page */" \
  162735. " schema TEXT HIDDEN /* Database schema being analyzed */" \
  162736. ");"
  162737. typedef struct StatTable StatTable;
  162738. typedef struct StatCursor StatCursor;
  162739. typedef struct StatPage StatPage;
  162740. typedef struct StatCell StatCell;
  162741. struct StatCell {
  162742. int nLocal; /* Bytes of local payload */
  162743. u32 iChildPg; /* Child node (or 0 if this is a leaf) */
  162744. int nOvfl; /* Entries in aOvfl[] */
  162745. u32 *aOvfl; /* Array of overflow page numbers */
  162746. int nLastOvfl; /* Bytes of payload on final overflow page */
  162747. int iOvfl; /* Iterates through aOvfl[] */
  162748. };
  162749. struct StatPage {
  162750. u32 iPgno;
  162751. DbPage *pPg;
  162752. int iCell;
  162753. char *zPath; /* Path to this page */
  162754. /* Variables populated by statDecodePage(): */
  162755. u8 flags; /* Copy of flags byte */
  162756. int nCell; /* Number of cells on page */
  162757. int nUnused; /* Number of unused bytes on page */
  162758. StatCell *aCell; /* Array of parsed cells */
  162759. u32 iRightChildPg; /* Right-child page number (or 0) */
  162760. int nMxPayload; /* Largest payload of any cell on this page */
  162761. };
  162762. struct StatCursor {
  162763. sqlite3_vtab_cursor base;
  162764. sqlite3_stmt *pStmt; /* Iterates through set of root pages */
  162765. int isEof; /* After pStmt has returned SQLITE_DONE */
  162766. int iDb; /* Schema used for this query */
  162767. StatPage aPage[32];
  162768. int iPage; /* Current entry in aPage[] */
  162769. /* Values to return. */
  162770. char *zName; /* Value of 'name' column */
  162771. char *zPath; /* Value of 'path' column */
  162772. u32 iPageno; /* Value of 'pageno' column */
  162773. char *zPagetype; /* Value of 'pagetype' column */
  162774. int nCell; /* Value of 'ncell' column */
  162775. int nPayload; /* Value of 'payload' column */
  162776. int nUnused; /* Value of 'unused' column */
  162777. int nMxPayload; /* Value of 'mx_payload' column */
  162778. i64 iOffset; /* Value of 'pgOffset' column */
  162779. int szPage; /* Value of 'pgSize' column */
  162780. };
  162781. struct StatTable {
  162782. sqlite3_vtab base;
  162783. sqlite3 *db;
  162784. int iDb; /* Index of database to analyze */
  162785. };
  162786. #ifndef get2byte
  162787. # define get2byte(x) ((x)[0]<<8 | (x)[1])
  162788. #endif
  162789. /*
  162790. ** Connect to or create a statvfs virtual table.
  162791. */
  162792. static int statConnect(
  162793. sqlite3 *db,
  162794. void *pAux,
  162795. int argc, const char *const*argv,
  162796. sqlite3_vtab **ppVtab,
  162797. char **pzErr
  162798. ){
  162799. StatTable *pTab = 0;
  162800. int rc = SQLITE_OK;
  162801. int iDb;
  162802. if( argc>=4 ){
  162803. Token nm;
  162804. sqlite3TokenInit(&nm, (char*)argv[3]);
  162805. iDb = sqlite3FindDb(db, &nm);
  162806. if( iDb<0 ){
  162807. *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
  162808. return SQLITE_ERROR;
  162809. }
  162810. }else{
  162811. iDb = 0;
  162812. }
  162813. rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
  162814. if( rc==SQLITE_OK ){
  162815. pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
  162816. if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  162817. }
  162818. assert( rc==SQLITE_OK || pTab==0 );
  162819. if( rc==SQLITE_OK ){
  162820. memset(pTab, 0, sizeof(StatTable));
  162821. pTab->db = db;
  162822. pTab->iDb = iDb;
  162823. }
  162824. *ppVtab = (sqlite3_vtab*)pTab;
  162825. return rc;
  162826. }
  162827. /*
  162828. ** Disconnect from or destroy a statvfs virtual table.
  162829. */
  162830. static int statDisconnect(sqlite3_vtab *pVtab){
  162831. sqlite3_free(pVtab);
  162832. return SQLITE_OK;
  162833. }
  162834. /*
  162835. ** There is no "best-index". This virtual table always does a linear
  162836. ** scan. However, a schema=? constraint should cause this table to
  162837. ** operate on a different database schema, so check for it.
  162838. **
  162839. ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
  162840. */
  162841. static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  162842. int i;
  162843. pIdxInfo->estimatedCost = 1.0e6; /* Initial cost estimate */
  162844. /* Look for a valid schema=? constraint. If found, change the idxNum to
  162845. ** 1 and request the value of that constraint be sent to xFilter. And
  162846. ** lower the cost estimate to encourage the constrained version to be
  162847. ** used.
  162848. */
  162849. for(i=0; i<pIdxInfo->nConstraint; i++){
  162850. if( pIdxInfo->aConstraint[i].usable==0 ) continue;
  162851. if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  162852. if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
  162853. pIdxInfo->idxNum = 1;
  162854. pIdxInfo->estimatedCost = 1.0;
  162855. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  162856. pIdxInfo->aConstraintUsage[i].omit = 1;
  162857. break;
  162858. }
  162859. /* Records are always returned in ascending order of (name, path).
  162860. ** If this will satisfy the client, set the orderByConsumed flag so that
  162861. ** SQLite does not do an external sort.
  162862. */
  162863. if( ( pIdxInfo->nOrderBy==1
  162864. && pIdxInfo->aOrderBy[0].iColumn==0
  162865. && pIdxInfo->aOrderBy[0].desc==0
  162866. ) ||
  162867. ( pIdxInfo->nOrderBy==2
  162868. && pIdxInfo->aOrderBy[0].iColumn==0
  162869. && pIdxInfo->aOrderBy[0].desc==0
  162870. && pIdxInfo->aOrderBy[1].iColumn==1
  162871. && pIdxInfo->aOrderBy[1].desc==0
  162872. )
  162873. ){
  162874. pIdxInfo->orderByConsumed = 1;
  162875. }
  162876. return SQLITE_OK;
  162877. }
  162878. /*
  162879. ** Open a new statvfs cursor.
  162880. */
  162881. static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  162882. StatTable *pTab = (StatTable *)pVTab;
  162883. StatCursor *pCsr;
  162884. pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
  162885. if( pCsr==0 ){
  162886. return SQLITE_NOMEM_BKPT;
  162887. }else{
  162888. memset(pCsr, 0, sizeof(StatCursor));
  162889. pCsr->base.pVtab = pVTab;
  162890. pCsr->iDb = pTab->iDb;
  162891. }
  162892. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  162893. return SQLITE_OK;
  162894. }
  162895. static void statClearPage(StatPage *p){
  162896. int i;
  162897. if( p->aCell ){
  162898. for(i=0; i<p->nCell; i++){
  162899. sqlite3_free(p->aCell[i].aOvfl);
  162900. }
  162901. sqlite3_free(p->aCell);
  162902. }
  162903. sqlite3PagerUnref(p->pPg);
  162904. sqlite3_free(p->zPath);
  162905. memset(p, 0, sizeof(StatPage));
  162906. }
  162907. static void statResetCsr(StatCursor *pCsr){
  162908. int i;
  162909. sqlite3_reset(pCsr->pStmt);
  162910. for(i=0; i<ArraySize(pCsr->aPage); i++){
  162911. statClearPage(&pCsr->aPage[i]);
  162912. }
  162913. pCsr->iPage = 0;
  162914. sqlite3_free(pCsr->zPath);
  162915. pCsr->zPath = 0;
  162916. pCsr->isEof = 0;
  162917. }
  162918. /*
  162919. ** Close a statvfs cursor.
  162920. */
  162921. static int statClose(sqlite3_vtab_cursor *pCursor){
  162922. StatCursor *pCsr = (StatCursor *)pCursor;
  162923. statResetCsr(pCsr);
  162924. sqlite3_finalize(pCsr->pStmt);
  162925. sqlite3_free(pCsr);
  162926. return SQLITE_OK;
  162927. }
  162928. static void getLocalPayload(
  162929. int nUsable, /* Usable bytes per page */
  162930. u8 flags, /* Page flags */
  162931. int nTotal, /* Total record (payload) size */
  162932. int *pnLocal /* OUT: Bytes stored locally */
  162933. ){
  162934. int nLocal;
  162935. int nMinLocal;
  162936. int nMaxLocal;
  162937. if( flags==0x0D ){ /* Table leaf node */
  162938. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  162939. nMaxLocal = nUsable - 35;
  162940. }else{ /* Index interior and leaf nodes */
  162941. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  162942. nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
  162943. }
  162944. nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
  162945. if( nLocal>nMaxLocal ) nLocal = nMinLocal;
  162946. *pnLocal = nLocal;
  162947. }
  162948. static int statDecodePage(Btree *pBt, StatPage *p){
  162949. int nUnused;
  162950. int iOff;
  162951. int nHdr;
  162952. int isLeaf;
  162953. int szPage;
  162954. u8 *aData = sqlite3PagerGetData(p->pPg);
  162955. u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
  162956. p->flags = aHdr[0];
  162957. p->nCell = get2byte(&aHdr[3]);
  162958. p->nMxPayload = 0;
  162959. isLeaf = (p->flags==0x0A || p->flags==0x0D);
  162960. nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
  162961. nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
  162962. nUnused += (int)aHdr[7];
  162963. iOff = get2byte(&aHdr[1]);
  162964. while( iOff ){
  162965. nUnused += get2byte(&aData[iOff+2]);
  162966. iOff = get2byte(&aData[iOff]);
  162967. }
  162968. p->nUnused = nUnused;
  162969. p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
  162970. szPage = sqlite3BtreeGetPageSize(pBt);
  162971. if( p->nCell ){
  162972. int i; /* Used to iterate through cells */
  162973. int nUsable; /* Usable bytes per page */
  162974. sqlite3BtreeEnter(pBt);
  162975. nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
  162976. sqlite3BtreeLeave(pBt);
  162977. p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
  162978. if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
  162979. memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
  162980. for(i=0; i<p->nCell; i++){
  162981. StatCell *pCell = &p->aCell[i];
  162982. iOff = get2byte(&aData[nHdr+i*2]);
  162983. if( !isLeaf ){
  162984. pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
  162985. iOff += 4;
  162986. }
  162987. if( p->flags==0x05 ){
  162988. /* A table interior node. nPayload==0. */
  162989. }else{
  162990. u32 nPayload; /* Bytes of payload total (local+overflow) */
  162991. int nLocal; /* Bytes of payload stored locally */
  162992. iOff += getVarint32(&aData[iOff], nPayload);
  162993. if( p->flags==0x0D ){
  162994. u64 dummy;
  162995. iOff += sqlite3GetVarint(&aData[iOff], &dummy);
  162996. }
  162997. if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
  162998. getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
  162999. pCell->nLocal = nLocal;
  163000. assert( nLocal>=0 );
  163001. assert( nPayload>=(u32)nLocal );
  163002. assert( nLocal<=(nUsable-35) );
  163003. if( nPayload>(u32)nLocal ){
  163004. int j;
  163005. int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
  163006. pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
  163007. pCell->nOvfl = nOvfl;
  163008. pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
  163009. if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
  163010. pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
  163011. for(j=1; j<nOvfl; j++){
  163012. int rc;
  163013. u32 iPrev = pCell->aOvfl[j-1];
  163014. DbPage *pPg = 0;
  163015. rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
  163016. if( rc!=SQLITE_OK ){
  163017. assert( pPg==0 );
  163018. return rc;
  163019. }
  163020. pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
  163021. sqlite3PagerUnref(pPg);
  163022. }
  163023. }
  163024. }
  163025. }
  163026. }
  163027. return SQLITE_OK;
  163028. }
  163029. /*
  163030. ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
  163031. ** the current value of pCsr->iPageno.
  163032. */
  163033. static void statSizeAndOffset(StatCursor *pCsr){
  163034. StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
  163035. Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
  163036. Pager *pPager = sqlite3BtreePager(pBt);
  163037. sqlite3_file *fd;
  163038. sqlite3_int64 x[2];
  163039. /* The default page size and offset */
  163040. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  163041. pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
  163042. /* If connected to a ZIPVFS backend, override the page size and
  163043. ** offset with actual values obtained from ZIPVFS.
  163044. */
  163045. fd = sqlite3PagerFile(pPager);
  163046. x[0] = pCsr->iPageno;
  163047. if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
  163048. pCsr->iOffset = x[0];
  163049. pCsr->szPage = (int)x[1];
  163050. }
  163051. }
  163052. /*
  163053. ** Move a statvfs cursor to the next entry in the file.
  163054. */
  163055. static int statNext(sqlite3_vtab_cursor *pCursor){
  163056. int rc;
  163057. int nPayload;
  163058. char *z;
  163059. StatCursor *pCsr = (StatCursor *)pCursor;
  163060. StatTable *pTab = (StatTable *)pCursor->pVtab;
  163061. Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
  163062. Pager *pPager = sqlite3BtreePager(pBt);
  163063. sqlite3_free(pCsr->zPath);
  163064. pCsr->zPath = 0;
  163065. statNextRestart:
  163066. if( pCsr->aPage[0].pPg==0 ){
  163067. rc = sqlite3_step(pCsr->pStmt);
  163068. if( rc==SQLITE_ROW ){
  163069. int nPage;
  163070. u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
  163071. sqlite3PagerPagecount(pPager, &nPage);
  163072. if( nPage==0 ){
  163073. pCsr->isEof = 1;
  163074. return sqlite3_reset(pCsr->pStmt);
  163075. }
  163076. rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
  163077. pCsr->aPage[0].iPgno = iRoot;
  163078. pCsr->aPage[0].iCell = 0;
  163079. pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
  163080. pCsr->iPage = 0;
  163081. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  163082. }else{
  163083. pCsr->isEof = 1;
  163084. return sqlite3_reset(pCsr->pStmt);
  163085. }
  163086. }else{
  163087. /* Page p itself has already been visited. */
  163088. StatPage *p = &pCsr->aPage[pCsr->iPage];
  163089. while( p->iCell<p->nCell ){
  163090. StatCell *pCell = &p->aCell[p->iCell];
  163091. if( pCell->iOvfl<pCell->nOvfl ){
  163092. int nUsable;
  163093. sqlite3BtreeEnter(pBt);
  163094. nUsable = sqlite3BtreeGetPageSize(pBt) -
  163095. sqlite3BtreeGetReserveNoMutex(pBt);
  163096. sqlite3BtreeLeave(pBt);
  163097. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  163098. pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
  163099. pCsr->zPagetype = "overflow";
  163100. pCsr->nCell = 0;
  163101. pCsr->nMxPayload = 0;
  163102. pCsr->zPath = z = sqlite3_mprintf(
  163103. "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
  163104. );
  163105. if( pCell->iOvfl<pCell->nOvfl-1 ){
  163106. pCsr->nUnused = 0;
  163107. pCsr->nPayload = nUsable - 4;
  163108. }else{
  163109. pCsr->nPayload = pCell->nLastOvfl;
  163110. pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
  163111. }
  163112. pCell->iOvfl++;
  163113. statSizeAndOffset(pCsr);
  163114. return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  163115. }
  163116. if( p->iRightChildPg ) break;
  163117. p->iCell++;
  163118. }
  163119. if( !p->iRightChildPg || p->iCell>p->nCell ){
  163120. statClearPage(p);
  163121. if( pCsr->iPage==0 ) return statNext(pCursor);
  163122. pCsr->iPage--;
  163123. goto statNextRestart; /* Tail recursion */
  163124. }
  163125. pCsr->iPage++;
  163126. assert( p==&pCsr->aPage[pCsr->iPage-1] );
  163127. if( p->iCell==p->nCell ){
  163128. p[1].iPgno = p->iRightChildPg;
  163129. }else{
  163130. p[1].iPgno = p->aCell[p->iCell].iChildPg;
  163131. }
  163132. rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
  163133. p[1].iCell = 0;
  163134. p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
  163135. p->iCell++;
  163136. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  163137. }
  163138. /* Populate the StatCursor fields with the values to be returned
  163139. ** by the xColumn() and xRowid() methods.
  163140. */
  163141. if( rc==SQLITE_OK ){
  163142. int i;
  163143. StatPage *p = &pCsr->aPage[pCsr->iPage];
  163144. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  163145. pCsr->iPageno = p->iPgno;
  163146. rc = statDecodePage(pBt, p);
  163147. if( rc==SQLITE_OK ){
  163148. statSizeAndOffset(pCsr);
  163149. switch( p->flags ){
  163150. case 0x05: /* table internal */
  163151. case 0x02: /* index internal */
  163152. pCsr->zPagetype = "internal";
  163153. break;
  163154. case 0x0D: /* table leaf */
  163155. case 0x0A: /* index leaf */
  163156. pCsr->zPagetype = "leaf";
  163157. break;
  163158. default:
  163159. pCsr->zPagetype = "corrupted";
  163160. break;
  163161. }
  163162. pCsr->nCell = p->nCell;
  163163. pCsr->nUnused = p->nUnused;
  163164. pCsr->nMxPayload = p->nMxPayload;
  163165. pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
  163166. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  163167. nPayload = 0;
  163168. for(i=0; i<p->nCell; i++){
  163169. nPayload += p->aCell[i].nLocal;
  163170. }
  163171. pCsr->nPayload = nPayload;
  163172. }
  163173. }
  163174. return rc;
  163175. }
  163176. static int statEof(sqlite3_vtab_cursor *pCursor){
  163177. StatCursor *pCsr = (StatCursor *)pCursor;
  163178. return pCsr->isEof;
  163179. }
  163180. static int statFilter(
  163181. sqlite3_vtab_cursor *pCursor,
  163182. int idxNum, const char *idxStr,
  163183. int argc, sqlite3_value **argv
  163184. ){
  163185. StatCursor *pCsr = (StatCursor *)pCursor;
  163186. StatTable *pTab = (StatTable*)(pCursor->pVtab);
  163187. char *zSql;
  163188. int rc = SQLITE_OK;
  163189. char *zMaster;
  163190. if( idxNum==1 ){
  163191. const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
  163192. pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
  163193. if( pCsr->iDb<0 ){
  163194. sqlite3_free(pCursor->pVtab->zErrMsg);
  163195. pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
  163196. return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
  163197. }
  163198. }else{
  163199. pCsr->iDb = pTab->iDb;
  163200. }
  163201. statResetCsr(pCsr);
  163202. sqlite3_finalize(pCsr->pStmt);
  163203. pCsr->pStmt = 0;
  163204. zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
  163205. zSql = sqlite3_mprintf(
  163206. "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
  163207. " UNION ALL "
  163208. "SELECT name, rootpage, type"
  163209. " FROM \"%w\".%s WHERE rootpage!=0"
  163210. " ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName, zMaster);
  163211. if( zSql==0 ){
  163212. return SQLITE_NOMEM_BKPT;
  163213. }else{
  163214. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
  163215. sqlite3_free(zSql);
  163216. }
  163217. if( rc==SQLITE_OK ){
  163218. rc = statNext(pCursor);
  163219. }
  163220. return rc;
  163221. }
  163222. static int statColumn(
  163223. sqlite3_vtab_cursor *pCursor,
  163224. sqlite3_context *ctx,
  163225. int i
  163226. ){
  163227. StatCursor *pCsr = (StatCursor *)pCursor;
  163228. switch( i ){
  163229. case 0: /* name */
  163230. sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
  163231. break;
  163232. case 1: /* path */
  163233. sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
  163234. break;
  163235. case 2: /* pageno */
  163236. sqlite3_result_int64(ctx, pCsr->iPageno);
  163237. break;
  163238. case 3: /* pagetype */
  163239. sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
  163240. break;
  163241. case 4: /* ncell */
  163242. sqlite3_result_int(ctx, pCsr->nCell);
  163243. break;
  163244. case 5: /* payload */
  163245. sqlite3_result_int(ctx, pCsr->nPayload);
  163246. break;
  163247. case 6: /* unused */
  163248. sqlite3_result_int(ctx, pCsr->nUnused);
  163249. break;
  163250. case 7: /* mx_payload */
  163251. sqlite3_result_int(ctx, pCsr->nMxPayload);
  163252. break;
  163253. case 8: /* pgoffset */
  163254. sqlite3_result_int64(ctx, pCsr->iOffset);
  163255. break;
  163256. case 9: /* pgsize */
  163257. sqlite3_result_int(ctx, pCsr->szPage);
  163258. break;
  163259. default: { /* schema */
  163260. sqlite3 *db = sqlite3_context_db_handle(ctx);
  163261. int iDb = pCsr->iDb;
  163262. sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
  163263. break;
  163264. }
  163265. }
  163266. return SQLITE_OK;
  163267. }
  163268. static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  163269. StatCursor *pCsr = (StatCursor *)pCursor;
  163270. *pRowid = pCsr->iPageno;
  163271. return SQLITE_OK;
  163272. }
  163273. /*
  163274. ** Invoke this routine to register the "dbstat" virtual table module
  163275. */
  163276. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
  163277. static sqlite3_module dbstat_module = {
  163278. 0, /* iVersion */
  163279. statConnect, /* xCreate */
  163280. statConnect, /* xConnect */
  163281. statBestIndex, /* xBestIndex */
  163282. statDisconnect, /* xDisconnect */
  163283. statDisconnect, /* xDestroy */
  163284. statOpen, /* xOpen - open a cursor */
  163285. statClose, /* xClose - close a cursor */
  163286. statFilter, /* xFilter - configure scan constraints */
  163287. statNext, /* xNext - advance a cursor */
  163288. statEof, /* xEof - check for end of scan */
  163289. statColumn, /* xColumn - read data */
  163290. statRowid, /* xRowid - read data */
  163291. 0, /* xUpdate */
  163292. 0, /* xBegin */
  163293. 0, /* xSync */
  163294. 0, /* xCommit */
  163295. 0, /* xRollback */
  163296. 0, /* xFindMethod */
  163297. 0, /* xRename */
  163298. };
  163299. return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
  163300. }
  163301. #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
  163302. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
  163303. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  163304. /************** End of dbstat.c **********************************************/
  163305. /************** Begin file sqlite3session.c **********************************/
  163306. #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  163307. /* #include "sqlite3session.h" */
  163308. /* #include <assert.h> */
  163309. /* #include <string.h> */
  163310. #ifndef SQLITE_AMALGAMATION
  163311. /* # include "sqliteInt.h" */
  163312. /* # include "vdbeInt.h" */
  163313. #endif
  163314. typedef struct SessionTable SessionTable;
  163315. typedef struct SessionChange SessionChange;
  163316. typedef struct SessionBuffer SessionBuffer;
  163317. typedef struct SessionInput SessionInput;
  163318. /*
  163319. ** Minimum chunk size used by streaming versions of functions.
  163320. */
  163321. #ifndef SESSIONS_STRM_CHUNK_SIZE
  163322. # ifdef SQLITE_TEST
  163323. # define SESSIONS_STRM_CHUNK_SIZE 64
  163324. # else
  163325. # define SESSIONS_STRM_CHUNK_SIZE 1024
  163326. # endif
  163327. #endif
  163328. typedef struct SessionHook SessionHook;
  163329. struct SessionHook {
  163330. void *pCtx;
  163331. int (*xOld)(void*,int,sqlite3_value**);
  163332. int (*xNew)(void*,int,sqlite3_value**);
  163333. int (*xCount)(void*);
  163334. int (*xDepth)(void*);
  163335. };
  163336. /*
  163337. ** Session handle structure.
  163338. */
  163339. struct sqlite3_session {
  163340. sqlite3 *db; /* Database handle session is attached to */
  163341. char *zDb; /* Name of database session is attached to */
  163342. int bEnable; /* True if currently recording */
  163343. int bIndirect; /* True if all changes are indirect */
  163344. int bAutoAttach; /* True to auto-attach tables */
  163345. int rc; /* Non-zero if an error has occurred */
  163346. void *pFilterCtx; /* First argument to pass to xTableFilter */
  163347. int (*xTableFilter)(void *pCtx, const char *zTab);
  163348. sqlite3_session *pNext; /* Next session object on same db. */
  163349. SessionTable *pTable; /* List of attached tables */
  163350. SessionHook hook; /* APIs to grab new and old data with */
  163351. };
  163352. /*
  163353. ** Instances of this structure are used to build strings or binary records.
  163354. */
  163355. struct SessionBuffer {
  163356. u8 *aBuf; /* Pointer to changeset buffer */
  163357. int nBuf; /* Size of buffer aBuf */
  163358. int nAlloc; /* Size of allocation containing aBuf */
  163359. };
  163360. /*
  163361. ** An object of this type is used internally as an abstraction for
  163362. ** input data. Input data may be supplied either as a single large buffer
  163363. ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
  163364. ** sqlite3changeset_start_strm()).
  163365. */
  163366. struct SessionInput {
  163367. int bNoDiscard; /* If true, discard no data */
  163368. int iCurrent; /* Offset in aData[] of current change */
  163369. int iNext; /* Offset in aData[] of next change */
  163370. u8 *aData; /* Pointer to buffer containing changeset */
  163371. int nData; /* Number of bytes in aData */
  163372. SessionBuffer buf; /* Current read buffer */
  163373. int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */
  163374. void *pIn; /* First argument to xInput */
  163375. int bEof; /* Set to true after xInput finished */
  163376. };
  163377. /*
  163378. ** Structure for changeset iterators.
  163379. */
  163380. struct sqlite3_changeset_iter {
  163381. SessionInput in; /* Input buffer or stream */
  163382. SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */
  163383. int bPatchset; /* True if this is a patchset */
  163384. int rc; /* Iterator error code */
  163385. sqlite3_stmt *pConflict; /* Points to conflicting row, if any */
  163386. char *zTab; /* Current table */
  163387. int nCol; /* Number of columns in zTab */
  163388. int op; /* Current operation */
  163389. int bIndirect; /* True if current change was indirect */
  163390. u8 *abPK; /* Primary key array */
  163391. sqlite3_value **apValue; /* old.* and new.* values */
  163392. };
  163393. /*
  163394. ** Each session object maintains a set of the following structures, one
  163395. ** for each table the session object is monitoring. The structures are
  163396. ** stored in a linked list starting at sqlite3_session.pTable.
  163397. **
  163398. ** The keys of the SessionTable.aChange[] hash table are all rows that have
  163399. ** been modified in any way since the session object was attached to the
  163400. ** table.
  163401. **
  163402. ** The data associated with each hash-table entry is a structure containing
  163403. ** a subset of the initial values that the modified row contained at the
  163404. ** start of the session. Or no initial values if the row was inserted.
  163405. */
  163406. struct SessionTable {
  163407. SessionTable *pNext;
  163408. char *zName; /* Local name of table */
  163409. int nCol; /* Number of columns in table zName */
  163410. const char **azCol; /* Column names */
  163411. u8 *abPK; /* Array of primary key flags */
  163412. int nEntry; /* Total number of entries in hash table */
  163413. int nChange; /* Size of apChange[] array */
  163414. SessionChange **apChange; /* Hash table buckets */
  163415. };
  163416. /*
  163417. ** RECORD FORMAT:
  163418. **
  163419. ** The following record format is similar to (but not compatible with) that
  163420. ** used in SQLite database files. This format is used as part of the
  163421. ** change-set binary format, and so must be architecture independent.
  163422. **
  163423. ** Unlike the SQLite database record format, each field is self-contained -
  163424. ** there is no separation of header and data. Each field begins with a
  163425. ** single byte describing its type, as follows:
  163426. **
  163427. ** 0x00: Undefined value.
  163428. ** 0x01: Integer value.
  163429. ** 0x02: Real value.
  163430. ** 0x03: Text value.
  163431. ** 0x04: Blob value.
  163432. ** 0x05: SQL NULL value.
  163433. **
  163434. ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
  163435. ** and so on in sqlite3.h. For undefined and NULL values, the field consists
  163436. ** only of the single type byte. For other types of values, the type byte
  163437. ** is followed by:
  163438. **
  163439. ** Text values:
  163440. ** A varint containing the number of bytes in the value (encoded using
  163441. ** UTF-8). Followed by a buffer containing the UTF-8 representation
  163442. ** of the text value. There is no nul terminator.
  163443. **
  163444. ** Blob values:
  163445. ** A varint containing the number of bytes in the value, followed by
  163446. ** a buffer containing the value itself.
  163447. **
  163448. ** Integer values:
  163449. ** An 8-byte big-endian integer value.
  163450. **
  163451. ** Real values:
  163452. ** An 8-byte big-endian IEEE 754-2008 real value.
  163453. **
  163454. ** Varint values are encoded in the same way as varints in the SQLite
  163455. ** record format.
  163456. **
  163457. ** CHANGESET FORMAT:
  163458. **
  163459. ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
  163460. ** one or more tables. Operations on a single table are grouped together,
  163461. ** but may occur in any order (i.e. deletes, updates and inserts are all
  163462. ** mixed together).
  163463. **
  163464. ** Each group of changes begins with a table header:
  163465. **
  163466. ** 1 byte: Constant 0x54 (capital 'T')
  163467. ** Varint: Number of columns in the table.
  163468. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  163469. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  163470. **
  163471. ** Followed by one or more changes to the table.
  163472. **
  163473. ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
  163474. ** 1 byte: The "indirect-change" flag.
  163475. ** old.* record: (delete and update only)
  163476. ** new.* record: (insert and update only)
  163477. **
  163478. ** The "old.*" and "new.*" records, if present, are N field records in the
  163479. ** format described above under "RECORD FORMAT", where N is the number of
  163480. ** columns in the table. The i'th field of each record is associated with
  163481. ** the i'th column of the table, counting from left to right in the order
  163482. ** in which columns were declared in the CREATE TABLE statement.
  163483. **
  163484. ** The new.* record that is part of each INSERT change contains the values
  163485. ** that make up the new row. Similarly, the old.* record that is part of each
  163486. ** DELETE change contains the values that made up the row that was deleted
  163487. ** from the database. In the changeset format, the records that are part
  163488. ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
  163489. ** fields.
  163490. **
  163491. ** Within the old.* record associated with an UPDATE change, all fields
  163492. ** associated with table columns that are not PRIMARY KEY columns and are
  163493. ** not modified by the UPDATE change are set to "undefined". Other fields
  163494. ** are set to the values that made up the row before the UPDATE that the
  163495. ** change records took place. Within the new.* record, fields associated
  163496. ** with table columns modified by the UPDATE change contain the new
  163497. ** values. Fields associated with table columns that are not modified
  163498. ** are set to "undefined".
  163499. **
  163500. ** PATCHSET FORMAT:
  163501. **
  163502. ** A patchset is also a collection of changes. It is similar to a changeset,
  163503. ** but leaves undefined those fields that are not useful if no conflict
  163504. ** resolution is required when applying the changeset.
  163505. **
  163506. ** Each group of changes begins with a table header:
  163507. **
  163508. ** 1 byte: Constant 0x50 (capital 'P')
  163509. ** Varint: Number of columns in the table.
  163510. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  163511. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  163512. **
  163513. ** Followed by one or more changes to the table.
  163514. **
  163515. ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
  163516. ** 1 byte: The "indirect-change" flag.
  163517. ** single record: (PK fields for DELETE, PK and modified fields for UPDATE,
  163518. ** full record for INSERT).
  163519. **
  163520. ** As in the changeset format, each field of the single record that is part
  163521. ** of a patchset change is associated with the correspondingly positioned
  163522. ** table column, counting from left to right within the CREATE TABLE
  163523. ** statement.
  163524. **
  163525. ** For a DELETE change, all fields within the record except those associated
  163526. ** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields
  163527. ** contain the values identifying the row to delete.
  163528. **
  163529. ** For an UPDATE change, all fields except those associated with PRIMARY KEY
  163530. ** columns and columns that are modified by the UPDATE are set to "undefined".
  163531. ** PRIMARY KEY fields contain the values identifying the table row to update,
  163532. ** and fields associated with modified columns contain the new column values.
  163533. **
  163534. ** The records associated with INSERT changes are in the same format as for
  163535. ** changesets. It is not possible for a record associated with an INSERT
  163536. ** change to contain a field set to "undefined".
  163537. */
  163538. /*
  163539. ** For each row modified during a session, there exists a single instance of
  163540. ** this structure stored in a SessionTable.aChange[] hash table.
  163541. */
  163542. struct SessionChange {
  163543. int op; /* One of UPDATE, DELETE, INSERT */
  163544. int bIndirect; /* True if this change is "indirect" */
  163545. int nRecord; /* Number of bytes in buffer aRecord[] */
  163546. u8 *aRecord; /* Buffer containing old.* record */
  163547. SessionChange *pNext; /* For hash-table collisions */
  163548. };
  163549. /*
  163550. ** Write a varint with value iVal into the buffer at aBuf. Return the
  163551. ** number of bytes written.
  163552. */
  163553. static int sessionVarintPut(u8 *aBuf, int iVal){
  163554. return putVarint32(aBuf, iVal);
  163555. }
  163556. /*
  163557. ** Return the number of bytes required to store value iVal as a varint.
  163558. */
  163559. static int sessionVarintLen(int iVal){
  163560. return sqlite3VarintLen(iVal);
  163561. }
  163562. /*
  163563. ** Read a varint value from aBuf[] into *piVal. Return the number of
  163564. ** bytes read.
  163565. */
  163566. static int sessionVarintGet(u8 *aBuf, int *piVal){
  163567. return getVarint32(aBuf, *piVal);
  163568. }
  163569. /* Load an unaligned and unsigned 32-bit integer */
  163570. #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  163571. /*
  163572. ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
  163573. ** the value read.
  163574. */
  163575. static sqlite3_int64 sessionGetI64(u8 *aRec){
  163576. u64 x = SESSION_UINT32(aRec);
  163577. u32 y = SESSION_UINT32(aRec+4);
  163578. x = (x<<32) + y;
  163579. return (sqlite3_int64)x;
  163580. }
  163581. /*
  163582. ** Write a 64-bit big-endian integer value to the buffer aBuf[].
  163583. */
  163584. static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
  163585. aBuf[0] = (i>>56) & 0xFF;
  163586. aBuf[1] = (i>>48) & 0xFF;
  163587. aBuf[2] = (i>>40) & 0xFF;
  163588. aBuf[3] = (i>>32) & 0xFF;
  163589. aBuf[4] = (i>>24) & 0xFF;
  163590. aBuf[5] = (i>>16) & 0xFF;
  163591. aBuf[6] = (i>> 8) & 0xFF;
  163592. aBuf[7] = (i>> 0) & 0xFF;
  163593. }
  163594. /*
  163595. ** This function is used to serialize the contents of value pValue (see
  163596. ** comment titled "RECORD FORMAT" above).
  163597. **
  163598. ** If it is non-NULL, the serialized form of the value is written to
  163599. ** buffer aBuf. *pnWrite is set to the number of bytes written before
  163600. ** returning. Or, if aBuf is NULL, the only thing this function does is
  163601. ** set *pnWrite.
  163602. **
  163603. ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
  163604. ** within a call to sqlite3_value_text() (may fail if the db is utf-16))
  163605. ** SQLITE_NOMEM is returned.
  163606. */
  163607. static int sessionSerializeValue(
  163608. u8 *aBuf, /* If non-NULL, write serialized value here */
  163609. sqlite3_value *pValue, /* Value to serialize */
  163610. int *pnWrite /* IN/OUT: Increment by bytes written */
  163611. ){
  163612. int nByte; /* Size of serialized value in bytes */
  163613. if( pValue ){
  163614. int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
  163615. eType = sqlite3_value_type(pValue);
  163616. if( aBuf ) aBuf[0] = eType;
  163617. switch( eType ){
  163618. case SQLITE_NULL:
  163619. nByte = 1;
  163620. break;
  163621. case SQLITE_INTEGER:
  163622. case SQLITE_FLOAT:
  163623. if( aBuf ){
  163624. /* TODO: SQLite does something special to deal with mixed-endian
  163625. ** floating point values (e.g. ARM7). This code probably should
  163626. ** too. */
  163627. u64 i;
  163628. if( eType==SQLITE_INTEGER ){
  163629. i = (u64)sqlite3_value_int64(pValue);
  163630. }else{
  163631. double r;
  163632. assert( sizeof(double)==8 && sizeof(u64)==8 );
  163633. r = sqlite3_value_double(pValue);
  163634. memcpy(&i, &r, 8);
  163635. }
  163636. sessionPutI64(&aBuf[1], i);
  163637. }
  163638. nByte = 9;
  163639. break;
  163640. default: {
  163641. u8 *z;
  163642. int n;
  163643. int nVarint;
  163644. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  163645. if( eType==SQLITE_TEXT ){
  163646. z = (u8 *)sqlite3_value_text(pValue);
  163647. }else{
  163648. z = (u8 *)sqlite3_value_blob(pValue);
  163649. }
  163650. n = sqlite3_value_bytes(pValue);
  163651. if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
  163652. nVarint = sessionVarintLen(n);
  163653. if( aBuf ){
  163654. sessionVarintPut(&aBuf[1], n);
  163655. if( n ) memcpy(&aBuf[nVarint + 1], z, n);
  163656. }
  163657. nByte = 1 + nVarint + n;
  163658. break;
  163659. }
  163660. }
  163661. }else{
  163662. nByte = 1;
  163663. if( aBuf ) aBuf[0] = '\0';
  163664. }
  163665. if( pnWrite ) *pnWrite += nByte;
  163666. return SQLITE_OK;
  163667. }
  163668. /*
  163669. ** This macro is used to calculate hash key values for data structures. In
  163670. ** order to use this macro, the entire data structure must be represented
  163671. ** as a series of unsigned integers. In order to calculate a hash-key value
  163672. ** for a data structure represented as three such integers, the macro may
  163673. ** then be used as follows:
  163674. **
  163675. ** int hash_key_value;
  163676. ** hash_key_value = HASH_APPEND(0, <value 1>);
  163677. ** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
  163678. ** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
  163679. **
  163680. ** In practice, the data structures this macro is used for are the primary
  163681. ** key values of modified rows.
  163682. */
  163683. #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
  163684. /*
  163685. ** Append the hash of the 64-bit integer passed as the second argument to the
  163686. ** hash-key value passed as the first. Return the new hash-key value.
  163687. */
  163688. static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
  163689. h = HASH_APPEND(h, i & 0xFFFFFFFF);
  163690. return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
  163691. }
  163692. /*
  163693. ** Append the hash of the blob passed via the second and third arguments to
  163694. ** the hash-key value passed as the first. Return the new hash-key value.
  163695. */
  163696. static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
  163697. int i;
  163698. for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
  163699. return h;
  163700. }
  163701. /*
  163702. ** Append the hash of the data type passed as the second argument to the
  163703. ** hash-key value passed as the first. Return the new hash-key value.
  163704. */
  163705. static unsigned int sessionHashAppendType(unsigned int h, int eType){
  163706. return HASH_APPEND(h, eType);
  163707. }
  163708. /*
  163709. ** This function may only be called from within a pre-update callback.
  163710. ** It calculates a hash based on the primary key values of the old.* or
  163711. ** new.* row currently available and, assuming no error occurs, writes it to
  163712. ** *piHash before returning. If the primary key contains one or more NULL
  163713. ** values, *pbNullPK is set to true before returning.
  163714. **
  163715. ** If an error occurs, an SQLite error code is returned and the final values
  163716. ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
  163717. ** and the output variables are set as described above.
  163718. */
  163719. static int sessionPreupdateHash(
  163720. sqlite3_session *pSession, /* Session object that owns pTab */
  163721. SessionTable *pTab, /* Session table handle */
  163722. int bNew, /* True to hash the new.* PK */
  163723. int *piHash, /* OUT: Hash value */
  163724. int *pbNullPK /* OUT: True if there are NULL values in PK */
  163725. ){
  163726. unsigned int h = 0; /* Hash value to return */
  163727. int i; /* Used to iterate through columns */
  163728. assert( *pbNullPK==0 );
  163729. assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
  163730. for(i=0; i<pTab->nCol; i++){
  163731. if( pTab->abPK[i] ){
  163732. int rc;
  163733. int eType;
  163734. sqlite3_value *pVal;
  163735. if( bNew ){
  163736. rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
  163737. }else{
  163738. rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
  163739. }
  163740. if( rc!=SQLITE_OK ) return rc;
  163741. eType = sqlite3_value_type(pVal);
  163742. h = sessionHashAppendType(h, eType);
  163743. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  163744. i64 iVal;
  163745. if( eType==SQLITE_INTEGER ){
  163746. iVal = sqlite3_value_int64(pVal);
  163747. }else{
  163748. double rVal = sqlite3_value_double(pVal);
  163749. assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
  163750. memcpy(&iVal, &rVal, 8);
  163751. }
  163752. h = sessionHashAppendI64(h, iVal);
  163753. }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  163754. const u8 *z;
  163755. int n;
  163756. if( eType==SQLITE_TEXT ){
  163757. z = (const u8 *)sqlite3_value_text(pVal);
  163758. }else{
  163759. z = (const u8 *)sqlite3_value_blob(pVal);
  163760. }
  163761. n = sqlite3_value_bytes(pVal);
  163762. if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
  163763. h = sessionHashAppendBlob(h, n, z);
  163764. }else{
  163765. assert( eType==SQLITE_NULL );
  163766. *pbNullPK = 1;
  163767. }
  163768. }
  163769. }
  163770. *piHash = (h % pTab->nChange);
  163771. return SQLITE_OK;
  163772. }
  163773. /*
  163774. ** The buffer that the argument points to contains a serialized SQL value.
  163775. ** Return the number of bytes of space occupied by the value (including
  163776. ** the type byte).
  163777. */
  163778. static int sessionSerialLen(u8 *a){
  163779. int e = *a;
  163780. int n;
  163781. if( e==0 ) return 1;
  163782. if( e==SQLITE_NULL ) return 1;
  163783. if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
  163784. return sessionVarintGet(&a[1], &n) + 1 + n;
  163785. }
  163786. /*
  163787. ** Based on the primary key values stored in change aRecord, calculate a
  163788. ** hash key. Assume the has table has nBucket buckets. The hash keys
  163789. ** calculated by this function are compatible with those calculated by
  163790. ** sessionPreupdateHash().
  163791. **
  163792. ** The bPkOnly argument is non-zero if the record at aRecord[] is from
  163793. ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
  163794. */
  163795. static unsigned int sessionChangeHash(
  163796. SessionTable *pTab, /* Table handle */
  163797. int bPkOnly, /* Record consists of PK fields only */
  163798. u8 *aRecord, /* Change record */
  163799. int nBucket /* Assume this many buckets in hash table */
  163800. ){
  163801. unsigned int h = 0; /* Value to return */
  163802. int i; /* Used to iterate through columns */
  163803. u8 *a = aRecord; /* Used to iterate through change record */
  163804. for(i=0; i<pTab->nCol; i++){
  163805. int eType = *a;
  163806. int isPK = pTab->abPK[i];
  163807. if( bPkOnly && isPK==0 ) continue;
  163808. /* It is not possible for eType to be SQLITE_NULL here. The session
  163809. ** module does not record changes for rows with NULL values stored in
  163810. ** primary key columns. */
  163811. assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
  163812. || eType==SQLITE_TEXT || eType==SQLITE_BLOB
  163813. || eType==SQLITE_NULL || eType==0
  163814. );
  163815. assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
  163816. if( isPK ){
  163817. a++;
  163818. h = sessionHashAppendType(h, eType);
  163819. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  163820. h = sessionHashAppendI64(h, sessionGetI64(a));
  163821. a += 8;
  163822. }else{
  163823. int n;
  163824. a += sessionVarintGet(a, &n);
  163825. h = sessionHashAppendBlob(h, n, a);
  163826. a += n;
  163827. }
  163828. }else{
  163829. a += sessionSerialLen(a);
  163830. }
  163831. }
  163832. return (h % nBucket);
  163833. }
  163834. /*
  163835. ** Arguments aLeft and aRight are pointers to change records for table pTab.
  163836. ** This function returns true if the two records apply to the same row (i.e.
  163837. ** have the same values stored in the primary key columns), or false
  163838. ** otherwise.
  163839. */
  163840. static int sessionChangeEqual(
  163841. SessionTable *pTab, /* Table used for PK definition */
  163842. int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
  163843. u8 *aLeft, /* Change record */
  163844. int bRightPkOnly, /* True if aRight[] contains PK fields only */
  163845. u8 *aRight /* Change record */
  163846. ){
  163847. u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
  163848. u8 *a2 = aRight; /* Cursor to iterate through aRight */
  163849. int iCol; /* Used to iterate through table columns */
  163850. for(iCol=0; iCol<pTab->nCol; iCol++){
  163851. if( pTab->abPK[iCol] ){
  163852. int n1 = sessionSerialLen(a1);
  163853. int n2 = sessionSerialLen(a2);
  163854. if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){
  163855. return 0;
  163856. }
  163857. a1 += n1;
  163858. a2 += n2;
  163859. }else{
  163860. if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
  163861. if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
  163862. }
  163863. }
  163864. return 1;
  163865. }
  163866. /*
  163867. ** Arguments aLeft and aRight both point to buffers containing change
  163868. ** records with nCol columns. This function "merges" the two records into
  163869. ** a single records which is written to the buffer at *paOut. *paOut is
  163870. ** then set to point to one byte after the last byte written before
  163871. ** returning.
  163872. **
  163873. ** The merging of records is done as follows: For each column, if the
  163874. ** aRight record contains a value for the column, copy the value from
  163875. ** their. Otherwise, if aLeft contains a value, copy it. If neither
  163876. ** record contains a value for a given column, then neither does the
  163877. ** output record.
  163878. */
  163879. static void sessionMergeRecord(
  163880. u8 **paOut,
  163881. int nCol,
  163882. u8 *aLeft,
  163883. u8 *aRight
  163884. ){
  163885. u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
  163886. u8 *a2 = aRight; /* Cursor used to iterate through aRight */
  163887. u8 *aOut = *paOut; /* Output cursor */
  163888. int iCol; /* Used to iterate from 0 to nCol */
  163889. for(iCol=0; iCol<nCol; iCol++){
  163890. int n1 = sessionSerialLen(a1);
  163891. int n2 = sessionSerialLen(a2);
  163892. if( *a2 ){
  163893. memcpy(aOut, a2, n2);
  163894. aOut += n2;
  163895. }else{
  163896. memcpy(aOut, a1, n1);
  163897. aOut += n1;
  163898. }
  163899. a1 += n1;
  163900. a2 += n2;
  163901. }
  163902. *paOut = aOut;
  163903. }
  163904. /*
  163905. ** This is a helper function used by sessionMergeUpdate().
  163906. **
  163907. ** When this function is called, both *paOne and *paTwo point to a value
  163908. ** within a change record. Before it returns, both have been advanced so
  163909. ** as to point to the next value in the record.
  163910. **
  163911. ** If, when this function is called, *paTwo points to a valid value (i.e.
  163912. ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
  163913. ** pointer is returned and *pnVal is set to the number of bytes in the
  163914. ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
  163915. ** set to the number of bytes in the value at *paOne. If *paOne points
  163916. ** to the "no value" placeholder, *pnVal is set to 1. In other words:
  163917. **
  163918. ** if( *paTwo is valid ) return *paTwo;
  163919. ** return *paOne;
  163920. **
  163921. */
  163922. static u8 *sessionMergeValue(
  163923. u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
  163924. u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
  163925. int *pnVal /* OUT: Bytes in returned value */
  163926. ){
  163927. u8 *a1 = *paOne;
  163928. u8 *a2 = *paTwo;
  163929. u8 *pRet = 0;
  163930. int n1;
  163931. assert( a1 );
  163932. if( a2 ){
  163933. int n2 = sessionSerialLen(a2);
  163934. if( *a2 ){
  163935. *pnVal = n2;
  163936. pRet = a2;
  163937. }
  163938. *paTwo = &a2[n2];
  163939. }
  163940. n1 = sessionSerialLen(a1);
  163941. if( pRet==0 ){
  163942. *pnVal = n1;
  163943. pRet = a1;
  163944. }
  163945. *paOne = &a1[n1];
  163946. return pRet;
  163947. }
  163948. /*
  163949. ** This function is used by changeset_concat() to merge two UPDATE changes
  163950. ** on the same row.
  163951. */
  163952. static int sessionMergeUpdate(
  163953. u8 **paOut, /* IN/OUT: Pointer to output buffer */
  163954. SessionTable *pTab, /* Table change pertains to */
  163955. int bPatchset, /* True if records are patchset records */
  163956. u8 *aOldRecord1, /* old.* record for first change */
  163957. u8 *aOldRecord2, /* old.* record for second change */
  163958. u8 *aNewRecord1, /* new.* record for first change */
  163959. u8 *aNewRecord2 /* new.* record for second change */
  163960. ){
  163961. u8 *aOld1 = aOldRecord1;
  163962. u8 *aOld2 = aOldRecord2;
  163963. u8 *aNew1 = aNewRecord1;
  163964. u8 *aNew2 = aNewRecord2;
  163965. u8 *aOut = *paOut;
  163966. int i;
  163967. if( bPatchset==0 ){
  163968. int bRequired = 0;
  163969. assert( aOldRecord1 && aNewRecord1 );
  163970. /* Write the old.* vector first. */
  163971. for(i=0; i<pTab->nCol; i++){
  163972. int nOld;
  163973. u8 *aOld;
  163974. int nNew;
  163975. u8 *aNew;
  163976. aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
  163977. aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
  163978. if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
  163979. if( pTab->abPK[i]==0 ) bRequired = 1;
  163980. memcpy(aOut, aOld, nOld);
  163981. aOut += nOld;
  163982. }else{
  163983. *(aOut++) = '\0';
  163984. }
  163985. }
  163986. if( !bRequired ) return 0;
  163987. }
  163988. /* Write the new.* vector */
  163989. aOld1 = aOldRecord1;
  163990. aOld2 = aOldRecord2;
  163991. aNew1 = aNewRecord1;
  163992. aNew2 = aNewRecord2;
  163993. for(i=0; i<pTab->nCol; i++){
  163994. int nOld;
  163995. u8 *aOld;
  163996. int nNew;
  163997. u8 *aNew;
  163998. aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
  163999. aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
  164000. if( bPatchset==0
  164001. && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
  164002. ){
  164003. *(aOut++) = '\0';
  164004. }else{
  164005. memcpy(aOut, aNew, nNew);
  164006. aOut += nNew;
  164007. }
  164008. }
  164009. *paOut = aOut;
  164010. return 1;
  164011. }
  164012. /*
  164013. ** This function is only called from within a pre-update-hook callback.
  164014. ** It determines if the current pre-update-hook change affects the same row
  164015. ** as the change stored in argument pChange. If so, it returns true. Otherwise
  164016. ** if the pre-update-hook does not affect the same row as pChange, it returns
  164017. ** false.
  164018. */
  164019. static int sessionPreupdateEqual(
  164020. sqlite3_session *pSession, /* Session object that owns SessionTable */
  164021. SessionTable *pTab, /* Table associated with change */
  164022. SessionChange *pChange, /* Change to compare to */
  164023. int op /* Current pre-update operation */
  164024. ){
  164025. int iCol; /* Used to iterate through columns */
  164026. u8 *a = pChange->aRecord; /* Cursor used to scan change record */
  164027. assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
  164028. for(iCol=0; iCol<pTab->nCol; iCol++){
  164029. if( !pTab->abPK[iCol] ){
  164030. a += sessionSerialLen(a);
  164031. }else{
  164032. sqlite3_value *pVal; /* Value returned by preupdate_new/old */
  164033. int rc; /* Error code from preupdate_new/old */
  164034. int eType = *a++; /* Type of value from change record */
  164035. /* The following calls to preupdate_new() and preupdate_old() can not
  164036. ** fail. This is because they cache their return values, and by the
  164037. ** time control flows to here they have already been called once from
  164038. ** within sessionPreupdateHash(). The first two asserts below verify
  164039. ** this (that the method has already been called). */
  164040. if( op==SQLITE_INSERT ){
  164041. /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
  164042. rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
  164043. }else{
  164044. /* assert( db->pPreUpdate->pUnpacked ); */
  164045. rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
  164046. }
  164047. assert( rc==SQLITE_OK );
  164048. if( sqlite3_value_type(pVal)!=eType ) return 0;
  164049. /* A SessionChange object never has a NULL value in a PK column */
  164050. assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
  164051. || eType==SQLITE_BLOB || eType==SQLITE_TEXT
  164052. );
  164053. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  164054. i64 iVal = sessionGetI64(a);
  164055. a += 8;
  164056. if( eType==SQLITE_INTEGER ){
  164057. if( sqlite3_value_int64(pVal)!=iVal ) return 0;
  164058. }else{
  164059. double rVal;
  164060. assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
  164061. memcpy(&rVal, &iVal, 8);
  164062. if( sqlite3_value_double(pVal)!=rVal ) return 0;
  164063. }
  164064. }else{
  164065. int n;
  164066. const u8 *z;
  164067. a += sessionVarintGet(a, &n);
  164068. if( sqlite3_value_bytes(pVal)!=n ) return 0;
  164069. if( eType==SQLITE_TEXT ){
  164070. z = sqlite3_value_text(pVal);
  164071. }else{
  164072. z = sqlite3_value_blob(pVal);
  164073. }
  164074. if( memcmp(a, z, n) ) return 0;
  164075. a += n;
  164076. break;
  164077. }
  164078. }
  164079. }
  164080. return 1;
  164081. }
  164082. /*
  164083. ** If required, grow the hash table used to store changes on table pTab
  164084. ** (part of the session pSession). If a fatal OOM error occurs, set the
  164085. ** session object to failed and return SQLITE_ERROR. Otherwise, return
  164086. ** SQLITE_OK.
  164087. **
  164088. ** It is possible that a non-fatal OOM error occurs in this function. In
  164089. ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
  164090. ** Growing the hash table in this case is a performance optimization only,
  164091. ** it is not required for correct operation.
  164092. */
  164093. static int sessionGrowHash(int bPatchset, SessionTable *pTab){
  164094. if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
  164095. int i;
  164096. SessionChange **apNew;
  164097. int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
  164098. apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
  164099. if( apNew==0 ){
  164100. if( pTab->nChange==0 ){
  164101. return SQLITE_ERROR;
  164102. }
  164103. return SQLITE_OK;
  164104. }
  164105. memset(apNew, 0, sizeof(SessionChange *) * nNew);
  164106. for(i=0; i<pTab->nChange; i++){
  164107. SessionChange *p;
  164108. SessionChange *pNext;
  164109. for(p=pTab->apChange[i]; p; p=pNext){
  164110. int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
  164111. int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
  164112. pNext = p->pNext;
  164113. p->pNext = apNew[iHash];
  164114. apNew[iHash] = p;
  164115. }
  164116. }
  164117. sqlite3_free(pTab->apChange);
  164118. pTab->nChange = nNew;
  164119. pTab->apChange = apNew;
  164120. }
  164121. return SQLITE_OK;
  164122. }
  164123. /*
  164124. ** This function queries the database for the names of the columns of table
  164125. ** zThis, in schema zDb. It is expected that the table has nCol columns. If
  164126. ** not, SQLITE_SCHEMA is returned and none of the output variables are
  164127. ** populated.
  164128. **
  164129. ** Otherwise, if they are not NULL, variable *pnCol is set to the number
  164130. ** of columns in the database table and variable *pzTab is set to point to a
  164131. ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
  164132. ** point to an array of pointers to column names. And *pabPK (again, if not
  164133. ** NULL) is set to point to an array of booleans - true if the corresponding
  164134. ** column is part of the primary key.
  164135. **
  164136. ** For example, if the table is declared as:
  164137. **
  164138. ** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
  164139. **
  164140. ** Then the four output variables are populated as follows:
  164141. **
  164142. ** *pnCol = 4
  164143. ** *pzTab = "tbl1"
  164144. ** *pazCol = {"w", "x", "y", "z"}
  164145. ** *pabPK = {1, 0, 0, 1}
  164146. **
  164147. ** All returned buffers are part of the same single allocation, which must
  164148. ** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then
  164149. ** pointer *pazCol should be freed to release all memory. Otherwise, pointer
  164150. ** *pabPK. It is illegal for both pazCol and pabPK to be NULL.
  164151. */
  164152. static int sessionTableInfo(
  164153. sqlite3 *db, /* Database connection */
  164154. const char *zDb, /* Name of attached database (e.g. "main") */
  164155. const char *zThis, /* Table name */
  164156. int *pnCol, /* OUT: number of columns */
  164157. const char **pzTab, /* OUT: Copy of zThis */
  164158. const char ***pazCol, /* OUT: Array of column names for table */
  164159. u8 **pabPK /* OUT: Array of booleans - true for PK col */
  164160. ){
  164161. char *zPragma;
  164162. sqlite3_stmt *pStmt;
  164163. int rc;
  164164. int nByte;
  164165. int nDbCol = 0;
  164166. int nThis;
  164167. int i;
  164168. u8 *pAlloc = 0;
  164169. char **azCol = 0;
  164170. u8 *abPK = 0;
  164171. assert( pazCol && pabPK );
  164172. nThis = sqlite3Strlen30(zThis);
  164173. zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
  164174. if( !zPragma ) return SQLITE_NOMEM;
  164175. rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
  164176. sqlite3_free(zPragma);
  164177. if( rc!=SQLITE_OK ) return rc;
  164178. nByte = nThis + 1;
  164179. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  164180. nByte += sqlite3_column_bytes(pStmt, 1);
  164181. nDbCol++;
  164182. }
  164183. rc = sqlite3_reset(pStmt);
  164184. if( rc==SQLITE_OK ){
  164185. nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
  164186. pAlloc = sqlite3_malloc(nByte);
  164187. if( pAlloc==0 ){
  164188. rc = SQLITE_NOMEM;
  164189. }
  164190. }
  164191. if( rc==SQLITE_OK ){
  164192. azCol = (char **)pAlloc;
  164193. pAlloc = (u8 *)&azCol[nDbCol];
  164194. abPK = (u8 *)pAlloc;
  164195. pAlloc = &abPK[nDbCol];
  164196. if( pzTab ){
  164197. memcpy(pAlloc, zThis, nThis+1);
  164198. *pzTab = (char *)pAlloc;
  164199. pAlloc += nThis+1;
  164200. }
  164201. i = 0;
  164202. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  164203. int nName = sqlite3_column_bytes(pStmt, 1);
  164204. const unsigned char *zName = sqlite3_column_text(pStmt, 1);
  164205. if( zName==0 ) break;
  164206. memcpy(pAlloc, zName, nName+1);
  164207. azCol[i] = (char *)pAlloc;
  164208. pAlloc += nName+1;
  164209. abPK[i] = sqlite3_column_int(pStmt, 5);
  164210. i++;
  164211. }
  164212. rc = sqlite3_reset(pStmt);
  164213. }
  164214. /* If successful, populate the output variables. Otherwise, zero them and
  164215. ** free any allocation made. An error code will be returned in this case.
  164216. */
  164217. if( rc==SQLITE_OK ){
  164218. *pazCol = (const char **)azCol;
  164219. *pabPK = abPK;
  164220. *pnCol = nDbCol;
  164221. }else{
  164222. *pazCol = 0;
  164223. *pabPK = 0;
  164224. *pnCol = 0;
  164225. if( pzTab ) *pzTab = 0;
  164226. sqlite3_free(azCol);
  164227. }
  164228. sqlite3_finalize(pStmt);
  164229. return rc;
  164230. }
  164231. /*
  164232. ** This function is only called from within a pre-update handler for a
  164233. ** write to table pTab, part of session pSession. If this is the first
  164234. ** write to this table, initalize the SessionTable.nCol, azCol[] and
  164235. ** abPK[] arrays accordingly.
  164236. **
  164237. ** If an error occurs, an error code is stored in sqlite3_session.rc and
  164238. ** non-zero returned. Or, if no error occurs but the table has no primary
  164239. ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
  164240. ** indicate that updates on this table should be ignored. SessionTable.abPK
  164241. ** is set to NULL in this case.
  164242. */
  164243. static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
  164244. if( pTab->nCol==0 ){
  164245. u8 *abPK;
  164246. assert( pTab->azCol==0 || pTab->abPK==0 );
  164247. pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
  164248. pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
  164249. );
  164250. if( pSession->rc==SQLITE_OK ){
  164251. int i;
  164252. for(i=0; i<pTab->nCol; i++){
  164253. if( abPK[i] ){
  164254. pTab->abPK = abPK;
  164255. break;
  164256. }
  164257. }
  164258. }
  164259. }
  164260. return (pSession->rc || pTab->abPK==0);
  164261. }
  164262. /*
  164263. ** This function is only called from with a pre-update-hook reporting a
  164264. ** change on table pTab (attached to session pSession). The type of change
  164265. ** (UPDATE, INSERT, DELETE) is specified by the first argument.
  164266. **
  164267. ** Unless one is already present or an error occurs, an entry is added
  164268. ** to the changed-rows hash table associated with table pTab.
  164269. */
  164270. static void sessionPreupdateOneChange(
  164271. int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
  164272. sqlite3_session *pSession, /* Session object pTab is attached to */
  164273. SessionTable *pTab /* Table that change applies to */
  164274. ){
  164275. int iHash;
  164276. int bNull = 0;
  164277. int rc = SQLITE_OK;
  164278. if( pSession->rc ) return;
  164279. /* Load table details if required */
  164280. if( sessionInitTable(pSession, pTab) ) return;
  164281. /* Check the number of columns in this xPreUpdate call matches the
  164282. ** number of columns in the table. */
  164283. if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
  164284. pSession->rc = SQLITE_SCHEMA;
  164285. return;
  164286. }
  164287. /* Grow the hash table if required */
  164288. if( sessionGrowHash(0, pTab) ){
  164289. pSession->rc = SQLITE_NOMEM;
  164290. return;
  164291. }
  164292. /* Calculate the hash-key for this change. If the primary key of the row
  164293. ** includes a NULL value, exit early. Such changes are ignored by the
  164294. ** session module. */
  164295. rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
  164296. if( rc!=SQLITE_OK ) goto error_out;
  164297. if( bNull==0 ){
  164298. /* Search the hash table for an existing record for this row. */
  164299. SessionChange *pC;
  164300. for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
  164301. if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
  164302. }
  164303. if( pC==0 ){
  164304. /* Create a new change object containing all the old values (if
  164305. ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
  164306. ** values (if this is an INSERT). */
  164307. SessionChange *pChange; /* New change object */
  164308. int nByte; /* Number of bytes to allocate */
  164309. int i; /* Used to iterate through columns */
  164310. assert( rc==SQLITE_OK );
  164311. pTab->nEntry++;
  164312. /* Figure out how large an allocation is required */
  164313. nByte = sizeof(SessionChange);
  164314. for(i=0; i<pTab->nCol; i++){
  164315. sqlite3_value *p = 0;
  164316. if( op!=SQLITE_INSERT ){
  164317. TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
  164318. assert( trc==SQLITE_OK );
  164319. }else if( pTab->abPK[i] ){
  164320. TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
  164321. assert( trc==SQLITE_OK );
  164322. }
  164323. /* This may fail if SQLite value p contains a utf-16 string that must
  164324. ** be converted to utf-8 and an OOM error occurs while doing so. */
  164325. rc = sessionSerializeValue(0, p, &nByte);
  164326. if( rc!=SQLITE_OK ) goto error_out;
  164327. }
  164328. /* Allocate the change object */
  164329. pChange = (SessionChange *)sqlite3_malloc(nByte);
  164330. if( !pChange ){
  164331. rc = SQLITE_NOMEM;
  164332. goto error_out;
  164333. }else{
  164334. memset(pChange, 0, sizeof(SessionChange));
  164335. pChange->aRecord = (u8 *)&pChange[1];
  164336. }
  164337. /* Populate the change object. None of the preupdate_old(),
  164338. ** preupdate_new() or SerializeValue() calls below may fail as all
  164339. ** required values and encodings have already been cached in memory.
  164340. ** It is not possible for an OOM to occur in this block. */
  164341. nByte = 0;
  164342. for(i=0; i<pTab->nCol; i++){
  164343. sqlite3_value *p = 0;
  164344. if( op!=SQLITE_INSERT ){
  164345. pSession->hook.xOld(pSession->hook.pCtx, i, &p);
  164346. }else if( pTab->abPK[i] ){
  164347. pSession->hook.xNew(pSession->hook.pCtx, i, &p);
  164348. }
  164349. sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
  164350. }
  164351. /* Add the change to the hash-table */
  164352. if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
  164353. pChange->bIndirect = 1;
  164354. }
  164355. pChange->nRecord = nByte;
  164356. pChange->op = op;
  164357. pChange->pNext = pTab->apChange[iHash];
  164358. pTab->apChange[iHash] = pChange;
  164359. }else if( pC->bIndirect ){
  164360. /* If the existing change is considered "indirect", but this current
  164361. ** change is "direct", mark the change object as direct. */
  164362. if( pSession->hook.xDepth(pSession->hook.pCtx)==0
  164363. && pSession->bIndirect==0
  164364. ){
  164365. pC->bIndirect = 0;
  164366. }
  164367. }
  164368. }
  164369. /* If an error has occurred, mark the session object as failed. */
  164370. error_out:
  164371. if( rc!=SQLITE_OK ){
  164372. pSession->rc = rc;
  164373. }
  164374. }
  164375. static int sessionFindTable(
  164376. sqlite3_session *pSession,
  164377. const char *zName,
  164378. SessionTable **ppTab
  164379. ){
  164380. int rc = SQLITE_OK;
  164381. int nName = sqlite3Strlen30(zName);
  164382. SessionTable *pRet;
  164383. /* Search for an existing table */
  164384. for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
  164385. if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
  164386. }
  164387. if( pRet==0 && pSession->bAutoAttach ){
  164388. /* If there is a table-filter configured, invoke it. If it returns 0,
  164389. ** do not automatically add the new table. */
  164390. if( pSession->xTableFilter==0
  164391. || pSession->xTableFilter(pSession->pFilterCtx, zName)
  164392. ){
  164393. rc = sqlite3session_attach(pSession, zName);
  164394. if( rc==SQLITE_OK ){
  164395. for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
  164396. assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
  164397. }
  164398. }
  164399. }
  164400. assert( rc==SQLITE_OK || pRet==0 );
  164401. *ppTab = pRet;
  164402. return rc;
  164403. }
  164404. /*
  164405. ** The 'pre-update' hook registered by this module with SQLite databases.
  164406. */
  164407. static void xPreUpdate(
  164408. void *pCtx, /* Copy of third arg to preupdate_hook() */
  164409. sqlite3 *db, /* Database handle */
  164410. int op, /* SQLITE_UPDATE, DELETE or INSERT */
  164411. char const *zDb, /* Database name */
  164412. char const *zName, /* Table name */
  164413. sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
  164414. sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
  164415. ){
  164416. sqlite3_session *pSession;
  164417. int nDb = sqlite3Strlen30(zDb);
  164418. assert( sqlite3_mutex_held(db->mutex) );
  164419. for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
  164420. SessionTable *pTab;
  164421. /* If this session is attached to a different database ("main", "temp"
  164422. ** etc.), or if it is not currently enabled, there is nothing to do. Skip
  164423. ** to the next session object attached to this database. */
  164424. if( pSession->bEnable==0 ) continue;
  164425. if( pSession->rc ) continue;
  164426. if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
  164427. pSession->rc = sessionFindTable(pSession, zName, &pTab);
  164428. if( pTab ){
  164429. assert( pSession->rc==SQLITE_OK );
  164430. sessionPreupdateOneChange(op, pSession, pTab);
  164431. if( op==SQLITE_UPDATE ){
  164432. sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
  164433. }
  164434. }
  164435. }
  164436. }
  164437. /*
  164438. ** The pre-update hook implementations.
  164439. */
  164440. static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  164441. return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
  164442. }
  164443. static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  164444. return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
  164445. }
  164446. static int sessionPreupdateCount(void *pCtx){
  164447. return sqlite3_preupdate_count((sqlite3*)pCtx);
  164448. }
  164449. static int sessionPreupdateDepth(void *pCtx){
  164450. return sqlite3_preupdate_depth((sqlite3*)pCtx);
  164451. }
  164452. /*
  164453. ** Install the pre-update hooks on the session object passed as the only
  164454. ** argument.
  164455. */
  164456. static void sessionPreupdateHooks(
  164457. sqlite3_session *pSession
  164458. ){
  164459. pSession->hook.pCtx = (void*)pSession->db;
  164460. pSession->hook.xOld = sessionPreupdateOld;
  164461. pSession->hook.xNew = sessionPreupdateNew;
  164462. pSession->hook.xCount = sessionPreupdateCount;
  164463. pSession->hook.xDepth = sessionPreupdateDepth;
  164464. }
  164465. typedef struct SessionDiffCtx SessionDiffCtx;
  164466. struct SessionDiffCtx {
  164467. sqlite3_stmt *pStmt;
  164468. int nOldOff;
  164469. };
  164470. /*
  164471. ** The diff hook implementations.
  164472. */
  164473. static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  164474. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  164475. *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
  164476. return SQLITE_OK;
  164477. }
  164478. static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  164479. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  164480. *ppVal = sqlite3_column_value(p->pStmt, iVal);
  164481. return SQLITE_OK;
  164482. }
  164483. static int sessionDiffCount(void *pCtx){
  164484. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  164485. return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
  164486. }
  164487. static int sessionDiffDepth(void *pCtx){
  164488. return 0;
  164489. }
  164490. /*
  164491. ** Install the diff hooks on the session object passed as the only
  164492. ** argument.
  164493. */
  164494. static void sessionDiffHooks(
  164495. sqlite3_session *pSession,
  164496. SessionDiffCtx *pDiffCtx
  164497. ){
  164498. pSession->hook.pCtx = (void*)pDiffCtx;
  164499. pSession->hook.xOld = sessionDiffOld;
  164500. pSession->hook.xNew = sessionDiffNew;
  164501. pSession->hook.xCount = sessionDiffCount;
  164502. pSession->hook.xDepth = sessionDiffDepth;
  164503. }
  164504. static char *sessionExprComparePK(
  164505. int nCol,
  164506. const char *zDb1, const char *zDb2,
  164507. const char *zTab,
  164508. const char **azCol, u8 *abPK
  164509. ){
  164510. int i;
  164511. const char *zSep = "";
  164512. char *zRet = 0;
  164513. for(i=0; i<nCol; i++){
  164514. if( abPK[i] ){
  164515. zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
  164516. zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
  164517. );
  164518. zSep = " AND ";
  164519. if( zRet==0 ) break;
  164520. }
  164521. }
  164522. return zRet;
  164523. }
  164524. static char *sessionExprCompareOther(
  164525. int nCol,
  164526. const char *zDb1, const char *zDb2,
  164527. const char *zTab,
  164528. const char **azCol, u8 *abPK
  164529. ){
  164530. int i;
  164531. const char *zSep = "";
  164532. char *zRet = 0;
  164533. int bHave = 0;
  164534. for(i=0; i<nCol; i++){
  164535. if( abPK[i]==0 ){
  164536. bHave = 1;
  164537. zRet = sqlite3_mprintf(
  164538. "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
  164539. zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
  164540. );
  164541. zSep = " OR ";
  164542. if( zRet==0 ) break;
  164543. }
  164544. }
  164545. if( bHave==0 ){
  164546. assert( zRet==0 );
  164547. zRet = sqlite3_mprintf("0");
  164548. }
  164549. return zRet;
  164550. }
  164551. static char *sessionSelectFindNew(
  164552. int nCol,
  164553. const char *zDb1, /* Pick rows in this db only */
  164554. const char *zDb2, /* But not in this one */
  164555. const char *zTbl, /* Table name */
  164556. const char *zExpr
  164557. ){
  164558. char *zRet = sqlite3_mprintf(
  164559. "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
  164560. " SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
  164561. ")",
  164562. zDb1, zTbl, zDb2, zTbl, zExpr
  164563. );
  164564. return zRet;
  164565. }
  164566. static int sessionDiffFindNew(
  164567. int op,
  164568. sqlite3_session *pSession,
  164569. SessionTable *pTab,
  164570. const char *zDb1,
  164571. const char *zDb2,
  164572. char *zExpr
  164573. ){
  164574. int rc = SQLITE_OK;
  164575. char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
  164576. if( zStmt==0 ){
  164577. rc = SQLITE_NOMEM;
  164578. }else{
  164579. sqlite3_stmt *pStmt;
  164580. rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
  164581. if( rc==SQLITE_OK ){
  164582. SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
  164583. pDiffCtx->pStmt = pStmt;
  164584. pDiffCtx->nOldOff = 0;
  164585. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  164586. sessionPreupdateOneChange(op, pSession, pTab);
  164587. }
  164588. rc = sqlite3_finalize(pStmt);
  164589. }
  164590. sqlite3_free(zStmt);
  164591. }
  164592. return rc;
  164593. }
  164594. static int sessionDiffFindModified(
  164595. sqlite3_session *pSession,
  164596. SessionTable *pTab,
  164597. const char *zFrom,
  164598. const char *zExpr
  164599. ){
  164600. int rc = SQLITE_OK;
  164601. char *zExpr2 = sessionExprCompareOther(pTab->nCol,
  164602. pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
  164603. );
  164604. if( zExpr2==0 ){
  164605. rc = SQLITE_NOMEM;
  164606. }else{
  164607. char *zStmt = sqlite3_mprintf(
  164608. "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
  164609. pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
  164610. );
  164611. if( zStmt==0 ){
  164612. rc = SQLITE_NOMEM;
  164613. }else{
  164614. sqlite3_stmt *pStmt;
  164615. rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
  164616. if( rc==SQLITE_OK ){
  164617. SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
  164618. pDiffCtx->pStmt = pStmt;
  164619. pDiffCtx->nOldOff = pTab->nCol;
  164620. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  164621. sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
  164622. }
  164623. rc = sqlite3_finalize(pStmt);
  164624. }
  164625. sqlite3_free(zStmt);
  164626. }
  164627. }
  164628. return rc;
  164629. }
  164630. SQLITE_API int sqlite3session_diff(
  164631. sqlite3_session *pSession,
  164632. const char *zFrom,
  164633. const char *zTbl,
  164634. char **pzErrMsg
  164635. ){
  164636. const char *zDb = pSession->zDb;
  164637. int rc = pSession->rc;
  164638. SessionDiffCtx d;
  164639. memset(&d, 0, sizeof(d));
  164640. sessionDiffHooks(pSession, &d);
  164641. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  164642. if( pzErrMsg ) *pzErrMsg = 0;
  164643. if( rc==SQLITE_OK ){
  164644. char *zExpr = 0;
  164645. sqlite3 *db = pSession->db;
  164646. SessionTable *pTo; /* Table zTbl */
  164647. /* Locate and if necessary initialize the target table object */
  164648. rc = sessionFindTable(pSession, zTbl, &pTo);
  164649. if( pTo==0 ) goto diff_out;
  164650. if( sessionInitTable(pSession, pTo) ){
  164651. rc = pSession->rc;
  164652. goto diff_out;
  164653. }
  164654. /* Check the table schemas match */
  164655. if( rc==SQLITE_OK ){
  164656. int bHasPk = 0;
  164657. int bMismatch = 0;
  164658. int nCol; /* Columns in zFrom.zTbl */
  164659. u8 *abPK;
  164660. const char **azCol = 0;
  164661. rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
  164662. if( rc==SQLITE_OK ){
  164663. if( pTo->nCol!=nCol ){
  164664. bMismatch = 1;
  164665. }else{
  164666. int i;
  164667. for(i=0; i<nCol; i++){
  164668. if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
  164669. if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
  164670. if( abPK[i] ) bHasPk = 1;
  164671. }
  164672. }
  164673. }
  164674. sqlite3_free((char*)azCol);
  164675. if( bMismatch ){
  164676. *pzErrMsg = sqlite3_mprintf("table schemas do not match");
  164677. rc = SQLITE_SCHEMA;
  164678. }
  164679. if( bHasPk==0 ){
  164680. /* Ignore tables with no primary keys */
  164681. goto diff_out;
  164682. }
  164683. }
  164684. if( rc==SQLITE_OK ){
  164685. zExpr = sessionExprComparePK(pTo->nCol,
  164686. zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
  164687. );
  164688. }
  164689. /* Find new rows */
  164690. if( rc==SQLITE_OK ){
  164691. rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
  164692. }
  164693. /* Find old rows */
  164694. if( rc==SQLITE_OK ){
  164695. rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
  164696. }
  164697. /* Find modified rows */
  164698. if( rc==SQLITE_OK ){
  164699. rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
  164700. }
  164701. sqlite3_free(zExpr);
  164702. }
  164703. diff_out:
  164704. sessionPreupdateHooks(pSession);
  164705. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  164706. return rc;
  164707. }
  164708. /*
  164709. ** Create a session object. This session object will record changes to
  164710. ** database zDb attached to connection db.
  164711. */
  164712. SQLITE_API int sqlite3session_create(
  164713. sqlite3 *db, /* Database handle */
  164714. const char *zDb, /* Name of db (e.g. "main") */
  164715. sqlite3_session **ppSession /* OUT: New session object */
  164716. ){
  164717. sqlite3_session *pNew; /* Newly allocated session object */
  164718. sqlite3_session *pOld; /* Session object already attached to db */
  164719. int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
  164720. /* Zero the output value in case an error occurs. */
  164721. *ppSession = 0;
  164722. /* Allocate and populate the new session object. */
  164723. pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
  164724. if( !pNew ) return SQLITE_NOMEM;
  164725. memset(pNew, 0, sizeof(sqlite3_session));
  164726. pNew->db = db;
  164727. pNew->zDb = (char *)&pNew[1];
  164728. pNew->bEnable = 1;
  164729. memcpy(pNew->zDb, zDb, nDb+1);
  164730. sessionPreupdateHooks(pNew);
  164731. /* Add the new session object to the linked list of session objects
  164732. ** attached to database handle $db. Do this under the cover of the db
  164733. ** handle mutex. */
  164734. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  164735. pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
  164736. pNew->pNext = pOld;
  164737. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  164738. *ppSession = pNew;
  164739. return SQLITE_OK;
  164740. }
  164741. /*
  164742. ** Free the list of table objects passed as the first argument. The contents
  164743. ** of the changed-rows hash tables are also deleted.
  164744. */
  164745. static void sessionDeleteTable(SessionTable *pList){
  164746. SessionTable *pNext;
  164747. SessionTable *pTab;
  164748. for(pTab=pList; pTab; pTab=pNext){
  164749. int i;
  164750. pNext = pTab->pNext;
  164751. for(i=0; i<pTab->nChange; i++){
  164752. SessionChange *p;
  164753. SessionChange *pNextChange;
  164754. for(p=pTab->apChange[i]; p; p=pNextChange){
  164755. pNextChange = p->pNext;
  164756. sqlite3_free(p);
  164757. }
  164758. }
  164759. sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */
  164760. sqlite3_free(pTab->apChange);
  164761. sqlite3_free(pTab);
  164762. }
  164763. }
  164764. /*
  164765. ** Delete a session object previously allocated using sqlite3session_create().
  164766. */
  164767. SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
  164768. sqlite3 *db = pSession->db;
  164769. sqlite3_session *pHead;
  164770. sqlite3_session **pp;
  164771. /* Unlink the session from the linked list of sessions attached to the
  164772. ** database handle. Hold the db mutex while doing so. */
  164773. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  164774. pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
  164775. for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
  164776. if( (*pp)==pSession ){
  164777. *pp = (*pp)->pNext;
  164778. if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
  164779. break;
  164780. }
  164781. }
  164782. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  164783. /* Delete all attached table objects. And the contents of their
  164784. ** associated hash-tables. */
  164785. sessionDeleteTable(pSession->pTable);
  164786. /* Free the session object itself. */
  164787. sqlite3_free(pSession);
  164788. }
  164789. /*
  164790. ** Set a table filter on a Session Object.
  164791. */
  164792. SQLITE_API void sqlite3session_table_filter(
  164793. sqlite3_session *pSession,
  164794. int(*xFilter)(void*, const char*),
  164795. void *pCtx /* First argument passed to xFilter */
  164796. ){
  164797. pSession->bAutoAttach = 1;
  164798. pSession->pFilterCtx = pCtx;
  164799. pSession->xTableFilter = xFilter;
  164800. }
  164801. /*
  164802. ** Attach a table to a session. All subsequent changes made to the table
  164803. ** while the session object is enabled will be recorded.
  164804. **
  164805. ** Only tables that have a PRIMARY KEY defined may be attached. It does
  164806. ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
  164807. ** or not.
  164808. */
  164809. SQLITE_API int sqlite3session_attach(
  164810. sqlite3_session *pSession, /* Session object */
  164811. const char *zName /* Table name */
  164812. ){
  164813. int rc = SQLITE_OK;
  164814. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  164815. if( !zName ){
  164816. pSession->bAutoAttach = 1;
  164817. }else{
  164818. SessionTable *pTab; /* New table object (if required) */
  164819. int nName; /* Number of bytes in string zName */
  164820. /* First search for an existing entry. If one is found, this call is
  164821. ** a no-op. Return early. */
  164822. nName = sqlite3Strlen30(zName);
  164823. for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
  164824. if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
  164825. }
  164826. if( !pTab ){
  164827. /* Allocate new SessionTable object. */
  164828. pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
  164829. if( !pTab ){
  164830. rc = SQLITE_NOMEM;
  164831. }else{
  164832. /* Populate the new SessionTable object and link it into the list.
  164833. ** The new object must be linked onto the end of the list, not
  164834. ** simply added to the start of it in order to ensure that tables
  164835. ** appear in the correct order when a changeset or patchset is
  164836. ** eventually generated. */
  164837. SessionTable **ppTab;
  164838. memset(pTab, 0, sizeof(SessionTable));
  164839. pTab->zName = (char *)&pTab[1];
  164840. memcpy(pTab->zName, zName, nName+1);
  164841. for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
  164842. *ppTab = pTab;
  164843. }
  164844. }
  164845. }
  164846. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  164847. return rc;
  164848. }
  164849. /*
  164850. ** Ensure that there is room in the buffer to append nByte bytes of data.
  164851. ** If not, use sqlite3_realloc() to grow the buffer so that there is.
  164852. **
  164853. ** If successful, return zero. Otherwise, if an OOM condition is encountered,
  164854. ** set *pRc to SQLITE_NOMEM and return non-zero.
  164855. */
  164856. static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
  164857. if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
  164858. u8 *aNew;
  164859. int nNew = p->nAlloc ? p->nAlloc : 128;
  164860. do {
  164861. nNew = nNew*2;
  164862. }while( nNew<(p->nBuf+nByte) );
  164863. aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
  164864. if( 0==aNew ){
  164865. *pRc = SQLITE_NOMEM;
  164866. }else{
  164867. p->aBuf = aNew;
  164868. p->nAlloc = nNew;
  164869. }
  164870. }
  164871. return (*pRc!=SQLITE_OK);
  164872. }
  164873. /*
  164874. ** Append the value passed as the second argument to the buffer passed
  164875. ** as the first.
  164876. **
  164877. ** This function is a no-op if *pRc is non-zero when it is called.
  164878. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
  164879. ** before returning.
  164880. */
  164881. static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
  164882. int rc = *pRc;
  164883. if( rc==SQLITE_OK ){
  164884. int nByte = 0;
  164885. rc = sessionSerializeValue(0, pVal, &nByte);
  164886. sessionBufferGrow(p, nByte, &rc);
  164887. if( rc==SQLITE_OK ){
  164888. rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
  164889. p->nBuf += nByte;
  164890. }else{
  164891. *pRc = rc;
  164892. }
  164893. }
  164894. }
  164895. /*
  164896. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  164897. ** called. Otherwise, append a single byte to the buffer.
  164898. **
  164899. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  164900. ** returning.
  164901. */
  164902. static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
  164903. if( 0==sessionBufferGrow(p, 1, pRc) ){
  164904. p->aBuf[p->nBuf++] = v;
  164905. }
  164906. }
  164907. /*
  164908. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  164909. ** called. Otherwise, append a single varint to the buffer.
  164910. **
  164911. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  164912. ** returning.
  164913. */
  164914. static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
  164915. if( 0==sessionBufferGrow(p, 9, pRc) ){
  164916. p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
  164917. }
  164918. }
  164919. /*
  164920. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  164921. ** called. Otherwise, append a blob of data to the buffer.
  164922. **
  164923. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  164924. ** returning.
  164925. */
  164926. static void sessionAppendBlob(
  164927. SessionBuffer *p,
  164928. const u8 *aBlob,
  164929. int nBlob,
  164930. int *pRc
  164931. ){
  164932. if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
  164933. memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
  164934. p->nBuf += nBlob;
  164935. }
  164936. }
  164937. /*
  164938. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  164939. ** called. Otherwise, append a string to the buffer. All bytes in the string
  164940. ** up to (but not including) the nul-terminator are written to the buffer.
  164941. **
  164942. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  164943. ** returning.
  164944. */
  164945. static void sessionAppendStr(
  164946. SessionBuffer *p,
  164947. const char *zStr,
  164948. int *pRc
  164949. ){
  164950. int nStr = sqlite3Strlen30(zStr);
  164951. if( 0==sessionBufferGrow(p, nStr, pRc) ){
  164952. memcpy(&p->aBuf[p->nBuf], zStr, nStr);
  164953. p->nBuf += nStr;
  164954. }
  164955. }
  164956. /*
  164957. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  164958. ** called. Otherwise, append the string representation of integer iVal
  164959. ** to the buffer. No nul-terminator is written.
  164960. **
  164961. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  164962. ** returning.
  164963. */
  164964. static void sessionAppendInteger(
  164965. SessionBuffer *p, /* Buffer to append to */
  164966. int iVal, /* Value to write the string rep. of */
  164967. int *pRc /* IN/OUT: Error code */
  164968. ){
  164969. char aBuf[24];
  164970. sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
  164971. sessionAppendStr(p, aBuf, pRc);
  164972. }
  164973. /*
  164974. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  164975. ** called. Otherwise, append the string zStr enclosed in quotes (") and
  164976. ** with any embedded quote characters escaped to the buffer. No
  164977. ** nul-terminator byte is written.
  164978. **
  164979. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  164980. ** returning.
  164981. */
  164982. static void sessionAppendIdent(
  164983. SessionBuffer *p, /* Buffer to a append to */
  164984. const char *zStr, /* String to quote, escape and append */
  164985. int *pRc /* IN/OUT: Error code */
  164986. ){
  164987. int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
  164988. if( 0==sessionBufferGrow(p, nStr, pRc) ){
  164989. char *zOut = (char *)&p->aBuf[p->nBuf];
  164990. const char *zIn = zStr;
  164991. *zOut++ = '"';
  164992. while( *zIn ){
  164993. if( *zIn=='"' ) *zOut++ = '"';
  164994. *zOut++ = *(zIn++);
  164995. }
  164996. *zOut++ = '"';
  164997. p->nBuf = (int)((u8 *)zOut - p->aBuf);
  164998. }
  164999. }
  165000. /*
  165001. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  165002. ** called. Otherwse, it appends the serialized version of the value stored
  165003. ** in column iCol of the row that SQL statement pStmt currently points
  165004. ** to to the buffer.
  165005. */
  165006. static void sessionAppendCol(
  165007. SessionBuffer *p, /* Buffer to append to */
  165008. sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
  165009. int iCol, /* Column to read value from */
  165010. int *pRc /* IN/OUT: Error code */
  165011. ){
  165012. if( *pRc==SQLITE_OK ){
  165013. int eType = sqlite3_column_type(pStmt, iCol);
  165014. sessionAppendByte(p, (u8)eType, pRc);
  165015. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  165016. sqlite3_int64 i;
  165017. u8 aBuf[8];
  165018. if( eType==SQLITE_INTEGER ){
  165019. i = sqlite3_column_int64(pStmt, iCol);
  165020. }else{
  165021. double r = sqlite3_column_double(pStmt, iCol);
  165022. memcpy(&i, &r, 8);
  165023. }
  165024. sessionPutI64(aBuf, i);
  165025. sessionAppendBlob(p, aBuf, 8, pRc);
  165026. }
  165027. if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
  165028. u8 *z;
  165029. int nByte;
  165030. if( eType==SQLITE_BLOB ){
  165031. z = (u8 *)sqlite3_column_blob(pStmt, iCol);
  165032. }else{
  165033. z = (u8 *)sqlite3_column_text(pStmt, iCol);
  165034. }
  165035. nByte = sqlite3_column_bytes(pStmt, iCol);
  165036. if( z || (eType==SQLITE_BLOB && nByte==0) ){
  165037. sessionAppendVarint(p, nByte, pRc);
  165038. sessionAppendBlob(p, z, nByte, pRc);
  165039. }else{
  165040. *pRc = SQLITE_NOMEM;
  165041. }
  165042. }
  165043. }
  165044. }
  165045. /*
  165046. **
  165047. ** This function appends an update change to the buffer (see the comments
  165048. ** under "CHANGESET FORMAT" at the top of the file). An update change
  165049. ** consists of:
  165050. **
  165051. ** 1 byte: SQLITE_UPDATE (0x17)
  165052. ** n bytes: old.* record (see RECORD FORMAT)
  165053. ** m bytes: new.* record (see RECORD FORMAT)
  165054. **
  165055. ** The SessionChange object passed as the third argument contains the
  165056. ** values that were stored in the row when the session began (the old.*
  165057. ** values). The statement handle passed as the second argument points
  165058. ** at the current version of the row (the new.* values).
  165059. **
  165060. ** If all of the old.* values are equal to their corresponding new.* value
  165061. ** (i.e. nothing has changed), then no data at all is appended to the buffer.
  165062. **
  165063. ** Otherwise, the old.* record contains all primary key values and the
  165064. ** original values of any fields that have been modified. The new.* record
  165065. ** contains the new values of only those fields that have been modified.
  165066. */
  165067. static int sessionAppendUpdate(
  165068. SessionBuffer *pBuf, /* Buffer to append to */
  165069. int bPatchset, /* True for "patchset", 0 for "changeset" */
  165070. sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
  165071. SessionChange *p, /* Object containing old values */
  165072. u8 *abPK /* Boolean array - true for PK columns */
  165073. ){
  165074. int rc = SQLITE_OK;
  165075. SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
  165076. int bNoop = 1; /* Set to zero if any values are modified */
  165077. int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
  165078. int i; /* Used to iterate through columns */
  165079. u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
  165080. sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
  165081. sessionAppendByte(pBuf, p->bIndirect, &rc);
  165082. for(i=0; i<sqlite3_column_count(pStmt); i++){
  165083. int bChanged = 0;
  165084. int nAdvance;
  165085. int eType = *pCsr;
  165086. switch( eType ){
  165087. case SQLITE_NULL:
  165088. nAdvance = 1;
  165089. if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  165090. bChanged = 1;
  165091. }
  165092. break;
  165093. case SQLITE_FLOAT:
  165094. case SQLITE_INTEGER: {
  165095. nAdvance = 9;
  165096. if( eType==sqlite3_column_type(pStmt, i) ){
  165097. sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
  165098. if( eType==SQLITE_INTEGER ){
  165099. if( iVal==sqlite3_column_int64(pStmt, i) ) break;
  165100. }else{
  165101. double dVal;
  165102. memcpy(&dVal, &iVal, 8);
  165103. if( dVal==sqlite3_column_double(pStmt, i) ) break;
  165104. }
  165105. }
  165106. bChanged = 1;
  165107. break;
  165108. }
  165109. default: {
  165110. int n;
  165111. int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
  165112. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  165113. nAdvance = nHdr + n;
  165114. if( eType==sqlite3_column_type(pStmt, i)
  165115. && n==sqlite3_column_bytes(pStmt, i)
  165116. && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
  165117. ){
  165118. break;
  165119. }
  165120. bChanged = 1;
  165121. }
  165122. }
  165123. /* If at least one field has been modified, this is not a no-op. */
  165124. if( bChanged ) bNoop = 0;
  165125. /* Add a field to the old.* record. This is omitted if this modules is
  165126. ** currently generating a patchset. */
  165127. if( bPatchset==0 ){
  165128. if( bChanged || abPK[i] ){
  165129. sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
  165130. }else{
  165131. sessionAppendByte(pBuf, 0, &rc);
  165132. }
  165133. }
  165134. /* Add a field to the new.* record. Or the only record if currently
  165135. ** generating a patchset. */
  165136. if( bChanged || (bPatchset && abPK[i]) ){
  165137. sessionAppendCol(&buf2, pStmt, i, &rc);
  165138. }else{
  165139. sessionAppendByte(&buf2, 0, &rc);
  165140. }
  165141. pCsr += nAdvance;
  165142. }
  165143. if( bNoop ){
  165144. pBuf->nBuf = nRewind;
  165145. }else{
  165146. sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
  165147. }
  165148. sqlite3_free(buf2.aBuf);
  165149. return rc;
  165150. }
  165151. /*
  165152. ** Append a DELETE change to the buffer passed as the first argument. Use
  165153. ** the changeset format if argument bPatchset is zero, or the patchset
  165154. ** format otherwise.
  165155. */
  165156. static int sessionAppendDelete(
  165157. SessionBuffer *pBuf, /* Buffer to append to */
  165158. int bPatchset, /* True for "patchset", 0 for "changeset" */
  165159. SessionChange *p, /* Object containing old values */
  165160. int nCol, /* Number of columns in table */
  165161. u8 *abPK /* Boolean array - true for PK columns */
  165162. ){
  165163. int rc = SQLITE_OK;
  165164. sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
  165165. sessionAppendByte(pBuf, p->bIndirect, &rc);
  165166. if( bPatchset==0 ){
  165167. sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
  165168. }else{
  165169. int i;
  165170. u8 *a = p->aRecord;
  165171. for(i=0; i<nCol; i++){
  165172. u8 *pStart = a;
  165173. int eType = *a++;
  165174. switch( eType ){
  165175. case 0:
  165176. case SQLITE_NULL:
  165177. assert( abPK[i]==0 );
  165178. break;
  165179. case SQLITE_FLOAT:
  165180. case SQLITE_INTEGER:
  165181. a += 8;
  165182. break;
  165183. default: {
  165184. int n;
  165185. a += sessionVarintGet(a, &n);
  165186. a += n;
  165187. break;
  165188. }
  165189. }
  165190. if( abPK[i] ){
  165191. sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
  165192. }
  165193. }
  165194. assert( (a - p->aRecord)==p->nRecord );
  165195. }
  165196. return rc;
  165197. }
  165198. /*
  165199. ** Formulate and prepare a SELECT statement to retrieve a row from table
  165200. ** zTab in database zDb based on its primary key. i.e.
  165201. **
  165202. ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
  165203. */
  165204. static int sessionSelectStmt(
  165205. sqlite3 *db, /* Database handle */
  165206. const char *zDb, /* Database name */
  165207. const char *zTab, /* Table name */
  165208. int nCol, /* Number of columns in table */
  165209. const char **azCol, /* Names of table columns */
  165210. u8 *abPK, /* PRIMARY KEY array */
  165211. sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
  165212. ){
  165213. int rc = SQLITE_OK;
  165214. int i;
  165215. const char *zSep = "";
  165216. SessionBuffer buf = {0, 0, 0};
  165217. sessionAppendStr(&buf, "SELECT * FROM ", &rc);
  165218. sessionAppendIdent(&buf, zDb, &rc);
  165219. sessionAppendStr(&buf, ".", &rc);
  165220. sessionAppendIdent(&buf, zTab, &rc);
  165221. sessionAppendStr(&buf, " WHERE ", &rc);
  165222. for(i=0; i<nCol; i++){
  165223. if( abPK[i] ){
  165224. sessionAppendStr(&buf, zSep, &rc);
  165225. sessionAppendIdent(&buf, azCol[i], &rc);
  165226. sessionAppendStr(&buf, " = ?", &rc);
  165227. sessionAppendInteger(&buf, i+1, &rc);
  165228. zSep = " AND ";
  165229. }
  165230. }
  165231. if( rc==SQLITE_OK ){
  165232. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
  165233. }
  165234. sqlite3_free(buf.aBuf);
  165235. return rc;
  165236. }
  165237. /*
  165238. ** Bind the PRIMARY KEY values from the change passed in argument pChange
  165239. ** to the SELECT statement passed as the first argument. The SELECT statement
  165240. ** is as prepared by function sessionSelectStmt().
  165241. **
  165242. ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
  165243. ** error code (e.g. SQLITE_NOMEM) otherwise.
  165244. */
  165245. static int sessionSelectBind(
  165246. sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
  165247. int nCol, /* Number of columns in table */
  165248. u8 *abPK, /* PRIMARY KEY array */
  165249. SessionChange *pChange /* Change structure */
  165250. ){
  165251. int i;
  165252. int rc = SQLITE_OK;
  165253. u8 *a = pChange->aRecord;
  165254. for(i=0; i<nCol && rc==SQLITE_OK; i++){
  165255. int eType = *a++;
  165256. switch( eType ){
  165257. case 0:
  165258. case SQLITE_NULL:
  165259. assert( abPK[i]==0 );
  165260. break;
  165261. case SQLITE_INTEGER: {
  165262. if( abPK[i] ){
  165263. i64 iVal = sessionGetI64(a);
  165264. rc = sqlite3_bind_int64(pSelect, i+1, iVal);
  165265. }
  165266. a += 8;
  165267. break;
  165268. }
  165269. case SQLITE_FLOAT: {
  165270. if( abPK[i] ){
  165271. double rVal;
  165272. i64 iVal = sessionGetI64(a);
  165273. memcpy(&rVal, &iVal, 8);
  165274. rc = sqlite3_bind_double(pSelect, i+1, rVal);
  165275. }
  165276. a += 8;
  165277. break;
  165278. }
  165279. case SQLITE_TEXT: {
  165280. int n;
  165281. a += sessionVarintGet(a, &n);
  165282. if( abPK[i] ){
  165283. rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
  165284. }
  165285. a += n;
  165286. break;
  165287. }
  165288. default: {
  165289. int n;
  165290. assert( eType==SQLITE_BLOB );
  165291. a += sessionVarintGet(a, &n);
  165292. if( abPK[i] ){
  165293. rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
  165294. }
  165295. a += n;
  165296. break;
  165297. }
  165298. }
  165299. }
  165300. return rc;
  165301. }
  165302. /*
  165303. ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
  165304. ** is called. Otherwise, append a serialized table header (part of the binary
  165305. ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
  165306. ** SQLite error code before returning.
  165307. */
  165308. static void sessionAppendTableHdr(
  165309. SessionBuffer *pBuf, /* Append header to this buffer */
  165310. int bPatchset, /* Use the patchset format if true */
  165311. SessionTable *pTab, /* Table object to append header for */
  165312. int *pRc /* IN/OUT: Error code */
  165313. ){
  165314. /* Write a table header */
  165315. sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
  165316. sessionAppendVarint(pBuf, pTab->nCol, pRc);
  165317. sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
  165318. sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
  165319. }
  165320. /*
  165321. ** Generate either a changeset (if argument bPatchset is zero) or a patchset
  165322. ** (if it is non-zero) based on the current contents of the session object
  165323. ** passed as the first argument.
  165324. **
  165325. ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
  165326. ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
  165327. ** occurs, an SQLite error code is returned and both output variables set
  165328. ** to 0.
  165329. */
  165330. static int sessionGenerateChangeset(
  165331. sqlite3_session *pSession, /* Session object */
  165332. int bPatchset, /* True for patchset, false for changeset */
  165333. int (*xOutput)(void *pOut, const void *pData, int nData),
  165334. void *pOut, /* First argument for xOutput */
  165335. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  165336. void **ppChangeset /* OUT: Buffer containing changeset */
  165337. ){
  165338. sqlite3 *db = pSession->db; /* Source database handle */
  165339. SessionTable *pTab; /* Used to iterate through attached tables */
  165340. SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
  165341. int rc; /* Return code */
  165342. assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
  165343. /* Zero the output variables in case an error occurs. If this session
  165344. ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
  165345. ** this call will be a no-op. */
  165346. if( xOutput==0 ){
  165347. *pnChangeset = 0;
  165348. *ppChangeset = 0;
  165349. }
  165350. if( pSession->rc ) return pSession->rc;
  165351. rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
  165352. if( rc!=SQLITE_OK ) return rc;
  165353. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  165354. for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
  165355. if( pTab->nEntry ){
  165356. const char *zName = pTab->zName;
  165357. int nCol; /* Number of columns in table */
  165358. u8 *abPK; /* Primary key array */
  165359. const char **azCol = 0; /* Table columns */
  165360. int i; /* Used to iterate through hash buckets */
  165361. sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
  165362. int nRewind = buf.nBuf; /* Initial size of write buffer */
  165363. int nNoop; /* Size of buffer after writing tbl header */
  165364. /* Check the table schema is still Ok. */
  165365. rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
  165366. if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
  165367. rc = SQLITE_SCHEMA;
  165368. }
  165369. /* Write a table header */
  165370. sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
  165371. /* Build and compile a statement to execute: */
  165372. if( rc==SQLITE_OK ){
  165373. rc = sessionSelectStmt(
  165374. db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
  165375. }
  165376. nNoop = buf.nBuf;
  165377. for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
  165378. SessionChange *p; /* Used to iterate through changes */
  165379. for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
  165380. rc = sessionSelectBind(pSel, nCol, abPK, p);
  165381. if( rc!=SQLITE_OK ) continue;
  165382. if( sqlite3_step(pSel)==SQLITE_ROW ){
  165383. if( p->op==SQLITE_INSERT ){
  165384. int iCol;
  165385. sessionAppendByte(&buf, SQLITE_INSERT, &rc);
  165386. sessionAppendByte(&buf, p->bIndirect, &rc);
  165387. for(iCol=0; iCol<nCol; iCol++){
  165388. sessionAppendCol(&buf, pSel, iCol, &rc);
  165389. }
  165390. }else{
  165391. rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
  165392. }
  165393. }else if( p->op!=SQLITE_INSERT ){
  165394. rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
  165395. }
  165396. if( rc==SQLITE_OK ){
  165397. rc = sqlite3_reset(pSel);
  165398. }
  165399. /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
  165400. ** its contents to the xOutput() callback. */
  165401. if( xOutput
  165402. && rc==SQLITE_OK
  165403. && buf.nBuf>nNoop
  165404. && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE
  165405. ){
  165406. rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
  165407. nNoop = -1;
  165408. buf.nBuf = 0;
  165409. }
  165410. }
  165411. }
  165412. sqlite3_finalize(pSel);
  165413. if( buf.nBuf==nNoop ){
  165414. buf.nBuf = nRewind;
  165415. }
  165416. sqlite3_free((char*)azCol); /* cast works around VC++ bug */
  165417. }
  165418. }
  165419. if( rc==SQLITE_OK ){
  165420. if( xOutput==0 ){
  165421. *pnChangeset = buf.nBuf;
  165422. *ppChangeset = buf.aBuf;
  165423. buf.aBuf = 0;
  165424. }else if( buf.nBuf>0 ){
  165425. rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
  165426. }
  165427. }
  165428. sqlite3_free(buf.aBuf);
  165429. sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
  165430. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  165431. return rc;
  165432. }
  165433. /*
  165434. ** Obtain a changeset object containing all changes recorded by the
  165435. ** session object passed as the first argument.
  165436. **
  165437. ** It is the responsibility of the caller to eventually free the buffer
  165438. ** using sqlite3_free().
  165439. */
  165440. SQLITE_API int sqlite3session_changeset(
  165441. sqlite3_session *pSession, /* Session object */
  165442. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  165443. void **ppChangeset /* OUT: Buffer containing changeset */
  165444. ){
  165445. return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
  165446. }
  165447. /*
  165448. ** Streaming version of sqlite3session_changeset().
  165449. */
  165450. SQLITE_API int sqlite3session_changeset_strm(
  165451. sqlite3_session *pSession,
  165452. int (*xOutput)(void *pOut, const void *pData, int nData),
  165453. void *pOut
  165454. ){
  165455. return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
  165456. }
  165457. /*
  165458. ** Streaming version of sqlite3session_patchset().
  165459. */
  165460. SQLITE_API int sqlite3session_patchset_strm(
  165461. sqlite3_session *pSession,
  165462. int (*xOutput)(void *pOut, const void *pData, int nData),
  165463. void *pOut
  165464. ){
  165465. return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
  165466. }
  165467. /*
  165468. ** Obtain a patchset object containing all changes recorded by the
  165469. ** session object passed as the first argument.
  165470. **
  165471. ** It is the responsibility of the caller to eventually free the buffer
  165472. ** using sqlite3_free().
  165473. */
  165474. SQLITE_API int sqlite3session_patchset(
  165475. sqlite3_session *pSession, /* Session object */
  165476. int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
  165477. void **ppPatchset /* OUT: Buffer containing changeset */
  165478. ){
  165479. return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
  165480. }
  165481. /*
  165482. ** Enable or disable the session object passed as the first argument.
  165483. */
  165484. SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
  165485. int ret;
  165486. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  165487. if( bEnable>=0 ){
  165488. pSession->bEnable = bEnable;
  165489. }
  165490. ret = pSession->bEnable;
  165491. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  165492. return ret;
  165493. }
  165494. /*
  165495. ** Enable or disable the session object passed as the first argument.
  165496. */
  165497. SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
  165498. int ret;
  165499. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  165500. if( bIndirect>=0 ){
  165501. pSession->bIndirect = bIndirect;
  165502. }
  165503. ret = pSession->bIndirect;
  165504. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  165505. return ret;
  165506. }
  165507. /*
  165508. ** Return true if there have been no changes to monitored tables recorded
  165509. ** by the session object passed as the only argument.
  165510. */
  165511. SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
  165512. int ret = 0;
  165513. SessionTable *pTab;
  165514. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  165515. for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
  165516. ret = (pTab->nEntry>0);
  165517. }
  165518. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  165519. return (ret==0);
  165520. }
  165521. /*
  165522. ** Do the work for either sqlite3changeset_start() or start_strm().
  165523. */
  165524. static int sessionChangesetStart(
  165525. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  165526. int (*xInput)(void *pIn, void *pData, int *pnData),
  165527. void *pIn,
  165528. int nChangeset, /* Size of buffer pChangeset in bytes */
  165529. void *pChangeset /* Pointer to buffer containing changeset */
  165530. ){
  165531. sqlite3_changeset_iter *pRet; /* Iterator to return */
  165532. int nByte; /* Number of bytes to allocate for iterator */
  165533. assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
  165534. /* Zero the output variable in case an error occurs. */
  165535. *pp = 0;
  165536. /* Allocate and initialize the iterator structure. */
  165537. nByte = sizeof(sqlite3_changeset_iter);
  165538. pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
  165539. if( !pRet ) return SQLITE_NOMEM;
  165540. memset(pRet, 0, sizeof(sqlite3_changeset_iter));
  165541. pRet->in.aData = (u8 *)pChangeset;
  165542. pRet->in.nData = nChangeset;
  165543. pRet->in.xInput = xInput;
  165544. pRet->in.pIn = pIn;
  165545. pRet->in.bEof = (xInput ? 0 : 1);
  165546. /* Populate the output variable and return success. */
  165547. *pp = pRet;
  165548. return SQLITE_OK;
  165549. }
  165550. /*
  165551. ** Create an iterator used to iterate through the contents of a changeset.
  165552. */
  165553. SQLITE_API int sqlite3changeset_start(
  165554. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  165555. int nChangeset, /* Size of buffer pChangeset in bytes */
  165556. void *pChangeset /* Pointer to buffer containing changeset */
  165557. ){
  165558. return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
  165559. }
  165560. /*
  165561. ** Streaming version of sqlite3changeset_start().
  165562. */
  165563. SQLITE_API int sqlite3changeset_start_strm(
  165564. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  165565. int (*xInput)(void *pIn, void *pData, int *pnData),
  165566. void *pIn
  165567. ){
  165568. return sessionChangesetStart(pp, xInput, pIn, 0, 0);
  165569. }
  165570. /*
  165571. ** If the SessionInput object passed as the only argument is a streaming
  165572. ** object and the buffer is full, discard some data to free up space.
  165573. */
  165574. static void sessionDiscardData(SessionInput *pIn){
  165575. if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
  165576. int nMove = pIn->buf.nBuf - pIn->iNext;
  165577. assert( nMove>=0 );
  165578. if( nMove>0 ){
  165579. memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
  165580. }
  165581. pIn->buf.nBuf -= pIn->iNext;
  165582. pIn->iNext = 0;
  165583. pIn->nData = pIn->buf.nBuf;
  165584. }
  165585. }
  165586. /*
  165587. ** Ensure that there are at least nByte bytes available in the buffer. Or,
  165588. ** if there are not nByte bytes remaining in the input, that all available
  165589. ** data is in the buffer.
  165590. **
  165591. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  165592. */
  165593. static int sessionInputBuffer(SessionInput *pIn, int nByte){
  165594. int rc = SQLITE_OK;
  165595. if( pIn->xInput ){
  165596. while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
  165597. int nNew = SESSIONS_STRM_CHUNK_SIZE;
  165598. if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
  165599. if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
  165600. rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
  165601. if( nNew==0 ){
  165602. pIn->bEof = 1;
  165603. }else{
  165604. pIn->buf.nBuf += nNew;
  165605. }
  165606. }
  165607. pIn->aData = pIn->buf.aBuf;
  165608. pIn->nData = pIn->buf.nBuf;
  165609. }
  165610. }
  165611. return rc;
  165612. }
  165613. /*
  165614. ** When this function is called, *ppRec points to the start of a record
  165615. ** that contains nCol values. This function advances the pointer *ppRec
  165616. ** until it points to the byte immediately following that record.
  165617. */
  165618. static void sessionSkipRecord(
  165619. u8 **ppRec, /* IN/OUT: Record pointer */
  165620. int nCol /* Number of values in record */
  165621. ){
  165622. u8 *aRec = *ppRec;
  165623. int i;
  165624. for(i=0; i<nCol; i++){
  165625. int eType = *aRec++;
  165626. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  165627. int nByte;
  165628. aRec += sessionVarintGet((u8*)aRec, &nByte);
  165629. aRec += nByte;
  165630. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  165631. aRec += 8;
  165632. }
  165633. }
  165634. *ppRec = aRec;
  165635. }
  165636. /*
  165637. ** This function sets the value of the sqlite3_value object passed as the
  165638. ** first argument to a copy of the string or blob held in the aData[]
  165639. ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
  165640. ** error occurs.
  165641. */
  165642. static int sessionValueSetStr(
  165643. sqlite3_value *pVal, /* Set the value of this object */
  165644. u8 *aData, /* Buffer containing string or blob data */
  165645. int nData, /* Size of buffer aData[] in bytes */
  165646. u8 enc /* String encoding (0 for blobs) */
  165647. ){
  165648. /* In theory this code could just pass SQLITE_TRANSIENT as the final
  165649. ** argument to sqlite3ValueSetStr() and have the copy created
  165650. ** automatically. But doing so makes it difficult to detect any OOM
  165651. ** error. Hence the code to create the copy externally. */
  165652. u8 *aCopy = sqlite3_malloc(nData+1);
  165653. if( aCopy==0 ) return SQLITE_NOMEM;
  165654. memcpy(aCopy, aData, nData);
  165655. sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
  165656. return SQLITE_OK;
  165657. }
  165658. /*
  165659. ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
  165660. ** for details.
  165661. **
  165662. ** When this function is called, *paChange points to the start of the record
  165663. ** to deserialize. Assuming no error occurs, *paChange is set to point to
  165664. ** one byte after the end of the same record before this function returns.
  165665. ** If the argument abPK is NULL, then the record contains nCol values. Or,
  165666. ** if abPK is other than NULL, then the record contains only the PK fields
  165667. ** (in other words, it is a patchset DELETE record).
  165668. **
  165669. ** If successful, each element of the apOut[] array (allocated by the caller)
  165670. ** is set to point to an sqlite3_value object containing the value read
  165671. ** from the corresponding position in the record. If that value is not
  165672. ** included in the record (i.e. because the record is part of an UPDATE change
  165673. ** and the field was not modified), the corresponding element of apOut[] is
  165674. ** set to NULL.
  165675. **
  165676. ** It is the responsibility of the caller to free all sqlite_value structures
  165677. ** using sqlite3_free().
  165678. **
  165679. ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
  165680. ** The apOut[] array may have been partially populated in this case.
  165681. */
  165682. static int sessionReadRecord(
  165683. SessionInput *pIn, /* Input data */
  165684. int nCol, /* Number of values in record */
  165685. u8 *abPK, /* Array of primary key flags, or NULL */
  165686. sqlite3_value **apOut /* Write values to this array */
  165687. ){
  165688. int i; /* Used to iterate through columns */
  165689. int rc = SQLITE_OK;
  165690. for(i=0; i<nCol && rc==SQLITE_OK; i++){
  165691. int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
  165692. if( abPK && abPK[i]==0 ) continue;
  165693. rc = sessionInputBuffer(pIn, 9);
  165694. if( rc==SQLITE_OK ){
  165695. eType = pIn->aData[pIn->iNext++];
  165696. }
  165697. assert( apOut[i]==0 );
  165698. if( eType ){
  165699. apOut[i] = sqlite3ValueNew(0);
  165700. if( !apOut[i] ) rc = SQLITE_NOMEM;
  165701. }
  165702. if( rc==SQLITE_OK ){
  165703. u8 *aVal = &pIn->aData[pIn->iNext];
  165704. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  165705. int nByte;
  165706. pIn->iNext += sessionVarintGet(aVal, &nByte);
  165707. rc = sessionInputBuffer(pIn, nByte);
  165708. if( rc==SQLITE_OK ){
  165709. u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
  165710. rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
  165711. }
  165712. pIn->iNext += nByte;
  165713. }
  165714. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  165715. sqlite3_int64 v = sessionGetI64(aVal);
  165716. if( eType==SQLITE_INTEGER ){
  165717. sqlite3VdbeMemSetInt64(apOut[i], v);
  165718. }else{
  165719. double d;
  165720. memcpy(&d, &v, 8);
  165721. sqlite3VdbeMemSetDouble(apOut[i], d);
  165722. }
  165723. pIn->iNext += 8;
  165724. }
  165725. }
  165726. }
  165727. return rc;
  165728. }
  165729. /*
  165730. ** The input pointer currently points to the second byte of a table-header.
  165731. ** Specifically, to the following:
  165732. **
  165733. ** + number of columns in table (varint)
  165734. ** + array of PK flags (1 byte per column),
  165735. ** + table name (nul terminated).
  165736. **
  165737. ** This function ensures that all of the above is present in the input
  165738. ** buffer (i.e. that it can be accessed without any calls to xInput()).
  165739. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  165740. ** The input pointer is not moved.
  165741. */
  165742. static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
  165743. int rc = SQLITE_OK;
  165744. int nCol = 0;
  165745. int nRead = 0;
  165746. rc = sessionInputBuffer(pIn, 9);
  165747. if( rc==SQLITE_OK ){
  165748. nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
  165749. rc = sessionInputBuffer(pIn, nRead+nCol+100);
  165750. nRead += nCol;
  165751. }
  165752. while( rc==SQLITE_OK ){
  165753. while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
  165754. nRead++;
  165755. }
  165756. if( (pIn->iNext + nRead)<pIn->nData ) break;
  165757. rc = sessionInputBuffer(pIn, nRead + 100);
  165758. }
  165759. *pnByte = nRead+1;
  165760. return rc;
  165761. }
  165762. /*
  165763. ** The input pointer currently points to the first byte of the first field
  165764. ** of a record consisting of nCol columns. This function ensures the entire
  165765. ** record is buffered. It does not move the input pointer.
  165766. **
  165767. ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
  165768. ** the record in bytes. Otherwise, an SQLite error code is returned. The
  165769. ** final value of *pnByte is undefined in this case.
  165770. */
  165771. static int sessionChangesetBufferRecord(
  165772. SessionInput *pIn, /* Input data */
  165773. int nCol, /* Number of columns in record */
  165774. int *pnByte /* OUT: Size of record in bytes */
  165775. ){
  165776. int rc = SQLITE_OK;
  165777. int nByte = 0;
  165778. int i;
  165779. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  165780. int eType;
  165781. rc = sessionInputBuffer(pIn, nByte + 10);
  165782. if( rc==SQLITE_OK ){
  165783. eType = pIn->aData[pIn->iNext + nByte++];
  165784. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  165785. int n;
  165786. nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
  165787. nByte += n;
  165788. rc = sessionInputBuffer(pIn, nByte);
  165789. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  165790. nByte += 8;
  165791. }
  165792. }
  165793. }
  165794. *pnByte = nByte;
  165795. return rc;
  165796. }
  165797. /*
  165798. ** The input pointer currently points to the second byte of a table-header.
  165799. ** Specifically, to the following:
  165800. **
  165801. ** + number of columns in table (varint)
  165802. ** + array of PK flags (1 byte per column),
  165803. ** + table name (nul terminated).
  165804. **
  165805. ** This function decodes the table-header and populates the p->nCol,
  165806. ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
  165807. ** also allocated or resized according to the new value of p->nCol. The
  165808. ** input pointer is left pointing to the byte following the table header.
  165809. **
  165810. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
  165811. ** is returned and the final values of the various fields enumerated above
  165812. ** are undefined.
  165813. */
  165814. static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
  165815. int rc;
  165816. int nCopy;
  165817. assert( p->rc==SQLITE_OK );
  165818. rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
  165819. if( rc==SQLITE_OK ){
  165820. int nByte;
  165821. int nVarint;
  165822. nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
  165823. nCopy -= nVarint;
  165824. p->in.iNext += nVarint;
  165825. nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
  165826. p->tblhdr.nBuf = 0;
  165827. sessionBufferGrow(&p->tblhdr, nByte, &rc);
  165828. }
  165829. if( rc==SQLITE_OK ){
  165830. int iPK = sizeof(sqlite3_value*)*p->nCol*2;
  165831. memset(p->tblhdr.aBuf, 0, iPK);
  165832. memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
  165833. p->in.iNext += nCopy;
  165834. }
  165835. p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
  165836. p->abPK = (u8*)&p->apValue[p->nCol*2];
  165837. p->zTab = (char*)&p->abPK[p->nCol];
  165838. return (p->rc = rc);
  165839. }
  165840. /*
  165841. ** Advance the changeset iterator to the next change.
  165842. **
  165843. ** If both paRec and pnRec are NULL, then this function works like the public
  165844. ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
  165845. ** sqlite3changeset_new() and old() APIs may be used to query for values.
  165846. **
  165847. ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
  165848. ** record is written to *paRec before returning and the number of bytes in
  165849. ** the record to *pnRec.
  165850. **
  165851. ** Either way, this function returns SQLITE_ROW if the iterator is
  165852. ** successfully advanced to the next change in the changeset, an SQLite
  165853. ** error code if an error occurs, or SQLITE_DONE if there are no further
  165854. ** changes in the changeset.
  165855. */
  165856. static int sessionChangesetNext(
  165857. sqlite3_changeset_iter *p, /* Changeset iterator */
  165858. u8 **paRec, /* If non-NULL, store record pointer here */
  165859. int *pnRec /* If non-NULL, store size of record here */
  165860. ){
  165861. int i;
  165862. u8 op;
  165863. assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
  165864. /* If the iterator is in the error-state, return immediately. */
  165865. if( p->rc!=SQLITE_OK ) return p->rc;
  165866. /* Free the current contents of p->apValue[], if any. */
  165867. if( p->apValue ){
  165868. for(i=0; i<p->nCol*2; i++){
  165869. sqlite3ValueFree(p->apValue[i]);
  165870. }
  165871. memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
  165872. }
  165873. /* Make sure the buffer contains at least 10 bytes of input data, or all
  165874. ** remaining data if there are less than 10 bytes available. This is
  165875. ** sufficient either for the 'T' or 'P' byte and the varint that follows
  165876. ** it, or for the two single byte values otherwise. */
  165877. p->rc = sessionInputBuffer(&p->in, 2);
  165878. if( p->rc!=SQLITE_OK ) return p->rc;
  165879. /* If the iterator is already at the end of the changeset, return DONE. */
  165880. if( p->in.iNext>=p->in.nData ){
  165881. return SQLITE_DONE;
  165882. }
  165883. sessionDiscardData(&p->in);
  165884. p->in.iCurrent = p->in.iNext;
  165885. op = p->in.aData[p->in.iNext++];
  165886. if( op=='T' || op=='P' ){
  165887. p->bPatchset = (op=='P');
  165888. if( sessionChangesetReadTblhdr(p) ) return p->rc;
  165889. if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
  165890. p->in.iCurrent = p->in.iNext;
  165891. op = p->in.aData[p->in.iNext++];
  165892. }
  165893. p->op = op;
  165894. p->bIndirect = p->in.aData[p->in.iNext++];
  165895. if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
  165896. return (p->rc = SQLITE_CORRUPT_BKPT);
  165897. }
  165898. if( paRec ){
  165899. int nVal; /* Number of values to buffer */
  165900. if( p->bPatchset==0 && op==SQLITE_UPDATE ){
  165901. nVal = p->nCol * 2;
  165902. }else if( p->bPatchset && op==SQLITE_DELETE ){
  165903. nVal = 0;
  165904. for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
  165905. }else{
  165906. nVal = p->nCol;
  165907. }
  165908. p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
  165909. if( p->rc!=SQLITE_OK ) return p->rc;
  165910. *paRec = &p->in.aData[p->in.iNext];
  165911. p->in.iNext += *pnRec;
  165912. }else{
  165913. /* If this is an UPDATE or DELETE, read the old.* record. */
  165914. if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
  165915. u8 *abPK = p->bPatchset ? p->abPK : 0;
  165916. p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
  165917. if( p->rc!=SQLITE_OK ) return p->rc;
  165918. }
  165919. /* If this is an INSERT or UPDATE, read the new.* record. */
  165920. if( p->op!=SQLITE_DELETE ){
  165921. p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
  165922. if( p->rc!=SQLITE_OK ) return p->rc;
  165923. }
  165924. if( p->bPatchset && p->op==SQLITE_UPDATE ){
  165925. /* If this is an UPDATE that is part of a patchset, then all PK and
  165926. ** modified fields are present in the new.* record. The old.* record
  165927. ** is currently completely empty. This block shifts the PK fields from
  165928. ** new.* to old.*, to accommodate the code that reads these arrays. */
  165929. for(i=0; i<p->nCol; i++){
  165930. assert( p->apValue[i]==0 );
  165931. assert( p->abPK[i]==0 || p->apValue[i+p->nCol] );
  165932. if( p->abPK[i] ){
  165933. p->apValue[i] = p->apValue[i+p->nCol];
  165934. p->apValue[i+p->nCol] = 0;
  165935. }
  165936. }
  165937. }
  165938. }
  165939. return SQLITE_ROW;
  165940. }
  165941. /*
  165942. ** Advance an iterator created by sqlite3changeset_start() to the next
  165943. ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
  165944. ** or SQLITE_CORRUPT.
  165945. **
  165946. ** This function may not be called on iterators passed to a conflict handler
  165947. ** callback by changeset_apply().
  165948. */
  165949. SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
  165950. return sessionChangesetNext(p, 0, 0);
  165951. }
  165952. /*
  165953. ** The following function extracts information on the current change
  165954. ** from a changeset iterator. It may only be called after changeset_next()
  165955. ** has returned SQLITE_ROW.
  165956. */
  165957. SQLITE_API int sqlite3changeset_op(
  165958. sqlite3_changeset_iter *pIter, /* Iterator handle */
  165959. const char **pzTab, /* OUT: Pointer to table name */
  165960. int *pnCol, /* OUT: Number of columns in table */
  165961. int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
  165962. int *pbIndirect /* OUT: True if change is indirect */
  165963. ){
  165964. *pOp = pIter->op;
  165965. *pnCol = pIter->nCol;
  165966. *pzTab = pIter->zTab;
  165967. if( pbIndirect ) *pbIndirect = pIter->bIndirect;
  165968. return SQLITE_OK;
  165969. }
  165970. /*
  165971. ** Return information regarding the PRIMARY KEY and number of columns in
  165972. ** the database table affected by the change that pIter currently points
  165973. ** to. This function may only be called after changeset_next() returns
  165974. ** SQLITE_ROW.
  165975. */
  165976. SQLITE_API int sqlite3changeset_pk(
  165977. sqlite3_changeset_iter *pIter, /* Iterator object */
  165978. unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
  165979. int *pnCol /* OUT: Number of entries in output array */
  165980. ){
  165981. *pabPK = pIter->abPK;
  165982. if( pnCol ) *pnCol = pIter->nCol;
  165983. return SQLITE_OK;
  165984. }
  165985. /*
  165986. ** This function may only be called while the iterator is pointing to an
  165987. ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
  165988. ** Otherwise, SQLITE_MISUSE is returned.
  165989. **
  165990. ** It sets *ppValue to point to an sqlite3_value structure containing the
  165991. ** iVal'th value in the old.* record. Or, if that particular value is not
  165992. ** included in the record (because the change is an UPDATE and the field
  165993. ** was not modified and is not a PK column), set *ppValue to NULL.
  165994. **
  165995. ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
  165996. ** not modified. Otherwise, SQLITE_OK.
  165997. */
  165998. SQLITE_API int sqlite3changeset_old(
  165999. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  166000. int iVal, /* Index of old.* value to retrieve */
  166001. sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
  166002. ){
  166003. if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
  166004. return SQLITE_MISUSE;
  166005. }
  166006. if( iVal<0 || iVal>=pIter->nCol ){
  166007. return SQLITE_RANGE;
  166008. }
  166009. *ppValue = pIter->apValue[iVal];
  166010. return SQLITE_OK;
  166011. }
  166012. /*
  166013. ** This function may only be called while the iterator is pointing to an
  166014. ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
  166015. ** Otherwise, SQLITE_MISUSE is returned.
  166016. **
  166017. ** It sets *ppValue to point to an sqlite3_value structure containing the
  166018. ** iVal'th value in the new.* record. Or, if that particular value is not
  166019. ** included in the record (because the change is an UPDATE and the field
  166020. ** was not modified), set *ppValue to NULL.
  166021. **
  166022. ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
  166023. ** not modified. Otherwise, SQLITE_OK.
  166024. */
  166025. SQLITE_API int sqlite3changeset_new(
  166026. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  166027. int iVal, /* Index of new.* value to retrieve */
  166028. sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
  166029. ){
  166030. if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
  166031. return SQLITE_MISUSE;
  166032. }
  166033. if( iVal<0 || iVal>=pIter->nCol ){
  166034. return SQLITE_RANGE;
  166035. }
  166036. *ppValue = pIter->apValue[pIter->nCol+iVal];
  166037. return SQLITE_OK;
  166038. }
  166039. /*
  166040. ** The following two macros are used internally. They are similar to the
  166041. ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
  166042. ** they omit all error checking and return a pointer to the requested value.
  166043. */
  166044. #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
  166045. #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
  166046. /*
  166047. ** This function may only be called with a changeset iterator that has been
  166048. ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
  166049. ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
  166050. **
  166051. ** If successful, *ppValue is set to point to an sqlite3_value structure
  166052. ** containing the iVal'th value of the conflicting record.
  166053. **
  166054. ** If value iVal is out-of-range or some other error occurs, an SQLite error
  166055. ** code is returned. Otherwise, SQLITE_OK.
  166056. */
  166057. SQLITE_API int sqlite3changeset_conflict(
  166058. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  166059. int iVal, /* Index of conflict record value to fetch */
  166060. sqlite3_value **ppValue /* OUT: Value from conflicting row */
  166061. ){
  166062. if( !pIter->pConflict ){
  166063. return SQLITE_MISUSE;
  166064. }
  166065. if( iVal<0 || iVal>=pIter->nCol ){
  166066. return SQLITE_RANGE;
  166067. }
  166068. *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
  166069. return SQLITE_OK;
  166070. }
  166071. /*
  166072. ** This function may only be called with an iterator passed to an
  166073. ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
  166074. ** it sets the output variable to the total number of known foreign key
  166075. ** violations in the destination database and returns SQLITE_OK.
  166076. **
  166077. ** In all other cases this function returns SQLITE_MISUSE.
  166078. */
  166079. SQLITE_API int sqlite3changeset_fk_conflicts(
  166080. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  166081. int *pnOut /* OUT: Number of FK violations */
  166082. ){
  166083. if( pIter->pConflict || pIter->apValue ){
  166084. return SQLITE_MISUSE;
  166085. }
  166086. *pnOut = pIter->nCol;
  166087. return SQLITE_OK;
  166088. }
  166089. /*
  166090. ** Finalize an iterator allocated with sqlite3changeset_start().
  166091. **
  166092. ** This function may not be called on iterators passed to a conflict handler
  166093. ** callback by changeset_apply().
  166094. */
  166095. SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
  166096. int rc = SQLITE_OK;
  166097. if( p ){
  166098. int i; /* Used to iterate through p->apValue[] */
  166099. rc = p->rc;
  166100. if( p->apValue ){
  166101. for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
  166102. }
  166103. sqlite3_free(p->tblhdr.aBuf);
  166104. sqlite3_free(p->in.buf.aBuf);
  166105. sqlite3_free(p);
  166106. }
  166107. return rc;
  166108. }
  166109. static int sessionChangesetInvert(
  166110. SessionInput *pInput, /* Input changeset */
  166111. int (*xOutput)(void *pOut, const void *pData, int nData),
  166112. void *pOut,
  166113. int *pnInverted, /* OUT: Number of bytes in output changeset */
  166114. void **ppInverted /* OUT: Inverse of pChangeset */
  166115. ){
  166116. int rc = SQLITE_OK; /* Return value */
  166117. SessionBuffer sOut; /* Output buffer */
  166118. int nCol = 0; /* Number of cols in current table */
  166119. u8 *abPK = 0; /* PK array for current table */
  166120. sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
  166121. SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
  166122. /* Initialize the output buffer */
  166123. memset(&sOut, 0, sizeof(SessionBuffer));
  166124. /* Zero the output variables in case an error occurs. */
  166125. if( ppInverted ){
  166126. *ppInverted = 0;
  166127. *pnInverted = 0;
  166128. }
  166129. while( 1 ){
  166130. u8 eType;
  166131. /* Test for EOF. */
  166132. if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
  166133. if( pInput->iNext>=pInput->nData ) break;
  166134. eType = pInput->aData[pInput->iNext];
  166135. switch( eType ){
  166136. case 'T': {
  166137. /* A 'table' record consists of:
  166138. **
  166139. ** * A constant 'T' character,
  166140. ** * Number of columns in said table (a varint),
  166141. ** * An array of nCol bytes (sPK),
  166142. ** * A nul-terminated table name.
  166143. */
  166144. int nByte;
  166145. int nVar;
  166146. pInput->iNext++;
  166147. if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
  166148. goto finished_invert;
  166149. }
  166150. nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
  166151. sPK.nBuf = 0;
  166152. sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
  166153. sessionAppendByte(&sOut, eType, &rc);
  166154. sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
  166155. if( rc ) goto finished_invert;
  166156. pInput->iNext += nByte;
  166157. sqlite3_free(apVal);
  166158. apVal = 0;
  166159. abPK = sPK.aBuf;
  166160. break;
  166161. }
  166162. case SQLITE_INSERT:
  166163. case SQLITE_DELETE: {
  166164. int nByte;
  166165. int bIndirect = pInput->aData[pInput->iNext+1];
  166166. int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
  166167. pInput->iNext += 2;
  166168. assert( rc==SQLITE_OK );
  166169. rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
  166170. sessionAppendByte(&sOut, eType2, &rc);
  166171. sessionAppendByte(&sOut, bIndirect, &rc);
  166172. sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
  166173. pInput->iNext += nByte;
  166174. if( rc ) goto finished_invert;
  166175. break;
  166176. }
  166177. case SQLITE_UPDATE: {
  166178. int iCol;
  166179. if( 0==apVal ){
  166180. apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
  166181. if( 0==apVal ){
  166182. rc = SQLITE_NOMEM;
  166183. goto finished_invert;
  166184. }
  166185. memset(apVal, 0, sizeof(apVal[0])*nCol*2);
  166186. }
  166187. /* Write the header for the new UPDATE change. Same as the original. */
  166188. sessionAppendByte(&sOut, eType, &rc);
  166189. sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
  166190. /* Read the old.* and new.* records for the update change. */
  166191. pInput->iNext += 2;
  166192. rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
  166193. if( rc==SQLITE_OK ){
  166194. rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
  166195. }
  166196. /* Write the new old.* record. Consists of the PK columns from the
  166197. ** original old.* record, and the other values from the original
  166198. ** new.* record. */
  166199. for(iCol=0; iCol<nCol; iCol++){
  166200. sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
  166201. sessionAppendValue(&sOut, pVal, &rc);
  166202. }
  166203. /* Write the new new.* record. Consists of a copy of all values
  166204. ** from the original old.* record, except for the PK columns, which
  166205. ** are set to "undefined". */
  166206. for(iCol=0; iCol<nCol; iCol++){
  166207. sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
  166208. sessionAppendValue(&sOut, pVal, &rc);
  166209. }
  166210. for(iCol=0; iCol<nCol*2; iCol++){
  166211. sqlite3ValueFree(apVal[iCol]);
  166212. }
  166213. memset(apVal, 0, sizeof(apVal[0])*nCol*2);
  166214. if( rc!=SQLITE_OK ){
  166215. goto finished_invert;
  166216. }
  166217. break;
  166218. }
  166219. default:
  166220. rc = SQLITE_CORRUPT_BKPT;
  166221. goto finished_invert;
  166222. }
  166223. assert( rc==SQLITE_OK );
  166224. if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
  166225. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  166226. sOut.nBuf = 0;
  166227. if( rc!=SQLITE_OK ) goto finished_invert;
  166228. }
  166229. }
  166230. assert( rc==SQLITE_OK );
  166231. if( pnInverted ){
  166232. *pnInverted = sOut.nBuf;
  166233. *ppInverted = sOut.aBuf;
  166234. sOut.aBuf = 0;
  166235. }else if( sOut.nBuf>0 ){
  166236. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  166237. }
  166238. finished_invert:
  166239. sqlite3_free(sOut.aBuf);
  166240. sqlite3_free(apVal);
  166241. sqlite3_free(sPK.aBuf);
  166242. return rc;
  166243. }
  166244. /*
  166245. ** Invert a changeset object.
  166246. */
  166247. SQLITE_API int sqlite3changeset_invert(
  166248. int nChangeset, /* Number of bytes in input */
  166249. const void *pChangeset, /* Input changeset */
  166250. int *pnInverted, /* OUT: Number of bytes in output changeset */
  166251. void **ppInverted /* OUT: Inverse of pChangeset */
  166252. ){
  166253. SessionInput sInput;
  166254. /* Set up the input stream */
  166255. memset(&sInput, 0, sizeof(SessionInput));
  166256. sInput.nData = nChangeset;
  166257. sInput.aData = (u8*)pChangeset;
  166258. return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
  166259. }
  166260. /*
  166261. ** Streaming version of sqlite3changeset_invert().
  166262. */
  166263. SQLITE_API int sqlite3changeset_invert_strm(
  166264. int (*xInput)(void *pIn, void *pData, int *pnData),
  166265. void *pIn,
  166266. int (*xOutput)(void *pOut, const void *pData, int nData),
  166267. void *pOut
  166268. ){
  166269. SessionInput sInput;
  166270. int rc;
  166271. /* Set up the input stream */
  166272. memset(&sInput, 0, sizeof(SessionInput));
  166273. sInput.xInput = xInput;
  166274. sInput.pIn = pIn;
  166275. rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
  166276. sqlite3_free(sInput.buf.aBuf);
  166277. return rc;
  166278. }
  166279. typedef struct SessionApplyCtx SessionApplyCtx;
  166280. struct SessionApplyCtx {
  166281. sqlite3 *db;
  166282. sqlite3_stmt *pDelete; /* DELETE statement */
  166283. sqlite3_stmt *pUpdate; /* UPDATE statement */
  166284. sqlite3_stmt *pInsert; /* INSERT statement */
  166285. sqlite3_stmt *pSelect; /* SELECT statement */
  166286. int nCol; /* Size of azCol[] and abPK[] arrays */
  166287. const char **azCol; /* Array of column names */
  166288. u8 *abPK; /* Boolean array - true if column is in PK */
  166289. int bDeferConstraints; /* True to defer constraints */
  166290. SessionBuffer constraints; /* Deferred constraints are stored here */
  166291. };
  166292. /*
  166293. ** Formulate a statement to DELETE a row from database db. Assuming a table
  166294. ** structure like this:
  166295. **
  166296. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  166297. **
  166298. ** The DELETE statement looks like this:
  166299. **
  166300. ** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
  166301. **
  166302. ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
  166303. ** matching b and d values, or 1 otherwise. The second case comes up if the
  166304. ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
  166305. **
  166306. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
  166307. ** pointing to the prepared version of the SQL statement.
  166308. */
  166309. static int sessionDeleteRow(
  166310. sqlite3 *db, /* Database handle */
  166311. const char *zTab, /* Table name */
  166312. SessionApplyCtx *p /* Session changeset-apply context */
  166313. ){
  166314. int i;
  166315. const char *zSep = "";
  166316. int rc = SQLITE_OK;
  166317. SessionBuffer buf = {0, 0, 0};
  166318. int nPk = 0;
  166319. sessionAppendStr(&buf, "DELETE FROM ", &rc);
  166320. sessionAppendIdent(&buf, zTab, &rc);
  166321. sessionAppendStr(&buf, " WHERE ", &rc);
  166322. for(i=0; i<p->nCol; i++){
  166323. if( p->abPK[i] ){
  166324. nPk++;
  166325. sessionAppendStr(&buf, zSep, &rc);
  166326. sessionAppendIdent(&buf, p->azCol[i], &rc);
  166327. sessionAppendStr(&buf, " = ?", &rc);
  166328. sessionAppendInteger(&buf, i+1, &rc);
  166329. zSep = " AND ";
  166330. }
  166331. }
  166332. if( nPk<p->nCol ){
  166333. sessionAppendStr(&buf, " AND (?", &rc);
  166334. sessionAppendInteger(&buf, p->nCol+1, &rc);
  166335. sessionAppendStr(&buf, " OR ", &rc);
  166336. zSep = "";
  166337. for(i=0; i<p->nCol; i++){
  166338. if( !p->abPK[i] ){
  166339. sessionAppendStr(&buf, zSep, &rc);
  166340. sessionAppendIdent(&buf, p->azCol[i], &rc);
  166341. sessionAppendStr(&buf, " IS ?", &rc);
  166342. sessionAppendInteger(&buf, i+1, &rc);
  166343. zSep = "AND ";
  166344. }
  166345. }
  166346. sessionAppendStr(&buf, ")", &rc);
  166347. }
  166348. if( rc==SQLITE_OK ){
  166349. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
  166350. }
  166351. sqlite3_free(buf.aBuf);
  166352. return rc;
  166353. }
  166354. /*
  166355. ** Formulate and prepare a statement to UPDATE a row from database db.
  166356. ** Assuming a table structure like this:
  166357. **
  166358. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  166359. **
  166360. ** The UPDATE statement looks like this:
  166361. **
  166362. ** UPDATE x SET
  166363. ** a = CASE WHEN ?2 THEN ?3 ELSE a END,
  166364. ** b = CASE WHEN ?5 THEN ?6 ELSE b END,
  166365. ** c = CASE WHEN ?8 THEN ?9 ELSE c END,
  166366. ** d = CASE WHEN ?11 THEN ?12 ELSE d END
  166367. ** WHERE a = ?1 AND c = ?7 AND (?13 OR
  166368. ** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
  166369. ** )
  166370. **
  166371. ** For each column in the table, there are three variables to bind:
  166372. **
  166373. ** ?(i*3+1) The old.* value of the column, if any.
  166374. ** ?(i*3+2) A boolean flag indicating that the value is being modified.
  166375. ** ?(i*3+3) The new.* value of the column, if any.
  166376. **
  166377. ** Also, a boolean flag that, if set to true, causes the statement to update
  166378. ** a row even if the non-PK values do not match. This is required if the
  166379. ** conflict-handler is invoked with CHANGESET_DATA and returns
  166380. ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
  166381. **
  166382. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
  166383. ** pointing to the prepared version of the SQL statement.
  166384. */
  166385. static int sessionUpdateRow(
  166386. sqlite3 *db, /* Database handle */
  166387. const char *zTab, /* Table name */
  166388. SessionApplyCtx *p /* Session changeset-apply context */
  166389. ){
  166390. int rc = SQLITE_OK;
  166391. int i;
  166392. const char *zSep = "";
  166393. SessionBuffer buf = {0, 0, 0};
  166394. /* Append "UPDATE tbl SET " */
  166395. sessionAppendStr(&buf, "UPDATE ", &rc);
  166396. sessionAppendIdent(&buf, zTab, &rc);
  166397. sessionAppendStr(&buf, " SET ", &rc);
  166398. /* Append the assignments */
  166399. for(i=0; i<p->nCol; i++){
  166400. sessionAppendStr(&buf, zSep, &rc);
  166401. sessionAppendIdent(&buf, p->azCol[i], &rc);
  166402. sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
  166403. sessionAppendInteger(&buf, i*3+2, &rc);
  166404. sessionAppendStr(&buf, " THEN ?", &rc);
  166405. sessionAppendInteger(&buf, i*3+3, &rc);
  166406. sessionAppendStr(&buf, " ELSE ", &rc);
  166407. sessionAppendIdent(&buf, p->azCol[i], &rc);
  166408. sessionAppendStr(&buf, " END", &rc);
  166409. zSep = ", ";
  166410. }
  166411. /* Append the PK part of the WHERE clause */
  166412. sessionAppendStr(&buf, " WHERE ", &rc);
  166413. for(i=0; i<p->nCol; i++){
  166414. if( p->abPK[i] ){
  166415. sessionAppendIdent(&buf, p->azCol[i], &rc);
  166416. sessionAppendStr(&buf, " = ?", &rc);
  166417. sessionAppendInteger(&buf, i*3+1, &rc);
  166418. sessionAppendStr(&buf, " AND ", &rc);
  166419. }
  166420. }
  166421. /* Append the non-PK part of the WHERE clause */
  166422. sessionAppendStr(&buf, " (?", &rc);
  166423. sessionAppendInteger(&buf, p->nCol*3+1, &rc);
  166424. sessionAppendStr(&buf, " OR 1", &rc);
  166425. for(i=0; i<p->nCol; i++){
  166426. if( !p->abPK[i] ){
  166427. sessionAppendStr(&buf, " AND (?", &rc);
  166428. sessionAppendInteger(&buf, i*3+2, &rc);
  166429. sessionAppendStr(&buf, "=0 OR ", &rc);
  166430. sessionAppendIdent(&buf, p->azCol[i], &rc);
  166431. sessionAppendStr(&buf, " IS ?", &rc);
  166432. sessionAppendInteger(&buf, i*3+1, &rc);
  166433. sessionAppendStr(&buf, ")", &rc);
  166434. }
  166435. }
  166436. sessionAppendStr(&buf, ")", &rc);
  166437. if( rc==SQLITE_OK ){
  166438. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
  166439. }
  166440. sqlite3_free(buf.aBuf);
  166441. return rc;
  166442. }
  166443. /*
  166444. ** Formulate and prepare an SQL statement to query table zTab by primary
  166445. ** key. Assuming the following table structure:
  166446. **
  166447. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  166448. **
  166449. ** The SELECT statement looks like this:
  166450. **
  166451. ** SELECT * FROM x WHERE a = ?1 AND c = ?3
  166452. **
  166453. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
  166454. ** pointing to the prepared version of the SQL statement.
  166455. */
  166456. static int sessionSelectRow(
  166457. sqlite3 *db, /* Database handle */
  166458. const char *zTab, /* Table name */
  166459. SessionApplyCtx *p /* Session changeset-apply context */
  166460. ){
  166461. return sessionSelectStmt(
  166462. db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
  166463. }
  166464. /*
  166465. ** Formulate and prepare an INSERT statement to add a record to table zTab.
  166466. ** For example:
  166467. **
  166468. ** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
  166469. **
  166470. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
  166471. ** pointing to the prepared version of the SQL statement.
  166472. */
  166473. static int sessionInsertRow(
  166474. sqlite3 *db, /* Database handle */
  166475. const char *zTab, /* Table name */
  166476. SessionApplyCtx *p /* Session changeset-apply context */
  166477. ){
  166478. int rc = SQLITE_OK;
  166479. int i;
  166480. SessionBuffer buf = {0, 0, 0};
  166481. sessionAppendStr(&buf, "INSERT INTO main.", &rc);
  166482. sessionAppendIdent(&buf, zTab, &rc);
  166483. sessionAppendStr(&buf, "(", &rc);
  166484. for(i=0; i<p->nCol; i++){
  166485. if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
  166486. sessionAppendIdent(&buf, p->azCol[i], &rc);
  166487. }
  166488. sessionAppendStr(&buf, ") VALUES(?", &rc);
  166489. for(i=1; i<p->nCol; i++){
  166490. sessionAppendStr(&buf, ", ?", &rc);
  166491. }
  166492. sessionAppendStr(&buf, ")", &rc);
  166493. if( rc==SQLITE_OK ){
  166494. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
  166495. }
  166496. sqlite3_free(buf.aBuf);
  166497. return rc;
  166498. }
  166499. /*
  166500. ** A wrapper around sqlite3_bind_value() that detects an extra problem.
  166501. ** See comments in the body of this function for details.
  166502. */
  166503. static int sessionBindValue(
  166504. sqlite3_stmt *pStmt, /* Statement to bind value to */
  166505. int i, /* Parameter number to bind to */
  166506. sqlite3_value *pVal /* Value to bind */
  166507. ){
  166508. int eType = sqlite3_value_type(pVal);
  166509. /* COVERAGE: The (pVal->z==0) branch is never true using current versions
  166510. ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
  166511. ** the (pVal->z) variable remains as it was or the type of the value is
  166512. ** set to SQLITE_NULL. */
  166513. if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
  166514. /* This condition occurs when an earlier OOM in a call to
  166515. ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
  166516. ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
  166517. return SQLITE_NOMEM;
  166518. }
  166519. return sqlite3_bind_value(pStmt, i, pVal);
  166520. }
  166521. /*
  166522. ** Iterator pIter must point to an SQLITE_INSERT entry. This function
  166523. ** transfers new.* values from the current iterator entry to statement
  166524. ** pStmt. The table being inserted into has nCol columns.
  166525. **
  166526. ** New.* value $i from the iterator is bound to variable ($i+1) of
  166527. ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
  166528. ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
  166529. ** to an array nCol elements in size. In this case only those values for
  166530. ** which abPK[$i] is true are read from the iterator and bound to the
  166531. ** statement.
  166532. **
  166533. ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
  166534. */
  166535. static int sessionBindRow(
  166536. sqlite3_changeset_iter *pIter, /* Iterator to read values from */
  166537. int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
  166538. int nCol, /* Number of columns */
  166539. u8 *abPK, /* If not NULL, bind only if true */
  166540. sqlite3_stmt *pStmt /* Bind values to this statement */
  166541. ){
  166542. int i;
  166543. int rc = SQLITE_OK;
  166544. /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
  166545. ** argument iterator points to a suitable entry. Make sure that xValue
  166546. ** is one of these to guarantee that it is safe to ignore the return
  166547. ** in the code below. */
  166548. assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
  166549. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  166550. if( !abPK || abPK[i] ){
  166551. sqlite3_value *pVal;
  166552. (void)xValue(pIter, i, &pVal);
  166553. rc = sessionBindValue(pStmt, i+1, pVal);
  166554. }
  166555. }
  166556. return rc;
  166557. }
  166558. /*
  166559. ** SQL statement pSelect is as generated by the sessionSelectRow() function.
  166560. ** This function binds the primary key values from the change that changeset
  166561. ** iterator pIter points to to the SELECT and attempts to seek to the table
  166562. ** entry. If a row is found, the SELECT statement left pointing at the row
  166563. ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
  166564. ** has occured, the statement is reset and SQLITE_OK is returned. If an
  166565. ** error occurs, the statement is reset and an SQLite error code is returned.
  166566. **
  166567. ** If this function returns SQLITE_ROW, the caller must eventually reset()
  166568. ** statement pSelect. If any other value is returned, the statement does
  166569. ** not require a reset().
  166570. **
  166571. ** If the iterator currently points to an INSERT record, bind values from the
  166572. ** new.* record to the SELECT statement. Or, if it points to a DELETE or
  166573. ** UPDATE, bind values from the old.* record.
  166574. */
  166575. static int sessionSeekToRow(
  166576. sqlite3 *db, /* Database handle */
  166577. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  166578. u8 *abPK, /* Primary key flags array */
  166579. sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
  166580. ){
  166581. int rc; /* Return code */
  166582. int nCol; /* Number of columns in table */
  166583. int op; /* Changset operation (SQLITE_UPDATE etc.) */
  166584. const char *zDummy; /* Unused */
  166585. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  166586. rc = sessionBindRow(pIter,
  166587. op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
  166588. nCol, abPK, pSelect
  166589. );
  166590. if( rc==SQLITE_OK ){
  166591. rc = sqlite3_step(pSelect);
  166592. if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
  166593. }
  166594. return rc;
  166595. }
  166596. /*
  166597. ** Invoke the conflict handler for the change that the changeset iterator
  166598. ** currently points to.
  166599. **
  166600. ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
  166601. ** If argument pbReplace is NULL, then the type of conflict handler invoked
  166602. ** depends solely on eType, as follows:
  166603. **
  166604. ** eType value Value passed to xConflict
  166605. ** -------------------------------------------------
  166606. ** CHANGESET_DATA CHANGESET_NOTFOUND
  166607. ** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
  166608. **
  166609. ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
  166610. ** record with the same primary key as the record about to be deleted, updated
  166611. ** or inserted. If such a record can be found, it is available to the conflict
  166612. ** handler as the "conflicting" record. In this case the type of conflict
  166613. ** handler invoked is as follows:
  166614. **
  166615. ** eType value PK Record found? Value passed to xConflict
  166616. ** ----------------------------------------------------------------
  166617. ** CHANGESET_DATA Yes CHANGESET_DATA
  166618. ** CHANGESET_DATA No CHANGESET_NOTFOUND
  166619. ** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
  166620. ** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
  166621. **
  166622. ** If pbReplace is not NULL, and a record with a matching PK is found, and
  166623. ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
  166624. ** is set to non-zero before returning SQLITE_OK.
  166625. **
  166626. ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
  166627. ** returned. Or, if the conflict handler returns an invalid value,
  166628. ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
  166629. ** this function returns SQLITE_OK.
  166630. */
  166631. static int sessionConflictHandler(
  166632. int eType, /* Either CHANGESET_DATA or CONFLICT */
  166633. SessionApplyCtx *p, /* changeset_apply() context */
  166634. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  166635. int(*xConflict)(void *, int, sqlite3_changeset_iter*),
  166636. void *pCtx, /* First argument for conflict handler */
  166637. int *pbReplace /* OUT: Set to true if PK row is found */
  166638. ){
  166639. int res = 0; /* Value returned by conflict handler */
  166640. int rc;
  166641. int nCol;
  166642. int op;
  166643. const char *zDummy;
  166644. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  166645. assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
  166646. assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
  166647. assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
  166648. /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
  166649. if( pbReplace ){
  166650. rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
  166651. }else{
  166652. rc = SQLITE_OK;
  166653. }
  166654. if( rc==SQLITE_ROW ){
  166655. /* There exists another row with the new.* primary key. */
  166656. pIter->pConflict = p->pSelect;
  166657. res = xConflict(pCtx, eType, pIter);
  166658. pIter->pConflict = 0;
  166659. rc = sqlite3_reset(p->pSelect);
  166660. }else if( rc==SQLITE_OK ){
  166661. if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
  166662. /* Instead of invoking the conflict handler, append the change blob
  166663. ** to the SessionApplyCtx.constraints buffer. */
  166664. u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
  166665. int nBlob = pIter->in.iNext - pIter->in.iCurrent;
  166666. sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
  166667. res = SQLITE_CHANGESET_OMIT;
  166668. }else{
  166669. /* No other row with the new.* primary key. */
  166670. res = xConflict(pCtx, eType+1, pIter);
  166671. if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
  166672. }
  166673. }
  166674. if( rc==SQLITE_OK ){
  166675. switch( res ){
  166676. case SQLITE_CHANGESET_REPLACE:
  166677. assert( pbReplace );
  166678. *pbReplace = 1;
  166679. break;
  166680. case SQLITE_CHANGESET_OMIT:
  166681. break;
  166682. case SQLITE_CHANGESET_ABORT:
  166683. rc = SQLITE_ABORT;
  166684. break;
  166685. default:
  166686. rc = SQLITE_MISUSE;
  166687. break;
  166688. }
  166689. }
  166690. return rc;
  166691. }
  166692. /*
  166693. ** Attempt to apply the change that the iterator passed as the first argument
  166694. ** currently points to to the database. If a conflict is encountered, invoke
  166695. ** the conflict handler callback.
  166696. **
  166697. ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
  166698. ** one is encountered, update or delete the row with the matching primary key
  166699. ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
  166700. ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
  166701. ** to true before returning. In this case the caller will invoke this function
  166702. ** again, this time with pbRetry set to NULL.
  166703. **
  166704. ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
  166705. ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
  166706. ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
  166707. ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
  166708. ** before retrying. In this case the caller attempts to remove the conflicting
  166709. ** row before invoking this function again, this time with pbReplace set
  166710. ** to NULL.
  166711. **
  166712. ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
  166713. ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
  166714. ** returned.
  166715. */
  166716. static int sessionApplyOneOp(
  166717. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  166718. SessionApplyCtx *p, /* changeset_apply() context */
  166719. int(*xConflict)(void *, int, sqlite3_changeset_iter *),
  166720. void *pCtx, /* First argument for the conflict handler */
  166721. int *pbReplace, /* OUT: True to remove PK row and retry */
  166722. int *pbRetry /* OUT: True to retry. */
  166723. ){
  166724. const char *zDummy;
  166725. int op;
  166726. int nCol;
  166727. int rc = SQLITE_OK;
  166728. assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
  166729. assert( p->azCol && p->abPK );
  166730. assert( !pbReplace || *pbReplace==0 );
  166731. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  166732. if( op==SQLITE_DELETE ){
  166733. /* Bind values to the DELETE statement. If conflict handling is required,
  166734. ** bind values for all columns and set bound variable (nCol+1) to true.
  166735. ** Or, if conflict handling is not required, bind just the PK column
  166736. ** values and, if it exists, set (nCol+1) to false. Conflict handling
  166737. ** is not required if:
  166738. **
  166739. ** * this is a patchset, or
  166740. ** * (pbRetry==0), or
  166741. ** * all columns of the table are PK columns (in this case there is
  166742. ** no (nCol+1) variable to bind to).
  166743. */
  166744. u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
  166745. rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
  166746. if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
  166747. rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
  166748. }
  166749. if( rc!=SQLITE_OK ) return rc;
  166750. sqlite3_step(p->pDelete);
  166751. rc = sqlite3_reset(p->pDelete);
  166752. if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
  166753. rc = sessionConflictHandler(
  166754. SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
  166755. );
  166756. }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
  166757. rc = sessionConflictHandler(
  166758. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
  166759. );
  166760. }
  166761. }else if( op==SQLITE_UPDATE ){
  166762. int i;
  166763. /* Bind values to the UPDATE statement. */
  166764. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  166765. sqlite3_value *pOld = sessionChangesetOld(pIter, i);
  166766. sqlite3_value *pNew = sessionChangesetNew(pIter, i);
  166767. sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
  166768. if( pOld ){
  166769. rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
  166770. }
  166771. if( rc==SQLITE_OK && pNew ){
  166772. rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
  166773. }
  166774. }
  166775. if( rc==SQLITE_OK ){
  166776. sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
  166777. }
  166778. if( rc!=SQLITE_OK ) return rc;
  166779. /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
  166780. ** the result will be SQLITE_OK with 0 rows modified. */
  166781. sqlite3_step(p->pUpdate);
  166782. rc = sqlite3_reset(p->pUpdate);
  166783. if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
  166784. /* A NOTFOUND or DATA error. Search the table to see if it contains
  166785. ** a row with a matching primary key. If so, this is a DATA conflict.
  166786. ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
  166787. rc = sessionConflictHandler(
  166788. SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
  166789. );
  166790. }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
  166791. /* This is always a CONSTRAINT conflict. */
  166792. rc = sessionConflictHandler(
  166793. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
  166794. );
  166795. }
  166796. }else{
  166797. assert( op==SQLITE_INSERT );
  166798. rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
  166799. if( rc!=SQLITE_OK ) return rc;
  166800. sqlite3_step(p->pInsert);
  166801. rc = sqlite3_reset(p->pInsert);
  166802. if( (rc&0xff)==SQLITE_CONSTRAINT ){
  166803. rc = sessionConflictHandler(
  166804. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
  166805. );
  166806. }
  166807. }
  166808. return rc;
  166809. }
  166810. /*
  166811. ** Attempt to apply the change that the iterator passed as the first argument
  166812. ** currently points to to the database. If a conflict is encountered, invoke
  166813. ** the conflict handler callback.
  166814. **
  166815. ** The difference between this function and sessionApplyOne() is that this
  166816. ** function handles the case where the conflict-handler is invoked and
  166817. ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
  166818. ** retried in some manner.
  166819. */
  166820. static int sessionApplyOneWithRetry(
  166821. sqlite3 *db, /* Apply change to "main" db of this handle */
  166822. sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
  166823. SessionApplyCtx *pApply, /* Apply context */
  166824. int(*xConflict)(void*, int, sqlite3_changeset_iter*),
  166825. void *pCtx /* First argument passed to xConflict */
  166826. ){
  166827. int bReplace = 0;
  166828. int bRetry = 0;
  166829. int rc;
  166830. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
  166831. assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) );
  166832. /* If the bRetry flag is set, the change has not been applied due to an
  166833. ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
  166834. ** a row with the correct PK is present in the db, but one or more other
  166835. ** fields do not contain the expected values) and the conflict handler
  166836. ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
  166837. ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
  166838. ** the SQLITE_CHANGESET_DATA problem. */
  166839. if( bRetry ){
  166840. assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
  166841. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
  166842. }
  166843. /* If the bReplace flag is set, the change is an INSERT that has not
  166844. ** been performed because the database already contains a row with the
  166845. ** specified primary key and the conflict handler returned
  166846. ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
  166847. ** before reattempting the INSERT. */
  166848. else if( bReplace ){
  166849. assert( pIter->op==SQLITE_INSERT );
  166850. rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
  166851. if( rc==SQLITE_OK ){
  166852. rc = sessionBindRow(pIter,
  166853. sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
  166854. sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
  166855. }
  166856. if( rc==SQLITE_OK ){
  166857. sqlite3_step(pApply->pDelete);
  166858. rc = sqlite3_reset(pApply->pDelete);
  166859. }
  166860. if( rc==SQLITE_OK ){
  166861. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
  166862. }
  166863. if( rc==SQLITE_OK ){
  166864. rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
  166865. }
  166866. }
  166867. return rc;
  166868. }
  166869. /*
  166870. ** Retry the changes accumulated in the pApply->constraints buffer.
  166871. */
  166872. static int sessionRetryConstraints(
  166873. sqlite3 *db,
  166874. int bPatchset,
  166875. const char *zTab,
  166876. SessionApplyCtx *pApply,
  166877. int(*xConflict)(void*, int, sqlite3_changeset_iter*),
  166878. void *pCtx /* First argument passed to xConflict */
  166879. ){
  166880. int rc = SQLITE_OK;
  166881. while( pApply->constraints.nBuf ){
  166882. sqlite3_changeset_iter *pIter2 = 0;
  166883. SessionBuffer cons = pApply->constraints;
  166884. memset(&pApply->constraints, 0, sizeof(SessionBuffer));
  166885. rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
  166886. if( rc==SQLITE_OK ){
  166887. int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
  166888. int rc2;
  166889. pIter2->bPatchset = bPatchset;
  166890. pIter2->zTab = (char*)zTab;
  166891. pIter2->nCol = pApply->nCol;
  166892. pIter2->abPK = pApply->abPK;
  166893. sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
  166894. pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
  166895. if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
  166896. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
  166897. rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
  166898. }
  166899. rc2 = sqlite3changeset_finalize(pIter2);
  166900. if( rc==SQLITE_OK ) rc = rc2;
  166901. }
  166902. assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
  166903. sqlite3_free(cons.aBuf);
  166904. if( rc!=SQLITE_OK ) break;
  166905. if( pApply->constraints.nBuf>=cons.nBuf ){
  166906. /* No progress was made on the last round. */
  166907. pApply->bDeferConstraints = 0;
  166908. }
  166909. }
  166910. return rc;
  166911. }
  166912. /*
  166913. ** Argument pIter is a changeset iterator that has been initialized, but
  166914. ** not yet passed to sqlite3changeset_next(). This function applies the
  166915. ** changeset to the main database attached to handle "db". The supplied
  166916. ** conflict handler callback is invoked to resolve any conflicts encountered
  166917. ** while applying the change.
  166918. */
  166919. static int sessionChangesetApply(
  166920. sqlite3 *db, /* Apply change to "main" db of this handle */
  166921. sqlite3_changeset_iter *pIter, /* Changeset to apply */
  166922. int(*xFilter)(
  166923. void *pCtx, /* Copy of sixth arg to _apply() */
  166924. const char *zTab /* Table name */
  166925. ),
  166926. int(*xConflict)(
  166927. void *pCtx, /* Copy of fifth arg to _apply() */
  166928. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  166929. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  166930. ),
  166931. void *pCtx /* First argument passed to xConflict */
  166932. ){
  166933. int schemaMismatch = 0;
  166934. int rc; /* Return code */
  166935. const char *zTab = 0; /* Name of current table */
  166936. int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
  166937. SessionApplyCtx sApply; /* changeset_apply() context object */
  166938. int bPatchset;
  166939. assert( xConflict!=0 );
  166940. pIter->in.bNoDiscard = 1;
  166941. memset(&sApply, 0, sizeof(sApply));
  166942. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  166943. rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
  166944. if( rc==SQLITE_OK ){
  166945. rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
  166946. }
  166947. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
  166948. int nCol;
  166949. int op;
  166950. const char *zNew;
  166951. sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
  166952. if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
  166953. u8 *abPK;
  166954. rc = sessionRetryConstraints(
  166955. db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
  166956. );
  166957. if( rc!=SQLITE_OK ) break;
  166958. sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
  166959. sqlite3_finalize(sApply.pDelete);
  166960. sqlite3_finalize(sApply.pUpdate);
  166961. sqlite3_finalize(sApply.pInsert);
  166962. sqlite3_finalize(sApply.pSelect);
  166963. memset(&sApply, 0, sizeof(sApply));
  166964. sApply.db = db;
  166965. sApply.bDeferConstraints = 1;
  166966. /* If an xFilter() callback was specified, invoke it now. If the
  166967. ** xFilter callback returns zero, skip this table. If it returns
  166968. ** non-zero, proceed. */
  166969. schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
  166970. if( schemaMismatch ){
  166971. zTab = sqlite3_mprintf("%s", zNew);
  166972. if( zTab==0 ){
  166973. rc = SQLITE_NOMEM;
  166974. break;
  166975. }
  166976. nTab = (int)strlen(zTab);
  166977. sApply.azCol = (const char **)zTab;
  166978. }else{
  166979. int nMinCol = 0;
  166980. int i;
  166981. sqlite3changeset_pk(pIter, &abPK, 0);
  166982. rc = sessionTableInfo(
  166983. db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
  166984. );
  166985. if( rc!=SQLITE_OK ) break;
  166986. for(i=0; i<sApply.nCol; i++){
  166987. if( sApply.abPK[i] ) nMinCol = i+1;
  166988. }
  166989. if( sApply.nCol==0 ){
  166990. schemaMismatch = 1;
  166991. sqlite3_log(SQLITE_SCHEMA,
  166992. "sqlite3changeset_apply(): no such table: %s", zTab
  166993. );
  166994. }
  166995. else if( sApply.nCol<nCol ){
  166996. schemaMismatch = 1;
  166997. sqlite3_log(SQLITE_SCHEMA,
  166998. "sqlite3changeset_apply(): table %s has %d columns, "
  166999. "expected %d or more",
  167000. zTab, sApply.nCol, nCol
  167001. );
  167002. }
  167003. else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
  167004. schemaMismatch = 1;
  167005. sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
  167006. "primary key mismatch for table %s", zTab
  167007. );
  167008. }
  167009. else{
  167010. sApply.nCol = nCol;
  167011. if((rc = sessionSelectRow(db, zTab, &sApply))
  167012. || (rc = sessionUpdateRow(db, zTab, &sApply))
  167013. || (rc = sessionDeleteRow(db, zTab, &sApply))
  167014. || (rc = sessionInsertRow(db, zTab, &sApply))
  167015. ){
  167016. break;
  167017. }
  167018. }
  167019. nTab = sqlite3Strlen30(zTab);
  167020. }
  167021. }
  167022. /* If there is a schema mismatch on the current table, proceed to the
  167023. ** next change. A log message has already been issued. */
  167024. if( schemaMismatch ) continue;
  167025. rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
  167026. }
  167027. bPatchset = pIter->bPatchset;
  167028. if( rc==SQLITE_OK ){
  167029. rc = sqlite3changeset_finalize(pIter);
  167030. }else{
  167031. sqlite3changeset_finalize(pIter);
  167032. }
  167033. if( rc==SQLITE_OK ){
  167034. rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
  167035. }
  167036. if( rc==SQLITE_OK ){
  167037. int nFk, notUsed;
  167038. sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
  167039. if( nFk!=0 ){
  167040. int res = SQLITE_CHANGESET_ABORT;
  167041. sqlite3_changeset_iter sIter;
  167042. memset(&sIter, 0, sizeof(sIter));
  167043. sIter.nCol = nFk;
  167044. res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
  167045. if( res!=SQLITE_CHANGESET_OMIT ){
  167046. rc = SQLITE_CONSTRAINT;
  167047. }
  167048. }
  167049. }
  167050. sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
  167051. if( rc==SQLITE_OK ){
  167052. rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  167053. }else{
  167054. sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
  167055. sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  167056. }
  167057. sqlite3_finalize(sApply.pInsert);
  167058. sqlite3_finalize(sApply.pDelete);
  167059. sqlite3_finalize(sApply.pUpdate);
  167060. sqlite3_finalize(sApply.pSelect);
  167061. sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
  167062. sqlite3_free((char*)sApply.constraints.aBuf);
  167063. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  167064. return rc;
  167065. }
  167066. /*
  167067. ** Apply the changeset passed via pChangeset/nChangeset to the main database
  167068. ** attached to handle "db". Invoke the supplied conflict handler callback
  167069. ** to resolve any conflicts encountered while applying the change.
  167070. */
  167071. SQLITE_API int sqlite3changeset_apply(
  167072. sqlite3 *db, /* Apply change to "main" db of this handle */
  167073. int nChangeset, /* Size of changeset in bytes */
  167074. void *pChangeset, /* Changeset blob */
  167075. int(*xFilter)(
  167076. void *pCtx, /* Copy of sixth arg to _apply() */
  167077. const char *zTab /* Table name */
  167078. ),
  167079. int(*xConflict)(
  167080. void *pCtx, /* Copy of fifth arg to _apply() */
  167081. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  167082. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  167083. ),
  167084. void *pCtx /* First argument passed to xConflict */
  167085. ){
  167086. sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
  167087. int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
  167088. if( rc==SQLITE_OK ){
  167089. rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
  167090. }
  167091. return rc;
  167092. }
  167093. /*
  167094. ** Apply the changeset passed via xInput/pIn to the main database
  167095. ** attached to handle "db". Invoke the supplied conflict handler callback
  167096. ** to resolve any conflicts encountered while applying the change.
  167097. */
  167098. SQLITE_API int sqlite3changeset_apply_strm(
  167099. sqlite3 *db, /* Apply change to "main" db of this handle */
  167100. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  167101. void *pIn, /* First arg for xInput */
  167102. int(*xFilter)(
  167103. void *pCtx, /* Copy of sixth arg to _apply() */
  167104. const char *zTab /* Table name */
  167105. ),
  167106. int(*xConflict)(
  167107. void *pCtx, /* Copy of sixth arg to _apply() */
  167108. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  167109. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  167110. ),
  167111. void *pCtx /* First argument passed to xConflict */
  167112. ){
  167113. sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
  167114. int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  167115. if( rc==SQLITE_OK ){
  167116. rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
  167117. }
  167118. return rc;
  167119. }
  167120. /*
  167121. ** sqlite3_changegroup handle.
  167122. */
  167123. struct sqlite3_changegroup {
  167124. int rc; /* Error code */
  167125. int bPatch; /* True to accumulate patchsets */
  167126. SessionTable *pList; /* List of tables in current patch */
  167127. };
  167128. /*
  167129. ** This function is called to merge two changes to the same row together as
  167130. ** part of an sqlite3changeset_concat() operation. A new change object is
  167131. ** allocated and a pointer to it stored in *ppNew.
  167132. */
  167133. static int sessionChangeMerge(
  167134. SessionTable *pTab, /* Table structure */
  167135. int bPatchset, /* True for patchsets */
  167136. SessionChange *pExist, /* Existing change */
  167137. int op2, /* Second change operation */
  167138. int bIndirect, /* True if second change is indirect */
  167139. u8 *aRec, /* Second change record */
  167140. int nRec, /* Number of bytes in aRec */
  167141. SessionChange **ppNew /* OUT: Merged change */
  167142. ){
  167143. SessionChange *pNew = 0;
  167144. if( !pExist ){
  167145. pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
  167146. if( !pNew ){
  167147. return SQLITE_NOMEM;
  167148. }
  167149. memset(pNew, 0, sizeof(SessionChange));
  167150. pNew->op = op2;
  167151. pNew->bIndirect = bIndirect;
  167152. pNew->nRecord = nRec;
  167153. pNew->aRecord = (u8*)&pNew[1];
  167154. memcpy(pNew->aRecord, aRec, nRec);
  167155. }else{
  167156. int op1 = pExist->op;
  167157. /*
  167158. ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
  167159. ** op1=INSERT, op2=UPDATE -> INSERT.
  167160. ** op1=INSERT, op2=DELETE -> (none)
  167161. **
  167162. ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
  167163. ** op1=UPDATE, op2=UPDATE -> UPDATE.
  167164. ** op1=UPDATE, op2=DELETE -> DELETE.
  167165. **
  167166. ** op1=DELETE, op2=INSERT -> UPDATE.
  167167. ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
  167168. ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
  167169. */
  167170. if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
  167171. || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
  167172. || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
  167173. || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
  167174. ){
  167175. pNew = pExist;
  167176. }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
  167177. sqlite3_free(pExist);
  167178. assert( pNew==0 );
  167179. }else{
  167180. u8 *aExist = pExist->aRecord;
  167181. int nByte;
  167182. u8 *aCsr;
  167183. /* Allocate a new SessionChange object. Ensure that the aRecord[]
  167184. ** buffer of the new object is large enough to hold any record that
  167185. ** may be generated by combining the input records. */
  167186. nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
  167187. pNew = (SessionChange *)sqlite3_malloc(nByte);
  167188. if( !pNew ){
  167189. sqlite3_free(pExist);
  167190. return SQLITE_NOMEM;
  167191. }
  167192. memset(pNew, 0, sizeof(SessionChange));
  167193. pNew->bIndirect = (bIndirect && pExist->bIndirect);
  167194. aCsr = pNew->aRecord = (u8 *)&pNew[1];
  167195. if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
  167196. u8 *a1 = aRec;
  167197. assert( op2==SQLITE_UPDATE );
  167198. pNew->op = SQLITE_INSERT;
  167199. if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
  167200. sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
  167201. }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
  167202. assert( op2==SQLITE_INSERT );
  167203. pNew->op = SQLITE_UPDATE;
  167204. if( bPatchset ){
  167205. memcpy(aCsr, aRec, nRec);
  167206. aCsr += nRec;
  167207. }else{
  167208. if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
  167209. sqlite3_free(pNew);
  167210. pNew = 0;
  167211. }
  167212. }
  167213. }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
  167214. u8 *a1 = aExist;
  167215. u8 *a2 = aRec;
  167216. assert( op1==SQLITE_UPDATE );
  167217. if( bPatchset==0 ){
  167218. sessionSkipRecord(&a1, pTab->nCol);
  167219. sessionSkipRecord(&a2, pTab->nCol);
  167220. }
  167221. pNew->op = SQLITE_UPDATE;
  167222. if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
  167223. sqlite3_free(pNew);
  167224. pNew = 0;
  167225. }
  167226. }else{ /* UPDATE + DELETE */
  167227. assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
  167228. pNew->op = SQLITE_DELETE;
  167229. if( bPatchset ){
  167230. memcpy(aCsr, aRec, nRec);
  167231. aCsr += nRec;
  167232. }else{
  167233. sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
  167234. }
  167235. }
  167236. if( pNew ){
  167237. pNew->nRecord = (int)(aCsr - pNew->aRecord);
  167238. }
  167239. sqlite3_free(pExist);
  167240. }
  167241. }
  167242. *ppNew = pNew;
  167243. return SQLITE_OK;
  167244. }
  167245. /*
  167246. ** Add all changes in the changeset traversed by the iterator passed as
  167247. ** the first argument to the changegroup hash tables.
  167248. */
  167249. static int sessionChangesetToHash(
  167250. sqlite3_changeset_iter *pIter, /* Iterator to read from */
  167251. sqlite3_changegroup *pGrp /* Changegroup object to add changeset to */
  167252. ){
  167253. u8 *aRec;
  167254. int nRec;
  167255. int rc = SQLITE_OK;
  167256. SessionTable *pTab = 0;
  167257. while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){
  167258. const char *zNew;
  167259. int nCol;
  167260. int op;
  167261. int iHash;
  167262. int bIndirect;
  167263. SessionChange *pChange;
  167264. SessionChange *pExist = 0;
  167265. SessionChange **pp;
  167266. if( pGrp->pList==0 ){
  167267. pGrp->bPatch = pIter->bPatchset;
  167268. }else if( pIter->bPatchset!=pGrp->bPatch ){
  167269. rc = SQLITE_ERROR;
  167270. break;
  167271. }
  167272. sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
  167273. if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
  167274. /* Search the list for a matching table */
  167275. int nNew = (int)strlen(zNew);
  167276. u8 *abPK;
  167277. sqlite3changeset_pk(pIter, &abPK, 0);
  167278. for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
  167279. if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
  167280. }
  167281. if( !pTab ){
  167282. SessionTable **ppTab;
  167283. pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
  167284. if( !pTab ){
  167285. rc = SQLITE_NOMEM;
  167286. break;
  167287. }
  167288. memset(pTab, 0, sizeof(SessionTable));
  167289. pTab->nCol = nCol;
  167290. pTab->abPK = (u8*)&pTab[1];
  167291. memcpy(pTab->abPK, abPK, nCol);
  167292. pTab->zName = (char*)&pTab->abPK[nCol];
  167293. memcpy(pTab->zName, zNew, nNew+1);
  167294. /* The new object must be linked on to the end of the list, not
  167295. ** simply added to the start of it. This is to ensure that the
  167296. ** tables within the output of sqlite3changegroup_output() are in
  167297. ** the right order. */
  167298. for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
  167299. *ppTab = pTab;
  167300. }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
  167301. rc = SQLITE_SCHEMA;
  167302. break;
  167303. }
  167304. }
  167305. if( sessionGrowHash(pIter->bPatchset, pTab) ){
  167306. rc = SQLITE_NOMEM;
  167307. break;
  167308. }
  167309. iHash = sessionChangeHash(
  167310. pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
  167311. );
  167312. /* Search for existing entry. If found, remove it from the hash table.
  167313. ** Code below may link it back in.
  167314. */
  167315. for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
  167316. int bPkOnly1 = 0;
  167317. int bPkOnly2 = 0;
  167318. if( pIter->bPatchset ){
  167319. bPkOnly1 = (*pp)->op==SQLITE_DELETE;
  167320. bPkOnly2 = op==SQLITE_DELETE;
  167321. }
  167322. if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
  167323. pExist = *pp;
  167324. *pp = (*pp)->pNext;
  167325. pTab->nEntry--;
  167326. break;
  167327. }
  167328. }
  167329. rc = sessionChangeMerge(pTab,
  167330. pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
  167331. );
  167332. if( rc ) break;
  167333. if( pChange ){
  167334. pChange->pNext = pTab->apChange[iHash];
  167335. pTab->apChange[iHash] = pChange;
  167336. pTab->nEntry++;
  167337. }
  167338. }
  167339. if( rc==SQLITE_OK ) rc = pIter->rc;
  167340. return rc;
  167341. }
  167342. /*
  167343. ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
  167344. ** added to the changegroup object passed as the first argument.
  167345. **
  167346. ** If xOutput is not NULL, then the changeset/patchset is returned to the
  167347. ** user via one or more calls to xOutput, as with the other streaming
  167348. ** interfaces.
  167349. **
  167350. ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
  167351. ** buffer containing the output changeset before this function returns. In
  167352. ** this case (*pnOut) is set to the size of the output buffer in bytes. It
  167353. ** is the responsibility of the caller to free the output buffer using
  167354. ** sqlite3_free() when it is no longer required.
  167355. **
  167356. ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
  167357. ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
  167358. ** are both set to 0 before returning.
  167359. */
  167360. static int sessionChangegroupOutput(
  167361. sqlite3_changegroup *pGrp,
  167362. int (*xOutput)(void *pOut, const void *pData, int nData),
  167363. void *pOut,
  167364. int *pnOut,
  167365. void **ppOut
  167366. ){
  167367. int rc = SQLITE_OK;
  167368. SessionBuffer buf = {0, 0, 0};
  167369. SessionTable *pTab;
  167370. assert( xOutput==0 || (ppOut==0 && pnOut==0) );
  167371. /* Create the serialized output changeset based on the contents of the
  167372. ** hash tables attached to the SessionTable objects in list p->pList.
  167373. */
  167374. for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
  167375. int i;
  167376. if( pTab->nEntry==0 ) continue;
  167377. sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
  167378. for(i=0; i<pTab->nChange; i++){
  167379. SessionChange *p;
  167380. for(p=pTab->apChange[i]; p; p=p->pNext){
  167381. sessionAppendByte(&buf, p->op, &rc);
  167382. sessionAppendByte(&buf, p->bIndirect, &rc);
  167383. sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
  167384. }
  167385. }
  167386. if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
  167387. rc = xOutput(pOut, buf.aBuf, buf.nBuf);
  167388. buf.nBuf = 0;
  167389. }
  167390. }
  167391. if( rc==SQLITE_OK ){
  167392. if( xOutput ){
  167393. if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
  167394. }else{
  167395. *ppOut = buf.aBuf;
  167396. *pnOut = buf.nBuf;
  167397. buf.aBuf = 0;
  167398. }
  167399. }
  167400. sqlite3_free(buf.aBuf);
  167401. return rc;
  167402. }
  167403. /*
  167404. ** Allocate a new, empty, sqlite3_changegroup.
  167405. */
  167406. SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
  167407. int rc = SQLITE_OK; /* Return code */
  167408. sqlite3_changegroup *p; /* New object */
  167409. p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
  167410. if( p==0 ){
  167411. rc = SQLITE_NOMEM;
  167412. }else{
  167413. memset(p, 0, sizeof(sqlite3_changegroup));
  167414. }
  167415. *pp = p;
  167416. return rc;
  167417. }
  167418. /*
  167419. ** Add the changeset currently stored in buffer pData, size nData bytes,
  167420. ** to changeset-group p.
  167421. */
  167422. SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
  167423. sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
  167424. int rc; /* Return code */
  167425. rc = sqlite3changeset_start(&pIter, nData, pData);
  167426. if( rc==SQLITE_OK ){
  167427. rc = sessionChangesetToHash(pIter, pGrp);
  167428. }
  167429. sqlite3changeset_finalize(pIter);
  167430. return rc;
  167431. }
  167432. /*
  167433. ** Obtain a buffer containing a changeset representing the concatenation
  167434. ** of all changesets added to the group so far.
  167435. */
  167436. SQLITE_API int sqlite3changegroup_output(
  167437. sqlite3_changegroup *pGrp,
  167438. int *pnData,
  167439. void **ppData
  167440. ){
  167441. return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
  167442. }
  167443. /*
  167444. ** Streaming versions of changegroup_add().
  167445. */
  167446. SQLITE_API int sqlite3changegroup_add_strm(
  167447. sqlite3_changegroup *pGrp,
  167448. int (*xInput)(void *pIn, void *pData, int *pnData),
  167449. void *pIn
  167450. ){
  167451. sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
  167452. int rc; /* Return code */
  167453. rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  167454. if( rc==SQLITE_OK ){
  167455. rc = sessionChangesetToHash(pIter, pGrp);
  167456. }
  167457. sqlite3changeset_finalize(pIter);
  167458. return rc;
  167459. }
  167460. /*
  167461. ** Streaming versions of changegroup_output().
  167462. */
  167463. SQLITE_API int sqlite3changegroup_output_strm(
  167464. sqlite3_changegroup *pGrp,
  167465. int (*xOutput)(void *pOut, const void *pData, int nData),
  167466. void *pOut
  167467. ){
  167468. return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
  167469. }
  167470. /*
  167471. ** Delete a changegroup object.
  167472. */
  167473. SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
  167474. if( pGrp ){
  167475. sessionDeleteTable(pGrp->pList);
  167476. sqlite3_free(pGrp);
  167477. }
  167478. }
  167479. /*
  167480. ** Combine two changesets together.
  167481. */
  167482. SQLITE_API int sqlite3changeset_concat(
  167483. int nLeft, /* Number of bytes in lhs input */
  167484. void *pLeft, /* Lhs input changeset */
  167485. int nRight /* Number of bytes in rhs input */,
  167486. void *pRight, /* Rhs input changeset */
  167487. int *pnOut, /* OUT: Number of bytes in output changeset */
  167488. void **ppOut /* OUT: changeset (left <concat> right) */
  167489. ){
  167490. sqlite3_changegroup *pGrp;
  167491. int rc;
  167492. rc = sqlite3changegroup_new(&pGrp);
  167493. if( rc==SQLITE_OK ){
  167494. rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
  167495. }
  167496. if( rc==SQLITE_OK ){
  167497. rc = sqlite3changegroup_add(pGrp, nRight, pRight);
  167498. }
  167499. if( rc==SQLITE_OK ){
  167500. rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
  167501. }
  167502. sqlite3changegroup_delete(pGrp);
  167503. return rc;
  167504. }
  167505. /*
  167506. ** Streaming version of sqlite3changeset_concat().
  167507. */
  167508. SQLITE_API int sqlite3changeset_concat_strm(
  167509. int (*xInputA)(void *pIn, void *pData, int *pnData),
  167510. void *pInA,
  167511. int (*xInputB)(void *pIn, void *pData, int *pnData),
  167512. void *pInB,
  167513. int (*xOutput)(void *pOut, const void *pData, int nData),
  167514. void *pOut
  167515. ){
  167516. sqlite3_changegroup *pGrp;
  167517. int rc;
  167518. rc = sqlite3changegroup_new(&pGrp);
  167519. if( rc==SQLITE_OK ){
  167520. rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
  167521. }
  167522. if( rc==SQLITE_OK ){
  167523. rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
  167524. }
  167525. if( rc==SQLITE_OK ){
  167526. rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
  167527. }
  167528. sqlite3changegroup_delete(pGrp);
  167529. return rc;
  167530. }
  167531. #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
  167532. /************** End of sqlite3session.c **************************************/
  167533. /************** Begin file json1.c *******************************************/
  167534. /*
  167535. ** 2015-08-12
  167536. **
  167537. ** The author disclaims copyright to this source code. In place of
  167538. ** a legal notice, here is a blessing:
  167539. **
  167540. ** May you do good and not evil.
  167541. ** May you find forgiveness for yourself and forgive others.
  167542. ** May you share freely, never taking more than you give.
  167543. **
  167544. ******************************************************************************
  167545. **
  167546. ** This SQLite extension implements JSON functions. The interface is
  167547. ** modeled after MySQL JSON functions:
  167548. **
  167549. ** https://dev.mysql.com/doc/refman/5.7/en/json.html
  167550. **
  167551. ** For the time being, all JSON is stored as pure text. (We might add
  167552. ** a JSONB type in the future which stores a binary encoding of JSON in
  167553. ** a BLOB, but there is no support for JSONB in the current implementation.
  167554. ** This implementation parses JSON text at 250 MB/s, so it is hard to see
  167555. ** how JSONB might improve on that.)
  167556. */
  167557. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
  167558. #if !defined(SQLITEINT_H)
  167559. /* #include "sqlite3ext.h" */
  167560. #endif
  167561. SQLITE_EXTENSION_INIT1
  167562. /* #include <assert.h> */
  167563. /* #include <string.h> */
  167564. /* #include <stdlib.h> */
  167565. /* #include <stdarg.h> */
  167566. /* Mark a function parameter as unused, to suppress nuisance compiler
  167567. ** warnings. */
  167568. #ifndef UNUSED_PARAM
  167569. # define UNUSED_PARAM(X) (void)(X)
  167570. #endif
  167571. #ifndef LARGEST_INT64
  167572. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  167573. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  167574. #endif
  167575. /*
  167576. ** Versions of isspace(), isalnum() and isdigit() to which it is safe
  167577. ** to pass signed char values.
  167578. */
  167579. #ifdef sqlite3Isdigit
  167580. /* Use the SQLite core versions if this routine is part of the
  167581. ** SQLite amalgamation */
  167582. # define safe_isdigit(x) sqlite3Isdigit(x)
  167583. # define safe_isalnum(x) sqlite3Isalnum(x)
  167584. # define safe_isxdigit(x) sqlite3Isxdigit(x)
  167585. #else
  167586. /* Use the standard library for separate compilation */
  167587. #include <ctype.h> /* amalgamator: keep */
  167588. # define safe_isdigit(x) isdigit((unsigned char)(x))
  167589. # define safe_isalnum(x) isalnum((unsigned char)(x))
  167590. # define safe_isxdigit(x) isxdigit((unsigned char)(x))
  167591. #endif
  167592. /*
  167593. ** Growing our own isspace() routine this way is twice as fast as
  167594. ** the library isspace() function, resulting in a 7% overall performance
  167595. ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
  167596. */
  167597. static const char jsonIsSpace[] = {
  167598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
  167599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167600. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  167614. };
  167615. #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
  167616. #ifndef SQLITE_AMALGAMATION
  167617. /* Unsigned integer types. These are already defined in the sqliteInt.h,
  167618. ** but the definitions need to be repeated for separate compilation. */
  167619. typedef sqlite3_uint64 u64;
  167620. typedef unsigned int u32;
  167621. typedef unsigned short int u16;
  167622. typedef unsigned char u8;
  167623. #endif
  167624. /* Objects */
  167625. typedef struct JsonString JsonString;
  167626. typedef struct JsonNode JsonNode;
  167627. typedef struct JsonParse JsonParse;
  167628. /* An instance of this object represents a JSON string
  167629. ** under construction. Really, this is a generic string accumulator
  167630. ** that can be and is used to create strings other than JSON.
  167631. */
  167632. struct JsonString {
  167633. sqlite3_context *pCtx; /* Function context - put error messages here */
  167634. char *zBuf; /* Append JSON content here */
  167635. u64 nAlloc; /* Bytes of storage available in zBuf[] */
  167636. u64 nUsed; /* Bytes of zBuf[] currently used */
  167637. u8 bStatic; /* True if zBuf is static space */
  167638. u8 bErr; /* True if an error has been encountered */
  167639. char zSpace[100]; /* Initial static space */
  167640. };
  167641. /* JSON type values
  167642. */
  167643. #define JSON_NULL 0
  167644. #define JSON_TRUE 1
  167645. #define JSON_FALSE 2
  167646. #define JSON_INT 3
  167647. #define JSON_REAL 4
  167648. #define JSON_STRING 5
  167649. #define JSON_ARRAY 6
  167650. #define JSON_OBJECT 7
  167651. /* The "subtype" set for JSON values */
  167652. #define JSON_SUBTYPE 74 /* Ascii for "J" */
  167653. /*
  167654. ** Names of the various JSON types:
  167655. */
  167656. static const char * const jsonType[] = {
  167657. "null", "true", "false", "integer", "real", "text", "array", "object"
  167658. };
  167659. /* Bit values for the JsonNode.jnFlag field
  167660. */
  167661. #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
  167662. #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
  167663. #define JNODE_REMOVE 0x04 /* Do not output */
  167664. #define JNODE_REPLACE 0x08 /* Replace with JsonNode.u.iReplace */
  167665. #define JNODE_PATCH 0x10 /* Patch with JsonNode.u.pPatch */
  167666. #define JNODE_APPEND 0x20 /* More ARRAY/OBJECT entries at u.iAppend */
  167667. #define JNODE_LABEL 0x40 /* Is a label of an object */
  167668. /* A single node of parsed JSON
  167669. */
  167670. struct JsonNode {
  167671. u8 eType; /* One of the JSON_ type values */
  167672. u8 jnFlags; /* JNODE flags */
  167673. u32 n; /* Bytes of content, or number of sub-nodes */
  167674. union {
  167675. const char *zJContent; /* Content for INT, REAL, and STRING */
  167676. u32 iAppend; /* More terms for ARRAY and OBJECT */
  167677. u32 iKey; /* Key for ARRAY objects in json_tree() */
  167678. u32 iReplace; /* Replacement content for JNODE_REPLACE */
  167679. JsonNode *pPatch; /* Node chain of patch for JNODE_PATCH */
  167680. } u;
  167681. };
  167682. /* A completely parsed JSON string
  167683. */
  167684. struct JsonParse {
  167685. u32 nNode; /* Number of slots of aNode[] used */
  167686. u32 nAlloc; /* Number of slots of aNode[] allocated */
  167687. JsonNode *aNode; /* Array of nodes containing the parse */
  167688. const char *zJson; /* Original JSON string */
  167689. u32 *aUp; /* Index of parent of each node */
  167690. u8 oom; /* Set to true if out of memory */
  167691. u8 nErr; /* Number of errors seen */
  167692. u16 iDepth; /* Nesting depth */
  167693. int nJson; /* Length of the zJson string in bytes */
  167694. };
  167695. /*
  167696. ** Maximum nesting depth of JSON for this implementation.
  167697. **
  167698. ** This limit is needed to avoid a stack overflow in the recursive
  167699. ** descent parser. A depth of 2000 is far deeper than any sane JSON
  167700. ** should go.
  167701. */
  167702. #define JSON_MAX_DEPTH 2000
  167703. /**************************************************************************
  167704. ** Utility routines for dealing with JsonString objects
  167705. **************************************************************************/
  167706. /* Set the JsonString object to an empty string
  167707. */
  167708. static void jsonZero(JsonString *p){
  167709. p->zBuf = p->zSpace;
  167710. p->nAlloc = sizeof(p->zSpace);
  167711. p->nUsed = 0;
  167712. p->bStatic = 1;
  167713. }
  167714. /* Initialize the JsonString object
  167715. */
  167716. static void jsonInit(JsonString *p, sqlite3_context *pCtx){
  167717. p->pCtx = pCtx;
  167718. p->bErr = 0;
  167719. jsonZero(p);
  167720. }
  167721. /* Free all allocated memory and reset the JsonString object back to its
  167722. ** initial state.
  167723. */
  167724. static void jsonReset(JsonString *p){
  167725. if( !p->bStatic ) sqlite3_free(p->zBuf);
  167726. jsonZero(p);
  167727. }
  167728. /* Report an out-of-memory (OOM) condition
  167729. */
  167730. static void jsonOom(JsonString *p){
  167731. p->bErr = 1;
  167732. sqlite3_result_error_nomem(p->pCtx);
  167733. jsonReset(p);
  167734. }
  167735. /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
  167736. ** Return zero on success. Return non-zero on an OOM error
  167737. */
  167738. static int jsonGrow(JsonString *p, u32 N){
  167739. u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
  167740. char *zNew;
  167741. if( p->bStatic ){
  167742. if( p->bErr ) return 1;
  167743. zNew = sqlite3_malloc64(nTotal);
  167744. if( zNew==0 ){
  167745. jsonOom(p);
  167746. return SQLITE_NOMEM;
  167747. }
  167748. memcpy(zNew, p->zBuf, (size_t)p->nUsed);
  167749. p->zBuf = zNew;
  167750. p->bStatic = 0;
  167751. }else{
  167752. zNew = sqlite3_realloc64(p->zBuf, nTotal);
  167753. if( zNew==0 ){
  167754. jsonOom(p);
  167755. return SQLITE_NOMEM;
  167756. }
  167757. p->zBuf = zNew;
  167758. }
  167759. p->nAlloc = nTotal;
  167760. return SQLITE_OK;
  167761. }
  167762. /* Append N bytes from zIn onto the end of the JsonString string.
  167763. */
  167764. static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
  167765. if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
  167766. memcpy(p->zBuf+p->nUsed, zIn, N);
  167767. p->nUsed += N;
  167768. }
  167769. /* Append formatted text (not to exceed N bytes) to the JsonString.
  167770. */
  167771. static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
  167772. va_list ap;
  167773. if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
  167774. va_start(ap, zFormat);
  167775. sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
  167776. va_end(ap);
  167777. p->nUsed += (int)strlen(p->zBuf+p->nUsed);
  167778. }
  167779. /* Append a single character
  167780. */
  167781. static void jsonAppendChar(JsonString *p, char c){
  167782. if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
  167783. p->zBuf[p->nUsed++] = c;
  167784. }
  167785. /* Append a comma separator to the output buffer, if the previous
  167786. ** character is not '[' or '{'.
  167787. */
  167788. static void jsonAppendSeparator(JsonString *p){
  167789. char c;
  167790. if( p->nUsed==0 ) return;
  167791. c = p->zBuf[p->nUsed-1];
  167792. if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
  167793. }
  167794. /* Append the N-byte string in zIn to the end of the JsonString string
  167795. ** under construction. Enclose the string in "..." and escape
  167796. ** any double-quotes or backslash characters contained within the
  167797. ** string.
  167798. */
  167799. static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
  167800. u32 i;
  167801. if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
  167802. p->zBuf[p->nUsed++] = '"';
  167803. for(i=0; i<N; i++){
  167804. unsigned char c = ((unsigned const char*)zIn)[i];
  167805. if( c=='"' || c=='\\' ){
  167806. json_simple_escape:
  167807. if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
  167808. p->zBuf[p->nUsed++] = '\\';
  167809. }else if( c<=0x1f ){
  167810. static const char aSpecial[] = {
  167811. 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
  167812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  167813. };
  167814. assert( sizeof(aSpecial)==32 );
  167815. assert( aSpecial['\b']=='b' );
  167816. assert( aSpecial['\f']=='f' );
  167817. assert( aSpecial['\n']=='n' );
  167818. assert( aSpecial['\r']=='r' );
  167819. assert( aSpecial['\t']=='t' );
  167820. if( aSpecial[c] ){
  167821. c = aSpecial[c];
  167822. goto json_simple_escape;
  167823. }
  167824. if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
  167825. p->zBuf[p->nUsed++] = '\\';
  167826. p->zBuf[p->nUsed++] = 'u';
  167827. p->zBuf[p->nUsed++] = '0';
  167828. p->zBuf[p->nUsed++] = '0';
  167829. p->zBuf[p->nUsed++] = '0' + (c>>4);
  167830. c = "0123456789abcdef"[c&0xf];
  167831. }
  167832. p->zBuf[p->nUsed++] = c;
  167833. }
  167834. p->zBuf[p->nUsed++] = '"';
  167835. assert( p->nUsed<p->nAlloc );
  167836. }
  167837. /*
  167838. ** Append a function parameter value to the JSON string under
  167839. ** construction.
  167840. */
  167841. static void jsonAppendValue(
  167842. JsonString *p, /* Append to this JSON string */
  167843. sqlite3_value *pValue /* Value to append */
  167844. ){
  167845. switch( sqlite3_value_type(pValue) ){
  167846. case SQLITE_NULL: {
  167847. jsonAppendRaw(p, "null", 4);
  167848. break;
  167849. }
  167850. case SQLITE_INTEGER:
  167851. case SQLITE_FLOAT: {
  167852. const char *z = (const char*)sqlite3_value_text(pValue);
  167853. u32 n = (u32)sqlite3_value_bytes(pValue);
  167854. jsonAppendRaw(p, z, n);
  167855. break;
  167856. }
  167857. case SQLITE_TEXT: {
  167858. const char *z = (const char*)sqlite3_value_text(pValue);
  167859. u32 n = (u32)sqlite3_value_bytes(pValue);
  167860. if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
  167861. jsonAppendRaw(p, z, n);
  167862. }else{
  167863. jsonAppendString(p, z, n);
  167864. }
  167865. break;
  167866. }
  167867. default: {
  167868. if( p->bErr==0 ){
  167869. sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
  167870. p->bErr = 2;
  167871. jsonReset(p);
  167872. }
  167873. break;
  167874. }
  167875. }
  167876. }
  167877. /* Make the JSON in p the result of the SQL function.
  167878. */
  167879. static void jsonResult(JsonString *p){
  167880. if( p->bErr==0 ){
  167881. sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
  167882. p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
  167883. SQLITE_UTF8);
  167884. jsonZero(p);
  167885. }
  167886. assert( p->bStatic );
  167887. }
  167888. /**************************************************************************
  167889. ** Utility routines for dealing with JsonNode and JsonParse objects
  167890. **************************************************************************/
  167891. /*
  167892. ** Return the number of consecutive JsonNode slots need to represent
  167893. ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
  167894. ** OBJECT types, the number might be larger.
  167895. **
  167896. ** Appended elements are not counted. The value returned is the number
  167897. ** by which the JsonNode counter should increment in order to go to the
  167898. ** next peer value.
  167899. */
  167900. static u32 jsonNodeSize(JsonNode *pNode){
  167901. return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
  167902. }
  167903. /*
  167904. ** Reclaim all memory allocated by a JsonParse object. But do not
  167905. ** delete the JsonParse object itself.
  167906. */
  167907. static void jsonParseReset(JsonParse *pParse){
  167908. sqlite3_free(pParse->aNode);
  167909. pParse->aNode = 0;
  167910. pParse->nNode = 0;
  167911. pParse->nAlloc = 0;
  167912. sqlite3_free(pParse->aUp);
  167913. pParse->aUp = 0;
  167914. }
  167915. /*
  167916. ** Free a JsonParse object that was obtained from sqlite3_malloc().
  167917. */
  167918. static void jsonParseFree(JsonParse *pParse){
  167919. jsonParseReset(pParse);
  167920. sqlite3_free(pParse);
  167921. }
  167922. /*
  167923. ** Convert the JsonNode pNode into a pure JSON string and
  167924. ** append to pOut. Subsubstructure is also included. Return
  167925. ** the number of JsonNode objects that are encoded.
  167926. */
  167927. static void jsonRenderNode(
  167928. JsonNode *pNode, /* The node to render */
  167929. JsonString *pOut, /* Write JSON here */
  167930. sqlite3_value **aReplace /* Replacement values */
  167931. ){
  167932. if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
  167933. if( pNode->jnFlags & JNODE_REPLACE ){
  167934. jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
  167935. return;
  167936. }
  167937. pNode = pNode->u.pPatch;
  167938. }
  167939. switch( pNode->eType ){
  167940. default: {
  167941. assert( pNode->eType==JSON_NULL );
  167942. jsonAppendRaw(pOut, "null", 4);
  167943. break;
  167944. }
  167945. case JSON_TRUE: {
  167946. jsonAppendRaw(pOut, "true", 4);
  167947. break;
  167948. }
  167949. case JSON_FALSE: {
  167950. jsonAppendRaw(pOut, "false", 5);
  167951. break;
  167952. }
  167953. case JSON_STRING: {
  167954. if( pNode->jnFlags & JNODE_RAW ){
  167955. jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
  167956. break;
  167957. }
  167958. /* Fall through into the next case */
  167959. }
  167960. case JSON_REAL:
  167961. case JSON_INT: {
  167962. jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
  167963. break;
  167964. }
  167965. case JSON_ARRAY: {
  167966. u32 j = 1;
  167967. jsonAppendChar(pOut, '[');
  167968. for(;;){
  167969. while( j<=pNode->n ){
  167970. if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
  167971. jsonAppendSeparator(pOut);
  167972. jsonRenderNode(&pNode[j], pOut, aReplace);
  167973. }
  167974. j += jsonNodeSize(&pNode[j]);
  167975. }
  167976. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  167977. pNode = &pNode[pNode->u.iAppend];
  167978. j = 1;
  167979. }
  167980. jsonAppendChar(pOut, ']');
  167981. break;
  167982. }
  167983. case JSON_OBJECT: {
  167984. u32 j = 1;
  167985. jsonAppendChar(pOut, '{');
  167986. for(;;){
  167987. while( j<=pNode->n ){
  167988. if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
  167989. jsonAppendSeparator(pOut);
  167990. jsonRenderNode(&pNode[j], pOut, aReplace);
  167991. jsonAppendChar(pOut, ':');
  167992. jsonRenderNode(&pNode[j+1], pOut, aReplace);
  167993. }
  167994. j += 1 + jsonNodeSize(&pNode[j+1]);
  167995. }
  167996. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  167997. pNode = &pNode[pNode->u.iAppend];
  167998. j = 1;
  167999. }
  168000. jsonAppendChar(pOut, '}');
  168001. break;
  168002. }
  168003. }
  168004. }
  168005. /*
  168006. ** Return a JsonNode and all its descendents as a JSON string.
  168007. */
  168008. static void jsonReturnJson(
  168009. JsonNode *pNode, /* Node to return */
  168010. sqlite3_context *pCtx, /* Return value for this function */
  168011. sqlite3_value **aReplace /* Array of replacement values */
  168012. ){
  168013. JsonString s;
  168014. jsonInit(&s, pCtx);
  168015. jsonRenderNode(pNode, &s, aReplace);
  168016. jsonResult(&s);
  168017. sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
  168018. }
  168019. /*
  168020. ** Make the JsonNode the return value of the function.
  168021. */
  168022. static void jsonReturn(
  168023. JsonNode *pNode, /* Node to return */
  168024. sqlite3_context *pCtx, /* Return value for this function */
  168025. sqlite3_value **aReplace /* Array of replacement values */
  168026. ){
  168027. switch( pNode->eType ){
  168028. default: {
  168029. assert( pNode->eType==JSON_NULL );
  168030. sqlite3_result_null(pCtx);
  168031. break;
  168032. }
  168033. case JSON_TRUE: {
  168034. sqlite3_result_int(pCtx, 1);
  168035. break;
  168036. }
  168037. case JSON_FALSE: {
  168038. sqlite3_result_int(pCtx, 0);
  168039. break;
  168040. }
  168041. case JSON_INT: {
  168042. sqlite3_int64 i = 0;
  168043. const char *z = pNode->u.zJContent;
  168044. if( z[0]=='-' ){ z++; }
  168045. while( z[0]>='0' && z[0]<='9' ){
  168046. unsigned v = *(z++) - '0';
  168047. if( i>=LARGEST_INT64/10 ){
  168048. if( i>LARGEST_INT64/10 ) goto int_as_real;
  168049. if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
  168050. if( v==9 ) goto int_as_real;
  168051. if( v==8 ){
  168052. if( pNode->u.zJContent[0]=='-' ){
  168053. sqlite3_result_int64(pCtx, SMALLEST_INT64);
  168054. goto int_done;
  168055. }else{
  168056. goto int_as_real;
  168057. }
  168058. }
  168059. }
  168060. i = i*10 + v;
  168061. }
  168062. if( pNode->u.zJContent[0]=='-' ){ i = -i; }
  168063. sqlite3_result_int64(pCtx, i);
  168064. int_done:
  168065. break;
  168066. int_as_real: /* fall through to real */;
  168067. }
  168068. case JSON_REAL: {
  168069. double r;
  168070. #ifdef SQLITE_AMALGAMATION
  168071. const char *z = pNode->u.zJContent;
  168072. sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
  168073. #else
  168074. r = strtod(pNode->u.zJContent, 0);
  168075. #endif
  168076. sqlite3_result_double(pCtx, r);
  168077. break;
  168078. }
  168079. case JSON_STRING: {
  168080. #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
  168081. ** json_insert() and json_replace() and those routines do not
  168082. ** call jsonReturn() */
  168083. if( pNode->jnFlags & JNODE_RAW ){
  168084. sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
  168085. SQLITE_TRANSIENT);
  168086. }else
  168087. #endif
  168088. assert( (pNode->jnFlags & JNODE_RAW)==0 );
  168089. if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
  168090. /* JSON formatted without any backslash-escapes */
  168091. sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
  168092. SQLITE_TRANSIENT);
  168093. }else{
  168094. /* Translate JSON formatted string into raw text */
  168095. u32 i;
  168096. u32 n = pNode->n;
  168097. const char *z = pNode->u.zJContent;
  168098. char *zOut;
  168099. u32 j;
  168100. zOut = sqlite3_malloc( n+1 );
  168101. if( zOut==0 ){
  168102. sqlite3_result_error_nomem(pCtx);
  168103. break;
  168104. }
  168105. for(i=1, j=0; i<n-1; i++){
  168106. char c = z[i];
  168107. if( c!='\\' ){
  168108. zOut[j++] = c;
  168109. }else{
  168110. c = z[++i];
  168111. if( c=='u' ){
  168112. u32 v = 0, k;
  168113. for(k=0; k<4; i++, k++){
  168114. assert( i<n-2 );
  168115. c = z[i+1];
  168116. assert( safe_isxdigit(c) );
  168117. if( c<='9' ) v = v*16 + c - '0';
  168118. else if( c<='F' ) v = v*16 + c - 'A' + 10;
  168119. else v = v*16 + c - 'a' + 10;
  168120. }
  168121. if( v==0 ) break;
  168122. if( v<=0x7f ){
  168123. zOut[j++] = (char)v;
  168124. }else if( v<=0x7ff ){
  168125. zOut[j++] = (char)(0xc0 | (v>>6));
  168126. zOut[j++] = 0x80 | (v&0x3f);
  168127. }else{
  168128. zOut[j++] = (char)(0xe0 | (v>>12));
  168129. zOut[j++] = 0x80 | ((v>>6)&0x3f);
  168130. zOut[j++] = 0x80 | (v&0x3f);
  168131. }
  168132. }else{
  168133. if( c=='b' ){
  168134. c = '\b';
  168135. }else if( c=='f' ){
  168136. c = '\f';
  168137. }else if( c=='n' ){
  168138. c = '\n';
  168139. }else if( c=='r' ){
  168140. c = '\r';
  168141. }else if( c=='t' ){
  168142. c = '\t';
  168143. }
  168144. zOut[j++] = c;
  168145. }
  168146. }
  168147. }
  168148. zOut[j] = 0;
  168149. sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
  168150. }
  168151. break;
  168152. }
  168153. case JSON_ARRAY:
  168154. case JSON_OBJECT: {
  168155. jsonReturnJson(pNode, pCtx, aReplace);
  168156. break;
  168157. }
  168158. }
  168159. }
  168160. /* Forward reference */
  168161. static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
  168162. /*
  168163. ** A macro to hint to the compiler that a function should not be
  168164. ** inlined.
  168165. */
  168166. #if defined(__GNUC__)
  168167. # define JSON_NOINLINE __attribute__((noinline))
  168168. #elif defined(_MSC_VER) && _MSC_VER>=1310
  168169. # define JSON_NOINLINE __declspec(noinline)
  168170. #else
  168171. # define JSON_NOINLINE
  168172. #endif
  168173. static JSON_NOINLINE int jsonParseAddNodeExpand(
  168174. JsonParse *pParse, /* Append the node to this object */
  168175. u32 eType, /* Node type */
  168176. u32 n, /* Content size or sub-node count */
  168177. const char *zContent /* Content */
  168178. ){
  168179. u32 nNew;
  168180. JsonNode *pNew;
  168181. assert( pParse->nNode>=pParse->nAlloc );
  168182. if( pParse->oom ) return -1;
  168183. nNew = pParse->nAlloc*2 + 10;
  168184. pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
  168185. if( pNew==0 ){
  168186. pParse->oom = 1;
  168187. return -1;
  168188. }
  168189. pParse->nAlloc = nNew;
  168190. pParse->aNode = pNew;
  168191. assert( pParse->nNode<pParse->nAlloc );
  168192. return jsonParseAddNode(pParse, eType, n, zContent);
  168193. }
  168194. /*
  168195. ** Create a new JsonNode instance based on the arguments and append that
  168196. ** instance to the JsonParse. Return the index in pParse->aNode[] of the
  168197. ** new node, or -1 if a memory allocation fails.
  168198. */
  168199. static int jsonParseAddNode(
  168200. JsonParse *pParse, /* Append the node to this object */
  168201. u32 eType, /* Node type */
  168202. u32 n, /* Content size or sub-node count */
  168203. const char *zContent /* Content */
  168204. ){
  168205. JsonNode *p;
  168206. if( pParse->nNode>=pParse->nAlloc ){
  168207. return jsonParseAddNodeExpand(pParse, eType, n, zContent);
  168208. }
  168209. p = &pParse->aNode[pParse->nNode];
  168210. p->eType = (u8)eType;
  168211. p->jnFlags = 0;
  168212. p->n = n;
  168213. p->u.zJContent = zContent;
  168214. return pParse->nNode++;
  168215. }
  168216. /*
  168217. ** Return true if z[] begins with 4 (or more) hexadecimal digits
  168218. */
  168219. static int jsonIs4Hex(const char *z){
  168220. int i;
  168221. for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
  168222. return 1;
  168223. }
  168224. /*
  168225. ** Parse a single JSON value which begins at pParse->zJson[i]. Return the
  168226. ** index of the first character past the end of the value parsed.
  168227. **
  168228. ** Return negative for a syntax error. Special cases: return -2 if the
  168229. ** first non-whitespace character is '}' and return -3 if the first
  168230. ** non-whitespace character is ']'.
  168231. */
  168232. static int jsonParseValue(JsonParse *pParse, u32 i){
  168233. char c;
  168234. u32 j;
  168235. int iThis;
  168236. int x;
  168237. JsonNode *pNode;
  168238. const char *z = pParse->zJson;
  168239. while( safe_isspace(z[i]) ){ i++; }
  168240. if( (c = z[i])=='{' ){
  168241. /* Parse object */
  168242. iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  168243. if( iThis<0 ) return -1;
  168244. for(j=i+1;;j++){
  168245. while( safe_isspace(z[j]) ){ j++; }
  168246. if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
  168247. x = jsonParseValue(pParse, j);
  168248. if( x<0 ){
  168249. pParse->iDepth--;
  168250. if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
  168251. return -1;
  168252. }
  168253. if( pParse->oom ) return -1;
  168254. pNode = &pParse->aNode[pParse->nNode-1];
  168255. if( pNode->eType!=JSON_STRING ) return -1;
  168256. pNode->jnFlags |= JNODE_LABEL;
  168257. j = x;
  168258. while( safe_isspace(z[j]) ){ j++; }
  168259. if( z[j]!=':' ) return -1;
  168260. j++;
  168261. x = jsonParseValue(pParse, j);
  168262. pParse->iDepth--;
  168263. if( x<0 ) return -1;
  168264. j = x;
  168265. while( safe_isspace(z[j]) ){ j++; }
  168266. c = z[j];
  168267. if( c==',' ) continue;
  168268. if( c!='}' ) return -1;
  168269. break;
  168270. }
  168271. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  168272. return j+1;
  168273. }else if( c=='[' ){
  168274. /* Parse array */
  168275. iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  168276. if( iThis<0 ) return -1;
  168277. for(j=i+1;;j++){
  168278. while( safe_isspace(z[j]) ){ j++; }
  168279. if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
  168280. x = jsonParseValue(pParse, j);
  168281. pParse->iDepth--;
  168282. if( x<0 ){
  168283. if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
  168284. return -1;
  168285. }
  168286. j = x;
  168287. while( safe_isspace(z[j]) ){ j++; }
  168288. c = z[j];
  168289. if( c==',' ) continue;
  168290. if( c!=']' ) return -1;
  168291. break;
  168292. }
  168293. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  168294. return j+1;
  168295. }else if( c=='"' ){
  168296. /* Parse string */
  168297. u8 jnFlags = 0;
  168298. j = i+1;
  168299. for(;;){
  168300. c = z[j];
  168301. if( (c & ~0x1f)==0 ){
  168302. /* Control characters are not allowed in strings */
  168303. return -1;
  168304. }
  168305. if( c=='\\' ){
  168306. c = z[++j];
  168307. if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
  168308. || c=='n' || c=='r' || c=='t'
  168309. || (c=='u' && jsonIs4Hex(z+j+1)) ){
  168310. jnFlags = JNODE_ESCAPE;
  168311. }else{
  168312. return -1;
  168313. }
  168314. }else if( c=='"' ){
  168315. break;
  168316. }
  168317. j++;
  168318. }
  168319. jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
  168320. if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
  168321. return j+1;
  168322. }else if( c=='n'
  168323. && strncmp(z+i,"null",4)==0
  168324. && !safe_isalnum(z[i+4]) ){
  168325. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  168326. return i+4;
  168327. }else if( c=='t'
  168328. && strncmp(z+i,"true",4)==0
  168329. && !safe_isalnum(z[i+4]) ){
  168330. jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  168331. return i+4;
  168332. }else if( c=='f'
  168333. && strncmp(z+i,"false",5)==0
  168334. && !safe_isalnum(z[i+5]) ){
  168335. jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
  168336. return i+5;
  168337. }else if( c=='-' || (c>='0' && c<='9') ){
  168338. /* Parse number */
  168339. u8 seenDP = 0;
  168340. u8 seenE = 0;
  168341. assert( '-' < '0' );
  168342. if( c<='0' ){
  168343. j = c=='-' ? i+1 : i;
  168344. if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
  168345. }
  168346. j = i+1;
  168347. for(;; j++){
  168348. c = z[j];
  168349. if( c>='0' && c<='9' ) continue;
  168350. if( c=='.' ){
  168351. if( z[j-1]=='-' ) return -1;
  168352. if( seenDP ) return -1;
  168353. seenDP = 1;
  168354. continue;
  168355. }
  168356. if( c=='e' || c=='E' ){
  168357. if( z[j-1]<'0' ) return -1;
  168358. if( seenE ) return -1;
  168359. seenDP = seenE = 1;
  168360. c = z[j+1];
  168361. if( c=='+' || c=='-' ){
  168362. j++;
  168363. c = z[j+1];
  168364. }
  168365. if( c<'0' || c>'9' ) return -1;
  168366. continue;
  168367. }
  168368. break;
  168369. }
  168370. if( z[j-1]<'0' ) return -1;
  168371. jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
  168372. j - i, &z[i]);
  168373. return j;
  168374. }else if( c=='}' ){
  168375. return -2; /* End of {...} */
  168376. }else if( c==']' ){
  168377. return -3; /* End of [...] */
  168378. }else if( c==0 ){
  168379. return 0; /* End of file */
  168380. }else{
  168381. return -1; /* Syntax error */
  168382. }
  168383. }
  168384. /*
  168385. ** Parse a complete JSON string. Return 0 on success or non-zero if there
  168386. ** are any errors. If an error occurs, free all memory associated with
  168387. ** pParse.
  168388. **
  168389. ** pParse is uninitialized when this routine is called.
  168390. */
  168391. static int jsonParse(
  168392. JsonParse *pParse, /* Initialize and fill this JsonParse object */
  168393. sqlite3_context *pCtx, /* Report errors here */
  168394. const char *zJson /* Input JSON text to be parsed */
  168395. ){
  168396. int i;
  168397. memset(pParse, 0, sizeof(*pParse));
  168398. if( zJson==0 ) return 1;
  168399. pParse->zJson = zJson;
  168400. i = jsonParseValue(pParse, 0);
  168401. if( pParse->oom ) i = -1;
  168402. if( i>0 ){
  168403. assert( pParse->iDepth==0 );
  168404. while( safe_isspace(zJson[i]) ) i++;
  168405. if( zJson[i] ) i = -1;
  168406. }
  168407. if( i<=0 ){
  168408. if( pCtx!=0 ){
  168409. if( pParse->oom ){
  168410. sqlite3_result_error_nomem(pCtx);
  168411. }else{
  168412. sqlite3_result_error(pCtx, "malformed JSON", -1);
  168413. }
  168414. }
  168415. jsonParseReset(pParse);
  168416. return 1;
  168417. }
  168418. return 0;
  168419. }
  168420. /* Mark node i of pParse as being a child of iParent. Call recursively
  168421. ** to fill in all the descendants of node i.
  168422. */
  168423. static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
  168424. JsonNode *pNode = &pParse->aNode[i];
  168425. u32 j;
  168426. pParse->aUp[i] = iParent;
  168427. switch( pNode->eType ){
  168428. case JSON_ARRAY: {
  168429. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
  168430. jsonParseFillInParentage(pParse, i+j, i);
  168431. }
  168432. break;
  168433. }
  168434. case JSON_OBJECT: {
  168435. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
  168436. pParse->aUp[i+j] = i;
  168437. jsonParseFillInParentage(pParse, i+j+1, i);
  168438. }
  168439. break;
  168440. }
  168441. default: {
  168442. break;
  168443. }
  168444. }
  168445. }
  168446. /*
  168447. ** Compute the parentage of all nodes in a completed parse.
  168448. */
  168449. static int jsonParseFindParents(JsonParse *pParse){
  168450. u32 *aUp;
  168451. assert( pParse->aUp==0 );
  168452. aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
  168453. if( aUp==0 ){
  168454. pParse->oom = 1;
  168455. return SQLITE_NOMEM;
  168456. }
  168457. jsonParseFillInParentage(pParse, 0, 0);
  168458. return SQLITE_OK;
  168459. }
  168460. /*
  168461. ** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
  168462. */
  168463. #define JSON_CACHE_ID (-429938)
  168464. /*
  168465. ** Obtain a complete parse of the JSON found in the first argument
  168466. ** of the argv array. Use the sqlite3_get_auxdata() cache for this
  168467. ** parse if it is available. If the cache is not available or if it
  168468. ** is no longer valid, parse the JSON again and return the new parse,
  168469. ** and also register the new parse so that it will be available for
  168470. ** future sqlite3_get_auxdata() calls.
  168471. */
  168472. static JsonParse *jsonParseCached(
  168473. sqlite3_context *pCtx,
  168474. sqlite3_value **argv
  168475. ){
  168476. const char *zJson = (const char*)sqlite3_value_text(argv[0]);
  168477. int nJson = sqlite3_value_bytes(argv[0]);
  168478. JsonParse *p;
  168479. if( zJson==0 ) return 0;
  168480. p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
  168481. if( p && p->nJson==nJson && memcmp(p->zJson,zJson,nJson)==0 ){
  168482. p->nErr = 0;
  168483. return p; /* The cached entry matches, so return it */
  168484. }
  168485. p = sqlite3_malloc( sizeof(*p) + nJson + 1 );
  168486. if( p==0 ){
  168487. sqlite3_result_error_nomem(pCtx);
  168488. return 0;
  168489. }
  168490. memset(p, 0, sizeof(*p));
  168491. p->zJson = (char*)&p[1];
  168492. memcpy((char*)p->zJson, zJson, nJson+1);
  168493. if( jsonParse(p, pCtx, p->zJson) ){
  168494. sqlite3_free(p);
  168495. return 0;
  168496. }
  168497. p->nJson = nJson;
  168498. sqlite3_set_auxdata(pCtx, JSON_CACHE_ID, p, (void(*)(void*))jsonParseFree);
  168499. return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
  168500. }
  168501. /*
  168502. ** Compare the OBJECT label at pNode against zKey,nKey. Return true on
  168503. ** a match.
  168504. */
  168505. static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
  168506. if( pNode->jnFlags & JNODE_RAW ){
  168507. if( pNode->n!=nKey ) return 0;
  168508. return strncmp(pNode->u.zJContent, zKey, nKey)==0;
  168509. }else{
  168510. if( pNode->n!=nKey+2 ) return 0;
  168511. return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
  168512. }
  168513. }
  168514. /* forward declaration */
  168515. static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
  168516. /*
  168517. ** Search along zPath to find the node specified. Return a pointer
  168518. ** to that node, or NULL if zPath is malformed or if there is no such
  168519. ** node.
  168520. **
  168521. ** If pApnd!=0, then try to append new nodes to complete zPath if it is
  168522. ** possible to do so and if no existing node corresponds to zPath. If
  168523. ** new nodes are appended *pApnd is set to 1.
  168524. */
  168525. static JsonNode *jsonLookupStep(
  168526. JsonParse *pParse, /* The JSON to search */
  168527. u32 iRoot, /* Begin the search at this node */
  168528. const char *zPath, /* The path to search */
  168529. int *pApnd, /* Append nodes to complete path if not NULL */
  168530. const char **pzErr /* Make *pzErr point to any syntax error in zPath */
  168531. ){
  168532. u32 i, j, nKey;
  168533. const char *zKey;
  168534. JsonNode *pRoot = &pParse->aNode[iRoot];
  168535. if( zPath[0]==0 ) return pRoot;
  168536. if( zPath[0]=='.' ){
  168537. if( pRoot->eType!=JSON_OBJECT ) return 0;
  168538. zPath++;
  168539. if( zPath[0]=='"' ){
  168540. zKey = zPath + 1;
  168541. for(i=1; zPath[i] && zPath[i]!='"'; i++){}
  168542. nKey = i-1;
  168543. if( zPath[i] ){
  168544. i++;
  168545. }else{
  168546. *pzErr = zPath;
  168547. return 0;
  168548. }
  168549. }else{
  168550. zKey = zPath;
  168551. for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
  168552. nKey = i;
  168553. }
  168554. if( nKey==0 ){
  168555. *pzErr = zPath;
  168556. return 0;
  168557. }
  168558. j = 1;
  168559. for(;;){
  168560. while( j<=pRoot->n ){
  168561. if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
  168562. return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
  168563. }
  168564. j++;
  168565. j += jsonNodeSize(&pRoot[j]);
  168566. }
  168567. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  168568. iRoot += pRoot->u.iAppend;
  168569. pRoot = &pParse->aNode[iRoot];
  168570. j = 1;
  168571. }
  168572. if( pApnd ){
  168573. u32 iStart, iLabel;
  168574. JsonNode *pNode;
  168575. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  168576. iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
  168577. zPath += i;
  168578. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  168579. if( pParse->oom ) return 0;
  168580. if( pNode ){
  168581. pRoot = &pParse->aNode[iRoot];
  168582. pRoot->u.iAppend = iStart - iRoot;
  168583. pRoot->jnFlags |= JNODE_APPEND;
  168584. pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
  168585. }
  168586. return pNode;
  168587. }
  168588. }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
  168589. if( pRoot->eType!=JSON_ARRAY ) return 0;
  168590. i = 0;
  168591. j = 1;
  168592. while( safe_isdigit(zPath[j]) ){
  168593. i = i*10 + zPath[j] - '0';
  168594. j++;
  168595. }
  168596. if( zPath[j]!=']' ){
  168597. *pzErr = zPath;
  168598. return 0;
  168599. }
  168600. zPath += j + 1;
  168601. j = 1;
  168602. for(;;){
  168603. while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
  168604. if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
  168605. j += jsonNodeSize(&pRoot[j]);
  168606. }
  168607. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  168608. iRoot += pRoot->u.iAppend;
  168609. pRoot = &pParse->aNode[iRoot];
  168610. j = 1;
  168611. }
  168612. if( j<=pRoot->n ){
  168613. return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
  168614. }
  168615. if( i==0 && pApnd ){
  168616. u32 iStart;
  168617. JsonNode *pNode;
  168618. iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
  168619. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  168620. if( pParse->oom ) return 0;
  168621. if( pNode ){
  168622. pRoot = &pParse->aNode[iRoot];
  168623. pRoot->u.iAppend = iStart - iRoot;
  168624. pRoot->jnFlags |= JNODE_APPEND;
  168625. }
  168626. return pNode;
  168627. }
  168628. }else{
  168629. *pzErr = zPath;
  168630. }
  168631. return 0;
  168632. }
  168633. /*
  168634. ** Append content to pParse that will complete zPath. Return a pointer
  168635. ** to the inserted node, or return NULL if the append fails.
  168636. */
  168637. static JsonNode *jsonLookupAppend(
  168638. JsonParse *pParse, /* Append content to the JSON parse */
  168639. const char *zPath, /* Description of content to append */
  168640. int *pApnd, /* Set this flag to 1 */
  168641. const char **pzErr /* Make this point to any syntax error */
  168642. ){
  168643. *pApnd = 1;
  168644. if( zPath[0]==0 ){
  168645. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  168646. return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
  168647. }
  168648. if( zPath[0]=='.' ){
  168649. jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  168650. }else if( strncmp(zPath,"[0]",3)==0 ){
  168651. jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  168652. }else{
  168653. return 0;
  168654. }
  168655. if( pParse->oom ) return 0;
  168656. return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
  168657. }
  168658. /*
  168659. ** Return the text of a syntax error message on a JSON path. Space is
  168660. ** obtained from sqlite3_malloc().
  168661. */
  168662. static char *jsonPathSyntaxError(const char *zErr){
  168663. return sqlite3_mprintf("JSON path error near '%q'", zErr);
  168664. }
  168665. /*
  168666. ** Do a node lookup using zPath. Return a pointer to the node on success.
  168667. ** Return NULL if not found or if there is an error.
  168668. **
  168669. ** On an error, write an error message into pCtx and increment the
  168670. ** pParse->nErr counter.
  168671. **
  168672. ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
  168673. ** nodes are appended.
  168674. */
  168675. static JsonNode *jsonLookup(
  168676. JsonParse *pParse, /* The JSON to search */
  168677. const char *zPath, /* The path to search */
  168678. int *pApnd, /* Append nodes to complete path if not NULL */
  168679. sqlite3_context *pCtx /* Report errors here, if not NULL */
  168680. ){
  168681. const char *zErr = 0;
  168682. JsonNode *pNode = 0;
  168683. char *zMsg;
  168684. if( zPath==0 ) return 0;
  168685. if( zPath[0]!='$' ){
  168686. zErr = zPath;
  168687. goto lookup_err;
  168688. }
  168689. zPath++;
  168690. pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
  168691. if( zErr==0 ) return pNode;
  168692. lookup_err:
  168693. pParse->nErr++;
  168694. assert( zErr!=0 && pCtx!=0 );
  168695. zMsg = jsonPathSyntaxError(zErr);
  168696. if( zMsg ){
  168697. sqlite3_result_error(pCtx, zMsg, -1);
  168698. sqlite3_free(zMsg);
  168699. }else{
  168700. sqlite3_result_error_nomem(pCtx);
  168701. }
  168702. return 0;
  168703. }
  168704. /*
  168705. ** Report the wrong number of arguments for json_insert(), json_replace()
  168706. ** or json_set().
  168707. */
  168708. static void jsonWrongNumArgs(
  168709. sqlite3_context *pCtx,
  168710. const char *zFuncName
  168711. ){
  168712. char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
  168713. zFuncName);
  168714. sqlite3_result_error(pCtx, zMsg, -1);
  168715. sqlite3_free(zMsg);
  168716. }
  168717. /*
  168718. ** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
  168719. */
  168720. static void jsonRemoveAllNulls(JsonNode *pNode){
  168721. int i, n;
  168722. assert( pNode->eType==JSON_OBJECT );
  168723. n = pNode->n;
  168724. for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
  168725. switch( pNode[i].eType ){
  168726. case JSON_NULL:
  168727. pNode[i].jnFlags |= JNODE_REMOVE;
  168728. break;
  168729. case JSON_OBJECT:
  168730. jsonRemoveAllNulls(&pNode[i]);
  168731. break;
  168732. }
  168733. }
  168734. }
  168735. /****************************************************************************
  168736. ** SQL functions used for testing and debugging
  168737. ****************************************************************************/
  168738. #ifdef SQLITE_DEBUG
  168739. /*
  168740. ** The json_parse(JSON) function returns a string which describes
  168741. ** a parse of the JSON provided. Or it returns NULL if JSON is not
  168742. ** well-formed.
  168743. */
  168744. static void jsonParseFunc(
  168745. sqlite3_context *ctx,
  168746. int argc,
  168747. sqlite3_value **argv
  168748. ){
  168749. JsonString s; /* Output string - not real JSON */
  168750. JsonParse x; /* The parse */
  168751. u32 i;
  168752. assert( argc==1 );
  168753. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  168754. jsonParseFindParents(&x);
  168755. jsonInit(&s, ctx);
  168756. for(i=0; i<x.nNode; i++){
  168757. const char *zType;
  168758. if( x.aNode[i].jnFlags & JNODE_LABEL ){
  168759. assert( x.aNode[i].eType==JSON_STRING );
  168760. zType = "label";
  168761. }else{
  168762. zType = jsonType[x.aNode[i].eType];
  168763. }
  168764. jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
  168765. i, zType, x.aNode[i].n, x.aUp[i]);
  168766. if( x.aNode[i].u.zJContent!=0 ){
  168767. jsonAppendRaw(&s, " ", 1);
  168768. jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
  168769. }
  168770. jsonAppendRaw(&s, "\n", 1);
  168771. }
  168772. jsonParseReset(&x);
  168773. jsonResult(&s);
  168774. }
  168775. /*
  168776. ** The json_test1(JSON) function return true (1) if the input is JSON
  168777. ** text generated by another json function. It returns (0) if the input
  168778. ** is not known to be JSON.
  168779. */
  168780. static void jsonTest1Func(
  168781. sqlite3_context *ctx,
  168782. int argc,
  168783. sqlite3_value **argv
  168784. ){
  168785. UNUSED_PARAM(argc);
  168786. sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
  168787. }
  168788. #endif /* SQLITE_DEBUG */
  168789. /****************************************************************************
  168790. ** Scalar SQL function implementations
  168791. ****************************************************************************/
  168792. /*
  168793. ** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
  168794. ** corresponding to the SQL value input. Mostly this means putting
  168795. ** double-quotes around strings and returning the unquoted string "null"
  168796. ** when given a NULL input.
  168797. */
  168798. static void jsonQuoteFunc(
  168799. sqlite3_context *ctx,
  168800. int argc,
  168801. sqlite3_value **argv
  168802. ){
  168803. JsonString jx;
  168804. UNUSED_PARAM(argc);
  168805. jsonInit(&jx, ctx);
  168806. jsonAppendValue(&jx, argv[0]);
  168807. jsonResult(&jx);
  168808. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  168809. }
  168810. /*
  168811. ** Implementation of the json_array(VALUE,...) function. Return a JSON
  168812. ** array that contains all values given in arguments. Or if any argument
  168813. ** is a BLOB, throw an error.
  168814. */
  168815. static void jsonArrayFunc(
  168816. sqlite3_context *ctx,
  168817. int argc,
  168818. sqlite3_value **argv
  168819. ){
  168820. int i;
  168821. JsonString jx;
  168822. jsonInit(&jx, ctx);
  168823. jsonAppendChar(&jx, '[');
  168824. for(i=0; i<argc; i++){
  168825. jsonAppendSeparator(&jx);
  168826. jsonAppendValue(&jx, argv[i]);
  168827. }
  168828. jsonAppendChar(&jx, ']');
  168829. jsonResult(&jx);
  168830. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  168831. }
  168832. /*
  168833. ** json_array_length(JSON)
  168834. ** json_array_length(JSON, PATH)
  168835. **
  168836. ** Return the number of elements in the top-level JSON array.
  168837. ** Return 0 if the input is not a well-formed JSON array.
  168838. */
  168839. static void jsonArrayLengthFunc(
  168840. sqlite3_context *ctx,
  168841. int argc,
  168842. sqlite3_value **argv
  168843. ){
  168844. JsonParse *p; /* The parse */
  168845. sqlite3_int64 n = 0;
  168846. u32 i;
  168847. JsonNode *pNode;
  168848. p = jsonParseCached(ctx, argv);
  168849. if( p==0 ) return;
  168850. assert( p->nNode );
  168851. if( argc==2 ){
  168852. const char *zPath = (const char*)sqlite3_value_text(argv[1]);
  168853. pNode = jsonLookup(p, zPath, 0, ctx);
  168854. }else{
  168855. pNode = p->aNode;
  168856. }
  168857. if( pNode==0 ){
  168858. return;
  168859. }
  168860. if( pNode->eType==JSON_ARRAY ){
  168861. assert( (pNode->jnFlags & JNODE_APPEND)==0 );
  168862. for(i=1; i<=pNode->n; n++){
  168863. i += jsonNodeSize(&pNode[i]);
  168864. }
  168865. }
  168866. sqlite3_result_int64(ctx, n);
  168867. }
  168868. /*
  168869. ** json_extract(JSON, PATH, ...)
  168870. **
  168871. ** Return the element described by PATH. Return NULL if there is no
  168872. ** PATH element. If there are multiple PATHs, then return a JSON array
  168873. ** with the result from each path. Throw an error if the JSON or any PATH
  168874. ** is malformed.
  168875. */
  168876. static void jsonExtractFunc(
  168877. sqlite3_context *ctx,
  168878. int argc,
  168879. sqlite3_value **argv
  168880. ){
  168881. JsonParse *p; /* The parse */
  168882. JsonNode *pNode;
  168883. const char *zPath;
  168884. JsonString jx;
  168885. int i;
  168886. if( argc<2 ) return;
  168887. p = jsonParseCached(ctx, argv);
  168888. if( p==0 ) return;
  168889. jsonInit(&jx, ctx);
  168890. jsonAppendChar(&jx, '[');
  168891. for(i=1; i<argc; i++){
  168892. zPath = (const char*)sqlite3_value_text(argv[i]);
  168893. pNode = jsonLookup(p, zPath, 0, ctx);
  168894. if( p->nErr ) break;
  168895. if( argc>2 ){
  168896. jsonAppendSeparator(&jx);
  168897. if( pNode ){
  168898. jsonRenderNode(pNode, &jx, 0);
  168899. }else{
  168900. jsonAppendRaw(&jx, "null", 4);
  168901. }
  168902. }else if( pNode ){
  168903. jsonReturn(pNode, ctx, 0);
  168904. }
  168905. }
  168906. if( argc>2 && i==argc ){
  168907. jsonAppendChar(&jx, ']');
  168908. jsonResult(&jx);
  168909. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  168910. }
  168911. jsonReset(&jx);
  168912. }
  168913. /* This is the RFC 7396 MergePatch algorithm.
  168914. */
  168915. static JsonNode *jsonMergePatch(
  168916. JsonParse *pParse, /* The JSON parser that contains the TARGET */
  168917. u32 iTarget, /* Node of the TARGET in pParse */
  168918. JsonNode *pPatch /* The PATCH */
  168919. ){
  168920. u32 i, j;
  168921. u32 iRoot;
  168922. JsonNode *pTarget;
  168923. if( pPatch->eType!=JSON_OBJECT ){
  168924. return pPatch;
  168925. }
  168926. assert( iTarget>=0 && iTarget<pParse->nNode );
  168927. pTarget = &pParse->aNode[iTarget];
  168928. assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
  168929. if( pTarget->eType!=JSON_OBJECT ){
  168930. jsonRemoveAllNulls(pPatch);
  168931. return pPatch;
  168932. }
  168933. iRoot = iTarget;
  168934. for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
  168935. u32 nKey;
  168936. const char *zKey;
  168937. assert( pPatch[i].eType==JSON_STRING );
  168938. assert( pPatch[i].jnFlags & JNODE_LABEL );
  168939. nKey = pPatch[i].n;
  168940. zKey = pPatch[i].u.zJContent;
  168941. assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  168942. for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
  168943. assert( pTarget[j].eType==JSON_STRING );
  168944. assert( pTarget[j].jnFlags & JNODE_LABEL );
  168945. assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  168946. if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
  168947. if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
  168948. if( pPatch[i+1].eType==JSON_NULL ){
  168949. pTarget[j+1].jnFlags |= JNODE_REMOVE;
  168950. }else{
  168951. JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
  168952. if( pNew==0 ) return 0;
  168953. pTarget = &pParse->aNode[iTarget];
  168954. if( pNew!=&pTarget[j+1] ){
  168955. pTarget[j+1].u.pPatch = pNew;
  168956. pTarget[j+1].jnFlags |= JNODE_PATCH;
  168957. }
  168958. }
  168959. break;
  168960. }
  168961. }
  168962. if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
  168963. int iStart, iPatch;
  168964. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  168965. jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
  168966. iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  168967. if( pParse->oom ) return 0;
  168968. jsonRemoveAllNulls(pPatch);
  168969. pTarget = &pParse->aNode[iTarget];
  168970. pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
  168971. pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
  168972. iRoot = iStart;
  168973. pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
  168974. pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
  168975. }
  168976. }
  168977. return pTarget;
  168978. }
  168979. /*
  168980. ** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
  168981. ** object that is the result of running the RFC 7396 MergePatch() algorithm
  168982. ** on the two arguments.
  168983. */
  168984. static void jsonPatchFunc(
  168985. sqlite3_context *ctx,
  168986. int argc,
  168987. sqlite3_value **argv
  168988. ){
  168989. JsonParse x; /* The JSON that is being patched */
  168990. JsonParse y; /* The patch */
  168991. JsonNode *pResult; /* The result of the merge */
  168992. UNUSED_PARAM(argc);
  168993. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  168994. if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
  168995. jsonParseReset(&x);
  168996. return;
  168997. }
  168998. pResult = jsonMergePatch(&x, 0, y.aNode);
  168999. assert( pResult!=0 || x.oom );
  169000. if( pResult ){
  169001. jsonReturnJson(pResult, ctx, 0);
  169002. }else{
  169003. sqlite3_result_error_nomem(ctx);
  169004. }
  169005. jsonParseReset(&x);
  169006. jsonParseReset(&y);
  169007. }
  169008. /*
  169009. ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
  169010. ** object that contains all name/value given in arguments. Or if any name
  169011. ** is not a string or if any value is a BLOB, throw an error.
  169012. */
  169013. static void jsonObjectFunc(
  169014. sqlite3_context *ctx,
  169015. int argc,
  169016. sqlite3_value **argv
  169017. ){
  169018. int i;
  169019. JsonString jx;
  169020. const char *z;
  169021. u32 n;
  169022. if( argc&1 ){
  169023. sqlite3_result_error(ctx, "json_object() requires an even number "
  169024. "of arguments", -1);
  169025. return;
  169026. }
  169027. jsonInit(&jx, ctx);
  169028. jsonAppendChar(&jx, '{');
  169029. for(i=0; i<argc; i+=2){
  169030. if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
  169031. sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
  169032. jsonReset(&jx);
  169033. return;
  169034. }
  169035. jsonAppendSeparator(&jx);
  169036. z = (const char*)sqlite3_value_text(argv[i]);
  169037. n = (u32)sqlite3_value_bytes(argv[i]);
  169038. jsonAppendString(&jx, z, n);
  169039. jsonAppendChar(&jx, ':');
  169040. jsonAppendValue(&jx, argv[i+1]);
  169041. }
  169042. jsonAppendChar(&jx, '}');
  169043. jsonResult(&jx);
  169044. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  169045. }
  169046. /*
  169047. ** json_remove(JSON, PATH, ...)
  169048. **
  169049. ** Remove the named elements from JSON and return the result. malformed
  169050. ** JSON or PATH arguments result in an error.
  169051. */
  169052. static void jsonRemoveFunc(
  169053. sqlite3_context *ctx,
  169054. int argc,
  169055. sqlite3_value **argv
  169056. ){
  169057. JsonParse x; /* The parse */
  169058. JsonNode *pNode;
  169059. const char *zPath;
  169060. u32 i;
  169061. if( argc<1 ) return;
  169062. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  169063. assert( x.nNode );
  169064. for(i=1; i<(u32)argc; i++){
  169065. zPath = (const char*)sqlite3_value_text(argv[i]);
  169066. if( zPath==0 ) goto remove_done;
  169067. pNode = jsonLookup(&x, zPath, 0, ctx);
  169068. if( x.nErr ) goto remove_done;
  169069. if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
  169070. }
  169071. if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
  169072. jsonReturnJson(x.aNode, ctx, 0);
  169073. }
  169074. remove_done:
  169075. jsonParseReset(&x);
  169076. }
  169077. /*
  169078. ** json_replace(JSON, PATH, VALUE, ...)
  169079. **
  169080. ** Replace the value at PATH with VALUE. If PATH does not already exist,
  169081. ** this routine is a no-op. If JSON or PATH is malformed, throw an error.
  169082. */
  169083. static void jsonReplaceFunc(
  169084. sqlite3_context *ctx,
  169085. int argc,
  169086. sqlite3_value **argv
  169087. ){
  169088. JsonParse x; /* The parse */
  169089. JsonNode *pNode;
  169090. const char *zPath;
  169091. u32 i;
  169092. if( argc<1 ) return;
  169093. if( (argc&1)==0 ) {
  169094. jsonWrongNumArgs(ctx, "replace");
  169095. return;
  169096. }
  169097. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  169098. assert( x.nNode );
  169099. for(i=1; i<(u32)argc; i+=2){
  169100. zPath = (const char*)sqlite3_value_text(argv[i]);
  169101. pNode = jsonLookup(&x, zPath, 0, ctx);
  169102. if( x.nErr ) goto replace_err;
  169103. if( pNode ){
  169104. pNode->jnFlags |= (u8)JNODE_REPLACE;
  169105. pNode->u.iReplace = i + 1;
  169106. }
  169107. }
  169108. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  169109. sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  169110. }else{
  169111. jsonReturnJson(x.aNode, ctx, argv);
  169112. }
  169113. replace_err:
  169114. jsonParseReset(&x);
  169115. }
  169116. /*
  169117. ** json_set(JSON, PATH, VALUE, ...)
  169118. **
  169119. ** Set the value at PATH to VALUE. Create the PATH if it does not already
  169120. ** exist. Overwrite existing values that do exist.
  169121. ** If JSON or PATH is malformed, throw an error.
  169122. **
  169123. ** json_insert(JSON, PATH, VALUE, ...)
  169124. **
  169125. ** Create PATH and initialize it to VALUE. If PATH already exists, this
  169126. ** routine is a no-op. If JSON or PATH is malformed, throw an error.
  169127. */
  169128. static void jsonSetFunc(
  169129. sqlite3_context *ctx,
  169130. int argc,
  169131. sqlite3_value **argv
  169132. ){
  169133. JsonParse x; /* The parse */
  169134. JsonNode *pNode;
  169135. const char *zPath;
  169136. u32 i;
  169137. int bApnd;
  169138. int bIsSet = *(int*)sqlite3_user_data(ctx);
  169139. if( argc<1 ) return;
  169140. if( (argc&1)==0 ) {
  169141. jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
  169142. return;
  169143. }
  169144. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  169145. assert( x.nNode );
  169146. for(i=1; i<(u32)argc; i+=2){
  169147. zPath = (const char*)sqlite3_value_text(argv[i]);
  169148. bApnd = 0;
  169149. pNode = jsonLookup(&x, zPath, &bApnd, ctx);
  169150. if( x.oom ){
  169151. sqlite3_result_error_nomem(ctx);
  169152. goto jsonSetDone;
  169153. }else if( x.nErr ){
  169154. goto jsonSetDone;
  169155. }else if( pNode && (bApnd || bIsSet) ){
  169156. pNode->jnFlags |= (u8)JNODE_REPLACE;
  169157. pNode->u.iReplace = i + 1;
  169158. }
  169159. }
  169160. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  169161. sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  169162. }else{
  169163. jsonReturnJson(x.aNode, ctx, argv);
  169164. }
  169165. jsonSetDone:
  169166. jsonParseReset(&x);
  169167. }
  169168. /*
  169169. ** json_type(JSON)
  169170. ** json_type(JSON, PATH)
  169171. **
  169172. ** Return the top-level "type" of a JSON string. Throw an error if
  169173. ** either the JSON or PATH inputs are not well-formed.
  169174. */
  169175. static void jsonTypeFunc(
  169176. sqlite3_context *ctx,
  169177. int argc,
  169178. sqlite3_value **argv
  169179. ){
  169180. JsonParse x; /* The parse */
  169181. const char *zPath;
  169182. JsonNode *pNode;
  169183. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  169184. assert( x.nNode );
  169185. if( argc==2 ){
  169186. zPath = (const char*)sqlite3_value_text(argv[1]);
  169187. pNode = jsonLookup(&x, zPath, 0, ctx);
  169188. }else{
  169189. pNode = x.aNode;
  169190. }
  169191. if( pNode ){
  169192. sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
  169193. }
  169194. jsonParseReset(&x);
  169195. }
  169196. /*
  169197. ** json_valid(JSON)
  169198. **
  169199. ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
  169200. ** Return 0 otherwise.
  169201. */
  169202. static void jsonValidFunc(
  169203. sqlite3_context *ctx,
  169204. int argc,
  169205. sqlite3_value **argv
  169206. ){
  169207. JsonParse x; /* The parse */
  169208. int rc = 0;
  169209. UNUSED_PARAM(argc);
  169210. if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
  169211. rc = 1;
  169212. }
  169213. jsonParseReset(&x);
  169214. sqlite3_result_int(ctx, rc);
  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 jsonArrayFinal(sqlite3_context *ctx){
  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{
  169253. sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
  169254. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  169255. pStr->bStatic = 1;
  169256. }
  169257. }else{
  169258. sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
  169259. }
  169260. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  169261. }
  169262. /*
  169263. ** json_group_obj(NAME,VALUE)
  169264. **
  169265. ** Return a JSON object composed of all names and values in the aggregate.
  169266. */
  169267. static void jsonObjectStep(
  169268. sqlite3_context *ctx,
  169269. int argc,
  169270. sqlite3_value **argv
  169271. ){
  169272. JsonString *pStr;
  169273. const char *z;
  169274. u32 n;
  169275. UNUSED_PARAM(argc);
  169276. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  169277. if( pStr ){
  169278. if( pStr->zBuf==0 ){
  169279. jsonInit(pStr, ctx);
  169280. jsonAppendChar(pStr, '{');
  169281. }else{
  169282. jsonAppendChar(pStr, ',');
  169283. pStr->pCtx = ctx;
  169284. }
  169285. z = (const char*)sqlite3_value_text(argv[0]);
  169286. n = (u32)sqlite3_value_bytes(argv[0]);
  169287. jsonAppendString(pStr, z, n);
  169288. jsonAppendChar(pStr, ':');
  169289. jsonAppendValue(pStr, argv[1]);
  169290. }
  169291. }
  169292. static void jsonObjectFinal(sqlite3_context *ctx){
  169293. JsonString *pStr;
  169294. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  169295. if( pStr ){
  169296. jsonAppendChar(pStr, '}');
  169297. if( pStr->bErr ){
  169298. if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  169299. assert( pStr->bStatic );
  169300. }else{
  169301. sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
  169302. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  169303. pStr->bStatic = 1;
  169304. }
  169305. }else{
  169306. sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
  169307. }
  169308. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  169309. }
  169310. #ifndef SQLITE_OMIT_VIRTUALTABLE
  169311. /****************************************************************************
  169312. ** The json_each virtual table
  169313. ****************************************************************************/
  169314. typedef struct JsonEachCursor JsonEachCursor;
  169315. struct JsonEachCursor {
  169316. sqlite3_vtab_cursor base; /* Base class - must be first */
  169317. u32 iRowid; /* The rowid */
  169318. u32 iBegin; /* The first node of the scan */
  169319. u32 i; /* Index in sParse.aNode[] of current row */
  169320. u32 iEnd; /* EOF when i equals or exceeds this value */
  169321. u8 eType; /* Type of top-level element */
  169322. u8 bRecursive; /* True for json_tree(). False for json_each() */
  169323. char *zJson; /* Input JSON */
  169324. char *zRoot; /* Path by which to filter zJson */
  169325. JsonParse sParse; /* Parse of the input JSON */
  169326. };
  169327. /* Constructor for the json_each virtual table */
  169328. static int jsonEachConnect(
  169329. sqlite3 *db,
  169330. void *pAux,
  169331. int argc, const char *const*argv,
  169332. sqlite3_vtab **ppVtab,
  169333. char **pzErr
  169334. ){
  169335. sqlite3_vtab *pNew;
  169336. int rc;
  169337. /* Column numbers */
  169338. #define JEACH_KEY 0
  169339. #define JEACH_VALUE 1
  169340. #define JEACH_TYPE 2
  169341. #define JEACH_ATOM 3
  169342. #define JEACH_ID 4
  169343. #define JEACH_PARENT 5
  169344. #define JEACH_FULLKEY 6
  169345. #define JEACH_PATH 7
  169346. #define JEACH_JSON 8
  169347. #define JEACH_ROOT 9
  169348. UNUSED_PARAM(pzErr);
  169349. UNUSED_PARAM(argv);
  169350. UNUSED_PARAM(argc);
  169351. UNUSED_PARAM(pAux);
  169352. rc = sqlite3_declare_vtab(db,
  169353. "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
  169354. "json HIDDEN,root HIDDEN)");
  169355. if( rc==SQLITE_OK ){
  169356. pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
  169357. if( pNew==0 ) return SQLITE_NOMEM;
  169358. memset(pNew, 0, sizeof(*pNew));
  169359. }
  169360. return rc;
  169361. }
  169362. /* destructor for json_each virtual table */
  169363. static int jsonEachDisconnect(sqlite3_vtab *pVtab){
  169364. sqlite3_free(pVtab);
  169365. return SQLITE_OK;
  169366. }
  169367. /* constructor for a JsonEachCursor object for json_each(). */
  169368. static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  169369. JsonEachCursor *pCur;
  169370. UNUSED_PARAM(p);
  169371. pCur = sqlite3_malloc( sizeof(*pCur) );
  169372. if( pCur==0 ) return SQLITE_NOMEM;
  169373. memset(pCur, 0, sizeof(*pCur));
  169374. *ppCursor = &pCur->base;
  169375. return SQLITE_OK;
  169376. }
  169377. /* constructor for a JsonEachCursor object for json_tree(). */
  169378. static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  169379. int rc = jsonEachOpenEach(p, ppCursor);
  169380. if( rc==SQLITE_OK ){
  169381. JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
  169382. pCur->bRecursive = 1;
  169383. }
  169384. return rc;
  169385. }
  169386. /* Reset a JsonEachCursor back to its original state. Free any memory
  169387. ** held. */
  169388. static void jsonEachCursorReset(JsonEachCursor *p){
  169389. sqlite3_free(p->zJson);
  169390. sqlite3_free(p->zRoot);
  169391. jsonParseReset(&p->sParse);
  169392. p->iRowid = 0;
  169393. p->i = 0;
  169394. p->iEnd = 0;
  169395. p->eType = 0;
  169396. p->zJson = 0;
  169397. p->zRoot = 0;
  169398. }
  169399. /* Destructor for a jsonEachCursor object */
  169400. static int jsonEachClose(sqlite3_vtab_cursor *cur){
  169401. JsonEachCursor *p = (JsonEachCursor*)cur;
  169402. jsonEachCursorReset(p);
  169403. sqlite3_free(cur);
  169404. return SQLITE_OK;
  169405. }
  169406. /* Return TRUE if the jsonEachCursor object has been advanced off the end
  169407. ** of the JSON object */
  169408. static int jsonEachEof(sqlite3_vtab_cursor *cur){
  169409. JsonEachCursor *p = (JsonEachCursor*)cur;
  169410. return p->i >= p->iEnd;
  169411. }
  169412. /* Advance the cursor to the next element for json_tree() */
  169413. static int jsonEachNext(sqlite3_vtab_cursor *cur){
  169414. JsonEachCursor *p = (JsonEachCursor*)cur;
  169415. if( p->bRecursive ){
  169416. if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
  169417. p->i++;
  169418. p->iRowid++;
  169419. if( p->i<p->iEnd ){
  169420. u32 iUp = p->sParse.aUp[p->i];
  169421. JsonNode *pUp = &p->sParse.aNode[iUp];
  169422. p->eType = pUp->eType;
  169423. if( pUp->eType==JSON_ARRAY ){
  169424. if( iUp==p->i-1 ){
  169425. pUp->u.iKey = 0;
  169426. }else{
  169427. pUp->u.iKey++;
  169428. }
  169429. }
  169430. }
  169431. }else{
  169432. switch( p->eType ){
  169433. case JSON_ARRAY: {
  169434. p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
  169435. p->iRowid++;
  169436. break;
  169437. }
  169438. case JSON_OBJECT: {
  169439. p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
  169440. p->iRowid++;
  169441. break;
  169442. }
  169443. default: {
  169444. p->i = p->iEnd;
  169445. break;
  169446. }
  169447. }
  169448. }
  169449. return SQLITE_OK;
  169450. }
  169451. /* Append the name of the path for element i to pStr
  169452. */
  169453. static void jsonEachComputePath(
  169454. JsonEachCursor *p, /* The cursor */
  169455. JsonString *pStr, /* Write the path here */
  169456. u32 i /* Path to this element */
  169457. ){
  169458. JsonNode *pNode, *pUp;
  169459. u32 iUp;
  169460. if( i==0 ){
  169461. jsonAppendChar(pStr, '$');
  169462. return;
  169463. }
  169464. iUp = p->sParse.aUp[i];
  169465. jsonEachComputePath(p, pStr, iUp);
  169466. pNode = &p->sParse.aNode[i];
  169467. pUp = &p->sParse.aNode[iUp];
  169468. if( pUp->eType==JSON_ARRAY ){
  169469. jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
  169470. }else{
  169471. assert( pUp->eType==JSON_OBJECT );
  169472. if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
  169473. assert( pNode->eType==JSON_STRING );
  169474. assert( pNode->jnFlags & JNODE_LABEL );
  169475. jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
  169476. }
  169477. }
  169478. /* Return the value of a column */
  169479. static int jsonEachColumn(
  169480. sqlite3_vtab_cursor *cur, /* The cursor */
  169481. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  169482. int i /* Which column to return */
  169483. ){
  169484. JsonEachCursor *p = (JsonEachCursor*)cur;
  169485. JsonNode *pThis = &p->sParse.aNode[p->i];
  169486. switch( i ){
  169487. case JEACH_KEY: {
  169488. if( p->i==0 ) break;
  169489. if( p->eType==JSON_OBJECT ){
  169490. jsonReturn(pThis, ctx, 0);
  169491. }else if( p->eType==JSON_ARRAY ){
  169492. u32 iKey;
  169493. if( p->bRecursive ){
  169494. if( p->iRowid==0 ) break;
  169495. iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
  169496. }else{
  169497. iKey = p->iRowid;
  169498. }
  169499. sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
  169500. }
  169501. break;
  169502. }
  169503. case JEACH_VALUE: {
  169504. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  169505. jsonReturn(pThis, ctx, 0);
  169506. break;
  169507. }
  169508. case JEACH_TYPE: {
  169509. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  169510. sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
  169511. break;
  169512. }
  169513. case JEACH_ATOM: {
  169514. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  169515. if( pThis->eType>=JSON_ARRAY ) break;
  169516. jsonReturn(pThis, ctx, 0);
  169517. break;
  169518. }
  169519. case JEACH_ID: {
  169520. sqlite3_result_int64(ctx,
  169521. (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
  169522. break;
  169523. }
  169524. case JEACH_PARENT: {
  169525. if( p->i>p->iBegin && p->bRecursive ){
  169526. sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
  169527. }
  169528. break;
  169529. }
  169530. case JEACH_FULLKEY: {
  169531. JsonString x;
  169532. jsonInit(&x, ctx);
  169533. if( p->bRecursive ){
  169534. jsonEachComputePath(p, &x, p->i);
  169535. }else{
  169536. if( p->zRoot ){
  169537. jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
  169538. }else{
  169539. jsonAppendChar(&x, '$');
  169540. }
  169541. if( p->eType==JSON_ARRAY ){
  169542. jsonPrintf(30, &x, "[%d]", p->iRowid);
  169543. }else{
  169544. jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
  169545. }
  169546. }
  169547. jsonResult(&x);
  169548. break;
  169549. }
  169550. case JEACH_PATH: {
  169551. if( p->bRecursive ){
  169552. JsonString x;
  169553. jsonInit(&x, ctx);
  169554. jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
  169555. jsonResult(&x);
  169556. break;
  169557. }
  169558. /* For json_each() path and root are the same so fall through
  169559. ** into the root case */
  169560. }
  169561. default: {
  169562. const char *zRoot = p->zRoot;
  169563. if( zRoot==0 ) zRoot = "$";
  169564. sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
  169565. break;
  169566. }
  169567. case JEACH_JSON: {
  169568. assert( i==JEACH_JSON );
  169569. sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
  169570. break;
  169571. }
  169572. }
  169573. return SQLITE_OK;
  169574. }
  169575. /* Return the current rowid value */
  169576. static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  169577. JsonEachCursor *p = (JsonEachCursor*)cur;
  169578. *pRowid = p->iRowid;
  169579. return SQLITE_OK;
  169580. }
  169581. /* The query strategy is to look for an equality constraint on the json
  169582. ** column. Without such a constraint, the table cannot operate. idxNum is
  169583. ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
  169584. ** and 0 otherwise.
  169585. */
  169586. static int jsonEachBestIndex(
  169587. sqlite3_vtab *tab,
  169588. sqlite3_index_info *pIdxInfo
  169589. ){
  169590. int i;
  169591. int jsonIdx = -1;
  169592. int rootIdx = -1;
  169593. const struct sqlite3_index_constraint *pConstraint;
  169594. UNUSED_PARAM(tab);
  169595. pConstraint = pIdxInfo->aConstraint;
  169596. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  169597. if( pConstraint->usable==0 ) continue;
  169598. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  169599. switch( pConstraint->iColumn ){
  169600. case JEACH_JSON: jsonIdx = i; break;
  169601. case JEACH_ROOT: rootIdx = i; break;
  169602. default: /* no-op */ break;
  169603. }
  169604. }
  169605. if( jsonIdx<0 ){
  169606. pIdxInfo->idxNum = 0;
  169607. pIdxInfo->estimatedCost = 1e99;
  169608. }else{
  169609. pIdxInfo->estimatedCost = 1.0;
  169610. pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
  169611. pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
  169612. if( rootIdx<0 ){
  169613. pIdxInfo->idxNum = 1;
  169614. }else{
  169615. pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
  169616. pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
  169617. pIdxInfo->idxNum = 3;
  169618. }
  169619. }
  169620. return SQLITE_OK;
  169621. }
  169622. /* Start a search on a new JSON string */
  169623. static int jsonEachFilter(
  169624. sqlite3_vtab_cursor *cur,
  169625. int idxNum, const char *idxStr,
  169626. int argc, sqlite3_value **argv
  169627. ){
  169628. JsonEachCursor *p = (JsonEachCursor*)cur;
  169629. const char *z;
  169630. const char *zRoot = 0;
  169631. sqlite3_int64 n;
  169632. UNUSED_PARAM(idxStr);
  169633. UNUSED_PARAM(argc);
  169634. jsonEachCursorReset(p);
  169635. if( idxNum==0 ) return SQLITE_OK;
  169636. z = (const char*)sqlite3_value_text(argv[0]);
  169637. if( z==0 ) return SQLITE_OK;
  169638. n = sqlite3_value_bytes(argv[0]);
  169639. p->zJson = sqlite3_malloc64( n+1 );
  169640. if( p->zJson==0 ) return SQLITE_NOMEM;
  169641. memcpy(p->zJson, z, (size_t)n+1);
  169642. if( jsonParse(&p->sParse, 0, p->zJson) ){
  169643. int rc = SQLITE_NOMEM;
  169644. if( p->sParse.oom==0 ){
  169645. sqlite3_free(cur->pVtab->zErrMsg);
  169646. cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
  169647. if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
  169648. }
  169649. jsonEachCursorReset(p);
  169650. return rc;
  169651. }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
  169652. jsonEachCursorReset(p);
  169653. return SQLITE_NOMEM;
  169654. }else{
  169655. JsonNode *pNode = 0;
  169656. if( idxNum==3 ){
  169657. const char *zErr = 0;
  169658. zRoot = (const char*)sqlite3_value_text(argv[1]);
  169659. if( zRoot==0 ) return SQLITE_OK;
  169660. n = sqlite3_value_bytes(argv[1]);
  169661. p->zRoot = sqlite3_malloc64( n+1 );
  169662. if( p->zRoot==0 ) return SQLITE_NOMEM;
  169663. memcpy(p->zRoot, zRoot, (size_t)n+1);
  169664. if( zRoot[0]!='$' ){
  169665. zErr = zRoot;
  169666. }else{
  169667. pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
  169668. }
  169669. if( zErr ){
  169670. sqlite3_free(cur->pVtab->zErrMsg);
  169671. cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
  169672. jsonEachCursorReset(p);
  169673. return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
  169674. }else if( pNode==0 ){
  169675. return SQLITE_OK;
  169676. }
  169677. }else{
  169678. pNode = p->sParse.aNode;
  169679. }
  169680. p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
  169681. p->eType = pNode->eType;
  169682. if( p->eType>=JSON_ARRAY ){
  169683. pNode->u.iKey = 0;
  169684. p->iEnd = p->i + pNode->n + 1;
  169685. if( p->bRecursive ){
  169686. p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
  169687. if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
  169688. p->i--;
  169689. }
  169690. }else{
  169691. p->i++;
  169692. }
  169693. }else{
  169694. p->iEnd = p->i+1;
  169695. }
  169696. }
  169697. return SQLITE_OK;
  169698. }
  169699. /* The methods of the json_each virtual table */
  169700. static sqlite3_module jsonEachModule = {
  169701. 0, /* iVersion */
  169702. 0, /* xCreate */
  169703. jsonEachConnect, /* xConnect */
  169704. jsonEachBestIndex, /* xBestIndex */
  169705. jsonEachDisconnect, /* xDisconnect */
  169706. 0, /* xDestroy */
  169707. jsonEachOpenEach, /* xOpen - open a cursor */
  169708. jsonEachClose, /* xClose - close a cursor */
  169709. jsonEachFilter, /* xFilter - configure scan constraints */
  169710. jsonEachNext, /* xNext - advance a cursor */
  169711. jsonEachEof, /* xEof - check for end of scan */
  169712. jsonEachColumn, /* xColumn - read data */
  169713. jsonEachRowid, /* xRowid - read data */
  169714. 0, /* xUpdate */
  169715. 0, /* xBegin */
  169716. 0, /* xSync */
  169717. 0, /* xCommit */
  169718. 0, /* xRollback */
  169719. 0, /* xFindMethod */
  169720. 0, /* xRename */
  169721. 0, /* xSavepoint */
  169722. 0, /* xRelease */
  169723. 0 /* xRollbackTo */
  169724. };
  169725. /* The methods of the json_tree virtual table. */
  169726. static sqlite3_module jsonTreeModule = {
  169727. 0, /* iVersion */
  169728. 0, /* xCreate */
  169729. jsonEachConnect, /* xConnect */
  169730. jsonEachBestIndex, /* xBestIndex */
  169731. jsonEachDisconnect, /* xDisconnect */
  169732. 0, /* xDestroy */
  169733. jsonEachOpenTree, /* xOpen - open a cursor */
  169734. jsonEachClose, /* xClose - close a cursor */
  169735. jsonEachFilter, /* xFilter - configure scan constraints */
  169736. jsonEachNext, /* xNext - advance a cursor */
  169737. jsonEachEof, /* xEof - check for end of scan */
  169738. jsonEachColumn, /* xColumn - read data */
  169739. jsonEachRowid, /* xRowid - read data */
  169740. 0, /* xUpdate */
  169741. 0, /* xBegin */
  169742. 0, /* xSync */
  169743. 0, /* xCommit */
  169744. 0, /* xRollback */
  169745. 0, /* xFindMethod */
  169746. 0, /* xRename */
  169747. 0, /* xSavepoint */
  169748. 0, /* xRelease */
  169749. 0 /* xRollbackTo */
  169750. };
  169751. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  169752. /****************************************************************************
  169753. ** The following routines are the only publically visible identifiers in this
  169754. ** file. Call the following routines in order to register the various SQL
  169755. ** functions and the virtual table implemented by this file.
  169756. ****************************************************************************/
  169757. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
  169758. int rc = SQLITE_OK;
  169759. unsigned int i;
  169760. static const struct {
  169761. const char *zName;
  169762. int nArg;
  169763. int flag;
  169764. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  169765. } aFunc[] = {
  169766. { "json", 1, 0, jsonRemoveFunc },
  169767. { "json_array", -1, 0, jsonArrayFunc },
  169768. { "json_array_length", 1, 0, jsonArrayLengthFunc },
  169769. { "json_array_length", 2, 0, jsonArrayLengthFunc },
  169770. { "json_extract", -1, 0, jsonExtractFunc },
  169771. { "json_insert", -1, 0, jsonSetFunc },
  169772. { "json_object", -1, 0, jsonObjectFunc },
  169773. { "json_patch", 2, 0, jsonPatchFunc },
  169774. { "json_quote", 1, 0, jsonQuoteFunc },
  169775. { "json_remove", -1, 0, jsonRemoveFunc },
  169776. { "json_replace", -1, 0, jsonReplaceFunc },
  169777. { "json_set", -1, 1, jsonSetFunc },
  169778. { "json_type", 1, 0, jsonTypeFunc },
  169779. { "json_type", 2, 0, jsonTypeFunc },
  169780. { "json_valid", 1, 0, jsonValidFunc },
  169781. #if SQLITE_DEBUG
  169782. /* DEBUG and TESTING functions */
  169783. { "json_parse", 1, 0, jsonParseFunc },
  169784. { "json_test1", 1, 0, jsonTest1Func },
  169785. #endif
  169786. };
  169787. static const struct {
  169788. const char *zName;
  169789. int nArg;
  169790. void (*xStep)(sqlite3_context*,int,sqlite3_value**);
  169791. void (*xFinal)(sqlite3_context*);
  169792. } aAgg[] = {
  169793. { "json_group_array", 1, jsonArrayStep, jsonArrayFinal },
  169794. { "json_group_object", 2, jsonObjectStep, jsonObjectFinal },
  169795. };
  169796. #ifndef SQLITE_OMIT_VIRTUALTABLE
  169797. static const struct {
  169798. const char *zName;
  169799. sqlite3_module *pModule;
  169800. } aMod[] = {
  169801. { "json_each", &jsonEachModule },
  169802. { "json_tree", &jsonTreeModule },
  169803. };
  169804. #endif
  169805. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  169806. rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
  169807. SQLITE_UTF8 | SQLITE_DETERMINISTIC,
  169808. (void*)&aFunc[i].flag,
  169809. aFunc[i].xFunc, 0, 0);
  169810. }
  169811. for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
  169812. rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
  169813. SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
  169814. 0, aAgg[i].xStep, aAgg[i].xFinal);
  169815. }
  169816. #ifndef SQLITE_OMIT_VIRTUALTABLE
  169817. for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
  169818. rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
  169819. }
  169820. #endif
  169821. return rc;
  169822. }
  169823. #ifndef SQLITE_CORE
  169824. #ifdef _WIN32
  169825. __declspec(dllexport)
  169826. #endif
  169827. SQLITE_API int sqlite3_json_init(
  169828. sqlite3 *db,
  169829. char **pzErrMsg,
  169830. const sqlite3_api_routines *pApi
  169831. ){
  169832. SQLITE_EXTENSION_INIT2(pApi);
  169833. (void)pzErrMsg; /* Unused parameter */
  169834. return sqlite3Json1Init(db);
  169835. }
  169836. #endif
  169837. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
  169838. /************** End of json1.c ***********************************************/
  169839. /************** Begin file fts5.c ********************************************/
  169840. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
  169841. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  169842. # define NDEBUG 1
  169843. #endif
  169844. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  169845. # undef NDEBUG
  169846. #endif
  169847. /*
  169848. ** 2014 May 31
  169849. **
  169850. ** The author disclaims copyright to this source code. In place of
  169851. ** a legal notice, here is a blessing:
  169852. **
  169853. ** May you do good and not evil.
  169854. ** May you find forgiveness for yourself and forgive others.
  169855. ** May you share freely, never taking more than you give.
  169856. **
  169857. ******************************************************************************
  169858. **
  169859. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  169860. ** FTS5 may be extended with:
  169861. **
  169862. ** * custom tokenizers, and
  169863. ** * custom auxiliary functions.
  169864. */
  169865. #ifndef _FTS5_H
  169866. #define _FTS5_H
  169867. /* #include "sqlite3.h" */
  169868. #if 0
  169869. extern "C" {
  169870. #endif
  169871. /*************************************************************************
  169872. ** CUSTOM AUXILIARY FUNCTIONS
  169873. **
  169874. ** Virtual table implementations may overload SQL functions by implementing
  169875. ** the sqlite3_module.xFindFunction() method.
  169876. */
  169877. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  169878. typedef struct Fts5Context Fts5Context;
  169879. typedef struct Fts5PhraseIter Fts5PhraseIter;
  169880. typedef void (*fts5_extension_function)(
  169881. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  169882. Fts5Context *pFts, /* First arg to pass to pApi functions */
  169883. sqlite3_context *pCtx, /* Context for returning result/error */
  169884. int nVal, /* Number of values in apVal[] array */
  169885. sqlite3_value **apVal /* Array of trailing arguments */
  169886. );
  169887. struct Fts5PhraseIter {
  169888. const unsigned char *a;
  169889. const unsigned char *b;
  169890. };
  169891. /*
  169892. ** EXTENSION API FUNCTIONS
  169893. **
  169894. ** xUserData(pFts):
  169895. ** Return a copy of the context pointer the extension function was
  169896. ** registered with.
  169897. **
  169898. ** xColumnTotalSize(pFts, iCol, pnToken):
  169899. ** If parameter iCol is less than zero, set output variable *pnToken
  169900. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  169901. ** non-negative but less than the number of columns in the table, return
  169902. ** the total number of tokens in column iCol, considering all rows in
  169903. ** the FTS5 table.
  169904. **
  169905. ** If parameter iCol is greater than or equal to the number of columns
  169906. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  169907. ** an OOM condition or IO error), an appropriate SQLite error code is
  169908. ** returned.
  169909. **
  169910. ** xColumnCount(pFts):
  169911. ** Return the number of columns in the table.
  169912. **
  169913. ** xColumnSize(pFts, iCol, pnToken):
  169914. ** If parameter iCol is less than zero, set output variable *pnToken
  169915. ** to the total number of tokens in the current row. Or, if iCol is
  169916. ** non-negative but less than the number of columns in the table, set
  169917. ** *pnToken to the number of tokens in column iCol of the current row.
  169918. **
  169919. ** If parameter iCol is greater than or equal to the number of columns
  169920. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  169921. ** an OOM condition or IO error), an appropriate SQLite error code is
  169922. ** returned.
  169923. **
  169924. ** This function may be quite inefficient if used with an FTS5 table
  169925. ** created with the "columnsize=0" option.
  169926. **
  169927. ** xColumnText:
  169928. ** This function attempts to retrieve the text of column iCol of the
  169929. ** current document. If successful, (*pz) is set to point to a buffer
  169930. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  169931. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  169932. ** if an error occurs, an SQLite error code is returned and the final values
  169933. ** of (*pz) and (*pn) are undefined.
  169934. **
  169935. ** xPhraseCount:
  169936. ** Returns the number of phrases in the current query expression.
  169937. **
  169938. ** xPhraseSize:
  169939. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  169940. ** are numbered starting from zero.
  169941. **
  169942. ** xInstCount:
  169943. ** Set *pnInst to the total number of occurrences of all phrases within
  169944. ** the query within the current row. Return SQLITE_OK if successful, or
  169945. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  169946. **
  169947. ** This API can be quite slow if used with an FTS5 table created with the
  169948. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  169949. ** with either "detail=none" or "detail=column" and "content=" option
  169950. ** (i.e. if it is a contentless table), then this API always returns 0.
  169951. **
  169952. ** xInst:
  169953. ** Query for the details of phrase match iIdx within the current row.
  169954. ** Phrase matches are numbered starting from zero, so the iIdx argument
  169955. ** should be greater than or equal to zero and smaller than the value
  169956. ** output by xInstCount().
  169957. **
  169958. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  169959. ** to the column in which it occurs and *piOff the token offset of the
  169960. ** first token of the phrase. The exception is if the table was created
  169961. ** with the offsets=0 option specified. In this case *piOff is always
  169962. ** set to -1.
  169963. **
  169964. ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
  169965. ** if an error occurs.
  169966. **
  169967. ** This API can be quite slow if used with an FTS5 table created with the
  169968. ** "detail=none" or "detail=column" option.
  169969. **
  169970. ** xRowid:
  169971. ** Returns the rowid of the current row.
  169972. **
  169973. ** xTokenize:
  169974. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  169975. **
  169976. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  169977. ** This API function is used to query the FTS table for phrase iPhrase
  169978. ** of the current query. Specifically, a query equivalent to:
  169979. **
  169980. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  169981. **
  169982. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  169983. ** current query is executed. Any column filter that applies to
  169984. ** phrase iPhrase of the current query is included in $p. For each
  169985. ** row visited, the callback function passed as the fourth argument
  169986. ** is invoked. The context and API objects passed to the callback
  169987. ** function may be used to access the properties of each matched row.
  169988. ** Invoking Api.xUserData() returns a copy of the pointer passed as
  169989. ** the third argument to pUserData.
  169990. **
  169991. ** If the callback function returns any value other than SQLITE_OK, the
  169992. ** query is abandoned and the xQueryPhrase function returns immediately.
  169993. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  169994. ** Otherwise, the error code is propagated upwards.
  169995. **
  169996. ** If the query runs to completion without incident, SQLITE_OK is returned.
  169997. ** Or, if some error occurs before the query completes or is aborted by
  169998. ** the callback, an SQLite error code is returned.
  169999. **
  170000. **
  170001. ** xSetAuxdata(pFts5, pAux, xDelete)
  170002. **
  170003. ** Save the pointer passed as the second argument as the extension functions
  170004. ** "auxiliary data". The pointer may then be retrieved by the current or any
  170005. ** future invocation of the same fts5 extension function made as part of
  170006. ** of the same MATCH query using the xGetAuxdata() API.
  170007. **
  170008. ** Each extension function is allocated a single auxiliary data slot for
  170009. ** each FTS query (MATCH expression). If the extension function is invoked
  170010. ** more than once for a single FTS query, then all invocations share a
  170011. ** single auxiliary data context.
  170012. **
  170013. ** If there is already an auxiliary data pointer when this function is
  170014. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  170015. ** was specified along with the original pointer, it is invoked at this
  170016. ** point.
  170017. **
  170018. ** The xDelete callback, if one is specified, is also invoked on the
  170019. ** auxiliary data pointer after the FTS5 query has finished.
  170020. **
  170021. ** If an error (e.g. an OOM condition) occurs within this function, an
  170022. ** the auxiliary data is set to NULL and an error code returned. If the
  170023. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  170024. ** pointer before returning.
  170025. **
  170026. **
  170027. ** xGetAuxdata(pFts5, bClear)
  170028. **
  170029. ** Returns the current auxiliary data pointer for the fts5 extension
  170030. ** function. See the xSetAuxdata() method for details.
  170031. **
  170032. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  170033. ** (set to NULL) before this function returns. In this case the xDelete,
  170034. ** if any, is not invoked.
  170035. **
  170036. **
  170037. ** xRowCount(pFts5, pnRow)
  170038. **
  170039. ** This function is used to retrieve the total number of rows in the table.
  170040. ** In other words, the same value that would be returned by:
  170041. **
  170042. ** SELECT count(*) FROM ftstable;
  170043. **
  170044. ** xPhraseFirst()
  170045. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  170046. ** method, to iterate through all instances of a single query phrase within
  170047. ** the current row. This is the same information as is accessible via the
  170048. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  170049. ** to use, this API may be faster under some circumstances. To iterate
  170050. ** through instances of phrase iPhrase, use the following code:
  170051. **
  170052. ** Fts5PhraseIter iter;
  170053. ** int iCol, iOff;
  170054. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  170055. ** iCol>=0;
  170056. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  170057. ** ){
  170058. ** // An instance of phrase iPhrase at offset iOff of column iCol
  170059. ** }
  170060. **
  170061. ** The Fts5PhraseIter structure is defined above. Applications should not
  170062. ** modify this structure directly - it should only be used as shown above
  170063. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  170064. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  170065. **
  170066. ** This API can be quite slow if used with an FTS5 table created with the
  170067. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  170068. ** with either "detail=none" or "detail=column" and "content=" option
  170069. ** (i.e. if it is a contentless table), then this API always iterates
  170070. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  170071. **
  170072. ** xPhraseNext()
  170073. ** See xPhraseFirst above.
  170074. **
  170075. ** xPhraseFirstColumn()
  170076. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  170077. ** and xPhraseNext() APIs described above. The difference is that instead
  170078. ** of iterating through all instances of a phrase in the current row, these
  170079. ** APIs are used to iterate through the set of columns in the current row
  170080. ** that contain one or more instances of a specified phrase. For example:
  170081. **
  170082. ** Fts5PhraseIter iter;
  170083. ** int iCol;
  170084. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  170085. ** iCol>=0;
  170086. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  170087. ** ){
  170088. ** // Column iCol contains at least one instance of phrase iPhrase
  170089. ** }
  170090. **
  170091. ** This API can be quite slow if used with an FTS5 table created with the
  170092. ** "detail=none" option. If the FTS5 table is created with either
  170093. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  170094. ** then this API always iterates through an empty set (all calls to
  170095. ** xPhraseFirstColumn() set iCol to -1).
  170096. **
  170097. ** The information accessed using this API and its companion
  170098. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  170099. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  170100. ** significantly more efficient than those alternatives when used with
  170101. ** "detail=column" tables.
  170102. **
  170103. ** xPhraseNextColumn()
  170104. ** See xPhraseFirstColumn above.
  170105. */
  170106. struct Fts5ExtensionApi {
  170107. int iVersion; /* Currently always set to 3 */
  170108. void *(*xUserData)(Fts5Context*);
  170109. int (*xColumnCount)(Fts5Context*);
  170110. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  170111. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  170112. int (*xTokenize)(Fts5Context*,
  170113. const char *pText, int nText, /* Text to tokenize */
  170114. void *pCtx, /* Context passed to xToken() */
  170115. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  170116. );
  170117. int (*xPhraseCount)(Fts5Context*);
  170118. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  170119. int (*xInstCount)(Fts5Context*, int *pnInst);
  170120. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  170121. sqlite3_int64 (*xRowid)(Fts5Context*);
  170122. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  170123. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  170124. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  170125. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  170126. );
  170127. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  170128. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  170129. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  170130. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  170131. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  170132. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  170133. };
  170134. /*
  170135. ** CUSTOM AUXILIARY FUNCTIONS
  170136. *************************************************************************/
  170137. /*************************************************************************
  170138. ** CUSTOM TOKENIZERS
  170139. **
  170140. ** Applications may also register custom tokenizer types. A tokenizer
  170141. ** is registered by providing fts5 with a populated instance of the
  170142. ** following structure. All structure methods must be defined, setting
  170143. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  170144. ** behaviour. The structure methods are expected to function as follows:
  170145. **
  170146. ** xCreate:
  170147. ** This function is used to allocate and initialize a tokenizer instance.
  170148. ** A tokenizer instance is required to actually tokenize text.
  170149. **
  170150. ** The first argument passed to this function is a copy of the (void*)
  170151. ** pointer provided by the application when the fts5_tokenizer object
  170152. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  170153. ** The second and third arguments are an array of nul-terminated strings
  170154. ** containing the tokenizer arguments, if any, specified following the
  170155. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  170156. ** to create the FTS5 table.
  170157. **
  170158. ** The final argument is an output variable. If successful, (*ppOut)
  170159. ** should be set to point to the new tokenizer handle and SQLITE_OK
  170160. ** returned. If an error occurs, some value other than SQLITE_OK should
  170161. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  170162. ** is undefined.
  170163. **
  170164. ** xDelete:
  170165. ** This function is invoked to delete a tokenizer handle previously
  170166. ** allocated using xCreate(). Fts5 guarantees that this function will
  170167. ** be invoked exactly once for each successful call to xCreate().
  170168. **
  170169. ** xTokenize:
  170170. ** This function is expected to tokenize the nText byte string indicated
  170171. ** by argument pText. pText may or may not be nul-terminated. The first
  170172. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  170173. ** returned by an earlier call to xCreate().
  170174. **
  170175. ** The second argument indicates the reason that FTS5 is requesting
  170176. ** tokenization of the supplied text. This is always one of the following
  170177. ** four values:
  170178. **
  170179. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  170180. ** or removed from the FTS table. The tokenizer is being invoked to
  170181. ** determine the set of tokens to add to (or delete from) the
  170182. ** FTS index.
  170183. **
  170184. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  170185. ** against the FTS index. The tokenizer is being called to tokenize
  170186. ** a bareword or quoted string specified as part of the query.
  170187. **
  170188. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  170189. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  170190. ** followed by a "*" character, indicating that the last token
  170191. ** returned by the tokenizer will be treated as a token prefix.
  170192. **
  170193. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  170194. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  170195. ** function. Or an fts5_api.xColumnSize() request made by the same
  170196. ** on a columnsize=0 database.
  170197. ** </ul>
  170198. **
  170199. ** For each token in the input string, the supplied callback xToken() must
  170200. ** be invoked. The first argument to it should be a copy of the pointer
  170201. ** passed as the second argument to xTokenize(). The third and fourth
  170202. ** arguments are a pointer to a buffer containing the token text, and the
  170203. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  170204. ** of the first byte of and first byte immediately following the text from
  170205. ** which the token is derived within the input.
  170206. **
  170207. ** The second argument passed to the xToken() callback ("tflags") should
  170208. ** normally be set to 0. The exception is if the tokenizer supports
  170209. ** synonyms. In this case see the discussion below for details.
  170210. **
  170211. ** FTS5 assumes the xToken() callback is invoked for each token in the
  170212. ** order that they occur within the input text.
  170213. **
  170214. ** If an xToken() callback returns any value other than SQLITE_OK, then
  170215. ** the tokenization should be abandoned and the xTokenize() method should
  170216. ** immediately return a copy of the xToken() return value. Or, if the
  170217. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  170218. ** if an error occurs with the xTokenize() implementation itself, it
  170219. ** may abandon the tokenization and return any error code other than
  170220. ** SQLITE_OK or SQLITE_DONE.
  170221. **
  170222. ** SYNONYM SUPPORT
  170223. **
  170224. ** Custom tokenizers may also support synonyms. Consider a case in which a
  170225. ** user wishes to query for a phrase such as "first place". Using the
  170226. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  170227. ** of "first place" within the document set, but not alternative forms
  170228. ** such as "1st place". In some applications, it would be better to match
  170229. ** all instances of "first place" or "1st place" regardless of which form
  170230. ** the user specified in the MATCH query text.
  170231. **
  170232. ** There are several ways to approach this in FTS5:
  170233. **
  170234. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  170235. ** In the above example, this means that the tokenizer returns the
  170236. ** same token for inputs "first" and "1st". Say that token is in
  170237. ** fact "first", so that when the user inserts the document "I won
  170238. ** 1st place" entries are added to the index for tokens "i", "won",
  170239. ** "first" and "place". If the user then queries for '1st + place',
  170240. ** the tokenizer substitutes "first" for "1st" and the query works
  170241. ** as expected.
  170242. **
  170243. ** <li> By adding multiple synonyms for a single term to the FTS index.
  170244. ** In this case, when tokenizing query text, the tokenizer may
  170245. ** provide multiple synonyms for a single term within the document.
  170246. ** FTS5 then queries the index for each synonym individually. For
  170247. ** example, faced with the query:
  170248. **
  170249. ** <codeblock>
  170250. ** ... MATCH 'first place'</codeblock>
  170251. **
  170252. ** the tokenizer offers both "1st" and "first" as synonyms for the
  170253. ** first token in the MATCH query and FTS5 effectively runs a query
  170254. ** similar to:
  170255. **
  170256. ** <codeblock>
  170257. ** ... MATCH '(first OR 1st) place'</codeblock>
  170258. **
  170259. ** except that, for the purposes of auxiliary functions, the query
  170260. ** still appears to contain just two phrases - "(first OR 1st)"
  170261. ** being treated as a single phrase.
  170262. **
  170263. ** <li> By adding multiple synonyms for a single term to the FTS index.
  170264. ** Using this method, when tokenizing document text, the tokenizer
  170265. ** provides multiple synonyms for each token. So that when a
  170266. ** document such as "I won first place" is tokenized, entries are
  170267. ** added to the FTS index for "i", "won", "first", "1st" and
  170268. ** "place".
  170269. **
  170270. ** This way, even if the tokenizer does not provide synonyms
  170271. ** when tokenizing query text (it should not - to do would be
  170272. ** inefficient), it doesn't matter if the user queries for
  170273. ** 'first + place' or '1st + place', as there are entires in the
  170274. ** FTS index corresponding to both forms of the first token.
  170275. ** </ol>
  170276. **
  170277. ** Whether it is parsing document or query text, any call to xToken that
  170278. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  170279. ** is considered to supply a synonym for the previous token. For example,
  170280. ** when parsing the document "I won first place", a tokenizer that supports
  170281. ** synonyms would call xToken() 5 times, as follows:
  170282. **
  170283. ** <codeblock>
  170284. ** xToken(pCtx, 0, "i", 1, 0, 1);
  170285. ** xToken(pCtx, 0, "won", 3, 2, 5);
  170286. ** xToken(pCtx, 0, "first", 5, 6, 11);
  170287. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  170288. ** xToken(pCtx, 0, "place", 5, 12, 17);
  170289. **</codeblock>
  170290. **
  170291. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  170292. ** xToken() is called. Multiple synonyms may be specified for a single token
  170293. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  170294. ** There is no limit to the number of synonyms that may be provided for a
  170295. ** single token.
  170296. **
  170297. ** In many cases, method (1) above is the best approach. It does not add
  170298. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  170299. ** so it is efficient in terms of disk space and query speed. However, it
  170300. ** does not support prefix queries very well. If, as suggested above, the
  170301. ** token "first" is subsituted for "1st" by the tokenizer, then the query:
  170302. **
  170303. ** <codeblock>
  170304. ** ... MATCH '1s*'</codeblock>
  170305. **
  170306. ** will not match documents that contain the token "1st" (as the tokenizer
  170307. ** will probably not map "1s" to any prefix of "first").
  170308. **
  170309. ** For full prefix support, method (3) may be preferred. In this case,
  170310. ** because the index contains entries for both "first" and "1st", prefix
  170311. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  170312. ** extra entries are added to the FTS index, this method uses more space
  170313. ** within the database.
  170314. **
  170315. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  170316. ** a query such as '1s*' will match documents that contain the literal
  170317. ** token "1st", but not "first" (assuming the tokenizer is not able to
  170318. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  170319. ** will match against "1st" and "first". This method does not require
  170320. ** extra disk space, as no extra entries are added to the FTS index.
  170321. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  170322. ** as separate queries of the FTS index are required for each synonym.
  170323. **
  170324. ** When using methods (2) or (3), it is important that the tokenizer only
  170325. ** provide synonyms when tokenizing document text (method (2)) or query
  170326. ** text (method (3)), not both. Doing so will not cause any errors, but is
  170327. ** inefficient.
  170328. */
  170329. typedef struct Fts5Tokenizer Fts5Tokenizer;
  170330. typedef struct fts5_tokenizer fts5_tokenizer;
  170331. struct fts5_tokenizer {
  170332. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  170333. void (*xDelete)(Fts5Tokenizer*);
  170334. int (*xTokenize)(Fts5Tokenizer*,
  170335. void *pCtx,
  170336. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  170337. const char *pText, int nText,
  170338. int (*xToken)(
  170339. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  170340. int tflags, /* Mask of FTS5_TOKEN_* flags */
  170341. const char *pToken, /* Pointer to buffer containing token */
  170342. int nToken, /* Size of token in bytes */
  170343. int iStart, /* Byte offset of token within input text */
  170344. int iEnd /* Byte offset of end of token within input text */
  170345. )
  170346. );
  170347. };
  170348. /* Flags that may be passed as the third argument to xTokenize() */
  170349. #define FTS5_TOKENIZE_QUERY 0x0001
  170350. #define FTS5_TOKENIZE_PREFIX 0x0002
  170351. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  170352. #define FTS5_TOKENIZE_AUX 0x0008
  170353. /* Flags that may be passed by the tokenizer implementation back to FTS5
  170354. ** as the third argument to the supplied xToken callback. */
  170355. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  170356. /*
  170357. ** END OF CUSTOM TOKENIZERS
  170358. *************************************************************************/
  170359. /*************************************************************************
  170360. ** FTS5 EXTENSION REGISTRATION API
  170361. */
  170362. typedef struct fts5_api fts5_api;
  170363. struct fts5_api {
  170364. int iVersion; /* Currently always set to 2 */
  170365. /* Create a new tokenizer */
  170366. int (*xCreateTokenizer)(
  170367. fts5_api *pApi,
  170368. const char *zName,
  170369. void *pContext,
  170370. fts5_tokenizer *pTokenizer,
  170371. void (*xDestroy)(void*)
  170372. );
  170373. /* Find an existing tokenizer */
  170374. int (*xFindTokenizer)(
  170375. fts5_api *pApi,
  170376. const char *zName,
  170377. void **ppContext,
  170378. fts5_tokenizer *pTokenizer
  170379. );
  170380. /* Create a new auxiliary function */
  170381. int (*xCreateFunction)(
  170382. fts5_api *pApi,
  170383. const char *zName,
  170384. void *pContext,
  170385. fts5_extension_function xFunction,
  170386. void (*xDestroy)(void*)
  170387. );
  170388. };
  170389. /*
  170390. ** END OF REGISTRATION API
  170391. *************************************************************************/
  170392. #if 0
  170393. } /* end of the 'extern "C"' block */
  170394. #endif
  170395. #endif /* _FTS5_H */
  170396. /*
  170397. ** 2014 May 31
  170398. **
  170399. ** The author disclaims copyright to this source code. In place of
  170400. ** a legal notice, here is a blessing:
  170401. **
  170402. ** May you do good and not evil.
  170403. ** May you find forgiveness for yourself and forgive others.
  170404. ** May you share freely, never taking more than you give.
  170405. **
  170406. ******************************************************************************
  170407. **
  170408. */
  170409. #ifndef _FTS5INT_H
  170410. #define _FTS5INT_H
  170411. /* #include "fts5.h" */
  170412. /* #include "sqlite3ext.h" */
  170413. SQLITE_EXTENSION_INIT1
  170414. /* #include <string.h> */
  170415. /* #include <assert.h> */
  170416. #ifndef SQLITE_AMALGAMATION
  170417. typedef unsigned char u8;
  170418. typedef unsigned int u32;
  170419. typedef unsigned short u16;
  170420. typedef short i16;
  170421. typedef sqlite3_int64 i64;
  170422. typedef sqlite3_uint64 u64;
  170423. #ifndef ArraySize
  170424. # define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
  170425. #endif
  170426. #define testcase(x)
  170427. #define ALWAYS(x) 1
  170428. #define NEVER(x) 0
  170429. #define MIN(x,y) (((x) < (y)) ? (x) : (y))
  170430. #define MAX(x,y) (((x) > (y)) ? (x) : (y))
  170431. /*
  170432. ** Constants for the largest and smallest possible 64-bit signed integers.
  170433. */
  170434. # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  170435. # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  170436. #endif
  170437. /* Truncate very long tokens to this many bytes. Hard limit is
  170438. ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
  170439. ** field that occurs at the start of each leaf page (see fts5_index.c). */
  170440. #define FTS5_MAX_TOKEN_SIZE 32768
  170441. /*
  170442. ** Maximum number of prefix indexes on single FTS5 table. This must be
  170443. ** less than 32. If it is set to anything large than that, an #error
  170444. ** directive in fts5_index.c will cause the build to fail.
  170445. */
  170446. #define FTS5_MAX_PREFIX_INDEXES 31
  170447. #define FTS5_DEFAULT_NEARDIST 10
  170448. #define FTS5_DEFAULT_RANK "bm25"
  170449. /* Name of rank and rowid columns */
  170450. #define FTS5_RANK_NAME "rank"
  170451. #define FTS5_ROWID_NAME "rowid"
  170452. #ifdef SQLITE_DEBUG
  170453. # define FTS5_CORRUPT sqlite3Fts5Corrupt()
  170454. static int sqlite3Fts5Corrupt(void);
  170455. #else
  170456. # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
  170457. #endif
  170458. /*
  170459. ** The assert_nc() macro is similar to the assert() macro, except that it
  170460. ** is used for assert() conditions that are true only if it can be
  170461. ** guranteed that the database is not corrupt.
  170462. */
  170463. #ifdef SQLITE_DEBUG
  170464. SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
  170465. # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
  170466. #else
  170467. # define assert_nc(x) assert(x)
  170468. #endif
  170469. /* Mark a function parameter as unused, to suppress nuisance compiler
  170470. ** warnings. */
  170471. #ifndef UNUSED_PARAM
  170472. # define UNUSED_PARAM(X) (void)(X)
  170473. #endif
  170474. #ifndef UNUSED_PARAM2
  170475. # define UNUSED_PARAM2(X, Y) (void)(X), (void)(Y)
  170476. #endif
  170477. typedef struct Fts5Global Fts5Global;
  170478. typedef struct Fts5Colset Fts5Colset;
  170479. /* If a NEAR() clump or phrase may only match a specific set of columns,
  170480. ** then an object of the following type is used to record the set of columns.
  170481. ** Each entry in the aiCol[] array is a column that may be matched.
  170482. **
  170483. ** This object is used by fts5_expr.c and fts5_index.c.
  170484. */
  170485. struct Fts5Colset {
  170486. int nCol;
  170487. int aiCol[1];
  170488. };
  170489. /**************************************************************************
  170490. ** Interface to code in fts5_config.c. fts5_config.c contains contains code
  170491. ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
  170492. */
  170493. typedef struct Fts5Config Fts5Config;
  170494. /*
  170495. ** An instance of the following structure encodes all information that can
  170496. ** be gleaned from the CREATE VIRTUAL TABLE statement.
  170497. **
  170498. ** And all information loaded from the %_config table.
  170499. **
  170500. ** nAutomerge:
  170501. ** The minimum number of segments that an auto-merge operation should
  170502. ** attempt to merge together. A value of 1 sets the object to use the
  170503. ** compile time default. Zero disables auto-merge altogether.
  170504. **
  170505. ** zContent:
  170506. **
  170507. ** zContentRowid:
  170508. ** The value of the content_rowid= option, if one was specified. Or
  170509. ** the string "rowid" otherwise. This text is not quoted - if it is
  170510. ** used as part of an SQL statement it needs to be quoted appropriately.
  170511. **
  170512. ** zContentExprlist:
  170513. **
  170514. ** pzErrmsg:
  170515. ** This exists in order to allow the fts5_index.c module to return a
  170516. ** decent error message if it encounters a file-format version it does
  170517. ** not understand.
  170518. **
  170519. ** bColumnsize:
  170520. ** True if the %_docsize table is created.
  170521. **
  170522. ** bPrefixIndex:
  170523. ** This is only used for debugging. If set to false, any prefix indexes
  170524. ** are ignored. This value is configured using:
  170525. **
  170526. ** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
  170527. **
  170528. */
  170529. struct Fts5Config {
  170530. sqlite3 *db; /* Database handle */
  170531. char *zDb; /* Database holding FTS index (e.g. "main") */
  170532. char *zName; /* Name of FTS index */
  170533. int nCol; /* Number of columns */
  170534. char **azCol; /* Column names */
  170535. u8 *abUnindexed; /* True for unindexed columns */
  170536. int nPrefix; /* Number of prefix indexes */
  170537. int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */
  170538. int eContent; /* An FTS5_CONTENT value */
  170539. char *zContent; /* content table */
  170540. char *zContentRowid; /* "content_rowid=" option value */
  170541. int bColumnsize; /* "columnsize=" option value (dflt==1) */
  170542. int eDetail; /* FTS5_DETAIL_XXX value */
  170543. char *zContentExprlist;
  170544. Fts5Tokenizer *pTok;
  170545. fts5_tokenizer *pTokApi;
  170546. /* Values loaded from the %_config table */
  170547. int iCookie; /* Incremented when %_config is modified */
  170548. int pgsz; /* Approximate page size used in %_data */
  170549. int nAutomerge; /* 'automerge' setting */
  170550. int nCrisisMerge; /* Maximum allowed segments per level */
  170551. int nUsermerge; /* 'usermerge' setting */
  170552. int nHashSize; /* Bytes of memory for in-memory hash */
  170553. char *zRank; /* Name of rank function */
  170554. char *zRankArgs; /* Arguments to rank function */
  170555. /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
  170556. char **pzErrmsg;
  170557. #ifdef SQLITE_DEBUG
  170558. int bPrefixIndex; /* True to use prefix-indexes */
  170559. #endif
  170560. };
  170561. /* Current expected value of %_config table 'version' field */
  170562. #define FTS5_CURRENT_VERSION 4
  170563. #define FTS5_CONTENT_NORMAL 0
  170564. #define FTS5_CONTENT_NONE 1
  170565. #define FTS5_CONTENT_EXTERNAL 2
  170566. #define FTS5_DETAIL_FULL 0
  170567. #define FTS5_DETAIL_NONE 1
  170568. #define FTS5_DETAIL_COLUMNS 2
  170569. static int sqlite3Fts5ConfigParse(
  170570. Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
  170571. );
  170572. static void sqlite3Fts5ConfigFree(Fts5Config*);
  170573. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
  170574. static int sqlite3Fts5Tokenize(
  170575. Fts5Config *pConfig, /* FTS5 Configuration object */
  170576. int flags, /* FTS5_TOKENIZE_* flags */
  170577. const char *pText, int nText, /* Text to tokenize */
  170578. void *pCtx, /* Context passed to xToken() */
  170579. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  170580. );
  170581. static void sqlite3Fts5Dequote(char *z);
  170582. /* Load the contents of the %_config table */
  170583. static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
  170584. /* Set the value of a single config attribute */
  170585. static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
  170586. static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
  170587. /*
  170588. ** End of interface to code in fts5_config.c.
  170589. **************************************************************************/
  170590. /**************************************************************************
  170591. ** Interface to code in fts5_buffer.c.
  170592. */
  170593. /*
  170594. ** Buffer object for the incremental building of string data.
  170595. */
  170596. typedef struct Fts5Buffer Fts5Buffer;
  170597. struct Fts5Buffer {
  170598. u8 *p;
  170599. int n;
  170600. int nSpace;
  170601. };
  170602. static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
  170603. static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
  170604. static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
  170605. static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
  170606. static void sqlite3Fts5BufferFree(Fts5Buffer*);
  170607. static void sqlite3Fts5BufferZero(Fts5Buffer*);
  170608. static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
  170609. static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
  170610. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
  170611. #define fts5BufferZero(x) sqlite3Fts5BufferZero(x)
  170612. #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
  170613. #define fts5BufferFree(a) sqlite3Fts5BufferFree(a)
  170614. #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
  170615. #define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d)
  170616. #define fts5BufferGrow(pRc,pBuf,nn) ( \
  170617. (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
  170618. sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
  170619. )
  170620. /* Write and decode big-endian 32-bit integer values */
  170621. static void sqlite3Fts5Put32(u8*, int);
  170622. static int sqlite3Fts5Get32(const u8*);
  170623. #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
  170624. #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
  170625. typedef struct Fts5PoslistReader Fts5PoslistReader;
  170626. struct Fts5PoslistReader {
  170627. /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
  170628. const u8 *a; /* Position list to iterate through */
  170629. int n; /* Size of buffer at a[] in bytes */
  170630. int i; /* Current offset in a[] */
  170631. u8 bFlag; /* For client use (any custom purpose) */
  170632. /* Output variables */
  170633. u8 bEof; /* Set to true at EOF */
  170634. i64 iPos; /* (iCol<<32) + iPos */
  170635. };
  170636. static int sqlite3Fts5PoslistReaderInit(
  170637. const u8 *a, int n, /* Poslist buffer to iterate through */
  170638. Fts5PoslistReader *pIter /* Iterator object to initialize */
  170639. );
  170640. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
  170641. typedef struct Fts5PoslistWriter Fts5PoslistWriter;
  170642. struct Fts5PoslistWriter {
  170643. i64 iPrev;
  170644. };
  170645. static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
  170646. static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
  170647. static int sqlite3Fts5PoslistNext64(
  170648. const u8 *a, int n, /* Buffer containing poslist */
  170649. int *pi, /* IN/OUT: Offset within a[] */
  170650. i64 *piOff /* IN/OUT: Current offset */
  170651. );
  170652. /* Malloc utility */
  170653. static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
  170654. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
  170655. /* Character set tests (like isspace(), isalpha() etc.) */
  170656. static int sqlite3Fts5IsBareword(char t);
  170657. /* Bucket of terms object used by the integrity-check in offsets=0 mode. */
  170658. typedef struct Fts5Termset Fts5Termset;
  170659. static int sqlite3Fts5TermsetNew(Fts5Termset**);
  170660. static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
  170661. static void sqlite3Fts5TermsetFree(Fts5Termset*);
  170662. /*
  170663. ** End of interface to code in fts5_buffer.c.
  170664. **************************************************************************/
  170665. /**************************************************************************
  170666. ** Interface to code in fts5_index.c. fts5_index.c contains contains code
  170667. ** to access the data stored in the %_data table.
  170668. */
  170669. typedef struct Fts5Index Fts5Index;
  170670. typedef struct Fts5IndexIter Fts5IndexIter;
  170671. struct Fts5IndexIter {
  170672. i64 iRowid;
  170673. const u8 *pData;
  170674. int nData;
  170675. u8 bEof;
  170676. };
  170677. #define sqlite3Fts5IterEof(x) ((x)->bEof)
  170678. /*
  170679. ** Values used as part of the flags argument passed to IndexQuery().
  170680. */
  170681. #define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */
  170682. #define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */
  170683. #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */
  170684. #define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */
  170685. /* The following are used internally by the fts5_index.c module. They are
  170686. ** defined here only to make it easier to avoid clashes with the flags
  170687. ** above. */
  170688. #define FTS5INDEX_QUERY_SKIPEMPTY 0x0010
  170689. #define FTS5INDEX_QUERY_NOOUTPUT 0x0020
  170690. /*
  170691. ** Create/destroy an Fts5Index object.
  170692. */
  170693. static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
  170694. static int sqlite3Fts5IndexClose(Fts5Index *p);
  170695. /*
  170696. ** Return a simple checksum value based on the arguments.
  170697. */
  170698. static u64 sqlite3Fts5IndexEntryCksum(
  170699. i64 iRowid,
  170700. int iCol,
  170701. int iPos,
  170702. int iIdx,
  170703. const char *pTerm,
  170704. int nTerm
  170705. );
  170706. /*
  170707. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  170708. ** size. Return the number of bytes in the nChar character prefix of the
  170709. ** buffer, or 0 if there are less than nChar characters in total.
  170710. */
  170711. static int sqlite3Fts5IndexCharlenToBytelen(
  170712. const char *p,
  170713. int nByte,
  170714. int nChar
  170715. );
  170716. /*
  170717. ** Open a new iterator to iterate though all rowids that match the
  170718. ** specified token or token prefix.
  170719. */
  170720. static int sqlite3Fts5IndexQuery(
  170721. Fts5Index *p, /* FTS index to query */
  170722. const char *pToken, int nToken, /* Token (or prefix) to query for */
  170723. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  170724. Fts5Colset *pColset, /* Match these columns only */
  170725. Fts5IndexIter **ppIter /* OUT: New iterator object */
  170726. );
  170727. /*
  170728. ** The various operations on open token or token prefix iterators opened
  170729. ** using sqlite3Fts5IndexQuery().
  170730. */
  170731. static int sqlite3Fts5IterNext(Fts5IndexIter*);
  170732. static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
  170733. /*
  170734. ** Close an iterator opened by sqlite3Fts5IndexQuery().
  170735. */
  170736. static void sqlite3Fts5IterClose(Fts5IndexIter*);
  170737. /*
  170738. ** This interface is used by the fts5vocab module.
  170739. */
  170740. static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
  170741. static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
  170742. /*
  170743. ** Insert or remove data to or from the index. Each time a document is
  170744. ** added to or removed from the index, this function is called one or more
  170745. ** times.
  170746. **
  170747. ** For an insert, it must be called once for each token in the new document.
  170748. ** If the operation is a delete, it must be called (at least) once for each
  170749. ** unique token in the document with an iCol value less than zero. The iPos
  170750. ** argument is ignored for a delete.
  170751. */
  170752. static int sqlite3Fts5IndexWrite(
  170753. Fts5Index *p, /* Index to write to */
  170754. int iCol, /* Column token appears in (-ve -> delete) */
  170755. int iPos, /* Position of token within column */
  170756. const char *pToken, int nToken /* Token to add or remove to or from index */
  170757. );
  170758. /*
  170759. ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
  170760. ** document iDocid.
  170761. */
  170762. static int sqlite3Fts5IndexBeginWrite(
  170763. Fts5Index *p, /* Index to write to */
  170764. int bDelete, /* True if current operation is a delete */
  170765. i64 iDocid /* Docid to add or remove data from */
  170766. );
  170767. /*
  170768. ** Flush any data stored in the in-memory hash tables to the database.
  170769. ** Also close any open blob handles.
  170770. */
  170771. static int sqlite3Fts5IndexSync(Fts5Index *p);
  170772. /*
  170773. ** Discard any data stored in the in-memory hash tables. Do not write it
  170774. ** to the database. Additionally, assume that the contents of the %_data
  170775. ** table may have changed on disk. So any in-memory caches of %_data
  170776. ** records must be invalidated.
  170777. */
  170778. static int sqlite3Fts5IndexRollback(Fts5Index *p);
  170779. /*
  170780. ** Get or set the "averages" values.
  170781. */
  170782. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
  170783. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
  170784. /*
  170785. ** Functions called by the storage module as part of integrity-check.
  170786. */
  170787. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
  170788. /*
  170789. ** Called during virtual module initialization to register UDF
  170790. ** fts5_decode() with SQLite
  170791. */
  170792. static int sqlite3Fts5IndexInit(sqlite3*);
  170793. static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
  170794. /*
  170795. ** Return the total number of entries read from the %_data table by
  170796. ** this connection since it was created.
  170797. */
  170798. static int sqlite3Fts5IndexReads(Fts5Index *p);
  170799. static int sqlite3Fts5IndexReinit(Fts5Index *p);
  170800. static int sqlite3Fts5IndexOptimize(Fts5Index *p);
  170801. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
  170802. static int sqlite3Fts5IndexReset(Fts5Index *p);
  170803. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
  170804. /*
  170805. ** End of interface to code in fts5_index.c.
  170806. **************************************************************************/
  170807. /**************************************************************************
  170808. ** Interface to code in fts5_varint.c.
  170809. */
  170810. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
  170811. static int sqlite3Fts5GetVarintLen(u32 iVal);
  170812. static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
  170813. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
  170814. #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
  170815. #define fts5GetVarint sqlite3Fts5GetVarint
  170816. #define fts5FastGetVarint32(a, iOff, nVal) { \
  170817. nVal = (a)[iOff++]; \
  170818. if( nVal & 0x80 ){ \
  170819. iOff--; \
  170820. iOff += fts5GetVarint32(&(a)[iOff], nVal); \
  170821. } \
  170822. }
  170823. /*
  170824. ** End of interface to code in fts5_varint.c.
  170825. **************************************************************************/
  170826. /**************************************************************************
  170827. ** Interface to code in fts5.c.
  170828. */
  170829. static int sqlite3Fts5GetTokenizer(
  170830. Fts5Global*,
  170831. const char **azArg,
  170832. int nArg,
  170833. Fts5Tokenizer**,
  170834. fts5_tokenizer**,
  170835. char **pzErr
  170836. );
  170837. static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
  170838. /*
  170839. ** End of interface to code in fts5.c.
  170840. **************************************************************************/
  170841. /**************************************************************************
  170842. ** Interface to code in fts5_hash.c.
  170843. */
  170844. typedef struct Fts5Hash Fts5Hash;
  170845. /*
  170846. ** Create a hash table, free a hash table.
  170847. */
  170848. static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
  170849. static void sqlite3Fts5HashFree(Fts5Hash*);
  170850. static int sqlite3Fts5HashWrite(
  170851. Fts5Hash*,
  170852. i64 iRowid, /* Rowid for this entry */
  170853. int iCol, /* Column token appears in (-ve -> delete) */
  170854. int iPos, /* Position of token within column */
  170855. char bByte,
  170856. const char *pToken, int nToken /* Token to add or remove to or from index */
  170857. );
  170858. /*
  170859. ** Empty (but do not delete) a hash table.
  170860. */
  170861. static void sqlite3Fts5HashClear(Fts5Hash*);
  170862. static int sqlite3Fts5HashQuery(
  170863. Fts5Hash*, /* Hash table to query */
  170864. const char *pTerm, int nTerm, /* Query term */
  170865. const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
  170866. int *pnDoclist /* OUT: Size of doclist in bytes */
  170867. );
  170868. static int sqlite3Fts5HashScanInit(
  170869. Fts5Hash*, /* Hash table to query */
  170870. const char *pTerm, int nTerm /* Query prefix */
  170871. );
  170872. static void sqlite3Fts5HashScanNext(Fts5Hash*);
  170873. static int sqlite3Fts5HashScanEof(Fts5Hash*);
  170874. static void sqlite3Fts5HashScanEntry(Fts5Hash *,
  170875. const char **pzTerm, /* OUT: term (nul-terminated) */
  170876. const u8 **ppDoclist, /* OUT: pointer to doclist */
  170877. int *pnDoclist /* OUT: size of doclist in bytes */
  170878. );
  170879. /*
  170880. ** End of interface to code in fts5_hash.c.
  170881. **************************************************************************/
  170882. /**************************************************************************
  170883. ** Interface to code in fts5_storage.c. fts5_storage.c contains contains
  170884. ** code to access the data stored in the %_content and %_docsize tables.
  170885. */
  170886. #define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
  170887. #define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
  170888. #define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */
  170889. typedef struct Fts5Storage Fts5Storage;
  170890. static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
  170891. static int sqlite3Fts5StorageClose(Fts5Storage *p);
  170892. static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
  170893. static int sqlite3Fts5DropAll(Fts5Config*);
  170894. static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
  170895. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
  170896. static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
  170897. static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
  170898. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
  170899. static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
  170900. static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
  170901. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
  170902. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
  170903. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
  170904. static int sqlite3Fts5StorageSync(Fts5Storage *p);
  170905. static int sqlite3Fts5StorageRollback(Fts5Storage *p);
  170906. static int sqlite3Fts5StorageConfigValue(
  170907. Fts5Storage *p, const char*, sqlite3_value*, int
  170908. );
  170909. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
  170910. static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
  170911. static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
  170912. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
  170913. static int sqlite3Fts5StorageReset(Fts5Storage *p);
  170914. /*
  170915. ** End of interface to code in fts5_storage.c.
  170916. **************************************************************************/
  170917. /**************************************************************************
  170918. ** Interface to code in fts5_expr.c.
  170919. */
  170920. typedef struct Fts5Expr Fts5Expr;
  170921. typedef struct Fts5ExprNode Fts5ExprNode;
  170922. typedef struct Fts5Parse Fts5Parse;
  170923. typedef struct Fts5Token Fts5Token;
  170924. typedef struct Fts5ExprPhrase Fts5ExprPhrase;
  170925. typedef struct Fts5ExprNearset Fts5ExprNearset;
  170926. struct Fts5Token {
  170927. const char *p; /* Token text (not NULL terminated) */
  170928. int n; /* Size of buffer p in bytes */
  170929. };
  170930. /* Parse a MATCH expression. */
  170931. static int sqlite3Fts5ExprNew(
  170932. Fts5Config *pConfig,
  170933. int iCol, /* Column on LHS of MATCH operator */
  170934. const char *zExpr,
  170935. Fts5Expr **ppNew,
  170936. char **pzErr
  170937. );
  170938. /*
  170939. ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
  170940. ** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
  170941. ** rc = sqlite3Fts5ExprNext(pExpr)
  170942. ** ){
  170943. ** // The document with rowid iRowid matches the expression!
  170944. ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
  170945. ** }
  170946. */
  170947. static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
  170948. static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
  170949. static int sqlite3Fts5ExprEof(Fts5Expr*);
  170950. static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
  170951. static void sqlite3Fts5ExprFree(Fts5Expr*);
  170952. /* Called during startup to register a UDF with SQLite */
  170953. static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
  170954. static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
  170955. static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
  170956. static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
  170957. typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
  170958. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
  170959. static int sqlite3Fts5ExprPopulatePoslists(
  170960. Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
  170961. );
  170962. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
  170963. static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
  170964. static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
  170965. /*******************************************
  170966. ** The fts5_expr.c API above this point is used by the other hand-written
  170967. ** C code in this module. The interfaces below this point are called by
  170968. ** the parser code in fts5parse.y. */
  170969. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
  170970. static Fts5ExprNode *sqlite3Fts5ParseNode(
  170971. Fts5Parse *pParse,
  170972. int eType,
  170973. Fts5ExprNode *pLeft,
  170974. Fts5ExprNode *pRight,
  170975. Fts5ExprNearset *pNear
  170976. );
  170977. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  170978. Fts5Parse *pParse,
  170979. Fts5ExprNode *pLeft,
  170980. Fts5ExprNode *pRight
  170981. );
  170982. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  170983. Fts5Parse *pParse,
  170984. Fts5ExprPhrase *pPhrase,
  170985. Fts5Token *pToken,
  170986. int bPrefix
  170987. );
  170988. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  170989. Fts5Parse*,
  170990. Fts5ExprNearset*,
  170991. Fts5ExprPhrase*
  170992. );
  170993. static Fts5Colset *sqlite3Fts5ParseColset(
  170994. Fts5Parse*,
  170995. Fts5Colset*,
  170996. Fts5Token *
  170997. );
  170998. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
  170999. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
  171000. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
  171001. static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
  171002. static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*);
  171003. static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
  171004. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
  171005. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
  171006. /*
  171007. ** End of interface to code in fts5_expr.c.
  171008. **************************************************************************/
  171009. /**************************************************************************
  171010. ** Interface to code in fts5_aux.c.
  171011. */
  171012. static int sqlite3Fts5AuxInit(fts5_api*);
  171013. /*
  171014. ** End of interface to code in fts5_aux.c.
  171015. **************************************************************************/
  171016. /**************************************************************************
  171017. ** Interface to code in fts5_tokenizer.c.
  171018. */
  171019. static int sqlite3Fts5TokenizerInit(fts5_api*);
  171020. /*
  171021. ** End of interface to code in fts5_tokenizer.c.
  171022. **************************************************************************/
  171023. /**************************************************************************
  171024. ** Interface to code in fts5_vocab.c.
  171025. */
  171026. static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
  171027. /*
  171028. ** End of interface to code in fts5_vocab.c.
  171029. **************************************************************************/
  171030. /**************************************************************************
  171031. ** Interface to automatically generated code in fts5_unicode2.c.
  171032. */
  171033. static int sqlite3Fts5UnicodeIsalnum(int c);
  171034. static int sqlite3Fts5UnicodeIsdiacritic(int c);
  171035. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
  171036. /*
  171037. ** End of interface to code in fts5_unicode2.c.
  171038. **************************************************************************/
  171039. #endif
  171040. #define FTS5_OR 1
  171041. #define FTS5_AND 2
  171042. #define FTS5_NOT 3
  171043. #define FTS5_TERM 4
  171044. #define FTS5_COLON 5
  171045. #define FTS5_MINUS 6
  171046. #define FTS5_LCP 7
  171047. #define FTS5_RCP 8
  171048. #define FTS5_STRING 9
  171049. #define FTS5_LP 10
  171050. #define FTS5_RP 11
  171051. #define FTS5_COMMA 12
  171052. #define FTS5_PLUS 13
  171053. #define FTS5_STAR 14
  171054. /*
  171055. ** 2000-05-29
  171056. **
  171057. ** The author disclaims copyright to this source code. In place of
  171058. ** a legal notice, here is a blessing:
  171059. **
  171060. ** May you do good and not evil.
  171061. ** May you find forgiveness for yourself and forgive others.
  171062. ** May you share freely, never taking more than you give.
  171063. **
  171064. *************************************************************************
  171065. ** Driver template for the LEMON parser generator.
  171066. **
  171067. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  171068. ** this template to construct a parser. The "lemon" program inserts text
  171069. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  171070. ** interstitial "-" characters) contained in this template is changed into
  171071. ** the value of the %name directive from the grammar. Otherwise, the content
  171072. ** of this template is copied straight through into the generate parser
  171073. ** source file.
  171074. **
  171075. ** The following is the concatenation of all %include directives from the
  171076. ** input grammar file:
  171077. */
  171078. /* #include <stdio.h> */
  171079. /************ Begin %include sections from the grammar ************************/
  171080. /* #include "fts5Int.h" */
  171081. /* #include "fts5parse.h" */
  171082. /*
  171083. ** Disable all error recovery processing in the parser push-down
  171084. ** automaton.
  171085. */
  171086. #define fts5YYNOERRORRECOVERY 1
  171087. /*
  171088. ** Make fts5yytestcase() the same as testcase()
  171089. */
  171090. #define fts5yytestcase(X) testcase(X)
  171091. /*
  171092. ** Indicate that sqlite3ParserFree() will never be called with a null
  171093. ** pointer.
  171094. */
  171095. #define fts5YYPARSEFREENOTNULL 1
  171096. /*
  171097. ** Alternative datatype for the argument to the malloc() routine passed
  171098. ** into sqlite3ParserAlloc(). The default is size_t.
  171099. */
  171100. #define fts5YYMALLOCARGTYPE u64
  171101. /**************** End of %include directives **********************************/
  171102. /* These constants specify the various numeric values for terminal symbols
  171103. ** in a format understandable to "makeheaders". This section is blank unless
  171104. ** "lemon" is run with the "-m" command-line option.
  171105. ***************** Begin makeheaders token definitions *************************/
  171106. /**************** End makeheaders token definitions ***************************/
  171107. /* The next sections is a series of control #defines.
  171108. ** various aspects of the generated parser.
  171109. ** fts5YYCODETYPE is the data type used to store the integer codes
  171110. ** that represent terminal and non-terminal symbols.
  171111. ** "unsigned char" is used if there are fewer than
  171112. ** 256 symbols. Larger types otherwise.
  171113. ** fts5YYNOCODE is a number of type fts5YYCODETYPE that is not used for
  171114. ** any terminal or nonterminal symbol.
  171115. ** fts5YYFALLBACK If defined, this indicates that one or more tokens
  171116. ** (also known as: "terminal symbols") have fall-back
  171117. ** values which should be used if the original symbol
  171118. ** would not parse. This permits keywords to sometimes
  171119. ** be used as identifiers, for example.
  171120. ** fts5YYACTIONTYPE is the data type used for "action codes" - numbers
  171121. ** that indicate what to do in response to the next
  171122. ** token.
  171123. ** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal
  171124. ** symbols. Background: A "minor type" is a semantic
  171125. ** value associated with a terminal or non-terminal
  171126. ** symbols. For example, for an "ID" terminal symbol,
  171127. ** the minor type might be the name of the identifier.
  171128. ** Each non-terminal can have a different minor type.
  171129. ** Terminal symbols all have the same minor type, though.
  171130. ** This macros defines the minor type for terminal
  171131. ** symbols.
  171132. ** fts5YYMINORTYPE is the data type used for all minor types.
  171133. ** This is typically a union of many types, one of
  171134. ** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union
  171135. ** for terminal symbols is called "fts5yy0".
  171136. ** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If
  171137. ** zero the stack is dynamically sized using realloc()
  171138. ** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument
  171139. ** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument
  171140. ** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser
  171141. ** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser
  171142. ** fts5YYERRORSYMBOL is the code number of the error symbol. If not
  171143. ** defined, then do no error processing.
  171144. ** fts5YYNSTATE the combined number of states.
  171145. ** fts5YYNRULE the number of rules in the grammar
  171146. ** fts5YY_MAX_SHIFT Maximum value for shift actions
  171147. ** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  171148. ** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  171149. ** fts5YY_MIN_REDUCE Maximum value for reduce actions
  171150. ** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error
  171151. ** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept
  171152. ** fts5YY_NO_ACTION The fts5yy_action[] code for no-op
  171153. */
  171154. #ifndef INTERFACE
  171155. # define INTERFACE 1
  171156. #endif
  171157. /************* Begin control #defines *****************************************/
  171158. #define fts5YYCODETYPE unsigned char
  171159. #define fts5YYNOCODE 28
  171160. #define fts5YYACTIONTYPE unsigned char
  171161. #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
  171162. typedef union {
  171163. int fts5yyinit;
  171164. sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
  171165. int fts5yy4;
  171166. Fts5Colset* fts5yy11;
  171167. Fts5ExprNode* fts5yy24;
  171168. Fts5ExprNearset* fts5yy46;
  171169. Fts5ExprPhrase* fts5yy53;
  171170. } fts5YYMINORTYPE;
  171171. #ifndef fts5YYSTACKDEPTH
  171172. #define fts5YYSTACKDEPTH 100
  171173. #endif
  171174. #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
  171175. #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
  171176. #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
  171177. #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
  171178. #define fts5YYNSTATE 33
  171179. #define fts5YYNRULE 27
  171180. #define fts5YY_MAX_SHIFT 32
  171181. #define fts5YY_MIN_SHIFTREDUCE 50
  171182. #define fts5YY_MAX_SHIFTREDUCE 76
  171183. #define fts5YY_MIN_REDUCE 77
  171184. #define fts5YY_MAX_REDUCE 103
  171185. #define fts5YY_ERROR_ACTION 104
  171186. #define fts5YY_ACCEPT_ACTION 105
  171187. #define fts5YY_NO_ACTION 106
  171188. /************* End control #defines *******************************************/
  171189. /* Define the fts5yytestcase() macro to be a no-op if is not already defined
  171190. ** otherwise.
  171191. **
  171192. ** Applications can choose to define fts5yytestcase() in the %include section
  171193. ** to a macro that can assist in verifying code coverage. For production
  171194. ** code the fts5yytestcase() macro should be turned off. But it is useful
  171195. ** for testing.
  171196. */
  171197. #ifndef fts5yytestcase
  171198. # define fts5yytestcase(X)
  171199. #endif
  171200. /* Next are the tables used to determine what action to take based on the
  171201. ** current state and lookahead token. These tables are used to implement
  171202. ** functions that take a state number and lookahead value and return an
  171203. ** action integer.
  171204. **
  171205. ** Suppose the action integer is N. Then the action is determined as
  171206. ** follows
  171207. **
  171208. ** 0 <= N <= fts5YY_MAX_SHIFT Shift N. That is, push the lookahead
  171209. ** token onto the stack and goto state N.
  171210. **
  171211. ** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  171212. ** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
  171213. **
  171214. ** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE
  171215. ** and fts5YY_MAX_REDUCE
  171216. **
  171217. ** N == fts5YY_ERROR_ACTION A syntax error has occurred.
  171218. **
  171219. ** N == fts5YY_ACCEPT_ACTION The parser accepts its input.
  171220. **
  171221. ** N == fts5YY_NO_ACTION No such action. Denotes unused
  171222. ** slots in the fts5yy_action[] table.
  171223. **
  171224. ** The action table is constructed as a single large table named fts5yy_action[].
  171225. ** Given state S and lookahead X, the action is computed as either:
  171226. **
  171227. ** (A) N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
  171228. ** (B) N = fts5yy_default[S]
  171229. **
  171230. ** The (A) formula is preferred. The B formula is used instead if:
  171231. ** (1) The fts5yy_shift_ofst[S]+X value is out of range, or
  171232. ** (2) fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X, or
  171233. ** (3) fts5yy_shift_ofst[S] equal fts5YY_SHIFT_USE_DFLT.
  171234. ** (Implementation note: fts5YY_SHIFT_USE_DFLT is chosen so that
  171235. ** fts5YY_SHIFT_USE_DFLT+X will be out of range for all possible lookaheads X.
  171236. ** Hence only tests (1) and (2) need to be evaluated.)
  171237. **
  171238. ** The formulas above are for computing the action when the lookahead is
  171239. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  171240. ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
  171241. ** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of
  171242. ** fts5YY_SHIFT_USE_DFLT.
  171243. **
  171244. ** The following are the tables generated in this section:
  171245. **
  171246. ** fts5yy_action[] A single table containing all actions.
  171247. ** fts5yy_lookahead[] A table containing the lookahead for each entry in
  171248. ** fts5yy_action. Used to detect hash collisions.
  171249. ** fts5yy_shift_ofst[] For each state, the offset into fts5yy_action for
  171250. ** shifting terminals.
  171251. ** fts5yy_reduce_ofst[] For each state, the offset into fts5yy_action for
  171252. ** shifting non-terminals after a reduce.
  171253. ** fts5yy_default[] Default action for each state.
  171254. **
  171255. *********** Begin parsing tables **********************************************/
  171256. #define fts5YY_ACTTAB_COUNT (98)
  171257. static const fts5YYACTIONTYPE fts5yy_action[] = {
  171258. /* 0 */ 105, 19, 63, 6, 26, 66, 65, 24, 24, 17,
  171259. /* 10 */ 63, 6, 26, 16, 65, 54, 24, 18, 63, 6,
  171260. /* 20 */ 26, 10, 65, 12, 24, 75, 59, 63, 6, 26,
  171261. /* 30 */ 13, 65, 75, 24, 20, 63, 6, 26, 74, 65,
  171262. /* 40 */ 56, 24, 27, 63, 6, 26, 73, 65, 21, 24,
  171263. /* 50 */ 23, 15, 30, 11, 1, 64, 22, 25, 9, 65,
  171264. /* 60 */ 7, 24, 3, 4, 5, 3, 4, 5, 3, 77,
  171265. /* 70 */ 4, 5, 3, 61, 23, 15, 60, 11, 80, 12,
  171266. /* 80 */ 2, 13, 68, 10, 29, 52, 55, 75, 31, 32,
  171267. /* 90 */ 8, 28, 5, 3, 51, 55, 72, 14,
  171268. };
  171269. static const fts5YYCODETYPE fts5yy_lookahead[] = {
  171270. /* 0 */ 16, 17, 18, 19, 20, 22, 22, 24, 24, 17,
  171271. /* 10 */ 18, 19, 20, 7, 22, 9, 24, 17, 18, 19,
  171272. /* 20 */ 20, 10, 22, 9, 24, 14, 17, 18, 19, 20,
  171273. /* 30 */ 9, 22, 14, 24, 17, 18, 19, 20, 26, 22,
  171274. /* 40 */ 9, 24, 17, 18, 19, 20, 26, 22, 21, 24,
  171275. /* 50 */ 6, 7, 13, 9, 10, 18, 21, 20, 5, 22,
  171276. /* 60 */ 5, 24, 3, 1, 2, 3, 1, 2, 3, 0,
  171277. /* 70 */ 1, 2, 3, 11, 6, 7, 11, 9, 5, 9,
  171278. /* 80 */ 10, 9, 11, 10, 12, 8, 9, 14, 24, 25,
  171279. /* 90 */ 23, 24, 2, 3, 8, 9, 9, 9,
  171280. };
  171281. #define fts5YY_SHIFT_USE_DFLT (98)
  171282. #define fts5YY_SHIFT_COUNT (32)
  171283. #define fts5YY_SHIFT_MIN (0)
  171284. #define fts5YY_SHIFT_MAX (90)
  171285. static const unsigned char fts5yy_shift_ofst[] = {
  171286. /* 0 */ 44, 44, 44, 44, 44, 44, 68, 70, 72, 14,
  171287. /* 10 */ 21, 73, 11, 18, 18, 31, 31, 62, 65, 69,
  171288. /* 20 */ 90, 77, 86, 6, 39, 53, 55, 59, 39, 87,
  171289. /* 30 */ 88, 39, 71,
  171290. };
  171291. #define fts5YY_REDUCE_USE_DFLT (-18)
  171292. #define fts5YY_REDUCE_COUNT (16)
  171293. #define fts5YY_REDUCE_MIN (-17)
  171294. #define fts5YY_REDUCE_MAX (67)
  171295. static const signed char fts5yy_reduce_ofst[] = {
  171296. /* 0 */ -16, -8, 0, 9, 17, 25, 37, -17, 64, -17,
  171297. /* 10 */ 67, 12, 12, 12, 20, 27, 35,
  171298. };
  171299. static const fts5YYACTIONTYPE fts5yy_default[] = {
  171300. /* 0 */ 104, 104, 104, 104, 104, 104, 89, 104, 98, 104,
  171301. /* 10 */ 104, 103, 103, 103, 103, 104, 104, 104, 104, 104,
  171302. /* 20 */ 85, 104, 104, 104, 94, 104, 104, 84, 96, 104,
  171303. /* 30 */ 104, 97, 104,
  171304. };
  171305. /********** End of lemon-generated parsing tables *****************************/
  171306. /* The next table maps tokens (terminal symbols) into fallback tokens.
  171307. ** If a construct like the following:
  171308. **
  171309. ** %fallback ID X Y Z.
  171310. **
  171311. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  171312. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  171313. ** but it does not parse, the type of the token is changed to ID and
  171314. ** the parse is retried before an error is thrown.
  171315. **
  171316. ** This feature can be used, for example, to cause some keywords in a language
  171317. ** to revert to identifiers if they keyword does not apply in the context where
  171318. ** it appears.
  171319. */
  171320. #ifdef fts5YYFALLBACK
  171321. static const fts5YYCODETYPE fts5yyFallback[] = {
  171322. };
  171323. #endif /* fts5YYFALLBACK */
  171324. /* The following structure represents a single element of the
  171325. ** parser's stack. Information stored includes:
  171326. **
  171327. ** + The state number for the parser at this level of the stack.
  171328. **
  171329. ** + The value of the token stored at this level of the stack.
  171330. ** (In other words, the "major" token.)
  171331. **
  171332. ** + The semantic value stored at this level of the stack. This is
  171333. ** the information used by the action routines in the grammar.
  171334. ** It is sometimes called the "minor" token.
  171335. **
  171336. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  171337. ** actually contains the reduce action for the second half of the
  171338. ** SHIFTREDUCE.
  171339. */
  171340. struct fts5yyStackEntry {
  171341. fts5YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  171342. fts5YYCODETYPE major; /* The major token value. This is the code
  171343. ** number for the token at this stack level */
  171344. fts5YYMINORTYPE minor; /* The user-supplied minor token value. This
  171345. ** is the value of the token */
  171346. };
  171347. typedef struct fts5yyStackEntry fts5yyStackEntry;
  171348. /* The state of the parser is completely contained in an instance of
  171349. ** the following structure */
  171350. struct fts5yyParser {
  171351. fts5yyStackEntry *fts5yytos; /* Pointer to top element of the stack */
  171352. #ifdef fts5YYTRACKMAXSTACKDEPTH
  171353. int fts5yyhwm; /* High-water mark of the stack */
  171354. #endif
  171355. #ifndef fts5YYNOERRORRECOVERY
  171356. int fts5yyerrcnt; /* Shifts left before out of the error */
  171357. #endif
  171358. sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */
  171359. #if fts5YYSTACKDEPTH<=0
  171360. int fts5yystksz; /* Current side of the stack */
  171361. fts5yyStackEntry *fts5yystack; /* The parser's stack */
  171362. fts5yyStackEntry fts5yystk0; /* First stack entry */
  171363. #else
  171364. fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */
  171365. #endif
  171366. };
  171367. typedef struct fts5yyParser fts5yyParser;
  171368. #ifndef NDEBUG
  171369. /* #include <stdio.h> */
  171370. static FILE *fts5yyTraceFILE = 0;
  171371. static char *fts5yyTracePrompt = 0;
  171372. #endif /* NDEBUG */
  171373. #ifndef NDEBUG
  171374. /*
  171375. ** Turn parser tracing on by giving a stream to which to write the trace
  171376. ** and a prompt to preface each trace message. Tracing is turned off
  171377. ** by making either argument NULL
  171378. **
  171379. ** Inputs:
  171380. ** <ul>
  171381. ** <li> A FILE* to which trace output should be written.
  171382. ** If NULL, then tracing is turned off.
  171383. ** <li> A prefix string written at the beginning of every
  171384. ** line of trace output. If NULL, then tracing is
  171385. ** turned off.
  171386. ** </ul>
  171387. **
  171388. ** Outputs:
  171389. ** None.
  171390. */
  171391. static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  171392. fts5yyTraceFILE = TraceFILE;
  171393. fts5yyTracePrompt = zTracePrompt;
  171394. if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
  171395. else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
  171396. }
  171397. #endif /* NDEBUG */
  171398. #ifndef NDEBUG
  171399. /* For tracing shifts, the names of all terminals and nonterminals
  171400. ** are required. The following table supplies these names */
  171401. static const char *const fts5yyTokenName[] = {
  171402. "$", "OR", "AND", "NOT",
  171403. "TERM", "COLON", "MINUS", "LCP",
  171404. "RCP", "STRING", "LP", "RP",
  171405. "COMMA", "PLUS", "STAR", "error",
  171406. "input", "expr", "cnearset", "exprlist",
  171407. "colset", "colsetlist", "nearset", "nearphrases",
  171408. "phrase", "neardist_opt", "star_opt",
  171409. };
  171410. #endif /* NDEBUG */
  171411. #ifndef NDEBUG
  171412. /* For tracing reduce actions, the names of all rules are required.
  171413. */
  171414. static const char *const fts5yyRuleName[] = {
  171415. /* 0 */ "input ::= expr",
  171416. /* 1 */ "colset ::= MINUS LCP colsetlist RCP",
  171417. /* 2 */ "colset ::= LCP colsetlist RCP",
  171418. /* 3 */ "colset ::= STRING",
  171419. /* 4 */ "colset ::= MINUS STRING",
  171420. /* 5 */ "colsetlist ::= colsetlist STRING",
  171421. /* 6 */ "colsetlist ::= STRING",
  171422. /* 7 */ "expr ::= expr AND expr",
  171423. /* 8 */ "expr ::= expr OR expr",
  171424. /* 9 */ "expr ::= expr NOT expr",
  171425. /* 10 */ "expr ::= colset COLON LP expr RP",
  171426. /* 11 */ "expr ::= LP expr RP",
  171427. /* 12 */ "expr ::= exprlist",
  171428. /* 13 */ "exprlist ::= cnearset",
  171429. /* 14 */ "exprlist ::= exprlist cnearset",
  171430. /* 15 */ "cnearset ::= nearset",
  171431. /* 16 */ "cnearset ::= colset COLON nearset",
  171432. /* 17 */ "nearset ::= phrase",
  171433. /* 18 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
  171434. /* 19 */ "nearphrases ::= phrase",
  171435. /* 20 */ "nearphrases ::= nearphrases phrase",
  171436. /* 21 */ "neardist_opt ::=",
  171437. /* 22 */ "neardist_opt ::= COMMA STRING",
  171438. /* 23 */ "phrase ::= phrase PLUS STRING star_opt",
  171439. /* 24 */ "phrase ::= STRING star_opt",
  171440. /* 25 */ "star_opt ::= STAR",
  171441. /* 26 */ "star_opt ::=",
  171442. };
  171443. #endif /* NDEBUG */
  171444. #if fts5YYSTACKDEPTH<=0
  171445. /*
  171446. ** Try to increase the size of the parser stack. Return the number
  171447. ** of errors. Return 0 on success.
  171448. */
  171449. static int fts5yyGrowStack(fts5yyParser *p){
  171450. int newSize;
  171451. int idx;
  171452. fts5yyStackEntry *pNew;
  171453. newSize = p->fts5yystksz*2 + 100;
  171454. idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
  171455. if( p->fts5yystack==&p->fts5yystk0 ){
  171456. pNew = malloc(newSize*sizeof(pNew[0]));
  171457. if( pNew ) pNew[0] = p->fts5yystk0;
  171458. }else{
  171459. pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
  171460. }
  171461. if( pNew ){
  171462. p->fts5yystack = pNew;
  171463. p->fts5yytos = &p->fts5yystack[idx];
  171464. #ifndef NDEBUG
  171465. if( fts5yyTraceFILE ){
  171466. fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
  171467. fts5yyTracePrompt, p->fts5yystksz, newSize);
  171468. }
  171469. #endif
  171470. p->fts5yystksz = newSize;
  171471. }
  171472. return pNew==0;
  171473. }
  171474. #endif
  171475. /* Datatype of the argument to the memory allocated passed as the
  171476. ** second argument to sqlite3Fts5ParserAlloc() below. This can be changed by
  171477. ** putting an appropriate #define in the %include section of the input
  171478. ** grammar.
  171479. */
  171480. #ifndef fts5YYMALLOCARGTYPE
  171481. # define fts5YYMALLOCARGTYPE size_t
  171482. #endif
  171483. /* Initialize a new parser that has already been allocated.
  171484. */
  171485. static void sqlite3Fts5ParserInit(void *fts5yypParser){
  171486. fts5yyParser *pParser = (fts5yyParser*)fts5yypParser;
  171487. #ifdef fts5YYTRACKMAXSTACKDEPTH
  171488. pParser->fts5yyhwm = 0;
  171489. #endif
  171490. #if fts5YYSTACKDEPTH<=0
  171491. pParser->fts5yytos = NULL;
  171492. pParser->fts5yystack = NULL;
  171493. pParser->fts5yystksz = 0;
  171494. if( fts5yyGrowStack(pParser) ){
  171495. pParser->fts5yystack = &pParser->fts5yystk0;
  171496. pParser->fts5yystksz = 1;
  171497. }
  171498. #endif
  171499. #ifndef fts5YYNOERRORRECOVERY
  171500. pParser->fts5yyerrcnt = -1;
  171501. #endif
  171502. pParser->fts5yytos = pParser->fts5yystack;
  171503. pParser->fts5yystack[0].stateno = 0;
  171504. pParser->fts5yystack[0].major = 0;
  171505. }
  171506. #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
  171507. /*
  171508. ** This function allocates a new parser.
  171509. ** The only argument is a pointer to a function which works like
  171510. ** malloc.
  171511. **
  171512. ** Inputs:
  171513. ** A pointer to the function used to allocate memory.
  171514. **
  171515. ** Outputs:
  171516. ** A pointer to a parser. This pointer is used in subsequent calls
  171517. ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
  171518. */
  171519. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){
  171520. fts5yyParser *pParser;
  171521. pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
  171522. if( pParser ) sqlite3Fts5ParserInit(pParser);
  171523. return pParser;
  171524. }
  171525. #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
  171526. /* The following function deletes the "minor type" or semantic value
  171527. ** associated with a symbol. The symbol can be either a terminal
  171528. ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
  171529. ** a pointer to the value to be deleted. The code used to do the
  171530. ** deletions is derived from the %destructor and/or %token_destructor
  171531. ** directives of the input grammar.
  171532. */
  171533. static void fts5yy_destructor(
  171534. fts5yyParser *fts5yypParser, /* The parser */
  171535. fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */
  171536. fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */
  171537. ){
  171538. sqlite3Fts5ParserARG_FETCH;
  171539. switch( fts5yymajor ){
  171540. /* Here is inserted the actions which take place when a
  171541. ** terminal or non-terminal is destroyed. This can happen
  171542. ** when the symbol is popped from the stack during a
  171543. ** reduce or during error processing or when a parser is
  171544. ** being destroyed before it is finished parsing.
  171545. **
  171546. ** Note: during a reduce, the only symbols destroyed are those
  171547. ** which appear on the RHS of the rule, but which are *not* used
  171548. ** inside the C code.
  171549. */
  171550. /********* Begin destructor definitions ***************************************/
  171551. case 16: /* input */
  171552. {
  171553. (void)pParse;
  171554. }
  171555. break;
  171556. case 17: /* expr */
  171557. case 18: /* cnearset */
  171558. case 19: /* exprlist */
  171559. {
  171560. sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24));
  171561. }
  171562. break;
  171563. case 20: /* colset */
  171564. case 21: /* colsetlist */
  171565. {
  171566. sqlite3_free((fts5yypminor->fts5yy11));
  171567. }
  171568. break;
  171569. case 22: /* nearset */
  171570. case 23: /* nearphrases */
  171571. {
  171572. sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46));
  171573. }
  171574. break;
  171575. case 24: /* phrase */
  171576. {
  171577. sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53));
  171578. }
  171579. break;
  171580. /********* End destructor definitions *****************************************/
  171581. default: break; /* If no destructor action specified: do nothing */
  171582. }
  171583. }
  171584. /*
  171585. ** Pop the parser's stack once.
  171586. **
  171587. ** If there is a destructor routine associated with the token which
  171588. ** is popped from the stack, then call it.
  171589. */
  171590. static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
  171591. fts5yyStackEntry *fts5yytos;
  171592. assert( pParser->fts5yytos!=0 );
  171593. assert( pParser->fts5yytos > pParser->fts5yystack );
  171594. fts5yytos = pParser->fts5yytos--;
  171595. #ifndef NDEBUG
  171596. if( fts5yyTraceFILE ){
  171597. fprintf(fts5yyTraceFILE,"%sPopping %s\n",
  171598. fts5yyTracePrompt,
  171599. fts5yyTokenName[fts5yytos->major]);
  171600. }
  171601. #endif
  171602. fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
  171603. }
  171604. /*
  171605. ** Clear all secondary memory allocations from the parser
  171606. */
  171607. static void sqlite3Fts5ParserFinalize(void *p){
  171608. fts5yyParser *pParser = (fts5yyParser*)p;
  171609. while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
  171610. #if fts5YYSTACKDEPTH<=0
  171611. if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
  171612. #endif
  171613. }
  171614. #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
  171615. /*
  171616. ** Deallocate and destroy a parser. Destructors are called for
  171617. ** all stack elements before shutting the parser down.
  171618. **
  171619. ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
  171620. ** is defined in a %include section of the input grammar) then it is
  171621. ** assumed that the input pointer is never NULL.
  171622. */
  171623. static void sqlite3Fts5ParserFree(
  171624. void *p, /* The parser to be deleted */
  171625. void (*freeProc)(void*) /* Function used to reclaim memory */
  171626. ){
  171627. #ifndef fts5YYPARSEFREENEVERNULL
  171628. if( p==0 ) return;
  171629. #endif
  171630. sqlite3Fts5ParserFinalize(p);
  171631. (*freeProc)(p);
  171632. }
  171633. #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
  171634. /*
  171635. ** Return the peak depth of the stack for a parser.
  171636. */
  171637. #ifdef fts5YYTRACKMAXSTACKDEPTH
  171638. static int sqlite3Fts5ParserStackPeak(void *p){
  171639. fts5yyParser *pParser = (fts5yyParser*)p;
  171640. return pParser->fts5yyhwm;
  171641. }
  171642. #endif
  171643. /*
  171644. ** Find the appropriate action for a parser given the terminal
  171645. ** look-ahead token iLookAhead.
  171646. */
  171647. static unsigned int fts5yy_find_shift_action(
  171648. fts5yyParser *pParser, /* The parser */
  171649. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  171650. ){
  171651. int i;
  171652. int stateno = pParser->fts5yytos->stateno;
  171653. if( stateno>=fts5YY_MIN_REDUCE ) return stateno;
  171654. assert( stateno <= fts5YY_SHIFT_COUNT );
  171655. do{
  171656. i = fts5yy_shift_ofst[stateno];
  171657. assert( iLookAhead!=fts5YYNOCODE );
  171658. i += iLookAhead;
  171659. if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
  171660. #ifdef fts5YYFALLBACK
  171661. fts5YYCODETYPE iFallback; /* Fallback token */
  171662. if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
  171663. && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
  171664. #ifndef NDEBUG
  171665. if( fts5yyTraceFILE ){
  171666. fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
  171667. fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
  171668. }
  171669. #endif
  171670. assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  171671. iLookAhead = iFallback;
  171672. continue;
  171673. }
  171674. #endif
  171675. #ifdef fts5YYWILDCARD
  171676. {
  171677. int j = i - iLookAhead + fts5YYWILDCARD;
  171678. if(
  171679. #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
  171680. j>=0 &&
  171681. #endif
  171682. #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
  171683. j<fts5YY_ACTTAB_COUNT &&
  171684. #endif
  171685. fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0
  171686. ){
  171687. #ifndef NDEBUG
  171688. if( fts5yyTraceFILE ){
  171689. fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
  171690. fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
  171691. fts5yyTokenName[fts5YYWILDCARD]);
  171692. }
  171693. #endif /* NDEBUG */
  171694. return fts5yy_action[j];
  171695. }
  171696. }
  171697. #endif /* fts5YYWILDCARD */
  171698. return fts5yy_default[stateno];
  171699. }else{
  171700. return fts5yy_action[i];
  171701. }
  171702. }while(1);
  171703. }
  171704. /*
  171705. ** Find the appropriate action for a parser given the non-terminal
  171706. ** look-ahead token iLookAhead.
  171707. */
  171708. static int fts5yy_find_reduce_action(
  171709. int stateno, /* Current state number */
  171710. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  171711. ){
  171712. int i;
  171713. #ifdef fts5YYERRORSYMBOL
  171714. if( stateno>fts5YY_REDUCE_COUNT ){
  171715. return fts5yy_default[stateno];
  171716. }
  171717. #else
  171718. assert( stateno<=fts5YY_REDUCE_COUNT );
  171719. #endif
  171720. i = fts5yy_reduce_ofst[stateno];
  171721. assert( i!=fts5YY_REDUCE_USE_DFLT );
  171722. assert( iLookAhead!=fts5YYNOCODE );
  171723. i += iLookAhead;
  171724. #ifdef fts5YYERRORSYMBOL
  171725. if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
  171726. return fts5yy_default[stateno];
  171727. }
  171728. #else
  171729. assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
  171730. assert( fts5yy_lookahead[i]==iLookAhead );
  171731. #endif
  171732. return fts5yy_action[i];
  171733. }
  171734. /*
  171735. ** The following routine is called if the stack overflows.
  171736. */
  171737. static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
  171738. sqlite3Fts5ParserARG_FETCH;
  171739. #ifndef NDEBUG
  171740. if( fts5yyTraceFILE ){
  171741. fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
  171742. }
  171743. #endif
  171744. while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
  171745. /* Here code is inserted which will execute if the parser
  171746. ** stack every overflows */
  171747. /******** Begin %stack_overflow code ******************************************/
  171748. sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
  171749. /******** End %stack_overflow code ********************************************/
  171750. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  171751. }
  171752. /*
  171753. ** Print tracing information for a SHIFT action
  171754. */
  171755. #ifndef NDEBUG
  171756. static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){
  171757. if( fts5yyTraceFILE ){
  171758. if( fts5yyNewState<fts5YYNSTATE ){
  171759. fprintf(fts5yyTraceFILE,"%sShift '%s', go to state %d\n",
  171760. fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major],
  171761. fts5yyNewState);
  171762. }else{
  171763. fprintf(fts5yyTraceFILE,"%sShift '%s'\n",
  171764. fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yytos->major]);
  171765. }
  171766. }
  171767. }
  171768. #else
  171769. # define fts5yyTraceShift(X,Y)
  171770. #endif
  171771. /*
  171772. ** Perform a shift action.
  171773. */
  171774. static void fts5yy_shift(
  171775. fts5yyParser *fts5yypParser, /* The parser to be shifted */
  171776. int fts5yyNewState, /* The new state to shift in */
  171777. int fts5yyMajor, /* The major token to shift in */
  171778. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor /* The minor token to shift in */
  171779. ){
  171780. fts5yyStackEntry *fts5yytos;
  171781. fts5yypParser->fts5yytos++;
  171782. #ifdef fts5YYTRACKMAXSTACKDEPTH
  171783. if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
  171784. fts5yypParser->fts5yyhwm++;
  171785. assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
  171786. }
  171787. #endif
  171788. #if fts5YYSTACKDEPTH>0
  171789. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH] ){
  171790. fts5yypParser->fts5yytos--;
  171791. fts5yyStackOverflow(fts5yypParser);
  171792. return;
  171793. }
  171794. #else
  171795. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
  171796. if( fts5yyGrowStack(fts5yypParser) ){
  171797. fts5yypParser->fts5yytos--;
  171798. fts5yyStackOverflow(fts5yypParser);
  171799. return;
  171800. }
  171801. }
  171802. #endif
  171803. if( fts5yyNewState > fts5YY_MAX_SHIFT ){
  171804. fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
  171805. }
  171806. fts5yytos = fts5yypParser->fts5yytos;
  171807. fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
  171808. fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
  171809. fts5yytos->minor.fts5yy0 = fts5yyMinor;
  171810. fts5yyTraceShift(fts5yypParser, fts5yyNewState);
  171811. }
  171812. /* The following table contains information about every rule that
  171813. ** is used during the reduce.
  171814. */
  171815. static const struct {
  171816. fts5YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  171817. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  171818. } fts5yyRuleInfo[] = {
  171819. { 16, 1 },
  171820. { 20, 4 },
  171821. { 20, 3 },
  171822. { 20, 1 },
  171823. { 20, 2 },
  171824. { 21, 2 },
  171825. { 21, 1 },
  171826. { 17, 3 },
  171827. { 17, 3 },
  171828. { 17, 3 },
  171829. { 17, 5 },
  171830. { 17, 3 },
  171831. { 17, 1 },
  171832. { 19, 1 },
  171833. { 19, 2 },
  171834. { 18, 1 },
  171835. { 18, 3 },
  171836. { 22, 1 },
  171837. { 22, 5 },
  171838. { 23, 1 },
  171839. { 23, 2 },
  171840. { 25, 0 },
  171841. { 25, 2 },
  171842. { 24, 4 },
  171843. { 24, 2 },
  171844. { 26, 1 },
  171845. { 26, 0 },
  171846. };
  171847. static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */
  171848. /*
  171849. ** Perform a reduce action and the shift that must immediately
  171850. ** follow the reduce.
  171851. */
  171852. static void fts5yy_reduce(
  171853. fts5yyParser *fts5yypParser, /* The parser */
  171854. unsigned int fts5yyruleno /* Number of the rule by which to reduce */
  171855. ){
  171856. int fts5yygoto; /* The next state */
  171857. int fts5yyact; /* The next action */
  171858. fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */
  171859. int fts5yysize; /* Amount to pop the stack */
  171860. sqlite3Fts5ParserARG_FETCH;
  171861. fts5yymsp = fts5yypParser->fts5yytos;
  171862. #ifndef NDEBUG
  171863. if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
  171864. fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
  171865. fprintf(fts5yyTraceFILE, "%sReduce [%s], go to state %d.\n", fts5yyTracePrompt,
  171866. fts5yyRuleName[fts5yyruleno], fts5yymsp[-fts5yysize].stateno);
  171867. }
  171868. #endif /* NDEBUG */
  171869. /* Check that the stack is large enough to grow by a single entry
  171870. ** if the RHS of the rule is empty. This ensures that there is room
  171871. ** enough on the stack to push the LHS value */
  171872. if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){
  171873. #ifdef fts5YYTRACKMAXSTACKDEPTH
  171874. if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
  171875. fts5yypParser->fts5yyhwm++;
  171876. assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
  171877. }
  171878. #endif
  171879. #if fts5YYSTACKDEPTH>0
  171880. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1] ){
  171881. fts5yyStackOverflow(fts5yypParser);
  171882. return;
  171883. }
  171884. #else
  171885. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
  171886. if( fts5yyGrowStack(fts5yypParser) ){
  171887. fts5yyStackOverflow(fts5yypParser);
  171888. return;
  171889. }
  171890. fts5yymsp = fts5yypParser->fts5yytos;
  171891. }
  171892. #endif
  171893. }
  171894. switch( fts5yyruleno ){
  171895. /* Beginning here are the reduction cases. A typical example
  171896. ** follows:
  171897. ** case 0:
  171898. ** #line <lineno> <grammarfile>
  171899. ** { ... } // User supplied code
  171900. ** #line <lineno> <thisfile>
  171901. ** break;
  171902. */
  171903. /********** Begin reduce actions **********************************************/
  171904. fts5YYMINORTYPE fts5yylhsminor;
  171905. case 0: /* input ::= expr */
  171906. { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }
  171907. break;
  171908. case 1: /* colset ::= MINUS LCP colsetlist RCP */
  171909. {
  171910. fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
  171911. }
  171912. break;
  171913. case 2: /* colset ::= LCP colsetlist RCP */
  171914. { fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; }
  171915. break;
  171916. case 3: /* colset ::= STRING */
  171917. {
  171918. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  171919. }
  171920. fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  171921. break;
  171922. case 4: /* colset ::= MINUS STRING */
  171923. {
  171924. fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  171925. fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
  171926. }
  171927. break;
  171928. case 5: /* colsetlist ::= colsetlist STRING */
  171929. {
  171930. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }
  171931. fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  171932. break;
  171933. case 6: /* colsetlist ::= STRING */
  171934. {
  171935. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  171936. }
  171937. fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  171938. break;
  171939. case 7: /* expr ::= expr AND expr */
  171940. {
  171941. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  171942. }
  171943. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  171944. break;
  171945. case 8: /* expr ::= expr OR expr */
  171946. {
  171947. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  171948. }
  171949. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  171950. break;
  171951. case 9: /* expr ::= expr NOT expr */
  171952. {
  171953. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  171954. }
  171955. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  171956. break;
  171957. case 10: /* expr ::= colset COLON LP expr RP */
  171958. {
  171959. sqlite3Fts5ParseSetColset(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[-4].minor.fts5yy11);
  171960. fts5yylhsminor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;
  171961. }
  171962. fts5yymsp[-4].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  171963. break;
  171964. case 11: /* expr ::= LP expr RP */
  171965. {fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;}
  171966. break;
  171967. case 12: /* expr ::= exprlist */
  171968. case 13: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==13);
  171969. {fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;}
  171970. fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  171971. break;
  171972. case 14: /* exprlist ::= exprlist cnearset */
  171973. {
  171974. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24);
  171975. }
  171976. fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  171977. break;
  171978. case 15: /* cnearset ::= nearset */
  171979. {
  171980. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
  171981. }
  171982. fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  171983. break;
  171984. case 16: /* cnearset ::= colset COLON nearset */
  171985. {
  171986. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
  171987. sqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy24, fts5yymsp[-2].minor.fts5yy11);
  171988. }
  171989. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  171990. break;
  171991. case 17: /* nearset ::= phrase */
  171992. { fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); }
  171993. fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  171994. break;
  171995. case 18: /* nearset ::= STRING LP nearphrases neardist_opt RP */
  171996. {
  171997. sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
  171998. sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0);
  171999. fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46;
  172000. }
  172001. fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  172002. break;
  172003. case 19: /* nearphrases ::= phrase */
  172004. {
  172005. fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
  172006. }
  172007. fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  172008. break;
  172009. case 20: /* nearphrases ::= nearphrases phrase */
  172010. {
  172011. fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53);
  172012. }
  172013. fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  172014. break;
  172015. case 21: /* neardist_opt ::= */
  172016. { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
  172017. break;
  172018. case 22: /* neardist_opt ::= COMMA STRING */
  172019. { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
  172020. break;
  172021. case 23: /* phrase ::= phrase PLUS STRING star_opt */
  172022. {
  172023. fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
  172024. }
  172025. fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
  172026. break;
  172027. case 24: /* phrase ::= STRING star_opt */
  172028. {
  172029. fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
  172030. }
  172031. fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
  172032. break;
  172033. case 25: /* star_opt ::= STAR */
  172034. { fts5yymsp[0].minor.fts5yy4 = 1; }
  172035. break;
  172036. case 26: /* star_opt ::= */
  172037. { fts5yymsp[1].minor.fts5yy4 = 0; }
  172038. break;
  172039. default:
  172040. break;
  172041. /********** End reduce actions ************************************************/
  172042. };
  172043. assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
  172044. fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
  172045. fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
  172046. fts5yyact = fts5yy_find_reduce_action(fts5yymsp[-fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
  172047. if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
  172048. if( fts5yyact>fts5YY_MAX_SHIFT ){
  172049. fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
  172050. }
  172051. fts5yymsp -= fts5yysize-1;
  172052. fts5yypParser->fts5yytos = fts5yymsp;
  172053. fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
  172054. fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
  172055. fts5yyTraceShift(fts5yypParser, fts5yyact);
  172056. }else{
  172057. assert( fts5yyact == fts5YY_ACCEPT_ACTION );
  172058. fts5yypParser->fts5yytos -= fts5yysize;
  172059. fts5yy_accept(fts5yypParser);
  172060. }
  172061. }
  172062. /*
  172063. ** The following code executes when the parse fails
  172064. */
  172065. #ifndef fts5YYNOERRORRECOVERY
  172066. static void fts5yy_parse_failed(
  172067. fts5yyParser *fts5yypParser /* The parser */
  172068. ){
  172069. sqlite3Fts5ParserARG_FETCH;
  172070. #ifndef NDEBUG
  172071. if( fts5yyTraceFILE ){
  172072. fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
  172073. }
  172074. #endif
  172075. while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
  172076. /* Here code is inserted which will be executed whenever the
  172077. ** parser fails */
  172078. /************ Begin %parse_failure code ***************************************/
  172079. /************ End %parse_failure code *****************************************/
  172080. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  172081. }
  172082. #endif /* fts5YYNOERRORRECOVERY */
  172083. /*
  172084. ** The following code executes when a syntax error first occurs.
  172085. */
  172086. static void fts5yy_syntax_error(
  172087. fts5yyParser *fts5yypParser, /* The parser */
  172088. int fts5yymajor, /* The major type of the error token */
  172089. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The minor type of the error token */
  172090. ){
  172091. sqlite3Fts5ParserARG_FETCH;
  172092. #define FTS5TOKEN fts5yyminor
  172093. /************ Begin %syntax_error code ****************************************/
  172094. UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
  172095. sqlite3Fts5ParseError(
  172096. pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
  172097. );
  172098. /************ End %syntax_error code ******************************************/
  172099. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  172100. }
  172101. /*
  172102. ** The following is executed when the parser accepts
  172103. */
  172104. static void fts5yy_accept(
  172105. fts5yyParser *fts5yypParser /* The parser */
  172106. ){
  172107. sqlite3Fts5ParserARG_FETCH;
  172108. #ifndef NDEBUG
  172109. if( fts5yyTraceFILE ){
  172110. fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
  172111. }
  172112. #endif
  172113. #ifndef fts5YYNOERRORRECOVERY
  172114. fts5yypParser->fts5yyerrcnt = -1;
  172115. #endif
  172116. assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
  172117. /* Here code is inserted which will be executed whenever the
  172118. ** parser accepts */
  172119. /*********** Begin %parse_accept code *****************************************/
  172120. /*********** End %parse_accept code *******************************************/
  172121. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  172122. }
  172123. /* The main parser program.
  172124. ** The first argument is a pointer to a structure obtained from
  172125. ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
  172126. ** The second argument is the major token number. The third is
  172127. ** the minor token. The fourth optional argument is whatever the
  172128. ** user wants (and specified in the grammar) and is available for
  172129. ** use by the action routines.
  172130. **
  172131. ** Inputs:
  172132. ** <ul>
  172133. ** <li> A pointer to the parser (an opaque structure.)
  172134. ** <li> The major token number.
  172135. ** <li> The minor token number.
  172136. ** <li> An option argument of a grammar-specified type.
  172137. ** </ul>
  172138. **
  172139. ** Outputs:
  172140. ** None.
  172141. */
  172142. static void sqlite3Fts5Parser(
  172143. void *fts5yyp, /* The parser */
  172144. int fts5yymajor, /* The major token code number */
  172145. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */
  172146. sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */
  172147. ){
  172148. fts5YYMINORTYPE fts5yyminorunion;
  172149. unsigned int fts5yyact; /* The parser action. */
  172150. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  172151. int fts5yyendofinput; /* True if we are at the end of input */
  172152. #endif
  172153. #ifdef fts5YYERRORSYMBOL
  172154. int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */
  172155. #endif
  172156. fts5yyParser *fts5yypParser; /* The parser */
  172157. fts5yypParser = (fts5yyParser*)fts5yyp;
  172158. assert( fts5yypParser->fts5yytos!=0 );
  172159. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  172160. fts5yyendofinput = (fts5yymajor==0);
  172161. #endif
  172162. sqlite3Fts5ParserARG_STORE;
  172163. #ifndef NDEBUG
  172164. if( fts5yyTraceFILE ){
  172165. fprintf(fts5yyTraceFILE,"%sInput '%s'\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
  172166. }
  172167. #endif
  172168. do{
  172169. fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
  172170. if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
  172171. fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor);
  172172. #ifndef fts5YYNOERRORRECOVERY
  172173. fts5yypParser->fts5yyerrcnt--;
  172174. #endif
  172175. fts5yymajor = fts5YYNOCODE;
  172176. }else if( fts5yyact <= fts5YY_MAX_REDUCE ){
  172177. fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE);
  172178. }else{
  172179. assert( fts5yyact == fts5YY_ERROR_ACTION );
  172180. fts5yyminorunion.fts5yy0 = fts5yyminor;
  172181. #ifdef fts5YYERRORSYMBOL
  172182. int fts5yymx;
  172183. #endif
  172184. #ifndef NDEBUG
  172185. if( fts5yyTraceFILE ){
  172186. fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
  172187. }
  172188. #endif
  172189. #ifdef fts5YYERRORSYMBOL
  172190. /* A syntax error has occurred.
  172191. ** The response to an error depends upon whether or not the
  172192. ** grammar defines an error token "ERROR".
  172193. **
  172194. ** This is what we do if the grammar does define ERROR:
  172195. **
  172196. ** * Call the %syntax_error function.
  172197. **
  172198. ** * Begin popping the stack until we enter a state where
  172199. ** it is legal to shift the error symbol, then shift
  172200. ** the error symbol.
  172201. **
  172202. ** * Set the error count to three.
  172203. **
  172204. ** * Begin accepting and shifting new tokens. No new error
  172205. ** processing will occur until three tokens have been
  172206. ** shifted successfully.
  172207. **
  172208. */
  172209. if( fts5yypParser->fts5yyerrcnt<0 ){
  172210. fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
  172211. }
  172212. fts5yymx = fts5yypParser->fts5yytos->major;
  172213. if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
  172214. #ifndef NDEBUG
  172215. if( fts5yyTraceFILE ){
  172216. fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
  172217. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
  172218. }
  172219. #endif
  172220. fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
  172221. fts5yymajor = fts5YYNOCODE;
  172222. }else{
  172223. while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
  172224. && fts5yymx != fts5YYERRORSYMBOL
  172225. && (fts5yyact = fts5yy_find_reduce_action(
  172226. fts5yypParser->fts5yytos->stateno,
  172227. fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
  172228. ){
  172229. fts5yy_pop_parser_stack(fts5yypParser);
  172230. }
  172231. if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
  172232. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  172233. fts5yy_parse_failed(fts5yypParser);
  172234. #ifndef fts5YYNOERRORRECOVERY
  172235. fts5yypParser->fts5yyerrcnt = -1;
  172236. #endif
  172237. fts5yymajor = fts5YYNOCODE;
  172238. }else if( fts5yymx!=fts5YYERRORSYMBOL ){
  172239. fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
  172240. }
  172241. }
  172242. fts5yypParser->fts5yyerrcnt = 3;
  172243. fts5yyerrorhit = 1;
  172244. #elif defined(fts5YYNOERRORRECOVERY)
  172245. /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
  172246. ** do any kind of error recovery. Instead, simply invoke the syntax
  172247. ** error routine and continue going as if nothing had happened.
  172248. **
  172249. ** Applications can set this macro (for example inside %include) if
  172250. ** they intend to abandon the parse upon the first syntax error seen.
  172251. */
  172252. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  172253. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  172254. fts5yymajor = fts5YYNOCODE;
  172255. #else /* fts5YYERRORSYMBOL is not defined */
  172256. /* This is what we do if the grammar does not define ERROR:
  172257. **
  172258. ** * Report an error message, and throw away the input token.
  172259. **
  172260. ** * If the input token is $, then fail the parse.
  172261. **
  172262. ** As before, subsequent error messages are suppressed until
  172263. ** three input tokens have been successfully shifted.
  172264. */
  172265. if( fts5yypParser->fts5yyerrcnt<=0 ){
  172266. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  172267. }
  172268. fts5yypParser->fts5yyerrcnt = 3;
  172269. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  172270. if( fts5yyendofinput ){
  172271. fts5yy_parse_failed(fts5yypParser);
  172272. #ifndef fts5YYNOERRORRECOVERY
  172273. fts5yypParser->fts5yyerrcnt = -1;
  172274. #endif
  172275. }
  172276. fts5yymajor = fts5YYNOCODE;
  172277. #endif
  172278. }
  172279. }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
  172280. #ifndef NDEBUG
  172281. if( fts5yyTraceFILE ){
  172282. fts5yyStackEntry *i;
  172283. char cDiv = '[';
  172284. fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
  172285. for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
  172286. fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
  172287. cDiv = ' ';
  172288. }
  172289. fprintf(fts5yyTraceFILE,"]\n");
  172290. }
  172291. #endif
  172292. return;
  172293. }
  172294. /*
  172295. ** 2014 May 31
  172296. **
  172297. ** The author disclaims copyright to this source code. In place of
  172298. ** a legal notice, here is a blessing:
  172299. **
  172300. ** May you do good and not evil.
  172301. ** May you find forgiveness for yourself and forgive others.
  172302. ** May you share freely, never taking more than you give.
  172303. **
  172304. ******************************************************************************
  172305. */
  172306. /* #include "fts5Int.h" */
  172307. #include <math.h> /* amalgamator: keep */
  172308. /*
  172309. ** Object used to iterate through all "coalesced phrase instances" in
  172310. ** a single column of the current row. If the phrase instances in the
  172311. ** column being considered do not overlap, this object simply iterates
  172312. ** through them. Or, if they do overlap (share one or more tokens in
  172313. ** common), each set of overlapping instances is treated as a single
  172314. ** match. See documentation for the highlight() auxiliary function for
  172315. ** details.
  172316. **
  172317. ** Usage is:
  172318. **
  172319. ** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
  172320. ** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
  172321. ** rc = fts5CInstIterNext(&iter)
  172322. ** ){
  172323. ** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
  172324. ** }
  172325. **
  172326. */
  172327. typedef struct CInstIter CInstIter;
  172328. struct CInstIter {
  172329. const Fts5ExtensionApi *pApi; /* API offered by current FTS version */
  172330. Fts5Context *pFts; /* First arg to pass to pApi functions */
  172331. int iCol; /* Column to search */
  172332. int iInst; /* Next phrase instance index */
  172333. int nInst; /* Total number of phrase instances */
  172334. /* Output variables */
  172335. int iStart; /* First token in coalesced phrase instance */
  172336. int iEnd; /* Last token in coalesced phrase instance */
  172337. };
  172338. /*
  172339. ** Advance the iterator to the next coalesced phrase instance. Return
  172340. ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  172341. */
  172342. static int fts5CInstIterNext(CInstIter *pIter){
  172343. int rc = SQLITE_OK;
  172344. pIter->iStart = -1;
  172345. pIter->iEnd = -1;
  172346. while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
  172347. int ip; int ic; int io;
  172348. rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
  172349. if( rc==SQLITE_OK ){
  172350. if( ic==pIter->iCol ){
  172351. int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
  172352. if( pIter->iStart<0 ){
  172353. pIter->iStart = io;
  172354. pIter->iEnd = iEnd;
  172355. }else if( io<=pIter->iEnd ){
  172356. if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
  172357. }else{
  172358. break;
  172359. }
  172360. }
  172361. pIter->iInst++;
  172362. }
  172363. }
  172364. return rc;
  172365. }
  172366. /*
  172367. ** Initialize the iterator object indicated by the final parameter to
  172368. ** iterate through coalesced phrase instances in column iCol.
  172369. */
  172370. static int fts5CInstIterInit(
  172371. const Fts5ExtensionApi *pApi,
  172372. Fts5Context *pFts,
  172373. int iCol,
  172374. CInstIter *pIter
  172375. ){
  172376. int rc;
  172377. memset(pIter, 0, sizeof(CInstIter));
  172378. pIter->pApi = pApi;
  172379. pIter->pFts = pFts;
  172380. pIter->iCol = iCol;
  172381. rc = pApi->xInstCount(pFts, &pIter->nInst);
  172382. if( rc==SQLITE_OK ){
  172383. rc = fts5CInstIterNext(pIter);
  172384. }
  172385. return rc;
  172386. }
  172387. /*************************************************************************
  172388. ** Start of highlight() implementation.
  172389. */
  172390. typedef struct HighlightContext HighlightContext;
  172391. struct HighlightContext {
  172392. CInstIter iter; /* Coalesced Instance Iterator */
  172393. int iPos; /* Current token offset in zIn[] */
  172394. int iRangeStart; /* First token to include */
  172395. int iRangeEnd; /* If non-zero, last token to include */
  172396. const char *zOpen; /* Opening highlight */
  172397. const char *zClose; /* Closing highlight */
  172398. const char *zIn; /* Input text */
  172399. int nIn; /* Size of input text in bytes */
  172400. int iOff; /* Current offset within zIn[] */
  172401. char *zOut; /* Output value */
  172402. };
  172403. /*
  172404. ** Append text to the HighlightContext output string - p->zOut. Argument
  172405. ** z points to a buffer containing n bytes of text to append. If n is
  172406. ** negative, everything up until the first '\0' is appended to the output.
  172407. **
  172408. ** If *pRc is set to any value other than SQLITE_OK when this function is
  172409. ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
  172410. ** *pRc is set to an error code before returning.
  172411. */
  172412. static void fts5HighlightAppend(
  172413. int *pRc,
  172414. HighlightContext *p,
  172415. const char *z, int n
  172416. ){
  172417. if( *pRc==SQLITE_OK ){
  172418. if( n<0 ) n = (int)strlen(z);
  172419. p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
  172420. if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
  172421. }
  172422. }
  172423. /*
  172424. ** Tokenizer callback used by implementation of highlight() function.
  172425. */
  172426. static int fts5HighlightCb(
  172427. void *pContext, /* Pointer to HighlightContext object */
  172428. int tflags, /* Mask of FTS5_TOKEN_* flags */
  172429. const char *pToken, /* Buffer containing token */
  172430. int nToken, /* Size of token in bytes */
  172431. int iStartOff, /* Start offset of token */
  172432. int iEndOff /* End offset of token */
  172433. ){
  172434. HighlightContext *p = (HighlightContext*)pContext;
  172435. int rc = SQLITE_OK;
  172436. int iPos;
  172437. UNUSED_PARAM2(pToken, nToken);
  172438. if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
  172439. iPos = p->iPos++;
  172440. if( p->iRangeEnd>0 ){
  172441. if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
  172442. if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
  172443. }
  172444. if( iPos==p->iter.iStart ){
  172445. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
  172446. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  172447. p->iOff = iStartOff;
  172448. }
  172449. if( iPos==p->iter.iEnd ){
  172450. if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
  172451. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  172452. }
  172453. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  172454. fts5HighlightAppend(&rc, p, p->zClose, -1);
  172455. p->iOff = iEndOff;
  172456. if( rc==SQLITE_OK ){
  172457. rc = fts5CInstIterNext(&p->iter);
  172458. }
  172459. }
  172460. if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
  172461. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  172462. p->iOff = iEndOff;
  172463. if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
  172464. fts5HighlightAppend(&rc, p, p->zClose, -1);
  172465. }
  172466. }
  172467. return rc;
  172468. }
  172469. /*
  172470. ** Implementation of highlight() function.
  172471. */
  172472. static void fts5HighlightFunction(
  172473. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  172474. Fts5Context *pFts, /* First arg to pass to pApi functions */
  172475. sqlite3_context *pCtx, /* Context for returning result/error */
  172476. int nVal, /* Number of values in apVal[] array */
  172477. sqlite3_value **apVal /* Array of trailing arguments */
  172478. ){
  172479. HighlightContext ctx;
  172480. int rc;
  172481. int iCol;
  172482. if( nVal!=3 ){
  172483. const char *zErr = "wrong number of arguments to function highlight()";
  172484. sqlite3_result_error(pCtx, zErr, -1);
  172485. return;
  172486. }
  172487. iCol = sqlite3_value_int(apVal[0]);
  172488. memset(&ctx, 0, sizeof(HighlightContext));
  172489. ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  172490. ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  172491. rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
  172492. if( ctx.zIn ){
  172493. if( rc==SQLITE_OK ){
  172494. rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
  172495. }
  172496. if( rc==SQLITE_OK ){
  172497. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  172498. }
  172499. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  172500. if( rc==SQLITE_OK ){
  172501. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  172502. }
  172503. sqlite3_free(ctx.zOut);
  172504. }
  172505. if( rc!=SQLITE_OK ){
  172506. sqlite3_result_error_code(pCtx, rc);
  172507. }
  172508. }
  172509. /*
  172510. ** End of highlight() implementation.
  172511. **************************************************************************/
  172512. /*
  172513. ** Context object passed to the fts5SentenceFinderCb() function.
  172514. */
  172515. typedef struct Fts5SFinder Fts5SFinder;
  172516. struct Fts5SFinder {
  172517. int iPos; /* Current token position */
  172518. int nFirstAlloc; /* Allocated size of aFirst[] */
  172519. int nFirst; /* Number of entries in aFirst[] */
  172520. int *aFirst; /* Array of first token in each sentence */
  172521. const char *zDoc; /* Document being tokenized */
  172522. };
  172523. /*
  172524. ** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
  172525. ** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
  172526. ** error occurs.
  172527. */
  172528. static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
  172529. if( p->nFirstAlloc==p->nFirst ){
  172530. int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
  172531. int *aNew;
  172532. aNew = (int*)sqlite3_realloc(p->aFirst, nNew*sizeof(int));
  172533. if( aNew==0 ) return SQLITE_NOMEM;
  172534. p->aFirst = aNew;
  172535. p->nFirstAlloc = nNew;
  172536. }
  172537. p->aFirst[p->nFirst++] = iAdd;
  172538. return SQLITE_OK;
  172539. }
  172540. /*
  172541. ** This function is an xTokenize() callback used by the auxiliary snippet()
  172542. ** function. Its job is to identify tokens that are the first in a sentence.
  172543. ** For each such token, an entry is added to the SFinder.aFirst[] array.
  172544. */
  172545. static int fts5SentenceFinderCb(
  172546. void *pContext, /* Pointer to HighlightContext object */
  172547. int tflags, /* Mask of FTS5_TOKEN_* flags */
  172548. const char *pToken, /* Buffer containing token */
  172549. int nToken, /* Size of token in bytes */
  172550. int iStartOff, /* Start offset of token */
  172551. int iEndOff /* End offset of token */
  172552. ){
  172553. int rc = SQLITE_OK;
  172554. UNUSED_PARAM2(pToken, nToken);
  172555. UNUSED_PARAM(iEndOff);
  172556. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  172557. Fts5SFinder *p = (Fts5SFinder*)pContext;
  172558. if( p->iPos>0 ){
  172559. int i;
  172560. char c = 0;
  172561. for(i=iStartOff-1; i>=0; i--){
  172562. c = p->zDoc[i];
  172563. if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
  172564. }
  172565. if( i!=iStartOff-1 && (c=='.' || c==':') ){
  172566. rc = fts5SentenceFinderAdd(p, p->iPos);
  172567. }
  172568. }else{
  172569. rc = fts5SentenceFinderAdd(p, 0);
  172570. }
  172571. p->iPos++;
  172572. }
  172573. return rc;
  172574. }
  172575. static int fts5SnippetScore(
  172576. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  172577. Fts5Context *pFts, /* First arg to pass to pApi functions */
  172578. int nDocsize, /* Size of column in tokens */
  172579. unsigned char *aSeen, /* Array with one element per query phrase */
  172580. int iCol, /* Column to score */
  172581. int iPos, /* Starting offset to score */
  172582. int nToken, /* Max tokens per snippet */
  172583. int *pnScore, /* OUT: Score */
  172584. int *piPos /* OUT: Adjusted offset */
  172585. ){
  172586. int rc;
  172587. int i;
  172588. int ip = 0;
  172589. int ic = 0;
  172590. int iOff = 0;
  172591. int iFirst = -1;
  172592. int nInst;
  172593. int nScore = 0;
  172594. int iLast = 0;
  172595. rc = pApi->xInstCount(pFts, &nInst);
  172596. for(i=0; i<nInst && rc==SQLITE_OK; i++){
  172597. rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
  172598. if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<(iPos+nToken) ){
  172599. nScore += (aSeen[ip] ? 1 : 1000);
  172600. aSeen[ip] = 1;
  172601. if( iFirst<0 ) iFirst = iOff;
  172602. iLast = iOff + pApi->xPhraseSize(pFts, ip);
  172603. }
  172604. }
  172605. *pnScore = nScore;
  172606. if( piPos ){
  172607. int iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
  172608. if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
  172609. if( iAdj<0 ) iAdj = 0;
  172610. *piPos = iAdj;
  172611. }
  172612. return rc;
  172613. }
  172614. /*
  172615. ** Implementation of snippet() function.
  172616. */
  172617. static void fts5SnippetFunction(
  172618. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  172619. Fts5Context *pFts, /* First arg to pass to pApi functions */
  172620. sqlite3_context *pCtx, /* Context for returning result/error */
  172621. int nVal, /* Number of values in apVal[] array */
  172622. sqlite3_value **apVal /* Array of trailing arguments */
  172623. ){
  172624. HighlightContext ctx;
  172625. int rc = SQLITE_OK; /* Return code */
  172626. int iCol; /* 1st argument to snippet() */
  172627. const char *zEllips; /* 4th argument to snippet() */
  172628. int nToken; /* 5th argument to snippet() */
  172629. int nInst = 0; /* Number of instance matches this row */
  172630. int i; /* Used to iterate through instances */
  172631. int nPhrase; /* Number of phrases in query */
  172632. unsigned char *aSeen; /* Array of "seen instance" flags */
  172633. int iBestCol; /* Column containing best snippet */
  172634. int iBestStart = 0; /* First token of best snippet */
  172635. int nBestScore = 0; /* Score of best snippet */
  172636. int nColSize = 0; /* Total size of iBestCol in tokens */
  172637. Fts5SFinder sFinder; /* Used to find the beginnings of sentences */
  172638. int nCol;
  172639. if( nVal!=5 ){
  172640. const char *zErr = "wrong number of arguments to function snippet()";
  172641. sqlite3_result_error(pCtx, zErr, -1);
  172642. return;
  172643. }
  172644. nCol = pApi->xColumnCount(pFts);
  172645. memset(&ctx, 0, sizeof(HighlightContext));
  172646. iCol = sqlite3_value_int(apVal[0]);
  172647. ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  172648. ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  172649. zEllips = (const char*)sqlite3_value_text(apVal[3]);
  172650. nToken = sqlite3_value_int(apVal[4]);
  172651. iBestCol = (iCol>=0 ? iCol : 0);
  172652. nPhrase = pApi->xPhraseCount(pFts);
  172653. aSeen = sqlite3_malloc(nPhrase);
  172654. if( aSeen==0 ){
  172655. rc = SQLITE_NOMEM;
  172656. }
  172657. if( rc==SQLITE_OK ){
  172658. rc = pApi->xInstCount(pFts, &nInst);
  172659. }
  172660. memset(&sFinder, 0, sizeof(Fts5SFinder));
  172661. for(i=0; i<nCol; i++){
  172662. if( iCol<0 || iCol==i ){
  172663. int nDoc;
  172664. int nDocsize;
  172665. int ii;
  172666. sFinder.iPos = 0;
  172667. sFinder.nFirst = 0;
  172668. rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
  172669. if( rc!=SQLITE_OK ) break;
  172670. rc = pApi->xTokenize(pFts,
  172671. sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
  172672. );
  172673. if( rc!=SQLITE_OK ) break;
  172674. rc = pApi->xColumnSize(pFts, i, &nDocsize);
  172675. if( rc!=SQLITE_OK ) break;
  172676. for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
  172677. int ip, ic, io;
  172678. int iAdj;
  172679. int nScore;
  172680. int jj;
  172681. rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
  172682. if( ic!=i || rc!=SQLITE_OK ) continue;
  172683. memset(aSeen, 0, nPhrase);
  172684. rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
  172685. io, nToken, &nScore, &iAdj
  172686. );
  172687. if( rc==SQLITE_OK && nScore>nBestScore ){
  172688. nBestScore = nScore;
  172689. iBestCol = i;
  172690. iBestStart = iAdj;
  172691. nColSize = nDocsize;
  172692. }
  172693. if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
  172694. for(jj=0; jj<(sFinder.nFirst-1); jj++){
  172695. if( sFinder.aFirst[jj+1]>io ) break;
  172696. }
  172697. if( sFinder.aFirst[jj]<io ){
  172698. memset(aSeen, 0, nPhrase);
  172699. rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
  172700. sFinder.aFirst[jj], nToken, &nScore, 0
  172701. );
  172702. nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
  172703. if( rc==SQLITE_OK && nScore>nBestScore ){
  172704. nBestScore = nScore;
  172705. iBestCol = i;
  172706. iBestStart = sFinder.aFirst[jj];
  172707. nColSize = nDocsize;
  172708. }
  172709. }
  172710. }
  172711. }
  172712. }
  172713. }
  172714. if( rc==SQLITE_OK ){
  172715. rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
  172716. }
  172717. if( rc==SQLITE_OK && nColSize==0 ){
  172718. rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
  172719. }
  172720. if( ctx.zIn ){
  172721. if( rc==SQLITE_OK ){
  172722. rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
  172723. }
  172724. ctx.iRangeStart = iBestStart;
  172725. ctx.iRangeEnd = iBestStart + nToken - 1;
  172726. if( iBestStart>0 ){
  172727. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  172728. }
  172729. /* Advance iterator ctx.iter so that it points to the first coalesced
  172730. ** phrase instance at or following position iBestStart. */
  172731. while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
  172732. rc = fts5CInstIterNext(&ctx.iter);
  172733. }
  172734. if( rc==SQLITE_OK ){
  172735. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  172736. }
  172737. if( ctx.iRangeEnd>=(nColSize-1) ){
  172738. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  172739. }else{
  172740. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  172741. }
  172742. }
  172743. if( rc==SQLITE_OK ){
  172744. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  172745. }else{
  172746. sqlite3_result_error_code(pCtx, rc);
  172747. }
  172748. sqlite3_free(ctx.zOut);
  172749. sqlite3_free(aSeen);
  172750. sqlite3_free(sFinder.aFirst);
  172751. }
  172752. /************************************************************************/
  172753. /*
  172754. ** The first time the bm25() function is called for a query, an instance
  172755. ** of the following structure is allocated and populated.
  172756. */
  172757. typedef struct Fts5Bm25Data Fts5Bm25Data;
  172758. struct Fts5Bm25Data {
  172759. int nPhrase; /* Number of phrases in query */
  172760. double avgdl; /* Average number of tokens in each row */
  172761. double *aIDF; /* IDF for each phrase */
  172762. double *aFreq; /* Array used to calculate phrase freq. */
  172763. };
  172764. /*
  172765. ** Callback used by fts5Bm25GetData() to count the number of rows in the
  172766. ** table matched by each individual phrase within the query.
  172767. */
  172768. static int fts5CountCb(
  172769. const Fts5ExtensionApi *pApi,
  172770. Fts5Context *pFts,
  172771. void *pUserData /* Pointer to sqlite3_int64 variable */
  172772. ){
  172773. sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
  172774. UNUSED_PARAM2(pApi, pFts);
  172775. (*pn)++;
  172776. return SQLITE_OK;
  172777. }
  172778. /*
  172779. ** Set *ppData to point to the Fts5Bm25Data object for the current query.
  172780. ** If the object has not already been allocated, allocate and populate it
  172781. ** now.
  172782. */
  172783. static int fts5Bm25GetData(
  172784. const Fts5ExtensionApi *pApi,
  172785. Fts5Context *pFts,
  172786. Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */
  172787. ){
  172788. int rc = SQLITE_OK; /* Return code */
  172789. Fts5Bm25Data *p; /* Object to return */
  172790. p = pApi->xGetAuxdata(pFts, 0);
  172791. if( p==0 ){
  172792. int nPhrase; /* Number of phrases in query */
  172793. sqlite3_int64 nRow = 0; /* Number of rows in table */
  172794. sqlite3_int64 nToken = 0; /* Number of tokens in table */
  172795. int nByte; /* Bytes of space to allocate */
  172796. int i;
  172797. /* Allocate the Fts5Bm25Data object */
  172798. nPhrase = pApi->xPhraseCount(pFts);
  172799. nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
  172800. p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
  172801. if( p==0 ){
  172802. rc = SQLITE_NOMEM;
  172803. }else{
  172804. memset(p, 0, nByte);
  172805. p->nPhrase = nPhrase;
  172806. p->aIDF = (double*)&p[1];
  172807. p->aFreq = &p->aIDF[nPhrase];
  172808. }
  172809. /* Calculate the average document length for this FTS5 table */
  172810. if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
  172811. if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
  172812. if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow;
  172813. /* Calculate an IDF for each phrase in the query */
  172814. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  172815. sqlite3_int64 nHit = 0;
  172816. rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
  172817. if( rc==SQLITE_OK ){
  172818. /* Calculate the IDF (Inverse Document Frequency) for phrase i.
  172819. ** This is done using the standard BM25 formula as found on wikipedia:
  172820. **
  172821. ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
  172822. **
  172823. ** where "N" is the total number of documents in the set and nHit
  172824. ** is the number that contain at least one instance of the phrase
  172825. ** under consideration.
  172826. **
  172827. ** The problem with this is that if (N < 2*nHit), the IDF is
  172828. ** negative. Which is undesirable. So the mimimum allowable IDF is
  172829. ** (1e-6) - roughly the same as a term that appears in just over
  172830. ** half of set of 5,000,000 documents. */
  172831. double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
  172832. if( idf<=0.0 ) idf = 1e-6;
  172833. p->aIDF[i] = idf;
  172834. }
  172835. }
  172836. if( rc!=SQLITE_OK ){
  172837. sqlite3_free(p);
  172838. }else{
  172839. rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
  172840. }
  172841. if( rc!=SQLITE_OK ) p = 0;
  172842. }
  172843. *ppData = p;
  172844. return rc;
  172845. }
  172846. /*
  172847. ** Implementation of bm25() function.
  172848. */
  172849. static void fts5Bm25Function(
  172850. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  172851. Fts5Context *pFts, /* First arg to pass to pApi functions */
  172852. sqlite3_context *pCtx, /* Context for returning result/error */
  172853. int nVal, /* Number of values in apVal[] array */
  172854. sqlite3_value **apVal /* Array of trailing arguments */
  172855. ){
  172856. const double k1 = 1.2; /* Constant "k1" from BM25 formula */
  172857. const double b = 0.75; /* Constant "b" from BM25 formula */
  172858. int rc = SQLITE_OK; /* Error code */
  172859. double score = 0.0; /* SQL function return value */
  172860. Fts5Bm25Data *pData; /* Values allocated/calculated once only */
  172861. int i; /* Iterator variable */
  172862. int nInst = 0; /* Value returned by xInstCount() */
  172863. double D = 0.0; /* Total number of tokens in row */
  172864. double *aFreq = 0; /* Array of phrase freq. for current row */
  172865. /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
  172866. ** for each phrase in the query for the current row. */
  172867. rc = fts5Bm25GetData(pApi, pFts, &pData);
  172868. if( rc==SQLITE_OK ){
  172869. aFreq = pData->aFreq;
  172870. memset(aFreq, 0, sizeof(double) * pData->nPhrase);
  172871. rc = pApi->xInstCount(pFts, &nInst);
  172872. }
  172873. for(i=0; rc==SQLITE_OK && i<nInst; i++){
  172874. int ip; int ic; int io;
  172875. rc = pApi->xInst(pFts, i, &ip, &ic, &io);
  172876. if( rc==SQLITE_OK ){
  172877. double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
  172878. aFreq[ip] += w;
  172879. }
  172880. }
  172881. /* Figure out the total size of the current row in tokens. */
  172882. if( rc==SQLITE_OK ){
  172883. int nTok;
  172884. rc = pApi->xColumnSize(pFts, -1, &nTok);
  172885. D = (double)nTok;
  172886. }
  172887. /* Determine the BM25 score for the current row. */
  172888. for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
  172889. score += pData->aIDF[i] * (
  172890. ( aFreq[i] * (k1 + 1.0) ) /
  172891. ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
  172892. );
  172893. }
  172894. /* If no error has occurred, return the calculated score. Otherwise,
  172895. ** throw an SQL exception. */
  172896. if( rc==SQLITE_OK ){
  172897. sqlite3_result_double(pCtx, -1.0 * score);
  172898. }else{
  172899. sqlite3_result_error_code(pCtx, rc);
  172900. }
  172901. }
  172902. static int sqlite3Fts5AuxInit(fts5_api *pApi){
  172903. struct Builtin {
  172904. const char *zFunc; /* Function name (nul-terminated) */
  172905. void *pUserData; /* User-data pointer */
  172906. fts5_extension_function xFunc;/* Callback function */
  172907. void (*xDestroy)(void*); /* Destructor function */
  172908. } aBuiltin [] = {
  172909. { "snippet", 0, fts5SnippetFunction, 0 },
  172910. { "highlight", 0, fts5HighlightFunction, 0 },
  172911. { "bm25", 0, fts5Bm25Function, 0 },
  172912. };
  172913. int rc = SQLITE_OK; /* Return code */
  172914. int i; /* To iterate through builtin functions */
  172915. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  172916. rc = pApi->xCreateFunction(pApi,
  172917. aBuiltin[i].zFunc,
  172918. aBuiltin[i].pUserData,
  172919. aBuiltin[i].xFunc,
  172920. aBuiltin[i].xDestroy
  172921. );
  172922. }
  172923. return rc;
  172924. }
  172925. /*
  172926. ** 2014 May 31
  172927. **
  172928. ** The author disclaims copyright to this source code. In place of
  172929. ** a legal notice, here is a blessing:
  172930. **
  172931. ** May you do good and not evil.
  172932. ** May you find forgiveness for yourself and forgive others.
  172933. ** May you share freely, never taking more than you give.
  172934. **
  172935. ******************************************************************************
  172936. */
  172937. /* #include "fts5Int.h" */
  172938. static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
  172939. if( (u32)pBuf->nSpace<nByte ){
  172940. u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
  172941. u8 *pNew;
  172942. while( nNew<nByte ){
  172943. nNew = nNew * 2;
  172944. }
  172945. pNew = sqlite3_realloc(pBuf->p, nNew);
  172946. if( pNew==0 ){
  172947. *pRc = SQLITE_NOMEM;
  172948. return 1;
  172949. }else{
  172950. pBuf->nSpace = nNew;
  172951. pBuf->p = pNew;
  172952. }
  172953. }
  172954. return 0;
  172955. }
  172956. /*
  172957. ** Encode value iVal as an SQLite varint and append it to the buffer object
  172958. ** pBuf. If an OOM error occurs, set the error code in p.
  172959. */
  172960. static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
  172961. if( fts5BufferGrow(pRc, pBuf, 9) ) return;
  172962. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
  172963. }
  172964. static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
  172965. aBuf[0] = (iVal>>24) & 0x00FF;
  172966. aBuf[1] = (iVal>>16) & 0x00FF;
  172967. aBuf[2] = (iVal>> 8) & 0x00FF;
  172968. aBuf[3] = (iVal>> 0) & 0x00FF;
  172969. }
  172970. static int sqlite3Fts5Get32(const u8 *aBuf){
  172971. return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
  172972. }
  172973. /*
  172974. ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
  172975. ** the error code in p. If an error has already occurred when this function
  172976. ** is called, it is a no-op.
  172977. */
  172978. static void sqlite3Fts5BufferAppendBlob(
  172979. int *pRc,
  172980. Fts5Buffer *pBuf,
  172981. u32 nData,
  172982. const u8 *pData
  172983. ){
  172984. assert_nc( *pRc || nData>=0 );
  172985. if( nData ){
  172986. if( fts5BufferGrow(pRc, pBuf, nData) ) return;
  172987. memcpy(&pBuf->p[pBuf->n], pData, nData);
  172988. pBuf->n += nData;
  172989. }
  172990. }
  172991. /*
  172992. ** Append the nul-terminated string zStr to the buffer pBuf. This function
  172993. ** ensures that the byte following the buffer data is set to 0x00, even
  172994. ** though this byte is not included in the pBuf->n count.
  172995. */
  172996. static void sqlite3Fts5BufferAppendString(
  172997. int *pRc,
  172998. Fts5Buffer *pBuf,
  172999. const char *zStr
  173000. ){
  173001. int nStr = (int)strlen(zStr);
  173002. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
  173003. pBuf->n--;
  173004. }
  173005. /*
  173006. ** Argument zFmt is a printf() style format string. This function performs
  173007. ** the printf() style processing, then appends the results to buffer pBuf.
  173008. **
  173009. ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
  173010. ** following the buffer data is set to 0x00, even though this byte is not
  173011. ** included in the pBuf->n count.
  173012. */
  173013. static void sqlite3Fts5BufferAppendPrintf(
  173014. int *pRc,
  173015. Fts5Buffer *pBuf,
  173016. char *zFmt, ...
  173017. ){
  173018. if( *pRc==SQLITE_OK ){
  173019. char *zTmp;
  173020. va_list ap;
  173021. va_start(ap, zFmt);
  173022. zTmp = sqlite3_vmprintf(zFmt, ap);
  173023. va_end(ap);
  173024. if( zTmp==0 ){
  173025. *pRc = SQLITE_NOMEM;
  173026. }else{
  173027. sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
  173028. sqlite3_free(zTmp);
  173029. }
  173030. }
  173031. }
  173032. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
  173033. char *zRet = 0;
  173034. if( *pRc==SQLITE_OK ){
  173035. va_list ap;
  173036. va_start(ap, zFmt);
  173037. zRet = sqlite3_vmprintf(zFmt, ap);
  173038. va_end(ap);
  173039. if( zRet==0 ){
  173040. *pRc = SQLITE_NOMEM;
  173041. }
  173042. }
  173043. return zRet;
  173044. }
  173045. /*
  173046. ** Free any buffer allocated by pBuf. Zero the structure before returning.
  173047. */
  173048. static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
  173049. sqlite3_free(pBuf->p);
  173050. memset(pBuf, 0, sizeof(Fts5Buffer));
  173051. }
  173052. /*
  173053. ** Zero the contents of the buffer object. But do not free the associated
  173054. ** memory allocation.
  173055. */
  173056. static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
  173057. pBuf->n = 0;
  173058. }
  173059. /*
  173060. ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
  173061. ** the error code in p. If an error has already occurred when this function
  173062. ** is called, it is a no-op.
  173063. */
  173064. static void sqlite3Fts5BufferSet(
  173065. int *pRc,
  173066. Fts5Buffer *pBuf,
  173067. int nData,
  173068. const u8 *pData
  173069. ){
  173070. pBuf->n = 0;
  173071. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
  173072. }
  173073. static int sqlite3Fts5PoslistNext64(
  173074. const u8 *a, int n, /* Buffer containing poslist */
  173075. int *pi, /* IN/OUT: Offset within a[] */
  173076. i64 *piOff /* IN/OUT: Current offset */
  173077. ){
  173078. int i = *pi;
  173079. if( i>=n ){
  173080. /* EOF */
  173081. *piOff = -1;
  173082. return 1;
  173083. }else{
  173084. i64 iOff = *piOff;
  173085. int iVal;
  173086. fts5FastGetVarint32(a, i, iVal);
  173087. if( iVal==1 ){
  173088. fts5FastGetVarint32(a, i, iVal);
  173089. iOff = ((i64)iVal) << 32;
  173090. fts5FastGetVarint32(a, i, iVal);
  173091. }
  173092. *piOff = iOff + (iVal-2);
  173093. *pi = i;
  173094. return 0;
  173095. }
  173096. }
  173097. /*
  173098. ** Advance the iterator object passed as the only argument. Return true
  173099. ** if the iterator reaches EOF, or false otherwise.
  173100. */
  173101. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
  173102. if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
  173103. pIter->bEof = 1;
  173104. }
  173105. return pIter->bEof;
  173106. }
  173107. static int sqlite3Fts5PoslistReaderInit(
  173108. const u8 *a, int n, /* Poslist buffer to iterate through */
  173109. Fts5PoslistReader *pIter /* Iterator object to initialize */
  173110. ){
  173111. memset(pIter, 0, sizeof(*pIter));
  173112. pIter->a = a;
  173113. pIter->n = n;
  173114. sqlite3Fts5PoslistReaderNext(pIter);
  173115. return pIter->bEof;
  173116. }
  173117. /*
  173118. ** Append position iPos to the position list being accumulated in buffer
  173119. ** pBuf, which must be already be large enough to hold the new data.
  173120. ** The previous position written to this list is *piPrev. *piPrev is set
  173121. ** to iPos before returning.
  173122. */
  173123. static void sqlite3Fts5PoslistSafeAppend(
  173124. Fts5Buffer *pBuf,
  173125. i64 *piPrev,
  173126. i64 iPos
  173127. ){
  173128. static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
  173129. if( (iPos & colmask) != (*piPrev & colmask) ){
  173130. pBuf->p[pBuf->n++] = 1;
  173131. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
  173132. *piPrev = (iPos & colmask);
  173133. }
  173134. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
  173135. *piPrev = iPos;
  173136. }
  173137. static int sqlite3Fts5PoslistWriterAppend(
  173138. Fts5Buffer *pBuf,
  173139. Fts5PoslistWriter *pWriter,
  173140. i64 iPos
  173141. ){
  173142. int rc = 0; /* Initialized only to suppress erroneous warning from Clang */
  173143. if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
  173144. sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
  173145. return SQLITE_OK;
  173146. }
  173147. static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
  173148. void *pRet = 0;
  173149. if( *pRc==SQLITE_OK ){
  173150. pRet = sqlite3_malloc(nByte);
  173151. if( pRet==0 ){
  173152. if( nByte>0 ) *pRc = SQLITE_NOMEM;
  173153. }else{
  173154. memset(pRet, 0, nByte);
  173155. }
  173156. }
  173157. return pRet;
  173158. }
  173159. /*
  173160. ** Return a nul-terminated copy of the string indicated by pIn. If nIn
  173161. ** is non-negative, then it is the length of the string in bytes. Otherwise,
  173162. ** the length of the string is determined using strlen().
  173163. **
  173164. ** It is the responsibility of the caller to eventually free the returned
  173165. ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
  173166. */
  173167. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
  173168. char *zRet = 0;
  173169. if( *pRc==SQLITE_OK ){
  173170. if( nIn<0 ){
  173171. nIn = (int)strlen(pIn);
  173172. }
  173173. zRet = (char*)sqlite3_malloc(nIn+1);
  173174. if( zRet ){
  173175. memcpy(zRet, pIn, nIn);
  173176. zRet[nIn] = '\0';
  173177. }else{
  173178. *pRc = SQLITE_NOMEM;
  173179. }
  173180. }
  173181. return zRet;
  173182. }
  173183. /*
  173184. ** Return true if character 't' may be part of an FTS5 bareword, or false
  173185. ** otherwise. Characters that may be part of barewords:
  173186. **
  173187. ** * All non-ASCII characters,
  173188. ** * The 52 upper and lower case ASCII characters, and
  173189. ** * The 10 integer ASCII characters.
  173190. ** * The underscore character "_" (0x5F).
  173191. ** * The unicode "subsitute" character (0x1A).
  173192. */
  173193. static int sqlite3Fts5IsBareword(char t){
  173194. u8 aBareword[128] = {
  173195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */
  173196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */
  173197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 .. 0x2F */
  173198. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30 .. 0x3F */
  173199. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 .. 0x4F */
  173200. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 0x50 .. 0x5F */
  173201. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 .. 0x6F */
  173202. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 /* 0x70 .. 0x7F */
  173203. };
  173204. return (t & 0x80) || aBareword[(int)t];
  173205. }
  173206. /*************************************************************************
  173207. */
  173208. typedef struct Fts5TermsetEntry Fts5TermsetEntry;
  173209. struct Fts5TermsetEntry {
  173210. char *pTerm;
  173211. int nTerm;
  173212. int iIdx; /* Index (main or aPrefix[] entry) */
  173213. Fts5TermsetEntry *pNext;
  173214. };
  173215. struct Fts5Termset {
  173216. Fts5TermsetEntry *apHash[512];
  173217. };
  173218. static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
  173219. int rc = SQLITE_OK;
  173220. *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
  173221. return rc;
  173222. }
  173223. static int sqlite3Fts5TermsetAdd(
  173224. Fts5Termset *p,
  173225. int iIdx,
  173226. const char *pTerm, int nTerm,
  173227. int *pbPresent
  173228. ){
  173229. int rc = SQLITE_OK;
  173230. *pbPresent = 0;
  173231. if( p ){
  173232. int i;
  173233. u32 hash = 13;
  173234. Fts5TermsetEntry *pEntry;
  173235. /* Calculate a hash value for this term. This is the same hash checksum
  173236. ** used by the fts5_hash.c module. This is not important for correct
  173237. ** operation of the module, but is necessary to ensure that some tests
  173238. ** designed to produce hash table collisions really do work. */
  173239. for(i=nTerm-1; i>=0; i--){
  173240. hash = (hash << 3) ^ hash ^ pTerm[i];
  173241. }
  173242. hash = (hash << 3) ^ hash ^ iIdx;
  173243. hash = hash % ArraySize(p->apHash);
  173244. for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
  173245. if( pEntry->iIdx==iIdx
  173246. && pEntry->nTerm==nTerm
  173247. && memcmp(pEntry->pTerm, pTerm, nTerm)==0
  173248. ){
  173249. *pbPresent = 1;
  173250. break;
  173251. }
  173252. }
  173253. if( pEntry==0 ){
  173254. pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
  173255. if( pEntry ){
  173256. pEntry->pTerm = (char*)&pEntry[1];
  173257. pEntry->nTerm = nTerm;
  173258. pEntry->iIdx = iIdx;
  173259. memcpy(pEntry->pTerm, pTerm, nTerm);
  173260. pEntry->pNext = p->apHash[hash];
  173261. p->apHash[hash] = pEntry;
  173262. }
  173263. }
  173264. }
  173265. return rc;
  173266. }
  173267. static void sqlite3Fts5TermsetFree(Fts5Termset *p){
  173268. if( p ){
  173269. u32 i;
  173270. for(i=0; i<ArraySize(p->apHash); i++){
  173271. Fts5TermsetEntry *pEntry = p->apHash[i];
  173272. while( pEntry ){
  173273. Fts5TermsetEntry *pDel = pEntry;
  173274. pEntry = pEntry->pNext;
  173275. sqlite3_free(pDel);
  173276. }
  173277. }
  173278. sqlite3_free(p);
  173279. }
  173280. }
  173281. /*
  173282. ** 2014 Jun 09
  173283. **
  173284. ** The author disclaims copyright to this source code. In place of
  173285. ** a legal notice, here is a blessing:
  173286. **
  173287. ** May you do good and not evil.
  173288. ** May you find forgiveness for yourself and forgive others.
  173289. ** May you share freely, never taking more than you give.
  173290. **
  173291. ******************************************************************************
  173292. **
  173293. ** This is an SQLite module implementing full-text search.
  173294. */
  173295. /* #include "fts5Int.h" */
  173296. #define FTS5_DEFAULT_PAGE_SIZE 4050
  173297. #define FTS5_DEFAULT_AUTOMERGE 4
  173298. #define FTS5_DEFAULT_USERMERGE 4
  173299. #define FTS5_DEFAULT_CRISISMERGE 16
  173300. #define FTS5_DEFAULT_HASHSIZE (1024*1024)
  173301. /* Maximum allowed page size */
  173302. #define FTS5_MAX_PAGE_SIZE (128*1024)
  173303. static int fts5_iswhitespace(char x){
  173304. return (x==' ');
  173305. }
  173306. static int fts5_isopenquote(char x){
  173307. return (x=='"' || x=='\'' || x=='[' || x=='`');
  173308. }
  173309. /*
  173310. ** Argument pIn points to a character that is part of a nul-terminated
  173311. ** string. Return a pointer to the first character following *pIn in
  173312. ** the string that is not a white-space character.
  173313. */
  173314. static const char *fts5ConfigSkipWhitespace(const char *pIn){
  173315. const char *p = pIn;
  173316. if( p ){
  173317. while( fts5_iswhitespace(*p) ){ p++; }
  173318. }
  173319. return p;
  173320. }
  173321. /*
  173322. ** Argument pIn points to a character that is part of a nul-terminated
  173323. ** string. Return a pointer to the first character following *pIn in
  173324. ** the string that is not a "bareword" character.
  173325. */
  173326. static const char *fts5ConfigSkipBareword(const char *pIn){
  173327. const char *p = pIn;
  173328. while ( sqlite3Fts5IsBareword(*p) ) p++;
  173329. if( p==pIn ) p = 0;
  173330. return p;
  173331. }
  173332. static int fts5_isdigit(char a){
  173333. return (a>='0' && a<='9');
  173334. }
  173335. static const char *fts5ConfigSkipLiteral(const char *pIn){
  173336. const char *p = pIn;
  173337. switch( *p ){
  173338. case 'n': case 'N':
  173339. if( sqlite3_strnicmp("null", p, 4)==0 ){
  173340. p = &p[4];
  173341. }else{
  173342. p = 0;
  173343. }
  173344. break;
  173345. case 'x': case 'X':
  173346. p++;
  173347. if( *p=='\'' ){
  173348. p++;
  173349. while( (*p>='a' && *p<='f')
  173350. || (*p>='A' && *p<='F')
  173351. || (*p>='0' && *p<='9')
  173352. ){
  173353. p++;
  173354. }
  173355. if( *p=='\'' && 0==((p-pIn)%2) ){
  173356. p++;
  173357. }else{
  173358. p = 0;
  173359. }
  173360. }else{
  173361. p = 0;
  173362. }
  173363. break;
  173364. case '\'':
  173365. p++;
  173366. while( p ){
  173367. if( *p=='\'' ){
  173368. p++;
  173369. if( *p!='\'' ) break;
  173370. }
  173371. p++;
  173372. if( *p==0 ) p = 0;
  173373. }
  173374. break;
  173375. default:
  173376. /* maybe a number */
  173377. if( *p=='+' || *p=='-' ) p++;
  173378. while( fts5_isdigit(*p) ) p++;
  173379. /* At this point, if the literal was an integer, the parse is
  173380. ** finished. Or, if it is a floating point value, it may continue
  173381. ** with either a decimal point or an 'E' character. */
  173382. if( *p=='.' && fts5_isdigit(p[1]) ){
  173383. p += 2;
  173384. while( fts5_isdigit(*p) ) p++;
  173385. }
  173386. if( p==pIn ) p = 0;
  173387. break;
  173388. }
  173389. return p;
  173390. }
  173391. /*
  173392. ** The first character of the string pointed to by argument z is guaranteed
  173393. ** to be an open-quote character (see function fts5_isopenquote()).
  173394. **
  173395. ** This function searches for the corresponding close-quote character within
  173396. ** the string and, if found, dequotes the string in place and adds a new
  173397. ** nul-terminator byte.
  173398. **
  173399. ** If the close-quote is found, the value returned is the byte offset of
  173400. ** the character immediately following it. Or, if the close-quote is not
  173401. ** found, -1 is returned. If -1 is returned, the buffer is left in an
  173402. ** undefined state.
  173403. */
  173404. static int fts5Dequote(char *z){
  173405. char q;
  173406. int iIn = 1;
  173407. int iOut = 0;
  173408. q = z[0];
  173409. /* Set stack variable q to the close-quote character */
  173410. assert( q=='[' || q=='\'' || q=='"' || q=='`' );
  173411. if( q=='[' ) q = ']';
  173412. while( ALWAYS(z[iIn]) ){
  173413. if( z[iIn]==q ){
  173414. if( z[iIn+1]!=q ){
  173415. /* Character iIn was the close quote. */
  173416. iIn++;
  173417. break;
  173418. }else{
  173419. /* Character iIn and iIn+1 form an escaped quote character. Skip
  173420. ** the input cursor past both and copy a single quote character
  173421. ** to the output buffer. */
  173422. iIn += 2;
  173423. z[iOut++] = q;
  173424. }
  173425. }else{
  173426. z[iOut++] = z[iIn++];
  173427. }
  173428. }
  173429. z[iOut] = '\0';
  173430. return iIn;
  173431. }
  173432. /*
  173433. ** Convert an SQL-style quoted string into a normal string by removing
  173434. ** the quote characters. The conversion is done in-place. If the
  173435. ** input does not begin with a quote character, then this routine
  173436. ** is a no-op.
  173437. **
  173438. ** Examples:
  173439. **
  173440. ** "abc" becomes abc
  173441. ** 'xyz' becomes xyz
  173442. ** [pqr] becomes pqr
  173443. ** `mno` becomes mno
  173444. */
  173445. static void sqlite3Fts5Dequote(char *z){
  173446. char quote; /* Quote character (if any ) */
  173447. assert( 0==fts5_iswhitespace(z[0]) );
  173448. quote = z[0];
  173449. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  173450. fts5Dequote(z);
  173451. }
  173452. }
  173453. struct Fts5Enum {
  173454. const char *zName;
  173455. int eVal;
  173456. };
  173457. typedef struct Fts5Enum Fts5Enum;
  173458. static int fts5ConfigSetEnum(
  173459. const Fts5Enum *aEnum,
  173460. const char *zEnum,
  173461. int *peVal
  173462. ){
  173463. int nEnum = (int)strlen(zEnum);
  173464. int i;
  173465. int iVal = -1;
  173466. for(i=0; aEnum[i].zName; i++){
  173467. if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
  173468. if( iVal>=0 ) return SQLITE_ERROR;
  173469. iVal = aEnum[i].eVal;
  173470. }
  173471. }
  173472. *peVal = iVal;
  173473. return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
  173474. }
  173475. /*
  173476. ** Parse a "special" CREATE VIRTUAL TABLE directive and update
  173477. ** configuration object pConfig as appropriate.
  173478. **
  173479. ** If successful, object pConfig is updated and SQLITE_OK returned. If
  173480. ** an error occurs, an SQLite error code is returned and an error message
  173481. ** may be left in *pzErr. It is the responsibility of the caller to
  173482. ** eventually free any such error message using sqlite3_free().
  173483. */
  173484. static int fts5ConfigParseSpecial(
  173485. Fts5Global *pGlobal,
  173486. Fts5Config *pConfig, /* Configuration object to update */
  173487. const char *zCmd, /* Special command to parse */
  173488. const char *zArg, /* Argument to parse */
  173489. char **pzErr /* OUT: Error message */
  173490. ){
  173491. int rc = SQLITE_OK;
  173492. int nCmd = (int)strlen(zCmd);
  173493. if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
  173494. const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
  173495. const char *p;
  173496. int bFirst = 1;
  173497. if( pConfig->aPrefix==0 ){
  173498. pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
  173499. if( rc ) return rc;
  173500. }
  173501. p = zArg;
  173502. while( 1 ){
  173503. int nPre = 0;
  173504. while( p[0]==' ' ) p++;
  173505. if( bFirst==0 && p[0]==',' ){
  173506. p++;
  173507. while( p[0]==' ' ) p++;
  173508. }else if( p[0]=='\0' ){
  173509. break;
  173510. }
  173511. if( p[0]<'0' || p[0]>'9' ){
  173512. *pzErr = sqlite3_mprintf("malformed prefix=... directive");
  173513. rc = SQLITE_ERROR;
  173514. break;
  173515. }
  173516. if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
  173517. *pzErr = sqlite3_mprintf(
  173518. "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
  173519. );
  173520. rc = SQLITE_ERROR;
  173521. break;
  173522. }
  173523. while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
  173524. nPre = nPre*10 + (p[0] - '0');
  173525. p++;
  173526. }
  173527. if( nPre<=0 || nPre>=1000 ){
  173528. *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
  173529. rc = SQLITE_ERROR;
  173530. break;
  173531. }
  173532. pConfig->aPrefix[pConfig->nPrefix] = nPre;
  173533. pConfig->nPrefix++;
  173534. bFirst = 0;
  173535. }
  173536. assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
  173537. return rc;
  173538. }
  173539. if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
  173540. const char *p = (const char*)zArg;
  173541. int nArg = (int)strlen(zArg) + 1;
  173542. char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
  173543. char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
  173544. char *pSpace = pDel;
  173545. if( azArg && pSpace ){
  173546. if( pConfig->pTok ){
  173547. *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
  173548. rc = SQLITE_ERROR;
  173549. }else{
  173550. for(nArg=0; p && *p; nArg++){
  173551. const char *p2 = fts5ConfigSkipWhitespace(p);
  173552. if( *p2=='\'' ){
  173553. p = fts5ConfigSkipLiteral(p2);
  173554. }else{
  173555. p = fts5ConfigSkipBareword(p2);
  173556. }
  173557. if( p ){
  173558. memcpy(pSpace, p2, p-p2);
  173559. azArg[nArg] = pSpace;
  173560. sqlite3Fts5Dequote(pSpace);
  173561. pSpace += (p - p2) + 1;
  173562. p = fts5ConfigSkipWhitespace(p);
  173563. }
  173564. }
  173565. if( p==0 ){
  173566. *pzErr = sqlite3_mprintf("parse error in tokenize directive");
  173567. rc = SQLITE_ERROR;
  173568. }else{
  173569. rc = sqlite3Fts5GetTokenizer(pGlobal,
  173570. (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
  173571. pzErr
  173572. );
  173573. }
  173574. }
  173575. }
  173576. sqlite3_free(azArg);
  173577. sqlite3_free(pDel);
  173578. return rc;
  173579. }
  173580. if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
  173581. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  173582. *pzErr = sqlite3_mprintf("multiple content=... directives");
  173583. rc = SQLITE_ERROR;
  173584. }else{
  173585. if( zArg[0] ){
  173586. pConfig->eContent = FTS5_CONTENT_EXTERNAL;
  173587. pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
  173588. }else{
  173589. pConfig->eContent = FTS5_CONTENT_NONE;
  173590. }
  173591. }
  173592. return rc;
  173593. }
  173594. if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
  173595. if( pConfig->zContentRowid ){
  173596. *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
  173597. rc = SQLITE_ERROR;
  173598. }else{
  173599. pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
  173600. }
  173601. return rc;
  173602. }
  173603. if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
  173604. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
  173605. *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
  173606. rc = SQLITE_ERROR;
  173607. }else{
  173608. pConfig->bColumnsize = (zArg[0]=='1');
  173609. }
  173610. return rc;
  173611. }
  173612. if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
  173613. const Fts5Enum aDetail[] = {
  173614. { "none", FTS5_DETAIL_NONE },
  173615. { "full", FTS5_DETAIL_FULL },
  173616. { "columns", FTS5_DETAIL_COLUMNS },
  173617. { 0, 0 }
  173618. };
  173619. if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
  173620. *pzErr = sqlite3_mprintf("malformed detail=... directive");
  173621. }
  173622. return rc;
  173623. }
  173624. *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
  173625. return SQLITE_ERROR;
  173626. }
  173627. /*
  173628. ** Allocate an instance of the default tokenizer ("simple") at
  173629. ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
  173630. ** code if an error occurs.
  173631. */
  173632. static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
  173633. assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
  173634. return sqlite3Fts5GetTokenizer(
  173635. pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
  173636. );
  173637. }
  173638. /*
  173639. ** Gobble up the first bareword or quoted word from the input buffer zIn.
  173640. ** Return a pointer to the character immediately following the last in
  173641. ** the gobbled word if successful, or a NULL pointer otherwise (failed
  173642. ** to find close-quote character).
  173643. **
  173644. ** Before returning, set pzOut to point to a new buffer containing a
  173645. ** nul-terminated, dequoted copy of the gobbled word. If the word was
  173646. ** quoted, *pbQuoted is also set to 1 before returning.
  173647. **
  173648. ** If *pRc is other than SQLITE_OK when this function is called, it is
  173649. ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
  173650. ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
  173651. ** set if a parse error (failed to find close quote) occurs.
  173652. */
  173653. static const char *fts5ConfigGobbleWord(
  173654. int *pRc, /* IN/OUT: Error code */
  173655. const char *zIn, /* Buffer to gobble string/bareword from */
  173656. char **pzOut, /* OUT: malloc'd buffer containing str/bw */
  173657. int *pbQuoted /* OUT: Set to true if dequoting required */
  173658. ){
  173659. const char *zRet = 0;
  173660. int nIn = (int)strlen(zIn);
  173661. char *zOut = sqlite3_malloc(nIn+1);
  173662. assert( *pRc==SQLITE_OK );
  173663. *pbQuoted = 0;
  173664. *pzOut = 0;
  173665. if( zOut==0 ){
  173666. *pRc = SQLITE_NOMEM;
  173667. }else{
  173668. memcpy(zOut, zIn, nIn+1);
  173669. if( fts5_isopenquote(zOut[0]) ){
  173670. int ii = fts5Dequote(zOut);
  173671. zRet = &zIn[ii];
  173672. *pbQuoted = 1;
  173673. }else{
  173674. zRet = fts5ConfigSkipBareword(zIn);
  173675. if( zRet ){
  173676. zOut[zRet-zIn] = '\0';
  173677. }
  173678. }
  173679. }
  173680. if( zRet==0 ){
  173681. sqlite3_free(zOut);
  173682. }else{
  173683. *pzOut = zOut;
  173684. }
  173685. return zRet;
  173686. }
  173687. static int fts5ConfigParseColumn(
  173688. Fts5Config *p,
  173689. char *zCol,
  173690. char *zArg,
  173691. char **pzErr
  173692. ){
  173693. int rc = SQLITE_OK;
  173694. if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
  173695. || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
  173696. ){
  173697. *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
  173698. rc = SQLITE_ERROR;
  173699. }else if( zArg ){
  173700. if( 0==sqlite3_stricmp(zArg, "unindexed") ){
  173701. p->abUnindexed[p->nCol] = 1;
  173702. }else{
  173703. *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
  173704. rc = SQLITE_ERROR;
  173705. }
  173706. }
  173707. p->azCol[p->nCol++] = zCol;
  173708. return rc;
  173709. }
  173710. /*
  173711. ** Populate the Fts5Config.zContentExprlist string.
  173712. */
  173713. static int fts5ConfigMakeExprlist(Fts5Config *p){
  173714. int i;
  173715. int rc = SQLITE_OK;
  173716. Fts5Buffer buf = {0, 0, 0};
  173717. sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
  173718. if( p->eContent!=FTS5_CONTENT_NONE ){
  173719. for(i=0; i<p->nCol; i++){
  173720. if( p->eContent==FTS5_CONTENT_EXTERNAL ){
  173721. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
  173722. }else{
  173723. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
  173724. }
  173725. }
  173726. }
  173727. assert( p->zContentExprlist==0 );
  173728. p->zContentExprlist = (char*)buf.p;
  173729. return rc;
  173730. }
  173731. /*
  173732. ** Arguments nArg/azArg contain the string arguments passed to the xCreate
  173733. ** or xConnect method of the virtual table. This function attempts to
  173734. ** allocate an instance of Fts5Config containing the results of parsing
  173735. ** those arguments.
  173736. **
  173737. ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
  173738. ** new Fts5Config object. If an error occurs, an SQLite error code is
  173739. ** returned, *ppOut is set to NULL and an error message may be left in
  173740. ** *pzErr. It is the responsibility of the caller to eventually free any
  173741. ** such error message using sqlite3_free().
  173742. */
  173743. static int sqlite3Fts5ConfigParse(
  173744. Fts5Global *pGlobal,
  173745. sqlite3 *db,
  173746. int nArg, /* Number of arguments */
  173747. const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */
  173748. Fts5Config **ppOut, /* OUT: Results of parse */
  173749. char **pzErr /* OUT: Error message */
  173750. ){
  173751. int rc = SQLITE_OK; /* Return code */
  173752. Fts5Config *pRet; /* New object to return */
  173753. int i;
  173754. int nByte;
  173755. *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
  173756. if( pRet==0 ) return SQLITE_NOMEM;
  173757. memset(pRet, 0, sizeof(Fts5Config));
  173758. pRet->db = db;
  173759. pRet->iCookie = -1;
  173760. nByte = nArg * (sizeof(char*) + sizeof(u8));
  173761. pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
  173762. pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
  173763. pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
  173764. pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
  173765. pRet->bColumnsize = 1;
  173766. pRet->eDetail = FTS5_DETAIL_FULL;
  173767. #ifdef SQLITE_DEBUG
  173768. pRet->bPrefixIndex = 1;
  173769. #endif
  173770. if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
  173771. *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
  173772. rc = SQLITE_ERROR;
  173773. }
  173774. for(i=3; rc==SQLITE_OK && i<nArg; i++){
  173775. const char *zOrig = azArg[i];
  173776. const char *z;
  173777. char *zOne = 0;
  173778. char *zTwo = 0;
  173779. int bOption = 0;
  173780. int bMustBeCol = 0;
  173781. z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
  173782. z = fts5ConfigSkipWhitespace(z);
  173783. if( z && *z=='=' ){
  173784. bOption = 1;
  173785. z++;
  173786. if( bMustBeCol ) z = 0;
  173787. }
  173788. z = fts5ConfigSkipWhitespace(z);
  173789. if( z && z[0] ){
  173790. int bDummy;
  173791. z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
  173792. if( z && z[0] ) z = 0;
  173793. }
  173794. if( rc==SQLITE_OK ){
  173795. if( z==0 ){
  173796. *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
  173797. rc = SQLITE_ERROR;
  173798. }else{
  173799. if( bOption ){
  173800. rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
  173801. }else{
  173802. rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
  173803. zOne = 0;
  173804. }
  173805. }
  173806. }
  173807. sqlite3_free(zOne);
  173808. sqlite3_free(zTwo);
  173809. }
  173810. /* If a tokenizer= option was successfully parsed, the tokenizer has
  173811. ** already been allocated. Otherwise, allocate an instance of the default
  173812. ** tokenizer (unicode61) now. */
  173813. if( rc==SQLITE_OK && pRet->pTok==0 ){
  173814. rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
  173815. }
  173816. /* If no zContent option was specified, fill in the default values. */
  173817. if( rc==SQLITE_OK && pRet->zContent==0 ){
  173818. const char *zTail = 0;
  173819. assert( pRet->eContent==FTS5_CONTENT_NORMAL
  173820. || pRet->eContent==FTS5_CONTENT_NONE
  173821. );
  173822. if( pRet->eContent==FTS5_CONTENT_NORMAL ){
  173823. zTail = "content";
  173824. }else if( pRet->bColumnsize ){
  173825. zTail = "docsize";
  173826. }
  173827. if( zTail ){
  173828. pRet->zContent = sqlite3Fts5Mprintf(
  173829. &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
  173830. );
  173831. }
  173832. }
  173833. if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
  173834. pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
  173835. }
  173836. /* Formulate the zContentExprlist text */
  173837. if( rc==SQLITE_OK ){
  173838. rc = fts5ConfigMakeExprlist(pRet);
  173839. }
  173840. if( rc!=SQLITE_OK ){
  173841. sqlite3Fts5ConfigFree(pRet);
  173842. *ppOut = 0;
  173843. }
  173844. return rc;
  173845. }
  173846. /*
  173847. ** Free the configuration object passed as the only argument.
  173848. */
  173849. static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
  173850. if( pConfig ){
  173851. int i;
  173852. if( pConfig->pTok ){
  173853. pConfig->pTokApi->xDelete(pConfig->pTok);
  173854. }
  173855. sqlite3_free(pConfig->zDb);
  173856. sqlite3_free(pConfig->zName);
  173857. for(i=0; i<pConfig->nCol; i++){
  173858. sqlite3_free(pConfig->azCol[i]);
  173859. }
  173860. sqlite3_free(pConfig->azCol);
  173861. sqlite3_free(pConfig->aPrefix);
  173862. sqlite3_free(pConfig->zRank);
  173863. sqlite3_free(pConfig->zRankArgs);
  173864. sqlite3_free(pConfig->zContent);
  173865. sqlite3_free(pConfig->zContentRowid);
  173866. sqlite3_free(pConfig->zContentExprlist);
  173867. sqlite3_free(pConfig);
  173868. }
  173869. }
  173870. /*
  173871. ** Call sqlite3_declare_vtab() based on the contents of the configuration
  173872. ** object passed as the only argument. Return SQLITE_OK if successful, or
  173873. ** an SQLite error code if an error occurs.
  173874. */
  173875. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
  173876. int i;
  173877. int rc = SQLITE_OK;
  173878. char *zSql;
  173879. zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
  173880. for(i=0; zSql && i<pConfig->nCol; i++){
  173881. const char *zSep = (i==0?"":", ");
  173882. zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
  173883. }
  173884. zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
  173885. zSql, pConfig->zName, FTS5_RANK_NAME
  173886. );
  173887. assert( zSql || rc==SQLITE_NOMEM );
  173888. if( zSql ){
  173889. rc = sqlite3_declare_vtab(pConfig->db, zSql);
  173890. sqlite3_free(zSql);
  173891. }
  173892. return rc;
  173893. }
  173894. /*
  173895. ** Tokenize the text passed via the second and third arguments.
  173896. **
  173897. ** The callback is invoked once for each token in the input text. The
  173898. ** arguments passed to it are, in order:
  173899. **
  173900. ** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize()
  173901. ** const char *pToken // Pointer to buffer containing token
  173902. ** int nToken // Size of token in bytes
  173903. ** int iStart // Byte offset of start of token within input text
  173904. ** int iEnd // Byte offset of end of token within input text
  173905. ** int iPos // Position of token in input (first token is 0)
  173906. **
  173907. ** If the callback returns a non-zero value the tokenization is abandoned
  173908. ** and no further callbacks are issued.
  173909. **
  173910. ** This function returns SQLITE_OK if successful or an SQLite error code
  173911. ** if an error occurs. If the tokenization was abandoned early because
  173912. ** the callback returned SQLITE_DONE, this is not an error and this function
  173913. ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
  173914. ** because the callback returned another non-zero value, it is assumed
  173915. ** to be an SQLite error code and returned to the caller.
  173916. */
  173917. static int sqlite3Fts5Tokenize(
  173918. Fts5Config *pConfig, /* FTS5 Configuration object */
  173919. int flags, /* FTS5_TOKENIZE_* flags */
  173920. const char *pText, int nText, /* Text to tokenize */
  173921. void *pCtx, /* Context passed to xToken() */
  173922. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  173923. ){
  173924. if( pText==0 ) return SQLITE_OK;
  173925. return pConfig->pTokApi->xTokenize(
  173926. pConfig->pTok, pCtx, flags, pText, nText, xToken
  173927. );
  173928. }
  173929. /*
  173930. ** Argument pIn points to the first character in what is expected to be
  173931. ** a comma-separated list of SQL literals followed by a ')' character.
  173932. ** If it actually is this, return a pointer to the ')'. Otherwise, return
  173933. ** NULL to indicate a parse error.
  173934. */
  173935. static const char *fts5ConfigSkipArgs(const char *pIn){
  173936. const char *p = pIn;
  173937. while( 1 ){
  173938. p = fts5ConfigSkipWhitespace(p);
  173939. p = fts5ConfigSkipLiteral(p);
  173940. p = fts5ConfigSkipWhitespace(p);
  173941. if( p==0 || *p==')' ) break;
  173942. if( *p!=',' ){
  173943. p = 0;
  173944. break;
  173945. }
  173946. p++;
  173947. }
  173948. return p;
  173949. }
  173950. /*
  173951. ** Parameter zIn contains a rank() function specification. The format of
  173952. ** this is:
  173953. **
  173954. ** + Bareword (function name)
  173955. ** + Open parenthesis - "("
  173956. ** + Zero or more SQL literals in a comma separated list
  173957. ** + Close parenthesis - ")"
  173958. */
  173959. static int sqlite3Fts5ConfigParseRank(
  173960. const char *zIn, /* Input string */
  173961. char **pzRank, /* OUT: Rank function name */
  173962. char **pzRankArgs /* OUT: Rank function arguments */
  173963. ){
  173964. const char *p = zIn;
  173965. const char *pRank;
  173966. char *zRank = 0;
  173967. char *zRankArgs = 0;
  173968. int rc = SQLITE_OK;
  173969. *pzRank = 0;
  173970. *pzRankArgs = 0;
  173971. if( p==0 ){
  173972. rc = SQLITE_ERROR;
  173973. }else{
  173974. p = fts5ConfigSkipWhitespace(p);
  173975. pRank = p;
  173976. p = fts5ConfigSkipBareword(p);
  173977. if( p ){
  173978. zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
  173979. if( zRank ) memcpy(zRank, pRank, p-pRank);
  173980. }else{
  173981. rc = SQLITE_ERROR;
  173982. }
  173983. if( rc==SQLITE_OK ){
  173984. p = fts5ConfigSkipWhitespace(p);
  173985. if( *p!='(' ) rc = SQLITE_ERROR;
  173986. p++;
  173987. }
  173988. if( rc==SQLITE_OK ){
  173989. const char *pArgs;
  173990. p = fts5ConfigSkipWhitespace(p);
  173991. pArgs = p;
  173992. if( *p!=')' ){
  173993. p = fts5ConfigSkipArgs(p);
  173994. if( p==0 ){
  173995. rc = SQLITE_ERROR;
  173996. }else{
  173997. zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
  173998. if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
  173999. }
  174000. }
  174001. }
  174002. }
  174003. if( rc!=SQLITE_OK ){
  174004. sqlite3_free(zRank);
  174005. assert( zRankArgs==0 );
  174006. }else{
  174007. *pzRank = zRank;
  174008. *pzRankArgs = zRankArgs;
  174009. }
  174010. return rc;
  174011. }
  174012. static int sqlite3Fts5ConfigSetValue(
  174013. Fts5Config *pConfig,
  174014. const char *zKey,
  174015. sqlite3_value *pVal,
  174016. int *pbBadkey
  174017. ){
  174018. int rc = SQLITE_OK;
  174019. if( 0==sqlite3_stricmp(zKey, "pgsz") ){
  174020. int pgsz = 0;
  174021. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  174022. pgsz = sqlite3_value_int(pVal);
  174023. }
  174024. if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
  174025. *pbBadkey = 1;
  174026. }else{
  174027. pConfig->pgsz = pgsz;
  174028. }
  174029. }
  174030. else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
  174031. int nHashSize = -1;
  174032. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  174033. nHashSize = sqlite3_value_int(pVal);
  174034. }
  174035. if( nHashSize<=0 ){
  174036. *pbBadkey = 1;
  174037. }else{
  174038. pConfig->nHashSize = nHashSize;
  174039. }
  174040. }
  174041. else if( 0==sqlite3_stricmp(zKey, "automerge") ){
  174042. int nAutomerge = -1;
  174043. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  174044. nAutomerge = sqlite3_value_int(pVal);
  174045. }
  174046. if( nAutomerge<0 || nAutomerge>64 ){
  174047. *pbBadkey = 1;
  174048. }else{
  174049. if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  174050. pConfig->nAutomerge = nAutomerge;
  174051. }
  174052. }
  174053. else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
  174054. int nUsermerge = -1;
  174055. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  174056. nUsermerge = sqlite3_value_int(pVal);
  174057. }
  174058. if( nUsermerge<2 || nUsermerge>16 ){
  174059. *pbBadkey = 1;
  174060. }else{
  174061. pConfig->nUsermerge = nUsermerge;
  174062. }
  174063. }
  174064. else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
  174065. int nCrisisMerge = -1;
  174066. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  174067. nCrisisMerge = sqlite3_value_int(pVal);
  174068. }
  174069. if( nCrisisMerge<0 ){
  174070. *pbBadkey = 1;
  174071. }else{
  174072. if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  174073. pConfig->nCrisisMerge = nCrisisMerge;
  174074. }
  174075. }
  174076. else if( 0==sqlite3_stricmp(zKey, "rank") ){
  174077. const char *zIn = (const char*)sqlite3_value_text(pVal);
  174078. char *zRank;
  174079. char *zRankArgs;
  174080. rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
  174081. if( rc==SQLITE_OK ){
  174082. sqlite3_free(pConfig->zRank);
  174083. sqlite3_free(pConfig->zRankArgs);
  174084. pConfig->zRank = zRank;
  174085. pConfig->zRankArgs = zRankArgs;
  174086. }else if( rc==SQLITE_ERROR ){
  174087. rc = SQLITE_OK;
  174088. *pbBadkey = 1;
  174089. }
  174090. }else{
  174091. *pbBadkey = 1;
  174092. }
  174093. return rc;
  174094. }
  174095. /*
  174096. ** Load the contents of the %_config table into memory.
  174097. */
  174098. static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
  174099. const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
  174100. char *zSql;
  174101. sqlite3_stmt *p = 0;
  174102. int rc = SQLITE_OK;
  174103. int iVersion = 0;
  174104. /* Set default values */
  174105. pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
  174106. pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  174107. pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
  174108. pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  174109. pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
  174110. zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
  174111. if( zSql ){
  174112. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
  174113. sqlite3_free(zSql);
  174114. }
  174115. assert( rc==SQLITE_OK || p==0 );
  174116. if( rc==SQLITE_OK ){
  174117. while( SQLITE_ROW==sqlite3_step(p) ){
  174118. const char *zK = (const char*)sqlite3_column_text(p, 0);
  174119. sqlite3_value *pVal = sqlite3_column_value(p, 1);
  174120. if( 0==sqlite3_stricmp(zK, "version") ){
  174121. iVersion = sqlite3_value_int(pVal);
  174122. }else{
  174123. int bDummy = 0;
  174124. sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
  174125. }
  174126. }
  174127. rc = sqlite3_finalize(p);
  174128. }
  174129. if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
  174130. rc = SQLITE_ERROR;
  174131. if( pConfig->pzErrmsg ){
  174132. assert( 0==*pConfig->pzErrmsg );
  174133. *pConfig->pzErrmsg = sqlite3_mprintf(
  174134. "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
  174135. iVersion, FTS5_CURRENT_VERSION
  174136. );
  174137. }
  174138. }
  174139. if( rc==SQLITE_OK ){
  174140. pConfig->iCookie = iCookie;
  174141. }
  174142. return rc;
  174143. }
  174144. /*
  174145. ** 2014 May 31
  174146. **
  174147. ** The author disclaims copyright to this source code. In place of
  174148. ** a legal notice, here is a blessing:
  174149. **
  174150. ** May you do good and not evil.
  174151. ** May you find forgiveness for yourself and forgive others.
  174152. ** May you share freely, never taking more than you give.
  174153. **
  174154. ******************************************************************************
  174155. **
  174156. */
  174157. /* #include "fts5Int.h" */
  174158. /* #include "fts5parse.h" */
  174159. /*
  174160. ** All token types in the generated fts5parse.h file are greater than 0.
  174161. */
  174162. #define FTS5_EOF 0
  174163. #define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  174164. typedef struct Fts5ExprTerm Fts5ExprTerm;
  174165. /*
  174166. ** Functions generated by lemon from fts5parse.y.
  174167. */
  174168. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
  174169. static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
  174170. static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
  174171. #ifndef NDEBUG
  174172. /* #include <stdio.h> */
  174173. static void sqlite3Fts5ParserTrace(FILE*, char*);
  174174. #endif
  174175. struct Fts5Expr {
  174176. Fts5Index *pIndex;
  174177. Fts5Config *pConfig;
  174178. Fts5ExprNode *pRoot;
  174179. int bDesc; /* Iterate in descending rowid order */
  174180. int nPhrase; /* Number of phrases in expression */
  174181. Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */
  174182. };
  174183. /*
  174184. ** eType:
  174185. ** Expression node type. Always one of:
  174186. **
  174187. ** FTS5_AND (nChild, apChild valid)
  174188. ** FTS5_OR (nChild, apChild valid)
  174189. ** FTS5_NOT (nChild, apChild valid)
  174190. ** FTS5_STRING (pNear valid)
  174191. ** FTS5_TERM (pNear valid)
  174192. */
  174193. struct Fts5ExprNode {
  174194. int eType; /* Node type */
  174195. int bEof; /* True at EOF */
  174196. int bNomatch; /* True if entry is not a match */
  174197. /* Next method for this node. */
  174198. int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
  174199. i64 iRowid; /* Current rowid */
  174200. Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */
  174201. /* Child nodes. For a NOT node, this array always contains 2 entries. For
  174202. ** AND or OR nodes, it contains 2 or more entries. */
  174203. int nChild; /* Number of child nodes */
  174204. Fts5ExprNode *apChild[1]; /* Array of child nodes */
  174205. };
  174206. #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
  174207. /*
  174208. ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
  174209. ** used as if it has the same signature as the xNext() methods themselves.
  174210. */
  174211. #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
  174212. /*
  174213. ** An instance of the following structure represents a single search term
  174214. ** or term prefix.
  174215. */
  174216. struct Fts5ExprTerm {
  174217. int bPrefix; /* True for a prefix term */
  174218. char *zTerm; /* nul-terminated term */
  174219. Fts5IndexIter *pIter; /* Iterator for this term */
  174220. Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */
  174221. };
  174222. /*
  174223. ** A phrase. One or more terms that must appear in a contiguous sequence
  174224. ** within a document for it to match.
  174225. */
  174226. struct Fts5ExprPhrase {
  174227. Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */
  174228. Fts5Buffer poslist; /* Current position list */
  174229. int nTerm; /* Number of entries in aTerm[] */
  174230. Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */
  174231. };
  174232. /*
  174233. ** One or more phrases that must appear within a certain token distance of
  174234. ** each other within each matching document.
  174235. */
  174236. struct Fts5ExprNearset {
  174237. int nNear; /* NEAR parameter */
  174238. Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */
  174239. int nPhrase; /* Number of entries in aPhrase[] array */
  174240. Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */
  174241. };
  174242. /*
  174243. ** Parse context.
  174244. */
  174245. struct Fts5Parse {
  174246. Fts5Config *pConfig;
  174247. char *zErr;
  174248. int rc;
  174249. int nPhrase; /* Size of apPhrase array */
  174250. Fts5ExprPhrase **apPhrase; /* Array of all phrases */
  174251. Fts5ExprNode *pExpr; /* Result of a successful parse */
  174252. };
  174253. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
  174254. va_list ap;
  174255. va_start(ap, zFmt);
  174256. if( pParse->rc==SQLITE_OK ){
  174257. pParse->zErr = sqlite3_vmprintf(zFmt, ap);
  174258. pParse->rc = SQLITE_ERROR;
  174259. }
  174260. va_end(ap);
  174261. }
  174262. static int fts5ExprIsspace(char t){
  174263. return t==' ' || t=='\t' || t=='\n' || t=='\r';
  174264. }
  174265. /*
  174266. ** Read the first token from the nul-terminated string at *pz.
  174267. */
  174268. static int fts5ExprGetToken(
  174269. Fts5Parse *pParse,
  174270. const char **pz, /* IN/OUT: Pointer into buffer */
  174271. Fts5Token *pToken
  174272. ){
  174273. const char *z = *pz;
  174274. int tok;
  174275. /* Skip past any whitespace */
  174276. while( fts5ExprIsspace(*z) ) z++;
  174277. pToken->p = z;
  174278. pToken->n = 1;
  174279. switch( *z ){
  174280. case '(': tok = FTS5_LP; break;
  174281. case ')': tok = FTS5_RP; break;
  174282. case '{': tok = FTS5_LCP; break;
  174283. case '}': tok = FTS5_RCP; break;
  174284. case ':': tok = FTS5_COLON; break;
  174285. case ',': tok = FTS5_COMMA; break;
  174286. case '+': tok = FTS5_PLUS; break;
  174287. case '*': tok = FTS5_STAR; break;
  174288. case '-': tok = FTS5_MINUS; break;
  174289. case '\0': tok = FTS5_EOF; break;
  174290. case '"': {
  174291. const char *z2;
  174292. tok = FTS5_STRING;
  174293. for(z2=&z[1]; 1; z2++){
  174294. if( z2[0]=='"' ){
  174295. z2++;
  174296. if( z2[0]!='"' ) break;
  174297. }
  174298. if( z2[0]=='\0' ){
  174299. sqlite3Fts5ParseError(pParse, "unterminated string");
  174300. return FTS5_EOF;
  174301. }
  174302. }
  174303. pToken->n = (z2 - z);
  174304. break;
  174305. }
  174306. default: {
  174307. const char *z2;
  174308. if( sqlite3Fts5IsBareword(z[0])==0 ){
  174309. sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
  174310. return FTS5_EOF;
  174311. }
  174312. tok = FTS5_STRING;
  174313. for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
  174314. pToken->n = (z2 - z);
  174315. if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR;
  174316. if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
  174317. if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
  174318. break;
  174319. }
  174320. }
  174321. *pz = &pToken->p[pToken->n];
  174322. return tok;
  174323. }
  174324. static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
  174325. static void fts5ParseFree(void *p){ sqlite3_free(p); }
  174326. static int sqlite3Fts5ExprNew(
  174327. Fts5Config *pConfig, /* FTS5 Configuration */
  174328. int iCol,
  174329. const char *zExpr, /* Expression text */
  174330. Fts5Expr **ppNew,
  174331. char **pzErr
  174332. ){
  174333. Fts5Parse sParse;
  174334. Fts5Token token;
  174335. const char *z = zExpr;
  174336. int t; /* Next token type */
  174337. void *pEngine;
  174338. Fts5Expr *pNew;
  174339. *ppNew = 0;
  174340. *pzErr = 0;
  174341. memset(&sParse, 0, sizeof(sParse));
  174342. pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
  174343. if( pEngine==0 ){ return SQLITE_NOMEM; }
  174344. sParse.pConfig = pConfig;
  174345. do {
  174346. t = fts5ExprGetToken(&sParse, &z, &token);
  174347. sqlite3Fts5Parser(pEngine, t, token, &sParse);
  174348. }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
  174349. sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
  174350. /* If the LHS of the MATCH expression was a user column, apply the
  174351. ** implicit column-filter. */
  174352. if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
  174353. int n = sizeof(Fts5Colset);
  174354. Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
  174355. if( pColset ){
  174356. pColset->nCol = 1;
  174357. pColset->aiCol[0] = iCol;
  174358. sqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset);
  174359. }
  174360. }
  174361. assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
  174362. if( sParse.rc==SQLITE_OK ){
  174363. *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
  174364. if( pNew==0 ){
  174365. sParse.rc = SQLITE_NOMEM;
  174366. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  174367. }else{
  174368. if( !sParse.pExpr ){
  174369. const int nByte = sizeof(Fts5ExprNode);
  174370. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
  174371. if( pNew->pRoot ){
  174372. pNew->pRoot->bEof = 1;
  174373. }
  174374. }else{
  174375. pNew->pRoot = sParse.pExpr;
  174376. }
  174377. pNew->pIndex = 0;
  174378. pNew->pConfig = pConfig;
  174379. pNew->apExprPhrase = sParse.apPhrase;
  174380. pNew->nPhrase = sParse.nPhrase;
  174381. sParse.apPhrase = 0;
  174382. }
  174383. }else{
  174384. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  174385. }
  174386. sqlite3_free(sParse.apPhrase);
  174387. *pzErr = sParse.zErr;
  174388. return sParse.rc;
  174389. }
  174390. /*
  174391. ** Free the expression node object passed as the only argument.
  174392. */
  174393. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
  174394. if( p ){
  174395. int i;
  174396. for(i=0; i<p->nChild; i++){
  174397. sqlite3Fts5ParseNodeFree(p->apChild[i]);
  174398. }
  174399. sqlite3Fts5ParseNearsetFree(p->pNear);
  174400. sqlite3_free(p);
  174401. }
  174402. }
  174403. /*
  174404. ** Free the expression object passed as the only argument.
  174405. */
  174406. static void sqlite3Fts5ExprFree(Fts5Expr *p){
  174407. if( p ){
  174408. sqlite3Fts5ParseNodeFree(p->pRoot);
  174409. sqlite3_free(p->apExprPhrase);
  174410. sqlite3_free(p);
  174411. }
  174412. }
  174413. /*
  174414. ** Argument pTerm must be a synonym iterator. Return the current rowid
  174415. ** that it points to.
  174416. */
  174417. static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
  174418. i64 iRet = 0;
  174419. int bRetValid = 0;
  174420. Fts5ExprTerm *p;
  174421. assert( pTerm->pSynonym );
  174422. assert( bDesc==0 || bDesc==1 );
  174423. for(p=pTerm; p; p=p->pSynonym){
  174424. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  174425. i64 iRowid = p->pIter->iRowid;
  174426. if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
  174427. iRet = iRowid;
  174428. bRetValid = 1;
  174429. }
  174430. }
  174431. }
  174432. if( pbEof && bRetValid==0 ) *pbEof = 1;
  174433. return iRet;
  174434. }
  174435. /*
  174436. ** Argument pTerm must be a synonym iterator.
  174437. */
  174438. static int fts5ExprSynonymList(
  174439. Fts5ExprTerm *pTerm,
  174440. i64 iRowid,
  174441. Fts5Buffer *pBuf, /* Use this buffer for space if required */
  174442. u8 **pa, int *pn
  174443. ){
  174444. Fts5PoslistReader aStatic[4];
  174445. Fts5PoslistReader *aIter = aStatic;
  174446. int nIter = 0;
  174447. int nAlloc = 4;
  174448. int rc = SQLITE_OK;
  174449. Fts5ExprTerm *p;
  174450. assert( pTerm->pSynonym );
  174451. for(p=pTerm; p; p=p->pSynonym){
  174452. Fts5IndexIter *pIter = p->pIter;
  174453. if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
  174454. if( pIter->nData==0 ) continue;
  174455. if( nIter==nAlloc ){
  174456. int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
  174457. Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
  174458. if( aNew==0 ){
  174459. rc = SQLITE_NOMEM;
  174460. goto synonym_poslist_out;
  174461. }
  174462. memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
  174463. nAlloc = nAlloc*2;
  174464. if( aIter!=aStatic ) sqlite3_free(aIter);
  174465. aIter = aNew;
  174466. }
  174467. sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
  174468. assert( aIter[nIter].bEof==0 );
  174469. nIter++;
  174470. }
  174471. }
  174472. if( nIter==1 ){
  174473. *pa = (u8*)aIter[0].a;
  174474. *pn = aIter[0].n;
  174475. }else{
  174476. Fts5PoslistWriter writer = {0};
  174477. i64 iPrev = -1;
  174478. fts5BufferZero(pBuf);
  174479. while( 1 ){
  174480. int i;
  174481. i64 iMin = FTS5_LARGEST_INT64;
  174482. for(i=0; i<nIter; i++){
  174483. if( aIter[i].bEof==0 ){
  174484. if( aIter[i].iPos==iPrev ){
  174485. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
  174486. }
  174487. if( aIter[i].iPos<iMin ){
  174488. iMin = aIter[i].iPos;
  174489. }
  174490. }
  174491. }
  174492. if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
  174493. rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
  174494. iPrev = iMin;
  174495. }
  174496. if( rc==SQLITE_OK ){
  174497. *pa = pBuf->p;
  174498. *pn = pBuf->n;
  174499. }
  174500. }
  174501. synonym_poslist_out:
  174502. if( aIter!=aStatic ) sqlite3_free(aIter);
  174503. return rc;
  174504. }
  174505. /*
  174506. ** All individual term iterators in pPhrase are guaranteed to be valid and
  174507. ** pointing to the same rowid when this function is called. This function
  174508. ** checks if the current rowid really is a match, and if so populates
  174509. ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
  174510. ** is set to true if this is really a match, or false otherwise.
  174511. **
  174512. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  174513. ** otherwise. It is not considered an error code if the current rowid is
  174514. ** not a match.
  174515. */
  174516. static int fts5ExprPhraseIsMatch(
  174517. Fts5ExprNode *pNode, /* Node pPhrase belongs to */
  174518. Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */
  174519. int *pbMatch /* OUT: Set to true if really a match */
  174520. ){
  174521. Fts5PoslistWriter writer = {0};
  174522. Fts5PoslistReader aStatic[4];
  174523. Fts5PoslistReader *aIter = aStatic;
  174524. int i;
  174525. int rc = SQLITE_OK;
  174526. fts5BufferZero(&pPhrase->poslist);
  174527. /* If the aStatic[] array is not large enough, allocate a large array
  174528. ** using sqlite3_malloc(). This approach could be improved upon. */
  174529. if( pPhrase->nTerm>ArraySize(aStatic) ){
  174530. int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
  174531. aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
  174532. if( !aIter ) return SQLITE_NOMEM;
  174533. }
  174534. memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
  174535. /* Initialize a term iterator for each term in the phrase */
  174536. for(i=0; i<pPhrase->nTerm; i++){
  174537. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  174538. int n = 0;
  174539. int bFlag = 0;
  174540. u8 *a = 0;
  174541. if( pTerm->pSynonym ){
  174542. Fts5Buffer buf = {0, 0, 0};
  174543. rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
  174544. if( rc ){
  174545. sqlite3_free(a);
  174546. goto ismatch_out;
  174547. }
  174548. if( a==buf.p ) bFlag = 1;
  174549. }else{
  174550. a = (u8*)pTerm->pIter->pData;
  174551. n = pTerm->pIter->nData;
  174552. }
  174553. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  174554. aIter[i].bFlag = (u8)bFlag;
  174555. if( aIter[i].bEof ) goto ismatch_out;
  174556. }
  174557. while( 1 ){
  174558. int bMatch;
  174559. i64 iPos = aIter[0].iPos;
  174560. do {
  174561. bMatch = 1;
  174562. for(i=0; i<pPhrase->nTerm; i++){
  174563. Fts5PoslistReader *pPos = &aIter[i];
  174564. i64 iAdj = iPos + i;
  174565. if( pPos->iPos!=iAdj ){
  174566. bMatch = 0;
  174567. while( pPos->iPos<iAdj ){
  174568. if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
  174569. }
  174570. if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
  174571. }
  174572. }
  174573. }while( bMatch==0 );
  174574. /* Append position iPos to the output */
  174575. rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
  174576. if( rc!=SQLITE_OK ) goto ismatch_out;
  174577. for(i=0; i<pPhrase->nTerm; i++){
  174578. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
  174579. }
  174580. }
  174581. ismatch_out:
  174582. *pbMatch = (pPhrase->poslist.n>0);
  174583. for(i=0; i<pPhrase->nTerm; i++){
  174584. if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
  174585. }
  174586. if( aIter!=aStatic ) sqlite3_free(aIter);
  174587. return rc;
  174588. }
  174589. typedef struct Fts5LookaheadReader Fts5LookaheadReader;
  174590. struct Fts5LookaheadReader {
  174591. const u8 *a; /* Buffer containing position list */
  174592. int n; /* Size of buffer a[] in bytes */
  174593. int i; /* Current offset in position list */
  174594. i64 iPos; /* Current position */
  174595. i64 iLookahead; /* Next position */
  174596. };
  174597. #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
  174598. static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
  174599. p->iPos = p->iLookahead;
  174600. if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
  174601. p->iLookahead = FTS5_LOOKAHEAD_EOF;
  174602. }
  174603. return (p->iPos==FTS5_LOOKAHEAD_EOF);
  174604. }
  174605. static int fts5LookaheadReaderInit(
  174606. const u8 *a, int n, /* Buffer to read position list from */
  174607. Fts5LookaheadReader *p /* Iterator object to initialize */
  174608. ){
  174609. memset(p, 0, sizeof(Fts5LookaheadReader));
  174610. p->a = a;
  174611. p->n = n;
  174612. fts5LookaheadReaderNext(p);
  174613. return fts5LookaheadReaderNext(p);
  174614. }
  174615. typedef struct Fts5NearTrimmer Fts5NearTrimmer;
  174616. struct Fts5NearTrimmer {
  174617. Fts5LookaheadReader reader; /* Input iterator */
  174618. Fts5PoslistWriter writer; /* Writer context */
  174619. Fts5Buffer *pOut; /* Output poslist */
  174620. };
  174621. /*
  174622. ** The near-set object passed as the first argument contains more than
  174623. ** one phrase. All phrases currently point to the same row. The
  174624. ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
  174625. ** tests if the current row contains instances of each phrase sufficiently
  174626. ** close together to meet the NEAR constraint. Non-zero is returned if it
  174627. ** does, or zero otherwise.
  174628. **
  174629. ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
  174630. ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
  174631. ** occurs within this function (*pRc) is set accordingly before returning.
  174632. ** The return value is undefined in both these cases.
  174633. **
  174634. ** If no error occurs and non-zero (a match) is returned, the position-list
  174635. ** of each phrase object is edited to contain only those entries that
  174636. ** meet the constraint before returning.
  174637. */
  174638. static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
  174639. Fts5NearTrimmer aStatic[4];
  174640. Fts5NearTrimmer *a = aStatic;
  174641. Fts5ExprPhrase **apPhrase = pNear->apPhrase;
  174642. int i;
  174643. int rc = *pRc;
  174644. int bMatch;
  174645. assert( pNear->nPhrase>1 );
  174646. /* If the aStatic[] array is not large enough, allocate a large array
  174647. ** using sqlite3_malloc(). This approach could be improved upon. */
  174648. if( pNear->nPhrase>ArraySize(aStatic) ){
  174649. int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
  174650. a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
  174651. }else{
  174652. memset(aStatic, 0, sizeof(aStatic));
  174653. }
  174654. if( rc!=SQLITE_OK ){
  174655. *pRc = rc;
  174656. return 0;
  174657. }
  174658. /* Initialize a lookahead iterator for each phrase. After passing the
  174659. ** buffer and buffer size to the lookaside-reader init function, zero
  174660. ** the phrase poslist buffer. The new poslist for the phrase (containing
  174661. ** the same entries as the original with some entries removed on account
  174662. ** of the NEAR constraint) is written over the original even as it is
  174663. ** being read. This is safe as the entries for the new poslist are a
  174664. ** subset of the old, so it is not possible for data yet to be read to
  174665. ** be overwritten. */
  174666. for(i=0; i<pNear->nPhrase; i++){
  174667. Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
  174668. fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
  174669. pPoslist->n = 0;
  174670. a[i].pOut = pPoslist;
  174671. }
  174672. while( 1 ){
  174673. int iAdv;
  174674. i64 iMin;
  174675. i64 iMax;
  174676. /* This block advances the phrase iterators until they point to a set of
  174677. ** entries that together comprise a match. */
  174678. iMax = a[0].reader.iPos;
  174679. do {
  174680. bMatch = 1;
  174681. for(i=0; i<pNear->nPhrase; i++){
  174682. Fts5LookaheadReader *pPos = &a[i].reader;
  174683. iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
  174684. if( pPos->iPos<iMin || pPos->iPos>iMax ){
  174685. bMatch = 0;
  174686. while( pPos->iPos<iMin ){
  174687. if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
  174688. }
  174689. if( pPos->iPos>iMax ) iMax = pPos->iPos;
  174690. }
  174691. }
  174692. }while( bMatch==0 );
  174693. /* Add an entry to each output position list */
  174694. for(i=0; i<pNear->nPhrase; i++){
  174695. i64 iPos = a[i].reader.iPos;
  174696. Fts5PoslistWriter *pWriter = &a[i].writer;
  174697. if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
  174698. sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
  174699. }
  174700. }
  174701. iAdv = 0;
  174702. iMin = a[0].reader.iLookahead;
  174703. for(i=0; i<pNear->nPhrase; i++){
  174704. if( a[i].reader.iLookahead < iMin ){
  174705. iMin = a[i].reader.iLookahead;
  174706. iAdv = i;
  174707. }
  174708. }
  174709. if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
  174710. }
  174711. ismatch_out: {
  174712. int bRet = a[0].pOut->n>0;
  174713. *pRc = rc;
  174714. if( a!=aStatic ) sqlite3_free(a);
  174715. return bRet;
  174716. }
  174717. }
  174718. /*
  174719. ** Advance iterator pIter until it points to a value equal to or laster
  174720. ** than the initial value of *piLast. If this means the iterator points
  174721. ** to a value laster than *piLast, update *piLast to the new lastest value.
  174722. **
  174723. ** If the iterator reaches EOF, set *pbEof to true before returning. If
  174724. ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
  174725. ** are set, return a non-zero value. Otherwise, return zero.
  174726. */
  174727. static int fts5ExprAdvanceto(
  174728. Fts5IndexIter *pIter, /* Iterator to advance */
  174729. int bDesc, /* True if iterator is "rowid DESC" */
  174730. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  174731. int *pRc, /* OUT: Error code */
  174732. int *pbEof /* OUT: Set to true if EOF */
  174733. ){
  174734. i64 iLast = *piLast;
  174735. i64 iRowid;
  174736. iRowid = pIter->iRowid;
  174737. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  174738. int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
  174739. if( rc || sqlite3Fts5IterEof(pIter) ){
  174740. *pRc = rc;
  174741. *pbEof = 1;
  174742. return 1;
  174743. }
  174744. iRowid = pIter->iRowid;
  174745. assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
  174746. }
  174747. *piLast = iRowid;
  174748. return 0;
  174749. }
  174750. static int fts5ExprSynonymAdvanceto(
  174751. Fts5ExprTerm *pTerm, /* Term iterator to advance */
  174752. int bDesc, /* True if iterator is "rowid DESC" */
  174753. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  174754. int *pRc /* OUT: Error code */
  174755. ){
  174756. int rc = SQLITE_OK;
  174757. i64 iLast = *piLast;
  174758. Fts5ExprTerm *p;
  174759. int bEof = 0;
  174760. for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
  174761. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  174762. i64 iRowid = p->pIter->iRowid;
  174763. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  174764. rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
  174765. }
  174766. }
  174767. }
  174768. if( rc!=SQLITE_OK ){
  174769. *pRc = rc;
  174770. bEof = 1;
  174771. }else{
  174772. *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
  174773. }
  174774. return bEof;
  174775. }
  174776. static int fts5ExprNearTest(
  174777. int *pRc,
  174778. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  174779. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */
  174780. ){
  174781. Fts5ExprNearset *pNear = pNode->pNear;
  174782. int rc = *pRc;
  174783. if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
  174784. Fts5ExprTerm *pTerm;
  174785. Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
  174786. pPhrase->poslist.n = 0;
  174787. for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  174788. Fts5IndexIter *pIter = pTerm->pIter;
  174789. if( sqlite3Fts5IterEof(pIter)==0 ){
  174790. if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
  174791. pPhrase->poslist.n = 1;
  174792. }
  174793. }
  174794. }
  174795. return pPhrase->poslist.n;
  174796. }else{
  174797. int i;
  174798. /* Check that each phrase in the nearset matches the current row.
  174799. ** Populate the pPhrase->poslist buffers at the same time. If any
  174800. ** phrase is not a match, break out of the loop early. */
  174801. for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
  174802. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  174803. if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){
  174804. int bMatch = 0;
  174805. rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
  174806. if( bMatch==0 ) break;
  174807. }else{
  174808. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  174809. fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
  174810. }
  174811. }
  174812. *pRc = rc;
  174813. if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
  174814. return 1;
  174815. }
  174816. return 0;
  174817. }
  174818. }
  174819. /*
  174820. ** Initialize all term iterators in the pNear object. If any term is found
  174821. ** to match no documents at all, return immediately without initializing any
  174822. ** further iterators.
  174823. **
  174824. ** If an error occurs, return an SQLite error code. Otherwise, return
  174825. ** SQLITE_OK. It is not considered an error if some term matches zero
  174826. ** documents.
  174827. */
  174828. static int fts5ExprNearInitAll(
  174829. Fts5Expr *pExpr,
  174830. Fts5ExprNode *pNode
  174831. ){
  174832. Fts5ExprNearset *pNear = pNode->pNear;
  174833. int i;
  174834. assert( pNode->bNomatch==0 );
  174835. for(i=0; i<pNear->nPhrase; i++){
  174836. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  174837. if( pPhrase->nTerm==0 ){
  174838. pNode->bEof = 1;
  174839. return SQLITE_OK;
  174840. }else{
  174841. int j;
  174842. for(j=0; j<pPhrase->nTerm; j++){
  174843. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  174844. Fts5ExprTerm *p;
  174845. int bHit = 0;
  174846. for(p=pTerm; p; p=p->pSynonym){
  174847. int rc;
  174848. if( p->pIter ){
  174849. sqlite3Fts5IterClose(p->pIter);
  174850. p->pIter = 0;
  174851. }
  174852. rc = sqlite3Fts5IndexQuery(
  174853. pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
  174854. (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
  174855. (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
  174856. pNear->pColset,
  174857. &p->pIter
  174858. );
  174859. assert( (rc==SQLITE_OK)==(p->pIter!=0) );
  174860. if( rc!=SQLITE_OK ) return rc;
  174861. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  174862. bHit = 1;
  174863. }
  174864. }
  174865. if( bHit==0 ){
  174866. pNode->bEof = 1;
  174867. return SQLITE_OK;
  174868. }
  174869. }
  174870. }
  174871. }
  174872. pNode->bEof = 0;
  174873. return SQLITE_OK;
  174874. }
  174875. /*
  174876. ** If pExpr is an ASC iterator, this function returns a value with the
  174877. ** same sign as:
  174878. **
  174879. ** (iLhs - iRhs)
  174880. **
  174881. ** Otherwise, if this is a DESC iterator, the opposite is returned:
  174882. **
  174883. ** (iRhs - iLhs)
  174884. */
  174885. static int fts5RowidCmp(
  174886. Fts5Expr *pExpr,
  174887. i64 iLhs,
  174888. i64 iRhs
  174889. ){
  174890. assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
  174891. if( pExpr->bDesc==0 ){
  174892. if( iLhs<iRhs ) return -1;
  174893. return (iLhs > iRhs);
  174894. }else{
  174895. if( iLhs>iRhs ) return -1;
  174896. return (iLhs < iRhs);
  174897. }
  174898. }
  174899. static void fts5ExprSetEof(Fts5ExprNode *pNode){
  174900. int i;
  174901. pNode->bEof = 1;
  174902. pNode->bNomatch = 0;
  174903. for(i=0; i<pNode->nChild; i++){
  174904. fts5ExprSetEof(pNode->apChild[i]);
  174905. }
  174906. }
  174907. static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
  174908. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  174909. Fts5ExprNearset *pNear = pNode->pNear;
  174910. int i;
  174911. for(i=0; i<pNear->nPhrase; i++){
  174912. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  174913. pPhrase->poslist.n = 0;
  174914. }
  174915. }else{
  174916. int i;
  174917. for(i=0; i<pNode->nChild; i++){
  174918. fts5ExprNodeZeroPoslist(pNode->apChild[i]);
  174919. }
  174920. }
  174921. }
  174922. /*
  174923. ** Compare the values currently indicated by the two nodes as follows:
  174924. **
  174925. ** res = (*p1) - (*p2)
  174926. **
  174927. ** Nodes that point to values that come later in the iteration order are
  174928. ** considered to be larger. Nodes at EOF are the largest of all.
  174929. **
  174930. ** This means that if the iteration order is ASC, then numerically larger
  174931. ** rowids are considered larger. Or if it is the default DESC, numerically
  174932. ** smaller rowids are larger.
  174933. */
  174934. static int fts5NodeCompare(
  174935. Fts5Expr *pExpr,
  174936. Fts5ExprNode *p1,
  174937. Fts5ExprNode *p2
  174938. ){
  174939. if( p2->bEof ) return -1;
  174940. if( p1->bEof ) return +1;
  174941. return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
  174942. }
  174943. /*
  174944. ** All individual term iterators in pNear are guaranteed to be valid when
  174945. ** this function is called. This function checks if all term iterators
  174946. ** point to the same rowid, and if not, advances them until they do.
  174947. ** If an EOF is reached before this happens, *pbEof is set to true before
  174948. ** returning.
  174949. **
  174950. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  174951. ** otherwise. It is not considered an error code if an iterator reaches
  174952. ** EOF.
  174953. */
  174954. static int fts5ExprNodeTest_STRING(
  174955. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  174956. Fts5ExprNode *pNode
  174957. ){
  174958. Fts5ExprNearset *pNear = pNode->pNear;
  174959. Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
  174960. int rc = SQLITE_OK;
  174961. i64 iLast; /* Lastest rowid any iterator points to */
  174962. int i, j; /* Phrase and token index, respectively */
  174963. int bMatch; /* True if all terms are at the same rowid */
  174964. const int bDesc = pExpr->bDesc;
  174965. /* Check that this node should not be FTS5_TERM */
  174966. assert( pNear->nPhrase>1
  174967. || pNear->apPhrase[0]->nTerm>1
  174968. || pNear->apPhrase[0]->aTerm[0].pSynonym
  174969. );
  174970. /* Initialize iLast, the "lastest" rowid any iterator points to. If the
  174971. ** iterator skips through rowids in the default ascending order, this means
  174972. ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
  174973. ** means the minimum rowid. */
  174974. if( pLeft->aTerm[0].pSynonym ){
  174975. iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
  174976. }else{
  174977. iLast = pLeft->aTerm[0].pIter->iRowid;
  174978. }
  174979. do {
  174980. bMatch = 1;
  174981. for(i=0; i<pNear->nPhrase; i++){
  174982. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  174983. for(j=0; j<pPhrase->nTerm; j++){
  174984. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  174985. if( pTerm->pSynonym ){
  174986. i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
  174987. if( iRowid==iLast ) continue;
  174988. bMatch = 0;
  174989. if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
  174990. pNode->bNomatch = 0;
  174991. pNode->bEof = 1;
  174992. return rc;
  174993. }
  174994. }else{
  174995. Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
  174996. if( pIter->iRowid==iLast || pIter->bEof ) continue;
  174997. bMatch = 0;
  174998. if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
  174999. return rc;
  175000. }
  175001. }
  175002. }
  175003. }
  175004. }while( bMatch==0 );
  175005. pNode->iRowid = iLast;
  175006. pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
  175007. assert( pNode->bEof==0 || pNode->bNomatch==0 );
  175008. return rc;
  175009. }
  175010. /*
  175011. ** Advance the first term iterator in the first phrase of pNear. Set output
  175012. ** variable *pbEof to true if it reaches EOF or if an error occurs.
  175013. **
  175014. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  175015. ** occurs.
  175016. */
  175017. static int fts5ExprNodeNext_STRING(
  175018. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  175019. Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */
  175020. int bFromValid,
  175021. i64 iFrom
  175022. ){
  175023. Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
  175024. int rc = SQLITE_OK;
  175025. pNode->bNomatch = 0;
  175026. if( pTerm->pSynonym ){
  175027. int bEof = 1;
  175028. Fts5ExprTerm *p;
  175029. /* Find the firstest rowid any synonym points to. */
  175030. i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
  175031. /* Advance each iterator that currently points to iRowid. Or, if iFrom
  175032. ** is valid - each iterator that points to a rowid before iFrom. */
  175033. for(p=pTerm; p; p=p->pSynonym){
  175034. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  175035. i64 ii = p->pIter->iRowid;
  175036. if( ii==iRowid
  175037. || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
  175038. ){
  175039. if( bFromValid ){
  175040. rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
  175041. }else{
  175042. rc = sqlite3Fts5IterNext(p->pIter);
  175043. }
  175044. if( rc!=SQLITE_OK ) break;
  175045. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  175046. bEof = 0;
  175047. }
  175048. }else{
  175049. bEof = 0;
  175050. }
  175051. }
  175052. }
  175053. /* Set the EOF flag if either all synonym iterators are at EOF or an
  175054. ** error has occurred. */
  175055. pNode->bEof = (rc || bEof);
  175056. }else{
  175057. Fts5IndexIter *pIter = pTerm->pIter;
  175058. assert( Fts5NodeIsString(pNode) );
  175059. if( bFromValid ){
  175060. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  175061. }else{
  175062. rc = sqlite3Fts5IterNext(pIter);
  175063. }
  175064. pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
  175065. }
  175066. if( pNode->bEof==0 ){
  175067. assert( rc==SQLITE_OK );
  175068. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  175069. }
  175070. return rc;
  175071. }
  175072. static int fts5ExprNodeTest_TERM(
  175073. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  175074. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */
  175075. ){
  175076. /* As this "NEAR" object is actually a single phrase that consists
  175077. ** of a single term only, grab pointers into the poslist managed by the
  175078. ** fts5_index.c iterator object. This is much faster than synthesizing
  175079. ** a new poslist the way we have to for more complicated phrase or NEAR
  175080. ** expressions. */
  175081. Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
  175082. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  175083. assert( pNode->eType==FTS5_TERM );
  175084. assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
  175085. assert( pPhrase->aTerm[0].pSynonym==0 );
  175086. pPhrase->poslist.n = pIter->nData;
  175087. if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
  175088. pPhrase->poslist.p = (u8*)pIter->pData;
  175089. }
  175090. pNode->iRowid = pIter->iRowid;
  175091. pNode->bNomatch = (pPhrase->poslist.n==0);
  175092. return SQLITE_OK;
  175093. }
  175094. /*
  175095. ** xNext() method for a node of type FTS5_TERM.
  175096. */
  175097. static int fts5ExprNodeNext_TERM(
  175098. Fts5Expr *pExpr,
  175099. Fts5ExprNode *pNode,
  175100. int bFromValid,
  175101. i64 iFrom
  175102. ){
  175103. int rc;
  175104. Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
  175105. assert( pNode->bEof==0 );
  175106. if( bFromValid ){
  175107. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  175108. }else{
  175109. rc = sqlite3Fts5IterNext(pIter);
  175110. }
  175111. if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
  175112. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  175113. }else{
  175114. pNode->bEof = 1;
  175115. pNode->bNomatch = 0;
  175116. }
  175117. return rc;
  175118. }
  175119. static void fts5ExprNodeTest_OR(
  175120. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  175121. Fts5ExprNode *pNode /* Expression node to test */
  175122. ){
  175123. Fts5ExprNode *pNext = pNode->apChild[0];
  175124. int i;
  175125. for(i=1; i<pNode->nChild; i++){
  175126. Fts5ExprNode *pChild = pNode->apChild[i];
  175127. int cmp = fts5NodeCompare(pExpr, pNext, pChild);
  175128. if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
  175129. pNext = pChild;
  175130. }
  175131. }
  175132. pNode->iRowid = pNext->iRowid;
  175133. pNode->bEof = pNext->bEof;
  175134. pNode->bNomatch = pNext->bNomatch;
  175135. }
  175136. static int fts5ExprNodeNext_OR(
  175137. Fts5Expr *pExpr,
  175138. Fts5ExprNode *pNode,
  175139. int bFromValid,
  175140. i64 iFrom
  175141. ){
  175142. int i;
  175143. i64 iLast = pNode->iRowid;
  175144. for(i=0; i<pNode->nChild; i++){
  175145. Fts5ExprNode *p1 = pNode->apChild[i];
  175146. assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
  175147. if( p1->bEof==0 ){
  175148. if( (p1->iRowid==iLast)
  175149. || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
  175150. ){
  175151. int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
  175152. if( rc!=SQLITE_OK ){
  175153. pNode->bNomatch = 0;
  175154. return rc;
  175155. }
  175156. }
  175157. }
  175158. }
  175159. fts5ExprNodeTest_OR(pExpr, pNode);
  175160. return SQLITE_OK;
  175161. }
  175162. /*
  175163. ** Argument pNode is an FTS5_AND node.
  175164. */
  175165. static int fts5ExprNodeTest_AND(
  175166. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  175167. Fts5ExprNode *pAnd /* FTS5_AND node to advance */
  175168. ){
  175169. int iChild;
  175170. i64 iLast = pAnd->iRowid;
  175171. int rc = SQLITE_OK;
  175172. int bMatch;
  175173. assert( pAnd->bEof==0 );
  175174. do {
  175175. pAnd->bNomatch = 0;
  175176. bMatch = 1;
  175177. for(iChild=0; iChild<pAnd->nChild; iChild++){
  175178. Fts5ExprNode *pChild = pAnd->apChild[iChild];
  175179. int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
  175180. if( cmp>0 ){
  175181. /* Advance pChild until it points to iLast or laster */
  175182. rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
  175183. if( rc!=SQLITE_OK ){
  175184. pAnd->bNomatch = 0;
  175185. return rc;
  175186. }
  175187. }
  175188. /* If the child node is now at EOF, so is the parent AND node. Otherwise,
  175189. ** the child node is guaranteed to have advanced at least as far as
  175190. ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
  175191. ** new lastest rowid seen so far. */
  175192. assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
  175193. if( pChild->bEof ){
  175194. fts5ExprSetEof(pAnd);
  175195. bMatch = 1;
  175196. break;
  175197. }else if( iLast!=pChild->iRowid ){
  175198. bMatch = 0;
  175199. iLast = pChild->iRowid;
  175200. }
  175201. if( pChild->bNomatch ){
  175202. pAnd->bNomatch = 1;
  175203. }
  175204. }
  175205. }while( bMatch==0 );
  175206. if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
  175207. fts5ExprNodeZeroPoslist(pAnd);
  175208. }
  175209. pAnd->iRowid = iLast;
  175210. return SQLITE_OK;
  175211. }
  175212. static int fts5ExprNodeNext_AND(
  175213. Fts5Expr *pExpr,
  175214. Fts5ExprNode *pNode,
  175215. int bFromValid,
  175216. i64 iFrom
  175217. ){
  175218. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  175219. if( rc==SQLITE_OK ){
  175220. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  175221. }else{
  175222. pNode->bNomatch = 0;
  175223. }
  175224. return rc;
  175225. }
  175226. static int fts5ExprNodeTest_NOT(
  175227. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  175228. Fts5ExprNode *pNode /* FTS5_NOT node to advance */
  175229. ){
  175230. int rc = SQLITE_OK;
  175231. Fts5ExprNode *p1 = pNode->apChild[0];
  175232. Fts5ExprNode *p2 = pNode->apChild[1];
  175233. assert( pNode->nChild==2 );
  175234. while( rc==SQLITE_OK && p1->bEof==0 ){
  175235. int cmp = fts5NodeCompare(pExpr, p1, p2);
  175236. if( cmp>0 ){
  175237. rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
  175238. cmp = fts5NodeCompare(pExpr, p1, p2);
  175239. }
  175240. assert( rc!=SQLITE_OK || cmp<=0 );
  175241. if( cmp || p2->bNomatch ) break;
  175242. rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
  175243. }
  175244. pNode->bEof = p1->bEof;
  175245. pNode->bNomatch = p1->bNomatch;
  175246. pNode->iRowid = p1->iRowid;
  175247. if( p1->bEof ){
  175248. fts5ExprNodeZeroPoslist(p2);
  175249. }
  175250. return rc;
  175251. }
  175252. static int fts5ExprNodeNext_NOT(
  175253. Fts5Expr *pExpr,
  175254. Fts5ExprNode *pNode,
  175255. int bFromValid,
  175256. i64 iFrom
  175257. ){
  175258. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  175259. if( rc==SQLITE_OK ){
  175260. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  175261. }
  175262. if( rc!=SQLITE_OK ){
  175263. pNode->bNomatch = 0;
  175264. }
  175265. return rc;
  175266. }
  175267. /*
  175268. ** If pNode currently points to a match, this function returns SQLITE_OK
  175269. ** without modifying it. Otherwise, pNode is advanced until it does point
  175270. ** to a match or EOF is reached.
  175271. */
  175272. static int fts5ExprNodeTest(
  175273. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  175274. Fts5ExprNode *pNode /* Expression node to test */
  175275. ){
  175276. int rc = SQLITE_OK;
  175277. if( pNode->bEof==0 ){
  175278. switch( pNode->eType ){
  175279. case FTS5_STRING: {
  175280. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  175281. break;
  175282. }
  175283. case FTS5_TERM: {
  175284. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  175285. break;
  175286. }
  175287. case FTS5_AND: {
  175288. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  175289. break;
  175290. }
  175291. case FTS5_OR: {
  175292. fts5ExprNodeTest_OR(pExpr, pNode);
  175293. break;
  175294. }
  175295. default: assert( pNode->eType==FTS5_NOT ); {
  175296. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  175297. break;
  175298. }
  175299. }
  175300. }
  175301. return rc;
  175302. }
  175303. /*
  175304. ** Set node pNode, which is part of expression pExpr, to point to the first
  175305. ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
  175306. **
  175307. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  175308. ** It is not an error if there are no matches.
  175309. */
  175310. static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
  175311. int rc = SQLITE_OK;
  175312. pNode->bEof = 0;
  175313. pNode->bNomatch = 0;
  175314. if( Fts5NodeIsString(pNode) ){
  175315. /* Initialize all term iterators in the NEAR object. */
  175316. rc = fts5ExprNearInitAll(pExpr, pNode);
  175317. }else if( pNode->xNext==0 ){
  175318. pNode->bEof = 1;
  175319. }else{
  175320. int i;
  175321. int nEof = 0;
  175322. for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
  175323. Fts5ExprNode *pChild = pNode->apChild[i];
  175324. rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
  175325. assert( pChild->bEof==0 || pChild->bEof==1 );
  175326. nEof += pChild->bEof;
  175327. }
  175328. pNode->iRowid = pNode->apChild[0]->iRowid;
  175329. switch( pNode->eType ){
  175330. case FTS5_AND:
  175331. if( nEof>0 ) fts5ExprSetEof(pNode);
  175332. break;
  175333. case FTS5_OR:
  175334. if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
  175335. break;
  175336. default:
  175337. assert( pNode->eType==FTS5_NOT );
  175338. pNode->bEof = pNode->apChild[0]->bEof;
  175339. break;
  175340. }
  175341. }
  175342. if( rc==SQLITE_OK ){
  175343. rc = fts5ExprNodeTest(pExpr, pNode);
  175344. }
  175345. return rc;
  175346. }
  175347. /*
  175348. ** Begin iterating through the set of documents in index pIdx matched by
  175349. ** the MATCH expression passed as the first argument. If the "bDesc"
  175350. ** parameter is passed a non-zero value, iteration is in descending rowid
  175351. ** order. Or, if it is zero, in ascending order.
  175352. **
  175353. ** If iterating in ascending rowid order (bDesc==0), the first document
  175354. ** visited is that with the smallest rowid that is larger than or equal
  175355. ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
  175356. ** then the first document visited must have a rowid smaller than or
  175357. ** equal to iFirst.
  175358. **
  175359. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  175360. ** is not considered an error if the query does not match any documents.
  175361. */
  175362. static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
  175363. Fts5ExprNode *pRoot = p->pRoot;
  175364. int rc; /* Return code */
  175365. p->pIndex = pIdx;
  175366. p->bDesc = bDesc;
  175367. rc = fts5ExprNodeFirst(p, pRoot);
  175368. /* If not at EOF but the current rowid occurs earlier than iFirst in
  175369. ** the iteration order, move to document iFirst or later. */
  175370. if( rc==SQLITE_OK
  175371. && 0==pRoot->bEof
  175372. && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0
  175373. ){
  175374. rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
  175375. }
  175376. /* If the iterator is not at a real match, skip forward until it is. */
  175377. while( pRoot->bNomatch ){
  175378. assert( pRoot->bEof==0 && rc==SQLITE_OK );
  175379. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  175380. }
  175381. return rc;
  175382. }
  175383. /*
  175384. ** Move to the next document
  175385. **
  175386. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  175387. ** is not considered an error if the query does not match any documents.
  175388. */
  175389. static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
  175390. int rc;
  175391. Fts5ExprNode *pRoot = p->pRoot;
  175392. assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
  175393. do {
  175394. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  175395. assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
  175396. }while( pRoot->bNomatch );
  175397. if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
  175398. pRoot->bEof = 1;
  175399. }
  175400. return rc;
  175401. }
  175402. static int sqlite3Fts5ExprEof(Fts5Expr *p){
  175403. return p->pRoot->bEof;
  175404. }
  175405. static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
  175406. return p->pRoot->iRowid;
  175407. }
  175408. static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
  175409. int rc = SQLITE_OK;
  175410. *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
  175411. return rc;
  175412. }
  175413. /*
  175414. ** Free the phrase object passed as the only argument.
  175415. */
  175416. static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
  175417. if( pPhrase ){
  175418. int i;
  175419. for(i=0; i<pPhrase->nTerm; i++){
  175420. Fts5ExprTerm *pSyn;
  175421. Fts5ExprTerm *pNext;
  175422. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  175423. sqlite3_free(pTerm->zTerm);
  175424. sqlite3Fts5IterClose(pTerm->pIter);
  175425. for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
  175426. pNext = pSyn->pSynonym;
  175427. sqlite3Fts5IterClose(pSyn->pIter);
  175428. fts5BufferFree((Fts5Buffer*)&pSyn[1]);
  175429. sqlite3_free(pSyn);
  175430. }
  175431. }
  175432. if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
  175433. sqlite3_free(pPhrase);
  175434. }
  175435. }
  175436. /*
  175437. ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
  175438. ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
  175439. ** appended to it and the results returned.
  175440. **
  175441. ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
  175442. ** NULL returned.
  175443. */
  175444. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  175445. Fts5Parse *pParse, /* Parse context */
  175446. Fts5ExprNearset *pNear, /* Existing nearset, or NULL */
  175447. Fts5ExprPhrase *pPhrase /* Recently parsed phrase */
  175448. ){
  175449. const int SZALLOC = 8;
  175450. Fts5ExprNearset *pRet = 0;
  175451. if( pParse->rc==SQLITE_OK ){
  175452. if( pPhrase==0 ){
  175453. return pNear;
  175454. }
  175455. if( pNear==0 ){
  175456. int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
  175457. pRet = sqlite3_malloc(nByte);
  175458. if( pRet==0 ){
  175459. pParse->rc = SQLITE_NOMEM;
  175460. }else{
  175461. memset(pRet, 0, nByte);
  175462. }
  175463. }else if( (pNear->nPhrase % SZALLOC)==0 ){
  175464. int nNew = pNear->nPhrase + SZALLOC;
  175465. int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
  175466. pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
  175467. if( pRet==0 ){
  175468. pParse->rc = SQLITE_NOMEM;
  175469. }
  175470. }else{
  175471. pRet = pNear;
  175472. }
  175473. }
  175474. if( pRet==0 ){
  175475. assert( pParse->rc!=SQLITE_OK );
  175476. sqlite3Fts5ParseNearsetFree(pNear);
  175477. sqlite3Fts5ParsePhraseFree(pPhrase);
  175478. }else{
  175479. if( pRet->nPhrase>0 ){
  175480. Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
  175481. assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
  175482. if( pPhrase->nTerm==0 ){
  175483. fts5ExprPhraseFree(pPhrase);
  175484. pRet->nPhrase--;
  175485. pParse->nPhrase--;
  175486. pPhrase = pLast;
  175487. }else if( pLast->nTerm==0 ){
  175488. fts5ExprPhraseFree(pLast);
  175489. pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
  175490. pParse->nPhrase--;
  175491. pRet->nPhrase--;
  175492. }
  175493. }
  175494. pRet->apPhrase[pRet->nPhrase++] = pPhrase;
  175495. }
  175496. return pRet;
  175497. }
  175498. typedef struct TokenCtx TokenCtx;
  175499. struct TokenCtx {
  175500. Fts5ExprPhrase *pPhrase;
  175501. int rc;
  175502. };
  175503. /*
  175504. ** Callback for tokenizing terms used by ParseTerm().
  175505. */
  175506. static int fts5ParseTokenize(
  175507. void *pContext, /* Pointer to Fts5InsertCtx object */
  175508. int tflags, /* Mask of FTS5_TOKEN_* flags */
  175509. const char *pToken, /* Buffer containing token */
  175510. int nToken, /* Size of token in bytes */
  175511. int iUnused1, /* Start offset of token */
  175512. int iUnused2 /* End offset of token */
  175513. ){
  175514. int rc = SQLITE_OK;
  175515. const int SZALLOC = 8;
  175516. TokenCtx *pCtx = (TokenCtx*)pContext;
  175517. Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
  175518. UNUSED_PARAM2(iUnused1, iUnused2);
  175519. /* If an error has already occurred, this is a no-op */
  175520. if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
  175521. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  175522. if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
  175523. Fts5ExprTerm *pSyn;
  175524. int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
  175525. pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
  175526. if( pSyn==0 ){
  175527. rc = SQLITE_NOMEM;
  175528. }else{
  175529. memset(pSyn, 0, nByte);
  175530. pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
  175531. memcpy(pSyn->zTerm, pToken, nToken);
  175532. pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
  175533. pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
  175534. }
  175535. }else{
  175536. Fts5ExprTerm *pTerm;
  175537. if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
  175538. Fts5ExprPhrase *pNew;
  175539. int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
  175540. pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
  175541. sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
  175542. );
  175543. if( pNew==0 ){
  175544. rc = SQLITE_NOMEM;
  175545. }else{
  175546. if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
  175547. pCtx->pPhrase = pPhrase = pNew;
  175548. pNew->nTerm = nNew - SZALLOC;
  175549. }
  175550. }
  175551. if( rc==SQLITE_OK ){
  175552. pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
  175553. memset(pTerm, 0, sizeof(Fts5ExprTerm));
  175554. pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
  175555. }
  175556. }
  175557. pCtx->rc = rc;
  175558. return rc;
  175559. }
  175560. /*
  175561. ** Free the phrase object passed as the only argument.
  175562. */
  175563. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
  175564. fts5ExprPhraseFree(pPhrase);
  175565. }
  175566. /*
  175567. ** Free the phrase object passed as the second argument.
  175568. */
  175569. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
  175570. if( pNear ){
  175571. int i;
  175572. for(i=0; i<pNear->nPhrase; i++){
  175573. fts5ExprPhraseFree(pNear->apPhrase[i]);
  175574. }
  175575. sqlite3_free(pNear->pColset);
  175576. sqlite3_free(pNear);
  175577. }
  175578. }
  175579. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
  175580. assert( pParse->pExpr==0 );
  175581. pParse->pExpr = p;
  175582. }
  175583. /*
  175584. ** This function is called by the parser to process a string token. The
  175585. ** string may or may not be quoted. In any case it is tokenized and a
  175586. ** phrase object consisting of all tokens returned.
  175587. */
  175588. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  175589. Fts5Parse *pParse, /* Parse context */
  175590. Fts5ExprPhrase *pAppend, /* Phrase to append to */
  175591. Fts5Token *pToken, /* String to tokenize */
  175592. int bPrefix /* True if there is a trailing "*" */
  175593. ){
  175594. Fts5Config *pConfig = pParse->pConfig;
  175595. TokenCtx sCtx; /* Context object passed to callback */
  175596. int rc; /* Tokenize return code */
  175597. char *z = 0;
  175598. memset(&sCtx, 0, sizeof(TokenCtx));
  175599. sCtx.pPhrase = pAppend;
  175600. rc = fts5ParseStringFromToken(pToken, &z);
  175601. if( rc==SQLITE_OK ){
  175602. int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);
  175603. int n;
  175604. sqlite3Fts5Dequote(z);
  175605. n = (int)strlen(z);
  175606. rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
  175607. }
  175608. sqlite3_free(z);
  175609. if( rc || (rc = sCtx.rc) ){
  175610. pParse->rc = rc;
  175611. fts5ExprPhraseFree(sCtx.pPhrase);
  175612. sCtx.pPhrase = 0;
  175613. }else{
  175614. if( pAppend==0 ){
  175615. if( (pParse->nPhrase % 8)==0 ){
  175616. int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
  175617. Fts5ExprPhrase **apNew;
  175618. apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
  175619. if( apNew==0 ){
  175620. pParse->rc = SQLITE_NOMEM;
  175621. fts5ExprPhraseFree(sCtx.pPhrase);
  175622. return 0;
  175623. }
  175624. pParse->apPhrase = apNew;
  175625. }
  175626. pParse->nPhrase++;
  175627. }
  175628. if( sCtx.pPhrase==0 ){
  175629. /* This happens when parsing a token or quoted phrase that contains
  175630. ** no token characters at all. (e.g ... MATCH '""'). */
  175631. sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
  175632. }else if( sCtx.pPhrase->nTerm ){
  175633. sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
  175634. }
  175635. pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
  175636. }
  175637. return sCtx.pPhrase;
  175638. }
  175639. /*
  175640. ** Create a new FTS5 expression by cloning phrase iPhrase of the
  175641. ** expression passed as the second argument.
  175642. */
  175643. static int sqlite3Fts5ExprClonePhrase(
  175644. Fts5Expr *pExpr,
  175645. int iPhrase,
  175646. Fts5Expr **ppNew
  175647. ){
  175648. int rc = SQLITE_OK; /* Return code */
  175649. Fts5ExprPhrase *pOrig; /* The phrase extracted from pExpr */
  175650. Fts5Expr *pNew = 0; /* Expression to return via *ppNew */
  175651. TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */
  175652. pOrig = pExpr->apExprPhrase[iPhrase];
  175653. pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
  175654. if( rc==SQLITE_OK ){
  175655. pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
  175656. sizeof(Fts5ExprPhrase*));
  175657. }
  175658. if( rc==SQLITE_OK ){
  175659. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
  175660. sizeof(Fts5ExprNode));
  175661. }
  175662. if( rc==SQLITE_OK ){
  175663. pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
  175664. sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
  175665. }
  175666. if( rc==SQLITE_OK ){
  175667. Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
  175668. if( pColsetOrig ){
  175669. int nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
  175670. Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
  175671. if( pColset ){
  175672. memcpy(pColset, pColsetOrig, nByte);
  175673. }
  175674. pNew->pRoot->pNear->pColset = pColset;
  175675. }
  175676. }
  175677. if( pOrig->nTerm ){
  175678. int i; /* Used to iterate through phrase terms */
  175679. for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
  175680. int tflags = 0;
  175681. Fts5ExprTerm *p;
  175682. for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
  175683. const char *zTerm = p->zTerm;
  175684. rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
  175685. 0, 0);
  175686. tflags = FTS5_TOKEN_COLOCATED;
  175687. }
  175688. if( rc==SQLITE_OK ){
  175689. sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
  175690. }
  175691. }
  175692. }else{
  175693. /* This happens when parsing a token or quoted phrase that contains
  175694. ** no token characters at all. (e.g ... MATCH '""'). */
  175695. sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
  175696. }
  175697. if( rc==SQLITE_OK ){
  175698. /* All the allocations succeeded. Put the expression object together. */
  175699. pNew->pIndex = pExpr->pIndex;
  175700. pNew->pConfig = pExpr->pConfig;
  175701. pNew->nPhrase = 1;
  175702. pNew->apExprPhrase[0] = sCtx.pPhrase;
  175703. pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
  175704. pNew->pRoot->pNear->nPhrase = 1;
  175705. sCtx.pPhrase->pNode = pNew->pRoot;
  175706. if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){
  175707. pNew->pRoot->eType = FTS5_TERM;
  175708. pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
  175709. }else{
  175710. pNew->pRoot->eType = FTS5_STRING;
  175711. pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
  175712. }
  175713. }else{
  175714. sqlite3Fts5ExprFree(pNew);
  175715. fts5ExprPhraseFree(sCtx.pPhrase);
  175716. pNew = 0;
  175717. }
  175718. *ppNew = pNew;
  175719. return rc;
  175720. }
  175721. /*
  175722. ** Token pTok has appeared in a MATCH expression where the NEAR operator
  175723. ** is expected. If token pTok does not contain "NEAR", store an error
  175724. ** in the pParse object.
  175725. */
  175726. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
  175727. if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
  175728. sqlite3Fts5ParseError(
  175729. pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
  175730. );
  175731. }
  175732. }
  175733. static void sqlite3Fts5ParseSetDistance(
  175734. Fts5Parse *pParse,
  175735. Fts5ExprNearset *pNear,
  175736. Fts5Token *p
  175737. ){
  175738. if( pNear ){
  175739. int nNear = 0;
  175740. int i;
  175741. if( p->n ){
  175742. for(i=0; i<p->n; i++){
  175743. char c = (char)p->p[i];
  175744. if( c<'0' || c>'9' ){
  175745. sqlite3Fts5ParseError(
  175746. pParse, "expected integer, got \"%.*s\"", p->n, p->p
  175747. );
  175748. return;
  175749. }
  175750. nNear = nNear * 10 + (p->p[i] - '0');
  175751. }
  175752. }else{
  175753. nNear = FTS5_DEFAULT_NEARDIST;
  175754. }
  175755. pNear->nNear = nNear;
  175756. }
  175757. }
  175758. /*
  175759. ** The second argument passed to this function may be NULL, or it may be
  175760. ** an existing Fts5Colset object. This function returns a pointer to
  175761. ** a new colset object containing the contents of (p) with new value column
  175762. ** number iCol appended.
  175763. **
  175764. ** If an OOM error occurs, store an error code in pParse and return NULL.
  175765. ** The old colset object (if any) is not freed in this case.
  175766. */
  175767. static Fts5Colset *fts5ParseColset(
  175768. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  175769. Fts5Colset *p, /* Existing colset object */
  175770. int iCol /* New column to add to colset object */
  175771. ){
  175772. int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */
  175773. Fts5Colset *pNew; /* New colset object to return */
  175774. assert( pParse->rc==SQLITE_OK );
  175775. assert( iCol>=0 && iCol<pParse->pConfig->nCol );
  175776. pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
  175777. if( pNew==0 ){
  175778. pParse->rc = SQLITE_NOMEM;
  175779. }else{
  175780. int *aiCol = pNew->aiCol;
  175781. int i, j;
  175782. for(i=0; i<nCol; i++){
  175783. if( aiCol[i]==iCol ) return pNew;
  175784. if( aiCol[i]>iCol ) break;
  175785. }
  175786. for(j=nCol; j>i; j--){
  175787. aiCol[j] = aiCol[j-1];
  175788. }
  175789. aiCol[i] = iCol;
  175790. pNew->nCol = nCol+1;
  175791. #ifndef NDEBUG
  175792. /* Check that the array is in order and contains no duplicate entries. */
  175793. for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
  175794. #endif
  175795. }
  175796. return pNew;
  175797. }
  175798. /*
  175799. ** Allocate and return an Fts5Colset object specifying the inverse of
  175800. ** the colset passed as the second argument. Free the colset passed
  175801. ** as the second argument before returning.
  175802. */
  175803. static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
  175804. Fts5Colset *pRet;
  175805. int nCol = pParse->pConfig->nCol;
  175806. pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
  175807. sizeof(Fts5Colset) + sizeof(int)*nCol
  175808. );
  175809. if( pRet ){
  175810. int i;
  175811. int iOld = 0;
  175812. for(i=0; i<nCol; i++){
  175813. if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
  175814. pRet->aiCol[pRet->nCol++] = i;
  175815. }else{
  175816. iOld++;
  175817. }
  175818. }
  175819. }
  175820. sqlite3_free(p);
  175821. return pRet;
  175822. }
  175823. static Fts5Colset *sqlite3Fts5ParseColset(
  175824. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  175825. Fts5Colset *pColset, /* Existing colset object */
  175826. Fts5Token *p
  175827. ){
  175828. Fts5Colset *pRet = 0;
  175829. int iCol;
  175830. char *z; /* Dequoted copy of token p */
  175831. z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
  175832. if( pParse->rc==SQLITE_OK ){
  175833. Fts5Config *pConfig = pParse->pConfig;
  175834. sqlite3Fts5Dequote(z);
  175835. for(iCol=0; iCol<pConfig->nCol; iCol++){
  175836. if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
  175837. }
  175838. if( iCol==pConfig->nCol ){
  175839. sqlite3Fts5ParseError(pParse, "no such column: %s", z);
  175840. }else{
  175841. pRet = fts5ParseColset(pParse, pColset, iCol);
  175842. }
  175843. sqlite3_free(z);
  175844. }
  175845. if( pRet==0 ){
  175846. assert( pParse->rc!=SQLITE_OK );
  175847. sqlite3_free(pColset);
  175848. }
  175849. return pRet;
  175850. }
  175851. /*
  175852. ** If argument pOrig is NULL, or if (*pRc) is set to anything other than
  175853. ** SQLITE_OK when this function is called, NULL is returned.
  175854. **
  175855. ** Otherwise, a copy of (*pOrig) is made into memory obtained from
  175856. ** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
  175857. ** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.
  175858. */
  175859. static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){
  175860. Fts5Colset *pRet;
  175861. if( pOrig ){
  175862. int nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);
  175863. pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);
  175864. if( pRet ){
  175865. memcpy(pRet, pOrig, nByte);
  175866. }
  175867. }else{
  175868. pRet = 0;
  175869. }
  175870. return pRet;
  175871. }
  175872. /*
  175873. ** Remove from colset pColset any columns that are not also in colset pMerge.
  175874. */
  175875. static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){
  175876. int iIn = 0; /* Next input in pColset */
  175877. int iMerge = 0; /* Next input in pMerge */
  175878. int iOut = 0; /* Next output slot in pColset */
  175879. while( iIn<pColset->nCol && iMerge<pMerge->nCol ){
  175880. int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge];
  175881. if( iDiff==0 ){
  175882. pColset->aiCol[iOut++] = pMerge->aiCol[iMerge];
  175883. iMerge++;
  175884. iIn++;
  175885. }else if( iDiff>0 ){
  175886. iMerge++;
  175887. }else{
  175888. iIn++;
  175889. }
  175890. }
  175891. pColset->nCol = iOut;
  175892. }
  175893. /*
  175894. ** Recursively apply colset pColset to expression node pNode and all of
  175895. ** its decendents. If (*ppFree) is not NULL, it contains a spare copy
  175896. ** of pColset. This function may use the spare copy and set (*ppFree) to
  175897. ** zero, or it may create copies of pColset using fts5CloneColset().
  175898. */
  175899. static void fts5ParseSetColset(
  175900. Fts5Parse *pParse,
  175901. Fts5ExprNode *pNode,
  175902. Fts5Colset *pColset,
  175903. Fts5Colset **ppFree
  175904. ){
  175905. if( pParse->rc==SQLITE_OK ){
  175906. assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING
  175907. || pNode->eType==FTS5_AND || pNode->eType==FTS5_OR
  175908. || pNode->eType==FTS5_NOT || pNode->eType==FTS5_EOF
  175909. );
  175910. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  175911. Fts5ExprNearset *pNear = pNode->pNear;
  175912. if( pNear->pColset ){
  175913. fts5MergeColset(pNear->pColset, pColset);
  175914. if( pNear->pColset->nCol==0 ){
  175915. pNode->eType = FTS5_EOF;
  175916. pNode->xNext = 0;
  175917. }
  175918. }else if( *ppFree ){
  175919. pNear->pColset = pColset;
  175920. *ppFree = 0;
  175921. }else{
  175922. pNear->pColset = fts5CloneColset(&pParse->rc, pColset);
  175923. }
  175924. }else{
  175925. int i;
  175926. assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 );
  175927. for(i=0; i<pNode->nChild; i++){
  175928. fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree);
  175929. }
  175930. }
  175931. }
  175932. }
  175933. /*
  175934. ** Apply colset pColset to expression node pExpr and all of its descendents.
  175935. */
  175936. static void sqlite3Fts5ParseSetColset(
  175937. Fts5Parse *pParse,
  175938. Fts5ExprNode *pExpr,
  175939. Fts5Colset *pColset
  175940. ){
  175941. Fts5Colset *pFree = pColset;
  175942. if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
  175943. pParse->rc = SQLITE_ERROR;
  175944. pParse->zErr = sqlite3_mprintf(
  175945. "fts5: column queries are not supported (detail=none)"
  175946. );
  175947. }else{
  175948. fts5ParseSetColset(pParse, pExpr, pColset, &pFree);
  175949. }
  175950. sqlite3_free(pFree);
  175951. }
  175952. static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
  175953. switch( pNode->eType ){
  175954. case FTS5_STRING: {
  175955. Fts5ExprNearset *pNear = pNode->pNear;
  175956. if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
  175957. && pNear->apPhrase[0]->aTerm[0].pSynonym==0
  175958. ){
  175959. pNode->eType = FTS5_TERM;
  175960. pNode->xNext = fts5ExprNodeNext_TERM;
  175961. }else{
  175962. pNode->xNext = fts5ExprNodeNext_STRING;
  175963. }
  175964. break;
  175965. };
  175966. case FTS5_OR: {
  175967. pNode->xNext = fts5ExprNodeNext_OR;
  175968. break;
  175969. };
  175970. case FTS5_AND: {
  175971. pNode->xNext = fts5ExprNodeNext_AND;
  175972. break;
  175973. };
  175974. default: assert( pNode->eType==FTS5_NOT ); {
  175975. pNode->xNext = fts5ExprNodeNext_NOT;
  175976. break;
  175977. };
  175978. }
  175979. }
  175980. static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
  175981. if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
  175982. int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
  175983. memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
  175984. p->nChild += pSub->nChild;
  175985. sqlite3_free(pSub);
  175986. }else{
  175987. p->apChild[p->nChild++] = pSub;
  175988. }
  175989. }
  175990. /*
  175991. ** Allocate and return a new expression object. If anything goes wrong (i.e.
  175992. ** OOM error), leave an error code in pParse and return NULL.
  175993. */
  175994. static Fts5ExprNode *sqlite3Fts5ParseNode(
  175995. Fts5Parse *pParse, /* Parse context */
  175996. int eType, /* FTS5_STRING, AND, OR or NOT */
  175997. Fts5ExprNode *pLeft, /* Left hand child expression */
  175998. Fts5ExprNode *pRight, /* Right hand child expression */
  175999. Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */
  176000. ){
  176001. Fts5ExprNode *pRet = 0;
  176002. if( pParse->rc==SQLITE_OK ){
  176003. int nChild = 0; /* Number of children of returned node */
  176004. int nByte; /* Bytes of space to allocate for this node */
  176005. assert( (eType!=FTS5_STRING && !pNear)
  176006. || (eType==FTS5_STRING && !pLeft && !pRight)
  176007. );
  176008. if( eType==FTS5_STRING && pNear==0 ) return 0;
  176009. if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
  176010. if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
  176011. if( eType==FTS5_NOT ){
  176012. nChild = 2;
  176013. }else if( eType==FTS5_AND || eType==FTS5_OR ){
  176014. nChild = 2;
  176015. if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
  176016. if( pRight->eType==eType ) nChild += pRight->nChild-1;
  176017. }
  176018. nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
  176019. pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
  176020. if( pRet ){
  176021. pRet->eType = eType;
  176022. pRet->pNear = pNear;
  176023. fts5ExprAssignXNext(pRet);
  176024. if( eType==FTS5_STRING ){
  176025. int iPhrase;
  176026. for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
  176027. pNear->apPhrase[iPhrase]->pNode = pRet;
  176028. if( pNear->apPhrase[iPhrase]->nTerm==0 ){
  176029. pRet->xNext = 0;
  176030. pRet->eType = FTS5_EOF;
  176031. }
  176032. }
  176033. if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL
  176034. && (pNear->nPhrase!=1 || pNear->apPhrase[0]->nTerm>1)
  176035. ){
  176036. assert( pParse->rc==SQLITE_OK );
  176037. pParse->rc = SQLITE_ERROR;
  176038. assert( pParse->zErr==0 );
  176039. pParse->zErr = sqlite3_mprintf(
  176040. "fts5: %s queries are not supported (detail!=full)",
  176041. pNear->nPhrase==1 ? "phrase": "NEAR"
  176042. );
  176043. sqlite3_free(pRet);
  176044. pRet = 0;
  176045. }
  176046. }else{
  176047. fts5ExprAddChildren(pRet, pLeft);
  176048. fts5ExprAddChildren(pRet, pRight);
  176049. }
  176050. }
  176051. }
  176052. if( pRet==0 ){
  176053. assert( pParse->rc!=SQLITE_OK );
  176054. sqlite3Fts5ParseNodeFree(pLeft);
  176055. sqlite3Fts5ParseNodeFree(pRight);
  176056. sqlite3Fts5ParseNearsetFree(pNear);
  176057. }
  176058. return pRet;
  176059. }
  176060. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  176061. Fts5Parse *pParse, /* Parse context */
  176062. Fts5ExprNode *pLeft, /* Left hand child expression */
  176063. Fts5ExprNode *pRight /* Right hand child expression */
  176064. ){
  176065. Fts5ExprNode *pRet = 0;
  176066. Fts5ExprNode *pPrev;
  176067. if( pParse->rc ){
  176068. sqlite3Fts5ParseNodeFree(pLeft);
  176069. sqlite3Fts5ParseNodeFree(pRight);
  176070. }else{
  176071. assert( pLeft->eType==FTS5_STRING
  176072. || pLeft->eType==FTS5_TERM
  176073. || pLeft->eType==FTS5_EOF
  176074. || pLeft->eType==FTS5_AND
  176075. );
  176076. assert( pRight->eType==FTS5_STRING
  176077. || pRight->eType==FTS5_TERM
  176078. || pRight->eType==FTS5_EOF
  176079. );
  176080. if( pLeft->eType==FTS5_AND ){
  176081. pPrev = pLeft->apChild[pLeft->nChild-1];
  176082. }else{
  176083. pPrev = pLeft;
  176084. }
  176085. assert( pPrev->eType==FTS5_STRING
  176086. || pPrev->eType==FTS5_TERM
  176087. || pPrev->eType==FTS5_EOF
  176088. );
  176089. if( pRight->eType==FTS5_EOF ){
  176090. assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
  176091. sqlite3Fts5ParseNodeFree(pRight);
  176092. pRet = pLeft;
  176093. pParse->nPhrase--;
  176094. }
  176095. else if( pPrev->eType==FTS5_EOF ){
  176096. Fts5ExprPhrase **ap;
  176097. if( pPrev==pLeft ){
  176098. pRet = pRight;
  176099. }else{
  176100. pLeft->apChild[pLeft->nChild-1] = pRight;
  176101. pRet = pLeft;
  176102. }
  176103. ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
  176104. assert( ap[0]==pPrev->pNear->apPhrase[0] );
  176105. memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
  176106. pParse->nPhrase--;
  176107. sqlite3Fts5ParseNodeFree(pPrev);
  176108. }
  176109. else{
  176110. pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
  176111. }
  176112. }
  176113. return pRet;
  176114. }
  176115. static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
  176116. int nByte = 0;
  176117. Fts5ExprTerm *p;
  176118. char *zQuoted;
  176119. /* Determine the maximum amount of space required. */
  176120. for(p=pTerm; p; p=p->pSynonym){
  176121. nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
  176122. }
  176123. zQuoted = sqlite3_malloc(nByte);
  176124. if( zQuoted ){
  176125. int i = 0;
  176126. for(p=pTerm; p; p=p->pSynonym){
  176127. char *zIn = p->zTerm;
  176128. zQuoted[i++] = '"';
  176129. while( *zIn ){
  176130. if( *zIn=='"' ) zQuoted[i++] = '"';
  176131. zQuoted[i++] = *zIn++;
  176132. }
  176133. zQuoted[i++] = '"';
  176134. if( p->pSynonym ) zQuoted[i++] = '|';
  176135. }
  176136. if( pTerm->bPrefix ){
  176137. zQuoted[i++] = ' ';
  176138. zQuoted[i++] = '*';
  176139. }
  176140. zQuoted[i++] = '\0';
  176141. }
  176142. return zQuoted;
  176143. }
  176144. static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
  176145. char *zNew;
  176146. va_list ap;
  176147. va_start(ap, zFmt);
  176148. zNew = sqlite3_vmprintf(zFmt, ap);
  176149. va_end(ap);
  176150. if( zApp && zNew ){
  176151. char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
  176152. sqlite3_free(zNew);
  176153. zNew = zNew2;
  176154. }
  176155. sqlite3_free(zApp);
  176156. return zNew;
  176157. }
  176158. /*
  176159. ** Compose a tcl-readable representation of expression pExpr. Return a
  176160. ** pointer to a buffer containing that representation. It is the
  176161. ** responsibility of the caller to at some point free the buffer using
  176162. ** sqlite3_free().
  176163. */
  176164. static char *fts5ExprPrintTcl(
  176165. Fts5Config *pConfig,
  176166. const char *zNearsetCmd,
  176167. Fts5ExprNode *pExpr
  176168. ){
  176169. char *zRet = 0;
  176170. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  176171. Fts5ExprNearset *pNear = pExpr->pNear;
  176172. int i;
  176173. int iTerm;
  176174. zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
  176175. if( zRet==0 ) return 0;
  176176. if( pNear->pColset ){
  176177. int *aiCol = pNear->pColset->aiCol;
  176178. int nCol = pNear->pColset->nCol;
  176179. if( nCol==1 ){
  176180. zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
  176181. }else{
  176182. zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
  176183. for(i=1; i<pNear->pColset->nCol; i++){
  176184. zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
  176185. }
  176186. zRet = fts5PrintfAppend(zRet, "} ");
  176187. }
  176188. if( zRet==0 ) return 0;
  176189. }
  176190. if( pNear->nPhrase>1 ){
  176191. zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
  176192. if( zRet==0 ) return 0;
  176193. }
  176194. zRet = fts5PrintfAppend(zRet, "--");
  176195. if( zRet==0 ) return 0;
  176196. for(i=0; i<pNear->nPhrase; i++){
  176197. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  176198. zRet = fts5PrintfAppend(zRet, " {");
  176199. for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
  176200. char *zTerm = pPhrase->aTerm[iTerm].zTerm;
  176201. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
  176202. if( pPhrase->aTerm[iTerm].bPrefix ){
  176203. zRet = fts5PrintfAppend(zRet, "*");
  176204. }
  176205. }
  176206. if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
  176207. if( zRet==0 ) return 0;
  176208. }
  176209. }else{
  176210. char const *zOp = 0;
  176211. int i;
  176212. switch( pExpr->eType ){
  176213. case FTS5_AND: zOp = "AND"; break;
  176214. case FTS5_NOT: zOp = "NOT"; break;
  176215. default:
  176216. assert( pExpr->eType==FTS5_OR );
  176217. zOp = "OR";
  176218. break;
  176219. }
  176220. zRet = sqlite3_mprintf("%s", zOp);
  176221. for(i=0; zRet && i<pExpr->nChild; i++){
  176222. char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
  176223. if( !z ){
  176224. sqlite3_free(zRet);
  176225. zRet = 0;
  176226. }else{
  176227. zRet = fts5PrintfAppend(zRet, " [%z]", z);
  176228. }
  176229. }
  176230. }
  176231. return zRet;
  176232. }
  176233. static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
  176234. char *zRet = 0;
  176235. if( pExpr->eType==0 ){
  176236. return sqlite3_mprintf("\"\"");
  176237. }else
  176238. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  176239. Fts5ExprNearset *pNear = pExpr->pNear;
  176240. int i;
  176241. int iTerm;
  176242. if( pNear->pColset ){
  176243. int iCol = pNear->pColset->aiCol[0];
  176244. zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
  176245. if( zRet==0 ) return 0;
  176246. }
  176247. if( pNear->nPhrase>1 ){
  176248. zRet = fts5PrintfAppend(zRet, "NEAR(");
  176249. if( zRet==0 ) return 0;
  176250. }
  176251. for(i=0; i<pNear->nPhrase; i++){
  176252. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  176253. if( i!=0 ){
  176254. zRet = fts5PrintfAppend(zRet, " ");
  176255. if( zRet==0 ) return 0;
  176256. }
  176257. for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
  176258. char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
  176259. if( zTerm ){
  176260. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
  176261. sqlite3_free(zTerm);
  176262. }
  176263. if( zTerm==0 || zRet==0 ){
  176264. sqlite3_free(zRet);
  176265. return 0;
  176266. }
  176267. }
  176268. }
  176269. if( pNear->nPhrase>1 ){
  176270. zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
  176271. if( zRet==0 ) return 0;
  176272. }
  176273. }else{
  176274. char const *zOp = 0;
  176275. int i;
  176276. switch( pExpr->eType ){
  176277. case FTS5_AND: zOp = " AND "; break;
  176278. case FTS5_NOT: zOp = " NOT "; break;
  176279. default:
  176280. assert( pExpr->eType==FTS5_OR );
  176281. zOp = " OR ";
  176282. break;
  176283. }
  176284. for(i=0; i<pExpr->nChild; i++){
  176285. char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
  176286. if( z==0 ){
  176287. sqlite3_free(zRet);
  176288. zRet = 0;
  176289. }else{
  176290. int e = pExpr->apChild[i]->eType;
  176291. int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
  176292. zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
  176293. (i==0 ? "" : zOp),
  176294. (b?"(":""), z, (b?")":"")
  176295. );
  176296. }
  176297. if( zRet==0 ) break;
  176298. }
  176299. }
  176300. return zRet;
  176301. }
  176302. /*
  176303. ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
  176304. ** and fts5_expr_tcl() (bTcl!=0).
  176305. */
  176306. static void fts5ExprFunction(
  176307. sqlite3_context *pCtx, /* Function call context */
  176308. int nArg, /* Number of args */
  176309. sqlite3_value **apVal, /* Function arguments */
  176310. int bTcl
  176311. ){
  176312. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  176313. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  176314. const char *zExpr = 0;
  176315. char *zErr = 0;
  176316. Fts5Expr *pExpr = 0;
  176317. int rc;
  176318. int i;
  176319. const char **azConfig; /* Array of arguments for Fts5Config */
  176320. const char *zNearsetCmd = "nearset";
  176321. int nConfig; /* Size of azConfig[] */
  176322. Fts5Config *pConfig = 0;
  176323. int iArg = 1;
  176324. if( nArg<1 ){
  176325. zErr = sqlite3_mprintf("wrong number of arguments to function %s",
  176326. bTcl ? "fts5_expr_tcl" : "fts5_expr"
  176327. );
  176328. sqlite3_result_error(pCtx, zErr, -1);
  176329. sqlite3_free(zErr);
  176330. return;
  176331. }
  176332. if( bTcl && nArg>1 ){
  176333. zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
  176334. iArg = 2;
  176335. }
  176336. nConfig = 3 + (nArg-iArg);
  176337. azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
  176338. if( azConfig==0 ){
  176339. sqlite3_result_error_nomem(pCtx);
  176340. return;
  176341. }
  176342. azConfig[0] = 0;
  176343. azConfig[1] = "main";
  176344. azConfig[2] = "tbl";
  176345. for(i=3; iArg<nArg; iArg++){
  176346. azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
  176347. }
  176348. zExpr = (const char*)sqlite3_value_text(apVal[0]);
  176349. rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
  176350. if( rc==SQLITE_OK ){
  176351. rc = sqlite3Fts5ExprNew(pConfig, pConfig->nCol, zExpr, &pExpr, &zErr);
  176352. }
  176353. if( rc==SQLITE_OK ){
  176354. char *zText;
  176355. if( pExpr->pRoot->xNext==0 ){
  176356. zText = sqlite3_mprintf("");
  176357. }else if( bTcl ){
  176358. zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
  176359. }else{
  176360. zText = fts5ExprPrint(pConfig, pExpr->pRoot);
  176361. }
  176362. if( zText==0 ){
  176363. rc = SQLITE_NOMEM;
  176364. }else{
  176365. sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
  176366. sqlite3_free(zText);
  176367. }
  176368. }
  176369. if( rc!=SQLITE_OK ){
  176370. if( zErr ){
  176371. sqlite3_result_error(pCtx, zErr, -1);
  176372. sqlite3_free(zErr);
  176373. }else{
  176374. sqlite3_result_error_code(pCtx, rc);
  176375. }
  176376. }
  176377. sqlite3_free((void *)azConfig);
  176378. sqlite3Fts5ConfigFree(pConfig);
  176379. sqlite3Fts5ExprFree(pExpr);
  176380. }
  176381. static void fts5ExprFunctionHr(
  176382. sqlite3_context *pCtx, /* Function call context */
  176383. int nArg, /* Number of args */
  176384. sqlite3_value **apVal /* Function arguments */
  176385. ){
  176386. fts5ExprFunction(pCtx, nArg, apVal, 0);
  176387. }
  176388. static void fts5ExprFunctionTcl(
  176389. sqlite3_context *pCtx, /* Function call context */
  176390. int nArg, /* Number of args */
  176391. sqlite3_value **apVal /* Function arguments */
  176392. ){
  176393. fts5ExprFunction(pCtx, nArg, apVal, 1);
  176394. }
  176395. /*
  176396. ** The implementation of an SQLite user-defined-function that accepts a
  176397. ** single integer as an argument. If the integer is an alpha-numeric
  176398. ** unicode code point, 1 is returned. Otherwise 0.
  176399. */
  176400. static void fts5ExprIsAlnum(
  176401. sqlite3_context *pCtx, /* Function call context */
  176402. int nArg, /* Number of args */
  176403. sqlite3_value **apVal /* Function arguments */
  176404. ){
  176405. int iCode;
  176406. if( nArg!=1 ){
  176407. sqlite3_result_error(pCtx,
  176408. "wrong number of arguments to function fts5_isalnum", -1
  176409. );
  176410. return;
  176411. }
  176412. iCode = sqlite3_value_int(apVal[0]);
  176413. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
  176414. }
  176415. static void fts5ExprFold(
  176416. sqlite3_context *pCtx, /* Function call context */
  176417. int nArg, /* Number of args */
  176418. sqlite3_value **apVal /* Function arguments */
  176419. ){
  176420. if( nArg!=1 && nArg!=2 ){
  176421. sqlite3_result_error(pCtx,
  176422. "wrong number of arguments to function fts5_fold", -1
  176423. );
  176424. }else{
  176425. int iCode;
  176426. int bRemoveDiacritics = 0;
  176427. iCode = sqlite3_value_int(apVal[0]);
  176428. if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
  176429. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
  176430. }
  176431. }
  176432. /*
  176433. ** This is called during initialization to register the fts5_expr() scalar
  176434. ** UDF with the SQLite handle passed as the only argument.
  176435. */
  176436. static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
  176437. struct Fts5ExprFunc {
  176438. const char *z;
  176439. void (*x)(sqlite3_context*,int,sqlite3_value**);
  176440. } aFunc[] = {
  176441. { "fts5_expr", fts5ExprFunctionHr },
  176442. { "fts5_expr_tcl", fts5ExprFunctionTcl },
  176443. { "fts5_isalnum", fts5ExprIsAlnum },
  176444. { "fts5_fold", fts5ExprFold },
  176445. };
  176446. int i;
  176447. int rc = SQLITE_OK;
  176448. void *pCtx = (void*)pGlobal;
  176449. for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
  176450. struct Fts5ExprFunc *p = &aFunc[i];
  176451. rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
  176452. }
  176453. /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
  176454. #ifndef NDEBUG
  176455. (void)sqlite3Fts5ParserTrace;
  176456. #endif
  176457. return rc;
  176458. }
  176459. /*
  176460. ** Return the number of phrases in expression pExpr.
  176461. */
  176462. static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
  176463. return (pExpr ? pExpr->nPhrase : 0);
  176464. }
  176465. /*
  176466. ** Return the number of terms in the iPhrase'th phrase in pExpr.
  176467. */
  176468. static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
  176469. if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
  176470. return pExpr->apExprPhrase[iPhrase]->nTerm;
  176471. }
  176472. /*
  176473. ** This function is used to access the current position list for phrase
  176474. ** iPhrase.
  176475. */
  176476. static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
  176477. int nRet;
  176478. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  176479. Fts5ExprNode *pNode = pPhrase->pNode;
  176480. if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
  176481. *pa = pPhrase->poslist.p;
  176482. nRet = pPhrase->poslist.n;
  176483. }else{
  176484. *pa = 0;
  176485. nRet = 0;
  176486. }
  176487. return nRet;
  176488. }
  176489. struct Fts5PoslistPopulator {
  176490. Fts5PoslistWriter writer;
  176491. int bOk; /* True if ok to populate */
  176492. int bMiss;
  176493. };
  176494. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
  176495. Fts5PoslistPopulator *pRet;
  176496. pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  176497. if( pRet ){
  176498. int i;
  176499. memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  176500. for(i=0; i<pExpr->nPhrase; i++){
  176501. Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
  176502. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  176503. assert( pExpr->apExprPhrase[i]->nTerm==1 );
  176504. if( bLive &&
  176505. (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
  176506. ){
  176507. pRet[i].bMiss = 1;
  176508. }else{
  176509. pBuf->n = 0;
  176510. }
  176511. }
  176512. }
  176513. return pRet;
  176514. }
  176515. struct Fts5ExprCtx {
  176516. Fts5Expr *pExpr;
  176517. Fts5PoslistPopulator *aPopulator;
  176518. i64 iOff;
  176519. };
  176520. typedef struct Fts5ExprCtx Fts5ExprCtx;
  176521. /*
  176522. ** TODO: Make this more efficient!
  176523. */
  176524. static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
  176525. int i;
  176526. for(i=0; i<pColset->nCol; i++){
  176527. if( pColset->aiCol[i]==iCol ) return 1;
  176528. }
  176529. return 0;
  176530. }
  176531. static int fts5ExprPopulatePoslistsCb(
  176532. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  176533. int tflags, /* Mask of FTS5_TOKEN_* flags */
  176534. const char *pToken, /* Pointer to buffer containing token */
  176535. int nToken, /* Size of token in bytes */
  176536. int iUnused1, /* Byte offset of token within input text */
  176537. int iUnused2 /* Byte offset of end of token within input text */
  176538. ){
  176539. Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
  176540. Fts5Expr *pExpr = p->pExpr;
  176541. int i;
  176542. UNUSED_PARAM2(iUnused1, iUnused2);
  176543. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  176544. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
  176545. for(i=0; i<pExpr->nPhrase; i++){
  176546. Fts5ExprTerm *pTerm;
  176547. if( p->aPopulator[i].bOk==0 ) continue;
  176548. for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  176549. int nTerm = (int)strlen(pTerm->zTerm);
  176550. if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
  176551. && memcmp(pTerm->zTerm, pToken, nTerm)==0
  176552. ){
  176553. int rc = sqlite3Fts5PoslistWriterAppend(
  176554. &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
  176555. );
  176556. if( rc ) return rc;
  176557. break;
  176558. }
  176559. }
  176560. }
  176561. return SQLITE_OK;
  176562. }
  176563. static int sqlite3Fts5ExprPopulatePoslists(
  176564. Fts5Config *pConfig,
  176565. Fts5Expr *pExpr,
  176566. Fts5PoslistPopulator *aPopulator,
  176567. int iCol,
  176568. const char *z, int n
  176569. ){
  176570. int i;
  176571. Fts5ExprCtx sCtx;
  176572. sCtx.pExpr = pExpr;
  176573. sCtx.aPopulator = aPopulator;
  176574. sCtx.iOff = (((i64)iCol) << 32) - 1;
  176575. for(i=0; i<pExpr->nPhrase; i++){
  176576. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  176577. Fts5Colset *pColset = pNode->pNear->pColset;
  176578. if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
  176579. || aPopulator[i].bMiss
  176580. ){
  176581. aPopulator[i].bOk = 0;
  176582. }else{
  176583. aPopulator[i].bOk = 1;
  176584. }
  176585. }
  176586. return sqlite3Fts5Tokenize(pConfig,
  176587. FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
  176588. );
  176589. }
  176590. static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
  176591. if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
  176592. pNode->pNear->apPhrase[0]->poslist.n = 0;
  176593. }else{
  176594. int i;
  176595. for(i=0; i<pNode->nChild; i++){
  176596. fts5ExprClearPoslists(pNode->apChild[i]);
  176597. }
  176598. }
  176599. }
  176600. static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
  176601. pNode->iRowid = iRowid;
  176602. pNode->bEof = 0;
  176603. switch( pNode->eType ){
  176604. case FTS5_TERM:
  176605. case FTS5_STRING:
  176606. return (pNode->pNear->apPhrase[0]->poslist.n>0);
  176607. case FTS5_AND: {
  176608. int i;
  176609. for(i=0; i<pNode->nChild; i++){
  176610. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
  176611. fts5ExprClearPoslists(pNode);
  176612. return 0;
  176613. }
  176614. }
  176615. break;
  176616. }
  176617. case FTS5_OR: {
  176618. int i;
  176619. int bRet = 0;
  176620. for(i=0; i<pNode->nChild; i++){
  176621. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
  176622. bRet = 1;
  176623. }
  176624. }
  176625. return bRet;
  176626. }
  176627. default: {
  176628. assert( pNode->eType==FTS5_NOT );
  176629. if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
  176630. || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
  176631. ){
  176632. fts5ExprClearPoslists(pNode);
  176633. return 0;
  176634. }
  176635. break;
  176636. }
  176637. }
  176638. return 1;
  176639. }
  176640. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
  176641. fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
  176642. }
  176643. /*
  176644. ** This function is only called for detail=columns tables.
  176645. */
  176646. static int sqlite3Fts5ExprPhraseCollist(
  176647. Fts5Expr *pExpr,
  176648. int iPhrase,
  176649. const u8 **ppCollist,
  176650. int *pnCollist
  176651. ){
  176652. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  176653. Fts5ExprNode *pNode = pPhrase->pNode;
  176654. int rc = SQLITE_OK;
  176655. assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
  176656. assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  176657. if( pNode->bEof==0
  176658. && pNode->iRowid==pExpr->pRoot->iRowid
  176659. && pPhrase->poslist.n>0
  176660. ){
  176661. Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
  176662. if( pTerm->pSynonym ){
  176663. Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
  176664. rc = fts5ExprSynonymList(
  176665. pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
  176666. );
  176667. }else{
  176668. *ppCollist = pPhrase->aTerm[0].pIter->pData;
  176669. *pnCollist = pPhrase->aTerm[0].pIter->nData;
  176670. }
  176671. }else{
  176672. *ppCollist = 0;
  176673. *pnCollist = 0;
  176674. }
  176675. return rc;
  176676. }
  176677. /*
  176678. ** 2014 August 11
  176679. **
  176680. ** The author disclaims copyright to this source code. In place of
  176681. ** a legal notice, here is a blessing:
  176682. **
  176683. ** May you do good and not evil.
  176684. ** May you find forgiveness for yourself and forgive others.
  176685. ** May you share freely, never taking more than you give.
  176686. **
  176687. ******************************************************************************
  176688. **
  176689. */
  176690. /* #include "fts5Int.h" */
  176691. typedef struct Fts5HashEntry Fts5HashEntry;
  176692. /*
  176693. ** This file contains the implementation of an in-memory hash table used
  176694. ** to accumuluate "term -> doclist" content before it is flused to a level-0
  176695. ** segment.
  176696. */
  176697. struct Fts5Hash {
  176698. int eDetail; /* Copy of Fts5Config.eDetail */
  176699. int *pnByte; /* Pointer to bytes counter */
  176700. int nEntry; /* Number of entries currently in hash */
  176701. int nSlot; /* Size of aSlot[] array */
  176702. Fts5HashEntry *pScan; /* Current ordered scan item */
  176703. Fts5HashEntry **aSlot; /* Array of hash slots */
  176704. };
  176705. /*
  176706. ** Each entry in the hash table is represented by an object of the
  176707. ** following type. Each object, its key (a nul-terminated string) and
  176708. ** its current data are stored in a single memory allocation. The
  176709. ** key immediately follows the object in memory. The position list
  176710. ** data immediately follows the key data in memory.
  176711. **
  176712. ** The data that follows the key is in a similar, but not identical format
  176713. ** to the doclist data stored in the database. It is:
  176714. **
  176715. ** * Rowid, as a varint
  176716. ** * Position list, without 0x00 terminator.
  176717. ** * Size of previous position list and rowid, as a 4 byte
  176718. ** big-endian integer.
  176719. **
  176720. ** iRowidOff:
  176721. ** Offset of last rowid written to data area. Relative to first byte of
  176722. ** structure.
  176723. **
  176724. ** nData:
  176725. ** Bytes of data written since iRowidOff.
  176726. */
  176727. struct Fts5HashEntry {
  176728. Fts5HashEntry *pHashNext; /* Next hash entry with same hash-key */
  176729. Fts5HashEntry *pScanNext; /* Next entry in sorted order */
  176730. int nAlloc; /* Total size of allocation */
  176731. int iSzPoslist; /* Offset of space for 4-byte poslist size */
  176732. int nData; /* Total bytes of data (incl. structure) */
  176733. int nKey; /* Length of key in bytes */
  176734. u8 bDel; /* Set delete-flag @ iSzPoslist */
  176735. u8 bContent; /* Set content-flag (detail=none mode) */
  176736. i16 iCol; /* Column of last value written */
  176737. int iPos; /* Position of last value written */
  176738. i64 iRowid; /* Rowid of last value written */
  176739. };
  176740. /*
  176741. ** Eqivalent to:
  176742. **
  176743. ** char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; }
  176744. */
  176745. #define fts5EntryKey(p) ( ((char *)(&(p)[1])) )
  176746. /*
  176747. ** Allocate a new hash table.
  176748. */
  176749. static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
  176750. int rc = SQLITE_OK;
  176751. Fts5Hash *pNew;
  176752. *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
  176753. if( pNew==0 ){
  176754. rc = SQLITE_NOMEM;
  176755. }else{
  176756. int nByte;
  176757. memset(pNew, 0, sizeof(Fts5Hash));
  176758. pNew->pnByte = pnByte;
  176759. pNew->eDetail = pConfig->eDetail;
  176760. pNew->nSlot = 1024;
  176761. nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
  176762. pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
  176763. if( pNew->aSlot==0 ){
  176764. sqlite3_free(pNew);
  176765. *ppNew = 0;
  176766. rc = SQLITE_NOMEM;
  176767. }else{
  176768. memset(pNew->aSlot, 0, nByte);
  176769. }
  176770. }
  176771. return rc;
  176772. }
  176773. /*
  176774. ** Free a hash table object.
  176775. */
  176776. static void sqlite3Fts5HashFree(Fts5Hash *pHash){
  176777. if( pHash ){
  176778. sqlite3Fts5HashClear(pHash);
  176779. sqlite3_free(pHash->aSlot);
  176780. sqlite3_free(pHash);
  176781. }
  176782. }
  176783. /*
  176784. ** Empty (but do not delete) a hash table.
  176785. */
  176786. static void sqlite3Fts5HashClear(Fts5Hash *pHash){
  176787. int i;
  176788. for(i=0; i<pHash->nSlot; i++){
  176789. Fts5HashEntry *pNext;
  176790. Fts5HashEntry *pSlot;
  176791. for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
  176792. pNext = pSlot->pHashNext;
  176793. sqlite3_free(pSlot);
  176794. }
  176795. }
  176796. memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
  176797. pHash->nEntry = 0;
  176798. }
  176799. static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
  176800. int i;
  176801. unsigned int h = 13;
  176802. for(i=n-1; i>=0; i--){
  176803. h = (h << 3) ^ h ^ p[i];
  176804. }
  176805. return (h % nSlot);
  176806. }
  176807. static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
  176808. int i;
  176809. unsigned int h = 13;
  176810. for(i=n-1; i>=0; i--){
  176811. h = (h << 3) ^ h ^ p[i];
  176812. }
  176813. h = (h << 3) ^ h ^ b;
  176814. return (h % nSlot);
  176815. }
  176816. /*
  176817. ** Resize the hash table by doubling the number of slots.
  176818. */
  176819. static int fts5HashResize(Fts5Hash *pHash){
  176820. int nNew = pHash->nSlot*2;
  176821. int i;
  176822. Fts5HashEntry **apNew;
  176823. Fts5HashEntry **apOld = pHash->aSlot;
  176824. apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
  176825. if( !apNew ) return SQLITE_NOMEM;
  176826. memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
  176827. for(i=0; i<pHash->nSlot; i++){
  176828. while( apOld[i] ){
  176829. int iHash;
  176830. Fts5HashEntry *p = apOld[i];
  176831. apOld[i] = p->pHashNext;
  176832. iHash = fts5HashKey(nNew, (u8*)fts5EntryKey(p), strlen(fts5EntryKey(p)));
  176833. p->pHashNext = apNew[iHash];
  176834. apNew[iHash] = p;
  176835. }
  176836. }
  176837. sqlite3_free(apOld);
  176838. pHash->nSlot = nNew;
  176839. pHash->aSlot = apNew;
  176840. return SQLITE_OK;
  176841. }
  176842. static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
  176843. if( p->iSzPoslist ){
  176844. u8 *pPtr = (u8*)p;
  176845. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  176846. assert( p->nData==p->iSzPoslist );
  176847. if( p->bDel ){
  176848. pPtr[p->nData++] = 0x00;
  176849. if( p->bContent ){
  176850. pPtr[p->nData++] = 0x00;
  176851. }
  176852. }
  176853. }else{
  176854. int nSz = (p->nData - p->iSzPoslist - 1); /* Size in bytes */
  176855. int nPos = nSz*2 + p->bDel; /* Value of nPos field */
  176856. assert( p->bDel==0 || p->bDel==1 );
  176857. if( nPos<=127 ){
  176858. pPtr[p->iSzPoslist] = (u8)nPos;
  176859. }else{
  176860. int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
  176861. memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
  176862. sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
  176863. p->nData += (nByte-1);
  176864. }
  176865. }
  176866. p->iSzPoslist = 0;
  176867. p->bDel = 0;
  176868. p->bContent = 0;
  176869. }
  176870. }
  176871. /*
  176872. ** Add an entry to the in-memory hash table. The key is the concatenation
  176873. ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
  176874. **
  176875. ** (bByte || pToken) -> (iRowid,iCol,iPos)
  176876. **
  176877. ** Or, if iCol is negative, then the value is a delete marker.
  176878. */
  176879. static int sqlite3Fts5HashWrite(
  176880. Fts5Hash *pHash,
  176881. i64 iRowid, /* Rowid for this entry */
  176882. int iCol, /* Column token appears in (-ve -> delete) */
  176883. int iPos, /* Position of token within column */
  176884. char bByte, /* First byte of token */
  176885. const char *pToken, int nToken /* Token to add or remove to or from index */
  176886. ){
  176887. unsigned int iHash;
  176888. Fts5HashEntry *p;
  176889. u8 *pPtr;
  176890. int nIncr = 0; /* Amount to increment (*pHash->pnByte) by */
  176891. int bNew; /* If non-delete entry should be written */
  176892. bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
  176893. /* Attempt to locate an existing hash entry */
  176894. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  176895. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  176896. char *zKey = fts5EntryKey(p);
  176897. if( zKey[0]==bByte
  176898. && p->nKey==nToken
  176899. && memcmp(&zKey[1], pToken, nToken)==0
  176900. ){
  176901. break;
  176902. }
  176903. }
  176904. /* If an existing hash entry cannot be found, create a new one. */
  176905. if( p==0 ){
  176906. /* Figure out how much space to allocate */
  176907. char *zKey;
  176908. int nByte = sizeof(Fts5HashEntry) + (nToken+1) + 1 + 64;
  176909. if( nByte<128 ) nByte = 128;
  176910. /* Grow the Fts5Hash.aSlot[] array if necessary. */
  176911. if( (pHash->nEntry*2)>=pHash->nSlot ){
  176912. int rc = fts5HashResize(pHash);
  176913. if( rc!=SQLITE_OK ) return rc;
  176914. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  176915. }
  176916. /* Allocate new Fts5HashEntry and add it to the hash table. */
  176917. p = (Fts5HashEntry*)sqlite3_malloc(nByte);
  176918. if( !p ) return SQLITE_NOMEM;
  176919. memset(p, 0, sizeof(Fts5HashEntry));
  176920. p->nAlloc = nByte;
  176921. zKey = fts5EntryKey(p);
  176922. zKey[0] = bByte;
  176923. memcpy(&zKey[1], pToken, nToken);
  176924. assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) );
  176925. p->nKey = nToken;
  176926. zKey[nToken+1] = '\0';
  176927. p->nData = nToken+1 + 1 + sizeof(Fts5HashEntry);
  176928. p->pHashNext = pHash->aSlot[iHash];
  176929. pHash->aSlot[iHash] = p;
  176930. pHash->nEntry++;
  176931. /* Add the first rowid field to the hash-entry */
  176932. p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
  176933. p->iRowid = iRowid;
  176934. p->iSzPoslist = p->nData;
  176935. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  176936. p->nData += 1;
  176937. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  176938. }
  176939. nIncr += p->nData;
  176940. }else{
  176941. /* Appending to an existing hash-entry. Check that there is enough
  176942. ** space to append the largest possible new entry. Worst case scenario
  176943. ** is:
  176944. **
  176945. ** + 9 bytes for a new rowid,
  176946. ** + 4 byte reserved for the "poslist size" varint.
  176947. ** + 1 byte for a "new column" byte,
  176948. ** + 3 bytes for a new column number (16-bit max) as a varint,
  176949. ** + 5 bytes for the new position offset (32-bit max).
  176950. */
  176951. if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
  176952. int nNew = p->nAlloc * 2;
  176953. Fts5HashEntry *pNew;
  176954. Fts5HashEntry **pp;
  176955. pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
  176956. if( pNew==0 ) return SQLITE_NOMEM;
  176957. pNew->nAlloc = nNew;
  176958. for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
  176959. *pp = pNew;
  176960. p = pNew;
  176961. }
  176962. nIncr -= p->nData;
  176963. }
  176964. assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
  176965. pPtr = (u8*)p;
  176966. /* If this is a new rowid, append the 4-byte size field for the previous
  176967. ** entry, and the new rowid for this entry. */
  176968. if( iRowid!=p->iRowid ){
  176969. fts5HashAddPoslistSize(pHash, p);
  176970. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
  176971. p->iRowid = iRowid;
  176972. bNew = 1;
  176973. p->iSzPoslist = p->nData;
  176974. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  176975. p->nData += 1;
  176976. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  176977. p->iPos = 0;
  176978. }
  176979. }
  176980. if( iCol>=0 ){
  176981. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  176982. p->bContent = 1;
  176983. }else{
  176984. /* Append a new column value, if necessary */
  176985. assert( iCol>=p->iCol );
  176986. if( iCol!=p->iCol ){
  176987. if( pHash->eDetail==FTS5_DETAIL_FULL ){
  176988. pPtr[p->nData++] = 0x01;
  176989. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
  176990. p->iCol = (i16)iCol;
  176991. p->iPos = 0;
  176992. }else{
  176993. bNew = 1;
  176994. p->iCol = (i16)(iPos = iCol);
  176995. }
  176996. }
  176997. /* Append the new position offset, if necessary */
  176998. if( bNew ){
  176999. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
  177000. p->iPos = iPos;
  177001. }
  177002. }
  177003. }else{
  177004. /* This is a delete. Set the delete flag. */
  177005. p->bDel = 1;
  177006. }
  177007. nIncr += p->nData;
  177008. *pHash->pnByte += nIncr;
  177009. return SQLITE_OK;
  177010. }
  177011. /*
  177012. ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
  177013. ** each sorted in key order. This function merges the two lists into a
  177014. ** single list and returns a pointer to its first element.
  177015. */
  177016. static Fts5HashEntry *fts5HashEntryMerge(
  177017. Fts5HashEntry *pLeft,
  177018. Fts5HashEntry *pRight
  177019. ){
  177020. Fts5HashEntry *p1 = pLeft;
  177021. Fts5HashEntry *p2 = pRight;
  177022. Fts5HashEntry *pRet = 0;
  177023. Fts5HashEntry **ppOut = &pRet;
  177024. while( p1 || p2 ){
  177025. if( p1==0 ){
  177026. *ppOut = p2;
  177027. p2 = 0;
  177028. }else if( p2==0 ){
  177029. *ppOut = p1;
  177030. p1 = 0;
  177031. }else{
  177032. int i = 0;
  177033. char *zKey1 = fts5EntryKey(p1);
  177034. char *zKey2 = fts5EntryKey(p2);
  177035. while( zKey1[i]==zKey2[i] ) i++;
  177036. if( ((u8)zKey1[i])>((u8)zKey2[i]) ){
  177037. /* p2 is smaller */
  177038. *ppOut = p2;
  177039. ppOut = &p2->pScanNext;
  177040. p2 = p2->pScanNext;
  177041. }else{
  177042. /* p1 is smaller */
  177043. *ppOut = p1;
  177044. ppOut = &p1->pScanNext;
  177045. p1 = p1->pScanNext;
  177046. }
  177047. *ppOut = 0;
  177048. }
  177049. }
  177050. return pRet;
  177051. }
  177052. /*
  177053. ** Extract all tokens from hash table iHash and link them into a list
  177054. ** in sorted order. The hash table is cleared before returning. It is
  177055. ** the responsibility of the caller to free the elements of the returned
  177056. ** list.
  177057. */
  177058. static int fts5HashEntrySort(
  177059. Fts5Hash *pHash,
  177060. const char *pTerm, int nTerm, /* Query prefix, if any */
  177061. Fts5HashEntry **ppSorted
  177062. ){
  177063. const int nMergeSlot = 32;
  177064. Fts5HashEntry **ap;
  177065. Fts5HashEntry *pList;
  177066. int iSlot;
  177067. int i;
  177068. *ppSorted = 0;
  177069. ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
  177070. if( !ap ) return SQLITE_NOMEM;
  177071. memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
  177072. for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
  177073. Fts5HashEntry *pIter;
  177074. for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
  177075. if( pTerm==0 || 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm) ){
  177076. Fts5HashEntry *pEntry = pIter;
  177077. pEntry->pScanNext = 0;
  177078. for(i=0; ap[i]; i++){
  177079. pEntry = fts5HashEntryMerge(pEntry, ap[i]);
  177080. ap[i] = 0;
  177081. }
  177082. ap[i] = pEntry;
  177083. }
  177084. }
  177085. }
  177086. pList = 0;
  177087. for(i=0; i<nMergeSlot; i++){
  177088. pList = fts5HashEntryMerge(pList, ap[i]);
  177089. }
  177090. pHash->nEntry = 0;
  177091. sqlite3_free(ap);
  177092. *ppSorted = pList;
  177093. return SQLITE_OK;
  177094. }
  177095. /*
  177096. ** Query the hash table for a doclist associated with term pTerm/nTerm.
  177097. */
  177098. static int sqlite3Fts5HashQuery(
  177099. Fts5Hash *pHash, /* Hash table to query */
  177100. const char *pTerm, int nTerm, /* Query term */
  177101. const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
  177102. int *pnDoclist /* OUT: Size of doclist in bytes */
  177103. ){
  177104. unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
  177105. char *zKey;
  177106. Fts5HashEntry *p;
  177107. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  177108. zKey = fts5EntryKey(p);
  177109. if( memcmp(zKey, pTerm, nTerm)==0 && zKey[nTerm]==0 ) break;
  177110. }
  177111. if( p ){
  177112. fts5HashAddPoslistSize(pHash, p);
  177113. *ppDoclist = (const u8*)&zKey[nTerm+1];
  177114. *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
  177115. }else{
  177116. *ppDoclist = 0;
  177117. *pnDoclist = 0;
  177118. }
  177119. return SQLITE_OK;
  177120. }
  177121. static int sqlite3Fts5HashScanInit(
  177122. Fts5Hash *p, /* Hash table to query */
  177123. const char *pTerm, int nTerm /* Query prefix */
  177124. ){
  177125. return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
  177126. }
  177127. static void sqlite3Fts5HashScanNext(Fts5Hash *p){
  177128. assert( !sqlite3Fts5HashScanEof(p) );
  177129. p->pScan = p->pScan->pScanNext;
  177130. }
  177131. static int sqlite3Fts5HashScanEof(Fts5Hash *p){
  177132. return (p->pScan==0);
  177133. }
  177134. static void sqlite3Fts5HashScanEntry(
  177135. Fts5Hash *pHash,
  177136. const char **pzTerm, /* OUT: term (nul-terminated) */
  177137. const u8 **ppDoclist, /* OUT: pointer to doclist */
  177138. int *pnDoclist /* OUT: size of doclist in bytes */
  177139. ){
  177140. Fts5HashEntry *p;
  177141. if( (p = pHash->pScan) ){
  177142. char *zKey = fts5EntryKey(p);
  177143. int nTerm = (int)strlen(zKey);
  177144. fts5HashAddPoslistSize(pHash, p);
  177145. *pzTerm = zKey;
  177146. *ppDoclist = (const u8*)&zKey[nTerm+1];
  177147. *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
  177148. }else{
  177149. *pzTerm = 0;
  177150. *ppDoclist = 0;
  177151. *pnDoclist = 0;
  177152. }
  177153. }
  177154. /*
  177155. ** 2014 May 31
  177156. **
  177157. ** The author disclaims copyright to this source code. In place of
  177158. ** a legal notice, here is a blessing:
  177159. **
  177160. ** May you do good and not evil.
  177161. ** May you find forgiveness for yourself and forgive others.
  177162. ** May you share freely, never taking more than you give.
  177163. **
  177164. ******************************************************************************
  177165. **
  177166. ** Low level access to the FTS index stored in the database file. The
  177167. ** routines in this file file implement all read and write access to the
  177168. ** %_data table. Other parts of the system access this functionality via
  177169. ** the interface defined in fts5Int.h.
  177170. */
  177171. /* #include "fts5Int.h" */
  177172. /*
  177173. ** Overview:
  177174. **
  177175. ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
  177176. ** As well as the main term index, there may be up to 31 prefix indexes.
  177177. ** The format is similar to FTS3/4, except that:
  177178. **
  177179. ** * all segment b-tree leaf data is stored in fixed size page records
  177180. ** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
  177181. ** taken to ensure it is possible to iterate in either direction through
  177182. ** the entries in a doclist, or to seek to a specific entry within a
  177183. ** doclist, without loading it into memory.
  177184. **
  177185. ** * large doclists that span many pages have associated "doclist index"
  177186. ** records that contain a copy of the first rowid on each page spanned by
  177187. ** the doclist. This is used to speed up seek operations, and merges of
  177188. ** large doclists with very small doclists.
  177189. **
  177190. ** * extra fields in the "structure record" record the state of ongoing
  177191. ** incremental merge operations.
  177192. **
  177193. */
  177194. #define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
  177195. #define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
  177196. #define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
  177197. #define FTS5_MAIN_PREFIX '0'
  177198. #if FTS5_MAX_PREFIX_INDEXES > 31
  177199. # error "FTS5_MAX_PREFIX_INDEXES is too large"
  177200. #endif
  177201. /*
  177202. ** Details:
  177203. **
  177204. ** The %_data table managed by this module,
  177205. **
  177206. ** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
  177207. **
  177208. ** , contains the following 5 types of records. See the comments surrounding
  177209. ** the FTS5_*_ROWID macros below for a description of how %_data rowids are
  177210. ** assigned to each fo them.
  177211. **
  177212. ** 1. Structure Records:
  177213. **
  177214. ** The set of segments that make up an index - the index structure - are
  177215. ** recorded in a single record within the %_data table. The record consists
  177216. ** of a single 32-bit configuration cookie value followed by a list of
  177217. ** SQLite varints. If the FTS table features more than one index (because
  177218. ** there are one or more prefix indexes), it is guaranteed that all share
  177219. ** the same cookie value.
  177220. **
  177221. ** Immediately following the configuration cookie, the record begins with
  177222. ** three varints:
  177223. **
  177224. ** + number of levels,
  177225. ** + total number of segments on all levels,
  177226. ** + value of write counter.
  177227. **
  177228. ** Then, for each level from 0 to nMax:
  177229. **
  177230. ** + number of input segments in ongoing merge.
  177231. ** + total number of segments in level.
  177232. ** + for each segment from oldest to newest:
  177233. ** + segment id (always > 0)
  177234. ** + first leaf page number (often 1, always greater than 0)
  177235. ** + final leaf page number
  177236. **
  177237. ** 2. The Averages Record:
  177238. **
  177239. ** A single record within the %_data table. The data is a list of varints.
  177240. ** The first value is the number of rows in the index. Then, for each column
  177241. ** from left to right, the total number of tokens in the column for all
  177242. ** rows of the table.
  177243. **
  177244. ** 3. Segment leaves:
  177245. **
  177246. ** TERM/DOCLIST FORMAT:
  177247. **
  177248. ** Most of each segment leaf is taken up by term/doclist data. The
  177249. ** general format of term/doclist, starting with the first term
  177250. ** on the leaf page, is:
  177251. **
  177252. ** varint : size of first term
  177253. ** blob: first term data
  177254. ** doclist: first doclist
  177255. ** zero-or-more {
  177256. ** varint: number of bytes in common with previous term
  177257. ** varint: number of bytes of new term data (nNew)
  177258. ** blob: nNew bytes of new term data
  177259. ** doclist: next doclist
  177260. ** }
  177261. **
  177262. ** doclist format:
  177263. **
  177264. ** varint: first rowid
  177265. ** poslist: first poslist
  177266. ** zero-or-more {
  177267. ** varint: rowid delta (always > 0)
  177268. ** poslist: next poslist
  177269. ** }
  177270. **
  177271. ** poslist format:
  177272. **
  177273. ** varint: size of poslist in bytes multiplied by 2, not including
  177274. ** this field. Plus 1 if this entry carries the "delete" flag.
  177275. ** collist: collist for column 0
  177276. ** zero-or-more {
  177277. ** 0x01 byte
  177278. ** varint: column number (I)
  177279. ** collist: collist for column I
  177280. ** }
  177281. **
  177282. ** collist format:
  177283. **
  177284. ** varint: first offset + 2
  177285. ** zero-or-more {
  177286. ** varint: offset delta + 2
  177287. ** }
  177288. **
  177289. ** PAGE FORMAT
  177290. **
  177291. ** Each leaf page begins with a 4-byte header containing 2 16-bit
  177292. ** unsigned integer fields in big-endian format. They are:
  177293. **
  177294. ** * The byte offset of the first rowid on the page, if it exists
  177295. ** and occurs before the first term (otherwise 0).
  177296. **
  177297. ** * The byte offset of the start of the page footer. If the page
  177298. ** footer is 0 bytes in size, then this field is the same as the
  177299. ** size of the leaf page in bytes.
  177300. **
  177301. ** The page footer consists of a single varint for each term located
  177302. ** on the page. Each varint is the byte offset of the current term
  177303. ** within the page, delta-compressed against the previous value. In
  177304. ** other words, the first varint in the footer is the byte offset of
  177305. ** the first term, the second is the byte offset of the second less that
  177306. ** of the first, and so on.
  177307. **
  177308. ** The term/doclist format described above is accurate if the entire
  177309. ** term/doclist data fits on a single leaf page. If this is not the case,
  177310. ** the format is changed in two ways:
  177311. **
  177312. ** + if the first rowid on a page occurs before the first term, it
  177313. ** is stored as a literal value:
  177314. **
  177315. ** varint: first rowid
  177316. **
  177317. ** + the first term on each page is stored in the same way as the
  177318. ** very first term of the segment:
  177319. **
  177320. ** varint : size of first term
  177321. ** blob: first term data
  177322. **
  177323. ** 5. Segment doclist indexes:
  177324. **
  177325. ** Doclist indexes are themselves b-trees, however they usually consist of
  177326. ** a single leaf record only. The format of each doclist index leaf page
  177327. ** is:
  177328. **
  177329. ** * Flags byte. Bits are:
  177330. ** 0x01: Clear if leaf is also the root page, otherwise set.
  177331. **
  177332. ** * Page number of fts index leaf page. As a varint.
  177333. **
  177334. ** * First rowid on page indicated by previous field. As a varint.
  177335. **
  177336. ** * A list of varints, one for each subsequent termless page. A
  177337. ** positive delta if the termless page contains at least one rowid,
  177338. ** or an 0x00 byte otherwise.
  177339. **
  177340. ** Internal doclist index nodes are:
  177341. **
  177342. ** * Flags byte. Bits are:
  177343. ** 0x01: Clear for root page, otherwise set.
  177344. **
  177345. ** * Page number of first child page. As a varint.
  177346. **
  177347. ** * Copy of first rowid on page indicated by previous field. As a varint.
  177348. **
  177349. ** * A list of delta-encoded varints - the first rowid on each subsequent
  177350. ** child page.
  177351. **
  177352. */
  177353. /*
  177354. ** Rowids for the averages and structure records in the %_data table.
  177355. */
  177356. #define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
  177357. #define FTS5_STRUCTURE_ROWID 10 /* The structure record */
  177358. /*
  177359. ** Macros determining the rowids used by segment leaves and dlidx leaves
  177360. ** and nodes. All nodes and leaves are stored in the %_data table with large
  177361. ** positive rowids.
  177362. **
  177363. ** Each segment has a unique non-zero 16-bit id.
  177364. **
  177365. ** The rowid for each segment leaf is found by passing the segment id and
  177366. ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
  177367. ** sequentially starting from 1.
  177368. */
  177369. #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
  177370. #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
  177371. #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
  177372. #define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */
  177373. #define fts5_dri(segid, dlidx, height, pgno) ( \
  177374. ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
  177375. ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
  177376. ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
  177377. ((i64)(pgno)) \
  177378. )
  177379. #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
  177380. #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
  177381. /*
  177382. ** Maximum segments permitted in a single index
  177383. */
  177384. #define FTS5_MAX_SEGMENT 2000
  177385. #ifdef SQLITE_DEBUG
  177386. static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
  177387. #endif
  177388. /*
  177389. ** Each time a blob is read from the %_data table, it is padded with this
  177390. ** many zero bytes. This makes it easier to decode the various record formats
  177391. ** without overreading if the records are corrupt.
  177392. */
  177393. #define FTS5_DATA_ZERO_PADDING 8
  177394. #define FTS5_DATA_PADDING 20
  177395. typedef struct Fts5Data Fts5Data;
  177396. typedef struct Fts5DlidxIter Fts5DlidxIter;
  177397. typedef struct Fts5DlidxLvl Fts5DlidxLvl;
  177398. typedef struct Fts5DlidxWriter Fts5DlidxWriter;
  177399. typedef struct Fts5Iter Fts5Iter;
  177400. typedef struct Fts5PageWriter Fts5PageWriter;
  177401. typedef struct Fts5SegIter Fts5SegIter;
  177402. typedef struct Fts5DoclistIter Fts5DoclistIter;
  177403. typedef struct Fts5SegWriter Fts5SegWriter;
  177404. typedef struct Fts5Structure Fts5Structure;
  177405. typedef struct Fts5StructureLevel Fts5StructureLevel;
  177406. typedef struct Fts5StructureSegment Fts5StructureSegment;
  177407. struct Fts5Data {
  177408. u8 *p; /* Pointer to buffer containing record */
  177409. int nn; /* Size of record in bytes */
  177410. int szLeaf; /* Size of leaf without page-index */
  177411. };
  177412. /*
  177413. ** One object per %_data table.
  177414. */
  177415. struct Fts5Index {
  177416. Fts5Config *pConfig; /* Virtual table configuration */
  177417. char *zDataTbl; /* Name of %_data table */
  177418. int nWorkUnit; /* Leaf pages in a "unit" of work */
  177419. /*
  177420. ** Variables related to the accumulation of tokens and doclists within the
  177421. ** in-memory hash tables before they are flushed to disk.
  177422. */
  177423. Fts5Hash *pHash; /* Hash table for in-memory data */
  177424. int nPendingData; /* Current bytes of pending data */
  177425. i64 iWriteRowid; /* Rowid for current doc being written */
  177426. int bDelete; /* Current write is a delete */
  177427. /* Error state. */
  177428. int rc; /* Current error code */
  177429. /* State used by the fts5DataXXX() functions. */
  177430. sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
  177431. sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
  177432. sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
  177433. sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
  177434. sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */
  177435. sqlite3_stmt *pIdxSelect;
  177436. int nRead; /* Total number of blocks read */
  177437. sqlite3_stmt *pDataVersion;
  177438. i64 iStructVersion; /* data_version when pStruct read */
  177439. Fts5Structure *pStruct; /* Current db structure (or NULL) */
  177440. };
  177441. struct Fts5DoclistIter {
  177442. u8 *aEof; /* Pointer to 1 byte past end of doclist */
  177443. /* Output variables. aPoslist==0 at EOF */
  177444. i64 iRowid;
  177445. u8 *aPoslist;
  177446. int nPoslist;
  177447. int nSize;
  177448. };
  177449. /*
  177450. ** The contents of the "structure" record for each index are represented
  177451. ** using an Fts5Structure record in memory. Which uses instances of the
  177452. ** other Fts5StructureXXX types as components.
  177453. */
  177454. struct Fts5StructureSegment {
  177455. int iSegid; /* Segment id */
  177456. int pgnoFirst; /* First leaf page number in segment */
  177457. int pgnoLast; /* Last leaf page number in segment */
  177458. };
  177459. struct Fts5StructureLevel {
  177460. int nMerge; /* Number of segments in incr-merge */
  177461. int nSeg; /* Total number of segments on level */
  177462. Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
  177463. };
  177464. struct Fts5Structure {
  177465. int nRef; /* Object reference count */
  177466. u64 nWriteCounter; /* Total leaves written to level 0 */
  177467. int nSegment; /* Total segments in this structure */
  177468. int nLevel; /* Number of levels in this index */
  177469. Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */
  177470. };
  177471. /*
  177472. ** An object of type Fts5SegWriter is used to write to segments.
  177473. */
  177474. struct Fts5PageWriter {
  177475. int pgno; /* Page number for this page */
  177476. int iPrevPgidx; /* Previous value written into pgidx */
  177477. Fts5Buffer buf; /* Buffer containing leaf data */
  177478. Fts5Buffer pgidx; /* Buffer containing page-index */
  177479. Fts5Buffer term; /* Buffer containing previous term on page */
  177480. };
  177481. struct Fts5DlidxWriter {
  177482. int pgno; /* Page number for this page */
  177483. int bPrevValid; /* True if iPrev is valid */
  177484. i64 iPrev; /* Previous rowid value written to page */
  177485. Fts5Buffer buf; /* Buffer containing page data */
  177486. };
  177487. struct Fts5SegWriter {
  177488. int iSegid; /* Segid to write to */
  177489. Fts5PageWriter writer; /* PageWriter object */
  177490. i64 iPrevRowid; /* Previous rowid written to current leaf */
  177491. u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
  177492. u8 bFirstRowidInPage; /* True if next rowid is first in page */
  177493. /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
  177494. u8 bFirstTermInPage; /* True if next term will be first in leaf */
  177495. int nLeafWritten; /* Number of leaf pages written */
  177496. int nEmpty; /* Number of contiguous term-less nodes */
  177497. int nDlidx; /* Allocated size of aDlidx[] array */
  177498. Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
  177499. /* Values to insert into the %_idx table */
  177500. Fts5Buffer btterm; /* Next term to insert into %_idx table */
  177501. int iBtPage; /* Page number corresponding to btterm */
  177502. };
  177503. typedef struct Fts5CResult Fts5CResult;
  177504. struct Fts5CResult {
  177505. u16 iFirst; /* aSeg[] index of firstest iterator */
  177506. u8 bTermEq; /* True if the terms are equal */
  177507. };
  177508. /*
  177509. ** Object for iterating through a single segment, visiting each term/rowid
  177510. ** pair in the segment.
  177511. **
  177512. ** pSeg:
  177513. ** The segment to iterate through.
  177514. **
  177515. ** iLeafPgno:
  177516. ** Current leaf page number within segment.
  177517. **
  177518. ** iLeafOffset:
  177519. ** Byte offset within the current leaf that is the first byte of the
  177520. ** position list data (one byte passed the position-list size field).
  177521. ** rowid field of the current entry. Usually this is the size field of the
  177522. ** position list data. The exception is if the rowid for the current entry
  177523. ** is the last thing on the leaf page.
  177524. **
  177525. ** pLeaf:
  177526. ** Buffer containing current leaf page data. Set to NULL at EOF.
  177527. **
  177528. ** iTermLeafPgno, iTermLeafOffset:
  177529. ** Leaf page number containing the last term read from the segment. And
  177530. ** the offset immediately following the term data.
  177531. **
  177532. ** flags:
  177533. ** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
  177534. **
  177535. ** FTS5_SEGITER_ONETERM:
  177536. ** If set, set the iterator to point to EOF after the current doclist
  177537. ** has been exhausted. Do not proceed to the next term in the segment.
  177538. **
  177539. ** FTS5_SEGITER_REVERSE:
  177540. ** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
  177541. ** it is set, iterate through rowid in descending order instead of the
  177542. ** default ascending order.
  177543. **
  177544. ** iRowidOffset/nRowidOffset/aRowidOffset:
  177545. ** These are used if the FTS5_SEGITER_REVERSE flag is set.
  177546. **
  177547. ** For each rowid on the page corresponding to the current term, the
  177548. ** corresponding aRowidOffset[] entry is set to the byte offset of the
  177549. ** start of the "position-list-size" field within the page.
  177550. **
  177551. ** iTermIdx:
  177552. ** Index of current term on iTermLeafPgno.
  177553. */
  177554. struct Fts5SegIter {
  177555. Fts5StructureSegment *pSeg; /* Segment to iterate through */
  177556. int flags; /* Mask of configuration flags */
  177557. int iLeafPgno; /* Current leaf page number */
  177558. Fts5Data *pLeaf; /* Current leaf data */
  177559. Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
  177560. int iLeafOffset; /* Byte offset within current leaf */
  177561. /* Next method */
  177562. void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
  177563. /* The page and offset from which the current term was read. The offset
  177564. ** is the offset of the first rowid in the current doclist. */
  177565. int iTermLeafPgno;
  177566. int iTermLeafOffset;
  177567. int iPgidxOff; /* Next offset in pgidx */
  177568. int iEndofDoclist;
  177569. /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
  177570. int iRowidOffset; /* Current entry in aRowidOffset[] */
  177571. int nRowidOffset; /* Allocated size of aRowidOffset[] array */
  177572. int *aRowidOffset; /* Array of offset to rowid fields */
  177573. Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
  177574. /* Variables populated based on current entry. */
  177575. Fts5Buffer term; /* Current term */
  177576. i64 iRowid; /* Current rowid */
  177577. int nPos; /* Number of bytes in current position list */
  177578. u8 bDel; /* True if the delete flag is set */
  177579. };
  177580. /*
  177581. ** Argument is a pointer to an Fts5Data structure that contains a
  177582. ** leaf page.
  177583. */
  177584. #define ASSERT_SZLEAF_OK(x) assert( \
  177585. (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
  177586. )
  177587. #define FTS5_SEGITER_ONETERM 0x01
  177588. #define FTS5_SEGITER_REVERSE 0x02
  177589. /*
  177590. ** Argument is a pointer to an Fts5Data structure that contains a leaf
  177591. ** page. This macro evaluates to true if the leaf contains no terms, or
  177592. ** false if it contains at least one term.
  177593. */
  177594. #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
  177595. #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
  177596. #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
  177597. /*
  177598. ** Object for iterating through the merged results of one or more segments,
  177599. ** visiting each term/rowid pair in the merged data.
  177600. **
  177601. ** nSeg is always a power of two greater than or equal to the number of
  177602. ** segments that this object is merging data from. Both the aSeg[] and
  177603. ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
  177604. ** with zeroed objects - these are handled as if they were iterators opened
  177605. ** on empty segments.
  177606. **
  177607. ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
  177608. ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
  177609. ** comparison in this context is the index of the iterator that currently
  177610. ** points to the smaller term/rowid combination. Iterators at EOF are
  177611. ** considered to be greater than all other iterators.
  177612. **
  177613. ** aFirst[1] contains the index in aSeg[] of the iterator that points to
  177614. ** the smallest key overall. aFirst[0] is unused.
  177615. **
  177616. ** poslist:
  177617. ** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
  177618. ** There is no way to tell if this is populated or not.
  177619. */
  177620. struct Fts5Iter {
  177621. Fts5IndexIter base; /* Base class containing output vars */
  177622. Fts5Index *pIndex; /* Index that owns this iterator */
  177623. Fts5Structure *pStruct; /* Database structure for this iterator */
  177624. Fts5Buffer poslist; /* Buffer containing current poslist */
  177625. Fts5Colset *pColset; /* Restrict matches to these columns */
  177626. /* Invoked to set output variables. */
  177627. void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
  177628. int nSeg; /* Size of aSeg[] array */
  177629. int bRev; /* True to iterate in reverse order */
  177630. u8 bSkipEmpty; /* True to skip deleted entries */
  177631. i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
  177632. Fts5CResult *aFirst; /* Current merge state (see above) */
  177633. Fts5SegIter aSeg[1]; /* Array of segment iterators */
  177634. };
  177635. /*
  177636. ** An instance of the following type is used to iterate through the contents
  177637. ** of a doclist-index record.
  177638. **
  177639. ** pData:
  177640. ** Record containing the doclist-index data.
  177641. **
  177642. ** bEof:
  177643. ** Set to true once iterator has reached EOF.
  177644. **
  177645. ** iOff:
  177646. ** Set to the current offset within record pData.
  177647. */
  177648. struct Fts5DlidxLvl {
  177649. Fts5Data *pData; /* Data for current page of this level */
  177650. int iOff; /* Current offset into pData */
  177651. int bEof; /* At EOF already */
  177652. int iFirstOff; /* Used by reverse iterators */
  177653. /* Output variables */
  177654. int iLeafPgno; /* Page number of current leaf page */
  177655. i64 iRowid; /* First rowid on leaf iLeafPgno */
  177656. };
  177657. struct Fts5DlidxIter {
  177658. int nLvl;
  177659. int iSegid;
  177660. Fts5DlidxLvl aLvl[1];
  177661. };
  177662. static void fts5PutU16(u8 *aOut, u16 iVal){
  177663. aOut[0] = (iVal>>8);
  177664. aOut[1] = (iVal&0xFF);
  177665. }
  177666. static u16 fts5GetU16(const u8 *aIn){
  177667. return ((u16)aIn[0] << 8) + aIn[1];
  177668. }
  177669. /*
  177670. ** Allocate and return a buffer at least nByte bytes in size.
  177671. **
  177672. ** If an OOM error is encountered, return NULL and set the error code in
  177673. ** the Fts5Index handle passed as the first argument.
  177674. */
  177675. static void *fts5IdxMalloc(Fts5Index *p, int nByte){
  177676. return sqlite3Fts5MallocZero(&p->rc, nByte);
  177677. }
  177678. /*
  177679. ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
  177680. **
  177681. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  177682. ** +ve if pRight is smaller than pLeft. In other words:
  177683. **
  177684. ** res = *pLeft - *pRight
  177685. */
  177686. #ifdef SQLITE_DEBUG
  177687. static int fts5BufferCompareBlob(
  177688. Fts5Buffer *pLeft, /* Left hand side of comparison */
  177689. const u8 *pRight, int nRight /* Right hand side of comparison */
  177690. ){
  177691. int nCmp = MIN(pLeft->n, nRight);
  177692. int res = memcmp(pLeft->p, pRight, nCmp);
  177693. return (res==0 ? (pLeft->n - nRight) : res);
  177694. }
  177695. #endif
  177696. /*
  177697. ** Compare the contents of the two buffers using memcmp(). If one buffer
  177698. ** is a prefix of the other, it is considered the lesser.
  177699. **
  177700. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  177701. ** +ve if pRight is smaller than pLeft. In other words:
  177702. **
  177703. ** res = *pLeft - *pRight
  177704. */
  177705. static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
  177706. int nCmp = MIN(pLeft->n, pRight->n);
  177707. int res = memcmp(pLeft->p, pRight->p, nCmp);
  177708. return (res==0 ? (pLeft->n - pRight->n) : res);
  177709. }
  177710. static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
  177711. int ret;
  177712. fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
  177713. return ret;
  177714. }
  177715. /*
  177716. ** Close the read-only blob handle, if it is open.
  177717. */
  177718. static void fts5CloseReader(Fts5Index *p){
  177719. if( p->pReader ){
  177720. sqlite3_blob *pReader = p->pReader;
  177721. p->pReader = 0;
  177722. sqlite3_blob_close(pReader);
  177723. }
  177724. }
  177725. /*
  177726. ** Retrieve a record from the %_data table.
  177727. **
  177728. ** If an error occurs, NULL is returned and an error left in the
  177729. ** Fts5Index object.
  177730. */
  177731. static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
  177732. Fts5Data *pRet = 0;
  177733. if( p->rc==SQLITE_OK ){
  177734. int rc = SQLITE_OK;
  177735. if( p->pReader ){
  177736. /* This call may return SQLITE_ABORT if there has been a savepoint
  177737. ** rollback since it was last used. In this case a new blob handle
  177738. ** is required. */
  177739. sqlite3_blob *pBlob = p->pReader;
  177740. p->pReader = 0;
  177741. rc = sqlite3_blob_reopen(pBlob, iRowid);
  177742. assert( p->pReader==0 );
  177743. p->pReader = pBlob;
  177744. if( rc!=SQLITE_OK ){
  177745. fts5CloseReader(p);
  177746. }
  177747. if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
  177748. }
  177749. /* If the blob handle is not open at this point, open it and seek
  177750. ** to the requested entry. */
  177751. if( p->pReader==0 && rc==SQLITE_OK ){
  177752. Fts5Config *pConfig = p->pConfig;
  177753. rc = sqlite3_blob_open(pConfig->db,
  177754. pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
  177755. );
  177756. }
  177757. /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
  177758. ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
  177759. ** All the reasons those functions might return SQLITE_ERROR - missing
  177760. ** table, missing row, non-blob/text in block column - indicate
  177761. ** backing store corruption. */
  177762. if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
  177763. if( rc==SQLITE_OK ){
  177764. u8 *aOut = 0; /* Read blob data into this buffer */
  177765. int nByte = sqlite3_blob_bytes(p->pReader);
  177766. int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
  177767. pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
  177768. if( pRet ){
  177769. pRet->nn = nByte;
  177770. aOut = pRet->p = (u8*)&pRet[1];
  177771. }else{
  177772. rc = SQLITE_NOMEM;
  177773. }
  177774. if( rc==SQLITE_OK ){
  177775. rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
  177776. }
  177777. if( rc!=SQLITE_OK ){
  177778. sqlite3_free(pRet);
  177779. pRet = 0;
  177780. }else{
  177781. /* TODO1: Fix this */
  177782. pRet->szLeaf = fts5GetU16(&pRet->p[2]);
  177783. }
  177784. }
  177785. p->rc = rc;
  177786. p->nRead++;
  177787. }
  177788. assert( (pRet==0)==(p->rc!=SQLITE_OK) );
  177789. return pRet;
  177790. }
  177791. /*
  177792. ** Release a reference to data record returned by an earlier call to
  177793. ** fts5DataRead().
  177794. */
  177795. static void fts5DataRelease(Fts5Data *pData){
  177796. sqlite3_free(pData);
  177797. }
  177798. static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
  177799. Fts5Data *pRet = fts5DataRead(p, iRowid);
  177800. if( pRet ){
  177801. if( pRet->szLeaf>pRet->nn ){
  177802. p->rc = FTS5_CORRUPT;
  177803. fts5DataRelease(pRet);
  177804. pRet = 0;
  177805. }
  177806. }
  177807. return pRet;
  177808. }
  177809. static int fts5IndexPrepareStmt(
  177810. Fts5Index *p,
  177811. sqlite3_stmt **ppStmt,
  177812. char *zSql
  177813. ){
  177814. if( p->rc==SQLITE_OK ){
  177815. if( zSql ){
  177816. p->rc = sqlite3_prepare_v2(p->pConfig->db, zSql, -1, ppStmt, 0);
  177817. }else{
  177818. p->rc = SQLITE_NOMEM;
  177819. }
  177820. }
  177821. sqlite3_free(zSql);
  177822. return p->rc;
  177823. }
  177824. /*
  177825. ** INSERT OR REPLACE a record into the %_data table.
  177826. */
  177827. static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
  177828. if( p->rc!=SQLITE_OK ) return;
  177829. if( p->pWriter==0 ){
  177830. Fts5Config *pConfig = p->pConfig;
  177831. fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
  177832. "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
  177833. pConfig->zDb, pConfig->zName
  177834. ));
  177835. if( p->rc ) return;
  177836. }
  177837. sqlite3_bind_int64(p->pWriter, 1, iRowid);
  177838. sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
  177839. sqlite3_step(p->pWriter);
  177840. p->rc = sqlite3_reset(p->pWriter);
  177841. }
  177842. /*
  177843. ** Execute the following SQL:
  177844. **
  177845. ** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
  177846. */
  177847. static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
  177848. if( p->rc!=SQLITE_OK ) return;
  177849. if( p->pDeleter==0 ){
  177850. int rc;
  177851. Fts5Config *pConfig = p->pConfig;
  177852. char *zSql = sqlite3_mprintf(
  177853. "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
  177854. pConfig->zDb, pConfig->zName
  177855. );
  177856. if( zSql==0 ){
  177857. rc = SQLITE_NOMEM;
  177858. }else{
  177859. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p->pDeleter, 0);
  177860. sqlite3_free(zSql);
  177861. }
  177862. if( rc!=SQLITE_OK ){
  177863. p->rc = rc;
  177864. return;
  177865. }
  177866. }
  177867. sqlite3_bind_int64(p->pDeleter, 1, iFirst);
  177868. sqlite3_bind_int64(p->pDeleter, 2, iLast);
  177869. sqlite3_step(p->pDeleter);
  177870. p->rc = sqlite3_reset(p->pDeleter);
  177871. }
  177872. /*
  177873. ** Remove all records associated with segment iSegid.
  177874. */
  177875. static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
  177876. i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
  177877. i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
  177878. fts5DataDelete(p, iFirst, iLast);
  177879. if( p->pIdxDeleter==0 ){
  177880. Fts5Config *pConfig = p->pConfig;
  177881. fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
  177882. "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
  177883. pConfig->zDb, pConfig->zName
  177884. ));
  177885. }
  177886. if( p->rc==SQLITE_OK ){
  177887. sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
  177888. sqlite3_step(p->pIdxDeleter);
  177889. p->rc = sqlite3_reset(p->pIdxDeleter);
  177890. }
  177891. }
  177892. /*
  177893. ** Release a reference to an Fts5Structure object returned by an earlier
  177894. ** call to fts5StructureRead() or fts5StructureDecode().
  177895. */
  177896. static void fts5StructureRelease(Fts5Structure *pStruct){
  177897. if( pStruct && 0>=(--pStruct->nRef) ){
  177898. int i;
  177899. assert( pStruct->nRef==0 );
  177900. for(i=0; i<pStruct->nLevel; i++){
  177901. sqlite3_free(pStruct->aLevel[i].aSeg);
  177902. }
  177903. sqlite3_free(pStruct);
  177904. }
  177905. }
  177906. static void fts5StructureRef(Fts5Structure *pStruct){
  177907. pStruct->nRef++;
  177908. }
  177909. /*
  177910. ** Deserialize and return the structure record currently stored in serialized
  177911. ** form within buffer pData/nData.
  177912. **
  177913. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  177914. ** are over-allocated by one slot. This allows the structure contents
  177915. ** to be more easily edited.
  177916. **
  177917. ** If an error occurs, *ppOut is set to NULL and an SQLite error code
  177918. ** returned. Otherwise, *ppOut is set to point to the new object and
  177919. ** SQLITE_OK returned.
  177920. */
  177921. static int fts5StructureDecode(
  177922. const u8 *pData, /* Buffer containing serialized structure */
  177923. int nData, /* Size of buffer pData in bytes */
  177924. int *piCookie, /* Configuration cookie value */
  177925. Fts5Structure **ppOut /* OUT: Deserialized object */
  177926. ){
  177927. int rc = SQLITE_OK;
  177928. int i = 0;
  177929. int iLvl;
  177930. int nLevel = 0;
  177931. int nSegment = 0;
  177932. int nByte; /* Bytes of space to allocate at pRet */
  177933. Fts5Structure *pRet = 0; /* Structure object to return */
  177934. /* Grab the cookie value */
  177935. if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
  177936. i = 4;
  177937. /* Read the total number of levels and segments from the start of the
  177938. ** structure record. */
  177939. i += fts5GetVarint32(&pData[i], nLevel);
  177940. i += fts5GetVarint32(&pData[i], nSegment);
  177941. nByte = (
  177942. sizeof(Fts5Structure) + /* Main structure */
  177943. sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */
  177944. );
  177945. pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
  177946. if( pRet ){
  177947. pRet->nRef = 1;
  177948. pRet->nLevel = nLevel;
  177949. pRet->nSegment = nSegment;
  177950. i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
  177951. for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
  177952. Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
  177953. int nTotal = 0;
  177954. int iSeg;
  177955. if( i>=nData ){
  177956. rc = FTS5_CORRUPT;
  177957. }else{
  177958. i += fts5GetVarint32(&pData[i], pLvl->nMerge);
  177959. i += fts5GetVarint32(&pData[i], nTotal);
  177960. assert( nTotal>=pLvl->nMerge );
  177961. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
  177962. nTotal * sizeof(Fts5StructureSegment)
  177963. );
  177964. }
  177965. if( rc==SQLITE_OK ){
  177966. pLvl->nSeg = nTotal;
  177967. for(iSeg=0; iSeg<nTotal; iSeg++){
  177968. if( i>=nData ){
  177969. rc = FTS5_CORRUPT;
  177970. break;
  177971. }
  177972. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
  177973. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
  177974. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
  177975. }
  177976. }
  177977. }
  177978. if( rc!=SQLITE_OK ){
  177979. fts5StructureRelease(pRet);
  177980. pRet = 0;
  177981. }
  177982. }
  177983. *ppOut = pRet;
  177984. return rc;
  177985. }
  177986. /*
  177987. **
  177988. */
  177989. static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
  177990. if( *pRc==SQLITE_OK ){
  177991. Fts5Structure *pStruct = *ppStruct;
  177992. int nLevel = pStruct->nLevel;
  177993. int nByte = (
  177994. sizeof(Fts5Structure) + /* Main structure */
  177995. sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */
  177996. );
  177997. pStruct = sqlite3_realloc(pStruct, nByte);
  177998. if( pStruct ){
  177999. memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
  178000. pStruct->nLevel++;
  178001. *ppStruct = pStruct;
  178002. }else{
  178003. *pRc = SQLITE_NOMEM;
  178004. }
  178005. }
  178006. }
  178007. /*
  178008. ** Extend level iLvl so that there is room for at least nExtra more
  178009. ** segments.
  178010. */
  178011. static void fts5StructureExtendLevel(
  178012. int *pRc,
  178013. Fts5Structure *pStruct,
  178014. int iLvl,
  178015. int nExtra,
  178016. int bInsert
  178017. ){
  178018. if( *pRc==SQLITE_OK ){
  178019. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  178020. Fts5StructureSegment *aNew;
  178021. int nByte;
  178022. nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
  178023. aNew = sqlite3_realloc(pLvl->aSeg, nByte);
  178024. if( aNew ){
  178025. if( bInsert==0 ){
  178026. memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
  178027. }else{
  178028. int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
  178029. memmove(&aNew[nExtra], aNew, nMove);
  178030. memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
  178031. }
  178032. pLvl->aSeg = aNew;
  178033. }else{
  178034. *pRc = SQLITE_NOMEM;
  178035. }
  178036. }
  178037. }
  178038. static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
  178039. Fts5Structure *pRet = 0;
  178040. Fts5Config *pConfig = p->pConfig;
  178041. int iCookie; /* Configuration cookie */
  178042. Fts5Data *pData;
  178043. pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
  178044. if( p->rc==SQLITE_OK ){
  178045. /* TODO: Do we need this if the leaf-index is appended? Probably... */
  178046. memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
  178047. p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
  178048. if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
  178049. p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
  178050. }
  178051. fts5DataRelease(pData);
  178052. if( p->rc!=SQLITE_OK ){
  178053. fts5StructureRelease(pRet);
  178054. pRet = 0;
  178055. }
  178056. }
  178057. return pRet;
  178058. }
  178059. static i64 fts5IndexDataVersion(Fts5Index *p){
  178060. i64 iVersion = 0;
  178061. if( p->rc==SQLITE_OK ){
  178062. if( p->pDataVersion==0 ){
  178063. p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
  178064. sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
  178065. );
  178066. if( p->rc ) return 0;
  178067. }
  178068. if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
  178069. iVersion = sqlite3_column_int64(p->pDataVersion, 0);
  178070. }
  178071. p->rc = sqlite3_reset(p->pDataVersion);
  178072. }
  178073. return iVersion;
  178074. }
  178075. /*
  178076. ** Read, deserialize and return the structure record.
  178077. **
  178078. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  178079. ** are over-allocated as described for function fts5StructureDecode()
  178080. ** above.
  178081. **
  178082. ** If an error occurs, NULL is returned and an error code left in the
  178083. ** Fts5Index handle. If an error has already occurred when this function
  178084. ** is called, it is a no-op.
  178085. */
  178086. static Fts5Structure *fts5StructureRead(Fts5Index *p){
  178087. if( p->pStruct==0 ){
  178088. p->iStructVersion = fts5IndexDataVersion(p);
  178089. if( p->rc==SQLITE_OK ){
  178090. p->pStruct = fts5StructureReadUncached(p);
  178091. }
  178092. }
  178093. #if 0
  178094. else{
  178095. Fts5Structure *pTest = fts5StructureReadUncached(p);
  178096. if( pTest ){
  178097. int i, j;
  178098. assert_nc( p->pStruct->nSegment==pTest->nSegment );
  178099. assert_nc( p->pStruct->nLevel==pTest->nLevel );
  178100. for(i=0; i<pTest->nLevel; i++){
  178101. assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
  178102. assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
  178103. for(j=0; j<pTest->aLevel[i].nSeg; j++){
  178104. Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
  178105. Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
  178106. assert_nc( p1->iSegid==p2->iSegid );
  178107. assert_nc( p1->pgnoFirst==p2->pgnoFirst );
  178108. assert_nc( p1->pgnoLast==p2->pgnoLast );
  178109. }
  178110. }
  178111. fts5StructureRelease(pTest);
  178112. }
  178113. }
  178114. #endif
  178115. if( p->rc!=SQLITE_OK ) return 0;
  178116. assert( p->iStructVersion!=0 );
  178117. assert( p->pStruct!=0 );
  178118. fts5StructureRef(p->pStruct);
  178119. return p->pStruct;
  178120. }
  178121. static void fts5StructureInvalidate(Fts5Index *p){
  178122. if( p->pStruct ){
  178123. fts5StructureRelease(p->pStruct);
  178124. p->pStruct = 0;
  178125. }
  178126. }
  178127. /*
  178128. ** Return the total number of segments in index structure pStruct. This
  178129. ** function is only ever used as part of assert() conditions.
  178130. */
  178131. #ifdef SQLITE_DEBUG
  178132. static int fts5StructureCountSegments(Fts5Structure *pStruct){
  178133. int nSegment = 0; /* Total number of segments */
  178134. if( pStruct ){
  178135. int iLvl; /* Used to iterate through levels */
  178136. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  178137. nSegment += pStruct->aLevel[iLvl].nSeg;
  178138. }
  178139. }
  178140. return nSegment;
  178141. }
  178142. #endif
  178143. #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
  178144. assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
  178145. memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
  178146. (pBuf)->n += nBlob; \
  178147. }
  178148. #define fts5BufferSafeAppendVarint(pBuf, iVal) { \
  178149. (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
  178150. assert( (pBuf)->nSpace>=(pBuf)->n ); \
  178151. }
  178152. /*
  178153. ** Serialize and store the "structure" record.
  178154. **
  178155. ** If an error occurs, leave an error code in the Fts5Index object. If an
  178156. ** error has already occurred, this function is a no-op.
  178157. */
  178158. static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
  178159. if( p->rc==SQLITE_OK ){
  178160. Fts5Buffer buf; /* Buffer to serialize record into */
  178161. int iLvl; /* Used to iterate through levels */
  178162. int iCookie; /* Cookie value to store */
  178163. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  178164. memset(&buf, 0, sizeof(Fts5Buffer));
  178165. /* Append the current configuration cookie */
  178166. iCookie = p->pConfig->iCookie;
  178167. if( iCookie<0 ) iCookie = 0;
  178168. if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
  178169. sqlite3Fts5Put32(buf.p, iCookie);
  178170. buf.n = 4;
  178171. fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
  178172. fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
  178173. fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
  178174. }
  178175. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  178176. int iSeg; /* Used to iterate through segments */
  178177. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  178178. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
  178179. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
  178180. assert( pLvl->nMerge<=pLvl->nSeg );
  178181. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  178182. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
  178183. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
  178184. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
  178185. }
  178186. }
  178187. fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
  178188. fts5BufferFree(&buf);
  178189. }
  178190. }
  178191. #if 0
  178192. static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
  178193. static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
  178194. int rc = SQLITE_OK;
  178195. Fts5Buffer buf;
  178196. memset(&buf, 0, sizeof(buf));
  178197. fts5DebugStructure(&rc, &buf, pStruct);
  178198. fprintf(stdout, "%s: %s\n", zCaption, buf.p);
  178199. fflush(stdout);
  178200. fts5BufferFree(&buf);
  178201. }
  178202. #else
  178203. # define fts5PrintStructure(x,y)
  178204. #endif
  178205. static int fts5SegmentSize(Fts5StructureSegment *pSeg){
  178206. return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
  178207. }
  178208. /*
  178209. ** Return a copy of index structure pStruct. Except, promote as many
  178210. ** segments as possible to level iPromote. If an OOM occurs, NULL is
  178211. ** returned.
  178212. */
  178213. static void fts5StructurePromoteTo(
  178214. Fts5Index *p,
  178215. int iPromote,
  178216. int szPromote,
  178217. Fts5Structure *pStruct
  178218. ){
  178219. int il, is;
  178220. Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
  178221. if( pOut->nMerge==0 ){
  178222. for(il=iPromote+1; il<pStruct->nLevel; il++){
  178223. Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
  178224. if( pLvl->nMerge ) return;
  178225. for(is=pLvl->nSeg-1; is>=0; is--){
  178226. int sz = fts5SegmentSize(&pLvl->aSeg[is]);
  178227. if( sz>szPromote ) return;
  178228. fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
  178229. if( p->rc ) return;
  178230. memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
  178231. pOut->nSeg++;
  178232. pLvl->nSeg--;
  178233. }
  178234. }
  178235. }
  178236. }
  178237. /*
  178238. ** A new segment has just been written to level iLvl of index structure
  178239. ** pStruct. This function determines if any segments should be promoted
  178240. ** as a result. Segments are promoted in two scenarios:
  178241. **
  178242. ** a) If the segment just written is smaller than one or more segments
  178243. ** within the previous populated level, it is promoted to the previous
  178244. ** populated level.
  178245. **
  178246. ** b) If the segment just written is larger than the newest segment on
  178247. ** the next populated level, then that segment, and any other adjacent
  178248. ** segments that are also smaller than the one just written, are
  178249. ** promoted.
  178250. **
  178251. ** If one or more segments are promoted, the structure object is updated
  178252. ** to reflect this.
  178253. */
  178254. static void fts5StructurePromote(
  178255. Fts5Index *p, /* FTS5 backend object */
  178256. int iLvl, /* Index level just updated */
  178257. Fts5Structure *pStruct /* Index structure */
  178258. ){
  178259. if( p->rc==SQLITE_OK ){
  178260. int iTst;
  178261. int iPromote = -1;
  178262. int szPromote = 0; /* Promote anything this size or smaller */
  178263. Fts5StructureSegment *pSeg; /* Segment just written */
  178264. int szSeg; /* Size of segment just written */
  178265. int nSeg = pStruct->aLevel[iLvl].nSeg;
  178266. if( nSeg==0 ) return;
  178267. pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
  178268. szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
  178269. /* Check for condition (a) */
  178270. for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
  178271. if( iTst>=0 ){
  178272. int i;
  178273. int szMax = 0;
  178274. Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
  178275. assert( pTst->nMerge==0 );
  178276. for(i=0; i<pTst->nSeg; i++){
  178277. int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
  178278. if( sz>szMax ) szMax = sz;
  178279. }
  178280. if( szMax>=szSeg ){
  178281. /* Condition (a) is true. Promote the newest segment on level
  178282. ** iLvl to level iTst. */
  178283. iPromote = iTst;
  178284. szPromote = szMax;
  178285. }
  178286. }
  178287. /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
  178288. ** is a no-op if it is not. */
  178289. if( iPromote<0 ){
  178290. iPromote = iLvl;
  178291. szPromote = szSeg;
  178292. }
  178293. fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
  178294. }
  178295. }
  178296. /*
  178297. ** Advance the iterator passed as the only argument. If the end of the
  178298. ** doclist-index page is reached, return non-zero.
  178299. */
  178300. static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
  178301. Fts5Data *pData = pLvl->pData;
  178302. if( pLvl->iOff==0 ){
  178303. assert( pLvl->bEof==0 );
  178304. pLvl->iOff = 1;
  178305. pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
  178306. pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
  178307. pLvl->iFirstOff = pLvl->iOff;
  178308. }else{
  178309. int iOff;
  178310. for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
  178311. if( pData->p[iOff] ) break;
  178312. }
  178313. if( iOff<pData->nn ){
  178314. i64 iVal;
  178315. pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
  178316. iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
  178317. pLvl->iRowid += iVal;
  178318. pLvl->iOff = iOff;
  178319. }else{
  178320. pLvl->bEof = 1;
  178321. }
  178322. }
  178323. return pLvl->bEof;
  178324. }
  178325. /*
  178326. ** Advance the iterator passed as the only argument.
  178327. */
  178328. static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  178329. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  178330. assert( iLvl<pIter->nLvl );
  178331. if( fts5DlidxLvlNext(pLvl) ){
  178332. if( (iLvl+1) < pIter->nLvl ){
  178333. fts5DlidxIterNextR(p, pIter, iLvl+1);
  178334. if( pLvl[1].bEof==0 ){
  178335. fts5DataRelease(pLvl->pData);
  178336. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  178337. pLvl->pData = fts5DataRead(p,
  178338. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  178339. );
  178340. if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
  178341. }
  178342. }
  178343. }
  178344. return pIter->aLvl[0].bEof;
  178345. }
  178346. static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
  178347. return fts5DlidxIterNextR(p, pIter, 0);
  178348. }
  178349. /*
  178350. ** The iterator passed as the first argument has the following fields set
  178351. ** as follows. This function sets up the rest of the iterator so that it
  178352. ** points to the first rowid in the doclist-index.
  178353. **
  178354. ** pData:
  178355. ** pointer to doclist-index record,
  178356. **
  178357. ** When this function is called pIter->iLeafPgno is the page number the
  178358. ** doclist is associated with (the one featuring the term).
  178359. */
  178360. static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
  178361. int i;
  178362. for(i=0; i<pIter->nLvl; i++){
  178363. fts5DlidxLvlNext(&pIter->aLvl[i]);
  178364. }
  178365. return pIter->aLvl[0].bEof;
  178366. }
  178367. static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
  178368. return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
  178369. }
  178370. static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
  178371. int i;
  178372. /* Advance each level to the last entry on the last page */
  178373. for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
  178374. Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
  178375. while( fts5DlidxLvlNext(pLvl)==0 );
  178376. pLvl->bEof = 0;
  178377. if( i>0 ){
  178378. Fts5DlidxLvl *pChild = &pLvl[-1];
  178379. fts5DataRelease(pChild->pData);
  178380. memset(pChild, 0, sizeof(Fts5DlidxLvl));
  178381. pChild->pData = fts5DataRead(p,
  178382. FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
  178383. );
  178384. }
  178385. }
  178386. }
  178387. /*
  178388. ** Move the iterator passed as the only argument to the previous entry.
  178389. */
  178390. static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
  178391. int iOff = pLvl->iOff;
  178392. assert( pLvl->bEof==0 );
  178393. if( iOff<=pLvl->iFirstOff ){
  178394. pLvl->bEof = 1;
  178395. }else{
  178396. u8 *a = pLvl->pData->p;
  178397. i64 iVal;
  178398. int iLimit;
  178399. int ii;
  178400. int nZero = 0;
  178401. /* Currently iOff points to the first byte of a varint. This block
  178402. ** decrements iOff until it points to the first byte of the previous
  178403. ** varint. Taking care not to read any memory locations that occur
  178404. ** before the buffer in memory. */
  178405. iLimit = (iOff>9 ? iOff-9 : 0);
  178406. for(iOff--; iOff>iLimit; iOff--){
  178407. if( (a[iOff-1] & 0x80)==0 ) break;
  178408. }
  178409. fts5GetVarint(&a[iOff], (u64*)&iVal);
  178410. pLvl->iRowid -= iVal;
  178411. pLvl->iLeafPgno--;
  178412. /* Skip backwards past any 0x00 varints. */
  178413. for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
  178414. nZero++;
  178415. }
  178416. if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
  178417. /* The byte immediately before the last 0x00 byte has the 0x80 bit
  178418. ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
  178419. ** bytes before a[ii]. */
  178420. int bZero = 0; /* True if last 0x00 counts */
  178421. if( (ii-8)>=pLvl->iFirstOff ){
  178422. int j;
  178423. for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
  178424. bZero = (j>8);
  178425. }
  178426. if( bZero==0 ) nZero--;
  178427. }
  178428. pLvl->iLeafPgno -= nZero;
  178429. pLvl->iOff = iOff - nZero;
  178430. }
  178431. return pLvl->bEof;
  178432. }
  178433. static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  178434. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  178435. assert( iLvl<pIter->nLvl );
  178436. if( fts5DlidxLvlPrev(pLvl) ){
  178437. if( (iLvl+1) < pIter->nLvl ){
  178438. fts5DlidxIterPrevR(p, pIter, iLvl+1);
  178439. if( pLvl[1].bEof==0 ){
  178440. fts5DataRelease(pLvl->pData);
  178441. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  178442. pLvl->pData = fts5DataRead(p,
  178443. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  178444. );
  178445. if( pLvl->pData ){
  178446. while( fts5DlidxLvlNext(pLvl)==0 );
  178447. pLvl->bEof = 0;
  178448. }
  178449. }
  178450. }
  178451. }
  178452. return pIter->aLvl[0].bEof;
  178453. }
  178454. static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
  178455. return fts5DlidxIterPrevR(p, pIter, 0);
  178456. }
  178457. /*
  178458. ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
  178459. */
  178460. static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
  178461. if( pIter ){
  178462. int i;
  178463. for(i=0; i<pIter->nLvl; i++){
  178464. fts5DataRelease(pIter->aLvl[i].pData);
  178465. }
  178466. sqlite3_free(pIter);
  178467. }
  178468. }
  178469. static Fts5DlidxIter *fts5DlidxIterInit(
  178470. Fts5Index *p, /* Fts5 Backend to iterate within */
  178471. int bRev, /* True for ORDER BY ASC */
  178472. int iSegid, /* Segment id */
  178473. int iLeafPg /* Leaf page number to load dlidx for */
  178474. ){
  178475. Fts5DlidxIter *pIter = 0;
  178476. int i;
  178477. int bDone = 0;
  178478. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  178479. int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
  178480. Fts5DlidxIter *pNew;
  178481. pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
  178482. if( pNew==0 ){
  178483. p->rc = SQLITE_NOMEM;
  178484. }else{
  178485. i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
  178486. Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
  178487. pIter = pNew;
  178488. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  178489. pLvl->pData = fts5DataRead(p, iRowid);
  178490. if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
  178491. bDone = 1;
  178492. }
  178493. pIter->nLvl = i+1;
  178494. }
  178495. }
  178496. if( p->rc==SQLITE_OK ){
  178497. pIter->iSegid = iSegid;
  178498. if( bRev==0 ){
  178499. fts5DlidxIterFirst(pIter);
  178500. }else{
  178501. fts5DlidxIterLast(p, pIter);
  178502. }
  178503. }
  178504. if( p->rc!=SQLITE_OK ){
  178505. fts5DlidxIterFree(pIter);
  178506. pIter = 0;
  178507. }
  178508. return pIter;
  178509. }
  178510. static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
  178511. return pIter->aLvl[0].iRowid;
  178512. }
  178513. static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
  178514. return pIter->aLvl[0].iLeafPgno;
  178515. }
  178516. /*
  178517. ** Load the next leaf page into the segment iterator.
  178518. */
  178519. static void fts5SegIterNextPage(
  178520. Fts5Index *p, /* FTS5 backend object */
  178521. Fts5SegIter *pIter /* Iterator to advance to next page */
  178522. ){
  178523. Fts5Data *pLeaf;
  178524. Fts5StructureSegment *pSeg = pIter->pSeg;
  178525. fts5DataRelease(pIter->pLeaf);
  178526. pIter->iLeafPgno++;
  178527. if( pIter->pNextLeaf ){
  178528. pIter->pLeaf = pIter->pNextLeaf;
  178529. pIter->pNextLeaf = 0;
  178530. }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
  178531. pIter->pLeaf = fts5LeafRead(p,
  178532. FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
  178533. );
  178534. }else{
  178535. pIter->pLeaf = 0;
  178536. }
  178537. pLeaf = pIter->pLeaf;
  178538. if( pLeaf ){
  178539. pIter->iPgidxOff = pLeaf->szLeaf;
  178540. if( fts5LeafIsTermless(pLeaf) ){
  178541. pIter->iEndofDoclist = pLeaf->nn+1;
  178542. }else{
  178543. pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
  178544. pIter->iEndofDoclist
  178545. );
  178546. }
  178547. }
  178548. }
  178549. /*
  178550. ** Argument p points to a buffer containing a varint to be interpreted as a
  178551. ** position list size field. Read the varint and return the number of bytes
  178552. ** read. Before returning, set *pnSz to the number of bytes in the position
  178553. ** list, and *pbDel to true if the delete flag is set, or false otherwise.
  178554. */
  178555. static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
  178556. int nSz;
  178557. int n = 0;
  178558. fts5FastGetVarint32(p, n, nSz);
  178559. assert_nc( nSz>=0 );
  178560. *pnSz = nSz/2;
  178561. *pbDel = nSz & 0x0001;
  178562. return n;
  178563. }
  178564. /*
  178565. ** Fts5SegIter.iLeafOffset currently points to the first byte of a
  178566. ** position-list size field. Read the value of the field and store it
  178567. ** in the following variables:
  178568. **
  178569. ** Fts5SegIter.nPos
  178570. ** Fts5SegIter.bDel
  178571. **
  178572. ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
  178573. ** position list content (if any).
  178574. */
  178575. static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
  178576. if( p->rc==SQLITE_OK ){
  178577. int iOff = pIter->iLeafOffset; /* Offset to read at */
  178578. ASSERT_SZLEAF_OK(pIter->pLeaf);
  178579. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  178580. int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
  178581. pIter->bDel = 0;
  178582. pIter->nPos = 1;
  178583. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  178584. pIter->bDel = 1;
  178585. iOff++;
  178586. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  178587. pIter->nPos = 1;
  178588. iOff++;
  178589. }else{
  178590. pIter->nPos = 0;
  178591. }
  178592. }
  178593. }else{
  178594. int nSz;
  178595. fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
  178596. pIter->bDel = (nSz & 0x0001);
  178597. pIter->nPos = nSz>>1;
  178598. assert_nc( pIter->nPos>=0 );
  178599. }
  178600. pIter->iLeafOffset = iOff;
  178601. }
  178602. }
  178603. static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
  178604. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  178605. int iOff = pIter->iLeafOffset;
  178606. ASSERT_SZLEAF_OK(pIter->pLeaf);
  178607. if( iOff>=pIter->pLeaf->szLeaf ){
  178608. fts5SegIterNextPage(p, pIter);
  178609. if( pIter->pLeaf==0 ){
  178610. if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
  178611. return;
  178612. }
  178613. iOff = 4;
  178614. a = pIter->pLeaf->p;
  178615. }
  178616. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  178617. pIter->iLeafOffset = iOff;
  178618. }
  178619. /*
  178620. ** Fts5SegIter.iLeafOffset currently points to the first byte of the
  178621. ** "nSuffix" field of a term. Function parameter nKeep contains the value
  178622. ** of the "nPrefix" field (if there was one - it is passed 0 if this is
  178623. ** the first term in the segment).
  178624. **
  178625. ** This function populates:
  178626. **
  178627. ** Fts5SegIter.term
  178628. ** Fts5SegIter.rowid
  178629. **
  178630. ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
  178631. ** the first position list. The position list belonging to document
  178632. ** (Fts5SegIter.iRowid).
  178633. */
  178634. static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
  178635. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  178636. int iOff = pIter->iLeafOffset; /* Offset to read at */
  178637. int nNew; /* Bytes of new data */
  178638. iOff += fts5GetVarint32(&a[iOff], nNew);
  178639. if( iOff+nNew>pIter->pLeaf->nn ){
  178640. p->rc = FTS5_CORRUPT;
  178641. return;
  178642. }
  178643. pIter->term.n = nKeep;
  178644. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  178645. iOff += nNew;
  178646. pIter->iTermLeafOffset = iOff;
  178647. pIter->iTermLeafPgno = pIter->iLeafPgno;
  178648. pIter->iLeafOffset = iOff;
  178649. if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
  178650. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  178651. }else{
  178652. int nExtra;
  178653. pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
  178654. pIter->iEndofDoclist += nExtra;
  178655. }
  178656. fts5SegIterLoadRowid(p, pIter);
  178657. }
  178658. static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
  178659. static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
  178660. static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
  178661. static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
  178662. if( pIter->flags & FTS5_SEGITER_REVERSE ){
  178663. pIter->xNext = fts5SegIterNext_Reverse;
  178664. }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  178665. pIter->xNext = fts5SegIterNext_None;
  178666. }else{
  178667. pIter->xNext = fts5SegIterNext;
  178668. }
  178669. }
  178670. /*
  178671. ** Initialize the iterator object pIter to iterate through the entries in
  178672. ** segment pSeg. The iterator is left pointing to the first entry when
  178673. ** this function returns.
  178674. **
  178675. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  178676. ** an error has already occurred when this function is called, it is a no-op.
  178677. */
  178678. static void fts5SegIterInit(
  178679. Fts5Index *p, /* FTS index object */
  178680. Fts5StructureSegment *pSeg, /* Description of segment */
  178681. Fts5SegIter *pIter /* Object to populate */
  178682. ){
  178683. if( pSeg->pgnoFirst==0 ){
  178684. /* This happens if the segment is being used as an input to an incremental
  178685. ** merge and all data has already been "trimmed". See function
  178686. ** fts5TrimSegments() for details. In this case leave the iterator empty.
  178687. ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
  178688. ** at EOF already. */
  178689. assert( pIter->pLeaf==0 );
  178690. return;
  178691. }
  178692. if( p->rc==SQLITE_OK ){
  178693. memset(pIter, 0, sizeof(*pIter));
  178694. fts5SegIterSetNext(p, pIter);
  178695. pIter->pSeg = pSeg;
  178696. pIter->iLeafPgno = pSeg->pgnoFirst-1;
  178697. fts5SegIterNextPage(p, pIter);
  178698. }
  178699. if( p->rc==SQLITE_OK ){
  178700. pIter->iLeafOffset = 4;
  178701. assert_nc( pIter->pLeaf->nn>4 );
  178702. assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
  178703. pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
  178704. fts5SegIterLoadTerm(p, pIter, 0);
  178705. fts5SegIterLoadNPos(p, pIter);
  178706. }
  178707. }
  178708. /*
  178709. ** This function is only ever called on iterators created by calls to
  178710. ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
  178711. **
  178712. ** The iterator is in an unusual state when this function is called: the
  178713. ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
  178714. ** the position-list size field for the first relevant rowid on the page.
  178715. ** Fts5SegIter.rowid is set, but nPos and bDel are not.
  178716. **
  178717. ** This function advances the iterator so that it points to the last
  178718. ** relevant rowid on the page and, if necessary, initializes the
  178719. ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
  178720. ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
  178721. ** byte of the position list content associated with said rowid.
  178722. */
  178723. static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
  178724. int eDetail = p->pConfig->eDetail;
  178725. int n = pIter->pLeaf->szLeaf;
  178726. int i = pIter->iLeafOffset;
  178727. u8 *a = pIter->pLeaf->p;
  178728. int iRowidOffset = 0;
  178729. if( n>pIter->iEndofDoclist ){
  178730. n = pIter->iEndofDoclist;
  178731. }
  178732. ASSERT_SZLEAF_OK(pIter->pLeaf);
  178733. while( 1 ){
  178734. i64 iDelta = 0;
  178735. if( eDetail==FTS5_DETAIL_NONE ){
  178736. /* todo */
  178737. if( i<n && a[i]==0 ){
  178738. i++;
  178739. if( i<n && a[i]==0 ) i++;
  178740. }
  178741. }else{
  178742. int nPos;
  178743. int bDummy;
  178744. i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
  178745. i += nPos;
  178746. }
  178747. if( i>=n ) break;
  178748. i += fts5GetVarint(&a[i], (u64*)&iDelta);
  178749. pIter->iRowid += iDelta;
  178750. /* If necessary, grow the pIter->aRowidOffset[] array. */
  178751. if( iRowidOffset>=pIter->nRowidOffset ){
  178752. int nNew = pIter->nRowidOffset + 8;
  178753. int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
  178754. if( aNew==0 ){
  178755. p->rc = SQLITE_NOMEM;
  178756. break;
  178757. }
  178758. pIter->aRowidOffset = aNew;
  178759. pIter->nRowidOffset = nNew;
  178760. }
  178761. pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
  178762. pIter->iLeafOffset = i;
  178763. }
  178764. pIter->iRowidOffset = iRowidOffset;
  178765. fts5SegIterLoadNPos(p, pIter);
  178766. }
  178767. /*
  178768. **
  178769. */
  178770. static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
  178771. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  178772. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  178773. fts5DataRelease(pIter->pLeaf);
  178774. pIter->pLeaf = 0;
  178775. while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
  178776. Fts5Data *pNew;
  178777. pIter->iLeafPgno--;
  178778. pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
  178779. pIter->pSeg->iSegid, pIter->iLeafPgno
  178780. ));
  178781. if( pNew ){
  178782. /* iTermLeafOffset may be equal to szLeaf if the term is the last
  178783. ** thing on the page - i.e. the first rowid is on the following page.
  178784. ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
  178785. if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
  178786. assert( pIter->pLeaf==0 );
  178787. if( pIter->iTermLeafOffset<pNew->szLeaf ){
  178788. pIter->pLeaf = pNew;
  178789. pIter->iLeafOffset = pIter->iTermLeafOffset;
  178790. }
  178791. }else{
  178792. int iRowidOff;
  178793. iRowidOff = fts5LeafFirstRowidOff(pNew);
  178794. if( iRowidOff ){
  178795. pIter->pLeaf = pNew;
  178796. pIter->iLeafOffset = iRowidOff;
  178797. }
  178798. }
  178799. if( pIter->pLeaf ){
  178800. u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
  178801. pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
  178802. break;
  178803. }else{
  178804. fts5DataRelease(pNew);
  178805. }
  178806. }
  178807. }
  178808. if( pIter->pLeaf ){
  178809. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  178810. fts5SegIterReverseInitPage(p, pIter);
  178811. }
  178812. }
  178813. /*
  178814. ** Return true if the iterator passed as the second argument currently
  178815. ** points to a delete marker. A delete marker is an entry with a 0 byte
  178816. ** position-list.
  178817. */
  178818. static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
  178819. Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  178820. return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
  178821. }
  178822. /*
  178823. ** Advance iterator pIter to the next entry.
  178824. **
  178825. ** This version of fts5SegIterNext() is only used by reverse iterators.
  178826. */
  178827. static void fts5SegIterNext_Reverse(
  178828. Fts5Index *p, /* FTS5 backend object */
  178829. Fts5SegIter *pIter, /* Iterator to advance */
  178830. int *pbUnused /* Unused */
  178831. ){
  178832. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  178833. assert( pIter->pNextLeaf==0 );
  178834. UNUSED_PARAM(pbUnused);
  178835. if( pIter->iRowidOffset>0 ){
  178836. u8 *a = pIter->pLeaf->p;
  178837. int iOff;
  178838. i64 iDelta;
  178839. pIter->iRowidOffset--;
  178840. pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
  178841. fts5SegIterLoadNPos(p, pIter);
  178842. iOff = pIter->iLeafOffset;
  178843. if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
  178844. iOff += pIter->nPos;
  178845. }
  178846. fts5GetVarint(&a[iOff], (u64*)&iDelta);
  178847. pIter->iRowid -= iDelta;
  178848. }else{
  178849. fts5SegIterReverseNewPage(p, pIter);
  178850. }
  178851. }
  178852. /*
  178853. ** Advance iterator pIter to the next entry.
  178854. **
  178855. ** This version of fts5SegIterNext() is only used if detail=none and the
  178856. ** iterator is not a reverse direction iterator.
  178857. */
  178858. static void fts5SegIterNext_None(
  178859. Fts5Index *p, /* FTS5 backend object */
  178860. Fts5SegIter *pIter, /* Iterator to advance */
  178861. int *pbNewTerm /* OUT: Set for new term */
  178862. ){
  178863. int iOff;
  178864. assert( p->rc==SQLITE_OK );
  178865. assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
  178866. assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
  178867. ASSERT_SZLEAF_OK(pIter->pLeaf);
  178868. iOff = pIter->iLeafOffset;
  178869. /* Next entry is on the next page */
  178870. if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
  178871. fts5SegIterNextPage(p, pIter);
  178872. if( p->rc || pIter->pLeaf==0 ) return;
  178873. pIter->iRowid = 0;
  178874. iOff = 4;
  178875. }
  178876. if( iOff<pIter->iEndofDoclist ){
  178877. /* Next entry is on the current page */
  178878. i64 iDelta;
  178879. iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
  178880. pIter->iLeafOffset = iOff;
  178881. pIter->iRowid += iDelta;
  178882. }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
  178883. if( pIter->pSeg ){
  178884. int nKeep = 0;
  178885. if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
  178886. iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
  178887. }
  178888. pIter->iLeafOffset = iOff;
  178889. fts5SegIterLoadTerm(p, pIter, nKeep);
  178890. }else{
  178891. const u8 *pList = 0;
  178892. const char *zTerm = 0;
  178893. int nList;
  178894. sqlite3Fts5HashScanNext(p->pHash);
  178895. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  178896. if( pList==0 ) goto next_none_eof;
  178897. pIter->pLeaf->p = (u8*)pList;
  178898. pIter->pLeaf->nn = nList;
  178899. pIter->pLeaf->szLeaf = nList;
  178900. pIter->iEndofDoclist = nList;
  178901. sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
  178902. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  178903. }
  178904. if( pbNewTerm ) *pbNewTerm = 1;
  178905. }else{
  178906. goto next_none_eof;
  178907. }
  178908. fts5SegIterLoadNPos(p, pIter);
  178909. return;
  178910. next_none_eof:
  178911. fts5DataRelease(pIter->pLeaf);
  178912. pIter->pLeaf = 0;
  178913. }
  178914. /*
  178915. ** Advance iterator pIter to the next entry.
  178916. **
  178917. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
  178918. ** is not considered an error if the iterator reaches EOF. If an error has
  178919. ** already occurred when this function is called, it is a no-op.
  178920. */
  178921. static void fts5SegIterNext(
  178922. Fts5Index *p, /* FTS5 backend object */
  178923. Fts5SegIter *pIter, /* Iterator to advance */
  178924. int *pbNewTerm /* OUT: Set for new term */
  178925. ){
  178926. Fts5Data *pLeaf = pIter->pLeaf;
  178927. int iOff;
  178928. int bNewTerm = 0;
  178929. int nKeep = 0;
  178930. u8 *a;
  178931. int n;
  178932. assert( pbNewTerm==0 || *pbNewTerm==0 );
  178933. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  178934. /* Search for the end of the position list within the current page. */
  178935. a = pLeaf->p;
  178936. n = pLeaf->szLeaf;
  178937. ASSERT_SZLEAF_OK(pLeaf);
  178938. iOff = pIter->iLeafOffset + pIter->nPos;
  178939. if( iOff<n ){
  178940. /* The next entry is on the current page. */
  178941. assert_nc( iOff<=pIter->iEndofDoclist );
  178942. if( iOff>=pIter->iEndofDoclist ){
  178943. bNewTerm = 1;
  178944. if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
  178945. iOff += fts5GetVarint32(&a[iOff], nKeep);
  178946. }
  178947. }else{
  178948. u64 iDelta;
  178949. iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
  178950. pIter->iRowid += iDelta;
  178951. assert_nc( iDelta>0 );
  178952. }
  178953. pIter->iLeafOffset = iOff;
  178954. }else if( pIter->pSeg==0 ){
  178955. const u8 *pList = 0;
  178956. const char *zTerm = 0;
  178957. int nList = 0;
  178958. assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
  178959. if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
  178960. sqlite3Fts5HashScanNext(p->pHash);
  178961. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  178962. }
  178963. if( pList==0 ){
  178964. fts5DataRelease(pIter->pLeaf);
  178965. pIter->pLeaf = 0;
  178966. }else{
  178967. pIter->pLeaf->p = (u8*)pList;
  178968. pIter->pLeaf->nn = nList;
  178969. pIter->pLeaf->szLeaf = nList;
  178970. pIter->iEndofDoclist = nList+1;
  178971. sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
  178972. (u8*)zTerm);
  178973. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  178974. *pbNewTerm = 1;
  178975. }
  178976. }else{
  178977. iOff = 0;
  178978. /* Next entry is not on the current page */
  178979. while( iOff==0 ){
  178980. fts5SegIterNextPage(p, pIter);
  178981. pLeaf = pIter->pLeaf;
  178982. if( pLeaf==0 ) break;
  178983. ASSERT_SZLEAF_OK(pLeaf);
  178984. if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
  178985. iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
  178986. pIter->iLeafOffset = iOff;
  178987. if( pLeaf->nn>pLeaf->szLeaf ){
  178988. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  178989. &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
  178990. );
  178991. }
  178992. }
  178993. else if( pLeaf->nn>pLeaf->szLeaf ){
  178994. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  178995. &pLeaf->p[pLeaf->szLeaf], iOff
  178996. );
  178997. pIter->iLeafOffset = iOff;
  178998. pIter->iEndofDoclist = iOff;
  178999. bNewTerm = 1;
  179000. }
  179001. assert_nc( iOff<pLeaf->szLeaf );
  179002. if( iOff>pLeaf->szLeaf ){
  179003. p->rc = FTS5_CORRUPT;
  179004. return;
  179005. }
  179006. }
  179007. }
  179008. /* Check if the iterator is now at EOF. If so, return early. */
  179009. if( pIter->pLeaf ){
  179010. if( bNewTerm ){
  179011. if( pIter->flags & FTS5_SEGITER_ONETERM ){
  179012. fts5DataRelease(pIter->pLeaf);
  179013. pIter->pLeaf = 0;
  179014. }else{
  179015. fts5SegIterLoadTerm(p, pIter, nKeep);
  179016. fts5SegIterLoadNPos(p, pIter);
  179017. if( pbNewTerm ) *pbNewTerm = 1;
  179018. }
  179019. }else{
  179020. /* The following could be done by calling fts5SegIterLoadNPos(). But
  179021. ** this block is particularly performance critical, so equivalent
  179022. ** code is inlined.
  179023. **
  179024. ** Later: Switched back to fts5SegIterLoadNPos() because it supports
  179025. ** detail=none mode. Not ideal.
  179026. */
  179027. int nSz;
  179028. assert( p->rc==SQLITE_OK );
  179029. assert( pIter->iLeafOffset<=pIter->pLeaf->nn );
  179030. fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
  179031. pIter->bDel = (nSz & 0x0001);
  179032. pIter->nPos = nSz>>1;
  179033. assert_nc( pIter->nPos>=0 );
  179034. }
  179035. }
  179036. }
  179037. #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
  179038. #define fts5IndexSkipVarint(a, iOff) { \
  179039. int iEnd = iOff+9; \
  179040. while( (a[iOff++] & 0x80) && iOff<iEnd ); \
  179041. }
  179042. /*
  179043. ** Iterator pIter currently points to the first rowid in a doclist. This
  179044. ** function sets the iterator up so that iterates in reverse order through
  179045. ** the doclist.
  179046. */
  179047. static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
  179048. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  179049. Fts5Data *pLast = 0;
  179050. int pgnoLast = 0;
  179051. if( pDlidx ){
  179052. int iSegid = pIter->pSeg->iSegid;
  179053. pgnoLast = fts5DlidxIterPgno(pDlidx);
  179054. pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
  179055. }else{
  179056. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  179057. /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
  179058. ** position-list content for the current rowid. Back it up so that it
  179059. ** points to the start of the position-list size field. */
  179060. int iPoslist;
  179061. if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
  179062. iPoslist = pIter->iTermLeafOffset;
  179063. }else{
  179064. iPoslist = 4;
  179065. }
  179066. fts5IndexSkipVarint(pLeaf->p, iPoslist);
  179067. pIter->iLeafOffset = iPoslist;
  179068. /* If this condition is true then the largest rowid for the current
  179069. ** term may not be stored on the current page. So search forward to
  179070. ** see where said rowid really is. */
  179071. if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
  179072. int pgno;
  179073. Fts5StructureSegment *pSeg = pIter->pSeg;
  179074. /* The last rowid in the doclist may not be on the current page. Search
  179075. ** forward to find the page containing the last rowid. */
  179076. for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
  179077. i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
  179078. Fts5Data *pNew = fts5DataRead(p, iAbs);
  179079. if( pNew ){
  179080. int iRowid, bTermless;
  179081. iRowid = fts5LeafFirstRowidOff(pNew);
  179082. bTermless = fts5LeafIsTermless(pNew);
  179083. if( iRowid ){
  179084. SWAPVAL(Fts5Data*, pNew, pLast);
  179085. pgnoLast = pgno;
  179086. }
  179087. fts5DataRelease(pNew);
  179088. if( bTermless==0 ) break;
  179089. }
  179090. }
  179091. }
  179092. }
  179093. /* If pLast is NULL at this point, then the last rowid for this doclist
  179094. ** lies on the page currently indicated by the iterator. In this case
  179095. ** pIter->iLeafOffset is already set to point to the position-list size
  179096. ** field associated with the first relevant rowid on the page.
  179097. **
  179098. ** Or, if pLast is non-NULL, then it is the page that contains the last
  179099. ** rowid. In this case configure the iterator so that it points to the
  179100. ** first rowid on this page.
  179101. */
  179102. if( pLast ){
  179103. int iOff;
  179104. fts5DataRelease(pIter->pLeaf);
  179105. pIter->pLeaf = pLast;
  179106. pIter->iLeafPgno = pgnoLast;
  179107. iOff = fts5LeafFirstRowidOff(pLast);
  179108. iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
  179109. pIter->iLeafOffset = iOff;
  179110. if( fts5LeafIsTermless(pLast) ){
  179111. pIter->iEndofDoclist = pLast->nn+1;
  179112. }else{
  179113. pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
  179114. }
  179115. }
  179116. fts5SegIterReverseInitPage(p, pIter);
  179117. }
  179118. /*
  179119. ** Iterator pIter currently points to the first rowid of a doclist.
  179120. ** There is a doclist-index associated with the final term on the current
  179121. ** page. If the current term is the last term on the page, load the
  179122. ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
  179123. */
  179124. static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
  179125. int iSeg = pIter->pSeg->iSegid;
  179126. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  179127. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  179128. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  179129. assert( pIter->pDlidx==0 );
  179130. /* Check if the current doclist ends on this page. If it does, return
  179131. ** early without loading the doclist-index (as it belongs to a different
  179132. ** term. */
  179133. if( pIter->iTermLeafPgno==pIter->iLeafPgno
  179134. && pIter->iEndofDoclist<pLeaf->szLeaf
  179135. ){
  179136. return;
  179137. }
  179138. pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
  179139. }
  179140. /*
  179141. ** The iterator object passed as the second argument currently contains
  179142. ** no valid values except for the Fts5SegIter.pLeaf member variable. This
  179143. ** function searches the leaf page for a term matching (pTerm/nTerm).
  179144. **
  179145. ** If the specified term is found on the page, then the iterator is left
  179146. ** pointing to it. If argument bGe is zero and the term is not found,
  179147. ** the iterator is left pointing at EOF.
  179148. **
  179149. ** If bGe is non-zero and the specified term is not found, then the
  179150. ** iterator is left pointing to the smallest term in the segment that
  179151. ** is larger than the specified term, even if this term is not on the
  179152. ** current page.
  179153. */
  179154. static void fts5LeafSeek(
  179155. Fts5Index *p, /* Leave any error code here */
  179156. int bGe, /* True for a >= search */
  179157. Fts5SegIter *pIter, /* Iterator to seek */
  179158. const u8 *pTerm, int nTerm /* Term to search for */
  179159. ){
  179160. int iOff;
  179161. const u8 *a = pIter->pLeaf->p;
  179162. int szLeaf = pIter->pLeaf->szLeaf;
  179163. int n = pIter->pLeaf->nn;
  179164. int nMatch = 0;
  179165. int nKeep = 0;
  179166. int nNew = 0;
  179167. int iTermOff;
  179168. int iPgidx; /* Current offset in pgidx */
  179169. int bEndOfPage = 0;
  179170. assert( p->rc==SQLITE_OK );
  179171. iPgidx = szLeaf;
  179172. iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
  179173. iOff = iTermOff;
  179174. if( iOff>n ){
  179175. p->rc = FTS5_CORRUPT;
  179176. return;
  179177. }
  179178. while( 1 ){
  179179. /* Figure out how many new bytes are in this term */
  179180. fts5FastGetVarint32(a, iOff, nNew);
  179181. if( nKeep<nMatch ){
  179182. goto search_failed;
  179183. }
  179184. assert( nKeep>=nMatch );
  179185. if( nKeep==nMatch ){
  179186. int nCmp;
  179187. int i;
  179188. nCmp = MIN(nNew, nTerm-nMatch);
  179189. for(i=0; i<nCmp; i++){
  179190. if( a[iOff+i]!=pTerm[nMatch+i] ) break;
  179191. }
  179192. nMatch += i;
  179193. if( nTerm==nMatch ){
  179194. if( i==nNew ){
  179195. goto search_success;
  179196. }else{
  179197. goto search_failed;
  179198. }
  179199. }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
  179200. goto search_failed;
  179201. }
  179202. }
  179203. if( iPgidx>=n ){
  179204. bEndOfPage = 1;
  179205. break;
  179206. }
  179207. iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
  179208. iTermOff += nKeep;
  179209. iOff = iTermOff;
  179210. if( iOff>=n ){
  179211. p->rc = FTS5_CORRUPT;
  179212. return;
  179213. }
  179214. /* Read the nKeep field of the next term. */
  179215. fts5FastGetVarint32(a, iOff, nKeep);
  179216. }
  179217. search_failed:
  179218. if( bGe==0 ){
  179219. fts5DataRelease(pIter->pLeaf);
  179220. pIter->pLeaf = 0;
  179221. return;
  179222. }else if( bEndOfPage ){
  179223. do {
  179224. fts5SegIterNextPage(p, pIter);
  179225. if( pIter->pLeaf==0 ) return;
  179226. a = pIter->pLeaf->p;
  179227. if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
  179228. iPgidx = pIter->pLeaf->szLeaf;
  179229. iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
  179230. if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
  179231. p->rc = FTS5_CORRUPT;
  179232. }else{
  179233. nKeep = 0;
  179234. iTermOff = iOff;
  179235. n = pIter->pLeaf->nn;
  179236. iOff += fts5GetVarint32(&a[iOff], nNew);
  179237. break;
  179238. }
  179239. }
  179240. }while( 1 );
  179241. }
  179242. search_success:
  179243. pIter->iLeafOffset = iOff + nNew;
  179244. pIter->iTermLeafOffset = pIter->iLeafOffset;
  179245. pIter->iTermLeafPgno = pIter->iLeafPgno;
  179246. fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
  179247. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  179248. if( iPgidx>=n ){
  179249. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  179250. }else{
  179251. int nExtra;
  179252. iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
  179253. pIter->iEndofDoclist = iTermOff + nExtra;
  179254. }
  179255. pIter->iPgidxOff = iPgidx;
  179256. fts5SegIterLoadRowid(p, pIter);
  179257. fts5SegIterLoadNPos(p, pIter);
  179258. }
  179259. static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
  179260. if( p->pIdxSelect==0 ){
  179261. Fts5Config *pConfig = p->pConfig;
  179262. fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
  179263. "SELECT pgno FROM '%q'.'%q_idx' WHERE "
  179264. "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
  179265. pConfig->zDb, pConfig->zName
  179266. ));
  179267. }
  179268. return p->pIdxSelect;
  179269. }
  179270. /*
  179271. ** Initialize the object pIter to point to term pTerm/nTerm within segment
  179272. ** pSeg. If there is no such term in the index, the iterator is set to EOF.
  179273. **
  179274. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  179275. ** an error has already occurred when this function is called, it is a no-op.
  179276. */
  179277. static void fts5SegIterSeekInit(
  179278. Fts5Index *p, /* FTS5 backend */
  179279. const u8 *pTerm, int nTerm, /* Term to seek to */
  179280. int flags, /* Mask of FTS5INDEX_XXX flags */
  179281. Fts5StructureSegment *pSeg, /* Description of segment */
  179282. Fts5SegIter *pIter /* Object to populate */
  179283. ){
  179284. int iPg = 1;
  179285. int bGe = (flags & FTS5INDEX_QUERY_SCAN);
  179286. int bDlidx = 0; /* True if there is a doclist-index */
  179287. sqlite3_stmt *pIdxSelect = 0;
  179288. assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
  179289. assert( pTerm && nTerm );
  179290. memset(pIter, 0, sizeof(*pIter));
  179291. pIter->pSeg = pSeg;
  179292. /* This block sets stack variable iPg to the leaf page number that may
  179293. ** contain term (pTerm/nTerm), if it is present in the segment. */
  179294. pIdxSelect = fts5IdxSelectStmt(p);
  179295. if( p->rc ) return;
  179296. sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
  179297. sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
  179298. if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
  179299. i64 val = sqlite3_column_int(pIdxSelect, 0);
  179300. iPg = (int)(val>>1);
  179301. bDlidx = (val & 0x0001);
  179302. }
  179303. p->rc = sqlite3_reset(pIdxSelect);
  179304. if( iPg<pSeg->pgnoFirst ){
  179305. iPg = pSeg->pgnoFirst;
  179306. bDlidx = 0;
  179307. }
  179308. pIter->iLeafPgno = iPg - 1;
  179309. fts5SegIterNextPage(p, pIter);
  179310. if( pIter->pLeaf ){
  179311. fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
  179312. }
  179313. if( p->rc==SQLITE_OK && bGe==0 ){
  179314. pIter->flags |= FTS5_SEGITER_ONETERM;
  179315. if( pIter->pLeaf ){
  179316. if( flags & FTS5INDEX_QUERY_DESC ){
  179317. pIter->flags |= FTS5_SEGITER_REVERSE;
  179318. }
  179319. if( bDlidx ){
  179320. fts5SegIterLoadDlidx(p, pIter);
  179321. }
  179322. if( flags & FTS5INDEX_QUERY_DESC ){
  179323. fts5SegIterReverse(p, pIter);
  179324. }
  179325. }
  179326. }
  179327. fts5SegIterSetNext(p, pIter);
  179328. /* Either:
  179329. **
  179330. ** 1) an error has occurred, or
  179331. ** 2) the iterator points to EOF, or
  179332. ** 3) the iterator points to an entry with term (pTerm/nTerm), or
  179333. ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
  179334. ** to an entry with a term greater than or equal to (pTerm/nTerm).
  179335. */
  179336. assert( p->rc!=SQLITE_OK /* 1 */
  179337. || pIter->pLeaf==0 /* 2 */
  179338. || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
  179339. || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
  179340. );
  179341. }
  179342. /*
  179343. ** Initialize the object pIter to point to term pTerm/nTerm within the
  179344. ** in-memory hash table. If there is no such term in the hash-table, the
  179345. ** iterator is set to EOF.
  179346. **
  179347. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  179348. ** an error has already occurred when this function is called, it is a no-op.
  179349. */
  179350. static void fts5SegIterHashInit(
  179351. Fts5Index *p, /* FTS5 backend */
  179352. const u8 *pTerm, int nTerm, /* Term to seek to */
  179353. int flags, /* Mask of FTS5INDEX_XXX flags */
  179354. Fts5SegIter *pIter /* Object to populate */
  179355. ){
  179356. const u8 *pList = 0;
  179357. int nList = 0;
  179358. const u8 *z = 0;
  179359. int n = 0;
  179360. assert( p->pHash );
  179361. assert( p->rc==SQLITE_OK );
  179362. if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
  179363. p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
  179364. sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
  179365. n = (z ? (int)strlen((const char*)z) : 0);
  179366. }else{
  179367. pIter->flags |= FTS5_SEGITER_ONETERM;
  179368. sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
  179369. z = pTerm;
  179370. n = nTerm;
  179371. }
  179372. if( pList ){
  179373. Fts5Data *pLeaf;
  179374. sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
  179375. pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
  179376. if( pLeaf==0 ) return;
  179377. pLeaf->p = (u8*)pList;
  179378. pLeaf->nn = pLeaf->szLeaf = nList;
  179379. pIter->pLeaf = pLeaf;
  179380. pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
  179381. pIter->iEndofDoclist = pLeaf->nn;
  179382. if( flags & FTS5INDEX_QUERY_DESC ){
  179383. pIter->flags |= FTS5_SEGITER_REVERSE;
  179384. fts5SegIterReverseInitPage(p, pIter);
  179385. }else{
  179386. fts5SegIterLoadNPos(p, pIter);
  179387. }
  179388. }
  179389. fts5SegIterSetNext(p, pIter);
  179390. }
  179391. /*
  179392. ** Zero the iterator passed as the only argument.
  179393. */
  179394. static void fts5SegIterClear(Fts5SegIter *pIter){
  179395. fts5BufferFree(&pIter->term);
  179396. fts5DataRelease(pIter->pLeaf);
  179397. fts5DataRelease(pIter->pNextLeaf);
  179398. fts5DlidxIterFree(pIter->pDlidx);
  179399. sqlite3_free(pIter->aRowidOffset);
  179400. memset(pIter, 0, sizeof(Fts5SegIter));
  179401. }
  179402. #ifdef SQLITE_DEBUG
  179403. /*
  179404. ** This function is used as part of the big assert() procedure implemented by
  179405. ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
  179406. ** in *pRes is the correct result of comparing the current positions of the
  179407. ** two iterators.
  179408. */
  179409. static void fts5AssertComparisonResult(
  179410. Fts5Iter *pIter,
  179411. Fts5SegIter *p1,
  179412. Fts5SegIter *p2,
  179413. Fts5CResult *pRes
  179414. ){
  179415. int i1 = p1 - pIter->aSeg;
  179416. int i2 = p2 - pIter->aSeg;
  179417. if( p1->pLeaf || p2->pLeaf ){
  179418. if( p1->pLeaf==0 ){
  179419. assert( pRes->iFirst==i2 );
  179420. }else if( p2->pLeaf==0 ){
  179421. assert( pRes->iFirst==i1 );
  179422. }else{
  179423. int nMin = MIN(p1->term.n, p2->term.n);
  179424. int res = memcmp(p1->term.p, p2->term.p, nMin);
  179425. if( res==0 ) res = p1->term.n - p2->term.n;
  179426. if( res==0 ){
  179427. assert( pRes->bTermEq==1 );
  179428. assert( p1->iRowid!=p2->iRowid );
  179429. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
  179430. }else{
  179431. assert( pRes->bTermEq==0 );
  179432. }
  179433. if( res<0 ){
  179434. assert( pRes->iFirst==i1 );
  179435. }else{
  179436. assert( pRes->iFirst==i2 );
  179437. }
  179438. }
  179439. }
  179440. }
  179441. /*
  179442. ** This function is a no-op unless SQLITE_DEBUG is defined when this module
  179443. ** is compiled. In that case, this function is essentially an assert()
  179444. ** statement used to verify that the contents of the pIter->aFirst[] array
  179445. ** are correct.
  179446. */
  179447. static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
  179448. if( p->rc==SQLITE_OK ){
  179449. Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  179450. int i;
  179451. assert( (pFirst->pLeaf==0)==pIter->base.bEof );
  179452. /* Check that pIter->iSwitchRowid is set correctly. */
  179453. for(i=0; i<pIter->nSeg; i++){
  179454. Fts5SegIter *p1 = &pIter->aSeg[i];
  179455. assert( p1==pFirst
  179456. || p1->pLeaf==0
  179457. || fts5BufferCompare(&pFirst->term, &p1->term)
  179458. || p1->iRowid==pIter->iSwitchRowid
  179459. || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
  179460. );
  179461. }
  179462. for(i=0; i<pIter->nSeg; i+=2){
  179463. Fts5SegIter *p1 = &pIter->aSeg[i];
  179464. Fts5SegIter *p2 = &pIter->aSeg[i+1];
  179465. Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
  179466. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  179467. }
  179468. for(i=1; i<(pIter->nSeg / 2); i+=2){
  179469. Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
  179470. Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
  179471. Fts5CResult *pRes = &pIter->aFirst[i];
  179472. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  179473. }
  179474. }
  179475. }
  179476. #else
  179477. # define fts5AssertMultiIterSetup(x,y)
  179478. #endif
  179479. /*
  179480. ** Do the comparison necessary to populate pIter->aFirst[iOut].
  179481. **
  179482. ** If the returned value is non-zero, then it is the index of an entry
  179483. ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
  179484. ** to a key that is a duplicate of another, higher priority,
  179485. ** segment-iterator in the pSeg->aSeg[] array.
  179486. */
  179487. static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
  179488. int i1; /* Index of left-hand Fts5SegIter */
  179489. int i2; /* Index of right-hand Fts5SegIter */
  179490. int iRes;
  179491. Fts5SegIter *p1; /* Left-hand Fts5SegIter */
  179492. Fts5SegIter *p2; /* Right-hand Fts5SegIter */
  179493. Fts5CResult *pRes = &pIter->aFirst[iOut];
  179494. assert( iOut<pIter->nSeg && iOut>0 );
  179495. assert( pIter->bRev==0 || pIter->bRev==1 );
  179496. if( iOut>=(pIter->nSeg/2) ){
  179497. i1 = (iOut - pIter->nSeg/2) * 2;
  179498. i2 = i1 + 1;
  179499. }else{
  179500. i1 = pIter->aFirst[iOut*2].iFirst;
  179501. i2 = pIter->aFirst[iOut*2+1].iFirst;
  179502. }
  179503. p1 = &pIter->aSeg[i1];
  179504. p2 = &pIter->aSeg[i2];
  179505. pRes->bTermEq = 0;
  179506. if( p1->pLeaf==0 ){ /* If p1 is at EOF */
  179507. iRes = i2;
  179508. }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
  179509. iRes = i1;
  179510. }else{
  179511. int res = fts5BufferCompare(&p1->term, &p2->term);
  179512. if( res==0 ){
  179513. assert( i2>i1 );
  179514. assert( i2!=0 );
  179515. pRes->bTermEq = 1;
  179516. if( p1->iRowid==p2->iRowid ){
  179517. p1->bDel = p2->bDel;
  179518. return i2;
  179519. }
  179520. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
  179521. }
  179522. assert( res!=0 );
  179523. if( res<0 ){
  179524. iRes = i1;
  179525. }else{
  179526. iRes = i2;
  179527. }
  179528. }
  179529. pRes->iFirst = (u16)iRes;
  179530. return 0;
  179531. }
  179532. /*
  179533. ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
  179534. ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
  179535. */
  179536. static void fts5SegIterGotoPage(
  179537. Fts5Index *p, /* FTS5 backend object */
  179538. Fts5SegIter *pIter, /* Iterator to advance */
  179539. int iLeafPgno
  179540. ){
  179541. assert( iLeafPgno>pIter->iLeafPgno );
  179542. if( iLeafPgno>pIter->pSeg->pgnoLast ){
  179543. p->rc = FTS5_CORRUPT;
  179544. }else{
  179545. fts5DataRelease(pIter->pNextLeaf);
  179546. pIter->pNextLeaf = 0;
  179547. pIter->iLeafPgno = iLeafPgno-1;
  179548. fts5SegIterNextPage(p, pIter);
  179549. assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
  179550. if( p->rc==SQLITE_OK ){
  179551. int iOff;
  179552. u8 *a = pIter->pLeaf->p;
  179553. int n = pIter->pLeaf->szLeaf;
  179554. iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
  179555. if( iOff<4 || iOff>=n ){
  179556. p->rc = FTS5_CORRUPT;
  179557. }else{
  179558. iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  179559. pIter->iLeafOffset = iOff;
  179560. fts5SegIterLoadNPos(p, pIter);
  179561. }
  179562. }
  179563. }
  179564. }
  179565. /*
  179566. ** Advance the iterator passed as the second argument until it is at or
  179567. ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
  179568. ** always advanced at least once.
  179569. */
  179570. static void fts5SegIterNextFrom(
  179571. Fts5Index *p, /* FTS5 backend object */
  179572. Fts5SegIter *pIter, /* Iterator to advance */
  179573. i64 iMatch /* Advance iterator at least this far */
  179574. ){
  179575. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  179576. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  179577. int iLeafPgno = pIter->iLeafPgno;
  179578. int bMove = 1;
  179579. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  179580. assert( pIter->pDlidx );
  179581. assert( pIter->pLeaf );
  179582. if( bRev==0 ){
  179583. while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
  179584. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  179585. fts5DlidxIterNext(p, pDlidx);
  179586. }
  179587. assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
  179588. if( iLeafPgno>pIter->iLeafPgno ){
  179589. fts5SegIterGotoPage(p, pIter, iLeafPgno);
  179590. bMove = 0;
  179591. }
  179592. }else{
  179593. assert( pIter->pNextLeaf==0 );
  179594. assert( iMatch<pIter->iRowid );
  179595. while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
  179596. fts5DlidxIterPrev(p, pDlidx);
  179597. }
  179598. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  179599. assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
  179600. if( iLeafPgno<pIter->iLeafPgno ){
  179601. pIter->iLeafPgno = iLeafPgno+1;
  179602. fts5SegIterReverseNewPage(p, pIter);
  179603. bMove = 0;
  179604. }
  179605. }
  179606. do{
  179607. if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
  179608. if( pIter->pLeaf==0 ) break;
  179609. if( bRev==0 && pIter->iRowid>=iMatch ) break;
  179610. if( bRev!=0 && pIter->iRowid<=iMatch ) break;
  179611. bMove = 1;
  179612. }while( p->rc==SQLITE_OK );
  179613. }
  179614. /*
  179615. ** Free the iterator object passed as the second argument.
  179616. */
  179617. static void fts5MultiIterFree(Fts5Iter *pIter){
  179618. if( pIter ){
  179619. int i;
  179620. for(i=0; i<pIter->nSeg; i++){
  179621. fts5SegIterClear(&pIter->aSeg[i]);
  179622. }
  179623. fts5StructureRelease(pIter->pStruct);
  179624. fts5BufferFree(&pIter->poslist);
  179625. sqlite3_free(pIter);
  179626. }
  179627. }
  179628. static void fts5MultiIterAdvanced(
  179629. Fts5Index *p, /* FTS5 backend to iterate within */
  179630. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  179631. int iChanged, /* Index of sub-iterator just advanced */
  179632. int iMinset /* Minimum entry in aFirst[] to set */
  179633. ){
  179634. int i;
  179635. for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
  179636. int iEq;
  179637. if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
  179638. Fts5SegIter *pSeg = &pIter->aSeg[iEq];
  179639. assert( p->rc==SQLITE_OK );
  179640. pSeg->xNext(p, pSeg, 0);
  179641. i = pIter->nSeg + iEq;
  179642. }
  179643. }
  179644. }
  179645. /*
  179646. ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
  179647. ** points to the same term though - just a different rowid. This function
  179648. ** attempts to update the contents of the pIter->aFirst[] accordingly.
  179649. ** If it does so successfully, 0 is returned. Otherwise 1.
  179650. **
  179651. ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
  179652. ** on the iterator instead. That function does the same as this one, except
  179653. ** that it deals with more complicated cases as well.
  179654. */
  179655. static int fts5MultiIterAdvanceRowid(
  179656. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  179657. int iChanged, /* Index of sub-iterator just advanced */
  179658. Fts5SegIter **ppFirst
  179659. ){
  179660. Fts5SegIter *pNew = &pIter->aSeg[iChanged];
  179661. if( pNew->iRowid==pIter->iSwitchRowid
  179662. || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
  179663. ){
  179664. int i;
  179665. Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
  179666. pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
  179667. for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
  179668. Fts5CResult *pRes = &pIter->aFirst[i];
  179669. assert( pNew->pLeaf );
  179670. assert( pRes->bTermEq==0 || pOther->pLeaf );
  179671. if( pRes->bTermEq ){
  179672. if( pNew->iRowid==pOther->iRowid ){
  179673. return 1;
  179674. }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
  179675. pIter->iSwitchRowid = pOther->iRowid;
  179676. pNew = pOther;
  179677. }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
  179678. pIter->iSwitchRowid = pOther->iRowid;
  179679. }
  179680. }
  179681. pRes->iFirst = (u16)(pNew - pIter->aSeg);
  179682. if( i==1 ) break;
  179683. pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
  179684. }
  179685. }
  179686. *ppFirst = pNew;
  179687. return 0;
  179688. }
  179689. /*
  179690. ** Set the pIter->bEof variable based on the state of the sub-iterators.
  179691. */
  179692. static void fts5MultiIterSetEof(Fts5Iter *pIter){
  179693. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  179694. pIter->base.bEof = pSeg->pLeaf==0;
  179695. pIter->iSwitchRowid = pSeg->iRowid;
  179696. }
  179697. /*
  179698. ** Move the iterator to the next entry.
  179699. **
  179700. ** If an error occurs, an error code is left in Fts5Index.rc. It is not
  179701. ** considered an error if the iterator reaches EOF, or if it is already at
  179702. ** EOF when this function is called.
  179703. */
  179704. static void fts5MultiIterNext(
  179705. Fts5Index *p,
  179706. Fts5Iter *pIter,
  179707. int bFrom, /* True if argument iFrom is valid */
  179708. i64 iFrom /* Advance at least as far as this */
  179709. ){
  179710. int bUseFrom = bFrom;
  179711. assert( pIter->base.bEof==0 );
  179712. while( p->rc==SQLITE_OK ){
  179713. int iFirst = pIter->aFirst[1].iFirst;
  179714. int bNewTerm = 0;
  179715. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  179716. assert( p->rc==SQLITE_OK );
  179717. if( bUseFrom && pSeg->pDlidx ){
  179718. fts5SegIterNextFrom(p, pSeg, iFrom);
  179719. }else{
  179720. pSeg->xNext(p, pSeg, &bNewTerm);
  179721. }
  179722. if( pSeg->pLeaf==0 || bNewTerm
  179723. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  179724. ){
  179725. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  179726. fts5MultiIterSetEof(pIter);
  179727. pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  179728. if( pSeg->pLeaf==0 ) return;
  179729. }
  179730. fts5AssertMultiIterSetup(p, pIter);
  179731. assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
  179732. if( pIter->bSkipEmpty==0 || pSeg->nPos ){
  179733. pIter->xSetOutputs(pIter, pSeg);
  179734. return;
  179735. }
  179736. bUseFrom = 0;
  179737. }
  179738. }
  179739. static void fts5MultiIterNext2(
  179740. Fts5Index *p,
  179741. Fts5Iter *pIter,
  179742. int *pbNewTerm /* OUT: True if *might* be new term */
  179743. ){
  179744. assert( pIter->bSkipEmpty );
  179745. if( p->rc==SQLITE_OK ){
  179746. *pbNewTerm = 0;
  179747. do{
  179748. int iFirst = pIter->aFirst[1].iFirst;
  179749. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  179750. int bNewTerm = 0;
  179751. assert( p->rc==SQLITE_OK );
  179752. pSeg->xNext(p, pSeg, &bNewTerm);
  179753. if( pSeg->pLeaf==0 || bNewTerm
  179754. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  179755. ){
  179756. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  179757. fts5MultiIterSetEof(pIter);
  179758. *pbNewTerm = 1;
  179759. }
  179760. fts5AssertMultiIterSetup(p, pIter);
  179761. }while( fts5MultiIterIsEmpty(p, pIter) );
  179762. }
  179763. }
  179764. static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
  179765. UNUSED_PARAM2(pUnused1, pUnused2);
  179766. }
  179767. static Fts5Iter *fts5MultiIterAlloc(
  179768. Fts5Index *p, /* FTS5 backend to iterate within */
  179769. int nSeg
  179770. ){
  179771. Fts5Iter *pNew;
  179772. int nSlot; /* Power of two >= nSeg */
  179773. for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
  179774. pNew = fts5IdxMalloc(p,
  179775. sizeof(Fts5Iter) + /* pNew */
  179776. sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */
  179777. sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
  179778. );
  179779. if( pNew ){
  179780. pNew->nSeg = nSlot;
  179781. pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
  179782. pNew->pIndex = p;
  179783. pNew->xSetOutputs = fts5IterSetOutputs_Noop;
  179784. }
  179785. return pNew;
  179786. }
  179787. static void fts5PoslistCallback(
  179788. Fts5Index *pUnused,
  179789. void *pContext,
  179790. const u8 *pChunk, int nChunk
  179791. ){
  179792. UNUSED_PARAM(pUnused);
  179793. assert_nc( nChunk>=0 );
  179794. if( nChunk>0 ){
  179795. fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
  179796. }
  179797. }
  179798. typedef struct PoslistCallbackCtx PoslistCallbackCtx;
  179799. struct PoslistCallbackCtx {
  179800. Fts5Buffer *pBuf; /* Append to this buffer */
  179801. Fts5Colset *pColset; /* Restrict matches to this column */
  179802. int eState; /* See above */
  179803. };
  179804. typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
  179805. struct PoslistOffsetsCtx {
  179806. Fts5Buffer *pBuf; /* Append to this buffer */
  179807. Fts5Colset *pColset; /* Restrict matches to this column */
  179808. int iRead;
  179809. int iWrite;
  179810. };
  179811. /*
  179812. ** TODO: Make this more efficient!
  179813. */
  179814. static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
  179815. int i;
  179816. for(i=0; i<pColset->nCol; i++){
  179817. if( pColset->aiCol[i]==iCol ) return 1;
  179818. }
  179819. return 0;
  179820. }
  179821. static void fts5PoslistOffsetsCallback(
  179822. Fts5Index *pUnused,
  179823. void *pContext,
  179824. const u8 *pChunk, int nChunk
  179825. ){
  179826. PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
  179827. UNUSED_PARAM(pUnused);
  179828. assert_nc( nChunk>=0 );
  179829. if( nChunk>0 ){
  179830. int i = 0;
  179831. while( i<nChunk ){
  179832. int iVal;
  179833. i += fts5GetVarint32(&pChunk[i], iVal);
  179834. iVal += pCtx->iRead - 2;
  179835. pCtx->iRead = iVal;
  179836. if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
  179837. fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
  179838. pCtx->iWrite = iVal;
  179839. }
  179840. }
  179841. }
  179842. }
  179843. static void fts5PoslistFilterCallback(
  179844. Fts5Index *pUnused,
  179845. void *pContext,
  179846. const u8 *pChunk, int nChunk
  179847. ){
  179848. PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
  179849. UNUSED_PARAM(pUnused);
  179850. assert_nc( nChunk>=0 );
  179851. if( nChunk>0 ){
  179852. /* Search through to find the first varint with value 1. This is the
  179853. ** start of the next columns hits. */
  179854. int i = 0;
  179855. int iStart = 0;
  179856. if( pCtx->eState==2 ){
  179857. int iCol;
  179858. fts5FastGetVarint32(pChunk, i, iCol);
  179859. if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
  179860. pCtx->eState = 1;
  179861. fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
  179862. }else{
  179863. pCtx->eState = 0;
  179864. }
  179865. }
  179866. do {
  179867. while( i<nChunk && pChunk[i]!=0x01 ){
  179868. while( pChunk[i] & 0x80 ) i++;
  179869. i++;
  179870. }
  179871. if( pCtx->eState ){
  179872. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  179873. }
  179874. if( i<nChunk ){
  179875. int iCol;
  179876. iStart = i;
  179877. i++;
  179878. if( i>=nChunk ){
  179879. pCtx->eState = 2;
  179880. }else{
  179881. fts5FastGetVarint32(pChunk, i, iCol);
  179882. pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
  179883. if( pCtx->eState ){
  179884. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  179885. iStart = i;
  179886. }
  179887. }
  179888. }
  179889. }while( i<nChunk );
  179890. }
  179891. }
  179892. static void fts5ChunkIterate(
  179893. Fts5Index *p, /* Index object */
  179894. Fts5SegIter *pSeg, /* Poslist of this iterator */
  179895. void *pCtx, /* Context pointer for xChunk callback */
  179896. void (*xChunk)(Fts5Index*, void*, const u8*, int)
  179897. ){
  179898. int nRem = pSeg->nPos; /* Number of bytes still to come */
  179899. Fts5Data *pData = 0;
  179900. u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  179901. int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
  179902. int pgno = pSeg->iLeafPgno;
  179903. int pgnoSave = 0;
  179904. /* This function does notmwork with detail=none databases. */
  179905. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  179906. if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
  179907. pgnoSave = pgno+1;
  179908. }
  179909. while( 1 ){
  179910. xChunk(p, pCtx, pChunk, nChunk);
  179911. nRem -= nChunk;
  179912. fts5DataRelease(pData);
  179913. if( nRem<=0 ){
  179914. break;
  179915. }else{
  179916. pgno++;
  179917. pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
  179918. if( pData==0 ) break;
  179919. pChunk = &pData->p[4];
  179920. nChunk = MIN(nRem, pData->szLeaf - 4);
  179921. if( pgno==pgnoSave ){
  179922. assert( pSeg->pNextLeaf==0 );
  179923. pSeg->pNextLeaf = pData;
  179924. pData = 0;
  179925. }
  179926. }
  179927. }
  179928. }
  179929. /*
  179930. ** Iterator pIter currently points to a valid entry (not EOF). This
  179931. ** function appends the position list data for the current entry to
  179932. ** buffer pBuf. It does not make a copy of the position-list size
  179933. ** field.
  179934. */
  179935. static void fts5SegiterPoslist(
  179936. Fts5Index *p,
  179937. Fts5SegIter *pSeg,
  179938. Fts5Colset *pColset,
  179939. Fts5Buffer *pBuf
  179940. ){
  179941. if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
  179942. if( pColset==0 ){
  179943. fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
  179944. }else{
  179945. if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
  179946. PoslistCallbackCtx sCtx;
  179947. sCtx.pBuf = pBuf;
  179948. sCtx.pColset = pColset;
  179949. sCtx.eState = fts5IndexColsetTest(pColset, 0);
  179950. assert( sCtx.eState==0 || sCtx.eState==1 );
  179951. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
  179952. }else{
  179953. PoslistOffsetsCtx sCtx;
  179954. memset(&sCtx, 0, sizeof(sCtx));
  179955. sCtx.pBuf = pBuf;
  179956. sCtx.pColset = pColset;
  179957. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
  179958. }
  179959. }
  179960. }
  179961. }
  179962. /*
  179963. ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
  179964. ** the position list contains entries for column iCol, then (*pa) is set
  179965. ** to point to the sub-position-list for that column and the number of
  179966. ** bytes in it returned. Or, if the argument position list does not
  179967. ** contain any entries for column iCol, return 0.
  179968. */
  179969. static int fts5IndexExtractCol(
  179970. const u8 **pa, /* IN/OUT: Pointer to poslist */
  179971. int n, /* IN: Size of poslist in bytes */
  179972. int iCol /* Column to extract from poslist */
  179973. ){
  179974. int iCurrent = 0; /* Anything before the first 0x01 is col 0 */
  179975. const u8 *p = *pa;
  179976. const u8 *pEnd = &p[n]; /* One byte past end of position list */
  179977. while( iCol>iCurrent ){
  179978. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  179979. ** not part of a varint. Note that it is not possible for a negative
  179980. ** or extremely large varint to occur within an uncorrupted position
  179981. ** list. So the last byte of each varint may be assumed to have a clear
  179982. ** 0x80 bit. */
  179983. while( *p!=0x01 ){
  179984. while( *p++ & 0x80 );
  179985. if( p>=pEnd ) return 0;
  179986. }
  179987. *pa = p++;
  179988. iCurrent = *p++;
  179989. if( iCurrent & 0x80 ){
  179990. p--;
  179991. p += fts5GetVarint32(p, iCurrent);
  179992. }
  179993. }
  179994. if( iCol!=iCurrent ) return 0;
  179995. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  179996. ** not part of a varint */
  179997. while( p<pEnd && *p!=0x01 ){
  179998. while( *p++ & 0x80 );
  179999. }
  180000. return p - (*pa);
  180001. }
  180002. static void fts5IndexExtractColset(
  180003. int *pRc,
  180004. Fts5Colset *pColset, /* Colset to filter on */
  180005. const u8 *pPos, int nPos, /* Position list */
  180006. Fts5Buffer *pBuf /* Output buffer */
  180007. ){
  180008. if( *pRc==SQLITE_OK ){
  180009. int i;
  180010. fts5BufferZero(pBuf);
  180011. for(i=0; i<pColset->nCol; i++){
  180012. const u8 *pSub = pPos;
  180013. int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
  180014. if( nSub ){
  180015. fts5BufferAppendBlob(pRc, pBuf, nSub, pSub);
  180016. }
  180017. }
  180018. }
  180019. }
  180020. /*
  180021. ** xSetOutputs callback used by detail=none tables.
  180022. */
  180023. static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
  180024. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
  180025. pIter->base.iRowid = pSeg->iRowid;
  180026. pIter->base.nData = pSeg->nPos;
  180027. }
  180028. /*
  180029. ** xSetOutputs callback used by detail=full and detail=col tables when no
  180030. ** column filters are specified.
  180031. */
  180032. static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  180033. pIter->base.iRowid = pSeg->iRowid;
  180034. pIter->base.nData = pSeg->nPos;
  180035. assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
  180036. assert( pIter->pColset==0 );
  180037. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  180038. /* All data is stored on the current page. Populate the output
  180039. ** variables to point into the body of the page object. */
  180040. pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  180041. }else{
  180042. /* The data is distributed over two or more pages. Copy it into the
  180043. ** Fts5Iter.poslist buffer and then set the output pointer to point
  180044. ** to this buffer. */
  180045. fts5BufferZero(&pIter->poslist);
  180046. fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
  180047. pIter->base.pData = pIter->poslist.p;
  180048. }
  180049. }
  180050. /*
  180051. ** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
  180052. ** against no columns at all).
  180053. */
  180054. static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  180055. UNUSED_PARAM(pSeg);
  180056. pIter->base.nData = 0;
  180057. }
  180058. /*
  180059. ** xSetOutputs callback used by detail=col when there is a column filter
  180060. ** and there are 100 or more columns. Also called as a fallback from
  180061. ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
  180062. */
  180063. static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
  180064. fts5BufferZero(&pIter->poslist);
  180065. fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
  180066. pIter->base.iRowid = pSeg->iRowid;
  180067. pIter->base.pData = pIter->poslist.p;
  180068. pIter->base.nData = pIter->poslist.n;
  180069. }
  180070. /*
  180071. ** xSetOutputs callback used when:
  180072. **
  180073. ** * detail=col,
  180074. ** * there is a column filter, and
  180075. ** * the table contains 100 or fewer columns.
  180076. **
  180077. ** The last point is to ensure all column numbers are stored as
  180078. ** single-byte varints.
  180079. */
  180080. static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
  180081. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  180082. assert( pIter->pColset );
  180083. if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
  180084. fts5IterSetOutputs_Col(pIter, pSeg);
  180085. }else{
  180086. u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
  180087. u8 *pEnd = (u8*)&a[pSeg->nPos];
  180088. int iPrev = 0;
  180089. int *aiCol = pIter->pColset->aiCol;
  180090. int *aiColEnd = &aiCol[pIter->pColset->nCol];
  180091. u8 *aOut = pIter->poslist.p;
  180092. int iPrevOut = 0;
  180093. pIter->base.iRowid = pSeg->iRowid;
  180094. while( a<pEnd ){
  180095. iPrev += (int)a++[0] - 2;
  180096. while( *aiCol<iPrev ){
  180097. aiCol++;
  180098. if( aiCol==aiColEnd ) goto setoutputs_col_out;
  180099. }
  180100. if( *aiCol==iPrev ){
  180101. *aOut++ = (u8)((iPrev - iPrevOut) + 2);
  180102. iPrevOut = iPrev;
  180103. }
  180104. }
  180105. setoutputs_col_out:
  180106. pIter->base.pData = pIter->poslist.p;
  180107. pIter->base.nData = aOut - pIter->poslist.p;
  180108. }
  180109. }
  180110. /*
  180111. ** xSetOutputs callback used by detail=full when there is a column filter.
  180112. */
  180113. static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
  180114. Fts5Colset *pColset = pIter->pColset;
  180115. pIter->base.iRowid = pSeg->iRowid;
  180116. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
  180117. assert( pColset );
  180118. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  180119. /* All data is stored on the current page. Populate the output
  180120. ** variables to point into the body of the page object. */
  180121. const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  180122. if( pColset->nCol==1 ){
  180123. pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
  180124. pIter->base.pData = a;
  180125. }else{
  180126. int *pRc = &pIter->pIndex->rc;
  180127. fts5BufferZero(&pIter->poslist);
  180128. fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, &pIter->poslist);
  180129. pIter->base.pData = pIter->poslist.p;
  180130. pIter->base.nData = pIter->poslist.n;
  180131. }
  180132. }else{
  180133. /* The data is distributed over two or more pages. Copy it into the
  180134. ** Fts5Iter.poslist buffer and then set the output pointer to point
  180135. ** to this buffer. */
  180136. fts5BufferZero(&pIter->poslist);
  180137. fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
  180138. pIter->base.pData = pIter->poslist.p;
  180139. pIter->base.nData = pIter->poslist.n;
  180140. }
  180141. }
  180142. static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
  180143. if( *pRc==SQLITE_OK ){
  180144. Fts5Config *pConfig = pIter->pIndex->pConfig;
  180145. if( pConfig->eDetail==FTS5_DETAIL_NONE ){
  180146. pIter->xSetOutputs = fts5IterSetOutputs_None;
  180147. }
  180148. else if( pIter->pColset==0 ){
  180149. pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
  180150. }
  180151. else if( pIter->pColset->nCol==0 ){
  180152. pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
  180153. }
  180154. else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
  180155. pIter->xSetOutputs = fts5IterSetOutputs_Full;
  180156. }
  180157. else{
  180158. assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  180159. if( pConfig->nCol<=100 ){
  180160. pIter->xSetOutputs = fts5IterSetOutputs_Col100;
  180161. sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
  180162. }else{
  180163. pIter->xSetOutputs = fts5IterSetOutputs_Col;
  180164. }
  180165. }
  180166. }
  180167. }
  180168. /*
  180169. ** Allocate a new Fts5Iter object.
  180170. **
  180171. ** The new object will be used to iterate through data in structure pStruct.
  180172. ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
  180173. ** is zero or greater, data from the first nSegment segments on level iLevel
  180174. ** is merged.
  180175. **
  180176. ** The iterator initially points to the first term/rowid entry in the
  180177. ** iterated data.
  180178. */
  180179. static void fts5MultiIterNew(
  180180. Fts5Index *p, /* FTS5 backend to iterate within */
  180181. Fts5Structure *pStruct, /* Structure of specific index */
  180182. int flags, /* FTS5INDEX_QUERY_XXX flags */
  180183. Fts5Colset *pColset, /* Colset to filter on (or NULL) */
  180184. const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
  180185. int iLevel, /* Level to iterate (-1 for all) */
  180186. int nSegment, /* Number of segments to merge (iLevel>=0) */
  180187. Fts5Iter **ppOut /* New object */
  180188. ){
  180189. int nSeg = 0; /* Number of segment-iters in use */
  180190. int iIter = 0; /* */
  180191. int iSeg; /* Used to iterate through segments */
  180192. Fts5StructureLevel *pLvl;
  180193. Fts5Iter *pNew;
  180194. assert( (pTerm==0 && nTerm==0) || iLevel<0 );
  180195. /* Allocate space for the new multi-seg-iterator. */
  180196. if( p->rc==SQLITE_OK ){
  180197. if( iLevel<0 ){
  180198. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  180199. nSeg = pStruct->nSegment;
  180200. nSeg += (p->pHash ? 1 : 0);
  180201. }else{
  180202. nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
  180203. }
  180204. }
  180205. *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
  180206. if( pNew==0 ) return;
  180207. pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
  180208. pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
  180209. pNew->pStruct = pStruct;
  180210. pNew->pColset = pColset;
  180211. fts5StructureRef(pStruct);
  180212. if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
  180213. fts5IterSetOutputCb(&p->rc, pNew);
  180214. }
  180215. /* Initialize each of the component segment iterators. */
  180216. if( p->rc==SQLITE_OK ){
  180217. if( iLevel<0 ){
  180218. Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
  180219. if( p->pHash ){
  180220. /* Add a segment iterator for the current contents of the hash table. */
  180221. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  180222. fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
  180223. }
  180224. for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
  180225. for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
  180226. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  180227. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  180228. if( pTerm==0 ){
  180229. fts5SegIterInit(p, pSeg, pIter);
  180230. }else{
  180231. fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
  180232. }
  180233. }
  180234. }
  180235. }else{
  180236. pLvl = &pStruct->aLevel[iLevel];
  180237. for(iSeg=nSeg-1; iSeg>=0; iSeg--){
  180238. fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
  180239. }
  180240. }
  180241. assert( iIter==nSeg );
  180242. }
  180243. /* If the above was successful, each component iterators now points
  180244. ** to the first entry in its segment. In this case initialize the
  180245. ** aFirst[] array. Or, if an error has occurred, free the iterator
  180246. ** object and set the output variable to NULL. */
  180247. if( p->rc==SQLITE_OK ){
  180248. for(iIter=pNew->nSeg-1; iIter>0; iIter--){
  180249. int iEq;
  180250. if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
  180251. Fts5SegIter *pSeg = &pNew->aSeg[iEq];
  180252. if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
  180253. fts5MultiIterAdvanced(p, pNew, iEq, iIter);
  180254. }
  180255. }
  180256. fts5MultiIterSetEof(pNew);
  180257. fts5AssertMultiIterSetup(p, pNew);
  180258. if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
  180259. fts5MultiIterNext(p, pNew, 0, 0);
  180260. }else if( pNew->base.bEof==0 ){
  180261. Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
  180262. pNew->xSetOutputs(pNew, pSeg);
  180263. }
  180264. }else{
  180265. fts5MultiIterFree(pNew);
  180266. *ppOut = 0;
  180267. }
  180268. }
  180269. /*
  180270. ** Create an Fts5Iter that iterates through the doclist provided
  180271. ** as the second argument.
  180272. */
  180273. static void fts5MultiIterNew2(
  180274. Fts5Index *p, /* FTS5 backend to iterate within */
  180275. Fts5Data *pData, /* Doclist to iterate through */
  180276. int bDesc, /* True for descending rowid order */
  180277. Fts5Iter **ppOut /* New object */
  180278. ){
  180279. Fts5Iter *pNew;
  180280. pNew = fts5MultiIterAlloc(p, 2);
  180281. if( pNew ){
  180282. Fts5SegIter *pIter = &pNew->aSeg[1];
  180283. pIter->flags = FTS5_SEGITER_ONETERM;
  180284. if( pData->szLeaf>0 ){
  180285. pIter->pLeaf = pData;
  180286. pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
  180287. pIter->iEndofDoclist = pData->nn;
  180288. pNew->aFirst[1].iFirst = 1;
  180289. if( bDesc ){
  180290. pNew->bRev = 1;
  180291. pIter->flags |= FTS5_SEGITER_REVERSE;
  180292. fts5SegIterReverseInitPage(p, pIter);
  180293. }else{
  180294. fts5SegIterLoadNPos(p, pIter);
  180295. }
  180296. pData = 0;
  180297. }else{
  180298. pNew->base.bEof = 1;
  180299. }
  180300. fts5SegIterSetNext(p, pIter);
  180301. *ppOut = pNew;
  180302. }
  180303. fts5DataRelease(pData);
  180304. }
  180305. /*
  180306. ** Return true if the iterator is at EOF or if an error has occurred.
  180307. ** False otherwise.
  180308. */
  180309. static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
  180310. assert( p->rc
  180311. || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
  180312. );
  180313. return (p->rc || pIter->base.bEof);
  180314. }
  180315. /*
  180316. ** Return the rowid of the entry that the iterator currently points
  180317. ** to. If the iterator points to EOF when this function is called the
  180318. ** results are undefined.
  180319. */
  180320. static i64 fts5MultiIterRowid(Fts5Iter *pIter){
  180321. assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
  180322. return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
  180323. }
  180324. /*
  180325. ** Move the iterator to the next entry at or following iMatch.
  180326. */
  180327. static void fts5MultiIterNextFrom(
  180328. Fts5Index *p,
  180329. Fts5Iter *pIter,
  180330. i64 iMatch
  180331. ){
  180332. while( 1 ){
  180333. i64 iRowid;
  180334. fts5MultiIterNext(p, pIter, 1, iMatch);
  180335. if( fts5MultiIterEof(p, pIter) ) break;
  180336. iRowid = fts5MultiIterRowid(pIter);
  180337. if( pIter->bRev==0 && iRowid>=iMatch ) break;
  180338. if( pIter->bRev!=0 && iRowid<=iMatch ) break;
  180339. }
  180340. }
  180341. /*
  180342. ** Return a pointer to a buffer containing the term associated with the
  180343. ** entry that the iterator currently points to.
  180344. */
  180345. static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
  180346. Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  180347. *pn = p->term.n;
  180348. return p->term.p;
  180349. }
  180350. /*
  180351. ** Allocate a new segment-id for the structure pStruct. The new segment
  180352. ** id must be between 1 and 65335 inclusive, and must not be used by
  180353. ** any currently existing segment. If a free segment id cannot be found,
  180354. ** SQLITE_FULL is returned.
  180355. **
  180356. ** If an error has already occurred, this function is a no-op. 0 is
  180357. ** returned in this case.
  180358. */
  180359. static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
  180360. int iSegid = 0;
  180361. if( p->rc==SQLITE_OK ){
  180362. if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
  180363. p->rc = SQLITE_FULL;
  180364. }else{
  180365. /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
  180366. ** array is 63 elements, or 252 bytes, in size. */
  180367. u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
  180368. int iLvl, iSeg;
  180369. int i;
  180370. u32 mask;
  180371. memset(aUsed, 0, sizeof(aUsed));
  180372. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  180373. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  180374. int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
  180375. if( iId<=FTS5_MAX_SEGMENT ){
  180376. aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32);
  180377. }
  180378. }
  180379. }
  180380. for(i=0; aUsed[i]==0xFFFFFFFF; i++);
  180381. mask = aUsed[i];
  180382. for(iSegid=0; mask & (1 << iSegid); iSegid++);
  180383. iSegid += 1 + i*32;
  180384. #ifdef SQLITE_DEBUG
  180385. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  180386. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  180387. assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
  180388. }
  180389. }
  180390. assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
  180391. {
  180392. sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
  180393. if( p->rc==SQLITE_OK ){
  180394. u8 aBlob[2] = {0xff, 0xff};
  180395. sqlite3_bind_int(pIdxSelect, 1, iSegid);
  180396. sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
  180397. assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
  180398. p->rc = sqlite3_reset(pIdxSelect);
  180399. }
  180400. }
  180401. #endif
  180402. }
  180403. }
  180404. return iSegid;
  180405. }
  180406. /*
  180407. ** Discard all data currently cached in the hash-tables.
  180408. */
  180409. static void fts5IndexDiscardData(Fts5Index *p){
  180410. assert( p->pHash || p->nPendingData==0 );
  180411. if( p->pHash ){
  180412. sqlite3Fts5HashClear(p->pHash);
  180413. p->nPendingData = 0;
  180414. }
  180415. }
  180416. /*
  180417. ** Return the size of the prefix, in bytes, that buffer
  180418. ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
  180419. **
  180420. ** Buffer (pNew/<length-unknown>) is guaranteed to be greater
  180421. ** than buffer (pOld/nOld).
  180422. */
  180423. static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
  180424. int i;
  180425. for(i=0; i<nOld; i++){
  180426. if( pOld[i]!=pNew[i] ) break;
  180427. }
  180428. return i;
  180429. }
  180430. static void fts5WriteDlidxClear(
  180431. Fts5Index *p,
  180432. Fts5SegWriter *pWriter,
  180433. int bFlush /* If true, write dlidx to disk */
  180434. ){
  180435. int i;
  180436. assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
  180437. for(i=0; i<pWriter->nDlidx; i++){
  180438. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  180439. if( pDlidx->buf.n==0 ) break;
  180440. if( bFlush ){
  180441. assert( pDlidx->pgno!=0 );
  180442. fts5DataWrite(p,
  180443. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  180444. pDlidx->buf.p, pDlidx->buf.n
  180445. );
  180446. }
  180447. sqlite3Fts5BufferZero(&pDlidx->buf);
  180448. pDlidx->bPrevValid = 0;
  180449. }
  180450. }
  180451. /*
  180452. ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
  180453. ** Any new array elements are zeroed before returning.
  180454. */
  180455. static int fts5WriteDlidxGrow(
  180456. Fts5Index *p,
  180457. Fts5SegWriter *pWriter,
  180458. int nLvl
  180459. ){
  180460. if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
  180461. Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
  180462. pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
  180463. );
  180464. if( aDlidx==0 ){
  180465. p->rc = SQLITE_NOMEM;
  180466. }else{
  180467. int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
  180468. memset(&aDlidx[pWriter->nDlidx], 0, nByte);
  180469. pWriter->aDlidx = aDlidx;
  180470. pWriter->nDlidx = nLvl;
  180471. }
  180472. }
  180473. return p->rc;
  180474. }
  180475. /*
  180476. ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
  180477. ** enough, flush it to disk and return 1. Otherwise discard it and return
  180478. ** zero.
  180479. */
  180480. static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
  180481. int bFlag = 0;
  180482. /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
  180483. ** to the database, also write the doclist-index to disk. */
  180484. if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
  180485. bFlag = 1;
  180486. }
  180487. fts5WriteDlidxClear(p, pWriter, bFlag);
  180488. pWriter->nEmpty = 0;
  180489. return bFlag;
  180490. }
  180491. /*
  180492. ** This function is called whenever processing of the doclist for the
  180493. ** last term on leaf page (pWriter->iBtPage) is completed.
  180494. **
  180495. ** The doclist-index for that term is currently stored in-memory within the
  180496. ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
  180497. ** writes it out to disk. Or, if it is too small to bother with, discards
  180498. ** it.
  180499. **
  180500. ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
  180501. */
  180502. static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
  180503. int bFlag;
  180504. assert( pWriter->iBtPage || pWriter->nEmpty==0 );
  180505. if( pWriter->iBtPage==0 ) return;
  180506. bFlag = fts5WriteFlushDlidx(p, pWriter);
  180507. if( p->rc==SQLITE_OK ){
  180508. const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
  180509. /* The following was already done in fts5WriteInit(): */
  180510. /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
  180511. sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
  180512. sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
  180513. sqlite3_step(p->pIdxWriter);
  180514. p->rc = sqlite3_reset(p->pIdxWriter);
  180515. }
  180516. pWriter->iBtPage = 0;
  180517. }
  180518. /*
  180519. ** This is called once for each leaf page except the first that contains
  180520. ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
  180521. ** is larger than all terms written to earlier leaves, and equal to or
  180522. ** smaller than the first term on the new leaf.
  180523. **
  180524. ** If an error occurs, an error code is left in Fts5Index.rc. If an error
  180525. ** has already occurred when this function is called, it is a no-op.
  180526. */
  180527. static void fts5WriteBtreeTerm(
  180528. Fts5Index *p, /* FTS5 backend object */
  180529. Fts5SegWriter *pWriter, /* Writer object */
  180530. int nTerm, const u8 *pTerm /* First term on new page */
  180531. ){
  180532. fts5WriteFlushBtree(p, pWriter);
  180533. fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
  180534. pWriter->iBtPage = pWriter->writer.pgno;
  180535. }
  180536. /*
  180537. ** This function is called when flushing a leaf page that contains no
  180538. ** terms at all to disk.
  180539. */
  180540. static void fts5WriteBtreeNoTerm(
  180541. Fts5Index *p, /* FTS5 backend object */
  180542. Fts5SegWriter *pWriter /* Writer object */
  180543. ){
  180544. /* If there were no rowids on the leaf page either and the doclist-index
  180545. ** has already been started, append an 0x00 byte to it. */
  180546. if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
  180547. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
  180548. assert( pDlidx->bPrevValid );
  180549. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
  180550. }
  180551. /* Increment the "number of sequential leaves without a term" counter. */
  180552. pWriter->nEmpty++;
  180553. }
  180554. static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
  180555. i64 iRowid;
  180556. int iOff;
  180557. iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
  180558. fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
  180559. return iRowid;
  180560. }
  180561. /*
  180562. ** Rowid iRowid has just been appended to the current leaf page. It is the
  180563. ** first on the page. This function appends an appropriate entry to the current
  180564. ** doclist-index.
  180565. */
  180566. static void fts5WriteDlidxAppend(
  180567. Fts5Index *p,
  180568. Fts5SegWriter *pWriter,
  180569. i64 iRowid
  180570. ){
  180571. int i;
  180572. int bDone = 0;
  180573. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  180574. i64 iVal;
  180575. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  180576. if( pDlidx->buf.n>=p->pConfig->pgsz ){
  180577. /* The current doclist-index page is full. Write it to disk and push
  180578. ** a copy of iRowid (which will become the first rowid on the next
  180579. ** doclist-index leaf page) up into the next level of the b-tree
  180580. ** hierarchy. If the node being flushed is currently the root node,
  180581. ** also push its first rowid upwards. */
  180582. pDlidx->buf.p[0] = 0x01; /* Not the root node */
  180583. fts5DataWrite(p,
  180584. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  180585. pDlidx->buf.p, pDlidx->buf.n
  180586. );
  180587. fts5WriteDlidxGrow(p, pWriter, i+2);
  180588. pDlidx = &pWriter->aDlidx[i];
  180589. if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
  180590. i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
  180591. /* This was the root node. Push its first rowid up to the new root. */
  180592. pDlidx[1].pgno = pDlidx->pgno;
  180593. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
  180594. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
  180595. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
  180596. pDlidx[1].bPrevValid = 1;
  180597. pDlidx[1].iPrev = iFirst;
  180598. }
  180599. sqlite3Fts5BufferZero(&pDlidx->buf);
  180600. pDlidx->bPrevValid = 0;
  180601. pDlidx->pgno++;
  180602. }else{
  180603. bDone = 1;
  180604. }
  180605. if( pDlidx->bPrevValid ){
  180606. iVal = iRowid - pDlidx->iPrev;
  180607. }else{
  180608. i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
  180609. assert( pDlidx->buf.n==0 );
  180610. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
  180611. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
  180612. iVal = iRowid;
  180613. }
  180614. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
  180615. pDlidx->bPrevValid = 1;
  180616. pDlidx->iPrev = iRowid;
  180617. }
  180618. }
  180619. static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
  180620. static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
  180621. Fts5PageWriter *pPage = &pWriter->writer;
  180622. i64 iRowid;
  180623. assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
  180624. /* Set the szLeaf header field. */
  180625. assert( 0==fts5GetU16(&pPage->buf.p[2]) );
  180626. fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
  180627. if( pWriter->bFirstTermInPage ){
  180628. /* No term was written to this page. */
  180629. assert( pPage->pgidx.n==0 );
  180630. fts5WriteBtreeNoTerm(p, pWriter);
  180631. }else{
  180632. /* Append the pgidx to the page buffer. Set the szLeaf header field. */
  180633. fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
  180634. }
  180635. /* Write the page out to disk */
  180636. iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
  180637. fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
  180638. /* Initialize the next page. */
  180639. fts5BufferZero(&pPage->buf);
  180640. fts5BufferZero(&pPage->pgidx);
  180641. fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
  180642. pPage->iPrevPgidx = 0;
  180643. pPage->pgno++;
  180644. /* Increase the leaves written counter */
  180645. pWriter->nLeafWritten++;
  180646. /* The new leaf holds no terms or rowids */
  180647. pWriter->bFirstTermInPage = 1;
  180648. pWriter->bFirstRowidInPage = 1;
  180649. }
  180650. /*
  180651. ** Append term pTerm/nTerm to the segment being written by the writer passed
  180652. ** as the second argument.
  180653. **
  180654. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  180655. ** already occurred, this function is a no-op.
  180656. */
  180657. static void fts5WriteAppendTerm(
  180658. Fts5Index *p,
  180659. Fts5SegWriter *pWriter,
  180660. int nTerm, const u8 *pTerm
  180661. ){
  180662. int nPrefix; /* Bytes of prefix compression for term */
  180663. Fts5PageWriter *pPage = &pWriter->writer;
  180664. Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
  180665. assert( p->rc==SQLITE_OK );
  180666. assert( pPage->buf.n>=4 );
  180667. assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
  180668. /* If the current leaf page is full, flush it to disk. */
  180669. if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
  180670. if( pPage->buf.n>4 ){
  180671. fts5WriteFlushLeaf(p, pWriter);
  180672. }
  180673. fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
  180674. }
  180675. /* TODO1: Updating pgidx here. */
  180676. pPgidx->n += sqlite3Fts5PutVarint(
  180677. &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
  180678. );
  180679. pPage->iPrevPgidx = pPage->buf.n;
  180680. #if 0
  180681. fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
  180682. pPgidx->n += 2;
  180683. #endif
  180684. if( pWriter->bFirstTermInPage ){
  180685. nPrefix = 0;
  180686. if( pPage->pgno!=1 ){
  180687. /* This is the first term on a leaf that is not the leftmost leaf in
  180688. ** the segment b-tree. In this case it is necessary to add a term to
  180689. ** the b-tree hierarchy that is (a) larger than the largest term
  180690. ** already written to the segment and (b) smaller than or equal to
  180691. ** this term. In other words, a prefix of (pTerm/nTerm) that is one
  180692. ** byte longer than the longest prefix (pTerm/nTerm) shares with the
  180693. ** previous term.
  180694. **
  180695. ** Usually, the previous term is available in pPage->term. The exception
  180696. ** is if this is the first term written in an incremental-merge step.
  180697. ** In this case the previous term is not available, so just write a
  180698. ** copy of (pTerm/nTerm) into the parent node. This is slightly
  180699. ** inefficient, but still correct. */
  180700. int n = nTerm;
  180701. if( pPage->term.n ){
  180702. n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
  180703. }
  180704. fts5WriteBtreeTerm(p, pWriter, n, pTerm);
  180705. pPage = &pWriter->writer;
  180706. }
  180707. }else{
  180708. nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
  180709. fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
  180710. }
  180711. /* Append the number of bytes of new data, then the term data itself
  180712. ** to the page. */
  180713. fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
  180714. fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
  180715. /* Update the Fts5PageWriter.term field. */
  180716. fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
  180717. pWriter->bFirstTermInPage = 0;
  180718. pWriter->bFirstRowidInPage = 0;
  180719. pWriter->bFirstRowidInDoclist = 1;
  180720. assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
  180721. pWriter->aDlidx[0].pgno = pPage->pgno;
  180722. }
  180723. /*
  180724. ** Append a rowid and position-list size field to the writers output.
  180725. */
  180726. static void fts5WriteAppendRowid(
  180727. Fts5Index *p,
  180728. Fts5SegWriter *pWriter,
  180729. i64 iRowid
  180730. ){
  180731. if( p->rc==SQLITE_OK ){
  180732. Fts5PageWriter *pPage = &pWriter->writer;
  180733. if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
  180734. fts5WriteFlushLeaf(p, pWriter);
  180735. }
  180736. /* If this is to be the first rowid written to the page, set the
  180737. ** rowid-pointer in the page-header. Also append a value to the dlidx
  180738. ** buffer, in case a doclist-index is required. */
  180739. if( pWriter->bFirstRowidInPage ){
  180740. fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
  180741. fts5WriteDlidxAppend(p, pWriter, iRowid);
  180742. }
  180743. /* Write the rowid. */
  180744. if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
  180745. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
  180746. }else{
  180747. assert( p->rc || iRowid>pWriter->iPrevRowid );
  180748. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
  180749. }
  180750. pWriter->iPrevRowid = iRowid;
  180751. pWriter->bFirstRowidInDoclist = 0;
  180752. pWriter->bFirstRowidInPage = 0;
  180753. }
  180754. }
  180755. static void fts5WriteAppendPoslistData(
  180756. Fts5Index *p,
  180757. Fts5SegWriter *pWriter,
  180758. const u8 *aData,
  180759. int nData
  180760. ){
  180761. Fts5PageWriter *pPage = &pWriter->writer;
  180762. const u8 *a = aData;
  180763. int n = nData;
  180764. assert( p->pConfig->pgsz>0 );
  180765. while( p->rc==SQLITE_OK
  180766. && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
  180767. ){
  180768. int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
  180769. int nCopy = 0;
  180770. while( nCopy<nReq ){
  180771. i64 dummy;
  180772. nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
  180773. }
  180774. fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
  180775. a += nCopy;
  180776. n -= nCopy;
  180777. fts5WriteFlushLeaf(p, pWriter);
  180778. }
  180779. if( n>0 ){
  180780. fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
  180781. }
  180782. }
  180783. /*
  180784. ** Flush any data cached by the writer object to the database. Free any
  180785. ** allocations associated with the writer.
  180786. */
  180787. static void fts5WriteFinish(
  180788. Fts5Index *p,
  180789. Fts5SegWriter *pWriter, /* Writer object */
  180790. int *pnLeaf /* OUT: Number of leaf pages in b-tree */
  180791. ){
  180792. int i;
  180793. Fts5PageWriter *pLeaf = &pWriter->writer;
  180794. if( p->rc==SQLITE_OK ){
  180795. assert( pLeaf->pgno>=1 );
  180796. if( pLeaf->buf.n>4 ){
  180797. fts5WriteFlushLeaf(p, pWriter);
  180798. }
  180799. *pnLeaf = pLeaf->pgno-1;
  180800. if( pLeaf->pgno>1 ){
  180801. fts5WriteFlushBtree(p, pWriter);
  180802. }
  180803. }
  180804. fts5BufferFree(&pLeaf->term);
  180805. fts5BufferFree(&pLeaf->buf);
  180806. fts5BufferFree(&pLeaf->pgidx);
  180807. fts5BufferFree(&pWriter->btterm);
  180808. for(i=0; i<pWriter->nDlidx; i++){
  180809. sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
  180810. }
  180811. sqlite3_free(pWriter->aDlidx);
  180812. }
  180813. static void fts5WriteInit(
  180814. Fts5Index *p,
  180815. Fts5SegWriter *pWriter,
  180816. int iSegid
  180817. ){
  180818. const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
  180819. memset(pWriter, 0, sizeof(Fts5SegWriter));
  180820. pWriter->iSegid = iSegid;
  180821. fts5WriteDlidxGrow(p, pWriter, 1);
  180822. pWriter->writer.pgno = 1;
  180823. pWriter->bFirstTermInPage = 1;
  180824. pWriter->iBtPage = 1;
  180825. assert( pWriter->writer.buf.n==0 );
  180826. assert( pWriter->writer.pgidx.n==0 );
  180827. /* Grow the two buffers to pgsz + padding bytes in size. */
  180828. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
  180829. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
  180830. if( p->pIdxWriter==0 ){
  180831. Fts5Config *pConfig = p->pConfig;
  180832. fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
  180833. "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
  180834. pConfig->zDb, pConfig->zName
  180835. ));
  180836. }
  180837. if( p->rc==SQLITE_OK ){
  180838. /* Initialize the 4-byte leaf-page header to 0x00. */
  180839. memset(pWriter->writer.buf.p, 0, 4);
  180840. pWriter->writer.buf.n = 4;
  180841. /* Bind the current output segment id to the index-writer. This is an
  180842. ** optimization over binding the same value over and over as rows are
  180843. ** inserted into %_idx by the current writer. */
  180844. sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
  180845. }
  180846. }
  180847. /*
  180848. ** Iterator pIter was used to iterate through the input segments of on an
  180849. ** incremental merge operation. This function is called if the incremental
  180850. ** merge step has finished but the input has not been completely exhausted.
  180851. */
  180852. static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
  180853. int i;
  180854. Fts5Buffer buf;
  180855. memset(&buf, 0, sizeof(Fts5Buffer));
  180856. for(i=0; i<pIter->nSeg; i++){
  180857. Fts5SegIter *pSeg = &pIter->aSeg[i];
  180858. if( pSeg->pSeg==0 ){
  180859. /* no-op */
  180860. }else if( pSeg->pLeaf==0 ){
  180861. /* All keys from this input segment have been transfered to the output.
  180862. ** Set both the first and last page-numbers to 0 to indicate that the
  180863. ** segment is now empty. */
  180864. pSeg->pSeg->pgnoLast = 0;
  180865. pSeg->pSeg->pgnoFirst = 0;
  180866. }else{
  180867. int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
  180868. i64 iLeafRowid;
  180869. Fts5Data *pData;
  180870. int iId = pSeg->pSeg->iSegid;
  180871. u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
  180872. iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
  180873. pData = fts5DataRead(p, iLeafRowid);
  180874. if( pData ){
  180875. fts5BufferZero(&buf);
  180876. fts5BufferGrow(&p->rc, &buf, pData->nn);
  180877. fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
  180878. fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
  180879. fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
  180880. fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
  180881. if( p->rc==SQLITE_OK ){
  180882. /* Set the szLeaf field */
  180883. fts5PutU16(&buf.p[2], (u16)buf.n);
  180884. }
  180885. /* Set up the new page-index array */
  180886. fts5BufferAppendVarint(&p->rc, &buf, 4);
  180887. if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
  180888. && pSeg->iEndofDoclist<pData->szLeaf
  180889. ){
  180890. int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
  180891. fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
  180892. fts5BufferAppendBlob(&p->rc, &buf,
  180893. pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
  180894. );
  180895. }
  180896. fts5DataRelease(pData);
  180897. pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
  180898. fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
  180899. fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
  180900. }
  180901. }
  180902. }
  180903. fts5BufferFree(&buf);
  180904. }
  180905. static void fts5MergeChunkCallback(
  180906. Fts5Index *p,
  180907. void *pCtx,
  180908. const u8 *pChunk, int nChunk
  180909. ){
  180910. Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
  180911. fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
  180912. }
  180913. /*
  180914. **
  180915. */
  180916. static void fts5IndexMergeLevel(
  180917. Fts5Index *p, /* FTS5 backend object */
  180918. Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
  180919. int iLvl, /* Level to read input from */
  180920. int *pnRem /* Write up to this many output leaves */
  180921. ){
  180922. Fts5Structure *pStruct = *ppStruct;
  180923. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  180924. Fts5StructureLevel *pLvlOut;
  180925. Fts5Iter *pIter = 0; /* Iterator to read input data */
  180926. int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
  180927. int nInput; /* Number of input segments */
  180928. Fts5SegWriter writer; /* Writer object */
  180929. Fts5StructureSegment *pSeg; /* Output segment */
  180930. Fts5Buffer term;
  180931. int bOldest; /* True if the output segment is the oldest */
  180932. int eDetail = p->pConfig->eDetail;
  180933. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  180934. int bTermWritten = 0; /* True if current term already output */
  180935. assert( iLvl<pStruct->nLevel );
  180936. assert( pLvl->nMerge<=pLvl->nSeg );
  180937. memset(&writer, 0, sizeof(Fts5SegWriter));
  180938. memset(&term, 0, sizeof(Fts5Buffer));
  180939. if( pLvl->nMerge ){
  180940. pLvlOut = &pStruct->aLevel[iLvl+1];
  180941. assert( pLvlOut->nSeg>0 );
  180942. nInput = pLvl->nMerge;
  180943. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
  180944. fts5WriteInit(p, &writer, pSeg->iSegid);
  180945. writer.writer.pgno = pSeg->pgnoLast+1;
  180946. writer.iBtPage = 0;
  180947. }else{
  180948. int iSegid = fts5AllocateSegid(p, pStruct);
  180949. /* Extend the Fts5Structure object as required to ensure the output
  180950. ** segment exists. */
  180951. if( iLvl==pStruct->nLevel-1 ){
  180952. fts5StructureAddLevel(&p->rc, ppStruct);
  180953. pStruct = *ppStruct;
  180954. }
  180955. fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
  180956. if( p->rc ) return;
  180957. pLvl = &pStruct->aLevel[iLvl];
  180958. pLvlOut = &pStruct->aLevel[iLvl+1];
  180959. fts5WriteInit(p, &writer, iSegid);
  180960. /* Add the new segment to the output level */
  180961. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
  180962. pLvlOut->nSeg++;
  180963. pSeg->pgnoFirst = 1;
  180964. pSeg->iSegid = iSegid;
  180965. pStruct->nSegment++;
  180966. /* Read input from all segments in the input level */
  180967. nInput = pLvl->nSeg;
  180968. }
  180969. bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
  180970. assert( iLvl>=0 );
  180971. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
  180972. fts5MultiIterEof(p, pIter)==0;
  180973. fts5MultiIterNext(p, pIter, 0, 0)
  180974. ){
  180975. Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  180976. int nPos; /* position-list size field value */
  180977. int nTerm;
  180978. const u8 *pTerm;
  180979. pTerm = fts5MultiIterTerm(pIter, &nTerm);
  180980. if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
  180981. if( pnRem && writer.nLeafWritten>nRem ){
  180982. break;
  180983. }
  180984. fts5BufferSet(&p->rc, &term, nTerm, pTerm);
  180985. bTermWritten =0;
  180986. }
  180987. /* Check for key annihilation. */
  180988. if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
  180989. if( p->rc==SQLITE_OK && bTermWritten==0 ){
  180990. /* This is a new term. Append a term to the output segment. */
  180991. fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
  180992. bTermWritten = 1;
  180993. }
  180994. /* Append the rowid to the output */
  180995. /* WRITEPOSLISTSIZE */
  180996. fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
  180997. if( eDetail==FTS5_DETAIL_NONE ){
  180998. if( pSegIter->bDel ){
  180999. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  181000. if( pSegIter->nPos>0 ){
  181001. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  181002. }
  181003. }
  181004. }else{
  181005. /* Append the position-list data to the output */
  181006. nPos = pSegIter->nPos*2 + pSegIter->bDel;
  181007. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
  181008. fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
  181009. }
  181010. }
  181011. /* Flush the last leaf page to disk. Set the output segment b-tree height
  181012. ** and last leaf page number at the same time. */
  181013. fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
  181014. if( fts5MultiIterEof(p, pIter) ){
  181015. int i;
  181016. /* Remove the redundant segments from the %_data table */
  181017. for(i=0; i<nInput; i++){
  181018. fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
  181019. }
  181020. /* Remove the redundant segments from the input level */
  181021. if( pLvl->nSeg!=nInput ){
  181022. int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
  181023. memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
  181024. }
  181025. pStruct->nSegment -= nInput;
  181026. pLvl->nSeg -= nInput;
  181027. pLvl->nMerge = 0;
  181028. if( pSeg->pgnoLast==0 ){
  181029. pLvlOut->nSeg--;
  181030. pStruct->nSegment--;
  181031. }
  181032. }else{
  181033. assert( pSeg->pgnoLast>0 );
  181034. fts5TrimSegments(p, pIter);
  181035. pLvl->nMerge = nInput;
  181036. }
  181037. fts5MultiIterFree(pIter);
  181038. fts5BufferFree(&term);
  181039. if( pnRem ) *pnRem -= writer.nLeafWritten;
  181040. }
  181041. /*
  181042. ** Do up to nPg pages of automerge work on the index.
  181043. **
  181044. ** Return true if any changes were actually made, or false otherwise.
  181045. */
  181046. static int fts5IndexMerge(
  181047. Fts5Index *p, /* FTS5 backend object */
  181048. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  181049. int nPg, /* Pages of work to do */
  181050. int nMin /* Minimum number of segments to merge */
  181051. ){
  181052. int nRem = nPg;
  181053. int bRet = 0;
  181054. Fts5Structure *pStruct = *ppStruct;
  181055. while( nRem>0 && p->rc==SQLITE_OK ){
  181056. int iLvl; /* To iterate through levels */
  181057. int iBestLvl = 0; /* Level offering the most input segments */
  181058. int nBest = 0; /* Number of input segments on best level */
  181059. /* Set iBestLvl to the level to read input segments from. */
  181060. assert( pStruct->nLevel>0 );
  181061. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  181062. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  181063. if( pLvl->nMerge ){
  181064. if( pLvl->nMerge>nBest ){
  181065. iBestLvl = iLvl;
  181066. nBest = pLvl->nMerge;
  181067. }
  181068. break;
  181069. }
  181070. if( pLvl->nSeg>nBest ){
  181071. nBest = pLvl->nSeg;
  181072. iBestLvl = iLvl;
  181073. }
  181074. }
  181075. /* If nBest is still 0, then the index must be empty. */
  181076. #ifdef SQLITE_DEBUG
  181077. for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
  181078. assert( pStruct->aLevel[iLvl].nSeg==0 );
  181079. }
  181080. #endif
  181081. if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
  181082. break;
  181083. }
  181084. bRet = 1;
  181085. fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
  181086. if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
  181087. fts5StructurePromote(p, iBestLvl+1, pStruct);
  181088. }
  181089. }
  181090. *ppStruct = pStruct;
  181091. return bRet;
  181092. }
  181093. /*
  181094. ** A total of nLeaf leaf pages of data has just been flushed to a level-0
  181095. ** segment. This function updates the write-counter accordingly and, if
  181096. ** necessary, performs incremental merge work.
  181097. **
  181098. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  181099. ** already occurred, this function is a no-op.
  181100. */
  181101. static void fts5IndexAutomerge(
  181102. Fts5Index *p, /* FTS5 backend object */
  181103. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  181104. int nLeaf /* Number of output leaves just written */
  181105. ){
  181106. if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
  181107. Fts5Structure *pStruct = *ppStruct;
  181108. u64 nWrite; /* Initial value of write-counter */
  181109. int nWork; /* Number of work-quanta to perform */
  181110. int nRem; /* Number of leaf pages left to write */
  181111. /* Update the write-counter. While doing so, set nWork. */
  181112. nWrite = pStruct->nWriteCounter;
  181113. nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
  181114. pStruct->nWriteCounter += nLeaf;
  181115. nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
  181116. fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
  181117. }
  181118. }
  181119. static void fts5IndexCrisismerge(
  181120. Fts5Index *p, /* FTS5 backend object */
  181121. Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
  181122. ){
  181123. const int nCrisis = p->pConfig->nCrisisMerge;
  181124. Fts5Structure *pStruct = *ppStruct;
  181125. int iLvl = 0;
  181126. assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
  181127. while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
  181128. fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
  181129. assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
  181130. fts5StructurePromote(p, iLvl+1, pStruct);
  181131. iLvl++;
  181132. }
  181133. *ppStruct = pStruct;
  181134. }
  181135. static int fts5IndexReturn(Fts5Index *p){
  181136. int rc = p->rc;
  181137. p->rc = SQLITE_OK;
  181138. return rc;
  181139. }
  181140. typedef struct Fts5FlushCtx Fts5FlushCtx;
  181141. struct Fts5FlushCtx {
  181142. Fts5Index *pIdx;
  181143. Fts5SegWriter writer;
  181144. };
  181145. /*
  181146. ** Buffer aBuf[] contains a list of varints, all small enough to fit
  181147. ** in a 32-bit integer. Return the size of the largest prefix of this
  181148. ** list nMax bytes or less in size.
  181149. */
  181150. static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
  181151. int ret;
  181152. u32 dummy;
  181153. ret = fts5GetVarint32(aBuf, dummy);
  181154. if( ret<nMax ){
  181155. while( 1 ){
  181156. int i = fts5GetVarint32(&aBuf[ret], dummy);
  181157. if( (ret + i) > nMax ) break;
  181158. ret += i;
  181159. }
  181160. }
  181161. return ret;
  181162. }
  181163. /*
  181164. ** Flush the contents of in-memory hash table iHash to a new level-0
  181165. ** segment on disk. Also update the corresponding structure record.
  181166. **
  181167. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  181168. ** already occurred, this function is a no-op.
  181169. */
  181170. static void fts5FlushOneHash(Fts5Index *p){
  181171. Fts5Hash *pHash = p->pHash;
  181172. Fts5Structure *pStruct;
  181173. int iSegid;
  181174. int pgnoLast = 0; /* Last leaf page number in segment */
  181175. /* Obtain a reference to the index structure and allocate a new segment-id
  181176. ** for the new level-0 segment. */
  181177. pStruct = fts5StructureRead(p);
  181178. iSegid = fts5AllocateSegid(p, pStruct);
  181179. fts5StructureInvalidate(p);
  181180. if( iSegid ){
  181181. const int pgsz = p->pConfig->pgsz;
  181182. int eDetail = p->pConfig->eDetail;
  181183. Fts5StructureSegment *pSeg; /* New segment within pStruct */
  181184. Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
  181185. Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
  181186. Fts5SegWriter writer;
  181187. fts5WriteInit(p, &writer, iSegid);
  181188. pBuf = &writer.writer.buf;
  181189. pPgidx = &writer.writer.pgidx;
  181190. /* fts5WriteInit() should have initialized the buffers to (most likely)
  181191. ** the maximum space required. */
  181192. assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  181193. assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  181194. /* Begin scanning through hash table entries. This loop runs once for each
  181195. ** term/doclist currently stored within the hash table. */
  181196. if( p->rc==SQLITE_OK ){
  181197. p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
  181198. }
  181199. while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
  181200. const char *zTerm; /* Buffer containing term */
  181201. const u8 *pDoclist; /* Pointer to doclist for this term */
  181202. int nDoclist; /* Size of doclist in bytes */
  181203. /* Write the term for this entry to disk. */
  181204. sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
  181205. fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
  181206. assert( writer.bFirstRowidInPage==0 );
  181207. if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
  181208. /* The entire doclist will fit on the current leaf. */
  181209. fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
  181210. }else{
  181211. i64 iRowid = 0;
  181212. i64 iDelta = 0;
  181213. int iOff = 0;
  181214. /* The entire doclist will not fit on this leaf. The following
  181215. ** loop iterates through the poslists that make up the current
  181216. ** doclist. */
  181217. while( p->rc==SQLITE_OK && iOff<nDoclist ){
  181218. iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
  181219. iRowid += iDelta;
  181220. if( writer.bFirstRowidInPage ){
  181221. fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */
  181222. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
  181223. writer.bFirstRowidInPage = 0;
  181224. fts5WriteDlidxAppend(p, &writer, iRowid);
  181225. }else{
  181226. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
  181227. }
  181228. assert( pBuf->n<=pBuf->nSpace );
  181229. if( eDetail==FTS5_DETAIL_NONE ){
  181230. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  181231. pBuf->p[pBuf->n++] = 0;
  181232. iOff++;
  181233. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  181234. pBuf->p[pBuf->n++] = 0;
  181235. iOff++;
  181236. }
  181237. }
  181238. if( (pBuf->n + pPgidx->n)>=pgsz ){
  181239. fts5WriteFlushLeaf(p, &writer);
  181240. }
  181241. }else{
  181242. int bDummy;
  181243. int nPos;
  181244. int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
  181245. nCopy += nPos;
  181246. if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
  181247. /* The entire poslist will fit on the current leaf. So copy
  181248. ** it in one go. */
  181249. fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
  181250. }else{
  181251. /* The entire poslist will not fit on this leaf. So it needs
  181252. ** to be broken into sections. The only qualification being
  181253. ** that each varint must be stored contiguously. */
  181254. const u8 *pPoslist = &pDoclist[iOff];
  181255. int iPos = 0;
  181256. while( p->rc==SQLITE_OK ){
  181257. int nSpace = pgsz - pBuf->n - pPgidx->n;
  181258. int n = 0;
  181259. if( (nCopy - iPos)<=nSpace ){
  181260. n = nCopy - iPos;
  181261. }else{
  181262. n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
  181263. }
  181264. assert( n>0 );
  181265. fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
  181266. iPos += n;
  181267. if( (pBuf->n + pPgidx->n)>=pgsz ){
  181268. fts5WriteFlushLeaf(p, &writer);
  181269. }
  181270. if( iPos>=nCopy ) break;
  181271. }
  181272. }
  181273. iOff += nCopy;
  181274. }
  181275. }
  181276. }
  181277. /* TODO2: Doclist terminator written here. */
  181278. /* pBuf->p[pBuf->n++] = '\0'; */
  181279. assert( pBuf->n<=pBuf->nSpace );
  181280. sqlite3Fts5HashScanNext(pHash);
  181281. }
  181282. sqlite3Fts5HashClear(pHash);
  181283. fts5WriteFinish(p, &writer, &pgnoLast);
  181284. /* Update the Fts5Structure. It is written back to the database by the
  181285. ** fts5StructureRelease() call below. */
  181286. if( pStruct->nLevel==0 ){
  181287. fts5StructureAddLevel(&p->rc, &pStruct);
  181288. }
  181289. fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
  181290. if( p->rc==SQLITE_OK ){
  181291. pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
  181292. pSeg->iSegid = iSegid;
  181293. pSeg->pgnoFirst = 1;
  181294. pSeg->pgnoLast = pgnoLast;
  181295. pStruct->nSegment++;
  181296. }
  181297. fts5StructurePromote(p, 0, pStruct);
  181298. }
  181299. fts5IndexAutomerge(p, &pStruct, pgnoLast);
  181300. fts5IndexCrisismerge(p, &pStruct);
  181301. fts5StructureWrite(p, pStruct);
  181302. fts5StructureRelease(pStruct);
  181303. }
  181304. /*
  181305. ** Flush any data stored in the in-memory hash tables to the database.
  181306. */
  181307. static void fts5IndexFlush(Fts5Index *p){
  181308. /* Unless it is empty, flush the hash table to disk */
  181309. if( p->nPendingData ){
  181310. assert( p->pHash );
  181311. p->nPendingData = 0;
  181312. fts5FlushOneHash(p);
  181313. }
  181314. }
  181315. static Fts5Structure *fts5IndexOptimizeStruct(
  181316. Fts5Index *p,
  181317. Fts5Structure *pStruct
  181318. ){
  181319. Fts5Structure *pNew = 0;
  181320. int nByte = sizeof(Fts5Structure);
  181321. int nSeg = pStruct->nSegment;
  181322. int i;
  181323. /* Figure out if this structure requires optimization. A structure does
  181324. ** not require optimization if either:
  181325. **
  181326. ** + it consists of fewer than two segments, or
  181327. ** + all segments are on the same level, or
  181328. ** + all segments except one are currently inputs to a merge operation.
  181329. **
  181330. ** In the first case, return NULL. In the second, increment the ref-count
  181331. ** on *pStruct and return a copy of the pointer to it.
  181332. */
  181333. if( nSeg<2 ) return 0;
  181334. for(i=0; i<pStruct->nLevel; i++){
  181335. int nThis = pStruct->aLevel[i].nSeg;
  181336. if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
  181337. fts5StructureRef(pStruct);
  181338. return pStruct;
  181339. }
  181340. assert( pStruct->aLevel[i].nMerge<=nThis );
  181341. }
  181342. nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
  181343. pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
  181344. if( pNew ){
  181345. Fts5StructureLevel *pLvl;
  181346. nByte = nSeg * sizeof(Fts5StructureSegment);
  181347. pNew->nLevel = pStruct->nLevel+1;
  181348. pNew->nRef = 1;
  181349. pNew->nWriteCounter = pStruct->nWriteCounter;
  181350. pLvl = &pNew->aLevel[pStruct->nLevel];
  181351. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
  181352. if( pLvl->aSeg ){
  181353. int iLvl, iSeg;
  181354. int iSegOut = 0;
  181355. /* Iterate through all segments, from oldest to newest. Add them to
  181356. ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
  181357. ** segment in the data structure. */
  181358. for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
  181359. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  181360. pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
  181361. iSegOut++;
  181362. }
  181363. }
  181364. pNew->nSegment = pLvl->nSeg = nSeg;
  181365. }else{
  181366. sqlite3_free(pNew);
  181367. pNew = 0;
  181368. }
  181369. }
  181370. return pNew;
  181371. }
  181372. static int sqlite3Fts5IndexOptimize(Fts5Index *p){
  181373. Fts5Structure *pStruct;
  181374. Fts5Structure *pNew = 0;
  181375. assert( p->rc==SQLITE_OK );
  181376. fts5IndexFlush(p);
  181377. pStruct = fts5StructureRead(p);
  181378. fts5StructureInvalidate(p);
  181379. if( pStruct ){
  181380. pNew = fts5IndexOptimizeStruct(p, pStruct);
  181381. }
  181382. fts5StructureRelease(pStruct);
  181383. assert( pNew==0 || pNew->nSegment>0 );
  181384. if( pNew ){
  181385. int iLvl;
  181386. for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
  181387. while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
  181388. int nRem = FTS5_OPT_WORK_UNIT;
  181389. fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
  181390. }
  181391. fts5StructureWrite(p, pNew);
  181392. fts5StructureRelease(pNew);
  181393. }
  181394. return fts5IndexReturn(p);
  181395. }
  181396. /*
  181397. ** This is called to implement the special "VALUES('merge', $nMerge)"
  181398. ** INSERT command.
  181399. */
  181400. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
  181401. Fts5Structure *pStruct = fts5StructureRead(p);
  181402. if( pStruct ){
  181403. int nMin = p->pConfig->nUsermerge;
  181404. fts5StructureInvalidate(p);
  181405. if( nMerge<0 ){
  181406. Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
  181407. fts5StructureRelease(pStruct);
  181408. pStruct = pNew;
  181409. nMin = 2;
  181410. nMerge = nMerge*-1;
  181411. }
  181412. if( pStruct && pStruct->nLevel ){
  181413. if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
  181414. fts5StructureWrite(p, pStruct);
  181415. }
  181416. }
  181417. fts5StructureRelease(pStruct);
  181418. }
  181419. return fts5IndexReturn(p);
  181420. }
  181421. static void fts5AppendRowid(
  181422. Fts5Index *p,
  181423. i64 iDelta,
  181424. Fts5Iter *pUnused,
  181425. Fts5Buffer *pBuf
  181426. ){
  181427. UNUSED_PARAM(pUnused);
  181428. fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
  181429. }
  181430. static void fts5AppendPoslist(
  181431. Fts5Index *p,
  181432. i64 iDelta,
  181433. Fts5Iter *pMulti,
  181434. Fts5Buffer *pBuf
  181435. ){
  181436. int nData = pMulti->base.nData;
  181437. assert( nData>0 );
  181438. if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){
  181439. fts5BufferSafeAppendVarint(pBuf, iDelta);
  181440. fts5BufferSafeAppendVarint(pBuf, nData*2);
  181441. fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
  181442. }
  181443. }
  181444. static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
  181445. u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
  181446. assert( pIter->aPoslist );
  181447. if( p>=pIter->aEof ){
  181448. pIter->aPoslist = 0;
  181449. }else{
  181450. i64 iDelta;
  181451. p += fts5GetVarint(p, (u64*)&iDelta);
  181452. pIter->iRowid += iDelta;
  181453. /* Read position list size */
  181454. if( p[0] & 0x80 ){
  181455. int nPos;
  181456. pIter->nSize = fts5GetVarint32(p, nPos);
  181457. pIter->nPoslist = (nPos>>1);
  181458. }else{
  181459. pIter->nPoslist = ((int)(p[0])) >> 1;
  181460. pIter->nSize = 1;
  181461. }
  181462. pIter->aPoslist = p;
  181463. }
  181464. }
  181465. static void fts5DoclistIterInit(
  181466. Fts5Buffer *pBuf,
  181467. Fts5DoclistIter *pIter
  181468. ){
  181469. memset(pIter, 0, sizeof(*pIter));
  181470. pIter->aPoslist = pBuf->p;
  181471. pIter->aEof = &pBuf->p[pBuf->n];
  181472. fts5DoclistIterNext(pIter);
  181473. }
  181474. #if 0
  181475. /*
  181476. ** Append a doclist to buffer pBuf.
  181477. **
  181478. ** This function assumes that space within the buffer has already been
  181479. ** allocated.
  181480. */
  181481. static void fts5MergeAppendDocid(
  181482. Fts5Buffer *pBuf, /* Buffer to write to */
  181483. i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
  181484. i64 iRowid /* Rowid to append */
  181485. ){
  181486. assert( pBuf->n!=0 || (*piLastRowid)==0 );
  181487. fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
  181488. *piLastRowid = iRowid;
  181489. }
  181490. #endif
  181491. #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
  181492. assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
  181493. fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
  181494. (iLastRowid) = (iRowid); \
  181495. }
  181496. /*
  181497. ** Swap the contents of buffer *p1 with that of *p2.
  181498. */
  181499. static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
  181500. Fts5Buffer tmp = *p1;
  181501. *p1 = *p2;
  181502. *p2 = tmp;
  181503. }
  181504. static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
  181505. int i = *piOff;
  181506. if( i>=pBuf->n ){
  181507. *piOff = -1;
  181508. }else{
  181509. u64 iVal;
  181510. *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
  181511. *piRowid += iVal;
  181512. }
  181513. }
  181514. /*
  181515. ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
  181516. ** In this case the buffers consist of a delta-encoded list of rowids only.
  181517. */
  181518. static void fts5MergeRowidLists(
  181519. Fts5Index *p, /* FTS5 backend object */
  181520. Fts5Buffer *p1, /* First list to merge */
  181521. Fts5Buffer *p2 /* Second list to merge */
  181522. ){
  181523. int i1 = 0;
  181524. int i2 = 0;
  181525. i64 iRowid1 = 0;
  181526. i64 iRowid2 = 0;
  181527. i64 iOut = 0;
  181528. Fts5Buffer out;
  181529. memset(&out, 0, sizeof(out));
  181530. sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
  181531. if( p->rc ) return;
  181532. fts5NextRowid(p1, &i1, &iRowid1);
  181533. fts5NextRowid(p2, &i2, &iRowid2);
  181534. while( i1>=0 || i2>=0 ){
  181535. if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
  181536. assert( iOut==0 || iRowid1>iOut );
  181537. fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
  181538. iOut = iRowid1;
  181539. fts5NextRowid(p1, &i1, &iRowid1);
  181540. }else{
  181541. assert( iOut==0 || iRowid2>iOut );
  181542. fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
  181543. iOut = iRowid2;
  181544. if( i1>=0 && iRowid1==iRowid2 ){
  181545. fts5NextRowid(p1, &i1, &iRowid1);
  181546. }
  181547. fts5NextRowid(p2, &i2, &iRowid2);
  181548. }
  181549. }
  181550. fts5BufferSwap(&out, p1);
  181551. fts5BufferFree(&out);
  181552. }
  181553. /*
  181554. ** Buffers p1 and p2 contain doclists. This function merges the content
  181555. ** of the two doclists together and sets buffer p1 to the result before
  181556. ** returning.
  181557. **
  181558. ** If an error occurs, an error code is left in p->rc. If an error has
  181559. ** already occurred, this function is a no-op.
  181560. */
  181561. static void fts5MergePrefixLists(
  181562. Fts5Index *p, /* FTS5 backend object */
  181563. Fts5Buffer *p1, /* First list to merge */
  181564. Fts5Buffer *p2 /* Second list to merge */
  181565. ){
  181566. if( p2->n ){
  181567. i64 iLastRowid = 0;
  181568. Fts5DoclistIter i1;
  181569. Fts5DoclistIter i2;
  181570. Fts5Buffer out = {0, 0, 0};
  181571. Fts5Buffer tmp = {0, 0, 0};
  181572. if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n) ) return;
  181573. fts5DoclistIterInit(p1, &i1);
  181574. fts5DoclistIterInit(p2, &i2);
  181575. while( 1 ){
  181576. if( i1.iRowid<i2.iRowid ){
  181577. /* Copy entry from i1 */
  181578. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  181579. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
  181580. fts5DoclistIterNext(&i1);
  181581. if( i1.aPoslist==0 ) break;
  181582. }
  181583. else if( i2.iRowid!=i1.iRowid ){
  181584. /* Copy entry from i2 */
  181585. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  181586. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
  181587. fts5DoclistIterNext(&i2);
  181588. if( i2.aPoslist==0 ) break;
  181589. }
  181590. else{
  181591. /* Merge the two position lists. */
  181592. i64 iPos1 = 0;
  181593. i64 iPos2 = 0;
  181594. int iOff1 = 0;
  181595. int iOff2 = 0;
  181596. u8 *a1 = &i1.aPoslist[i1.nSize];
  181597. u8 *a2 = &i2.aPoslist[i2.nSize];
  181598. i64 iPrev = 0;
  181599. Fts5PoslistWriter writer;
  181600. memset(&writer, 0, sizeof(writer));
  181601. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  181602. fts5BufferZero(&tmp);
  181603. sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
  181604. if( p->rc ) break;
  181605. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  181606. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  181607. assert( iPos1>=0 && iPos2>=0 );
  181608. if( iPos1<iPos2 ){
  181609. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  181610. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  181611. }else{
  181612. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  181613. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  181614. }
  181615. if( iPos1>=0 && iPos2>=0 ){
  181616. while( 1 ){
  181617. if( iPos1<iPos2 ){
  181618. if( iPos1!=iPrev ){
  181619. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  181620. }
  181621. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  181622. if( iPos1<0 ) break;
  181623. }else{
  181624. assert( iPos2!=iPrev );
  181625. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  181626. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  181627. if( iPos2<0 ) break;
  181628. }
  181629. }
  181630. }
  181631. if( iPos1>=0 ){
  181632. if( iPos1!=iPrev ){
  181633. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  181634. }
  181635. fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
  181636. }else{
  181637. assert( iPos2>=0 && iPos2!=iPrev );
  181638. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  181639. fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
  181640. }
  181641. /* WRITEPOSLISTSIZE */
  181642. fts5BufferSafeAppendVarint(&out, tmp.n * 2);
  181643. fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
  181644. fts5DoclistIterNext(&i1);
  181645. fts5DoclistIterNext(&i2);
  181646. if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
  181647. }
  181648. }
  181649. if( i1.aPoslist ){
  181650. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  181651. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
  181652. }
  181653. else if( i2.aPoslist ){
  181654. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  181655. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
  181656. }
  181657. fts5BufferSet(&p->rc, p1, out.n, out.p);
  181658. fts5BufferFree(&tmp);
  181659. fts5BufferFree(&out);
  181660. }
  181661. }
  181662. static void fts5SetupPrefixIter(
  181663. Fts5Index *p, /* Index to read from */
  181664. int bDesc, /* True for "ORDER BY rowid DESC" */
  181665. const u8 *pToken, /* Buffer containing prefix to match */
  181666. int nToken, /* Size of buffer pToken in bytes */
  181667. Fts5Colset *pColset, /* Restrict matches to these columns */
  181668. Fts5Iter **ppIter /* OUT: New iterator */
  181669. ){
  181670. Fts5Structure *pStruct;
  181671. Fts5Buffer *aBuf;
  181672. const int nBuf = 32;
  181673. void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
  181674. void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
  181675. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  181676. xMerge = fts5MergeRowidLists;
  181677. xAppend = fts5AppendRowid;
  181678. }else{
  181679. xMerge = fts5MergePrefixLists;
  181680. xAppend = fts5AppendPoslist;
  181681. }
  181682. aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
  181683. pStruct = fts5StructureRead(p);
  181684. if( aBuf && pStruct ){
  181685. const int flags = FTS5INDEX_QUERY_SCAN
  181686. | FTS5INDEX_QUERY_SKIPEMPTY
  181687. | FTS5INDEX_QUERY_NOOUTPUT;
  181688. int i;
  181689. i64 iLastRowid = 0;
  181690. Fts5Iter *p1 = 0; /* Iterator used to gather data from index */
  181691. Fts5Data *pData;
  181692. Fts5Buffer doclist;
  181693. int bNewTerm = 1;
  181694. memset(&doclist, 0, sizeof(doclist));
  181695. fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
  181696. fts5IterSetOutputCb(&p->rc, p1);
  181697. for( /* no-op */ ;
  181698. fts5MultiIterEof(p, p1)==0;
  181699. fts5MultiIterNext2(p, p1, &bNewTerm)
  181700. ){
  181701. Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
  181702. int nTerm = pSeg->term.n;
  181703. const u8 *pTerm = pSeg->term.p;
  181704. p1->xSetOutputs(p1, pSeg);
  181705. assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
  181706. if( bNewTerm ){
  181707. if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
  181708. }
  181709. if( p1->base.nData==0 ) continue;
  181710. if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
  181711. for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
  181712. assert( i<nBuf );
  181713. if( aBuf[i].n==0 ){
  181714. fts5BufferSwap(&doclist, &aBuf[i]);
  181715. fts5BufferZero(&doclist);
  181716. }else{
  181717. xMerge(p, &doclist, &aBuf[i]);
  181718. fts5BufferZero(&aBuf[i]);
  181719. }
  181720. }
  181721. iLastRowid = 0;
  181722. }
  181723. xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
  181724. iLastRowid = p1->base.iRowid;
  181725. }
  181726. for(i=0; i<nBuf; i++){
  181727. if( p->rc==SQLITE_OK ){
  181728. xMerge(p, &doclist, &aBuf[i]);
  181729. }
  181730. fts5BufferFree(&aBuf[i]);
  181731. }
  181732. fts5MultiIterFree(p1);
  181733. pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
  181734. if( pData ){
  181735. pData->p = (u8*)&pData[1];
  181736. pData->nn = pData->szLeaf = doclist.n;
  181737. if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n);
  181738. fts5MultiIterNew2(p, pData, bDesc, ppIter);
  181739. }
  181740. fts5BufferFree(&doclist);
  181741. }
  181742. fts5StructureRelease(pStruct);
  181743. sqlite3_free(aBuf);
  181744. }
  181745. /*
  181746. ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
  181747. ** to the document with rowid iRowid.
  181748. */
  181749. static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
  181750. assert( p->rc==SQLITE_OK );
  181751. /* Allocate the hash table if it has not already been allocated */
  181752. if( p->pHash==0 ){
  181753. p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
  181754. }
  181755. /* Flush the hash table to disk if required */
  181756. if( iRowid<p->iWriteRowid
  181757. || (iRowid==p->iWriteRowid && p->bDelete==0)
  181758. || (p->nPendingData > p->pConfig->nHashSize)
  181759. ){
  181760. fts5IndexFlush(p);
  181761. }
  181762. p->iWriteRowid = iRowid;
  181763. p->bDelete = bDelete;
  181764. return fts5IndexReturn(p);
  181765. }
  181766. /*
  181767. ** Commit data to disk.
  181768. */
  181769. static int sqlite3Fts5IndexSync(Fts5Index *p){
  181770. assert( p->rc==SQLITE_OK );
  181771. fts5IndexFlush(p);
  181772. fts5CloseReader(p);
  181773. return fts5IndexReturn(p);
  181774. }
  181775. /*
  181776. ** Discard any data stored in the in-memory hash tables. Do not write it
  181777. ** to the database. Additionally, assume that the contents of the %_data
  181778. ** table may have changed on disk. So any in-memory caches of %_data
  181779. ** records must be invalidated.
  181780. */
  181781. static int sqlite3Fts5IndexRollback(Fts5Index *p){
  181782. fts5CloseReader(p);
  181783. fts5IndexDiscardData(p);
  181784. fts5StructureInvalidate(p);
  181785. /* assert( p->rc==SQLITE_OK ); */
  181786. return SQLITE_OK;
  181787. }
  181788. /*
  181789. ** The %_data table is completely empty when this function is called. This
  181790. ** function populates it with the initial structure objects for each index,
  181791. ** and the initial version of the "averages" record (a zero-byte blob).
  181792. */
  181793. static int sqlite3Fts5IndexReinit(Fts5Index *p){
  181794. Fts5Structure s;
  181795. fts5StructureInvalidate(p);
  181796. memset(&s, 0, sizeof(Fts5Structure));
  181797. fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
  181798. fts5StructureWrite(p, &s);
  181799. return fts5IndexReturn(p);
  181800. }
  181801. /*
  181802. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  181803. ** and initialize the underlying %_data table.
  181804. **
  181805. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  181806. ** Otherwise, set *pp to NULL and return an SQLite error code.
  181807. */
  181808. static int sqlite3Fts5IndexOpen(
  181809. Fts5Config *pConfig,
  181810. int bCreate,
  181811. Fts5Index **pp,
  181812. char **pzErr
  181813. ){
  181814. int rc = SQLITE_OK;
  181815. Fts5Index *p; /* New object */
  181816. *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
  181817. if( rc==SQLITE_OK ){
  181818. p->pConfig = pConfig;
  181819. p->nWorkUnit = FTS5_WORK_UNIT;
  181820. p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
  181821. if( p->zDataTbl && bCreate ){
  181822. rc = sqlite3Fts5CreateTable(
  181823. pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
  181824. );
  181825. if( rc==SQLITE_OK ){
  181826. rc = sqlite3Fts5CreateTable(pConfig, "idx",
  181827. "segid, term, pgno, PRIMARY KEY(segid, term)",
  181828. 1, pzErr
  181829. );
  181830. }
  181831. if( rc==SQLITE_OK ){
  181832. rc = sqlite3Fts5IndexReinit(p);
  181833. }
  181834. }
  181835. }
  181836. assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
  181837. if( rc ){
  181838. sqlite3Fts5IndexClose(p);
  181839. *pp = 0;
  181840. }
  181841. return rc;
  181842. }
  181843. /*
  181844. ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
  181845. */
  181846. static int sqlite3Fts5IndexClose(Fts5Index *p){
  181847. int rc = SQLITE_OK;
  181848. if( p ){
  181849. assert( p->pReader==0 );
  181850. fts5StructureInvalidate(p);
  181851. sqlite3_finalize(p->pWriter);
  181852. sqlite3_finalize(p->pDeleter);
  181853. sqlite3_finalize(p->pIdxWriter);
  181854. sqlite3_finalize(p->pIdxDeleter);
  181855. sqlite3_finalize(p->pIdxSelect);
  181856. sqlite3_finalize(p->pDataVersion);
  181857. sqlite3Fts5HashFree(p->pHash);
  181858. sqlite3_free(p->zDataTbl);
  181859. sqlite3_free(p);
  181860. }
  181861. return rc;
  181862. }
  181863. /*
  181864. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  181865. ** size. Return the number of bytes in the nChar character prefix of the
  181866. ** buffer, or 0 if there are less than nChar characters in total.
  181867. */
  181868. static int sqlite3Fts5IndexCharlenToBytelen(
  181869. const char *p,
  181870. int nByte,
  181871. int nChar
  181872. ){
  181873. int n = 0;
  181874. int i;
  181875. for(i=0; i<nChar; i++){
  181876. if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
  181877. if( (unsigned char)p[n++]>=0xc0 ){
  181878. while( (p[n] & 0xc0)==0x80 ) n++;
  181879. }
  181880. }
  181881. return n;
  181882. }
  181883. /*
  181884. ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
  181885. ** unicode characters in the string.
  181886. */
  181887. static int fts5IndexCharlen(const char *pIn, int nIn){
  181888. int nChar = 0;
  181889. int i = 0;
  181890. while( i<nIn ){
  181891. if( (unsigned char)pIn[i++]>=0xc0 ){
  181892. while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
  181893. }
  181894. nChar++;
  181895. }
  181896. return nChar;
  181897. }
  181898. /*
  181899. ** Insert or remove data to or from the index. Each time a document is
  181900. ** added to or removed from the index, this function is called one or more
  181901. ** times.
  181902. **
  181903. ** For an insert, it must be called once for each token in the new document.
  181904. ** If the operation is a delete, it must be called (at least) once for each
  181905. ** unique token in the document with an iCol value less than zero. The iPos
  181906. ** argument is ignored for a delete.
  181907. */
  181908. static int sqlite3Fts5IndexWrite(
  181909. Fts5Index *p, /* Index to write to */
  181910. int iCol, /* Column token appears in (-ve -> delete) */
  181911. int iPos, /* Position of token within column */
  181912. const char *pToken, int nToken /* Token to add or remove to or from index */
  181913. ){
  181914. int i; /* Used to iterate through indexes */
  181915. int rc = SQLITE_OK; /* Return code */
  181916. Fts5Config *pConfig = p->pConfig;
  181917. assert( p->rc==SQLITE_OK );
  181918. assert( (iCol<0)==p->bDelete );
  181919. /* Add the entry to the main terms index. */
  181920. rc = sqlite3Fts5HashWrite(
  181921. p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
  181922. );
  181923. for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
  181924. const int nChar = pConfig->aPrefix[i];
  181925. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  181926. if( nByte ){
  181927. rc = sqlite3Fts5HashWrite(p->pHash,
  181928. p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
  181929. nByte
  181930. );
  181931. }
  181932. }
  181933. return rc;
  181934. }
  181935. /*
  181936. ** Open a new iterator to iterate though all rowid that match the
  181937. ** specified token or token prefix.
  181938. */
  181939. static int sqlite3Fts5IndexQuery(
  181940. Fts5Index *p, /* FTS index to query */
  181941. const char *pToken, int nToken, /* Token (or prefix) to query for */
  181942. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  181943. Fts5Colset *pColset, /* Match these columns only */
  181944. Fts5IndexIter **ppIter /* OUT: New iterator object */
  181945. ){
  181946. Fts5Config *pConfig = p->pConfig;
  181947. Fts5Iter *pRet = 0;
  181948. Fts5Buffer buf = {0, 0, 0};
  181949. /* If the QUERY_SCAN flag is set, all other flags must be clear. */
  181950. assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
  181951. if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
  181952. int iIdx = 0; /* Index to search */
  181953. if( nToken ) memcpy(&buf.p[1], pToken, nToken);
  181954. /* Figure out which index to search and set iIdx accordingly. If this
  181955. ** is a prefix query for which there is no prefix index, set iIdx to
  181956. ** greater than pConfig->nPrefix to indicate that the query will be
  181957. ** satisfied by scanning multiple terms in the main index.
  181958. **
  181959. ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
  181960. ** prefix-query. Instead of using a prefix-index (if one exists),
  181961. ** evaluate the prefix query using the main FTS index. This is used
  181962. ** for internal sanity checking by the integrity-check in debug
  181963. ** mode only. */
  181964. #ifdef SQLITE_DEBUG
  181965. if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
  181966. assert( flags & FTS5INDEX_QUERY_PREFIX );
  181967. iIdx = 1+pConfig->nPrefix;
  181968. }else
  181969. #endif
  181970. if( flags & FTS5INDEX_QUERY_PREFIX ){
  181971. int nChar = fts5IndexCharlen(pToken, nToken);
  181972. for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
  181973. if( pConfig->aPrefix[iIdx-1]==nChar ) break;
  181974. }
  181975. }
  181976. if( iIdx<=pConfig->nPrefix ){
  181977. /* Straight index lookup */
  181978. Fts5Structure *pStruct = fts5StructureRead(p);
  181979. buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
  181980. if( pStruct ){
  181981. fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
  181982. pColset, buf.p, nToken+1, -1, 0, &pRet
  181983. );
  181984. fts5StructureRelease(pStruct);
  181985. }
  181986. }else{
  181987. /* Scan multiple terms in the main index */
  181988. int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
  181989. buf.p[0] = FTS5_MAIN_PREFIX;
  181990. fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
  181991. assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
  181992. fts5IterSetOutputCb(&p->rc, pRet);
  181993. if( p->rc==SQLITE_OK ){
  181994. Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
  181995. if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
  181996. }
  181997. }
  181998. if( p->rc ){
  181999. sqlite3Fts5IterClose((Fts5IndexIter*)pRet);
  182000. pRet = 0;
  182001. fts5CloseReader(p);
  182002. }
  182003. *ppIter = &pRet->base;
  182004. sqlite3Fts5BufferFree(&buf);
  182005. }
  182006. return fts5IndexReturn(p);
  182007. }
  182008. /*
  182009. ** Return true if the iterator passed as the only argument is at EOF.
  182010. */
  182011. /*
  182012. ** Move to the next matching rowid.
  182013. */
  182014. static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
  182015. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  182016. assert( pIter->pIndex->rc==SQLITE_OK );
  182017. fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
  182018. return fts5IndexReturn(pIter->pIndex);
  182019. }
  182020. /*
  182021. ** Move to the next matching term/rowid. Used by the fts5vocab module.
  182022. */
  182023. static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
  182024. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  182025. Fts5Index *p = pIter->pIndex;
  182026. assert( pIter->pIndex->rc==SQLITE_OK );
  182027. fts5MultiIterNext(p, pIter, 0, 0);
  182028. if( p->rc==SQLITE_OK ){
  182029. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  182030. if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
  182031. fts5DataRelease(pSeg->pLeaf);
  182032. pSeg->pLeaf = 0;
  182033. pIter->base.bEof = 1;
  182034. }
  182035. }
  182036. return fts5IndexReturn(pIter->pIndex);
  182037. }
  182038. /*
  182039. ** Move to the next matching rowid that occurs at or after iMatch. The
  182040. ** definition of "at or after" depends on whether this iterator iterates
  182041. ** in ascending or descending rowid order.
  182042. */
  182043. static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
  182044. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  182045. fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
  182046. return fts5IndexReturn(pIter->pIndex);
  182047. }
  182048. /*
  182049. ** Return the current term.
  182050. */
  182051. static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
  182052. int n;
  182053. const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
  182054. *pn = n-1;
  182055. return &z[1];
  182056. }
  182057. /*
  182058. ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
  182059. */
  182060. static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
  182061. if( pIndexIter ){
  182062. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  182063. Fts5Index *pIndex = pIter->pIndex;
  182064. fts5MultiIterFree(pIter);
  182065. fts5CloseReader(pIndex);
  182066. }
  182067. }
  182068. /*
  182069. ** Read and decode the "averages" record from the database.
  182070. **
  182071. ** Parameter anSize must point to an array of size nCol, where nCol is
  182072. ** the number of user defined columns in the FTS table.
  182073. */
  182074. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
  182075. int nCol = p->pConfig->nCol;
  182076. Fts5Data *pData;
  182077. *pnRow = 0;
  182078. memset(anSize, 0, sizeof(i64) * nCol);
  182079. pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
  182080. if( p->rc==SQLITE_OK && pData->nn ){
  182081. int i = 0;
  182082. int iCol;
  182083. i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
  182084. for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
  182085. i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
  182086. }
  182087. }
  182088. fts5DataRelease(pData);
  182089. return fts5IndexReturn(p);
  182090. }
  182091. /*
  182092. ** Replace the current "averages" record with the contents of the buffer
  182093. ** supplied as the second argument.
  182094. */
  182095. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
  182096. assert( p->rc==SQLITE_OK );
  182097. fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
  182098. return fts5IndexReturn(p);
  182099. }
  182100. /*
  182101. ** Return the total number of blocks this module has read from the %_data
  182102. ** table since it was created.
  182103. */
  182104. static int sqlite3Fts5IndexReads(Fts5Index *p){
  182105. return p->nRead;
  182106. }
  182107. /*
  182108. ** Set the 32-bit cookie value stored at the start of all structure
  182109. ** records to the value passed as the second argument.
  182110. **
  182111. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  182112. ** occurs.
  182113. */
  182114. static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
  182115. int rc; /* Return code */
  182116. Fts5Config *pConfig = p->pConfig; /* Configuration object */
  182117. u8 aCookie[4]; /* Binary representation of iNew */
  182118. sqlite3_blob *pBlob = 0;
  182119. assert( p->rc==SQLITE_OK );
  182120. sqlite3Fts5Put32(aCookie, iNew);
  182121. rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
  182122. "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
  182123. );
  182124. if( rc==SQLITE_OK ){
  182125. sqlite3_blob_write(pBlob, aCookie, 4, 0);
  182126. rc = sqlite3_blob_close(pBlob);
  182127. }
  182128. return rc;
  182129. }
  182130. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
  182131. Fts5Structure *pStruct;
  182132. pStruct = fts5StructureRead(p);
  182133. fts5StructureRelease(pStruct);
  182134. return fts5IndexReturn(p);
  182135. }
  182136. /*************************************************************************
  182137. **************************************************************************
  182138. ** Below this point is the implementation of the integrity-check
  182139. ** functionality.
  182140. */
  182141. /*
  182142. ** Return a simple checksum value based on the arguments.
  182143. */
  182144. static u64 sqlite3Fts5IndexEntryCksum(
  182145. i64 iRowid,
  182146. int iCol,
  182147. int iPos,
  182148. int iIdx,
  182149. const char *pTerm,
  182150. int nTerm
  182151. ){
  182152. int i;
  182153. u64 ret = iRowid;
  182154. ret += (ret<<3) + iCol;
  182155. ret += (ret<<3) + iPos;
  182156. if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
  182157. for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
  182158. return ret;
  182159. }
  182160. #ifdef SQLITE_DEBUG
  182161. /*
  182162. ** This function is purely an internal test. It does not contribute to
  182163. ** FTS functionality, or even the integrity-check, in any way.
  182164. **
  182165. ** Instead, it tests that the same set of pgno/rowid combinations are
  182166. ** visited regardless of whether the doclist-index identified by parameters
  182167. ** iSegid/iLeaf is iterated in forwards or reverse order.
  182168. */
  182169. static void fts5TestDlidxReverse(
  182170. Fts5Index *p,
  182171. int iSegid, /* Segment id to load from */
  182172. int iLeaf /* Load doclist-index for this leaf */
  182173. ){
  182174. Fts5DlidxIter *pDlidx = 0;
  182175. u64 cksum1 = 13;
  182176. u64 cksum2 = 13;
  182177. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
  182178. fts5DlidxIterEof(p, pDlidx)==0;
  182179. fts5DlidxIterNext(p, pDlidx)
  182180. ){
  182181. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  182182. int pgno = fts5DlidxIterPgno(pDlidx);
  182183. assert( pgno>iLeaf );
  182184. cksum1 += iRowid + ((i64)pgno<<32);
  182185. }
  182186. fts5DlidxIterFree(pDlidx);
  182187. pDlidx = 0;
  182188. for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
  182189. fts5DlidxIterEof(p, pDlidx)==0;
  182190. fts5DlidxIterPrev(p, pDlidx)
  182191. ){
  182192. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  182193. int pgno = fts5DlidxIterPgno(pDlidx);
  182194. assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
  182195. cksum2 += iRowid + ((i64)pgno<<32);
  182196. }
  182197. fts5DlidxIterFree(pDlidx);
  182198. pDlidx = 0;
  182199. if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
  182200. }
  182201. static int fts5QueryCksum(
  182202. Fts5Index *p, /* Fts5 index object */
  182203. int iIdx,
  182204. const char *z, /* Index key to query for */
  182205. int n, /* Size of index key in bytes */
  182206. int flags, /* Flags for Fts5IndexQuery */
  182207. u64 *pCksum /* IN/OUT: Checksum value */
  182208. ){
  182209. int eDetail = p->pConfig->eDetail;
  182210. u64 cksum = *pCksum;
  182211. Fts5IndexIter *pIter = 0;
  182212. int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
  182213. while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
  182214. i64 rowid = pIter->iRowid;
  182215. if( eDetail==FTS5_DETAIL_NONE ){
  182216. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
  182217. }else{
  182218. Fts5PoslistReader sReader;
  182219. for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
  182220. sReader.bEof==0;
  182221. sqlite3Fts5PoslistReaderNext(&sReader)
  182222. ){
  182223. int iCol = FTS5_POS2COLUMN(sReader.iPos);
  182224. int iOff = FTS5_POS2OFFSET(sReader.iPos);
  182225. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
  182226. }
  182227. }
  182228. if( rc==SQLITE_OK ){
  182229. rc = sqlite3Fts5IterNext(pIter);
  182230. }
  182231. }
  182232. sqlite3Fts5IterClose(pIter);
  182233. *pCksum = cksum;
  182234. return rc;
  182235. }
  182236. /*
  182237. ** This function is also purely an internal test. It does not contribute to
  182238. ** FTS functionality, or even the integrity-check, in any way.
  182239. */
  182240. static void fts5TestTerm(
  182241. Fts5Index *p,
  182242. Fts5Buffer *pPrev, /* Previous term */
  182243. const char *z, int n, /* Possibly new term to test */
  182244. u64 expected,
  182245. u64 *pCksum
  182246. ){
  182247. int rc = p->rc;
  182248. if( pPrev->n==0 ){
  182249. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  182250. }else
  182251. if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
  182252. u64 cksum3 = *pCksum;
  182253. const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
  182254. int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
  182255. int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
  182256. int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
  182257. u64 ck1 = 0;
  182258. u64 ck2 = 0;
  182259. /* Check that the results returned for ASC and DESC queries are
  182260. ** the same. If not, call this corruption. */
  182261. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
  182262. if( rc==SQLITE_OK ){
  182263. int f = flags|FTS5INDEX_QUERY_DESC;
  182264. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  182265. }
  182266. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  182267. /* If this is a prefix query, check that the results returned if the
  182268. ** the index is disabled are the same. In both ASC and DESC order.
  182269. **
  182270. ** This check may only be performed if the hash table is empty. This
  182271. ** is because the hash table only supports a single scan query at
  182272. ** a time, and the multi-iter loop from which this function is called
  182273. ** is already performing such a scan. */
  182274. if( p->nPendingData==0 ){
  182275. if( iIdx>0 && rc==SQLITE_OK ){
  182276. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
  182277. ck2 = 0;
  182278. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  182279. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  182280. }
  182281. if( iIdx>0 && rc==SQLITE_OK ){
  182282. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
  182283. ck2 = 0;
  182284. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  182285. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  182286. }
  182287. }
  182288. cksum3 ^= ck1;
  182289. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  182290. if( rc==SQLITE_OK && cksum3!=expected ){
  182291. rc = FTS5_CORRUPT;
  182292. }
  182293. *pCksum = cksum3;
  182294. }
  182295. p->rc = rc;
  182296. }
  182297. #else
  182298. # define fts5TestDlidxReverse(x,y,z)
  182299. # define fts5TestTerm(u,v,w,x,y,z)
  182300. #endif
  182301. /*
  182302. ** Check that:
  182303. **
  182304. ** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
  182305. ** contain zero terms.
  182306. ** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
  182307. ** contain zero rowids.
  182308. */
  182309. static void fts5IndexIntegrityCheckEmpty(
  182310. Fts5Index *p,
  182311. Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
  182312. int iFirst,
  182313. int iNoRowid,
  182314. int iLast
  182315. ){
  182316. int i;
  182317. /* Now check that the iter.nEmpty leaves following the current leaf
  182318. ** (a) exist and (b) contain no terms. */
  182319. for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
  182320. Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
  182321. if( pLeaf ){
  182322. if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
  182323. if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
  182324. }
  182325. fts5DataRelease(pLeaf);
  182326. }
  182327. }
  182328. static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
  182329. int iTermOff = 0;
  182330. int ii;
  182331. Fts5Buffer buf1 = {0,0,0};
  182332. Fts5Buffer buf2 = {0,0,0};
  182333. ii = pLeaf->szLeaf;
  182334. while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
  182335. int res;
  182336. int iOff;
  182337. int nIncr;
  182338. ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
  182339. iTermOff += nIncr;
  182340. iOff = iTermOff;
  182341. if( iOff>=pLeaf->szLeaf ){
  182342. p->rc = FTS5_CORRUPT;
  182343. }else if( iTermOff==nIncr ){
  182344. int nByte;
  182345. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  182346. if( (iOff+nByte)>pLeaf->szLeaf ){
  182347. p->rc = FTS5_CORRUPT;
  182348. }else{
  182349. fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  182350. }
  182351. }else{
  182352. int nKeep, nByte;
  182353. iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
  182354. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  182355. if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
  182356. p->rc = FTS5_CORRUPT;
  182357. }else{
  182358. buf1.n = nKeep;
  182359. fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  182360. }
  182361. if( p->rc==SQLITE_OK ){
  182362. res = fts5BufferCompare(&buf1, &buf2);
  182363. if( res<=0 ) p->rc = FTS5_CORRUPT;
  182364. }
  182365. }
  182366. fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
  182367. }
  182368. fts5BufferFree(&buf1);
  182369. fts5BufferFree(&buf2);
  182370. }
  182371. static void fts5IndexIntegrityCheckSegment(
  182372. Fts5Index *p, /* FTS5 backend object */
  182373. Fts5StructureSegment *pSeg /* Segment to check internal consistency */
  182374. ){
  182375. Fts5Config *pConfig = p->pConfig;
  182376. sqlite3_stmt *pStmt = 0;
  182377. int rc2;
  182378. int iIdxPrevLeaf = pSeg->pgnoFirst-1;
  182379. int iDlidxPrevLeaf = pSeg->pgnoLast;
  182380. if( pSeg->pgnoFirst==0 ) return;
  182381. fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
  182382. "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
  182383. pConfig->zDb, pConfig->zName, pSeg->iSegid
  182384. ));
  182385. /* Iterate through the b-tree hierarchy. */
  182386. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  182387. i64 iRow; /* Rowid for this leaf */
  182388. Fts5Data *pLeaf; /* Data for this leaf */
  182389. int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
  182390. const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
  182391. int iIdxLeaf = sqlite3_column_int(pStmt, 2);
  182392. int bIdxDlidx = sqlite3_column_int(pStmt, 3);
  182393. /* If the leaf in question has already been trimmed from the segment,
  182394. ** ignore this b-tree entry. Otherwise, load it into memory. */
  182395. if( iIdxLeaf<pSeg->pgnoFirst ) continue;
  182396. iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
  182397. pLeaf = fts5LeafRead(p, iRow);
  182398. if( pLeaf==0 ) break;
  182399. /* Check that the leaf contains at least one term, and that it is equal
  182400. ** to or larger than the split-key in zIdxTerm. Also check that if there
  182401. ** is also a rowid pointer within the leaf page header, it points to a
  182402. ** location before the term. */
  182403. if( pLeaf->nn<=pLeaf->szLeaf ){
  182404. p->rc = FTS5_CORRUPT;
  182405. }else{
  182406. int iOff; /* Offset of first term on leaf */
  182407. int iRowidOff; /* Offset of first rowid on leaf */
  182408. int nTerm; /* Size of term on leaf in bytes */
  182409. int res; /* Comparison of term and split-key */
  182410. iOff = fts5LeafFirstTermOff(pLeaf);
  182411. iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  182412. if( iRowidOff>=iOff ){
  182413. p->rc = FTS5_CORRUPT;
  182414. }else{
  182415. iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
  182416. res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
  182417. if( res==0 ) res = nTerm - nIdxTerm;
  182418. if( res<0 ) p->rc = FTS5_CORRUPT;
  182419. }
  182420. fts5IntegrityCheckPgidx(p, pLeaf);
  182421. }
  182422. fts5DataRelease(pLeaf);
  182423. if( p->rc ) break;
  182424. /* Now check that the iter.nEmpty leaves following the current leaf
  182425. ** (a) exist and (b) contain no terms. */
  182426. fts5IndexIntegrityCheckEmpty(
  182427. p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
  182428. );
  182429. if( p->rc ) break;
  182430. /* If there is a doclist-index, check that it looks right. */
  182431. if( bIdxDlidx ){
  182432. Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
  182433. int iPrevLeaf = iIdxLeaf;
  182434. int iSegid = pSeg->iSegid;
  182435. int iPg = 0;
  182436. i64 iKey;
  182437. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
  182438. fts5DlidxIterEof(p, pDlidx)==0;
  182439. fts5DlidxIterNext(p, pDlidx)
  182440. ){
  182441. /* Check any rowid-less pages that occur before the current leaf. */
  182442. for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
  182443. iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
  182444. pLeaf = fts5DataRead(p, iKey);
  182445. if( pLeaf ){
  182446. if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
  182447. fts5DataRelease(pLeaf);
  182448. }
  182449. }
  182450. iPrevLeaf = fts5DlidxIterPgno(pDlidx);
  182451. /* Check that the leaf page indicated by the iterator really does
  182452. ** contain the rowid suggested by the same. */
  182453. iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
  182454. pLeaf = fts5DataRead(p, iKey);
  182455. if( pLeaf ){
  182456. i64 iRowid;
  182457. int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  182458. ASSERT_SZLEAF_OK(pLeaf);
  182459. if( iRowidOff>=pLeaf->szLeaf ){
  182460. p->rc = FTS5_CORRUPT;
  182461. }else{
  182462. fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
  182463. if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
  182464. }
  182465. fts5DataRelease(pLeaf);
  182466. }
  182467. }
  182468. iDlidxPrevLeaf = iPg;
  182469. fts5DlidxIterFree(pDlidx);
  182470. fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
  182471. }else{
  182472. iDlidxPrevLeaf = pSeg->pgnoLast;
  182473. /* TODO: Check there is no doclist index */
  182474. }
  182475. iIdxPrevLeaf = iIdxLeaf;
  182476. }
  182477. rc2 = sqlite3_finalize(pStmt);
  182478. if( p->rc==SQLITE_OK ) p->rc = rc2;
  182479. /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
  182480. #if 0
  182481. if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
  182482. p->rc = FTS5_CORRUPT;
  182483. }
  182484. #endif
  182485. }
  182486. /*
  182487. ** Run internal checks to ensure that the FTS index (a) is internally
  182488. ** consistent and (b) contains entries for which the XOR of the checksums
  182489. ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
  182490. **
  182491. ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
  182492. ** checksum does not match. Return SQLITE_OK if all checks pass without
  182493. ** error, or some other SQLite error code if another error (e.g. OOM)
  182494. ** occurs.
  182495. */
  182496. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
  182497. int eDetail = p->pConfig->eDetail;
  182498. u64 cksum2 = 0; /* Checksum based on contents of indexes */
  182499. Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
  182500. Fts5Iter *pIter; /* Used to iterate through entire index */
  182501. Fts5Structure *pStruct; /* Index structure */
  182502. #ifdef SQLITE_DEBUG
  182503. /* Used by extra internal tests only run if NDEBUG is not defined */
  182504. u64 cksum3 = 0; /* Checksum based on contents of indexes */
  182505. Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
  182506. #endif
  182507. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  182508. /* Load the FTS index structure */
  182509. pStruct = fts5StructureRead(p);
  182510. /* Check that the internal nodes of each segment match the leaves */
  182511. if( pStruct ){
  182512. int iLvl, iSeg;
  182513. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  182514. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  182515. Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
  182516. fts5IndexIntegrityCheckSegment(p, pSeg);
  182517. }
  182518. }
  182519. }
  182520. /* The cksum argument passed to this function is a checksum calculated
  182521. ** based on all expected entries in the FTS index (including prefix index
  182522. ** entries). This block checks that a checksum calculated based on the
  182523. ** actual contents of FTS index is identical.
  182524. **
  182525. ** Two versions of the same checksum are calculated. The first (stack
  182526. ** variable cksum2) based on entries extracted from the full-text index
  182527. ** while doing a linear scan of each individual index in turn.
  182528. **
  182529. ** As each term visited by the linear scans, a separate query for the
  182530. ** same term is performed. cksum3 is calculated based on the entries
  182531. ** extracted by these queries.
  182532. */
  182533. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
  182534. fts5MultiIterEof(p, pIter)==0;
  182535. fts5MultiIterNext(p, pIter, 0, 0)
  182536. ){
  182537. int n; /* Size of term in bytes */
  182538. i64 iPos = 0; /* Position read from poslist */
  182539. int iOff = 0; /* Offset within poslist */
  182540. i64 iRowid = fts5MultiIterRowid(pIter);
  182541. char *z = (char*)fts5MultiIterTerm(pIter, &n);
  182542. /* If this is a new term, query for it. Update cksum3 with the results. */
  182543. fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
  182544. if( eDetail==FTS5_DETAIL_NONE ){
  182545. if( 0==fts5MultiIterIsEmpty(p, pIter) ){
  182546. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
  182547. }
  182548. }else{
  182549. poslist.n = 0;
  182550. fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
  182551. while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
  182552. int iCol = FTS5_POS2COLUMN(iPos);
  182553. int iTokOff = FTS5_POS2OFFSET(iPos);
  182554. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
  182555. }
  182556. }
  182557. }
  182558. fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
  182559. fts5MultiIterFree(pIter);
  182560. if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
  182561. fts5StructureRelease(pStruct);
  182562. #ifdef SQLITE_DEBUG
  182563. fts5BufferFree(&term);
  182564. #endif
  182565. fts5BufferFree(&poslist);
  182566. return fts5IndexReturn(p);
  182567. }
  182568. /*************************************************************************
  182569. **************************************************************************
  182570. ** Below this point is the implementation of the fts5_decode() scalar
  182571. ** function only.
  182572. */
  182573. /*
  182574. ** Decode a segment-data rowid from the %_data table. This function is
  182575. ** the opposite of macro FTS5_SEGMENT_ROWID().
  182576. */
  182577. static void fts5DecodeRowid(
  182578. i64 iRowid, /* Rowid from %_data table */
  182579. int *piSegid, /* OUT: Segment id */
  182580. int *pbDlidx, /* OUT: Dlidx flag */
  182581. int *piHeight, /* OUT: Height */
  182582. int *piPgno /* OUT: Page number */
  182583. ){
  182584. *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
  182585. iRowid >>= FTS5_DATA_PAGE_B;
  182586. *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
  182587. iRowid >>= FTS5_DATA_HEIGHT_B;
  182588. *pbDlidx = (int)(iRowid & 0x0001);
  182589. iRowid >>= FTS5_DATA_DLI_B;
  182590. *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
  182591. }
  182592. static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
  182593. int iSegid, iHeight, iPgno, bDlidx; /* Rowid compenents */
  182594. fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
  182595. if( iSegid==0 ){
  182596. if( iKey==FTS5_AVERAGES_ROWID ){
  182597. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
  182598. }else{
  182599. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
  182600. }
  182601. }
  182602. else{
  182603. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
  182604. bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
  182605. );
  182606. }
  182607. }
  182608. static void fts5DebugStructure(
  182609. int *pRc, /* IN/OUT: error code */
  182610. Fts5Buffer *pBuf,
  182611. Fts5Structure *p
  182612. ){
  182613. int iLvl, iSeg; /* Iterate through levels, segments */
  182614. for(iLvl=0; iLvl<p->nLevel; iLvl++){
  182615. Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
  182616. sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
  182617. " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
  182618. );
  182619. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  182620. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  182621. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
  182622. pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
  182623. );
  182624. }
  182625. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
  182626. }
  182627. }
  182628. /*
  182629. ** This is part of the fts5_decode() debugging aid.
  182630. **
  182631. ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
  182632. ** function appends a human-readable representation of the same object
  182633. ** to the buffer passed as the second argument.
  182634. */
  182635. static void fts5DecodeStructure(
  182636. int *pRc, /* IN/OUT: error code */
  182637. Fts5Buffer *pBuf,
  182638. const u8 *pBlob, int nBlob
  182639. ){
  182640. int rc; /* Return code */
  182641. Fts5Structure *p = 0; /* Decoded structure object */
  182642. rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
  182643. if( rc!=SQLITE_OK ){
  182644. *pRc = rc;
  182645. return;
  182646. }
  182647. fts5DebugStructure(pRc, pBuf, p);
  182648. fts5StructureRelease(p);
  182649. }
  182650. /*
  182651. ** This is part of the fts5_decode() debugging aid.
  182652. **
  182653. ** Arguments pBlob/nBlob contain an "averages" record. This function
  182654. ** appends a human-readable representation of record to the buffer passed
  182655. ** as the second argument.
  182656. */
  182657. static void fts5DecodeAverages(
  182658. int *pRc, /* IN/OUT: error code */
  182659. Fts5Buffer *pBuf,
  182660. const u8 *pBlob, int nBlob
  182661. ){
  182662. int i = 0;
  182663. const char *zSpace = "";
  182664. while( i<nBlob ){
  182665. u64 iVal;
  182666. i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
  182667. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
  182668. zSpace = " ";
  182669. }
  182670. }
  182671. /*
  182672. ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
  182673. ** each varint and append its string representation to buffer pBuf. Return
  182674. ** after either the input buffer is exhausted or a 0 value is read.
  182675. **
  182676. ** The return value is the number of bytes read from the input buffer.
  182677. */
  182678. static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  182679. int iOff = 0;
  182680. while( iOff<n ){
  182681. int iVal;
  182682. iOff += fts5GetVarint32(&a[iOff], iVal);
  182683. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
  182684. }
  182685. return iOff;
  182686. }
  182687. /*
  182688. ** The start of buffer (a/n) contains the start of a doclist. The doclist
  182689. ** may or may not finish within the buffer. This function appends a text
  182690. ** representation of the part of the doclist that is present to buffer
  182691. ** pBuf.
  182692. **
  182693. ** The return value is the number of bytes read from the input buffer.
  182694. */
  182695. static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  182696. i64 iDocid = 0;
  182697. int iOff = 0;
  182698. if( n>0 ){
  182699. iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
  182700. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  182701. }
  182702. while( iOff<n ){
  182703. int nPos;
  182704. int bDel;
  182705. iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
  182706. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
  182707. iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
  182708. if( iOff<n ){
  182709. i64 iDelta;
  182710. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
  182711. iDocid += iDelta;
  182712. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  182713. }
  182714. }
  182715. return iOff;
  182716. }
  182717. /*
  182718. ** This function is part of the fts5_decode() debugging function. It is
  182719. ** only ever used with detail=none tables.
  182720. **
  182721. ** Buffer (pData/nData) contains a doclist in the format used by detail=none
  182722. ** tables. This function appends a human-readable version of that list to
  182723. ** buffer pBuf.
  182724. **
  182725. ** If *pRc is other than SQLITE_OK when this function is called, it is a
  182726. ** no-op. If an OOM or other error occurs within this function, *pRc is
  182727. ** set to an SQLite error code before returning. The final state of buffer
  182728. ** pBuf is undefined in this case.
  182729. */
  182730. static void fts5DecodeRowidList(
  182731. int *pRc, /* IN/OUT: Error code */
  182732. Fts5Buffer *pBuf, /* Buffer to append text to */
  182733. const u8 *pData, int nData /* Data to decode list-of-rowids from */
  182734. ){
  182735. int i = 0;
  182736. i64 iRowid = 0;
  182737. while( i<nData ){
  182738. const char *zApp = "";
  182739. u64 iVal;
  182740. i += sqlite3Fts5GetVarint(&pData[i], &iVal);
  182741. iRowid += iVal;
  182742. if( i<nData && pData[i]==0x00 ){
  182743. i++;
  182744. if( i<nData && pData[i]==0x00 ){
  182745. i++;
  182746. zApp = "+";
  182747. }else{
  182748. zApp = "*";
  182749. }
  182750. }
  182751. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
  182752. }
  182753. }
  182754. /*
  182755. ** The implementation of user-defined scalar function fts5_decode().
  182756. */
  182757. static void fts5DecodeFunction(
  182758. sqlite3_context *pCtx, /* Function call context */
  182759. int nArg, /* Number of args (always 2) */
  182760. sqlite3_value **apVal /* Function arguments */
  182761. ){
  182762. i64 iRowid; /* Rowid for record being decoded */
  182763. int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
  182764. const u8 *aBlob; int n; /* Record to decode */
  182765. u8 *a = 0;
  182766. Fts5Buffer s; /* Build up text to return here */
  182767. int rc = SQLITE_OK; /* Return code */
  182768. int nSpace = 0;
  182769. int eDetailNone = (sqlite3_user_data(pCtx)!=0);
  182770. assert( nArg==2 );
  182771. UNUSED_PARAM(nArg);
  182772. memset(&s, 0, sizeof(Fts5Buffer));
  182773. iRowid = sqlite3_value_int64(apVal[0]);
  182774. /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
  182775. ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
  182776. ** buffer overreads even if the record is corrupt. */
  182777. n = sqlite3_value_bytes(apVal[1]);
  182778. aBlob = sqlite3_value_blob(apVal[1]);
  182779. nSpace = n + FTS5_DATA_ZERO_PADDING;
  182780. a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
  182781. if( a==0 ) goto decode_out;
  182782. memcpy(a, aBlob, n);
  182783. fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
  182784. fts5DebugRowid(&rc, &s, iRowid);
  182785. if( bDlidx ){
  182786. Fts5Data dlidx;
  182787. Fts5DlidxLvl lvl;
  182788. dlidx.p = a;
  182789. dlidx.nn = n;
  182790. memset(&lvl, 0, sizeof(Fts5DlidxLvl));
  182791. lvl.pData = &dlidx;
  182792. lvl.iLeafPgno = iPgno;
  182793. for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
  182794. sqlite3Fts5BufferAppendPrintf(&rc, &s,
  182795. " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
  182796. );
  182797. }
  182798. }else if( iSegid==0 ){
  182799. if( iRowid==FTS5_AVERAGES_ROWID ){
  182800. fts5DecodeAverages(&rc, &s, a, n);
  182801. }else{
  182802. fts5DecodeStructure(&rc, &s, a, n);
  182803. }
  182804. }else if( eDetailNone ){
  182805. Fts5Buffer term; /* Current term read from page */
  182806. int szLeaf;
  182807. int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  182808. int iTermOff;
  182809. int nKeep = 0;
  182810. int iOff;
  182811. memset(&term, 0, sizeof(Fts5Buffer));
  182812. /* Decode any entries that occur before the first term. */
  182813. if( szLeaf<n ){
  182814. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
  182815. }else{
  182816. iTermOff = szLeaf;
  182817. }
  182818. fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
  182819. iOff = iTermOff;
  182820. while( iOff<szLeaf ){
  182821. int nAppend;
  182822. /* Read the term data for the next term*/
  182823. iOff += fts5GetVarint32(&a[iOff], nAppend);
  182824. term.n = nKeep;
  182825. fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
  182826. sqlite3Fts5BufferAppendPrintf(
  182827. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  182828. );
  182829. iOff += nAppend;
  182830. /* Figure out where the doclist for this term ends */
  182831. if( iPgidxOff<n ){
  182832. int nIncr;
  182833. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
  182834. iTermOff += nIncr;
  182835. }else{
  182836. iTermOff = szLeaf;
  182837. }
  182838. fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
  182839. iOff = iTermOff;
  182840. if( iOff<szLeaf ){
  182841. iOff += fts5GetVarint32(&a[iOff], nKeep);
  182842. }
  182843. }
  182844. fts5BufferFree(&term);
  182845. }else{
  182846. Fts5Buffer term; /* Current term read from page */
  182847. int szLeaf; /* Offset of pgidx in a[] */
  182848. int iPgidxOff;
  182849. int iPgidxPrev = 0; /* Previous value read from pgidx */
  182850. int iTermOff = 0;
  182851. int iRowidOff = 0;
  182852. int iOff;
  182853. int nDoclist;
  182854. memset(&term, 0, sizeof(Fts5Buffer));
  182855. if( n<4 ){
  182856. sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
  182857. goto decode_out;
  182858. }else{
  182859. iRowidOff = fts5GetU16(&a[0]);
  182860. iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  182861. if( iPgidxOff<n ){
  182862. fts5GetVarint32(&a[iPgidxOff], iTermOff);
  182863. }
  182864. }
  182865. /* Decode the position list tail at the start of the page */
  182866. if( iRowidOff!=0 ){
  182867. iOff = iRowidOff;
  182868. }else if( iTermOff!=0 ){
  182869. iOff = iTermOff;
  182870. }else{
  182871. iOff = szLeaf;
  182872. }
  182873. fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
  182874. /* Decode any more doclist data that appears on the page before the
  182875. ** first term. */
  182876. nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
  182877. fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
  182878. while( iPgidxOff<n ){
  182879. int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
  182880. int nByte; /* Bytes of data */
  182881. int iEnd;
  182882. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
  182883. iPgidxPrev += nByte;
  182884. iOff = iPgidxPrev;
  182885. if( iPgidxOff<n ){
  182886. fts5GetVarint32(&a[iPgidxOff], nByte);
  182887. iEnd = iPgidxPrev + nByte;
  182888. }else{
  182889. iEnd = szLeaf;
  182890. }
  182891. if( bFirst==0 ){
  182892. iOff += fts5GetVarint32(&a[iOff], nByte);
  182893. term.n = nByte;
  182894. }
  182895. iOff += fts5GetVarint32(&a[iOff], nByte);
  182896. fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
  182897. iOff += nByte;
  182898. sqlite3Fts5BufferAppendPrintf(
  182899. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  182900. );
  182901. iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
  182902. }
  182903. fts5BufferFree(&term);
  182904. }
  182905. decode_out:
  182906. sqlite3_free(a);
  182907. if( rc==SQLITE_OK ){
  182908. sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
  182909. }else{
  182910. sqlite3_result_error_code(pCtx, rc);
  182911. }
  182912. fts5BufferFree(&s);
  182913. }
  182914. /*
  182915. ** The implementation of user-defined scalar function fts5_rowid().
  182916. */
  182917. static void fts5RowidFunction(
  182918. sqlite3_context *pCtx, /* Function call context */
  182919. int nArg, /* Number of args (always 2) */
  182920. sqlite3_value **apVal /* Function arguments */
  182921. ){
  182922. const char *zArg;
  182923. if( nArg==0 ){
  182924. sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
  182925. }else{
  182926. zArg = (const char*)sqlite3_value_text(apVal[0]);
  182927. if( 0==sqlite3_stricmp(zArg, "segment") ){
  182928. i64 iRowid;
  182929. int segid, pgno;
  182930. if( nArg!=3 ){
  182931. sqlite3_result_error(pCtx,
  182932. "should be: fts5_rowid('segment', segid, pgno))", -1
  182933. );
  182934. }else{
  182935. segid = sqlite3_value_int(apVal[1]);
  182936. pgno = sqlite3_value_int(apVal[2]);
  182937. iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
  182938. sqlite3_result_int64(pCtx, iRowid);
  182939. }
  182940. }else{
  182941. sqlite3_result_error(pCtx,
  182942. "first arg to fts5_rowid() must be 'segment'" , -1
  182943. );
  182944. }
  182945. }
  182946. }
  182947. /*
  182948. ** This is called as part of registering the FTS5 module with database
  182949. ** connection db. It registers several user-defined scalar functions useful
  182950. ** with FTS5.
  182951. **
  182952. ** If successful, SQLITE_OK is returned. If an error occurs, some other
  182953. ** SQLite error code is returned instead.
  182954. */
  182955. static int sqlite3Fts5IndexInit(sqlite3 *db){
  182956. int rc = sqlite3_create_function(
  182957. db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
  182958. );
  182959. if( rc==SQLITE_OK ){
  182960. rc = sqlite3_create_function(
  182961. db, "fts5_decode_none", 2,
  182962. SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
  182963. );
  182964. }
  182965. if( rc==SQLITE_OK ){
  182966. rc = sqlite3_create_function(
  182967. db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
  182968. );
  182969. }
  182970. return rc;
  182971. }
  182972. static int sqlite3Fts5IndexReset(Fts5Index *p){
  182973. assert( p->pStruct==0 || p->iStructVersion!=0 );
  182974. if( fts5IndexDataVersion(p)!=p->iStructVersion ){
  182975. fts5StructureInvalidate(p);
  182976. }
  182977. return fts5IndexReturn(p);
  182978. }
  182979. /*
  182980. ** 2014 Jun 09
  182981. **
  182982. ** The author disclaims copyright to this source code. In place of
  182983. ** a legal notice, here is a blessing:
  182984. **
  182985. ** May you do good and not evil.
  182986. ** May you find forgiveness for yourself and forgive others.
  182987. ** May you share freely, never taking more than you give.
  182988. **
  182989. ******************************************************************************
  182990. **
  182991. ** This is an SQLite module implementing full-text search.
  182992. */
  182993. /* #include "fts5Int.h" */
  182994. /*
  182995. ** This variable is set to false when running tests for which the on disk
  182996. ** structures should not be corrupt. Otherwise, true. If it is false, extra
  182997. ** assert() conditions in the fts5 code are activated - conditions that are
  182998. ** only true if it is guaranteed that the fts5 database is not corrupt.
  182999. */
  183000. SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
  183001. typedef struct Fts5Auxdata Fts5Auxdata;
  183002. typedef struct Fts5Auxiliary Fts5Auxiliary;
  183003. typedef struct Fts5Cursor Fts5Cursor;
  183004. typedef struct Fts5Sorter Fts5Sorter;
  183005. typedef struct Fts5Table Fts5Table;
  183006. typedef struct Fts5TokenizerModule Fts5TokenizerModule;
  183007. /*
  183008. ** NOTES ON TRANSACTIONS:
  183009. **
  183010. ** SQLite invokes the following virtual table methods as transactions are
  183011. ** opened and closed by the user:
  183012. **
  183013. ** xBegin(): Start of a new transaction.
  183014. ** xSync(): Initial part of two-phase commit.
  183015. ** xCommit(): Final part of two-phase commit.
  183016. ** xRollback(): Rollback the transaction.
  183017. **
  183018. ** Anything that is required as part of a commit that may fail is performed
  183019. ** in the xSync() callback. Current versions of SQLite ignore any errors
  183020. ** returned by xCommit().
  183021. **
  183022. ** And as sub-transactions are opened/closed:
  183023. **
  183024. ** xSavepoint(int S): Open savepoint S.
  183025. ** xRelease(int S): Commit and close savepoint S.
  183026. ** xRollbackTo(int S): Rollback to start of savepoint S.
  183027. **
  183028. ** During a write-transaction the fts5_index.c module may cache some data
  183029. ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
  183030. ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
  183031. ** is called.
  183032. **
  183033. ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
  183034. ** structure is used to record the current transaction state. This information
  183035. ** is not required, but it is used in the assert() statements executed by
  183036. ** function fts5CheckTransactionState() (see below).
  183037. */
  183038. struct Fts5TransactionState {
  183039. int eState; /* 0==closed, 1==open, 2==synced */
  183040. int iSavepoint; /* Number of open savepoints (0 -> none) */
  183041. };
  183042. /*
  183043. ** A single object of this type is allocated when the FTS5 module is
  183044. ** registered with a database handle. It is used to store pointers to
  183045. ** all registered FTS5 extensions - tokenizers and auxiliary functions.
  183046. */
  183047. struct Fts5Global {
  183048. fts5_api api; /* User visible part of object (see fts5.h) */
  183049. sqlite3 *db; /* Associated database connection */
  183050. i64 iNextId; /* Used to allocate unique cursor ids */
  183051. Fts5Auxiliary *pAux; /* First in list of all aux. functions */
  183052. Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */
  183053. Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */
  183054. Fts5Cursor *pCsr; /* First in list of all open cursors */
  183055. };
  183056. /*
  183057. ** Each auxiliary function registered with the FTS5 module is represented
  183058. ** by an object of the following type. All such objects are stored as part
  183059. ** of the Fts5Global.pAux list.
  183060. */
  183061. struct Fts5Auxiliary {
  183062. Fts5Global *pGlobal; /* Global context for this function */
  183063. char *zFunc; /* Function name (nul-terminated) */
  183064. void *pUserData; /* User-data pointer */
  183065. fts5_extension_function xFunc; /* Callback function */
  183066. void (*xDestroy)(void*); /* Destructor function */
  183067. Fts5Auxiliary *pNext; /* Next registered auxiliary function */
  183068. };
  183069. /*
  183070. ** Each tokenizer module registered with the FTS5 module is represented
  183071. ** by an object of the following type. All such objects are stored as part
  183072. ** of the Fts5Global.pTok list.
  183073. */
  183074. struct Fts5TokenizerModule {
  183075. char *zName; /* Name of tokenizer */
  183076. void *pUserData; /* User pointer passed to xCreate() */
  183077. fts5_tokenizer x; /* Tokenizer functions */
  183078. void (*xDestroy)(void*); /* Destructor function */
  183079. Fts5TokenizerModule *pNext; /* Next registered tokenizer module */
  183080. };
  183081. /*
  183082. ** Virtual-table object.
  183083. */
  183084. struct Fts5Table {
  183085. sqlite3_vtab base; /* Base class used by SQLite core */
  183086. Fts5Config *pConfig; /* Virtual table configuration */
  183087. Fts5Index *pIndex; /* Full-text index */
  183088. Fts5Storage *pStorage; /* Document store */
  183089. Fts5Global *pGlobal; /* Global (connection wide) data */
  183090. Fts5Cursor *pSortCsr; /* Sort data from this cursor */
  183091. #ifdef SQLITE_DEBUG
  183092. struct Fts5TransactionState ts;
  183093. #endif
  183094. };
  183095. struct Fts5MatchPhrase {
  183096. Fts5Buffer *pPoslist; /* Pointer to current poslist */
  183097. int nTerm; /* Size of phrase in terms */
  183098. };
  183099. /*
  183100. ** pStmt:
  183101. ** SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
  183102. **
  183103. ** aIdx[]:
  183104. ** There is one entry in the aIdx[] array for each phrase in the query,
  183105. ** the value of which is the offset within aPoslist[] following the last
  183106. ** byte of the position list for the corresponding phrase.
  183107. */
  183108. struct Fts5Sorter {
  183109. sqlite3_stmt *pStmt;
  183110. i64 iRowid; /* Current rowid */
  183111. const u8 *aPoslist; /* Position lists for current row */
  183112. int nIdx; /* Number of entries in aIdx[] */
  183113. int aIdx[1]; /* Offsets into aPoslist for current row */
  183114. };
  183115. /*
  183116. ** Virtual-table cursor object.
  183117. **
  183118. ** iSpecial:
  183119. ** If this is a 'special' query (refer to function fts5SpecialMatch()),
  183120. ** then this variable contains the result of the query.
  183121. **
  183122. ** iFirstRowid, iLastRowid:
  183123. ** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
  183124. ** cursor iterates in ascending order of rowids, iFirstRowid is the lower
  183125. ** limit of rowids to return, and iLastRowid the upper. In other words, the
  183126. ** WHERE clause in the user's query might have been:
  183127. **
  183128. ** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
  183129. **
  183130. ** If the cursor iterates in descending order of rowid, iFirstRowid
  183131. ** is the upper limit (i.e. the "first" rowid visited) and iLastRowid
  183132. ** the lower.
  183133. */
  183134. struct Fts5Cursor {
  183135. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  183136. Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */
  183137. int *aColumnSize; /* Values for xColumnSize() */
  183138. i64 iCsrId; /* Cursor id */
  183139. /* Zero from this point onwards on cursor reset */
  183140. int ePlan; /* FTS5_PLAN_XXX value */
  183141. int bDesc; /* True for "ORDER BY rowid DESC" queries */
  183142. i64 iFirstRowid; /* Return no rowids earlier than this */
  183143. i64 iLastRowid; /* Return no rowids later than this */
  183144. sqlite3_stmt *pStmt; /* Statement used to read %_content */
  183145. Fts5Expr *pExpr; /* Expression for MATCH queries */
  183146. Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */
  183147. int csrflags; /* Mask of cursor flags (see below) */
  183148. i64 iSpecial; /* Result of special query */
  183149. /* "rank" function. Populated on demand from vtab.xColumn(). */
  183150. char *zRank; /* Custom rank function */
  183151. char *zRankArgs; /* Custom rank function args */
  183152. Fts5Auxiliary *pRank; /* Rank callback (or NULL) */
  183153. int nRankArg; /* Number of trailing arguments for rank() */
  183154. sqlite3_value **apRankArg; /* Array of trailing arguments */
  183155. sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */
  183156. /* Auxiliary data storage */
  183157. Fts5Auxiliary *pAux; /* Currently executing extension function */
  183158. Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */
  183159. /* Cache used by auxiliary functions xInst() and xInstCount() */
  183160. Fts5PoslistReader *aInstIter; /* One for each phrase */
  183161. int nInstAlloc; /* Size of aInst[] array (entries / 3) */
  183162. int nInstCount; /* Number of phrase instances */
  183163. int *aInst; /* 3 integers per phrase instance */
  183164. };
  183165. /*
  183166. ** Bits that make up the "idxNum" parameter passed indirectly by
  183167. ** xBestIndex() to xFilter().
  183168. */
  183169. #define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */
  183170. #define FTS5_BI_RANK 0x0002 /* rank MATCH ? */
  183171. #define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */
  183172. #define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */
  183173. #define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */
  183174. #define FTS5_BI_ORDER_RANK 0x0020
  183175. #define FTS5_BI_ORDER_ROWID 0x0040
  183176. #define FTS5_BI_ORDER_DESC 0x0080
  183177. /*
  183178. ** Values for Fts5Cursor.csrflags
  183179. */
  183180. #define FTS5CSR_EOF 0x01
  183181. #define FTS5CSR_REQUIRE_CONTENT 0x02
  183182. #define FTS5CSR_REQUIRE_DOCSIZE 0x04
  183183. #define FTS5CSR_REQUIRE_INST 0x08
  183184. #define FTS5CSR_FREE_ZRANK 0x10
  183185. #define FTS5CSR_REQUIRE_RESEEK 0x20
  183186. #define FTS5CSR_REQUIRE_POSLIST 0x40
  183187. #define BitFlagAllTest(x,y) (((x) & (y))==(y))
  183188. #define BitFlagTest(x,y) (((x) & (y))!=0)
  183189. /*
  183190. ** Macros to Set(), Clear() and Test() cursor flags.
  183191. */
  183192. #define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag))
  183193. #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
  183194. #define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag))
  183195. struct Fts5Auxdata {
  183196. Fts5Auxiliary *pAux; /* Extension to which this belongs */
  183197. void *pPtr; /* Pointer value */
  183198. void(*xDelete)(void*); /* Destructor */
  183199. Fts5Auxdata *pNext; /* Next object in linked list */
  183200. };
  183201. #ifdef SQLITE_DEBUG
  183202. #define FTS5_BEGIN 1
  183203. #define FTS5_SYNC 2
  183204. #define FTS5_COMMIT 3
  183205. #define FTS5_ROLLBACK 4
  183206. #define FTS5_SAVEPOINT 5
  183207. #define FTS5_RELEASE 6
  183208. #define FTS5_ROLLBACKTO 7
  183209. static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
  183210. switch( op ){
  183211. case FTS5_BEGIN:
  183212. assert( p->ts.eState==0 );
  183213. p->ts.eState = 1;
  183214. p->ts.iSavepoint = -1;
  183215. break;
  183216. case FTS5_SYNC:
  183217. assert( p->ts.eState==1 );
  183218. p->ts.eState = 2;
  183219. break;
  183220. case FTS5_COMMIT:
  183221. assert( p->ts.eState==2 );
  183222. p->ts.eState = 0;
  183223. break;
  183224. case FTS5_ROLLBACK:
  183225. assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
  183226. p->ts.eState = 0;
  183227. break;
  183228. case FTS5_SAVEPOINT:
  183229. assert( p->ts.eState==1 );
  183230. assert( iSavepoint>=0 );
  183231. assert( iSavepoint>p->ts.iSavepoint );
  183232. p->ts.iSavepoint = iSavepoint;
  183233. break;
  183234. case FTS5_RELEASE:
  183235. assert( p->ts.eState==1 );
  183236. assert( iSavepoint>=0 );
  183237. assert( iSavepoint<=p->ts.iSavepoint );
  183238. p->ts.iSavepoint = iSavepoint-1;
  183239. break;
  183240. case FTS5_ROLLBACKTO:
  183241. assert( p->ts.eState==1 );
  183242. assert( iSavepoint>=0 );
  183243. assert( iSavepoint<=p->ts.iSavepoint );
  183244. p->ts.iSavepoint = iSavepoint;
  183245. break;
  183246. }
  183247. }
  183248. #else
  183249. # define fts5CheckTransactionState(x,y,z)
  183250. #endif
  183251. /*
  183252. ** Return true if pTab is a contentless table.
  183253. */
  183254. static int fts5IsContentless(Fts5Table *pTab){
  183255. return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
  183256. }
  183257. /*
  183258. ** Delete a virtual table handle allocated by fts5InitVtab().
  183259. */
  183260. static void fts5FreeVtab(Fts5Table *pTab){
  183261. if( pTab ){
  183262. sqlite3Fts5IndexClose(pTab->pIndex);
  183263. sqlite3Fts5StorageClose(pTab->pStorage);
  183264. sqlite3Fts5ConfigFree(pTab->pConfig);
  183265. sqlite3_free(pTab);
  183266. }
  183267. }
  183268. /*
  183269. ** The xDisconnect() virtual table method.
  183270. */
  183271. static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
  183272. fts5FreeVtab((Fts5Table*)pVtab);
  183273. return SQLITE_OK;
  183274. }
  183275. /*
  183276. ** The xDestroy() virtual table method.
  183277. */
  183278. static int fts5DestroyMethod(sqlite3_vtab *pVtab){
  183279. Fts5Table *pTab = (Fts5Table*)pVtab;
  183280. int rc = sqlite3Fts5DropAll(pTab->pConfig);
  183281. if( rc==SQLITE_OK ){
  183282. fts5FreeVtab((Fts5Table*)pVtab);
  183283. }
  183284. return rc;
  183285. }
  183286. /*
  183287. ** This function is the implementation of both the xConnect and xCreate
  183288. ** methods of the FTS3 virtual table.
  183289. **
  183290. ** The argv[] array contains the following:
  183291. **
  183292. ** argv[0] -> module name ("fts5")
  183293. ** argv[1] -> database name
  183294. ** argv[2] -> table name
  183295. ** argv[...] -> "column name" and other module argument fields.
  183296. */
  183297. static int fts5InitVtab(
  183298. int bCreate, /* True for xCreate, false for xConnect */
  183299. sqlite3 *db, /* The SQLite database connection */
  183300. void *pAux, /* Hash table containing tokenizers */
  183301. int argc, /* Number of elements in argv array */
  183302. const char * const *argv, /* xCreate/xConnect argument array */
  183303. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  183304. char **pzErr /* Write any error message here */
  183305. ){
  183306. Fts5Global *pGlobal = (Fts5Global*)pAux;
  183307. const char **azConfig = (const char**)argv;
  183308. int rc = SQLITE_OK; /* Return code */
  183309. Fts5Config *pConfig = 0; /* Results of parsing argc/argv */
  183310. Fts5Table *pTab = 0; /* New virtual table object */
  183311. /* Allocate the new vtab object and parse the configuration */
  183312. pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
  183313. if( rc==SQLITE_OK ){
  183314. rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
  183315. assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
  183316. }
  183317. if( rc==SQLITE_OK ){
  183318. pTab->pConfig = pConfig;
  183319. pTab->pGlobal = pGlobal;
  183320. }
  183321. /* Open the index sub-system */
  183322. if( rc==SQLITE_OK ){
  183323. rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
  183324. }
  183325. /* Open the storage sub-system */
  183326. if( rc==SQLITE_OK ){
  183327. rc = sqlite3Fts5StorageOpen(
  183328. pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
  183329. );
  183330. }
  183331. /* Call sqlite3_declare_vtab() */
  183332. if( rc==SQLITE_OK ){
  183333. rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
  183334. }
  183335. /* Load the initial configuration */
  183336. if( rc==SQLITE_OK ){
  183337. assert( pConfig->pzErrmsg==0 );
  183338. pConfig->pzErrmsg = pzErr;
  183339. rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
  183340. sqlite3Fts5IndexRollback(pTab->pIndex);
  183341. pConfig->pzErrmsg = 0;
  183342. }
  183343. if( rc!=SQLITE_OK ){
  183344. fts5FreeVtab(pTab);
  183345. pTab = 0;
  183346. }else if( bCreate ){
  183347. fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
  183348. }
  183349. *ppVTab = (sqlite3_vtab*)pTab;
  183350. return rc;
  183351. }
  183352. /*
  183353. ** The xConnect() and xCreate() methods for the virtual table. All the
  183354. ** work is done in function fts5InitVtab().
  183355. */
  183356. static int fts5ConnectMethod(
  183357. sqlite3 *db, /* Database connection */
  183358. void *pAux, /* Pointer to tokenizer hash table */
  183359. int argc, /* Number of elements in argv array */
  183360. const char * const *argv, /* xCreate/xConnect argument array */
  183361. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  183362. char **pzErr /* OUT: sqlite3_malloc'd error message */
  183363. ){
  183364. return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  183365. }
  183366. static int fts5CreateMethod(
  183367. sqlite3 *db, /* Database connection */
  183368. void *pAux, /* Pointer to tokenizer hash table */
  183369. int argc, /* Number of elements in argv array */
  183370. const char * const *argv, /* xCreate/xConnect argument array */
  183371. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  183372. char **pzErr /* OUT: sqlite3_malloc'd error message */
  183373. ){
  183374. return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  183375. }
  183376. /*
  183377. ** The different query plans.
  183378. */
  183379. #define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */
  183380. #define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */
  183381. #define FTS5_PLAN_SPECIAL 3 /* An internal query */
  183382. #define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */
  183383. #define FTS5_PLAN_SCAN 5 /* No usable constraint */
  183384. #define FTS5_PLAN_ROWID 6 /* (rowid = ?) */
  183385. /*
  183386. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  183387. ** extension is currently being used by a version of SQLite too old to
  183388. ** support index-info flags. In that case this function is a no-op.
  183389. */
  183390. static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  183391. #if SQLITE_VERSION_NUMBER>=3008012
  183392. #ifndef SQLITE_CORE
  183393. if( sqlite3_libversion_number()>=3008012 )
  183394. #endif
  183395. {
  183396. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  183397. }
  183398. #endif
  183399. }
  183400. /*
  183401. ** Implementation of the xBestIndex method for FTS5 tables. Within the
  183402. ** WHERE constraint, it searches for the following:
  183403. **
  183404. ** 1. A MATCH constraint against the special column.
  183405. ** 2. A MATCH constraint against the "rank" column.
  183406. ** 3. An == constraint against the rowid column.
  183407. ** 4. A < or <= constraint against the rowid column.
  183408. ** 5. A > or >= constraint against the rowid column.
  183409. **
  183410. ** Within the ORDER BY, either:
  183411. **
  183412. ** 5. ORDER BY rank [ASC|DESC]
  183413. ** 6. ORDER BY rowid [ASC|DESC]
  183414. **
  183415. ** Costs are assigned as follows:
  183416. **
  183417. ** a) If an unusable MATCH operator is present in the WHERE clause, the
  183418. ** cost is unconditionally set to 1e50 (a really big number).
  183419. **
  183420. ** a) If a MATCH operator is present, the cost depends on the other
  183421. ** constraints also present. As follows:
  183422. **
  183423. ** * No other constraints: cost=1000.0
  183424. ** * One rowid range constraint: cost=750.0
  183425. ** * Both rowid range constraints: cost=500.0
  183426. ** * An == rowid constraint: cost=100.0
  183427. **
  183428. ** b) Otherwise, if there is no MATCH:
  183429. **
  183430. ** * No other constraints: cost=1000000.0
  183431. ** * One rowid range constraint: cost=750000.0
  183432. ** * Both rowid range constraints: cost=250000.0
  183433. ** * An == rowid constraint: cost=10.0
  183434. **
  183435. ** Costs are not modified by the ORDER BY clause.
  183436. */
  183437. static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  183438. Fts5Table *pTab = (Fts5Table*)pVTab;
  183439. Fts5Config *pConfig = pTab->pConfig;
  183440. const int nCol = pConfig->nCol;
  183441. int idxFlags = 0; /* Parameter passed through to xFilter() */
  183442. int bHasMatch;
  183443. int iNext;
  183444. int i;
  183445. struct Constraint {
  183446. int op; /* Mask against sqlite3_index_constraint.op */
  183447. int fts5op; /* FTS5 mask for idxFlags */
  183448. int iCol; /* 0==rowid, 1==tbl, 2==rank */
  183449. int omit; /* True to omit this if found */
  183450. int iConsIndex; /* Index in pInfo->aConstraint[] */
  183451. } aConstraint[] = {
  183452. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  183453. FTS5_BI_MATCH, 1, 1, -1},
  183454. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  183455. FTS5_BI_RANK, 2, 1, -1},
  183456. {SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_ROWID_EQ, 0, 0, -1},
  183457. {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
  183458. FTS5_BI_ROWID_LE, 0, 0, -1},
  183459. {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
  183460. FTS5_BI_ROWID_GE, 0, 0, -1},
  183461. };
  183462. int aColMap[3];
  183463. aColMap[0] = -1;
  183464. aColMap[1] = nCol;
  183465. aColMap[2] = nCol+1;
  183466. /* Set idxFlags flags for all WHERE clause terms that will be used. */
  183467. for(i=0; i<pInfo->nConstraint; i++){
  183468. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  183469. int iCol = p->iColumn;
  183470. if( (p->op==SQLITE_INDEX_CONSTRAINT_MATCH && iCol>=0 && iCol<=nCol)
  183471. || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol==nCol)
  183472. ){
  183473. /* A MATCH operator or equivalent */
  183474. if( p->usable ){
  183475. idxFlags = (idxFlags & 0xFFFF) | FTS5_BI_MATCH | (iCol << 16);
  183476. aConstraint[0].iConsIndex = i;
  183477. }else{
  183478. /* As there exists an unusable MATCH constraint this is an
  183479. ** unusable plan. Set a prohibitively high cost. */
  183480. pInfo->estimatedCost = 1e50;
  183481. return SQLITE_OK;
  183482. }
  183483. }else{
  183484. int j;
  183485. for(j=1; j<ArraySize(aConstraint); j++){
  183486. struct Constraint *pC = &aConstraint[j];
  183487. if( iCol==aColMap[pC->iCol] && p->op & pC->op && p->usable ){
  183488. pC->iConsIndex = i;
  183489. idxFlags |= pC->fts5op;
  183490. }
  183491. }
  183492. }
  183493. }
  183494. /* Set idxFlags flags for the ORDER BY clause */
  183495. if( pInfo->nOrderBy==1 ){
  183496. int iSort = pInfo->aOrderBy[0].iColumn;
  183497. if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
  183498. idxFlags |= FTS5_BI_ORDER_RANK;
  183499. }else if( iSort==-1 ){
  183500. idxFlags |= FTS5_BI_ORDER_ROWID;
  183501. }
  183502. if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
  183503. pInfo->orderByConsumed = 1;
  183504. if( pInfo->aOrderBy[0].desc ){
  183505. idxFlags |= FTS5_BI_ORDER_DESC;
  183506. }
  183507. }
  183508. }
  183509. /* Calculate the estimated cost based on the flags set in idxFlags. */
  183510. bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
  183511. if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
  183512. pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
  183513. if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
  183514. }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  183515. pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
  183516. }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  183517. pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
  183518. }else{
  183519. pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
  183520. }
  183521. /* Assign argvIndex values to each constraint in use. */
  183522. iNext = 1;
  183523. for(i=0; i<ArraySize(aConstraint); i++){
  183524. struct Constraint *pC = &aConstraint[i];
  183525. if( pC->iConsIndex>=0 ){
  183526. pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
  183527. pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
  183528. }
  183529. }
  183530. pInfo->idxNum = idxFlags;
  183531. return SQLITE_OK;
  183532. }
  183533. static int fts5NewTransaction(Fts5Table *pTab){
  183534. Fts5Cursor *pCsr;
  183535. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  183536. if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
  183537. }
  183538. return sqlite3Fts5StorageReset(pTab->pStorage);
  183539. }
  183540. /*
  183541. ** Implementation of xOpen method.
  183542. */
  183543. static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  183544. Fts5Table *pTab = (Fts5Table*)pVTab;
  183545. Fts5Config *pConfig = pTab->pConfig;
  183546. Fts5Cursor *pCsr = 0; /* New cursor object */
  183547. int nByte; /* Bytes of space to allocate */
  183548. int rc; /* Return code */
  183549. rc = fts5NewTransaction(pTab);
  183550. if( rc==SQLITE_OK ){
  183551. nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
  183552. pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
  183553. if( pCsr ){
  183554. Fts5Global *pGlobal = pTab->pGlobal;
  183555. memset(pCsr, 0, nByte);
  183556. pCsr->aColumnSize = (int*)&pCsr[1];
  183557. pCsr->pNext = pGlobal->pCsr;
  183558. pGlobal->pCsr = pCsr;
  183559. pCsr->iCsrId = ++pGlobal->iNextId;
  183560. }else{
  183561. rc = SQLITE_NOMEM;
  183562. }
  183563. }
  183564. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  183565. return rc;
  183566. }
  183567. static int fts5StmtType(Fts5Cursor *pCsr){
  183568. if( pCsr->ePlan==FTS5_PLAN_SCAN ){
  183569. return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
  183570. }
  183571. return FTS5_STMT_LOOKUP;
  183572. }
  183573. /*
  183574. ** This function is called after the cursor passed as the only argument
  183575. ** is moved to point at a different row. It clears all cached data
  183576. ** specific to the previous row stored by the cursor object.
  183577. */
  183578. static void fts5CsrNewrow(Fts5Cursor *pCsr){
  183579. CsrFlagSet(pCsr,
  183580. FTS5CSR_REQUIRE_CONTENT
  183581. | FTS5CSR_REQUIRE_DOCSIZE
  183582. | FTS5CSR_REQUIRE_INST
  183583. | FTS5CSR_REQUIRE_POSLIST
  183584. );
  183585. }
  183586. static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
  183587. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  183588. Fts5Auxdata *pData;
  183589. Fts5Auxdata *pNext;
  183590. sqlite3_free(pCsr->aInstIter);
  183591. sqlite3_free(pCsr->aInst);
  183592. if( pCsr->pStmt ){
  183593. int eStmt = fts5StmtType(pCsr);
  183594. sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
  183595. }
  183596. if( pCsr->pSorter ){
  183597. Fts5Sorter *pSorter = pCsr->pSorter;
  183598. sqlite3_finalize(pSorter->pStmt);
  183599. sqlite3_free(pSorter);
  183600. }
  183601. if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
  183602. sqlite3Fts5ExprFree(pCsr->pExpr);
  183603. }
  183604. for(pData=pCsr->pAuxdata; pData; pData=pNext){
  183605. pNext = pData->pNext;
  183606. if( pData->xDelete ) pData->xDelete(pData->pPtr);
  183607. sqlite3_free(pData);
  183608. }
  183609. sqlite3_finalize(pCsr->pRankArgStmt);
  183610. sqlite3_free(pCsr->apRankArg);
  183611. if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
  183612. sqlite3_free(pCsr->zRank);
  183613. sqlite3_free(pCsr->zRankArgs);
  183614. }
  183615. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
  183616. }
  183617. /*
  183618. ** Close the cursor. For additional information see the documentation
  183619. ** on the xClose method of the virtual table interface.
  183620. */
  183621. static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
  183622. if( pCursor ){
  183623. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  183624. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  183625. Fts5Cursor **pp;
  183626. fts5FreeCursorComponents(pCsr);
  183627. /* Remove the cursor from the Fts5Global.pCsr list */
  183628. for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
  183629. *pp = pCsr->pNext;
  183630. sqlite3_free(pCsr);
  183631. }
  183632. return SQLITE_OK;
  183633. }
  183634. static int fts5SorterNext(Fts5Cursor *pCsr){
  183635. Fts5Sorter *pSorter = pCsr->pSorter;
  183636. int rc;
  183637. rc = sqlite3_step(pSorter->pStmt);
  183638. if( rc==SQLITE_DONE ){
  183639. rc = SQLITE_OK;
  183640. CsrFlagSet(pCsr, FTS5CSR_EOF);
  183641. }else if( rc==SQLITE_ROW ){
  183642. const u8 *a;
  183643. const u8 *aBlob;
  183644. int nBlob;
  183645. int i;
  183646. int iOff = 0;
  183647. rc = SQLITE_OK;
  183648. pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
  183649. nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
  183650. aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
  183651. /* nBlob==0 in detail=none mode. */
  183652. if( nBlob>0 ){
  183653. for(i=0; i<(pSorter->nIdx-1); i++){
  183654. int iVal;
  183655. a += fts5GetVarint32(a, iVal);
  183656. iOff += iVal;
  183657. pSorter->aIdx[i] = iOff;
  183658. }
  183659. pSorter->aIdx[i] = &aBlob[nBlob] - a;
  183660. pSorter->aPoslist = a;
  183661. }
  183662. fts5CsrNewrow(pCsr);
  183663. }
  183664. return rc;
  183665. }
  183666. /*
  183667. ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
  183668. ** open on table pTab.
  183669. */
  183670. static void fts5TripCursors(Fts5Table *pTab){
  183671. Fts5Cursor *pCsr;
  183672. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  183673. if( pCsr->ePlan==FTS5_PLAN_MATCH
  183674. && pCsr->base.pVtab==(sqlite3_vtab*)pTab
  183675. ){
  183676. CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
  183677. }
  183678. }
  183679. }
  183680. /*
  183681. ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
  183682. ** argument, close and reopen all Fts5IndexIter iterators that the cursor
  183683. ** is using. Then attempt to move the cursor to a rowid equal to or laster
  183684. ** (in the cursors sort order - ASC or DESC) than the current rowid.
  183685. **
  183686. ** If the new rowid is not equal to the old, set output parameter *pbSkip
  183687. ** to 1 before returning. Otherwise, leave it unchanged.
  183688. **
  183689. ** Return SQLITE_OK if successful or if no reseek was required, or an
  183690. ** error code if an error occurred.
  183691. */
  183692. static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
  183693. int rc = SQLITE_OK;
  183694. assert( *pbSkip==0 );
  183695. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
  183696. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  183697. int bDesc = pCsr->bDesc;
  183698. i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
  183699. rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
  183700. if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
  183701. *pbSkip = 1;
  183702. }
  183703. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
  183704. fts5CsrNewrow(pCsr);
  183705. if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
  183706. CsrFlagSet(pCsr, FTS5CSR_EOF);
  183707. *pbSkip = 1;
  183708. }
  183709. }
  183710. return rc;
  183711. }
  183712. /*
  183713. ** Advance the cursor to the next row in the table that matches the
  183714. ** search criteria.
  183715. **
  183716. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  183717. ** even if we reach end-of-file. The fts5EofMethod() will be called
  183718. ** subsequently to determine whether or not an EOF was hit.
  183719. */
  183720. static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
  183721. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  183722. int rc;
  183723. assert( (pCsr->ePlan<3)==
  183724. (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
  183725. );
  183726. assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
  183727. if( pCsr->ePlan<3 ){
  183728. int bSkip = 0;
  183729. if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
  183730. rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
  183731. CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
  183732. fts5CsrNewrow(pCsr);
  183733. }else{
  183734. switch( pCsr->ePlan ){
  183735. case FTS5_PLAN_SPECIAL: {
  183736. CsrFlagSet(pCsr, FTS5CSR_EOF);
  183737. rc = SQLITE_OK;
  183738. break;
  183739. }
  183740. case FTS5_PLAN_SORTED_MATCH: {
  183741. rc = fts5SorterNext(pCsr);
  183742. break;
  183743. }
  183744. default:
  183745. rc = sqlite3_step(pCsr->pStmt);
  183746. if( rc!=SQLITE_ROW ){
  183747. CsrFlagSet(pCsr, FTS5CSR_EOF);
  183748. rc = sqlite3_reset(pCsr->pStmt);
  183749. }else{
  183750. rc = SQLITE_OK;
  183751. }
  183752. break;
  183753. }
  183754. }
  183755. return rc;
  183756. }
  183757. static int fts5PrepareStatement(
  183758. sqlite3_stmt **ppStmt,
  183759. Fts5Config *pConfig,
  183760. const char *zFmt,
  183761. ...
  183762. ){
  183763. sqlite3_stmt *pRet = 0;
  183764. int rc;
  183765. char *zSql;
  183766. va_list ap;
  183767. va_start(ap, zFmt);
  183768. zSql = sqlite3_vmprintf(zFmt, ap);
  183769. if( zSql==0 ){
  183770. rc = SQLITE_NOMEM;
  183771. }else{
  183772. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pRet, 0);
  183773. if( rc!=SQLITE_OK ){
  183774. *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
  183775. }
  183776. sqlite3_free(zSql);
  183777. }
  183778. va_end(ap);
  183779. *ppStmt = pRet;
  183780. return rc;
  183781. }
  183782. static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
  183783. Fts5Config *pConfig = pTab->pConfig;
  183784. Fts5Sorter *pSorter;
  183785. int nPhrase;
  183786. int nByte;
  183787. int rc;
  183788. const char *zRank = pCsr->zRank;
  183789. const char *zRankArgs = pCsr->zRankArgs;
  183790. nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  183791. nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
  183792. pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
  183793. if( pSorter==0 ) return SQLITE_NOMEM;
  183794. memset(pSorter, 0, nByte);
  183795. pSorter->nIdx = nPhrase;
  183796. /* TODO: It would be better to have some system for reusing statement
  183797. ** handles here, rather than preparing a new one for each query. But that
  183798. ** is not possible as SQLite reference counts the virtual table objects.
  183799. ** And since the statement required here reads from this very virtual
  183800. ** table, saving it creates a circular reference.
  183801. **
  183802. ** If SQLite a built-in statement cache, this wouldn't be a problem. */
  183803. rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
  183804. "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
  183805. pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
  183806. (zRankArgs ? ", " : ""),
  183807. (zRankArgs ? zRankArgs : ""),
  183808. bDesc ? "DESC" : "ASC"
  183809. );
  183810. pCsr->pSorter = pSorter;
  183811. if( rc==SQLITE_OK ){
  183812. assert( pTab->pSortCsr==0 );
  183813. pTab->pSortCsr = pCsr;
  183814. rc = fts5SorterNext(pCsr);
  183815. pTab->pSortCsr = 0;
  183816. }
  183817. if( rc!=SQLITE_OK ){
  183818. sqlite3_finalize(pSorter->pStmt);
  183819. sqlite3_free(pSorter);
  183820. pCsr->pSorter = 0;
  183821. }
  183822. return rc;
  183823. }
  183824. static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
  183825. int rc;
  183826. Fts5Expr *pExpr = pCsr->pExpr;
  183827. rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
  183828. if( sqlite3Fts5ExprEof(pExpr) ){
  183829. CsrFlagSet(pCsr, FTS5CSR_EOF);
  183830. }
  183831. fts5CsrNewrow(pCsr);
  183832. return rc;
  183833. }
  183834. /*
  183835. ** Process a "special" query. A special query is identified as one with a
  183836. ** MATCH expression that begins with a '*' character. The remainder of
  183837. ** the text passed to the MATCH operator are used as the special query
  183838. ** parameters.
  183839. */
  183840. static int fts5SpecialMatch(
  183841. Fts5Table *pTab,
  183842. Fts5Cursor *pCsr,
  183843. const char *zQuery
  183844. ){
  183845. int rc = SQLITE_OK; /* Return code */
  183846. const char *z = zQuery; /* Special query text */
  183847. int n; /* Number of bytes in text at z */
  183848. while( z[0]==' ' ) z++;
  183849. for(n=0; z[n] && z[n]!=' '; n++);
  183850. assert( pTab->base.zErrMsg==0 );
  183851. pCsr->ePlan = FTS5_PLAN_SPECIAL;
  183852. if( 0==sqlite3_strnicmp("reads", z, n) ){
  183853. pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
  183854. }
  183855. else if( 0==sqlite3_strnicmp("id", z, n) ){
  183856. pCsr->iSpecial = pCsr->iCsrId;
  183857. }
  183858. else{
  183859. /* An unrecognized directive. Return an error message. */
  183860. pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
  183861. rc = SQLITE_ERROR;
  183862. }
  183863. return rc;
  183864. }
  183865. /*
  183866. ** Search for an auxiliary function named zName that can be used with table
  183867. ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
  183868. ** structure. Otherwise, if no such function exists, return NULL.
  183869. */
  183870. static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
  183871. Fts5Auxiliary *pAux;
  183872. for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
  183873. if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
  183874. }
  183875. /* No function of the specified name was found. Return 0. */
  183876. return 0;
  183877. }
  183878. static int fts5FindRankFunction(Fts5Cursor *pCsr){
  183879. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  183880. Fts5Config *pConfig = pTab->pConfig;
  183881. int rc = SQLITE_OK;
  183882. Fts5Auxiliary *pAux = 0;
  183883. const char *zRank = pCsr->zRank;
  183884. const char *zRankArgs = pCsr->zRankArgs;
  183885. if( zRankArgs ){
  183886. char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
  183887. if( zSql ){
  183888. sqlite3_stmt *pStmt = 0;
  183889. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pStmt, 0);
  183890. sqlite3_free(zSql);
  183891. assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
  183892. if( rc==SQLITE_OK ){
  183893. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  183894. int nByte;
  183895. pCsr->nRankArg = sqlite3_column_count(pStmt);
  183896. nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
  183897. pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
  183898. if( rc==SQLITE_OK ){
  183899. int i;
  183900. for(i=0; i<pCsr->nRankArg; i++){
  183901. pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
  183902. }
  183903. }
  183904. pCsr->pRankArgStmt = pStmt;
  183905. }else{
  183906. rc = sqlite3_finalize(pStmt);
  183907. assert( rc!=SQLITE_OK );
  183908. }
  183909. }
  183910. }
  183911. }
  183912. if( rc==SQLITE_OK ){
  183913. pAux = fts5FindAuxiliary(pTab, zRank);
  183914. if( pAux==0 ){
  183915. assert( pTab->base.zErrMsg==0 );
  183916. pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
  183917. rc = SQLITE_ERROR;
  183918. }
  183919. }
  183920. pCsr->pRank = pAux;
  183921. return rc;
  183922. }
  183923. static int fts5CursorParseRank(
  183924. Fts5Config *pConfig,
  183925. Fts5Cursor *pCsr,
  183926. sqlite3_value *pRank
  183927. ){
  183928. int rc = SQLITE_OK;
  183929. if( pRank ){
  183930. const char *z = (const char*)sqlite3_value_text(pRank);
  183931. char *zRank = 0;
  183932. char *zRankArgs = 0;
  183933. if( z==0 ){
  183934. if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
  183935. }else{
  183936. rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
  183937. }
  183938. if( rc==SQLITE_OK ){
  183939. pCsr->zRank = zRank;
  183940. pCsr->zRankArgs = zRankArgs;
  183941. CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
  183942. }else if( rc==SQLITE_ERROR ){
  183943. pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
  183944. "parse error in rank function: %s", z
  183945. );
  183946. }
  183947. }else{
  183948. if( pConfig->zRank ){
  183949. pCsr->zRank = (char*)pConfig->zRank;
  183950. pCsr->zRankArgs = (char*)pConfig->zRankArgs;
  183951. }else{
  183952. pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
  183953. pCsr->zRankArgs = 0;
  183954. }
  183955. }
  183956. return rc;
  183957. }
  183958. static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
  183959. if( pVal ){
  183960. int eType = sqlite3_value_numeric_type(pVal);
  183961. if( eType==SQLITE_INTEGER ){
  183962. return sqlite3_value_int64(pVal);
  183963. }
  183964. }
  183965. return iDefault;
  183966. }
  183967. /*
  183968. ** This is the xFilter interface for the virtual table. See
  183969. ** the virtual table xFilter method documentation for additional
  183970. ** information.
  183971. **
  183972. ** There are three possible query strategies:
  183973. **
  183974. ** 1. Full-text search using a MATCH operator.
  183975. ** 2. A by-rowid lookup.
  183976. ** 3. A full-table scan.
  183977. */
  183978. static int fts5FilterMethod(
  183979. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  183980. int idxNum, /* Strategy index */
  183981. const char *zUnused, /* Unused */
  183982. int nVal, /* Number of elements in apVal */
  183983. sqlite3_value **apVal /* Arguments for the indexing scheme */
  183984. ){
  183985. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  183986. Fts5Config *pConfig = pTab->pConfig;
  183987. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  183988. int rc = SQLITE_OK; /* Error code */
  183989. int iVal = 0; /* Counter for apVal[] */
  183990. int bDesc; /* True if ORDER BY [rank|rowid] DESC */
  183991. int bOrderByRank; /* True if ORDER BY rank */
  183992. sqlite3_value *pMatch = 0; /* <tbl> MATCH ? expression (or NULL) */
  183993. sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */
  183994. sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */
  183995. sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */
  183996. sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */
  183997. int iCol; /* Column on LHS of MATCH operator */
  183998. char **pzErrmsg = pConfig->pzErrmsg;
  183999. UNUSED_PARAM(zUnused);
  184000. UNUSED_PARAM(nVal);
  184001. if( pCsr->ePlan ){
  184002. fts5FreeCursorComponents(pCsr);
  184003. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
  184004. }
  184005. assert( pCsr->pStmt==0 );
  184006. assert( pCsr->pExpr==0 );
  184007. assert( pCsr->csrflags==0 );
  184008. assert( pCsr->pRank==0 );
  184009. assert( pCsr->zRank==0 );
  184010. assert( pCsr->zRankArgs==0 );
  184011. assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
  184012. pConfig->pzErrmsg = &pTab->base.zErrMsg;
  184013. /* Decode the arguments passed through to this function.
  184014. **
  184015. ** Note: The following set of if(...) statements must be in the same
  184016. ** order as the corresponding entries in the struct at the top of
  184017. ** fts5BestIndexMethod(). */
  184018. if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
  184019. if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
  184020. if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
  184021. if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
  184022. if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
  184023. iCol = (idxNum>>16);
  184024. assert( iCol>=0 && iCol<=pConfig->nCol );
  184025. assert( iVal==nVal );
  184026. bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
  184027. pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
  184028. /* Set the cursor upper and lower rowid limits. Only some strategies
  184029. ** actually use them. This is ok, as the xBestIndex() method leaves the
  184030. ** sqlite3_index_constraint.omit flag clear for range constraints
  184031. ** on the rowid field. */
  184032. if( pRowidEq ){
  184033. pRowidLe = pRowidGe = pRowidEq;
  184034. }
  184035. if( bDesc ){
  184036. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  184037. pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  184038. }else{
  184039. pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  184040. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  184041. }
  184042. if( pTab->pSortCsr ){
  184043. /* If pSortCsr is non-NULL, then this call is being made as part of
  184044. ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
  184045. ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
  184046. ** return results to the user for this query. The current cursor
  184047. ** (pCursor) is used to execute the query issued by function
  184048. ** fts5CursorFirstSorted() above. */
  184049. assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
  184050. assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
  184051. assert( pCsr->iLastRowid==LARGEST_INT64 );
  184052. assert( pCsr->iFirstRowid==SMALLEST_INT64 );
  184053. pCsr->ePlan = FTS5_PLAN_SOURCE;
  184054. pCsr->pExpr = pTab->pSortCsr->pExpr;
  184055. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  184056. }else if( pMatch ){
  184057. const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
  184058. if( zExpr==0 ) zExpr = "";
  184059. rc = fts5CursorParseRank(pConfig, pCsr, pRank);
  184060. if( rc==SQLITE_OK ){
  184061. if( zExpr[0]=='*' ){
  184062. /* The user has issued a query of the form "MATCH '*...'". This
  184063. ** indicates that the MATCH expression is not a full text query,
  184064. ** but a request for an internal parameter. */
  184065. rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
  184066. }else{
  184067. char **pzErr = &pTab->base.zErrMsg;
  184068. rc = sqlite3Fts5ExprNew(pConfig, iCol, zExpr, &pCsr->pExpr, pzErr);
  184069. if( rc==SQLITE_OK ){
  184070. if( bOrderByRank ){
  184071. pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
  184072. rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
  184073. }else{
  184074. pCsr->ePlan = FTS5_PLAN_MATCH;
  184075. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  184076. }
  184077. }
  184078. }
  184079. }
  184080. }else if( pConfig->zContent==0 ){
  184081. *pConfig->pzErrmsg = sqlite3_mprintf(
  184082. "%s: table does not support scanning", pConfig->zName
  184083. );
  184084. rc = SQLITE_ERROR;
  184085. }else{
  184086. /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
  184087. ** by rowid (ePlan==FTS5_PLAN_ROWID). */
  184088. pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
  184089. rc = sqlite3Fts5StorageStmt(
  184090. pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
  184091. );
  184092. if( rc==SQLITE_OK ){
  184093. if( pCsr->ePlan==FTS5_PLAN_ROWID ){
  184094. sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
  184095. }else{
  184096. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
  184097. sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
  184098. }
  184099. rc = fts5NextMethod(pCursor);
  184100. }
  184101. }
  184102. pConfig->pzErrmsg = pzErrmsg;
  184103. return rc;
  184104. }
  184105. /*
  184106. ** This is the xEof method of the virtual table. SQLite calls this
  184107. ** routine to find out if it has reached the end of a result set.
  184108. */
  184109. static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
  184110. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  184111. return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
  184112. }
  184113. /*
  184114. ** Return the rowid that the cursor currently points to.
  184115. */
  184116. static i64 fts5CursorRowid(Fts5Cursor *pCsr){
  184117. assert( pCsr->ePlan==FTS5_PLAN_MATCH
  184118. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  184119. || pCsr->ePlan==FTS5_PLAN_SOURCE
  184120. );
  184121. if( pCsr->pSorter ){
  184122. return pCsr->pSorter->iRowid;
  184123. }else{
  184124. return sqlite3Fts5ExprRowid(pCsr->pExpr);
  184125. }
  184126. }
  184127. /*
  184128. ** This is the xRowid method. The SQLite core calls this routine to
  184129. ** retrieve the rowid for the current row of the result set. fts5
  184130. ** exposes %_content.rowid as the rowid for the virtual table. The
  184131. ** rowid should be written to *pRowid.
  184132. */
  184133. static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  184134. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  184135. int ePlan = pCsr->ePlan;
  184136. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  184137. switch( ePlan ){
  184138. case FTS5_PLAN_SPECIAL:
  184139. *pRowid = 0;
  184140. break;
  184141. case FTS5_PLAN_SOURCE:
  184142. case FTS5_PLAN_MATCH:
  184143. case FTS5_PLAN_SORTED_MATCH:
  184144. *pRowid = fts5CursorRowid(pCsr);
  184145. break;
  184146. default:
  184147. *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
  184148. break;
  184149. }
  184150. return SQLITE_OK;
  184151. }
  184152. /*
  184153. ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
  184154. ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
  184155. **
  184156. ** If argument bErrormsg is true and an error occurs, an error message may
  184157. ** be left in sqlite3_vtab.zErrMsg.
  184158. */
  184159. static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
  184160. int rc = SQLITE_OK;
  184161. /* If the cursor does not yet have a statement handle, obtain one now. */
  184162. if( pCsr->pStmt==0 ){
  184163. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  184164. int eStmt = fts5StmtType(pCsr);
  184165. rc = sqlite3Fts5StorageStmt(
  184166. pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
  184167. );
  184168. assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
  184169. assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
  184170. }
  184171. if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
  184172. assert( pCsr->pExpr );
  184173. sqlite3_reset(pCsr->pStmt);
  184174. sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
  184175. rc = sqlite3_step(pCsr->pStmt);
  184176. if( rc==SQLITE_ROW ){
  184177. rc = SQLITE_OK;
  184178. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
  184179. }else{
  184180. rc = sqlite3_reset(pCsr->pStmt);
  184181. if( rc==SQLITE_OK ){
  184182. rc = FTS5_CORRUPT;
  184183. }
  184184. }
  184185. }
  184186. return rc;
  184187. }
  184188. static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
  184189. va_list ap; /* ... printf arguments */
  184190. va_start(ap, zFormat);
  184191. assert( p->base.zErrMsg==0 );
  184192. p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
  184193. va_end(ap);
  184194. }
  184195. /*
  184196. ** This function is called to handle an FTS INSERT command. In other words,
  184197. ** an INSERT statement of the form:
  184198. **
  184199. ** INSERT INTO fts(fts) VALUES($pCmd)
  184200. ** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
  184201. **
  184202. ** Argument pVal is the value assigned to column "fts" by the INSERT
  184203. ** statement. This function returns SQLITE_OK if successful, or an SQLite
  184204. ** error code if an error occurs.
  184205. **
  184206. ** The commands implemented by this function are documented in the "Special
  184207. ** INSERT Directives" section of the documentation. It should be updated if
  184208. ** more commands are added to this function.
  184209. */
  184210. static int fts5SpecialInsert(
  184211. Fts5Table *pTab, /* Fts5 table object */
  184212. const char *zCmd, /* Text inserted into table-name column */
  184213. sqlite3_value *pVal /* Value inserted into rank column */
  184214. ){
  184215. Fts5Config *pConfig = pTab->pConfig;
  184216. int rc = SQLITE_OK;
  184217. int bError = 0;
  184218. if( 0==sqlite3_stricmp("delete-all", zCmd) ){
  184219. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  184220. fts5SetVtabError(pTab,
  184221. "'delete-all' may only be used with a "
  184222. "contentless or external content fts5 table"
  184223. );
  184224. rc = SQLITE_ERROR;
  184225. }else{
  184226. rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
  184227. }
  184228. }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
  184229. if( pConfig->eContent==FTS5_CONTENT_NONE ){
  184230. fts5SetVtabError(pTab,
  184231. "'rebuild' may not be used with a contentless fts5 table"
  184232. );
  184233. rc = SQLITE_ERROR;
  184234. }else{
  184235. rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
  184236. }
  184237. }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
  184238. rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
  184239. }else if( 0==sqlite3_stricmp("merge", zCmd) ){
  184240. int nMerge = sqlite3_value_int(pVal);
  184241. rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
  184242. }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
  184243. rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
  184244. #ifdef SQLITE_DEBUG
  184245. }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
  184246. pConfig->bPrefixIndex = sqlite3_value_int(pVal);
  184247. #endif
  184248. }else{
  184249. rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
  184250. if( rc==SQLITE_OK ){
  184251. rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
  184252. }
  184253. if( rc==SQLITE_OK ){
  184254. if( bError ){
  184255. rc = SQLITE_ERROR;
  184256. }else{
  184257. rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
  184258. }
  184259. }
  184260. }
  184261. return rc;
  184262. }
  184263. static int fts5SpecialDelete(
  184264. Fts5Table *pTab,
  184265. sqlite3_value **apVal
  184266. ){
  184267. int rc = SQLITE_OK;
  184268. int eType1 = sqlite3_value_type(apVal[1]);
  184269. if( eType1==SQLITE_INTEGER ){
  184270. sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
  184271. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
  184272. }
  184273. return rc;
  184274. }
  184275. static void fts5StorageInsert(
  184276. int *pRc,
  184277. Fts5Table *pTab,
  184278. sqlite3_value **apVal,
  184279. i64 *piRowid
  184280. ){
  184281. int rc = *pRc;
  184282. if( rc==SQLITE_OK ){
  184283. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
  184284. }
  184285. if( rc==SQLITE_OK ){
  184286. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
  184287. }
  184288. *pRc = rc;
  184289. }
  184290. /*
  184291. ** This function is the implementation of the xUpdate callback used by
  184292. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  184293. ** inserted, updated or deleted.
  184294. **
  184295. ** A delete specifies a single argument - the rowid of the row to remove.
  184296. **
  184297. ** Update and insert operations pass:
  184298. **
  184299. ** 1. The "old" rowid, or NULL.
  184300. ** 2. The "new" rowid.
  184301. ** 3. Values for each of the nCol matchable columns.
  184302. ** 4. Values for the two hidden columns (<tablename> and "rank").
  184303. */
  184304. static int fts5UpdateMethod(
  184305. sqlite3_vtab *pVtab, /* Virtual table handle */
  184306. int nArg, /* Size of argument array */
  184307. sqlite3_value **apVal, /* Array of arguments */
  184308. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  184309. ){
  184310. Fts5Table *pTab = (Fts5Table*)pVtab;
  184311. Fts5Config *pConfig = pTab->pConfig;
  184312. int eType0; /* value_type() of apVal[0] */
  184313. int rc = SQLITE_OK; /* Return code */
  184314. /* A transaction must be open when this is called. */
  184315. assert( pTab->ts.eState==1 );
  184316. assert( pVtab->zErrMsg==0 );
  184317. assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
  184318. assert( nArg==1
  184319. || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
  184320. || sqlite3_value_type(apVal[1])==SQLITE_NULL
  184321. );
  184322. assert( pTab->pConfig->pzErrmsg==0 );
  184323. pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
  184324. /* Put any active cursors into REQUIRE_SEEK state. */
  184325. fts5TripCursors(pTab);
  184326. eType0 = sqlite3_value_type(apVal[0]);
  184327. if( eType0==SQLITE_NULL
  184328. && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
  184329. ){
  184330. /* A "special" INSERT op. These are handled separately. */
  184331. const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
  184332. if( pConfig->eContent!=FTS5_CONTENT_NORMAL
  184333. && 0==sqlite3_stricmp("delete", z)
  184334. ){
  184335. rc = fts5SpecialDelete(pTab, apVal);
  184336. }else{
  184337. rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
  184338. }
  184339. }else{
  184340. /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
  184341. ** any conflict on the rowid value must be detected before any
  184342. ** modifications are made to the database file. There are 4 cases:
  184343. **
  184344. ** 1) DELETE
  184345. ** 2) UPDATE (rowid not modified)
  184346. ** 3) UPDATE (rowid modified)
  184347. ** 4) INSERT
  184348. **
  184349. ** Cases 3 and 4 may violate the rowid constraint.
  184350. */
  184351. int eConflict = SQLITE_ABORT;
  184352. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  184353. eConflict = sqlite3_vtab_on_conflict(pConfig->db);
  184354. }
  184355. assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
  184356. assert( nArg!=1 || eType0==SQLITE_INTEGER );
  184357. /* Filter out attempts to run UPDATE or DELETE on contentless tables.
  184358. ** This is not suported. */
  184359. if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
  184360. pTab->base.zErrMsg = sqlite3_mprintf(
  184361. "cannot %s contentless fts5 table: %s",
  184362. (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
  184363. );
  184364. rc = SQLITE_ERROR;
  184365. }
  184366. /* DELETE */
  184367. else if( nArg==1 ){
  184368. i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */
  184369. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
  184370. }
  184371. /* INSERT */
  184372. else if( eType0!=SQLITE_INTEGER ){
  184373. /* If this is a REPLACE, first remove the current entry (if any) */
  184374. if( eConflict==SQLITE_REPLACE
  184375. && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
  184376. ){
  184377. i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */
  184378. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  184379. }
  184380. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  184381. }
  184382. /* UPDATE */
  184383. else{
  184384. i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */
  184385. i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */
  184386. if( iOld!=iNew ){
  184387. if( eConflict==SQLITE_REPLACE ){
  184388. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  184389. if( rc==SQLITE_OK ){
  184390. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  184391. }
  184392. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  184393. }else{
  184394. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
  184395. if( rc==SQLITE_OK ){
  184396. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  184397. }
  184398. if( rc==SQLITE_OK ){
  184399. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
  184400. }
  184401. }
  184402. }else{
  184403. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  184404. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  184405. }
  184406. }
  184407. }
  184408. pTab->pConfig->pzErrmsg = 0;
  184409. return rc;
  184410. }
  184411. /*
  184412. ** Implementation of xSync() method.
  184413. */
  184414. static int fts5SyncMethod(sqlite3_vtab *pVtab){
  184415. int rc;
  184416. Fts5Table *pTab = (Fts5Table*)pVtab;
  184417. fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
  184418. pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
  184419. fts5TripCursors(pTab);
  184420. rc = sqlite3Fts5StorageSync(pTab->pStorage);
  184421. pTab->pConfig->pzErrmsg = 0;
  184422. return rc;
  184423. }
  184424. /*
  184425. ** Implementation of xBegin() method.
  184426. */
  184427. static int fts5BeginMethod(sqlite3_vtab *pVtab){
  184428. fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
  184429. fts5NewTransaction((Fts5Table*)pVtab);
  184430. return SQLITE_OK;
  184431. }
  184432. /*
  184433. ** Implementation of xCommit() method. This is a no-op. The contents of
  184434. ** the pending-terms hash-table have already been flushed into the database
  184435. ** by fts5SyncMethod().
  184436. */
  184437. static int fts5CommitMethod(sqlite3_vtab *pVtab){
  184438. UNUSED_PARAM(pVtab); /* Call below is a no-op for NDEBUG builds */
  184439. fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
  184440. return SQLITE_OK;
  184441. }
  184442. /*
  184443. ** Implementation of xRollback(). Discard the contents of the pending-terms
  184444. ** hash-table. Any changes made to the database are reverted by SQLite.
  184445. */
  184446. static int fts5RollbackMethod(sqlite3_vtab *pVtab){
  184447. int rc;
  184448. Fts5Table *pTab = (Fts5Table*)pVtab;
  184449. fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
  184450. rc = sqlite3Fts5StorageRollback(pTab->pStorage);
  184451. return rc;
  184452. }
  184453. static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
  184454. static void *fts5ApiUserData(Fts5Context *pCtx){
  184455. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184456. return pCsr->pAux->pUserData;
  184457. }
  184458. static int fts5ApiColumnCount(Fts5Context *pCtx){
  184459. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184460. return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
  184461. }
  184462. static int fts5ApiColumnTotalSize(
  184463. Fts5Context *pCtx,
  184464. int iCol,
  184465. sqlite3_int64 *pnToken
  184466. ){
  184467. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184468. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  184469. return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
  184470. }
  184471. static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
  184472. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184473. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  184474. return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
  184475. }
  184476. static int fts5ApiTokenize(
  184477. Fts5Context *pCtx,
  184478. const char *pText, int nText,
  184479. void *pUserData,
  184480. int (*xToken)(void*, int, const char*, int, int, int)
  184481. ){
  184482. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184483. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  184484. return sqlite3Fts5Tokenize(
  184485. pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
  184486. );
  184487. }
  184488. static int fts5ApiPhraseCount(Fts5Context *pCtx){
  184489. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184490. return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  184491. }
  184492. static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
  184493. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184494. return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
  184495. }
  184496. static int fts5ApiColumnText(
  184497. Fts5Context *pCtx,
  184498. int iCol,
  184499. const char **pz,
  184500. int *pn
  184501. ){
  184502. int rc = SQLITE_OK;
  184503. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184504. if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
  184505. *pz = 0;
  184506. *pn = 0;
  184507. }else{
  184508. rc = fts5SeekCursor(pCsr, 0);
  184509. if( rc==SQLITE_OK ){
  184510. *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
  184511. *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  184512. }
  184513. }
  184514. return rc;
  184515. }
  184516. static int fts5CsrPoslist(
  184517. Fts5Cursor *pCsr,
  184518. int iPhrase,
  184519. const u8 **pa,
  184520. int *pn
  184521. ){
  184522. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  184523. int rc = SQLITE_OK;
  184524. int bLive = (pCsr->pSorter==0);
  184525. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
  184526. if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
  184527. Fts5PoslistPopulator *aPopulator;
  184528. int i;
  184529. aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
  184530. if( aPopulator==0 ) rc = SQLITE_NOMEM;
  184531. for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
  184532. int n; const char *z;
  184533. rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
  184534. if( rc==SQLITE_OK ){
  184535. rc = sqlite3Fts5ExprPopulatePoslists(
  184536. pConfig, pCsr->pExpr, aPopulator, i, z, n
  184537. );
  184538. }
  184539. }
  184540. sqlite3_free(aPopulator);
  184541. if( pCsr->pSorter ){
  184542. sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
  184543. }
  184544. }
  184545. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
  184546. }
  184547. if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
  184548. Fts5Sorter *pSorter = pCsr->pSorter;
  184549. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  184550. *pn = pSorter->aIdx[iPhrase] - i1;
  184551. *pa = &pSorter->aPoslist[i1];
  184552. }else{
  184553. *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
  184554. }
  184555. return rc;
  184556. }
  184557. /*
  184558. ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
  184559. ** correctly for the current view. Return SQLITE_OK if successful, or an
  184560. ** SQLite error code otherwise.
  184561. */
  184562. static int fts5CacheInstArray(Fts5Cursor *pCsr){
  184563. int rc = SQLITE_OK;
  184564. Fts5PoslistReader *aIter; /* One iterator for each phrase */
  184565. int nIter; /* Number of iterators/phrases */
  184566. nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  184567. if( pCsr->aInstIter==0 ){
  184568. int nByte = sizeof(Fts5PoslistReader) * nIter;
  184569. pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
  184570. }
  184571. aIter = pCsr->aInstIter;
  184572. if( aIter ){
  184573. int nInst = 0; /* Number instances seen so far */
  184574. int i;
  184575. /* Initialize all iterators */
  184576. for(i=0; i<nIter && rc==SQLITE_OK; i++){
  184577. const u8 *a;
  184578. int n;
  184579. rc = fts5CsrPoslist(pCsr, i, &a, &n);
  184580. if( rc==SQLITE_OK ){
  184581. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  184582. }
  184583. }
  184584. if( rc==SQLITE_OK ){
  184585. while( 1 ){
  184586. int *aInst;
  184587. int iBest = -1;
  184588. for(i=0; i<nIter; i++){
  184589. if( (aIter[i].bEof==0)
  184590. && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
  184591. ){
  184592. iBest = i;
  184593. }
  184594. }
  184595. if( iBest<0 ) break;
  184596. nInst++;
  184597. if( nInst>=pCsr->nInstAlloc ){
  184598. pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
  184599. aInst = (int*)sqlite3_realloc(
  184600. pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
  184601. );
  184602. if( aInst ){
  184603. pCsr->aInst = aInst;
  184604. }else{
  184605. rc = SQLITE_NOMEM;
  184606. break;
  184607. }
  184608. }
  184609. aInst = &pCsr->aInst[3 * (nInst-1)];
  184610. aInst[0] = iBest;
  184611. aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
  184612. aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
  184613. sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
  184614. }
  184615. }
  184616. pCsr->nInstCount = nInst;
  184617. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
  184618. }
  184619. return rc;
  184620. }
  184621. static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
  184622. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184623. int rc = SQLITE_OK;
  184624. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  184625. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
  184626. *pnInst = pCsr->nInstCount;
  184627. }
  184628. return rc;
  184629. }
  184630. static int fts5ApiInst(
  184631. Fts5Context *pCtx,
  184632. int iIdx,
  184633. int *piPhrase,
  184634. int *piCol,
  184635. int *piOff
  184636. ){
  184637. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184638. int rc = SQLITE_OK;
  184639. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  184640. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
  184641. ){
  184642. if( iIdx<0 || iIdx>=pCsr->nInstCount ){
  184643. rc = SQLITE_RANGE;
  184644. #if 0
  184645. }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
  184646. *piPhrase = pCsr->aInst[iIdx*3];
  184647. *piCol = pCsr->aInst[iIdx*3 + 2];
  184648. *piOff = -1;
  184649. #endif
  184650. }else{
  184651. *piPhrase = pCsr->aInst[iIdx*3];
  184652. *piCol = pCsr->aInst[iIdx*3 + 1];
  184653. *piOff = pCsr->aInst[iIdx*3 + 2];
  184654. }
  184655. }
  184656. return rc;
  184657. }
  184658. static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
  184659. return fts5CursorRowid((Fts5Cursor*)pCtx);
  184660. }
  184661. static int fts5ColumnSizeCb(
  184662. void *pContext, /* Pointer to int */
  184663. int tflags,
  184664. const char *pUnused, /* Buffer containing token */
  184665. int nUnused, /* Size of token in bytes */
  184666. int iUnused1, /* Start offset of token */
  184667. int iUnused2 /* End offset of token */
  184668. ){
  184669. int *pCnt = (int*)pContext;
  184670. UNUSED_PARAM2(pUnused, nUnused);
  184671. UNUSED_PARAM2(iUnused1, iUnused2);
  184672. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  184673. (*pCnt)++;
  184674. }
  184675. return SQLITE_OK;
  184676. }
  184677. static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
  184678. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184679. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  184680. Fts5Config *pConfig = pTab->pConfig;
  184681. int rc = SQLITE_OK;
  184682. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
  184683. if( pConfig->bColumnsize ){
  184684. i64 iRowid = fts5CursorRowid(pCsr);
  184685. rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
  184686. }else if( pConfig->zContent==0 ){
  184687. int i;
  184688. for(i=0; i<pConfig->nCol; i++){
  184689. if( pConfig->abUnindexed[i]==0 ){
  184690. pCsr->aColumnSize[i] = -1;
  184691. }
  184692. }
  184693. }else{
  184694. int i;
  184695. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  184696. if( pConfig->abUnindexed[i]==0 ){
  184697. const char *z; int n;
  184698. void *p = (void*)(&pCsr->aColumnSize[i]);
  184699. pCsr->aColumnSize[i] = 0;
  184700. rc = fts5ApiColumnText(pCtx, i, &z, &n);
  184701. if( rc==SQLITE_OK ){
  184702. rc = sqlite3Fts5Tokenize(
  184703. pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
  184704. );
  184705. }
  184706. }
  184707. }
  184708. }
  184709. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
  184710. }
  184711. if( iCol<0 ){
  184712. int i;
  184713. *pnToken = 0;
  184714. for(i=0; i<pConfig->nCol; i++){
  184715. *pnToken += pCsr->aColumnSize[i];
  184716. }
  184717. }else if( iCol<pConfig->nCol ){
  184718. *pnToken = pCsr->aColumnSize[iCol];
  184719. }else{
  184720. *pnToken = 0;
  184721. rc = SQLITE_RANGE;
  184722. }
  184723. return rc;
  184724. }
  184725. /*
  184726. ** Implementation of the xSetAuxdata() method.
  184727. */
  184728. static int fts5ApiSetAuxdata(
  184729. Fts5Context *pCtx, /* Fts5 context */
  184730. void *pPtr, /* Pointer to save as auxdata */
  184731. void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */
  184732. ){
  184733. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184734. Fts5Auxdata *pData;
  184735. /* Search through the cursors list of Fts5Auxdata objects for one that
  184736. ** corresponds to the currently executing auxiliary function. */
  184737. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  184738. if( pData->pAux==pCsr->pAux ) break;
  184739. }
  184740. if( pData ){
  184741. if( pData->xDelete ){
  184742. pData->xDelete(pData->pPtr);
  184743. }
  184744. }else{
  184745. int rc = SQLITE_OK;
  184746. pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
  184747. if( pData==0 ){
  184748. if( xDelete ) xDelete(pPtr);
  184749. return rc;
  184750. }
  184751. pData->pAux = pCsr->pAux;
  184752. pData->pNext = pCsr->pAuxdata;
  184753. pCsr->pAuxdata = pData;
  184754. }
  184755. pData->xDelete = xDelete;
  184756. pData->pPtr = pPtr;
  184757. return SQLITE_OK;
  184758. }
  184759. static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
  184760. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184761. Fts5Auxdata *pData;
  184762. void *pRet = 0;
  184763. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  184764. if( pData->pAux==pCsr->pAux ) break;
  184765. }
  184766. if( pData ){
  184767. pRet = pData->pPtr;
  184768. if( bClear ){
  184769. pData->pPtr = 0;
  184770. pData->xDelete = 0;
  184771. }
  184772. }
  184773. return pRet;
  184774. }
  184775. static void fts5ApiPhraseNext(
  184776. Fts5Context *pUnused,
  184777. Fts5PhraseIter *pIter,
  184778. int *piCol, int *piOff
  184779. ){
  184780. UNUSED_PARAM(pUnused);
  184781. if( pIter->a>=pIter->b ){
  184782. *piCol = -1;
  184783. *piOff = -1;
  184784. }else{
  184785. int iVal;
  184786. pIter->a += fts5GetVarint32(pIter->a, iVal);
  184787. if( iVal==1 ){
  184788. pIter->a += fts5GetVarint32(pIter->a, iVal);
  184789. *piCol = iVal;
  184790. *piOff = 0;
  184791. pIter->a += fts5GetVarint32(pIter->a, iVal);
  184792. }
  184793. *piOff += (iVal-2);
  184794. }
  184795. }
  184796. static int fts5ApiPhraseFirst(
  184797. Fts5Context *pCtx,
  184798. int iPhrase,
  184799. Fts5PhraseIter *pIter,
  184800. int *piCol, int *piOff
  184801. ){
  184802. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184803. int n;
  184804. int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  184805. if( rc==SQLITE_OK ){
  184806. pIter->b = &pIter->a[n];
  184807. *piCol = 0;
  184808. *piOff = 0;
  184809. fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
  184810. }
  184811. return rc;
  184812. }
  184813. static void fts5ApiPhraseNextColumn(
  184814. Fts5Context *pCtx,
  184815. Fts5PhraseIter *pIter,
  184816. int *piCol
  184817. ){
  184818. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184819. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  184820. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  184821. if( pIter->a>=pIter->b ){
  184822. *piCol = -1;
  184823. }else{
  184824. int iIncr;
  184825. pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
  184826. *piCol += (iIncr-2);
  184827. }
  184828. }else{
  184829. while( 1 ){
  184830. int dummy;
  184831. if( pIter->a>=pIter->b ){
  184832. *piCol = -1;
  184833. return;
  184834. }
  184835. if( pIter->a[0]==0x01 ) break;
  184836. pIter->a += fts5GetVarint32(pIter->a, dummy);
  184837. }
  184838. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  184839. }
  184840. }
  184841. static int fts5ApiPhraseFirstColumn(
  184842. Fts5Context *pCtx,
  184843. int iPhrase,
  184844. Fts5PhraseIter *pIter,
  184845. int *piCol
  184846. ){
  184847. int rc = SQLITE_OK;
  184848. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184849. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  184850. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  184851. Fts5Sorter *pSorter = pCsr->pSorter;
  184852. int n;
  184853. if( pSorter ){
  184854. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  184855. n = pSorter->aIdx[iPhrase] - i1;
  184856. pIter->a = &pSorter->aPoslist[i1];
  184857. }else{
  184858. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
  184859. }
  184860. if( rc==SQLITE_OK ){
  184861. pIter->b = &pIter->a[n];
  184862. *piCol = 0;
  184863. fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
  184864. }
  184865. }else{
  184866. int n;
  184867. rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  184868. if( rc==SQLITE_OK ){
  184869. pIter->b = &pIter->a[n];
  184870. if( n<=0 ){
  184871. *piCol = -1;
  184872. }else if( pIter->a[0]==0x01 ){
  184873. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  184874. }else{
  184875. *piCol = 0;
  184876. }
  184877. }
  184878. }
  184879. return rc;
  184880. }
  184881. static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
  184882. int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
  184883. );
  184884. static const Fts5ExtensionApi sFts5Api = {
  184885. 2, /* iVersion */
  184886. fts5ApiUserData,
  184887. fts5ApiColumnCount,
  184888. fts5ApiRowCount,
  184889. fts5ApiColumnTotalSize,
  184890. fts5ApiTokenize,
  184891. fts5ApiPhraseCount,
  184892. fts5ApiPhraseSize,
  184893. fts5ApiInstCount,
  184894. fts5ApiInst,
  184895. fts5ApiRowid,
  184896. fts5ApiColumnText,
  184897. fts5ApiColumnSize,
  184898. fts5ApiQueryPhrase,
  184899. fts5ApiSetAuxdata,
  184900. fts5ApiGetAuxdata,
  184901. fts5ApiPhraseFirst,
  184902. fts5ApiPhraseNext,
  184903. fts5ApiPhraseFirstColumn,
  184904. fts5ApiPhraseNextColumn,
  184905. };
  184906. /*
  184907. ** Implementation of API function xQueryPhrase().
  184908. */
  184909. static int fts5ApiQueryPhrase(
  184910. Fts5Context *pCtx,
  184911. int iPhrase,
  184912. void *pUserData,
  184913. int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
  184914. ){
  184915. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  184916. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  184917. int rc;
  184918. Fts5Cursor *pNew = 0;
  184919. rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
  184920. if( rc==SQLITE_OK ){
  184921. pNew->ePlan = FTS5_PLAN_MATCH;
  184922. pNew->iFirstRowid = SMALLEST_INT64;
  184923. pNew->iLastRowid = LARGEST_INT64;
  184924. pNew->base.pVtab = (sqlite3_vtab*)pTab;
  184925. rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
  184926. }
  184927. if( rc==SQLITE_OK ){
  184928. for(rc = fts5CursorFirst(pTab, pNew, 0);
  184929. rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
  184930. rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
  184931. ){
  184932. rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
  184933. if( rc!=SQLITE_OK ){
  184934. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  184935. break;
  184936. }
  184937. }
  184938. }
  184939. fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
  184940. return rc;
  184941. }
  184942. static void fts5ApiInvoke(
  184943. Fts5Auxiliary *pAux,
  184944. Fts5Cursor *pCsr,
  184945. sqlite3_context *context,
  184946. int argc,
  184947. sqlite3_value **argv
  184948. ){
  184949. assert( pCsr->pAux==0 );
  184950. pCsr->pAux = pAux;
  184951. pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
  184952. pCsr->pAux = 0;
  184953. }
  184954. static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
  184955. Fts5Cursor *pCsr;
  184956. for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  184957. if( pCsr->iCsrId==iCsrId ) break;
  184958. }
  184959. return pCsr;
  184960. }
  184961. static void fts5ApiCallback(
  184962. sqlite3_context *context,
  184963. int argc,
  184964. sqlite3_value **argv
  184965. ){
  184966. Fts5Auxiliary *pAux;
  184967. Fts5Cursor *pCsr;
  184968. i64 iCsrId;
  184969. assert( argc>=1 );
  184970. pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
  184971. iCsrId = sqlite3_value_int64(argv[0]);
  184972. pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
  184973. if( pCsr==0 ){
  184974. char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
  184975. sqlite3_result_error(context, zErr, -1);
  184976. sqlite3_free(zErr);
  184977. }else{
  184978. fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
  184979. }
  184980. }
  184981. /*
  184982. ** Given cursor id iId, return a pointer to the corresponding Fts5Index
  184983. ** object. Or NULL If the cursor id does not exist.
  184984. **
  184985. ** If successful, set *ppConfig to point to the associated config object
  184986. ** before returning.
  184987. */
  184988. static Fts5Index *sqlite3Fts5IndexFromCsrid(
  184989. Fts5Global *pGlobal, /* FTS5 global context for db handle */
  184990. i64 iCsrId, /* Id of cursor to find */
  184991. Fts5Config **ppConfig /* OUT: Configuration object */
  184992. ){
  184993. Fts5Cursor *pCsr;
  184994. Fts5Table *pTab;
  184995. pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
  184996. pTab = (Fts5Table*)pCsr->base.pVtab;
  184997. *ppConfig = pTab->pConfig;
  184998. return pTab->pIndex;
  184999. }
  185000. /*
  185001. ** Return a "position-list blob" corresponding to the current position of
  185002. ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
  185003. ** the current position-list for each phrase in the query associated with
  185004. ** cursor pCsr.
  185005. **
  185006. ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
  185007. ** the number of phrases in the query. Following the varints are the
  185008. ** concatenated position lists for each phrase, in order.
  185009. **
  185010. ** The first varint (if it exists) contains the size of the position list
  185011. ** for phrase 0. The second (same disclaimer) contains the size of position
  185012. ** list 1. And so on. There is no size field for the final position list,
  185013. ** as it can be derived from the total size of the blob.
  185014. */
  185015. static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
  185016. int i;
  185017. int rc = SQLITE_OK;
  185018. int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  185019. Fts5Buffer val;
  185020. memset(&val, 0, sizeof(Fts5Buffer));
  185021. switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
  185022. case FTS5_DETAIL_FULL:
  185023. /* Append the varints */
  185024. for(i=0; i<(nPhrase-1); i++){
  185025. const u8 *dummy;
  185026. int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
  185027. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  185028. }
  185029. /* Append the position lists */
  185030. for(i=0; i<nPhrase; i++){
  185031. const u8 *pPoslist;
  185032. int nPoslist;
  185033. nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
  185034. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  185035. }
  185036. break;
  185037. case FTS5_DETAIL_COLUMNS:
  185038. /* Append the varints */
  185039. for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
  185040. const u8 *dummy;
  185041. int nByte;
  185042. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
  185043. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  185044. }
  185045. /* Append the position lists */
  185046. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  185047. const u8 *pPoslist;
  185048. int nPoslist;
  185049. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
  185050. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  185051. }
  185052. break;
  185053. default:
  185054. break;
  185055. }
  185056. sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
  185057. return rc;
  185058. }
  185059. /*
  185060. ** This is the xColumn method, called by SQLite to request a value from
  185061. ** the row that the supplied cursor currently points to.
  185062. */
  185063. static int fts5ColumnMethod(
  185064. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  185065. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  185066. int iCol /* Index of column to read value from */
  185067. ){
  185068. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  185069. Fts5Config *pConfig = pTab->pConfig;
  185070. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  185071. int rc = SQLITE_OK;
  185072. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  185073. if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
  185074. if( iCol==pConfig->nCol ){
  185075. sqlite3_result_int64(pCtx, pCsr->iSpecial);
  185076. }
  185077. }else
  185078. if( iCol==pConfig->nCol ){
  185079. /* User is requesting the value of the special column with the same name
  185080. ** as the table. Return the cursor integer id number. This value is only
  185081. ** useful in that it may be passed as the first argument to an FTS5
  185082. ** auxiliary function. */
  185083. sqlite3_result_int64(pCtx, pCsr->iCsrId);
  185084. }else if( iCol==pConfig->nCol+1 ){
  185085. /* The value of the "rank" column. */
  185086. if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
  185087. fts5PoslistBlob(pCtx, pCsr);
  185088. }else if(
  185089. pCsr->ePlan==FTS5_PLAN_MATCH
  185090. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  185091. ){
  185092. if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
  185093. fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
  185094. }
  185095. }
  185096. }else if( !fts5IsContentless(pTab) ){
  185097. rc = fts5SeekCursor(pCsr, 1);
  185098. if( rc==SQLITE_OK ){
  185099. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  185100. }
  185101. }
  185102. return rc;
  185103. }
  185104. /*
  185105. ** This routine implements the xFindFunction method for the FTS3
  185106. ** virtual table.
  185107. */
  185108. static int fts5FindFunctionMethod(
  185109. sqlite3_vtab *pVtab, /* Virtual table handle */
  185110. int nUnused, /* Number of SQL function arguments */
  185111. const char *zName, /* Name of SQL function */
  185112. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  185113. void **ppArg /* OUT: User data for *pxFunc */
  185114. ){
  185115. Fts5Table *pTab = (Fts5Table*)pVtab;
  185116. Fts5Auxiliary *pAux;
  185117. UNUSED_PARAM(nUnused);
  185118. pAux = fts5FindAuxiliary(pTab, zName);
  185119. if( pAux ){
  185120. *pxFunc = fts5ApiCallback;
  185121. *ppArg = (void*)pAux;
  185122. return 1;
  185123. }
  185124. /* No function of the specified name was found. Return 0. */
  185125. return 0;
  185126. }
  185127. /*
  185128. ** Implementation of FTS5 xRename method. Rename an fts5 table.
  185129. */
  185130. static int fts5RenameMethod(
  185131. sqlite3_vtab *pVtab, /* Virtual table handle */
  185132. const char *zName /* New name of table */
  185133. ){
  185134. Fts5Table *pTab = (Fts5Table*)pVtab;
  185135. return sqlite3Fts5StorageRename(pTab->pStorage, zName);
  185136. }
  185137. /*
  185138. ** The xSavepoint() method.
  185139. **
  185140. ** Flush the contents of the pending-terms table to disk.
  185141. */
  185142. static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  185143. Fts5Table *pTab = (Fts5Table*)pVtab;
  185144. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  185145. fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
  185146. fts5TripCursors(pTab);
  185147. return sqlite3Fts5StorageSync(pTab->pStorage);
  185148. }
  185149. /*
  185150. ** The xRelease() method.
  185151. **
  185152. ** This is a no-op.
  185153. */
  185154. static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  185155. Fts5Table *pTab = (Fts5Table*)pVtab;
  185156. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  185157. fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
  185158. fts5TripCursors(pTab);
  185159. return sqlite3Fts5StorageSync(pTab->pStorage);
  185160. }
  185161. /*
  185162. ** The xRollbackTo() method.
  185163. **
  185164. ** Discard the contents of the pending terms table.
  185165. */
  185166. static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  185167. Fts5Table *pTab = (Fts5Table*)pVtab;
  185168. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  185169. fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
  185170. fts5TripCursors(pTab);
  185171. return sqlite3Fts5StorageRollback(pTab->pStorage);
  185172. }
  185173. /*
  185174. ** Register a new auxiliary function with global context pGlobal.
  185175. */
  185176. static int fts5CreateAux(
  185177. fts5_api *pApi, /* Global context (one per db handle) */
  185178. const char *zName, /* Name of new function */
  185179. void *pUserData, /* User data for aux. function */
  185180. fts5_extension_function xFunc, /* Aux. function implementation */
  185181. void(*xDestroy)(void*) /* Destructor for pUserData */
  185182. ){
  185183. Fts5Global *pGlobal = (Fts5Global*)pApi;
  185184. int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
  185185. if( rc==SQLITE_OK ){
  185186. Fts5Auxiliary *pAux;
  185187. int nName; /* Size of zName in bytes, including \0 */
  185188. int nByte; /* Bytes of space to allocate */
  185189. nName = (int)strlen(zName) + 1;
  185190. nByte = sizeof(Fts5Auxiliary) + nName;
  185191. pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
  185192. if( pAux ){
  185193. memset(pAux, 0, nByte);
  185194. pAux->zFunc = (char*)&pAux[1];
  185195. memcpy(pAux->zFunc, zName, nName);
  185196. pAux->pGlobal = pGlobal;
  185197. pAux->pUserData = pUserData;
  185198. pAux->xFunc = xFunc;
  185199. pAux->xDestroy = xDestroy;
  185200. pAux->pNext = pGlobal->pAux;
  185201. pGlobal->pAux = pAux;
  185202. }else{
  185203. rc = SQLITE_NOMEM;
  185204. }
  185205. }
  185206. return rc;
  185207. }
  185208. /*
  185209. ** Register a new tokenizer. This is the implementation of the
  185210. ** fts5_api.xCreateTokenizer() method.
  185211. */
  185212. static int fts5CreateTokenizer(
  185213. fts5_api *pApi, /* Global context (one per db handle) */
  185214. const char *zName, /* Name of new function */
  185215. void *pUserData, /* User data for aux. function */
  185216. fts5_tokenizer *pTokenizer, /* Tokenizer implementation */
  185217. void(*xDestroy)(void*) /* Destructor for pUserData */
  185218. ){
  185219. Fts5Global *pGlobal = (Fts5Global*)pApi;
  185220. Fts5TokenizerModule *pNew;
  185221. int nName; /* Size of zName and its \0 terminator */
  185222. int nByte; /* Bytes of space to allocate */
  185223. int rc = SQLITE_OK;
  185224. nName = (int)strlen(zName) + 1;
  185225. nByte = sizeof(Fts5TokenizerModule) + nName;
  185226. pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
  185227. if( pNew ){
  185228. memset(pNew, 0, nByte);
  185229. pNew->zName = (char*)&pNew[1];
  185230. memcpy(pNew->zName, zName, nName);
  185231. pNew->pUserData = pUserData;
  185232. pNew->x = *pTokenizer;
  185233. pNew->xDestroy = xDestroy;
  185234. pNew->pNext = pGlobal->pTok;
  185235. pGlobal->pTok = pNew;
  185236. if( pNew->pNext==0 ){
  185237. pGlobal->pDfltTok = pNew;
  185238. }
  185239. }else{
  185240. rc = SQLITE_NOMEM;
  185241. }
  185242. return rc;
  185243. }
  185244. static Fts5TokenizerModule *fts5LocateTokenizer(
  185245. Fts5Global *pGlobal,
  185246. const char *zName
  185247. ){
  185248. Fts5TokenizerModule *pMod = 0;
  185249. if( zName==0 ){
  185250. pMod = pGlobal->pDfltTok;
  185251. }else{
  185252. for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
  185253. if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
  185254. }
  185255. }
  185256. return pMod;
  185257. }
  185258. /*
  185259. ** Find a tokenizer. This is the implementation of the
  185260. ** fts5_api.xFindTokenizer() method.
  185261. */
  185262. static int fts5FindTokenizer(
  185263. fts5_api *pApi, /* Global context (one per db handle) */
  185264. const char *zName, /* Name of new function */
  185265. void **ppUserData,
  185266. fts5_tokenizer *pTokenizer /* Populate this object */
  185267. ){
  185268. int rc = SQLITE_OK;
  185269. Fts5TokenizerModule *pMod;
  185270. pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
  185271. if( pMod ){
  185272. *pTokenizer = pMod->x;
  185273. *ppUserData = pMod->pUserData;
  185274. }else{
  185275. memset(pTokenizer, 0, sizeof(fts5_tokenizer));
  185276. rc = SQLITE_ERROR;
  185277. }
  185278. return rc;
  185279. }
  185280. static int sqlite3Fts5GetTokenizer(
  185281. Fts5Global *pGlobal,
  185282. const char **azArg,
  185283. int nArg,
  185284. Fts5Tokenizer **ppTok,
  185285. fts5_tokenizer **ppTokApi,
  185286. char **pzErr
  185287. ){
  185288. Fts5TokenizerModule *pMod;
  185289. int rc = SQLITE_OK;
  185290. pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
  185291. if( pMod==0 ){
  185292. assert( nArg>0 );
  185293. rc = SQLITE_ERROR;
  185294. *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
  185295. }else{
  185296. rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
  185297. *ppTokApi = &pMod->x;
  185298. if( rc!=SQLITE_OK && pzErr ){
  185299. *pzErr = sqlite3_mprintf("error in tokenizer constructor");
  185300. }
  185301. }
  185302. if( rc!=SQLITE_OK ){
  185303. *ppTokApi = 0;
  185304. *ppTok = 0;
  185305. }
  185306. return rc;
  185307. }
  185308. static void fts5ModuleDestroy(void *pCtx){
  185309. Fts5TokenizerModule *pTok, *pNextTok;
  185310. Fts5Auxiliary *pAux, *pNextAux;
  185311. Fts5Global *pGlobal = (Fts5Global*)pCtx;
  185312. for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
  185313. pNextAux = pAux->pNext;
  185314. if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
  185315. sqlite3_free(pAux);
  185316. }
  185317. for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
  185318. pNextTok = pTok->pNext;
  185319. if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
  185320. sqlite3_free(pTok);
  185321. }
  185322. sqlite3_free(pGlobal);
  185323. }
  185324. static void fts5Fts5Func(
  185325. sqlite3_context *pCtx, /* Function call context */
  185326. int nArg, /* Number of args */
  185327. sqlite3_value **apUnused /* Function arguments */
  185328. ){
  185329. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  185330. char buf[8];
  185331. UNUSED_PARAM2(nArg, apUnused);
  185332. assert( nArg==0 );
  185333. assert( sizeof(buf)>=sizeof(pGlobal) );
  185334. memcpy(buf, (void*)&pGlobal, sizeof(pGlobal));
  185335. sqlite3_result_blob(pCtx, buf, sizeof(pGlobal), SQLITE_TRANSIENT);
  185336. }
  185337. /*
  185338. ** Implementation of fts5_source_id() function.
  185339. */
  185340. static void fts5SourceIdFunc(
  185341. sqlite3_context *pCtx, /* Function call context */
  185342. int nArg, /* Number of args */
  185343. sqlite3_value **apUnused /* Function arguments */
  185344. ){
  185345. assert( nArg==0 );
  185346. UNUSED_PARAM2(nArg, apUnused);
  185347. sqlite3_result_text(pCtx, "fts5: 2017-06-08 14:26:16 0ee482a1e0eae22e08edc8978c9733a96603d4509645f348ebf55b579e89636b", -1, SQLITE_TRANSIENT);
  185348. }
  185349. static int fts5Init(sqlite3 *db){
  185350. static const sqlite3_module fts5Mod = {
  185351. /* iVersion */ 2,
  185352. /* xCreate */ fts5CreateMethod,
  185353. /* xConnect */ fts5ConnectMethod,
  185354. /* xBestIndex */ fts5BestIndexMethod,
  185355. /* xDisconnect */ fts5DisconnectMethod,
  185356. /* xDestroy */ fts5DestroyMethod,
  185357. /* xOpen */ fts5OpenMethod,
  185358. /* xClose */ fts5CloseMethod,
  185359. /* xFilter */ fts5FilterMethod,
  185360. /* xNext */ fts5NextMethod,
  185361. /* xEof */ fts5EofMethod,
  185362. /* xColumn */ fts5ColumnMethod,
  185363. /* xRowid */ fts5RowidMethod,
  185364. /* xUpdate */ fts5UpdateMethod,
  185365. /* xBegin */ fts5BeginMethod,
  185366. /* xSync */ fts5SyncMethod,
  185367. /* xCommit */ fts5CommitMethod,
  185368. /* xRollback */ fts5RollbackMethod,
  185369. /* xFindFunction */ fts5FindFunctionMethod,
  185370. /* xRename */ fts5RenameMethod,
  185371. /* xSavepoint */ fts5SavepointMethod,
  185372. /* xRelease */ fts5ReleaseMethod,
  185373. /* xRollbackTo */ fts5RollbackToMethod,
  185374. };
  185375. int rc;
  185376. Fts5Global *pGlobal = 0;
  185377. pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
  185378. if( pGlobal==0 ){
  185379. rc = SQLITE_NOMEM;
  185380. }else{
  185381. void *p = (void*)pGlobal;
  185382. memset(pGlobal, 0, sizeof(Fts5Global));
  185383. pGlobal->db = db;
  185384. pGlobal->api.iVersion = 2;
  185385. pGlobal->api.xCreateFunction = fts5CreateAux;
  185386. pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
  185387. pGlobal->api.xFindTokenizer = fts5FindTokenizer;
  185388. rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
  185389. if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
  185390. if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
  185391. if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
  185392. if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
  185393. if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
  185394. if( rc==SQLITE_OK ){
  185395. rc = sqlite3_create_function(
  185396. db, "fts5", 0, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
  185397. );
  185398. }
  185399. if( rc==SQLITE_OK ){
  185400. rc = sqlite3_create_function(
  185401. db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
  185402. );
  185403. }
  185404. }
  185405. /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
  185406. ** fts5_test_mi.c is compiled and linked into the executable. And call
  185407. ** its entry point to enable the matchinfo() demo. */
  185408. #ifdef SQLITE_FTS5_ENABLE_TEST_MI
  185409. if( rc==SQLITE_OK ){
  185410. extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
  185411. rc = sqlite3Fts5TestRegisterMatchinfo(db);
  185412. }
  185413. #endif
  185414. return rc;
  185415. }
  185416. /*
  185417. ** The following functions are used to register the module with SQLite. If
  185418. ** this module is being built as part of the SQLite core (SQLITE_CORE is
  185419. ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
  185420. **
  185421. ** Or, if this module is being built as a loadable extension,
  185422. ** sqlite3Fts5Init() is omitted and the two standard entry points
  185423. ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
  185424. */
  185425. #ifndef SQLITE_CORE
  185426. #ifdef _WIN32
  185427. __declspec(dllexport)
  185428. #endif
  185429. SQLITE_API int sqlite3_fts_init(
  185430. sqlite3 *db,
  185431. char **pzErrMsg,
  185432. const sqlite3_api_routines *pApi
  185433. ){
  185434. SQLITE_EXTENSION_INIT2(pApi);
  185435. (void)pzErrMsg; /* Unused parameter */
  185436. return fts5Init(db);
  185437. }
  185438. #ifdef _WIN32
  185439. __declspec(dllexport)
  185440. #endif
  185441. SQLITE_API int sqlite3_fts5_init(
  185442. sqlite3 *db,
  185443. char **pzErrMsg,
  185444. const sqlite3_api_routines *pApi
  185445. ){
  185446. SQLITE_EXTENSION_INIT2(pApi);
  185447. (void)pzErrMsg; /* Unused parameter */
  185448. return fts5Init(db);
  185449. }
  185450. #else
  185451. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
  185452. return fts5Init(db);
  185453. }
  185454. #endif
  185455. /*
  185456. ** 2014 May 31
  185457. **
  185458. ** The author disclaims copyright to this source code. In place of
  185459. ** a legal notice, here is a blessing:
  185460. **
  185461. ** May you do good and not evil.
  185462. ** May you find forgiveness for yourself and forgive others.
  185463. ** May you share freely, never taking more than you give.
  185464. **
  185465. ******************************************************************************
  185466. **
  185467. */
  185468. /* #include "fts5Int.h" */
  185469. struct Fts5Storage {
  185470. Fts5Config *pConfig;
  185471. Fts5Index *pIndex;
  185472. int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */
  185473. i64 nTotalRow; /* Total number of rows in FTS table */
  185474. i64 *aTotalSize; /* Total sizes of each column */
  185475. sqlite3_stmt *aStmt[11];
  185476. };
  185477. #if FTS5_STMT_SCAN_ASC!=0
  185478. # error "FTS5_STMT_SCAN_ASC mismatch"
  185479. #endif
  185480. #if FTS5_STMT_SCAN_DESC!=1
  185481. # error "FTS5_STMT_SCAN_DESC mismatch"
  185482. #endif
  185483. #if FTS5_STMT_LOOKUP!=2
  185484. # error "FTS5_STMT_LOOKUP mismatch"
  185485. #endif
  185486. #define FTS5_STMT_INSERT_CONTENT 3
  185487. #define FTS5_STMT_REPLACE_CONTENT 4
  185488. #define FTS5_STMT_DELETE_CONTENT 5
  185489. #define FTS5_STMT_REPLACE_DOCSIZE 6
  185490. #define FTS5_STMT_DELETE_DOCSIZE 7
  185491. #define FTS5_STMT_LOOKUP_DOCSIZE 8
  185492. #define FTS5_STMT_REPLACE_CONFIG 9
  185493. #define FTS5_STMT_SCAN 10
  185494. /*
  185495. ** Prepare the two insert statements - Fts5Storage.pInsertContent and
  185496. ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
  185497. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  185498. ** occurs.
  185499. */
  185500. static int fts5StorageGetStmt(
  185501. Fts5Storage *p, /* Storage handle */
  185502. int eStmt, /* FTS5_STMT_XXX constant */
  185503. sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */
  185504. char **pzErrMsg /* OUT: Error message (if any) */
  185505. ){
  185506. int rc = SQLITE_OK;
  185507. /* If there is no %_docsize table, there should be no requests for
  185508. ** statements to operate on it. */
  185509. assert( p->pConfig->bColumnsize || (
  185510. eStmt!=FTS5_STMT_REPLACE_DOCSIZE
  185511. && eStmt!=FTS5_STMT_DELETE_DOCSIZE
  185512. && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
  185513. ));
  185514. assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
  185515. if( p->aStmt[eStmt]==0 ){
  185516. const char *azStmt[] = {
  185517. "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
  185518. "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
  185519. "SELECT %s FROM %s T WHERE T.%Q=?", /* LOOKUP */
  185520. "INSERT INTO %Q.'%q_content' VALUES(%s)", /* INSERT_CONTENT */
  185521. "REPLACE INTO %Q.'%q_content' VALUES(%s)", /* REPLACE_CONTENT */
  185522. "DELETE FROM %Q.'%q_content' WHERE id=?", /* DELETE_CONTENT */
  185523. "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* REPLACE_DOCSIZE */
  185524. "DELETE FROM %Q.'%q_docsize' WHERE id=?", /* DELETE_DOCSIZE */
  185525. "SELECT sz FROM %Q.'%q_docsize' WHERE id=?", /* LOOKUP_DOCSIZE */
  185526. "REPLACE INTO %Q.'%q_config' VALUES(?,?)", /* REPLACE_CONFIG */
  185527. "SELECT %s FROM %s AS T", /* SCAN */
  185528. };
  185529. Fts5Config *pC = p->pConfig;
  185530. char *zSql = 0;
  185531. switch( eStmt ){
  185532. case FTS5_STMT_SCAN:
  185533. zSql = sqlite3_mprintf(azStmt[eStmt],
  185534. pC->zContentExprlist, pC->zContent
  185535. );
  185536. break;
  185537. case FTS5_STMT_SCAN_ASC:
  185538. case FTS5_STMT_SCAN_DESC:
  185539. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
  185540. pC->zContent, pC->zContentRowid, pC->zContentRowid,
  185541. pC->zContentRowid
  185542. );
  185543. break;
  185544. case FTS5_STMT_LOOKUP:
  185545. zSql = sqlite3_mprintf(azStmt[eStmt],
  185546. pC->zContentExprlist, pC->zContent, pC->zContentRowid
  185547. );
  185548. break;
  185549. case FTS5_STMT_INSERT_CONTENT:
  185550. case FTS5_STMT_REPLACE_CONTENT: {
  185551. int nCol = pC->nCol + 1;
  185552. char *zBind;
  185553. int i;
  185554. zBind = sqlite3_malloc(1 + nCol*2);
  185555. if( zBind ){
  185556. for(i=0; i<nCol; i++){
  185557. zBind[i*2] = '?';
  185558. zBind[i*2 + 1] = ',';
  185559. }
  185560. zBind[i*2-1] = '\0';
  185561. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
  185562. sqlite3_free(zBind);
  185563. }
  185564. break;
  185565. }
  185566. default:
  185567. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
  185568. break;
  185569. }
  185570. if( zSql==0 ){
  185571. rc = SQLITE_NOMEM;
  185572. }else{
  185573. rc = sqlite3_prepare_v2(pC->db, zSql, -1, &p->aStmt[eStmt], 0);
  185574. sqlite3_free(zSql);
  185575. if( rc!=SQLITE_OK && pzErrMsg ){
  185576. *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
  185577. }
  185578. }
  185579. }
  185580. *ppStmt = p->aStmt[eStmt];
  185581. sqlite3_reset(*ppStmt);
  185582. return rc;
  185583. }
  185584. static int fts5ExecPrintf(
  185585. sqlite3 *db,
  185586. char **pzErr,
  185587. const char *zFormat,
  185588. ...
  185589. ){
  185590. int rc;
  185591. va_list ap; /* ... printf arguments */
  185592. char *zSql;
  185593. va_start(ap, zFormat);
  185594. zSql = sqlite3_vmprintf(zFormat, ap);
  185595. if( zSql==0 ){
  185596. rc = SQLITE_NOMEM;
  185597. }else{
  185598. rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
  185599. sqlite3_free(zSql);
  185600. }
  185601. va_end(ap);
  185602. return rc;
  185603. }
  185604. /*
  185605. ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
  185606. ** code otherwise.
  185607. */
  185608. static int sqlite3Fts5DropAll(Fts5Config *pConfig){
  185609. int rc = fts5ExecPrintf(pConfig->db, 0,
  185610. "DROP TABLE IF EXISTS %Q.'%q_data';"
  185611. "DROP TABLE IF EXISTS %Q.'%q_idx';"
  185612. "DROP TABLE IF EXISTS %Q.'%q_config';",
  185613. pConfig->zDb, pConfig->zName,
  185614. pConfig->zDb, pConfig->zName,
  185615. pConfig->zDb, pConfig->zName
  185616. );
  185617. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  185618. rc = fts5ExecPrintf(pConfig->db, 0,
  185619. "DROP TABLE IF EXISTS %Q.'%q_docsize';",
  185620. pConfig->zDb, pConfig->zName
  185621. );
  185622. }
  185623. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  185624. rc = fts5ExecPrintf(pConfig->db, 0,
  185625. "DROP TABLE IF EXISTS %Q.'%q_content';",
  185626. pConfig->zDb, pConfig->zName
  185627. );
  185628. }
  185629. return rc;
  185630. }
  185631. static void fts5StorageRenameOne(
  185632. Fts5Config *pConfig, /* Current FTS5 configuration */
  185633. int *pRc, /* IN/OUT: Error code */
  185634. const char *zTail, /* Tail of table name e.g. "data", "config" */
  185635. const char *zName /* New name of FTS5 table */
  185636. ){
  185637. if( *pRc==SQLITE_OK ){
  185638. *pRc = fts5ExecPrintf(pConfig->db, 0,
  185639. "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
  185640. pConfig->zDb, pConfig->zName, zTail, zName, zTail
  185641. );
  185642. }
  185643. }
  185644. static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
  185645. Fts5Config *pConfig = pStorage->pConfig;
  185646. int rc = sqlite3Fts5StorageSync(pStorage);
  185647. fts5StorageRenameOne(pConfig, &rc, "data", zName);
  185648. fts5StorageRenameOne(pConfig, &rc, "idx", zName);
  185649. fts5StorageRenameOne(pConfig, &rc, "config", zName);
  185650. if( pConfig->bColumnsize ){
  185651. fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
  185652. }
  185653. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  185654. fts5StorageRenameOne(pConfig, &rc, "content", zName);
  185655. }
  185656. return rc;
  185657. }
  185658. /*
  185659. ** Create the shadow table named zPost, with definition zDefn. Return
  185660. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  185661. */
  185662. static int sqlite3Fts5CreateTable(
  185663. Fts5Config *pConfig, /* FTS5 configuration */
  185664. const char *zPost, /* Shadow table to create (e.g. "content") */
  185665. const char *zDefn, /* Columns etc. for shadow table */
  185666. int bWithout, /* True for without rowid */
  185667. char **pzErr /* OUT: Error message */
  185668. ){
  185669. int rc;
  185670. char *zErr = 0;
  185671. rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
  185672. pConfig->zDb, pConfig->zName, zPost, zDefn,
  185673. #ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
  185674. bWithout?" WITHOUT ROWID":
  185675. #endif
  185676. ""
  185677. );
  185678. if( zErr ){
  185679. *pzErr = sqlite3_mprintf(
  185680. "fts5: error creating shadow table %q_%s: %s",
  185681. pConfig->zName, zPost, zErr
  185682. );
  185683. sqlite3_free(zErr);
  185684. }
  185685. return rc;
  185686. }
  185687. /*
  185688. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  185689. ** and initialize the underlying tables
  185690. **
  185691. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  185692. ** Otherwise, set *pp to NULL and return an SQLite error code.
  185693. */
  185694. static int sqlite3Fts5StorageOpen(
  185695. Fts5Config *pConfig,
  185696. Fts5Index *pIndex,
  185697. int bCreate,
  185698. Fts5Storage **pp,
  185699. char **pzErr /* OUT: Error message */
  185700. ){
  185701. int rc = SQLITE_OK;
  185702. Fts5Storage *p; /* New object */
  185703. int nByte; /* Bytes of space to allocate */
  185704. nByte = sizeof(Fts5Storage) /* Fts5Storage object */
  185705. + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */
  185706. *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
  185707. if( !p ) return SQLITE_NOMEM;
  185708. memset(p, 0, nByte);
  185709. p->aTotalSize = (i64*)&p[1];
  185710. p->pConfig = pConfig;
  185711. p->pIndex = pIndex;
  185712. if( bCreate ){
  185713. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  185714. int nDefn = 32 + pConfig->nCol*10;
  185715. char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
  185716. if( zDefn==0 ){
  185717. rc = SQLITE_NOMEM;
  185718. }else{
  185719. int i;
  185720. int iOff;
  185721. sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
  185722. iOff = (int)strlen(zDefn);
  185723. for(i=0; i<pConfig->nCol; i++){
  185724. sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
  185725. iOff += (int)strlen(&zDefn[iOff]);
  185726. }
  185727. rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
  185728. }
  185729. sqlite3_free(zDefn);
  185730. }
  185731. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  185732. rc = sqlite3Fts5CreateTable(
  185733. pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
  185734. );
  185735. }
  185736. if( rc==SQLITE_OK ){
  185737. rc = sqlite3Fts5CreateTable(
  185738. pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
  185739. );
  185740. }
  185741. if( rc==SQLITE_OK ){
  185742. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  185743. }
  185744. }
  185745. if( rc ){
  185746. sqlite3Fts5StorageClose(p);
  185747. *pp = 0;
  185748. }
  185749. return rc;
  185750. }
  185751. /*
  185752. ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
  185753. */
  185754. static int sqlite3Fts5StorageClose(Fts5Storage *p){
  185755. int rc = SQLITE_OK;
  185756. if( p ){
  185757. int i;
  185758. /* Finalize all SQL statements */
  185759. for(i=0; i<ArraySize(p->aStmt); i++){
  185760. sqlite3_finalize(p->aStmt[i]);
  185761. }
  185762. sqlite3_free(p);
  185763. }
  185764. return rc;
  185765. }
  185766. typedef struct Fts5InsertCtx Fts5InsertCtx;
  185767. struct Fts5InsertCtx {
  185768. Fts5Storage *pStorage;
  185769. int iCol;
  185770. int szCol; /* Size of column value in tokens */
  185771. };
  185772. /*
  185773. ** Tokenization callback used when inserting tokens into the FTS index.
  185774. */
  185775. static int fts5StorageInsertCallback(
  185776. void *pContext, /* Pointer to Fts5InsertCtx object */
  185777. int tflags,
  185778. const char *pToken, /* Buffer containing token */
  185779. int nToken, /* Size of token in bytes */
  185780. int iUnused1, /* Start offset of token */
  185781. int iUnused2 /* End offset of token */
  185782. ){
  185783. Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
  185784. Fts5Index *pIdx = pCtx->pStorage->pIndex;
  185785. UNUSED_PARAM2(iUnused1, iUnused2);
  185786. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  185787. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  185788. pCtx->szCol++;
  185789. }
  185790. return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
  185791. }
  185792. /*
  185793. ** If a row with rowid iDel is present in the %_content table, add the
  185794. ** delete-markers to the FTS index necessary to delete it. Do not actually
  185795. ** remove the %_content row at this time though.
  185796. */
  185797. static int fts5StorageDeleteFromIndex(
  185798. Fts5Storage *p,
  185799. i64 iDel,
  185800. sqlite3_value **apVal
  185801. ){
  185802. Fts5Config *pConfig = p->pConfig;
  185803. sqlite3_stmt *pSeek = 0; /* SELECT to read row iDel from %_data */
  185804. int rc; /* Return code */
  185805. int rc2; /* sqlite3_reset() return code */
  185806. int iCol;
  185807. Fts5InsertCtx ctx;
  185808. if( apVal==0 ){
  185809. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
  185810. if( rc!=SQLITE_OK ) return rc;
  185811. sqlite3_bind_int64(pSeek, 1, iDel);
  185812. if( sqlite3_step(pSeek)!=SQLITE_ROW ){
  185813. return sqlite3_reset(pSeek);
  185814. }
  185815. }
  185816. ctx.pStorage = p;
  185817. ctx.iCol = -1;
  185818. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
  185819. for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
  185820. if( pConfig->abUnindexed[iCol-1]==0 ){
  185821. const char *zText;
  185822. int nText;
  185823. if( pSeek ){
  185824. zText = (const char*)sqlite3_column_text(pSeek, iCol);
  185825. nText = sqlite3_column_bytes(pSeek, iCol);
  185826. }else{
  185827. zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
  185828. nText = sqlite3_value_bytes(apVal[iCol-1]);
  185829. }
  185830. ctx.szCol = 0;
  185831. rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
  185832. zText, nText, (void*)&ctx, fts5StorageInsertCallback
  185833. );
  185834. p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
  185835. }
  185836. }
  185837. p->nTotalRow--;
  185838. rc2 = sqlite3_reset(pSeek);
  185839. if( rc==SQLITE_OK ) rc = rc2;
  185840. return rc;
  185841. }
  185842. /*
  185843. ** Insert a record into the %_docsize table. Specifically, do:
  185844. **
  185845. ** INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
  185846. **
  185847. ** If there is no %_docsize table (as happens if the columnsize=0 option
  185848. ** is specified when the FTS5 table is created), this function is a no-op.
  185849. */
  185850. static int fts5StorageInsertDocsize(
  185851. Fts5Storage *p, /* Storage module to write to */
  185852. i64 iRowid, /* id value */
  185853. Fts5Buffer *pBuf /* sz value */
  185854. ){
  185855. int rc = SQLITE_OK;
  185856. if( p->pConfig->bColumnsize ){
  185857. sqlite3_stmt *pReplace = 0;
  185858. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  185859. if( rc==SQLITE_OK ){
  185860. sqlite3_bind_int64(pReplace, 1, iRowid);
  185861. sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
  185862. sqlite3_step(pReplace);
  185863. rc = sqlite3_reset(pReplace);
  185864. }
  185865. }
  185866. return rc;
  185867. }
  185868. /*
  185869. ** Load the contents of the "averages" record from disk into the
  185870. ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
  185871. ** argument bCache is true, set the p->bTotalsValid flag to indicate
  185872. ** that the contents of aTotalSize[] and nTotalRow are valid until
  185873. ** further notice.
  185874. **
  185875. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  185876. ** occurs.
  185877. */
  185878. static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
  185879. int rc = SQLITE_OK;
  185880. if( p->bTotalsValid==0 ){
  185881. rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
  185882. p->bTotalsValid = bCache;
  185883. }
  185884. return rc;
  185885. }
  185886. /*
  185887. ** Store the current contents of the p->nTotalRow and p->aTotalSize[]
  185888. ** variables in the "averages" record on disk.
  185889. **
  185890. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  185891. ** occurs.
  185892. */
  185893. static int fts5StorageSaveTotals(Fts5Storage *p){
  185894. int nCol = p->pConfig->nCol;
  185895. int i;
  185896. Fts5Buffer buf;
  185897. int rc = SQLITE_OK;
  185898. memset(&buf, 0, sizeof(buf));
  185899. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
  185900. for(i=0; i<nCol; i++){
  185901. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
  185902. }
  185903. if( rc==SQLITE_OK ){
  185904. rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
  185905. }
  185906. sqlite3_free(buf.p);
  185907. return rc;
  185908. }
  185909. /*
  185910. ** Remove a row from the FTS table.
  185911. */
  185912. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
  185913. Fts5Config *pConfig = p->pConfig;
  185914. int rc;
  185915. sqlite3_stmt *pDel = 0;
  185916. assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
  185917. rc = fts5StorageLoadTotals(p, 1);
  185918. /* Delete the index records */
  185919. if( rc==SQLITE_OK ){
  185920. rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
  185921. }
  185922. /* Delete the %_docsize record */
  185923. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  185924. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
  185925. if( rc==SQLITE_OK ){
  185926. sqlite3_bind_int64(pDel, 1, iDel);
  185927. sqlite3_step(pDel);
  185928. rc = sqlite3_reset(pDel);
  185929. }
  185930. }
  185931. /* Delete the %_content record */
  185932. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  185933. if( rc==SQLITE_OK ){
  185934. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
  185935. }
  185936. if( rc==SQLITE_OK ){
  185937. sqlite3_bind_int64(pDel, 1, iDel);
  185938. sqlite3_step(pDel);
  185939. rc = sqlite3_reset(pDel);
  185940. }
  185941. }
  185942. return rc;
  185943. }
  185944. /*
  185945. ** Delete all entries in the FTS5 index.
  185946. */
  185947. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
  185948. Fts5Config *pConfig = p->pConfig;
  185949. int rc;
  185950. /* Delete the contents of the %_data and %_docsize tables. */
  185951. rc = fts5ExecPrintf(pConfig->db, 0,
  185952. "DELETE FROM %Q.'%q_data';"
  185953. "DELETE FROM %Q.'%q_idx';",
  185954. pConfig->zDb, pConfig->zName,
  185955. pConfig->zDb, pConfig->zName
  185956. );
  185957. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  185958. rc = fts5ExecPrintf(pConfig->db, 0,
  185959. "DELETE FROM %Q.'%q_docsize';",
  185960. pConfig->zDb, pConfig->zName
  185961. );
  185962. }
  185963. /* Reinitialize the %_data table. This call creates the initial structure
  185964. ** and averages records. */
  185965. if( rc==SQLITE_OK ){
  185966. rc = sqlite3Fts5IndexReinit(p->pIndex);
  185967. }
  185968. if( rc==SQLITE_OK ){
  185969. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  185970. }
  185971. return rc;
  185972. }
  185973. static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
  185974. Fts5Buffer buf = {0,0,0};
  185975. Fts5Config *pConfig = p->pConfig;
  185976. sqlite3_stmt *pScan = 0;
  185977. Fts5InsertCtx ctx;
  185978. int rc;
  185979. memset(&ctx, 0, sizeof(Fts5InsertCtx));
  185980. ctx.pStorage = p;
  185981. rc = sqlite3Fts5StorageDeleteAll(p);
  185982. if( rc==SQLITE_OK ){
  185983. rc = fts5StorageLoadTotals(p, 1);
  185984. }
  185985. if( rc==SQLITE_OK ){
  185986. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  185987. }
  185988. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
  185989. i64 iRowid = sqlite3_column_int64(pScan, 0);
  185990. sqlite3Fts5BufferZero(&buf);
  185991. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  185992. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  185993. ctx.szCol = 0;
  185994. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  185995. rc = sqlite3Fts5Tokenize(pConfig,
  185996. FTS5_TOKENIZE_DOCUMENT,
  185997. (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
  185998. sqlite3_column_bytes(pScan, ctx.iCol+1),
  185999. (void*)&ctx,
  186000. fts5StorageInsertCallback
  186001. );
  186002. }
  186003. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  186004. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  186005. }
  186006. p->nTotalRow++;
  186007. if( rc==SQLITE_OK ){
  186008. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  186009. }
  186010. }
  186011. sqlite3_free(buf.p);
  186012. /* Write the averages record */
  186013. if( rc==SQLITE_OK ){
  186014. rc = fts5StorageSaveTotals(p);
  186015. }
  186016. return rc;
  186017. }
  186018. static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
  186019. return sqlite3Fts5IndexOptimize(p->pIndex);
  186020. }
  186021. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
  186022. return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
  186023. }
  186024. static int sqlite3Fts5StorageReset(Fts5Storage *p){
  186025. return sqlite3Fts5IndexReset(p->pIndex);
  186026. }
  186027. /*
  186028. ** Allocate a new rowid. This is used for "external content" tables when
  186029. ** a NULL value is inserted into the rowid column. The new rowid is allocated
  186030. ** by inserting a dummy row into the %_docsize table. The dummy will be
  186031. ** overwritten later.
  186032. **
  186033. ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
  186034. ** this case the user is required to provide a rowid explicitly.
  186035. */
  186036. static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
  186037. int rc = SQLITE_MISMATCH;
  186038. if( p->pConfig->bColumnsize ){
  186039. sqlite3_stmt *pReplace = 0;
  186040. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  186041. if( rc==SQLITE_OK ){
  186042. sqlite3_bind_null(pReplace, 1);
  186043. sqlite3_bind_null(pReplace, 2);
  186044. sqlite3_step(pReplace);
  186045. rc = sqlite3_reset(pReplace);
  186046. }
  186047. if( rc==SQLITE_OK ){
  186048. *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  186049. }
  186050. }
  186051. return rc;
  186052. }
  186053. /*
  186054. ** Insert a new row into the FTS content table.
  186055. */
  186056. static int sqlite3Fts5StorageContentInsert(
  186057. Fts5Storage *p,
  186058. sqlite3_value **apVal,
  186059. i64 *piRowid
  186060. ){
  186061. Fts5Config *pConfig = p->pConfig;
  186062. int rc = SQLITE_OK;
  186063. /* Insert the new row into the %_content table. */
  186064. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  186065. if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
  186066. *piRowid = sqlite3_value_int64(apVal[1]);
  186067. }else{
  186068. rc = fts5StorageNewRowid(p, piRowid);
  186069. }
  186070. }else{
  186071. sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */
  186072. int i; /* Counter variable */
  186073. rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
  186074. for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
  186075. rc = sqlite3_bind_value(pInsert, i, apVal[i]);
  186076. }
  186077. if( rc==SQLITE_OK ){
  186078. sqlite3_step(pInsert);
  186079. rc = sqlite3_reset(pInsert);
  186080. }
  186081. *piRowid = sqlite3_last_insert_rowid(pConfig->db);
  186082. }
  186083. return rc;
  186084. }
  186085. /*
  186086. ** Insert new entries into the FTS index and %_docsize table.
  186087. */
  186088. static int sqlite3Fts5StorageIndexInsert(
  186089. Fts5Storage *p,
  186090. sqlite3_value **apVal,
  186091. i64 iRowid
  186092. ){
  186093. Fts5Config *pConfig = p->pConfig;
  186094. int rc = SQLITE_OK; /* Return code */
  186095. Fts5InsertCtx ctx; /* Tokenization callback context object */
  186096. Fts5Buffer buf; /* Buffer used to build up %_docsize blob */
  186097. memset(&buf, 0, sizeof(Fts5Buffer));
  186098. ctx.pStorage = p;
  186099. rc = fts5StorageLoadTotals(p, 1);
  186100. if( rc==SQLITE_OK ){
  186101. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  186102. }
  186103. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  186104. ctx.szCol = 0;
  186105. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  186106. rc = sqlite3Fts5Tokenize(pConfig,
  186107. FTS5_TOKENIZE_DOCUMENT,
  186108. (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
  186109. sqlite3_value_bytes(apVal[ctx.iCol+2]),
  186110. (void*)&ctx,
  186111. fts5StorageInsertCallback
  186112. );
  186113. }
  186114. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  186115. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  186116. }
  186117. p->nTotalRow++;
  186118. /* Write the %_docsize record */
  186119. if( rc==SQLITE_OK ){
  186120. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  186121. }
  186122. sqlite3_free(buf.p);
  186123. return rc;
  186124. }
  186125. static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
  186126. Fts5Config *pConfig = p->pConfig;
  186127. char *zSql;
  186128. int rc;
  186129. zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
  186130. pConfig->zDb, pConfig->zName, zSuffix
  186131. );
  186132. if( zSql==0 ){
  186133. rc = SQLITE_NOMEM;
  186134. }else{
  186135. sqlite3_stmt *pCnt = 0;
  186136. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
  186137. if( rc==SQLITE_OK ){
  186138. if( SQLITE_ROW==sqlite3_step(pCnt) ){
  186139. *pnRow = sqlite3_column_int64(pCnt, 0);
  186140. }
  186141. rc = sqlite3_finalize(pCnt);
  186142. }
  186143. }
  186144. sqlite3_free(zSql);
  186145. return rc;
  186146. }
  186147. /*
  186148. ** Context object used by sqlite3Fts5StorageIntegrity().
  186149. */
  186150. typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
  186151. struct Fts5IntegrityCtx {
  186152. i64 iRowid;
  186153. int iCol;
  186154. int szCol;
  186155. u64 cksum;
  186156. Fts5Termset *pTermset;
  186157. Fts5Config *pConfig;
  186158. };
  186159. /*
  186160. ** Tokenization callback used by integrity check.
  186161. */
  186162. static int fts5StorageIntegrityCallback(
  186163. void *pContext, /* Pointer to Fts5IntegrityCtx object */
  186164. int tflags,
  186165. const char *pToken, /* Buffer containing token */
  186166. int nToken, /* Size of token in bytes */
  186167. int iUnused1, /* Start offset of token */
  186168. int iUnused2 /* End offset of token */
  186169. ){
  186170. Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
  186171. Fts5Termset *pTermset = pCtx->pTermset;
  186172. int bPresent;
  186173. int ii;
  186174. int rc = SQLITE_OK;
  186175. int iPos;
  186176. int iCol;
  186177. UNUSED_PARAM2(iUnused1, iUnused2);
  186178. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  186179. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  186180. pCtx->szCol++;
  186181. }
  186182. switch( pCtx->pConfig->eDetail ){
  186183. case FTS5_DETAIL_FULL:
  186184. iPos = pCtx->szCol-1;
  186185. iCol = pCtx->iCol;
  186186. break;
  186187. case FTS5_DETAIL_COLUMNS:
  186188. iPos = pCtx->iCol;
  186189. iCol = 0;
  186190. break;
  186191. default:
  186192. assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
  186193. iPos = 0;
  186194. iCol = 0;
  186195. break;
  186196. }
  186197. rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
  186198. if( rc==SQLITE_OK && bPresent==0 ){
  186199. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  186200. pCtx->iRowid, iCol, iPos, 0, pToken, nToken
  186201. );
  186202. }
  186203. for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
  186204. const int nChar = pCtx->pConfig->aPrefix[ii];
  186205. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  186206. if( nByte ){
  186207. rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
  186208. if( bPresent==0 ){
  186209. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  186210. pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
  186211. );
  186212. }
  186213. }
  186214. }
  186215. return rc;
  186216. }
  186217. /*
  186218. ** Check that the contents of the FTS index match that of the %_content
  186219. ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
  186220. ** some other SQLite error code if an error occurs while attempting to
  186221. ** determine this.
  186222. */
  186223. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
  186224. Fts5Config *pConfig = p->pConfig;
  186225. int rc; /* Return code */
  186226. int *aColSize; /* Array of size pConfig->nCol */
  186227. i64 *aTotalSize; /* Array of size pConfig->nCol */
  186228. Fts5IntegrityCtx ctx;
  186229. sqlite3_stmt *pScan;
  186230. memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
  186231. ctx.pConfig = p->pConfig;
  186232. aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
  186233. if( !aTotalSize ) return SQLITE_NOMEM;
  186234. aColSize = (int*)&aTotalSize[pConfig->nCol];
  186235. memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
  186236. /* Generate the expected index checksum based on the contents of the
  186237. ** %_content table. This block stores the checksum in ctx.cksum. */
  186238. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  186239. if( rc==SQLITE_OK ){
  186240. int rc2;
  186241. while( SQLITE_ROW==sqlite3_step(pScan) ){
  186242. int i;
  186243. ctx.iRowid = sqlite3_column_int64(pScan, 0);
  186244. ctx.szCol = 0;
  186245. if( pConfig->bColumnsize ){
  186246. rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
  186247. }
  186248. if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
  186249. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  186250. }
  186251. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  186252. if( pConfig->abUnindexed[i] ) continue;
  186253. ctx.iCol = i;
  186254. ctx.szCol = 0;
  186255. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  186256. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  186257. }
  186258. if( rc==SQLITE_OK ){
  186259. rc = sqlite3Fts5Tokenize(pConfig,
  186260. FTS5_TOKENIZE_DOCUMENT,
  186261. (const char*)sqlite3_column_text(pScan, i+1),
  186262. sqlite3_column_bytes(pScan, i+1),
  186263. (void*)&ctx,
  186264. fts5StorageIntegrityCallback
  186265. );
  186266. }
  186267. if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
  186268. rc = FTS5_CORRUPT;
  186269. }
  186270. aTotalSize[i] += ctx.szCol;
  186271. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  186272. sqlite3Fts5TermsetFree(ctx.pTermset);
  186273. ctx.pTermset = 0;
  186274. }
  186275. }
  186276. sqlite3Fts5TermsetFree(ctx.pTermset);
  186277. ctx.pTermset = 0;
  186278. if( rc!=SQLITE_OK ) break;
  186279. }
  186280. rc2 = sqlite3_reset(pScan);
  186281. if( rc==SQLITE_OK ) rc = rc2;
  186282. }
  186283. /* Test that the "totals" (sometimes called "averages") record looks Ok */
  186284. if( rc==SQLITE_OK ){
  186285. int i;
  186286. rc = fts5StorageLoadTotals(p, 0);
  186287. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  186288. if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
  186289. }
  186290. }
  186291. /* Check that the %_docsize and %_content tables contain the expected
  186292. ** number of rows. */
  186293. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  186294. i64 nRow = 0;
  186295. rc = fts5StorageCount(p, "content", &nRow);
  186296. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  186297. }
  186298. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  186299. i64 nRow = 0;
  186300. rc = fts5StorageCount(p, "docsize", &nRow);
  186301. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  186302. }
  186303. /* Pass the expected checksum down to the FTS index module. It will
  186304. ** verify, amongst other things, that it matches the checksum generated by
  186305. ** inspecting the index itself. */
  186306. if( rc==SQLITE_OK ){
  186307. rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
  186308. }
  186309. sqlite3_free(aTotalSize);
  186310. return rc;
  186311. }
  186312. /*
  186313. ** Obtain an SQLite statement handle that may be used to read data from the
  186314. ** %_content table.
  186315. */
  186316. static int sqlite3Fts5StorageStmt(
  186317. Fts5Storage *p,
  186318. int eStmt,
  186319. sqlite3_stmt **pp,
  186320. char **pzErrMsg
  186321. ){
  186322. int rc;
  186323. assert( eStmt==FTS5_STMT_SCAN_ASC
  186324. || eStmt==FTS5_STMT_SCAN_DESC
  186325. || eStmt==FTS5_STMT_LOOKUP
  186326. );
  186327. rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
  186328. if( rc==SQLITE_OK ){
  186329. assert( p->aStmt[eStmt]==*pp );
  186330. p->aStmt[eStmt] = 0;
  186331. }
  186332. return rc;
  186333. }
  186334. /*
  186335. ** Release an SQLite statement handle obtained via an earlier call to
  186336. ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
  186337. ** must match that passed to the sqlite3Fts5StorageStmt() call.
  186338. */
  186339. static void sqlite3Fts5StorageStmtRelease(
  186340. Fts5Storage *p,
  186341. int eStmt,
  186342. sqlite3_stmt *pStmt
  186343. ){
  186344. assert( eStmt==FTS5_STMT_SCAN_ASC
  186345. || eStmt==FTS5_STMT_SCAN_DESC
  186346. || eStmt==FTS5_STMT_LOOKUP
  186347. );
  186348. if( p->aStmt[eStmt]==0 ){
  186349. sqlite3_reset(pStmt);
  186350. p->aStmt[eStmt] = pStmt;
  186351. }else{
  186352. sqlite3_finalize(pStmt);
  186353. }
  186354. }
  186355. static int fts5StorageDecodeSizeArray(
  186356. int *aCol, int nCol, /* Array to populate */
  186357. const u8 *aBlob, int nBlob /* Record to read varints from */
  186358. ){
  186359. int i;
  186360. int iOff = 0;
  186361. for(i=0; i<nCol; i++){
  186362. if( iOff>=nBlob ) return 1;
  186363. iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
  186364. }
  186365. return (iOff!=nBlob);
  186366. }
  186367. /*
  186368. ** Argument aCol points to an array of integers containing one entry for
  186369. ** each table column. This function reads the %_docsize record for the
  186370. ** specified rowid and populates aCol[] with the results.
  186371. **
  186372. ** An SQLite error code is returned if an error occurs, or SQLITE_OK
  186373. ** otherwise.
  186374. */
  186375. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
  186376. int nCol = p->pConfig->nCol; /* Number of user columns in table */
  186377. sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */
  186378. int rc; /* Return Code */
  186379. assert( p->pConfig->bColumnsize );
  186380. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
  186381. if( rc==SQLITE_OK ){
  186382. int bCorrupt = 1;
  186383. sqlite3_bind_int64(pLookup, 1, iRowid);
  186384. if( SQLITE_ROW==sqlite3_step(pLookup) ){
  186385. const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
  186386. int nBlob = sqlite3_column_bytes(pLookup, 0);
  186387. if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
  186388. bCorrupt = 0;
  186389. }
  186390. }
  186391. rc = sqlite3_reset(pLookup);
  186392. if( bCorrupt && rc==SQLITE_OK ){
  186393. rc = FTS5_CORRUPT;
  186394. }
  186395. }
  186396. return rc;
  186397. }
  186398. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
  186399. int rc = fts5StorageLoadTotals(p, 0);
  186400. if( rc==SQLITE_OK ){
  186401. *pnToken = 0;
  186402. if( iCol<0 ){
  186403. int i;
  186404. for(i=0; i<p->pConfig->nCol; i++){
  186405. *pnToken += p->aTotalSize[i];
  186406. }
  186407. }else if( iCol<p->pConfig->nCol ){
  186408. *pnToken = p->aTotalSize[iCol];
  186409. }else{
  186410. rc = SQLITE_RANGE;
  186411. }
  186412. }
  186413. return rc;
  186414. }
  186415. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
  186416. int rc = fts5StorageLoadTotals(p, 0);
  186417. if( rc==SQLITE_OK ){
  186418. *pnRow = p->nTotalRow;
  186419. }
  186420. return rc;
  186421. }
  186422. /*
  186423. ** Flush any data currently held in-memory to disk.
  186424. */
  186425. static int sqlite3Fts5StorageSync(Fts5Storage *p){
  186426. int rc = SQLITE_OK;
  186427. i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  186428. if( p->bTotalsValid ){
  186429. rc = fts5StorageSaveTotals(p);
  186430. p->bTotalsValid = 0;
  186431. }
  186432. if( rc==SQLITE_OK ){
  186433. rc = sqlite3Fts5IndexSync(p->pIndex);
  186434. }
  186435. sqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid);
  186436. return rc;
  186437. }
  186438. static int sqlite3Fts5StorageRollback(Fts5Storage *p){
  186439. p->bTotalsValid = 0;
  186440. return sqlite3Fts5IndexRollback(p->pIndex);
  186441. }
  186442. static int sqlite3Fts5StorageConfigValue(
  186443. Fts5Storage *p,
  186444. const char *z,
  186445. sqlite3_value *pVal,
  186446. int iVal
  186447. ){
  186448. sqlite3_stmt *pReplace = 0;
  186449. int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
  186450. if( rc==SQLITE_OK ){
  186451. sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
  186452. if( pVal ){
  186453. sqlite3_bind_value(pReplace, 2, pVal);
  186454. }else{
  186455. sqlite3_bind_int(pReplace, 2, iVal);
  186456. }
  186457. sqlite3_step(pReplace);
  186458. rc = sqlite3_reset(pReplace);
  186459. }
  186460. if( rc==SQLITE_OK && pVal ){
  186461. int iNew = p->pConfig->iCookie + 1;
  186462. rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
  186463. if( rc==SQLITE_OK ){
  186464. p->pConfig->iCookie = iNew;
  186465. }
  186466. }
  186467. return rc;
  186468. }
  186469. /*
  186470. ** 2014 May 31
  186471. **
  186472. ** The author disclaims copyright to this source code. In place of
  186473. ** a legal notice, here is a blessing:
  186474. **
  186475. ** May you do good and not evil.
  186476. ** May you find forgiveness for yourself and forgive others.
  186477. ** May you share freely, never taking more than you give.
  186478. **
  186479. ******************************************************************************
  186480. */
  186481. /* #include "fts5Int.h" */
  186482. /**************************************************************************
  186483. ** Start of ascii tokenizer implementation.
  186484. */
  186485. /*
  186486. ** For tokenizers with no "unicode" modifier, the set of token characters
  186487. ** is the same as the set of ASCII range alphanumeric characters.
  186488. */
  186489. static unsigned char aAsciiTokenChar[128] = {
  186490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00..0x0F */
  186491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10..0x1F */
  186492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20..0x2F */
  186493. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30..0x3F */
  186494. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40..0x4F */
  186495. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x50..0x5F */
  186496. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60..0x6F */
  186497. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x70..0x7F */
  186498. };
  186499. typedef struct AsciiTokenizer AsciiTokenizer;
  186500. struct AsciiTokenizer {
  186501. unsigned char aTokenChar[128];
  186502. };
  186503. static void fts5AsciiAddExceptions(
  186504. AsciiTokenizer *p,
  186505. const char *zArg,
  186506. int bTokenChars
  186507. ){
  186508. int i;
  186509. for(i=0; zArg[i]; i++){
  186510. if( (zArg[i] & 0x80)==0 ){
  186511. p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
  186512. }
  186513. }
  186514. }
  186515. /*
  186516. ** Delete a "ascii" tokenizer.
  186517. */
  186518. static void fts5AsciiDelete(Fts5Tokenizer *p){
  186519. sqlite3_free(p);
  186520. }
  186521. /*
  186522. ** Create an "ascii" tokenizer.
  186523. */
  186524. static int fts5AsciiCreate(
  186525. void *pUnused,
  186526. const char **azArg, int nArg,
  186527. Fts5Tokenizer **ppOut
  186528. ){
  186529. int rc = SQLITE_OK;
  186530. AsciiTokenizer *p = 0;
  186531. UNUSED_PARAM(pUnused);
  186532. if( nArg%2 ){
  186533. rc = SQLITE_ERROR;
  186534. }else{
  186535. p = sqlite3_malloc(sizeof(AsciiTokenizer));
  186536. if( p==0 ){
  186537. rc = SQLITE_NOMEM;
  186538. }else{
  186539. int i;
  186540. memset(p, 0, sizeof(AsciiTokenizer));
  186541. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  186542. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  186543. const char *zArg = azArg[i+1];
  186544. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  186545. fts5AsciiAddExceptions(p, zArg, 1);
  186546. }else
  186547. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  186548. fts5AsciiAddExceptions(p, zArg, 0);
  186549. }else{
  186550. rc = SQLITE_ERROR;
  186551. }
  186552. }
  186553. if( rc!=SQLITE_OK ){
  186554. fts5AsciiDelete((Fts5Tokenizer*)p);
  186555. p = 0;
  186556. }
  186557. }
  186558. }
  186559. *ppOut = (Fts5Tokenizer*)p;
  186560. return rc;
  186561. }
  186562. static void asciiFold(char *aOut, const char *aIn, int nByte){
  186563. int i;
  186564. for(i=0; i<nByte; i++){
  186565. char c = aIn[i];
  186566. if( c>='A' && c<='Z' ) c += 32;
  186567. aOut[i] = c;
  186568. }
  186569. }
  186570. /*
  186571. ** Tokenize some text using the ascii tokenizer.
  186572. */
  186573. static int fts5AsciiTokenize(
  186574. Fts5Tokenizer *pTokenizer,
  186575. void *pCtx,
  186576. int iUnused,
  186577. const char *pText, int nText,
  186578. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  186579. ){
  186580. AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
  186581. int rc = SQLITE_OK;
  186582. int ie;
  186583. int is = 0;
  186584. char aFold[64];
  186585. int nFold = sizeof(aFold);
  186586. char *pFold = aFold;
  186587. unsigned char *a = p->aTokenChar;
  186588. UNUSED_PARAM(iUnused);
  186589. while( is<nText && rc==SQLITE_OK ){
  186590. int nByte;
  186591. /* Skip any leading divider characters. */
  186592. while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
  186593. is++;
  186594. }
  186595. if( is==nText ) break;
  186596. /* Count the token characters */
  186597. ie = is+1;
  186598. while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
  186599. ie++;
  186600. }
  186601. /* Fold to lower case */
  186602. nByte = ie-is;
  186603. if( nByte>nFold ){
  186604. if( pFold!=aFold ) sqlite3_free(pFold);
  186605. pFold = sqlite3_malloc(nByte*2);
  186606. if( pFold==0 ){
  186607. rc = SQLITE_NOMEM;
  186608. break;
  186609. }
  186610. nFold = nByte*2;
  186611. }
  186612. asciiFold(pFold, &pText[is], nByte);
  186613. /* Invoke the token callback */
  186614. rc = xToken(pCtx, 0, pFold, nByte, is, ie);
  186615. is = ie+1;
  186616. }
  186617. if( pFold!=aFold ) sqlite3_free(pFold);
  186618. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  186619. return rc;
  186620. }
  186621. /**************************************************************************
  186622. ** Start of unicode61 tokenizer implementation.
  186623. */
  186624. /*
  186625. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  186626. ** from the sqlite3 source file utf.c. If this file is compiled as part
  186627. ** of the amalgamation, they are not required.
  186628. */
  186629. #ifndef SQLITE_AMALGAMATION
  186630. static const unsigned char sqlite3Utf8Trans1[] = {
  186631. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  186632. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  186633. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  186634. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  186635. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  186636. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  186637. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  186638. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  186639. };
  186640. #define READ_UTF8(zIn, zTerm, c) \
  186641. c = *(zIn++); \
  186642. if( c>=0xc0 ){ \
  186643. c = sqlite3Utf8Trans1[c-0xc0]; \
  186644. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  186645. c = (c<<6) + (0x3f & *(zIn++)); \
  186646. } \
  186647. if( c<0x80 \
  186648. || (c&0xFFFFF800)==0xD800 \
  186649. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  186650. }
  186651. #define WRITE_UTF8(zOut, c) { \
  186652. if( c<0x00080 ){ \
  186653. *zOut++ = (unsigned char)(c&0xFF); \
  186654. } \
  186655. else if( c<0x00800 ){ \
  186656. *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \
  186657. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  186658. } \
  186659. else if( c<0x10000 ){ \
  186660. *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \
  186661. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  186662. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  186663. }else{ \
  186664. *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \
  186665. *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \
  186666. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  186667. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  186668. } \
  186669. }
  186670. #endif /* ifndef SQLITE_AMALGAMATION */
  186671. typedef struct Unicode61Tokenizer Unicode61Tokenizer;
  186672. struct Unicode61Tokenizer {
  186673. unsigned char aTokenChar[128]; /* ASCII range token characters */
  186674. char *aFold; /* Buffer to fold text into */
  186675. int nFold; /* Size of aFold[] in bytes */
  186676. int bRemoveDiacritic; /* True if remove_diacritics=1 is set */
  186677. int nException;
  186678. int *aiException;
  186679. };
  186680. static int fts5UnicodeAddExceptions(
  186681. Unicode61Tokenizer *p, /* Tokenizer object */
  186682. const char *z, /* Characters to treat as exceptions */
  186683. int bTokenChars /* 1 for 'tokenchars', 0 for 'separators' */
  186684. ){
  186685. int rc = SQLITE_OK;
  186686. int n = (int)strlen(z);
  186687. int *aNew;
  186688. if( n>0 ){
  186689. aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
  186690. if( aNew ){
  186691. int nNew = p->nException;
  186692. const unsigned char *zCsr = (const unsigned char*)z;
  186693. const unsigned char *zTerm = (const unsigned char*)&z[n];
  186694. while( zCsr<zTerm ){
  186695. int iCode;
  186696. int bToken;
  186697. READ_UTF8(zCsr, zTerm, iCode);
  186698. if( iCode<128 ){
  186699. p->aTokenChar[iCode] = (unsigned char)bTokenChars;
  186700. }else{
  186701. bToken = sqlite3Fts5UnicodeIsalnum(iCode);
  186702. assert( (bToken==0 || bToken==1) );
  186703. assert( (bTokenChars==0 || bTokenChars==1) );
  186704. if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
  186705. int i;
  186706. for(i=0; i<nNew; i++){
  186707. if( aNew[i]>iCode ) break;
  186708. }
  186709. memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
  186710. aNew[i] = iCode;
  186711. nNew++;
  186712. }
  186713. }
  186714. }
  186715. p->aiException = aNew;
  186716. p->nException = nNew;
  186717. }else{
  186718. rc = SQLITE_NOMEM;
  186719. }
  186720. }
  186721. return rc;
  186722. }
  186723. /*
  186724. ** Return true if the p->aiException[] array contains the value iCode.
  186725. */
  186726. static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
  186727. if( p->nException>0 ){
  186728. int *a = p->aiException;
  186729. int iLo = 0;
  186730. int iHi = p->nException-1;
  186731. while( iHi>=iLo ){
  186732. int iTest = (iHi + iLo) / 2;
  186733. if( iCode==a[iTest] ){
  186734. return 1;
  186735. }else if( iCode>a[iTest] ){
  186736. iLo = iTest+1;
  186737. }else{
  186738. iHi = iTest-1;
  186739. }
  186740. }
  186741. }
  186742. return 0;
  186743. }
  186744. /*
  186745. ** Delete a "unicode61" tokenizer.
  186746. */
  186747. static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
  186748. if( pTok ){
  186749. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
  186750. sqlite3_free(p->aiException);
  186751. sqlite3_free(p->aFold);
  186752. sqlite3_free(p);
  186753. }
  186754. return;
  186755. }
  186756. /*
  186757. ** Create a "unicode61" tokenizer.
  186758. */
  186759. static int fts5UnicodeCreate(
  186760. void *pUnused,
  186761. const char **azArg, int nArg,
  186762. Fts5Tokenizer **ppOut
  186763. ){
  186764. int rc = SQLITE_OK; /* Return code */
  186765. Unicode61Tokenizer *p = 0; /* New tokenizer object */
  186766. UNUSED_PARAM(pUnused);
  186767. if( nArg%2 ){
  186768. rc = SQLITE_ERROR;
  186769. }else{
  186770. p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
  186771. if( p ){
  186772. int i;
  186773. memset(p, 0, sizeof(Unicode61Tokenizer));
  186774. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  186775. p->bRemoveDiacritic = 1;
  186776. p->nFold = 64;
  186777. p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
  186778. if( p->aFold==0 ){
  186779. rc = SQLITE_NOMEM;
  186780. }
  186781. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  186782. const char *zArg = azArg[i+1];
  186783. if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
  186784. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
  186785. rc = SQLITE_ERROR;
  186786. }
  186787. p->bRemoveDiacritic = (zArg[0]=='1');
  186788. }else
  186789. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  186790. rc = fts5UnicodeAddExceptions(p, zArg, 1);
  186791. }else
  186792. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  186793. rc = fts5UnicodeAddExceptions(p, zArg, 0);
  186794. }else{
  186795. rc = SQLITE_ERROR;
  186796. }
  186797. }
  186798. }else{
  186799. rc = SQLITE_NOMEM;
  186800. }
  186801. if( rc!=SQLITE_OK ){
  186802. fts5UnicodeDelete((Fts5Tokenizer*)p);
  186803. p = 0;
  186804. }
  186805. *ppOut = (Fts5Tokenizer*)p;
  186806. }
  186807. return rc;
  186808. }
  186809. /*
  186810. ** Return true if, for the purposes of tokenizing with the tokenizer
  186811. ** passed as the first argument, codepoint iCode is considered a token
  186812. ** character (not a separator).
  186813. */
  186814. static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
  186815. assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  186816. return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
  186817. }
  186818. static int fts5UnicodeTokenize(
  186819. Fts5Tokenizer *pTokenizer,
  186820. void *pCtx,
  186821. int iUnused,
  186822. const char *pText, int nText,
  186823. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  186824. ){
  186825. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
  186826. int rc = SQLITE_OK;
  186827. unsigned char *a = p->aTokenChar;
  186828. unsigned char *zTerm = (unsigned char*)&pText[nText];
  186829. unsigned char *zCsr = (unsigned char *)pText;
  186830. /* Output buffer */
  186831. char *aFold = p->aFold;
  186832. int nFold = p->nFold;
  186833. const char *pEnd = &aFold[nFold-6];
  186834. UNUSED_PARAM(iUnused);
  186835. /* Each iteration of this loop gobbles up a contiguous run of separators,
  186836. ** then the next token. */
  186837. while( rc==SQLITE_OK ){
  186838. int iCode; /* non-ASCII codepoint read from input */
  186839. char *zOut = aFold;
  186840. int is;
  186841. int ie;
  186842. /* Skip any separator characters. */
  186843. while( 1 ){
  186844. if( zCsr>=zTerm ) goto tokenize_done;
  186845. if( *zCsr & 0x80 ) {
  186846. /* A character outside of the ascii range. Skip past it if it is
  186847. ** a separator character. Or break out of the loop if it is not. */
  186848. is = zCsr - (unsigned char*)pText;
  186849. READ_UTF8(zCsr, zTerm, iCode);
  186850. if( fts5UnicodeIsAlnum(p, iCode) ){
  186851. goto non_ascii_tokenchar;
  186852. }
  186853. }else{
  186854. if( a[*zCsr] ){
  186855. is = zCsr - (unsigned char*)pText;
  186856. goto ascii_tokenchar;
  186857. }
  186858. zCsr++;
  186859. }
  186860. }
  186861. /* Run through the tokenchars. Fold them into the output buffer along
  186862. ** the way. */
  186863. while( zCsr<zTerm ){
  186864. /* Grow the output buffer so that there is sufficient space to fit the
  186865. ** largest possible utf-8 character. */
  186866. if( zOut>pEnd ){
  186867. aFold = sqlite3_malloc(nFold*2);
  186868. if( aFold==0 ){
  186869. rc = SQLITE_NOMEM;
  186870. goto tokenize_done;
  186871. }
  186872. zOut = &aFold[zOut - p->aFold];
  186873. memcpy(aFold, p->aFold, nFold);
  186874. sqlite3_free(p->aFold);
  186875. p->aFold = aFold;
  186876. p->nFold = nFold = nFold*2;
  186877. pEnd = &aFold[nFold-6];
  186878. }
  186879. if( *zCsr & 0x80 ){
  186880. /* An non-ascii-range character. Fold it into the output buffer if
  186881. ** it is a token character, or break out of the loop if it is not. */
  186882. READ_UTF8(zCsr, zTerm, iCode);
  186883. if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
  186884. non_ascii_tokenchar:
  186885. iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
  186886. if( iCode ) WRITE_UTF8(zOut, iCode);
  186887. }else{
  186888. break;
  186889. }
  186890. }else if( a[*zCsr]==0 ){
  186891. /* An ascii-range separator character. End of token. */
  186892. break;
  186893. }else{
  186894. ascii_tokenchar:
  186895. if( *zCsr>='A' && *zCsr<='Z' ){
  186896. *zOut++ = *zCsr + 32;
  186897. }else{
  186898. *zOut++ = *zCsr;
  186899. }
  186900. zCsr++;
  186901. }
  186902. ie = zCsr - (unsigned char*)pText;
  186903. }
  186904. /* Invoke the token callback */
  186905. rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
  186906. }
  186907. tokenize_done:
  186908. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  186909. return rc;
  186910. }
  186911. /**************************************************************************
  186912. ** Start of porter stemmer implementation.
  186913. */
  186914. /* Any tokens larger than this (in bytes) are passed through without
  186915. ** stemming. */
  186916. #define FTS5_PORTER_MAX_TOKEN 64
  186917. typedef struct PorterTokenizer PorterTokenizer;
  186918. struct PorterTokenizer {
  186919. fts5_tokenizer tokenizer; /* Parent tokenizer module */
  186920. Fts5Tokenizer *pTokenizer; /* Parent tokenizer instance */
  186921. char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
  186922. };
  186923. /*
  186924. ** Delete a "porter" tokenizer.
  186925. */
  186926. static void fts5PorterDelete(Fts5Tokenizer *pTok){
  186927. if( pTok ){
  186928. PorterTokenizer *p = (PorterTokenizer*)pTok;
  186929. if( p->pTokenizer ){
  186930. p->tokenizer.xDelete(p->pTokenizer);
  186931. }
  186932. sqlite3_free(p);
  186933. }
  186934. }
  186935. /*
  186936. ** Create a "porter" tokenizer.
  186937. */
  186938. static int fts5PorterCreate(
  186939. void *pCtx,
  186940. const char **azArg, int nArg,
  186941. Fts5Tokenizer **ppOut
  186942. ){
  186943. fts5_api *pApi = (fts5_api*)pCtx;
  186944. int rc = SQLITE_OK;
  186945. PorterTokenizer *pRet;
  186946. void *pUserdata = 0;
  186947. const char *zBase = "unicode61";
  186948. if( nArg>0 ){
  186949. zBase = azArg[0];
  186950. }
  186951. pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
  186952. if( pRet ){
  186953. memset(pRet, 0, sizeof(PorterTokenizer));
  186954. rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
  186955. }else{
  186956. rc = SQLITE_NOMEM;
  186957. }
  186958. if( rc==SQLITE_OK ){
  186959. int nArg2 = (nArg>0 ? nArg-1 : 0);
  186960. const char **azArg2 = (nArg2 ? &azArg[1] : 0);
  186961. rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
  186962. }
  186963. if( rc!=SQLITE_OK ){
  186964. fts5PorterDelete((Fts5Tokenizer*)pRet);
  186965. pRet = 0;
  186966. }
  186967. *ppOut = (Fts5Tokenizer*)pRet;
  186968. return rc;
  186969. }
  186970. typedef struct PorterContext PorterContext;
  186971. struct PorterContext {
  186972. void *pCtx;
  186973. int (*xToken)(void*, int, const char*, int, int, int);
  186974. char *aBuf;
  186975. };
  186976. typedef struct PorterRule PorterRule;
  186977. struct PorterRule {
  186978. const char *zSuffix;
  186979. int nSuffix;
  186980. int (*xCond)(char *zStem, int nStem);
  186981. const char *zOutput;
  186982. int nOutput;
  186983. };
  186984. #if 0
  186985. static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
  186986. int ret = -1;
  186987. int nBuf = *pnBuf;
  186988. PorterRule *p;
  186989. for(p=aRule; p->zSuffix; p++){
  186990. assert( strlen(p->zSuffix)==p->nSuffix );
  186991. assert( strlen(p->zOutput)==p->nOutput );
  186992. if( nBuf<p->nSuffix ) continue;
  186993. if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
  186994. }
  186995. if( p->zSuffix ){
  186996. int nStem = nBuf - p->nSuffix;
  186997. if( p->xCond==0 || p->xCond(aBuf, nStem) ){
  186998. memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
  186999. *pnBuf = nStem + p->nOutput;
  187000. ret = p - aRule;
  187001. }
  187002. }
  187003. return ret;
  187004. }
  187005. #endif
  187006. static int fts5PorterIsVowel(char c, int bYIsVowel){
  187007. return (
  187008. c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
  187009. );
  187010. }
  187011. static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
  187012. int i;
  187013. int bCons = bPrevCons;
  187014. /* Scan for a vowel */
  187015. for(i=0; i<nStem; i++){
  187016. if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
  187017. }
  187018. /* Scan for a consonent */
  187019. for(i++; i<nStem; i++){
  187020. if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
  187021. }
  187022. return 0;
  187023. }
  187024. /* porter rule condition: (m > 0) */
  187025. static int fts5Porter_MGt0(char *zStem, int nStem){
  187026. return !!fts5PorterGobbleVC(zStem, nStem, 0);
  187027. }
  187028. /* porter rule condition: (m > 1) */
  187029. static int fts5Porter_MGt1(char *zStem, int nStem){
  187030. int n;
  187031. n = fts5PorterGobbleVC(zStem, nStem, 0);
  187032. if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  187033. return 1;
  187034. }
  187035. return 0;
  187036. }
  187037. /* porter rule condition: (m = 1) */
  187038. static int fts5Porter_MEq1(char *zStem, int nStem){
  187039. int n;
  187040. n = fts5PorterGobbleVC(zStem, nStem, 0);
  187041. if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  187042. return 1;
  187043. }
  187044. return 0;
  187045. }
  187046. /* porter rule condition: (*o) */
  187047. static int fts5Porter_Ostar(char *zStem, int nStem){
  187048. if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
  187049. return 0;
  187050. }else{
  187051. int i;
  187052. int mask = 0;
  187053. int bCons = 0;
  187054. for(i=0; i<nStem; i++){
  187055. bCons = !fts5PorterIsVowel(zStem[i], bCons);
  187056. assert( bCons==0 || bCons==1 );
  187057. mask = (mask << 1) + bCons;
  187058. }
  187059. return ((mask & 0x0007)==0x0005);
  187060. }
  187061. }
  187062. /* porter rule condition: (m > 1 and (*S or *T)) */
  187063. static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
  187064. assert( nStem>0 );
  187065. return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
  187066. && fts5Porter_MGt1(zStem, nStem);
  187067. }
  187068. /* porter rule condition: (*v*) */
  187069. static int fts5Porter_Vowel(char *zStem, int nStem){
  187070. int i;
  187071. for(i=0; i<nStem; i++){
  187072. if( fts5PorterIsVowel(zStem[i], i>0) ){
  187073. return 1;
  187074. }
  187075. }
  187076. return 0;
  187077. }
  187078. /**************************************************************************
  187079. ***************************************************************************
  187080. ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
  187081. */
  187082. static int fts5PorterStep4(char *aBuf, int *pnBuf){
  187083. int ret = 0;
  187084. int nBuf = *pnBuf;
  187085. switch( aBuf[nBuf-2] ){
  187086. case 'a':
  187087. if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
  187088. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  187089. *pnBuf = nBuf - 2;
  187090. }
  187091. }
  187092. break;
  187093. case 'c':
  187094. if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
  187095. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  187096. *pnBuf = nBuf - 4;
  187097. }
  187098. }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
  187099. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  187100. *pnBuf = nBuf - 4;
  187101. }
  187102. }
  187103. break;
  187104. case 'e':
  187105. if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
  187106. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  187107. *pnBuf = nBuf - 2;
  187108. }
  187109. }
  187110. break;
  187111. case 'i':
  187112. if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
  187113. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  187114. *pnBuf = nBuf - 2;
  187115. }
  187116. }
  187117. break;
  187118. case 'l':
  187119. if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
  187120. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  187121. *pnBuf = nBuf - 4;
  187122. }
  187123. }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
  187124. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  187125. *pnBuf = nBuf - 4;
  187126. }
  187127. }
  187128. break;
  187129. case 'n':
  187130. if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
  187131. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  187132. *pnBuf = nBuf - 3;
  187133. }
  187134. }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
  187135. if( fts5Porter_MGt1(aBuf, nBuf-5) ){
  187136. *pnBuf = nBuf - 5;
  187137. }
  187138. }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
  187139. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  187140. *pnBuf = nBuf - 4;
  187141. }
  187142. }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
  187143. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  187144. *pnBuf = nBuf - 3;
  187145. }
  187146. }
  187147. break;
  187148. case 'o':
  187149. if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
  187150. if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
  187151. *pnBuf = nBuf - 3;
  187152. }
  187153. }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
  187154. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  187155. *pnBuf = nBuf - 2;
  187156. }
  187157. }
  187158. break;
  187159. case 's':
  187160. if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
  187161. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  187162. *pnBuf = nBuf - 3;
  187163. }
  187164. }
  187165. break;
  187166. case 't':
  187167. if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
  187168. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  187169. *pnBuf = nBuf - 3;
  187170. }
  187171. }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
  187172. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  187173. *pnBuf = nBuf - 3;
  187174. }
  187175. }
  187176. break;
  187177. case 'u':
  187178. if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
  187179. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  187180. *pnBuf = nBuf - 3;
  187181. }
  187182. }
  187183. break;
  187184. case 'v':
  187185. if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
  187186. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  187187. *pnBuf = nBuf - 3;
  187188. }
  187189. }
  187190. break;
  187191. case 'z':
  187192. if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
  187193. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  187194. *pnBuf = nBuf - 3;
  187195. }
  187196. }
  187197. break;
  187198. }
  187199. return ret;
  187200. }
  187201. static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
  187202. int ret = 0;
  187203. int nBuf = *pnBuf;
  187204. switch( aBuf[nBuf-2] ){
  187205. case 'a':
  187206. if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
  187207. memcpy(&aBuf[nBuf-2], "ate", 3);
  187208. *pnBuf = nBuf - 2 + 3;
  187209. ret = 1;
  187210. }
  187211. break;
  187212. case 'b':
  187213. if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
  187214. memcpy(&aBuf[nBuf-2], "ble", 3);
  187215. *pnBuf = nBuf - 2 + 3;
  187216. ret = 1;
  187217. }
  187218. break;
  187219. case 'i':
  187220. if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
  187221. memcpy(&aBuf[nBuf-2], "ize", 3);
  187222. *pnBuf = nBuf - 2 + 3;
  187223. ret = 1;
  187224. }
  187225. break;
  187226. }
  187227. return ret;
  187228. }
  187229. static int fts5PorterStep2(char *aBuf, int *pnBuf){
  187230. int ret = 0;
  187231. int nBuf = *pnBuf;
  187232. switch( aBuf[nBuf-2] ){
  187233. case 'a':
  187234. if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
  187235. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  187236. memcpy(&aBuf[nBuf-7], "ate", 3);
  187237. *pnBuf = nBuf - 7 + 3;
  187238. }
  187239. }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
  187240. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  187241. memcpy(&aBuf[nBuf-6], "tion", 4);
  187242. *pnBuf = nBuf - 6 + 4;
  187243. }
  187244. }
  187245. break;
  187246. case 'c':
  187247. if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
  187248. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  187249. memcpy(&aBuf[nBuf-4], "ence", 4);
  187250. *pnBuf = nBuf - 4 + 4;
  187251. }
  187252. }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
  187253. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  187254. memcpy(&aBuf[nBuf-4], "ance", 4);
  187255. *pnBuf = nBuf - 4 + 4;
  187256. }
  187257. }
  187258. break;
  187259. case 'e':
  187260. if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
  187261. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  187262. memcpy(&aBuf[nBuf-4], "ize", 3);
  187263. *pnBuf = nBuf - 4 + 3;
  187264. }
  187265. }
  187266. break;
  187267. case 'g':
  187268. if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
  187269. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  187270. memcpy(&aBuf[nBuf-4], "log", 3);
  187271. *pnBuf = nBuf - 4 + 3;
  187272. }
  187273. }
  187274. break;
  187275. case 'l':
  187276. if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
  187277. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  187278. memcpy(&aBuf[nBuf-3], "ble", 3);
  187279. *pnBuf = nBuf - 3 + 3;
  187280. }
  187281. }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
  187282. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  187283. memcpy(&aBuf[nBuf-4], "al", 2);
  187284. *pnBuf = nBuf - 4 + 2;
  187285. }
  187286. }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
  187287. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187288. memcpy(&aBuf[nBuf-5], "ent", 3);
  187289. *pnBuf = nBuf - 5 + 3;
  187290. }
  187291. }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
  187292. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  187293. memcpy(&aBuf[nBuf-3], "e", 1);
  187294. *pnBuf = nBuf - 3 + 1;
  187295. }
  187296. }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
  187297. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187298. memcpy(&aBuf[nBuf-5], "ous", 3);
  187299. *pnBuf = nBuf - 5 + 3;
  187300. }
  187301. }
  187302. break;
  187303. case 'o':
  187304. if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
  187305. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  187306. memcpy(&aBuf[nBuf-7], "ize", 3);
  187307. *pnBuf = nBuf - 7 + 3;
  187308. }
  187309. }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
  187310. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187311. memcpy(&aBuf[nBuf-5], "ate", 3);
  187312. *pnBuf = nBuf - 5 + 3;
  187313. }
  187314. }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
  187315. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  187316. memcpy(&aBuf[nBuf-4], "ate", 3);
  187317. *pnBuf = nBuf - 4 + 3;
  187318. }
  187319. }
  187320. break;
  187321. case 's':
  187322. if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
  187323. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187324. memcpy(&aBuf[nBuf-5], "al", 2);
  187325. *pnBuf = nBuf - 5 + 2;
  187326. }
  187327. }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
  187328. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  187329. memcpy(&aBuf[nBuf-7], "ive", 3);
  187330. *pnBuf = nBuf - 7 + 3;
  187331. }
  187332. }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
  187333. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  187334. memcpy(&aBuf[nBuf-7], "ful", 3);
  187335. *pnBuf = nBuf - 7 + 3;
  187336. }
  187337. }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
  187338. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  187339. memcpy(&aBuf[nBuf-7], "ous", 3);
  187340. *pnBuf = nBuf - 7 + 3;
  187341. }
  187342. }
  187343. break;
  187344. case 't':
  187345. if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
  187346. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187347. memcpy(&aBuf[nBuf-5], "al", 2);
  187348. *pnBuf = nBuf - 5 + 2;
  187349. }
  187350. }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
  187351. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187352. memcpy(&aBuf[nBuf-5], "ive", 3);
  187353. *pnBuf = nBuf - 5 + 3;
  187354. }
  187355. }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
  187356. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  187357. memcpy(&aBuf[nBuf-6], "ble", 3);
  187358. *pnBuf = nBuf - 6 + 3;
  187359. }
  187360. }
  187361. break;
  187362. }
  187363. return ret;
  187364. }
  187365. static int fts5PorterStep3(char *aBuf, int *pnBuf){
  187366. int ret = 0;
  187367. int nBuf = *pnBuf;
  187368. switch( aBuf[nBuf-2] ){
  187369. case 'a':
  187370. if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
  187371. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  187372. memcpy(&aBuf[nBuf-4], "ic", 2);
  187373. *pnBuf = nBuf - 4 + 2;
  187374. }
  187375. }
  187376. break;
  187377. case 's':
  187378. if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
  187379. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  187380. *pnBuf = nBuf - 4;
  187381. }
  187382. }
  187383. break;
  187384. case 't':
  187385. if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
  187386. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187387. memcpy(&aBuf[nBuf-5], "ic", 2);
  187388. *pnBuf = nBuf - 5 + 2;
  187389. }
  187390. }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
  187391. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187392. memcpy(&aBuf[nBuf-5], "ic", 2);
  187393. *pnBuf = nBuf - 5 + 2;
  187394. }
  187395. }
  187396. break;
  187397. case 'u':
  187398. if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
  187399. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  187400. *pnBuf = nBuf - 3;
  187401. }
  187402. }
  187403. break;
  187404. case 'v':
  187405. if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
  187406. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187407. *pnBuf = nBuf - 5;
  187408. }
  187409. }
  187410. break;
  187411. case 'z':
  187412. if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
  187413. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  187414. memcpy(&aBuf[nBuf-5], "al", 2);
  187415. *pnBuf = nBuf - 5 + 2;
  187416. }
  187417. }
  187418. break;
  187419. }
  187420. return ret;
  187421. }
  187422. static int fts5PorterStep1B(char *aBuf, int *pnBuf){
  187423. int ret = 0;
  187424. int nBuf = *pnBuf;
  187425. switch( aBuf[nBuf-2] ){
  187426. case 'e':
  187427. if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
  187428. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  187429. memcpy(&aBuf[nBuf-3], "ee", 2);
  187430. *pnBuf = nBuf - 3 + 2;
  187431. }
  187432. }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
  187433. if( fts5Porter_Vowel(aBuf, nBuf-2) ){
  187434. *pnBuf = nBuf - 2;
  187435. ret = 1;
  187436. }
  187437. }
  187438. break;
  187439. case 'n':
  187440. if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
  187441. if( fts5Porter_Vowel(aBuf, nBuf-3) ){
  187442. *pnBuf = nBuf - 3;
  187443. ret = 1;
  187444. }
  187445. }
  187446. break;
  187447. }
  187448. return ret;
  187449. }
  187450. /*
  187451. ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
  187452. ***************************************************************************
  187453. **************************************************************************/
  187454. static void fts5PorterStep1A(char *aBuf, int *pnBuf){
  187455. int nBuf = *pnBuf;
  187456. if( aBuf[nBuf-1]=='s' ){
  187457. if( aBuf[nBuf-2]=='e' ){
  187458. if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
  187459. || (nBuf>3 && aBuf[nBuf-3]=='i' )
  187460. ){
  187461. *pnBuf = nBuf-2;
  187462. }else{
  187463. *pnBuf = nBuf-1;
  187464. }
  187465. }
  187466. else if( aBuf[nBuf-2]!='s' ){
  187467. *pnBuf = nBuf-1;
  187468. }
  187469. }
  187470. }
  187471. static int fts5PorterCb(
  187472. void *pCtx,
  187473. int tflags,
  187474. const char *pToken,
  187475. int nToken,
  187476. int iStart,
  187477. int iEnd
  187478. ){
  187479. PorterContext *p = (PorterContext*)pCtx;
  187480. char *aBuf;
  187481. int nBuf;
  187482. if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
  187483. aBuf = p->aBuf;
  187484. nBuf = nToken;
  187485. memcpy(aBuf, pToken, nBuf);
  187486. /* Step 1. */
  187487. fts5PorterStep1A(aBuf, &nBuf);
  187488. if( fts5PorterStep1B(aBuf, &nBuf) ){
  187489. if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
  187490. char c = aBuf[nBuf-1];
  187491. if( fts5PorterIsVowel(c, 0)==0
  187492. && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
  187493. ){
  187494. nBuf--;
  187495. }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
  187496. aBuf[nBuf++] = 'e';
  187497. }
  187498. }
  187499. }
  187500. /* Step 1C. */
  187501. if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
  187502. aBuf[nBuf-1] = 'i';
  187503. }
  187504. /* Steps 2 through 4. */
  187505. fts5PorterStep2(aBuf, &nBuf);
  187506. fts5PorterStep3(aBuf, &nBuf);
  187507. fts5PorterStep4(aBuf, &nBuf);
  187508. /* Step 5a. */
  187509. assert( nBuf>0 );
  187510. if( aBuf[nBuf-1]=='e' ){
  187511. if( fts5Porter_MGt1(aBuf, nBuf-1)
  187512. || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
  187513. ){
  187514. nBuf--;
  187515. }
  187516. }
  187517. /* Step 5b. */
  187518. if( nBuf>1 && aBuf[nBuf-1]=='l'
  187519. && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
  187520. ){
  187521. nBuf--;
  187522. }
  187523. return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
  187524. pass_through:
  187525. return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
  187526. }
  187527. /*
  187528. ** Tokenize using the porter tokenizer.
  187529. */
  187530. static int fts5PorterTokenize(
  187531. Fts5Tokenizer *pTokenizer,
  187532. void *pCtx,
  187533. int flags,
  187534. const char *pText, int nText,
  187535. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  187536. ){
  187537. PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
  187538. PorterContext sCtx;
  187539. sCtx.xToken = xToken;
  187540. sCtx.pCtx = pCtx;
  187541. sCtx.aBuf = p->aBuf;
  187542. return p->tokenizer.xTokenize(
  187543. p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
  187544. );
  187545. }
  187546. /*
  187547. ** Register all built-in tokenizers with FTS5.
  187548. */
  187549. static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
  187550. struct BuiltinTokenizer {
  187551. const char *zName;
  187552. fts5_tokenizer x;
  187553. } aBuiltin[] = {
  187554. { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
  187555. { "ascii", {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
  187556. { "porter", {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
  187557. };
  187558. int rc = SQLITE_OK; /* Return code */
  187559. int i; /* To iterate through builtin functions */
  187560. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  187561. rc = pApi->xCreateTokenizer(pApi,
  187562. aBuiltin[i].zName,
  187563. (void*)pApi,
  187564. &aBuiltin[i].x,
  187565. 0
  187566. );
  187567. }
  187568. return rc;
  187569. }
  187570. /*
  187571. ** 2012 May 25
  187572. **
  187573. ** The author disclaims copyright to this source code. In place of
  187574. ** a legal notice, here is a blessing:
  187575. **
  187576. ** May you do good and not evil.
  187577. ** May you find forgiveness for yourself and forgive others.
  187578. ** May you share freely, never taking more than you give.
  187579. **
  187580. ******************************************************************************
  187581. */
  187582. /*
  187583. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  187584. */
  187585. /* #include <assert.h> */
  187586. /*
  187587. ** Return true if the argument corresponds to a unicode codepoint
  187588. ** classified as either a letter or a number. Otherwise false.
  187589. **
  187590. ** The results are undefined if the value passed to this function
  187591. ** is less than zero.
  187592. */
  187593. static int sqlite3Fts5UnicodeIsalnum(int c){
  187594. /* Each unsigned integer in the following array corresponds to a contiguous
  187595. ** range of unicode codepoints that are not either letters or numbers (i.e.
  187596. ** codepoints for which this function should return 0).
  187597. **
  187598. ** The most significant 22 bits in each 32-bit value contain the first
  187599. ** codepoint in the range. The least significant 10 bits are used to store
  187600. ** the size of the range (always at least 1). In other words, the value
  187601. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  187602. ** C. It is not possible to represent a range larger than 1023 codepoints
  187603. ** using this format.
  187604. */
  187605. static const unsigned int aEntry[] = {
  187606. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  187607. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  187608. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  187609. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  187610. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  187611. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  187612. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  187613. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  187614. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  187615. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  187616. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  187617. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  187618. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  187619. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  187620. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  187621. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  187622. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  187623. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  187624. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  187625. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  187626. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  187627. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  187628. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  187629. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  187630. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  187631. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  187632. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  187633. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  187634. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  187635. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  187636. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  187637. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  187638. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  187639. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  187640. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  187641. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  187642. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  187643. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  187644. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  187645. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  187646. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  187647. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  187648. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  187649. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  187650. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  187651. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  187652. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  187653. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  187654. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  187655. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  187656. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  187657. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  187658. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  187659. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  187660. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  187661. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  187662. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  187663. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  187664. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  187665. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  187666. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  187667. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  187668. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  187669. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  187670. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  187671. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  187672. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  187673. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  187674. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  187675. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  187676. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  187677. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  187678. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  187679. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  187680. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  187681. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  187682. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  187683. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  187684. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  187685. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  187686. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  187687. 0x380400F0,
  187688. };
  187689. static const unsigned int aAscii[4] = {
  187690. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  187691. };
  187692. if( (unsigned int)c<128 ){
  187693. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  187694. }else if( (unsigned int)c<(1<<22) ){
  187695. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  187696. int iRes = 0;
  187697. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  187698. int iLo = 0;
  187699. while( iHi>=iLo ){
  187700. int iTest = (iHi + iLo) / 2;
  187701. if( key >= aEntry[iTest] ){
  187702. iRes = iTest;
  187703. iLo = iTest+1;
  187704. }else{
  187705. iHi = iTest-1;
  187706. }
  187707. }
  187708. assert( aEntry[0]<key );
  187709. assert( key>=aEntry[iRes] );
  187710. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  187711. }
  187712. return 1;
  187713. }
  187714. /*
  187715. ** If the argument is a codepoint corresponding to a lowercase letter
  187716. ** in the ASCII range with a diacritic added, return the codepoint
  187717. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  187718. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  187719. ** E"). The resuls of passing a codepoint that corresponds to an
  187720. ** uppercase letter are undefined.
  187721. */
  187722. static int fts5_remove_diacritic(int c){
  187723. unsigned short aDia[] = {
  187724. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  187725. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  187726. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  187727. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  187728. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  187729. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  187730. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  187731. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  187732. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  187733. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  187734. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  187735. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  187736. 62924, 63050, 63082, 63274, 63390,
  187737. };
  187738. char aChar[] = {
  187739. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  187740. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  187741. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  187742. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  187743. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  187744. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  187745. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  187746. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  187747. 'e', 'i', 'o', 'u', 'y',
  187748. };
  187749. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  187750. int iRes = 0;
  187751. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  187752. int iLo = 0;
  187753. while( iHi>=iLo ){
  187754. int iTest = (iHi + iLo) / 2;
  187755. if( key >= aDia[iTest] ){
  187756. iRes = iTest;
  187757. iLo = iTest+1;
  187758. }else{
  187759. iHi = iTest-1;
  187760. }
  187761. }
  187762. assert( key>=aDia[iRes] );
  187763. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  187764. }
  187765. /*
  187766. ** Return true if the argument interpreted as a unicode codepoint
  187767. ** is a diacritical modifier character.
  187768. */
  187769. static int sqlite3Fts5UnicodeIsdiacritic(int c){
  187770. unsigned int mask0 = 0x08029FDF;
  187771. unsigned int mask1 = 0x000361F8;
  187772. if( c<768 || c>817 ) return 0;
  187773. return (c < 768+32) ?
  187774. (mask0 & (1 << (c-768))) :
  187775. (mask1 & (1 << (c-768-32)));
  187776. }
  187777. /*
  187778. ** Interpret the argument as a unicode codepoint. If the codepoint
  187779. ** is an upper case character that has a lower case equivalent,
  187780. ** return the codepoint corresponding to the lower case version.
  187781. ** Otherwise, return a copy of the argument.
  187782. **
  187783. ** The results are undefined if the value passed to this function
  187784. ** is less than zero.
  187785. */
  187786. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
  187787. /* Each entry in the following array defines a rule for folding a range
  187788. ** of codepoints to lower case. The rule applies to a range of nRange
  187789. ** codepoints starting at codepoint iCode.
  187790. **
  187791. ** If the least significant bit in flags is clear, then the rule applies
  187792. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  187793. ** need to be folded). Or, if it is set, then the rule only applies to
  187794. ** every second codepoint in the range, starting with codepoint C.
  187795. **
  187796. ** The 7 most significant bits in flags are an index into the aiOff[]
  187797. ** array. If a specific codepoint C does require folding, then its lower
  187798. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  187799. **
  187800. ** The contents of this array are generated by parsing the CaseFolding.txt
  187801. ** file distributed as part of the "Unicode Character Database". See
  187802. ** http://www.unicode.org for details.
  187803. */
  187804. static const struct TableEntry {
  187805. unsigned short iCode;
  187806. unsigned char flags;
  187807. unsigned char nRange;
  187808. } aEntry[] = {
  187809. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  187810. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  187811. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  187812. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  187813. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  187814. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  187815. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  187816. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  187817. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  187818. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  187819. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  187820. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  187821. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  187822. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  187823. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  187824. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  187825. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  187826. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  187827. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  187828. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  187829. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  187830. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  187831. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  187832. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  187833. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  187834. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  187835. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  187836. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  187837. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  187838. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  187839. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  187840. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  187841. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  187842. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  187843. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  187844. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  187845. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  187846. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  187847. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  187848. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  187849. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  187850. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  187851. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  187852. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  187853. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  187854. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  187855. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  187856. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  187857. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  187858. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  187859. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  187860. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  187861. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  187862. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  187863. {65313, 14, 26},
  187864. };
  187865. static const unsigned short aiOff[] = {
  187866. 1, 2, 8, 15, 16, 26, 28, 32,
  187867. 37, 38, 40, 48, 63, 64, 69, 71,
  187868. 79, 80, 116, 202, 203, 205, 206, 207,
  187869. 209, 210, 211, 213, 214, 217, 218, 219,
  187870. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  187871. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  187872. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  187873. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  187874. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  187875. 65514, 65521, 65527, 65528, 65529,
  187876. };
  187877. int ret = c;
  187878. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  187879. if( c<128 ){
  187880. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  187881. }else if( c<65536 ){
  187882. const struct TableEntry *p;
  187883. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  187884. int iLo = 0;
  187885. int iRes = -1;
  187886. assert( c>aEntry[0].iCode );
  187887. while( iHi>=iLo ){
  187888. int iTest = (iHi + iLo) / 2;
  187889. int cmp = (c - aEntry[iTest].iCode);
  187890. if( cmp>=0 ){
  187891. iRes = iTest;
  187892. iLo = iTest+1;
  187893. }else{
  187894. iHi = iTest-1;
  187895. }
  187896. }
  187897. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  187898. p = &aEntry[iRes];
  187899. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  187900. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  187901. assert( ret>0 );
  187902. }
  187903. if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
  187904. }
  187905. else if( c>=66560 && c<66600 ){
  187906. ret = c + 40;
  187907. }
  187908. return ret;
  187909. }
  187910. /*
  187911. ** 2015 May 30
  187912. **
  187913. ** The author disclaims copyright to this source code. In place of
  187914. ** a legal notice, here is a blessing:
  187915. **
  187916. ** May you do good and not evil.
  187917. ** May you find forgiveness for yourself and forgive others.
  187918. ** May you share freely, never taking more than you give.
  187919. **
  187920. ******************************************************************************
  187921. **
  187922. ** Routines for varint serialization and deserialization.
  187923. */
  187924. /* #include "fts5Int.h" */
  187925. /*
  187926. ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
  187927. ** Except, this version does handle the single byte case that the core
  187928. ** version depends on being handled before its function is called.
  187929. */
  187930. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
  187931. u32 a,b;
  187932. /* The 1-byte case. Overwhelmingly the most common. */
  187933. a = *p;
  187934. /* a: p0 (unmasked) */
  187935. if (!(a&0x80))
  187936. {
  187937. /* Values between 0 and 127 */
  187938. *v = a;
  187939. return 1;
  187940. }
  187941. /* The 2-byte case */
  187942. p++;
  187943. b = *p;
  187944. /* b: p1 (unmasked) */
  187945. if (!(b&0x80))
  187946. {
  187947. /* Values between 128 and 16383 */
  187948. a &= 0x7f;
  187949. a = a<<7;
  187950. *v = a | b;
  187951. return 2;
  187952. }
  187953. /* The 3-byte case */
  187954. p++;
  187955. a = a<<14;
  187956. a |= *p;
  187957. /* a: p0<<14 | p2 (unmasked) */
  187958. if (!(a&0x80))
  187959. {
  187960. /* Values between 16384 and 2097151 */
  187961. a &= (0x7f<<14)|(0x7f);
  187962. b &= 0x7f;
  187963. b = b<<7;
  187964. *v = a | b;
  187965. return 3;
  187966. }
  187967. /* A 32-bit varint is used to store size information in btrees.
  187968. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  187969. ** A 3-byte varint is sufficient, for example, to record the size
  187970. ** of a 1048569-byte BLOB or string.
  187971. **
  187972. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  187973. ** rare larger cases can be handled by the slower 64-bit varint
  187974. ** routine.
  187975. */
  187976. {
  187977. u64 v64;
  187978. u8 n;
  187979. p -= 2;
  187980. n = sqlite3Fts5GetVarint(p, &v64);
  187981. *v = (u32)v64;
  187982. assert( n>3 && n<=9 );
  187983. return n;
  187984. }
  187985. }
  187986. /*
  187987. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  187988. ** are defined here rather than simply putting the constant expressions
  187989. ** inline in order to work around bugs in the RVT compiler.
  187990. **
  187991. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  187992. **
  187993. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  187994. */
  187995. #define SLOT_2_0 0x001fc07f
  187996. #define SLOT_4_2_0 0xf01fc07f
  187997. /*
  187998. ** Read a 64-bit variable-length integer from memory starting at p[0].
  187999. ** Return the number of bytes read. The value is stored in *v.
  188000. */
  188001. static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
  188002. u32 a,b,s;
  188003. a = *p;
  188004. /* a: p0 (unmasked) */
  188005. if (!(a&0x80))
  188006. {
  188007. *v = a;
  188008. return 1;
  188009. }
  188010. p++;
  188011. b = *p;
  188012. /* b: p1 (unmasked) */
  188013. if (!(b&0x80))
  188014. {
  188015. a &= 0x7f;
  188016. a = a<<7;
  188017. a |= b;
  188018. *v = a;
  188019. return 2;
  188020. }
  188021. /* Verify that constants are precomputed correctly */
  188022. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  188023. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  188024. p++;
  188025. a = a<<14;
  188026. a |= *p;
  188027. /* a: p0<<14 | p2 (unmasked) */
  188028. if (!(a&0x80))
  188029. {
  188030. a &= SLOT_2_0;
  188031. b &= 0x7f;
  188032. b = b<<7;
  188033. a |= b;
  188034. *v = a;
  188035. return 3;
  188036. }
  188037. /* CSE1 from below */
  188038. a &= SLOT_2_0;
  188039. p++;
  188040. b = b<<14;
  188041. b |= *p;
  188042. /* b: p1<<14 | p3 (unmasked) */
  188043. if (!(b&0x80))
  188044. {
  188045. b &= SLOT_2_0;
  188046. /* moved CSE1 up */
  188047. /* a &= (0x7f<<14)|(0x7f); */
  188048. a = a<<7;
  188049. a |= b;
  188050. *v = a;
  188051. return 4;
  188052. }
  188053. /* a: p0<<14 | p2 (masked) */
  188054. /* b: p1<<14 | p3 (unmasked) */
  188055. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  188056. /* moved CSE1 up */
  188057. /* a &= (0x7f<<14)|(0x7f); */
  188058. b &= SLOT_2_0;
  188059. s = a;
  188060. /* s: p0<<14 | p2 (masked) */
  188061. p++;
  188062. a = a<<14;
  188063. a |= *p;
  188064. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  188065. if (!(a&0x80))
  188066. {
  188067. /* we can skip these cause they were (effectively) done above in calc'ing s */
  188068. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  188069. /* b &= (0x7f<<14)|(0x7f); */
  188070. b = b<<7;
  188071. a |= b;
  188072. s = s>>18;
  188073. *v = ((u64)s)<<32 | a;
  188074. return 5;
  188075. }
  188076. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  188077. s = s<<7;
  188078. s |= b;
  188079. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  188080. p++;
  188081. b = b<<14;
  188082. b |= *p;
  188083. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  188084. if (!(b&0x80))
  188085. {
  188086. /* we can skip this cause it was (effectively) done above in calc'ing s */
  188087. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  188088. a &= SLOT_2_0;
  188089. a = a<<7;
  188090. a |= b;
  188091. s = s>>18;
  188092. *v = ((u64)s)<<32 | a;
  188093. return 6;
  188094. }
  188095. p++;
  188096. a = a<<14;
  188097. a |= *p;
  188098. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  188099. if (!(a&0x80))
  188100. {
  188101. a &= SLOT_4_2_0;
  188102. b &= SLOT_2_0;
  188103. b = b<<7;
  188104. a |= b;
  188105. s = s>>11;
  188106. *v = ((u64)s)<<32 | a;
  188107. return 7;
  188108. }
  188109. /* CSE2 from below */
  188110. a &= SLOT_2_0;
  188111. p++;
  188112. b = b<<14;
  188113. b |= *p;
  188114. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  188115. if (!(b&0x80))
  188116. {
  188117. b &= SLOT_4_2_0;
  188118. /* moved CSE2 up */
  188119. /* a &= (0x7f<<14)|(0x7f); */
  188120. a = a<<7;
  188121. a |= b;
  188122. s = s>>4;
  188123. *v = ((u64)s)<<32 | a;
  188124. return 8;
  188125. }
  188126. p++;
  188127. a = a<<15;
  188128. a |= *p;
  188129. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  188130. /* moved CSE2 up */
  188131. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  188132. b &= SLOT_2_0;
  188133. b = b<<8;
  188134. a |= b;
  188135. s = s<<4;
  188136. b = p[-4];
  188137. b &= 0x7f;
  188138. b = b>>3;
  188139. s |= b;
  188140. *v = ((u64)s)<<32 | a;
  188141. return 9;
  188142. }
  188143. /*
  188144. ** The variable-length integer encoding is as follows:
  188145. **
  188146. ** KEY:
  188147. ** A = 0xxxxxxx 7 bits of data and one flag bit
  188148. ** B = 1xxxxxxx 7 bits of data and one flag bit
  188149. ** C = xxxxxxxx 8 bits of data
  188150. **
  188151. ** 7 bits - A
  188152. ** 14 bits - BA
  188153. ** 21 bits - BBA
  188154. ** 28 bits - BBBA
  188155. ** 35 bits - BBBBA
  188156. ** 42 bits - BBBBBA
  188157. ** 49 bits - BBBBBBA
  188158. ** 56 bits - BBBBBBBA
  188159. ** 64 bits - BBBBBBBBC
  188160. */
  188161. #ifdef SQLITE_NOINLINE
  188162. # define FTS5_NOINLINE SQLITE_NOINLINE
  188163. #else
  188164. # define FTS5_NOINLINE
  188165. #endif
  188166. /*
  188167. ** Write a 64-bit variable-length integer to memory starting at p[0].
  188168. ** The length of data write will be between 1 and 9 bytes. The number
  188169. ** of bytes written is returned.
  188170. **
  188171. ** A variable-length integer consists of the lower 7 bits of each byte
  188172. ** for all bytes that have the 8th bit set and one byte with the 8th
  188173. ** bit clear. Except, if we get to the 9th byte, it stores the full
  188174. ** 8 bits and is the last byte.
  188175. */
  188176. static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
  188177. int i, j, n;
  188178. u8 buf[10];
  188179. if( v & (((u64)0xff000000)<<32) ){
  188180. p[8] = (u8)v;
  188181. v >>= 8;
  188182. for(i=7; i>=0; i--){
  188183. p[i] = (u8)((v & 0x7f) | 0x80);
  188184. v >>= 7;
  188185. }
  188186. return 9;
  188187. }
  188188. n = 0;
  188189. do{
  188190. buf[n++] = (u8)((v & 0x7f) | 0x80);
  188191. v >>= 7;
  188192. }while( v!=0 );
  188193. buf[0] &= 0x7f;
  188194. assert( n<=9 );
  188195. for(i=0, j=n-1; j>=0; j--, i++){
  188196. p[i] = buf[j];
  188197. }
  188198. return n;
  188199. }
  188200. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
  188201. if( v<=0x7f ){
  188202. p[0] = v&0x7f;
  188203. return 1;
  188204. }
  188205. if( v<=0x3fff ){
  188206. p[0] = ((v>>7)&0x7f)|0x80;
  188207. p[1] = v&0x7f;
  188208. return 2;
  188209. }
  188210. return fts5PutVarint64(p,v);
  188211. }
  188212. static int sqlite3Fts5GetVarintLen(u32 iVal){
  188213. #if 0
  188214. if( iVal<(1 << 7 ) ) return 1;
  188215. #endif
  188216. assert( iVal>=(1 << 7) );
  188217. if( iVal<(1 << 14) ) return 2;
  188218. if( iVal<(1 << 21) ) return 3;
  188219. if( iVal<(1 << 28) ) return 4;
  188220. return 5;
  188221. }
  188222. /*
  188223. ** 2015 May 08
  188224. **
  188225. ** The author disclaims copyright to this source code. In place of
  188226. ** a legal notice, here is a blessing:
  188227. **
  188228. ** May you do good and not evil.
  188229. ** May you find forgiveness for yourself and forgive others.
  188230. ** May you share freely, never taking more than you give.
  188231. **
  188232. ******************************************************************************
  188233. **
  188234. ** This is an SQLite virtual table module implementing direct access to an
  188235. ** existing FTS5 index. The module may create several different types of
  188236. ** tables:
  188237. **
  188238. ** col:
  188239. ** CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
  188240. **
  188241. ** One row for each term/column combination. The value of $doc is set to
  188242. ** the number of fts5 rows that contain at least one instance of term
  188243. ** $term within column $col. Field $cnt is set to the total number of
  188244. ** instances of term $term in column $col (in any row of the fts5 table).
  188245. **
  188246. ** row:
  188247. ** CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
  188248. **
  188249. ** One row for each term in the database. The value of $doc is set to
  188250. ** the number of fts5 rows that contain at least one instance of term
  188251. ** $term. Field $cnt is set to the total number of instances of term
  188252. ** $term in the database.
  188253. */
  188254. /* #include "fts5Int.h" */
  188255. typedef struct Fts5VocabTable Fts5VocabTable;
  188256. typedef struct Fts5VocabCursor Fts5VocabCursor;
  188257. struct Fts5VocabTable {
  188258. sqlite3_vtab base;
  188259. char *zFts5Tbl; /* Name of fts5 table */
  188260. char *zFts5Db; /* Db containing fts5 table */
  188261. sqlite3 *db; /* Database handle */
  188262. Fts5Global *pGlobal; /* FTS5 global object for this database */
  188263. int eType; /* FTS5_VOCAB_COL or ROW */
  188264. };
  188265. struct Fts5VocabCursor {
  188266. sqlite3_vtab_cursor base;
  188267. sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */
  188268. Fts5Index *pIndex; /* Associated FTS5 index */
  188269. int bEof; /* True if this cursor is at EOF */
  188270. Fts5IndexIter *pIter; /* Term/rowid iterator object */
  188271. int nLeTerm; /* Size of zLeTerm in bytes */
  188272. char *zLeTerm; /* (term <= $zLeTerm) paramater, or NULL */
  188273. /* These are used by 'col' tables only */
  188274. Fts5Config *pConfig; /* Fts5 table configuration */
  188275. int iCol;
  188276. i64 *aCnt;
  188277. i64 *aDoc;
  188278. /* Output values used by 'row' and 'col' tables */
  188279. i64 rowid; /* This table's current rowid value */
  188280. Fts5Buffer term; /* Current value of 'term' column */
  188281. };
  188282. #define FTS5_VOCAB_COL 0
  188283. #define FTS5_VOCAB_ROW 1
  188284. #define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt"
  188285. #define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt"
  188286. /*
  188287. ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
  188288. */
  188289. #define FTS5_VOCAB_TERM_EQ 0x01
  188290. #define FTS5_VOCAB_TERM_GE 0x02
  188291. #define FTS5_VOCAB_TERM_LE 0x04
  188292. /*
  188293. ** Translate a string containing an fts5vocab table type to an
  188294. ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
  188295. ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
  188296. ** and return SQLITE_ERROR.
  188297. */
  188298. static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
  188299. int rc = SQLITE_OK;
  188300. char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
  188301. if( rc==SQLITE_OK ){
  188302. sqlite3Fts5Dequote(zCopy);
  188303. if( sqlite3_stricmp(zCopy, "col")==0 ){
  188304. *peType = FTS5_VOCAB_COL;
  188305. }else
  188306. if( sqlite3_stricmp(zCopy, "row")==0 ){
  188307. *peType = FTS5_VOCAB_ROW;
  188308. }else
  188309. {
  188310. *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
  188311. rc = SQLITE_ERROR;
  188312. }
  188313. sqlite3_free(zCopy);
  188314. }
  188315. return rc;
  188316. }
  188317. /*
  188318. ** The xDisconnect() virtual table method.
  188319. */
  188320. static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
  188321. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  188322. sqlite3_free(pTab);
  188323. return SQLITE_OK;
  188324. }
  188325. /*
  188326. ** The xDestroy() virtual table method.
  188327. */
  188328. static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
  188329. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  188330. sqlite3_free(pTab);
  188331. return SQLITE_OK;
  188332. }
  188333. /*
  188334. ** This function is the implementation of both the xConnect and xCreate
  188335. ** methods of the FTS3 virtual table.
  188336. **
  188337. ** The argv[] array contains the following:
  188338. **
  188339. ** argv[0] -> module name ("fts5vocab")
  188340. ** argv[1] -> database name
  188341. ** argv[2] -> table name
  188342. **
  188343. ** then:
  188344. **
  188345. ** argv[3] -> name of fts5 table
  188346. ** argv[4] -> type of fts5vocab table
  188347. **
  188348. ** or, for tables in the TEMP schema only.
  188349. **
  188350. ** argv[3] -> name of fts5 tables database
  188351. ** argv[4] -> name of fts5 table
  188352. ** argv[5] -> type of fts5vocab table
  188353. */
  188354. static int fts5VocabInitVtab(
  188355. sqlite3 *db, /* The SQLite database connection */
  188356. void *pAux, /* Pointer to Fts5Global object */
  188357. int argc, /* Number of elements in argv array */
  188358. const char * const *argv, /* xCreate/xConnect argument array */
  188359. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  188360. char **pzErr /* Write any error message here */
  188361. ){
  188362. const char *azSchema[] = {
  188363. "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")",
  188364. "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")"
  188365. };
  188366. Fts5VocabTable *pRet = 0;
  188367. int rc = SQLITE_OK; /* Return code */
  188368. int bDb;
  188369. bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
  188370. if( argc!=5 && bDb==0 ){
  188371. *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
  188372. rc = SQLITE_ERROR;
  188373. }else{
  188374. int nByte; /* Bytes of space to allocate */
  188375. const char *zDb = bDb ? argv[3] : argv[1];
  188376. const char *zTab = bDb ? argv[4] : argv[3];
  188377. const char *zType = bDb ? argv[5] : argv[4];
  188378. int nDb = (int)strlen(zDb)+1;
  188379. int nTab = (int)strlen(zTab)+1;
  188380. int eType = 0;
  188381. rc = fts5VocabTableType(zType, pzErr, &eType);
  188382. if( rc==SQLITE_OK ){
  188383. assert( eType>=0 && eType<ArraySize(azSchema) );
  188384. rc = sqlite3_declare_vtab(db, azSchema[eType]);
  188385. }
  188386. nByte = sizeof(Fts5VocabTable) + nDb + nTab;
  188387. pRet = sqlite3Fts5MallocZero(&rc, nByte);
  188388. if( pRet ){
  188389. pRet->pGlobal = (Fts5Global*)pAux;
  188390. pRet->eType = eType;
  188391. pRet->db = db;
  188392. pRet->zFts5Tbl = (char*)&pRet[1];
  188393. pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
  188394. memcpy(pRet->zFts5Tbl, zTab, nTab);
  188395. memcpy(pRet->zFts5Db, zDb, nDb);
  188396. sqlite3Fts5Dequote(pRet->zFts5Tbl);
  188397. sqlite3Fts5Dequote(pRet->zFts5Db);
  188398. }
  188399. }
  188400. *ppVTab = (sqlite3_vtab*)pRet;
  188401. return rc;
  188402. }
  188403. /*
  188404. ** The xConnect() and xCreate() methods for the virtual table. All the
  188405. ** work is done in function fts5VocabInitVtab().
  188406. */
  188407. static int fts5VocabConnectMethod(
  188408. sqlite3 *db, /* Database connection */
  188409. void *pAux, /* Pointer to tokenizer hash table */
  188410. int argc, /* Number of elements in argv array */
  188411. const char * const *argv, /* xCreate/xConnect argument array */
  188412. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  188413. char **pzErr /* OUT: sqlite3_malloc'd error message */
  188414. ){
  188415. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  188416. }
  188417. static int fts5VocabCreateMethod(
  188418. sqlite3 *db, /* Database connection */
  188419. void *pAux, /* Pointer to tokenizer hash table */
  188420. int argc, /* Number of elements in argv array */
  188421. const char * const *argv, /* xCreate/xConnect argument array */
  188422. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  188423. char **pzErr /* OUT: sqlite3_malloc'd error message */
  188424. ){
  188425. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  188426. }
  188427. /*
  188428. ** Implementation of the xBestIndex method.
  188429. */
  188430. static int fts5VocabBestIndexMethod(
  188431. sqlite3_vtab *pUnused,
  188432. sqlite3_index_info *pInfo
  188433. ){
  188434. int i;
  188435. int iTermEq = -1;
  188436. int iTermGe = -1;
  188437. int iTermLe = -1;
  188438. int idxNum = 0;
  188439. int nArg = 0;
  188440. UNUSED_PARAM(pUnused);
  188441. for(i=0; i<pInfo->nConstraint; i++){
  188442. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  188443. if( p->usable==0 ) continue;
  188444. if( p->iColumn==0 ){ /* term column */
  188445. if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
  188446. if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
  188447. if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
  188448. if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
  188449. if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
  188450. }
  188451. }
  188452. if( iTermEq>=0 ){
  188453. idxNum |= FTS5_VOCAB_TERM_EQ;
  188454. pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
  188455. pInfo->estimatedCost = 100;
  188456. }else{
  188457. pInfo->estimatedCost = 1000000;
  188458. if( iTermGe>=0 ){
  188459. idxNum |= FTS5_VOCAB_TERM_GE;
  188460. pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
  188461. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  188462. }
  188463. if( iTermLe>=0 ){
  188464. idxNum |= FTS5_VOCAB_TERM_LE;
  188465. pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
  188466. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  188467. }
  188468. }
  188469. /* This virtual table always delivers results in ascending order of
  188470. ** the "term" column (column 0). So if the user has requested this
  188471. ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
  188472. ** sqlite3_index_info.orderByConsumed flag to tell the core the results
  188473. ** are already in sorted order. */
  188474. if( pInfo->nOrderBy==1
  188475. && pInfo->aOrderBy[0].iColumn==0
  188476. && pInfo->aOrderBy[0].desc==0
  188477. ){
  188478. pInfo->orderByConsumed = 1;
  188479. }
  188480. pInfo->idxNum = idxNum;
  188481. return SQLITE_OK;
  188482. }
  188483. /*
  188484. ** Implementation of xOpen method.
  188485. */
  188486. static int fts5VocabOpenMethod(
  188487. sqlite3_vtab *pVTab,
  188488. sqlite3_vtab_cursor **ppCsr
  188489. ){
  188490. Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
  188491. Fts5Index *pIndex = 0;
  188492. Fts5Config *pConfig = 0;
  188493. Fts5VocabCursor *pCsr = 0;
  188494. int rc = SQLITE_OK;
  188495. sqlite3_stmt *pStmt = 0;
  188496. char *zSql = 0;
  188497. zSql = sqlite3Fts5Mprintf(&rc,
  188498. "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
  188499. pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
  188500. );
  188501. if( zSql ){
  188502. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
  188503. }
  188504. sqlite3_free(zSql);
  188505. assert( rc==SQLITE_OK || pStmt==0 );
  188506. if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
  188507. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  188508. i64 iId = sqlite3_column_int64(pStmt, 0);
  188509. pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
  188510. }
  188511. if( rc==SQLITE_OK && pIndex==0 ){
  188512. rc = sqlite3_finalize(pStmt);
  188513. pStmt = 0;
  188514. if( rc==SQLITE_OK ){
  188515. pVTab->zErrMsg = sqlite3_mprintf(
  188516. "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
  188517. );
  188518. rc = SQLITE_ERROR;
  188519. }
  188520. }
  188521. if( rc==SQLITE_OK ){
  188522. int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
  188523. pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
  188524. }
  188525. if( pCsr ){
  188526. pCsr->pIndex = pIndex;
  188527. pCsr->pStmt = pStmt;
  188528. pCsr->pConfig = pConfig;
  188529. pCsr->aCnt = (i64*)&pCsr[1];
  188530. pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
  188531. }else{
  188532. sqlite3_finalize(pStmt);
  188533. }
  188534. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  188535. return rc;
  188536. }
  188537. static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
  188538. pCsr->rowid = 0;
  188539. sqlite3Fts5IterClose(pCsr->pIter);
  188540. pCsr->pIter = 0;
  188541. sqlite3_free(pCsr->zLeTerm);
  188542. pCsr->nLeTerm = -1;
  188543. pCsr->zLeTerm = 0;
  188544. }
  188545. /*
  188546. ** Close the cursor. For additional information see the documentation
  188547. ** on the xClose method of the virtual table interface.
  188548. */
  188549. static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
  188550. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  188551. fts5VocabResetCursor(pCsr);
  188552. sqlite3Fts5BufferFree(&pCsr->term);
  188553. sqlite3_finalize(pCsr->pStmt);
  188554. sqlite3_free(pCsr);
  188555. return SQLITE_OK;
  188556. }
  188557. /*
  188558. ** Advance the cursor to the next row in the table.
  188559. */
  188560. static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
  188561. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  188562. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  188563. int rc = SQLITE_OK;
  188564. int nCol = pCsr->pConfig->nCol;
  188565. pCsr->rowid++;
  188566. if( pTab->eType==FTS5_VOCAB_COL ){
  188567. for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
  188568. if( pCsr->aDoc[pCsr->iCol] ) break;
  188569. }
  188570. }
  188571. if( pTab->eType==FTS5_VOCAB_ROW || pCsr->iCol>=nCol ){
  188572. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  188573. pCsr->bEof = 1;
  188574. }else{
  188575. const char *zTerm;
  188576. int nTerm;
  188577. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  188578. if( pCsr->nLeTerm>=0 ){
  188579. int nCmp = MIN(nTerm, pCsr->nLeTerm);
  188580. int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
  188581. if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
  188582. pCsr->bEof = 1;
  188583. return SQLITE_OK;
  188584. }
  188585. }
  188586. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  188587. memset(pCsr->aCnt, 0, nCol * sizeof(i64));
  188588. memset(pCsr->aDoc, 0, nCol * sizeof(i64));
  188589. pCsr->iCol = 0;
  188590. assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
  188591. while( rc==SQLITE_OK ){
  188592. const u8 *pPos; int nPos; /* Position list */
  188593. i64 iPos = 0; /* 64-bit position read from poslist */
  188594. int iOff = 0; /* Current offset within position list */
  188595. pPos = pCsr->pIter->pData;
  188596. nPos = pCsr->pIter->nData;
  188597. switch( pCsr->pConfig->eDetail ){
  188598. case FTS5_DETAIL_FULL:
  188599. pPos = pCsr->pIter->pData;
  188600. nPos = pCsr->pIter->nData;
  188601. if( pTab->eType==FTS5_VOCAB_ROW ){
  188602. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  188603. pCsr->aCnt[0]++;
  188604. }
  188605. pCsr->aDoc[0]++;
  188606. }else{
  188607. int iCol = -1;
  188608. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  188609. int ii = FTS5_POS2COLUMN(iPos);
  188610. pCsr->aCnt[ii]++;
  188611. if( iCol!=ii ){
  188612. if( ii>=nCol ){
  188613. rc = FTS5_CORRUPT;
  188614. break;
  188615. }
  188616. pCsr->aDoc[ii]++;
  188617. iCol = ii;
  188618. }
  188619. }
  188620. }
  188621. break;
  188622. case FTS5_DETAIL_COLUMNS:
  188623. if( pTab->eType==FTS5_VOCAB_ROW ){
  188624. pCsr->aDoc[0]++;
  188625. }else{
  188626. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
  188627. assert_nc( iPos>=0 && iPos<nCol );
  188628. if( iPos>=nCol ){
  188629. rc = FTS5_CORRUPT;
  188630. break;
  188631. }
  188632. pCsr->aDoc[iPos]++;
  188633. }
  188634. }
  188635. break;
  188636. default:
  188637. assert( pCsr->pConfig->eDetail==FTS5_DETAIL_NONE );
  188638. pCsr->aDoc[0]++;
  188639. break;
  188640. }
  188641. if( rc==SQLITE_OK ){
  188642. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  188643. }
  188644. if( rc==SQLITE_OK ){
  188645. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  188646. if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
  188647. break;
  188648. }
  188649. if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
  188650. }
  188651. }
  188652. }
  188653. }
  188654. if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
  188655. while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
  188656. assert( pCsr->iCol<pCsr->pConfig->nCol );
  188657. }
  188658. return rc;
  188659. }
  188660. /*
  188661. ** This is the xFilter implementation for the virtual table.
  188662. */
  188663. static int fts5VocabFilterMethod(
  188664. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  188665. int idxNum, /* Strategy index */
  188666. const char *zUnused, /* Unused */
  188667. int nUnused, /* Number of elements in apVal */
  188668. sqlite3_value **apVal /* Arguments for the indexing scheme */
  188669. ){
  188670. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  188671. int rc = SQLITE_OK;
  188672. int iVal = 0;
  188673. int f = FTS5INDEX_QUERY_SCAN;
  188674. const char *zTerm = 0;
  188675. int nTerm = 0;
  188676. sqlite3_value *pEq = 0;
  188677. sqlite3_value *pGe = 0;
  188678. sqlite3_value *pLe = 0;
  188679. UNUSED_PARAM2(zUnused, nUnused);
  188680. fts5VocabResetCursor(pCsr);
  188681. if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
  188682. if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
  188683. if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
  188684. if( pEq ){
  188685. zTerm = (const char *)sqlite3_value_text(pEq);
  188686. nTerm = sqlite3_value_bytes(pEq);
  188687. f = 0;
  188688. }else{
  188689. if( pGe ){
  188690. zTerm = (const char *)sqlite3_value_text(pGe);
  188691. nTerm = sqlite3_value_bytes(pGe);
  188692. }
  188693. if( pLe ){
  188694. const char *zCopy = (const char *)sqlite3_value_text(pLe);
  188695. pCsr->nLeTerm = sqlite3_value_bytes(pLe);
  188696. pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
  188697. if( pCsr->zLeTerm==0 ){
  188698. rc = SQLITE_NOMEM;
  188699. }else{
  188700. memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
  188701. }
  188702. }
  188703. }
  188704. if( rc==SQLITE_OK ){
  188705. rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
  188706. }
  188707. if( rc==SQLITE_OK ){
  188708. rc = fts5VocabNextMethod(pCursor);
  188709. }
  188710. return rc;
  188711. }
  188712. /*
  188713. ** This is the xEof method of the virtual table. SQLite calls this
  188714. ** routine to find out if it has reached the end of a result set.
  188715. */
  188716. static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
  188717. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  188718. return pCsr->bEof;
  188719. }
  188720. static int fts5VocabColumnMethod(
  188721. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  188722. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  188723. int iCol /* Index of column to read value from */
  188724. ){
  188725. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  188726. int eDetail = pCsr->pConfig->eDetail;
  188727. int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
  188728. i64 iVal = 0;
  188729. if( iCol==0 ){
  188730. sqlite3_result_text(
  188731. pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
  188732. );
  188733. }else if( eType==FTS5_VOCAB_COL ){
  188734. assert( iCol==1 || iCol==2 || iCol==3 );
  188735. if( iCol==1 ){
  188736. if( eDetail!=FTS5_DETAIL_NONE ){
  188737. const char *z = pCsr->pConfig->azCol[pCsr->iCol];
  188738. sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
  188739. }
  188740. }else if( iCol==2 ){
  188741. iVal = pCsr->aDoc[pCsr->iCol];
  188742. }else{
  188743. iVal = pCsr->aCnt[pCsr->iCol];
  188744. }
  188745. }else{
  188746. assert( iCol==1 || iCol==2 );
  188747. if( iCol==1 ){
  188748. iVal = pCsr->aDoc[0];
  188749. }else{
  188750. iVal = pCsr->aCnt[0];
  188751. }
  188752. }
  188753. if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
  188754. return SQLITE_OK;
  188755. }
  188756. /*
  188757. ** This is the xRowid method. The SQLite core calls this routine to
  188758. ** retrieve the rowid for the current row of the result set. The
  188759. ** rowid should be written to *pRowid.
  188760. */
  188761. static int fts5VocabRowidMethod(
  188762. sqlite3_vtab_cursor *pCursor,
  188763. sqlite_int64 *pRowid
  188764. ){
  188765. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  188766. *pRowid = pCsr->rowid;
  188767. return SQLITE_OK;
  188768. }
  188769. static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
  188770. static const sqlite3_module fts5Vocab = {
  188771. /* iVersion */ 2,
  188772. /* xCreate */ fts5VocabCreateMethod,
  188773. /* xConnect */ fts5VocabConnectMethod,
  188774. /* xBestIndex */ fts5VocabBestIndexMethod,
  188775. /* xDisconnect */ fts5VocabDisconnectMethod,
  188776. /* xDestroy */ fts5VocabDestroyMethod,
  188777. /* xOpen */ fts5VocabOpenMethod,
  188778. /* xClose */ fts5VocabCloseMethod,
  188779. /* xFilter */ fts5VocabFilterMethod,
  188780. /* xNext */ fts5VocabNextMethod,
  188781. /* xEof */ fts5VocabEofMethod,
  188782. /* xColumn */ fts5VocabColumnMethod,
  188783. /* xRowid */ fts5VocabRowidMethod,
  188784. /* xUpdate */ 0,
  188785. /* xBegin */ 0,
  188786. /* xSync */ 0,
  188787. /* xCommit */ 0,
  188788. /* xRollback */ 0,
  188789. /* xFindFunction */ 0,
  188790. /* xRename */ 0,
  188791. /* xSavepoint */ 0,
  188792. /* xRelease */ 0,
  188793. /* xRollbackTo */ 0,
  188794. };
  188795. void *p = (void*)pGlobal;
  188796. return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
  188797. }
  188798. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
  188799. /************** End of fts5.c ************************************************/